# 13 — downloads-and-processing: file workbook

[Implementation chapter](../chapters/13-downloads-and-processing.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/services/download/DownloadForegroundService.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/download/DownloadForegroundService.kt) · implementation · 173 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: class DownloadForegroundService : Service() {
42: override fun onBind(intent: Intent?): IBinder? = null
44: override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
97: override fun onTimeout(startId: Int, fgsType: Int) {
102: override fun onDestroy() {
107: private suspend fun mirrorProgress(binding: ProfileDownloadBindings.Binding, downloads: DownloadService) {
122: private fun notification(binding: ProfileDownloadBindings.Binding?, status: DownloadQueueStatus, active: List<DownloadProgress>): Notification {
155: private fun ownerIntent(context: Context, binding: ProfileDownloadBindings.Binding?): Intent =
168: fun start(context: Context, binding: ProfileDownloadBindings.Binding) {
```

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

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.download

import android.app.Notification
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.ServiceInfo
import android.graphics.drawable.Icon
import android.os.Build
import android.os.IBinder
import android.net.Uri
import eu.friedcutlet.yokan.services.scheduling.ProfileWorkNamespace
import eu.friedcutlet.yokan.services.logging.AppLogger
import eu.friedcutlet.yokan.services.notifications.NotificationChannel
import eu.friedcutlet.yokan.services.notifications.ensureChannel
import kotlinx.coroutines.Job
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.conflate
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * Keeps the process in the foreground while downloads are pending and mirrors their progress in an ongoing
 * notification on the Downloads channel. The downloads run in the app's services; this only reads and
 * cancels them, and stops itself once the queue drains. Without the notification permission it still runs;
 * only the notification stays hidden.
 */
class DownloadForegroundService : Service() {
    private val scope = MainScope()
    private var mirror: Job? = null
    private var foregroundBinding: ProfileDownloadBindings.Binding? = null

    /** The newest start; stopping with it never drops a start that is still on its way. */
    private var lastStartId = 0

    override fun onBind(intent: Intent?): IBinder? = null

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        lastStartId = startId
        val requested = androidDownloadBindings.resolve(
            intent?.getStringExtra(ProfileWorkNamespace.OwnerKey),
            intent?.getStringExtra(ProfileDownloadBindings.TokenKey),
        )
        if (intent?.action == ACTION_CANCEL_ALL) {
            // A service started only for this action stays alive until the owner has handled it.
            if (mirror == null && requested != null) {
                scope.launch {
                    try { requested.run { it.cancelAll() } }
                    finally { if (mirror == null) stopSelf(startId) }
                }
            } else {
                requested?.cancelAll()
                // A live mirror stops its foreground service once that owner's queue drains.
                if (mirror == null) stopSelf(startId)
            }
            return START_NOT_STICKY
        }
        // One service has one foreground indicator. Never retarget a live mirror to another owner.
        val current = foregroundBinding?.takeIf { it.isActive }
        val binding = current ?: requested
        val downloads = binding?.downloads
        // Always first: a service started for the foreground must call startForeground, even to stop right away.
        val started = runCatching {
            val notification = notification(binding, downloads?.queueStatus?.value ?: DownloadQueueStatus(), downloads?.activeDownloadProgress?.value.orEmpty())
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                startForeground(NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC)
            } else {
                startForeground(NOTIFICATION_ID, notification)
            }
        }.onFailure { AppLogger.warn("Download foreground service could not start: ${it.message.orEmpty()}") }
        if ((started.isFailure && mirror == null) || downloads == null || !needsKeepAlive(downloads.queueStatus.value)) {
            stopSelf(startId)
        } else if (mirror == null || current == null) {
            mirror?.cancel()
            foregroundBinding = binding
            mirror = scope.launch {
                try { binding.run { mirrorProgress(binding, it) } }
                finally {
                    if (foregroundBinding === binding) {
                        foregroundBinding = null
                        mirror = null
                        stopSelf(lastStartId)
                    }
                }
            }
        }
        return START_NOT_STICKY
    }

    /** Android 15+ caps dataSync services at 6 hours a day; downloads carry on for as long as the process lives. */
    override fun onTimeout(startId: Int, fgsType: Int) {
        stopForeground(STOP_FOREGROUND_REMOVE)
        stopSelf()
    }

    override fun onDestroy() {
        scope.cancel()
        super.onDestroy()
    }

    private suspend fun mirrorProgress(binding: ProfileDownloadBindings.Binding, downloads: DownloadService) {
        combine(downloads.queueStatus, downloads.activeDownloadProgress) { status, active -> status to active }
            .conflate()
            .collect { (status, active) ->
                withContext(Dispatchers.Main.immediate) {
                    if (foregroundBinding === binding) {
                        if (!needsKeepAlive(status)) stopSelf(lastStartId)
                        else runCatching { getSystemService(NotificationManager::class.java).notify(NOTIFICATION_ID, notification(binding, status, active)) }
                    }
                }
                // Android drops notification updates posted faster than a few per second.
                delay(UPDATE_INTERVAL_MS)
            }
    }

    private fun notification(binding: ProfileDownloadBindings.Binding?, status: DownloadQueueStatus, active: List<DownloadProgress>): Notification {
        val channelId = checkNotNull(getSystemService(NotificationManager::class.java).ensureChannel(NotificationChannel.Downloads))
        val hidden = runCatching { binding?.hideContent?.invoke() == true }.getOrDefault(false)
        val current = (active.firstOrNull { !it.isPaused && !it.isCompleted } ?: active.firstOrNull())
            ?.let { if (hidden) it.copy(mangaName = "", chapterName = "") else it }
        val pages = current?.takeIf { it.total > 0 }?.let { "${it.succeeded}/${it.total}" }
        val cancelAll = PendingIntent.getService(
            this,
            0,
            ownerIntent(this, binding).setAction(ACTION_CANCEL_ALL),
            PendingIntent.FLAG_IMMUTABLE,
        )
        val open = packageManager.getLaunchIntentForPackage(packageName)
            ?.let { PendingIntent.getActivity(this, 0, it, PendingIntent.FLAG_IMMUTABLE) }
        return Notification.Builder(this, channelId)
            .setSmallIcon(applicationInfo.icon)
            .setOngoing(true)
            .setOnlyAlertOnce(true)
            .setContentTitle(current?.mangaName?.ifBlank { null } ?: "Downloading")
            .setContentText(listOfNotNull(current?.chapterName?.ifBlank { null }, pages).joinToString(" • "))
            .setSubText(if (status.pending > 1) "${status.pending} chapters left" else null)
            .setProgress(current?.total ?: 0, current?.succeeded ?: 0, pages == null)
            .setContentIntent(open)
            .apply { if (binding != null) addAction(Notification.Action.Builder(Icon.createWithResource(this@DownloadForegroundService, applicationInfo.icon), "Cancel all", cancelAll).build()) }
            .apply { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_IMMEDIATE) }
            .build()
    }

    internal companion object {
        private const val ACTION_CANCEL_ALL = "eu.friedcutlet.yokan.action.CANCEL_ALL_DOWNLOADS"
        private const val UPDATE_INTERVAL_MS = 1_000L
        private val NOTIFICATION_ID = "yokan_downloads:foreground".hashCode()

        private fun ownerIntent(context: Context, binding: ProfileDownloadBindings.Binding?): Intent =
            Intent(context, DownloadForegroundService::class.java).apply {
                if (binding != null) {
                    data = Uri.parse(binding.actionIdentity)
                    putExtra(ProfileWorkNamespace.OwnerKey, binding.id.value)
                    putExtra(ProfileDownloadBindings.TokenKey, binding.token)
                }
            }

        /**
         * Android 12+ refuses this from the background: downloads then continue while the process lives and
         * resume through the resume job or on the next launch.
         */
        fun start(context: Context, binding: ProfileDownloadBindings.Binding) {
            runCatching { context.startForegroundService(ownerIntent(context, binding)) }
                .onFailure { AppLogger.info("Downloads continue without a foreground service: ${it.message.orEmpty()}") }
        }
    }
}
```
[complete-source-end]: #

## `composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/download/DownloadKeepAlive.android.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/download/DownloadKeepAlive.android.kt) · implementation · 85 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
23: interface DownloadTaskHost {
24: suspend fun runBackgroundDownloads(owner: String?, task: suspend DownloadService.() -> Unit): ProfileWorkResult<Unit>
30: actual fun keepDownloadsAlive(downloads: DownloadService, database: YokanDatabase, scope: CoroutineScope, profileId: ProfileId) {
56: private fun resumeRequest(wifiOnly: Boolean, profileId: ProfileId) = OneTimeWorkRequestBuilder<DownloadResumeWorker>()
69: class DownloadResumeWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {
70: override suspend fun doWork(): Result {
```

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

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.download

import android.content.Context
import androidx.work.Constraints
import androidx.work.CoroutineWorker
import androidx.work.ExistingWorkPolicy
import androidx.work.NetworkType
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.WorkerParameters
import androidx.work.workDataOf
import eu.friedcutlet.yokan.AndroidAppContext
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.services.scheduling.ProfileWorkNamespace
import eu.friedcutlet.yokan.services.scheduling.ProfileWorkResult
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.services.logging.AppLogger
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch

/** Implemented by the `Application`: a resume worker in a cold process gets a profile-bound download service through it. */
interface DownloadTaskHost {
    suspend fun runBackgroundDownloads(owner: String?, task: suspend DownloadService.() -> Unit): ProfileWorkResult<Unit>
}

private const val DOWNLOAD_RESUME_WORK = "yokan.download_resume"
internal val androidDownloadBindings = ProfileDownloadBindings()

actual fun keepDownloadsAlive(downloads: DownloadService, database: YokanDatabase, scope: CoroutineScope, profileId: ProfileId) {
    val context = AndroidAppContext.appContext ?: return
    val binding = androidDownloadBindings.install(profileId, downloads, scope) { database.settings().features.privacy.hideNotificationContent }
    val workName = ProfileWorkNamespace(profileId).uniqueName(DOWNLOAD_RESUME_WORK)
    scope.launch {
        var resumeScheduled = false
        downloads.queueStatus.collect { status ->
            // Asked again on every queue change: a start refused in the background succeeds once the app is back.
            if (needsKeepAlive(status)) DownloadForegroundService.start(context, binding)
            val pending = status.pending > 0
            if (pending == resumeScheduled) return@collect
            resumeScheduled = pending
            runCatching {
                val work = WorkManager.getInstance(context)
                if (pending) {
                    // ponytail: KEEP keeps the network constraint the work was enqueued with; a Wi-Fi-only toggle
                    // while downloads are pending applies from the next queue.
                    work.enqueueUniqueWork(workName, ExistingWorkPolicy.KEEP, resumeRequest(database.settings().downloadOnlyOnWifi, profileId))
                } else {
                    work.cancelUniqueWork(workName)
                }
            }.onFailure { AppLogger.warn("Could not schedule the download resume job: ${it.message.orEmpty()}") }
        }
    }
}

private fun resumeRequest(wifiOnly: Boolean, profileId: ProfileId) = OneTimeWorkRequestBuilder<DownloadResumeWorker>()
    .setInputData(workDataOf(ProfileWorkNamespace.OwnerKey to profileId.value))
    .setConstraints(
        Constraints.Builder()
            .setRequiredNetworkType(if (wifiOnly) NetworkType.UNMETERED else NetworkType.CONNECTED)
            .build(),
    )
    .build()

/**
 * Resumes downloads in a process the system killed: bootstrapping re-queues the interrupted ones. It runs until
 * the queue drains, which keeps the process alive; when the system stops it, WorkManager runs it again later.
 */
class DownloadResumeWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {
    override suspend fun doWork(): Result {
        // YokanApplication normally sets this; never let a worker fail on a missing context.
        if (AndroidAppContext.appContext == null) AndroidAppContext.appContext = applicationContext
        val owner = if (inputData.keyValueMap.containsKey(ProfileWorkNamespace.OwnerKey)) {
            inputData.getString(ProfileWorkNamespace.OwnerKey) ?: ""
        } else null // Explicit adoption of pre-profile Default resume jobs only.
        val outcome = (applicationContext as DownloadTaskHost).runBackgroundDownloads(owner) {
            initialize()
            queueStatus.first { it.pending == 0 }
        }
        return when (outcome) {
            is ProfileWorkResult.Completed, ProfileWorkResult.Skipped -> Result.success()
            ProfileWorkResult.Retry -> if (runAttemptCount < 3) Result.retry() else Result.failure()
        }
    }
}
```
[complete-source-end]: #

## `composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/download/EinkPageTranscoder.android.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/download/EinkPageTranscoder.android.kt) · implementation · 46 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 fun transcodeEinkPage(bytes: ByteArray, maxShortSide: Int): ByteArray? {
```

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

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.download

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.ColorMatrix
import android.graphics.ColorMatrixColorFilter
import android.graphics.Paint
import android.graphics.Rect
import eu.friedcutlet.yokan.database.einkScaledSize
import java.io.ByteArrayOutputStream

internal actual fun transcodeEinkPage(bytes: ByteArray, maxShortSide: Int): ByteArray? {
    if (bytes.isGif()) return null
    val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
    BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
    if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return null
    val (width, height) = einkScaledSize(bounds.outWidth, bounds.outHeight, maxShortSide)
    // Power-of-two subsampling keeps peak memory low; the final scale happens while drawing.
    var sample = 1
    while (bounds.outWidth / (sample * 2) >= width && bounds.outHeight / (sample * 2) >= height) sample *= 2
    val decoded = runCatching {
        BitmapFactory.decodeByteArray(bytes, 0, bytes.size, BitmapFactory.Options().apply { inSampleSize = sample })
    }.getOrNull() ?: return null
    val target = runCatching { Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888) }.getOrNull()
    if (target == null) {
        decoded.recycle()
        return null
    }
    return try {
        val paint = Paint(Paint.FILTER_BITMAP_FLAG).apply {
            colorFilter = ColorMatrixColorFilter(ColorMatrix().apply { setSaturation(0f) })
        }
        Canvas(target).apply {
            drawColor(android.graphics.Color.WHITE)
            drawBitmap(decoded, null, Rect(0, 0, width, height), paint)
        }
        ByteArrayOutputStream().use { out ->
            if (!target.compress(Bitmap.CompressFormat.JPEG, EinkJpegQuality, out)) return null
            out.toByteArray()
        }.takeIf { it.isNotEmpty() && it.size < bytes.size }
    } finally {
        decoded.recycle()
        target.recycle()
    }
}
```
[complete-source-end]: #

## `composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/download/TallImageSplitter.android.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/download/TallImageSplitter.android.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
14: internal actual suspend fun splitTallImage(bytes: ByteArray, maximumHeight: Int, writeTile: suspend (index: Int, bytes: ByteArray) -> Unit): Boolean {
```

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

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.download

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Rect
import android.media.ExifInterface
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive

internal actual suspend fun splitTallImage(bytes: ByteArray, maximumHeight: Int, writeTile: suspend (index: Int, bytes: ByteArray) -> Unit): Boolean {
    if (bytes.size > MaxSplitImageBytes || bytes.mayBeAnimatedImage()) return false
    val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
    BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
    val regions = tallImageRegions(bounds.outWidth, bounds.outHeight, maximumHeight)
    if (regions.isEmpty()) return false
    // Splitting must not discard an orientation that the reader would apply to the original.
    if (bytes.size >= 2 && bytes[0] == 0xff.toByte() && bytes[1] == 0xd8.toByte()) {
        val orientation = ByteArrayInputStream(bytes).use { ExifInterface(it).getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL) }
        if (orientation != ExifInterface.ORIENTATION_NORMAL && orientation != ExifInterface.ORIENTATION_UNDEFINED) return false
    }
    val image = BitmapFactory.decodeByteArray(bytes, 0, bytes.size) ?: return false
    try {
        regions.forEachIndexed { index, region ->
            currentCoroutineContext().ensureActive()
            val tile = Bitmap.createBitmap(image.width, region.height, Bitmap.Config.ARGB_8888)
            val encoded = try {
                Canvas(tile).apply {
                    drawColor(Color.WHITE)
                    drawBitmap(image, Rect(0, region.top, image.width, region.top + region.height), Rect(0, 0, image.width, region.height), null)
                }
                ByteArrayOutputStream().use { out ->
                    check(tile.compress(Bitmap.CompressFormat.JPEG, 90, out))
                    out.toByteArray()
                }
            } finally { tile.recycle() }
            writeTile(index, encoded)
        }
        return true
    } finally { image.recycle() }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/download/Aria2RpcClient.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/download/Aria2RpcClient.kt) · implementation · 141 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 Aria2RpcException(val code: Int? = null) : IllegalStateException(
15: internal enum class Aria2Status { Active, Waiting, Paused, Error, Complete, Removed }
17: internal data class Aria2Progress(
27: internal class Aria2RpcClient(private val http: HttpService, private val endpoint: String, private val secret: String) {
32: suspend fun version(): String {
37: suspend fun addUri(gid: String, url: String, directory: String, fileName: String, headers: Map<String, String>, paused: Boolean = false) {
61: suspend fun statuses(gids: List<String>): Map<String, Result<Aria2Progress>> {
69: fun length(name: String): Long = (value[name] as? JsonPrimitive)?.longOrNull?.takeIf { it >= 0 } ?: throw Aria2RpcException()
74: suspend fun pause(gid: String) = control("aria2.forcePause", gid, expected = gid)
75: suspend fun resume(gid: String) = control("aria2.unpause", gid, expected = gid)
76: suspend fun cancel(gid: String) = control("aria2.forceRemove", gid, expected = gid)
77: suspend fun forgetResult(gid: String) = control("aria2.removeDownloadResult", gid, expected = "OK")
79: private suspend fun control(method: String, gid: String, expected: String) {
84: private suspend fun call(method: String, params: List<JsonElement>): JsonElement {
89: private suspend fun batch(calls: List<Pair<String, List<JsonElement>>>): List<Result<JsonElement>> {
101: private fun request(method: String, params: List<JsonElement>) = buildJsonObject {
108: private fun result(response: JsonObject, id: String): Result<JsonElement> {
116: private suspend fun exchange(body: JsonElement): JsonElement = withTimeoutOrNull(15_000) {
134: fun validGid(gid: String) = gid.matches(Regex("[0-9a-fA-F]{16}")) && gid.any { it != '0' }
135: fun validEndpoint(raw: String): Boolean = try {
```

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

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.download

import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.util.PlatformLock
import io.ktor.http.Url
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.withTimeoutOrNull
import kotlinx.serialization.json.*

internal class Aria2RpcException(val code: Int? = null) : IllegalStateException(
    if (code == null) "Invalid external downloader response" else "External downloader RPC error ($code)",
)

internal enum class Aria2Status { Active, Waiting, Paused, Error, Complete, Removed }

internal data class Aria2Progress(
    val gid: String,
    val status: Aria2Status,
    val totalBytes: Long,
    val completedBytes: Long,
    val bytesPerSecond: Long,
    val errorCode: Int?,
)

/** Bounded JSON-RPC transport; callers persist owned GIDs before creating remote work. */
internal class Aria2RpcClient(private val http: HttpService, private val endpoint: String, private val secret: String) {
    private val idsLock = PlatformLock()
    private var nextId = 0L
    init { require(validEndpoint(endpoint)) { "Invalid external downloader URL" } }

    suspend fun version(): String {
        val response = call("aria2.getVersion", emptyList()) as? JsonObject ?: throw Aria2RpcException()
        return (response["version"] as? JsonPrimitive)?.contentOrNull?.takeIf { it.isNotBlank() && it.length <= 128 } ?: throw Aria2RpcException()
    }

    suspend fun addUri(gid: String, url: String, directory: String, fileName: String, headers: Map<String, String>, paused: Boolean = false) {
        require(validGid(gid))
        require(fileName.isNotBlank() && fileName !in setOf(".", "..") && fileName.none { it == '/' || it == '\\' || it.code < 32 })
        require(directory.isNotBlank() && directory.none { it.code < 32 })
        require(directory.replace('\\', '/').split('/').none { it == ".." })
        val parsed = Url(url)
        require(parsed.protocol.name in setOf("http", "https") && parsed.host.isNotBlank() && parsed.user.isNullOrEmpty() && parsed.password.isNullOrEmpty())
        val options = buildJsonObject {
            put("gid", gid)
            put("dir", directory)
            put("out", fileName)
            put("allow-overwrite", "false")
            put("auto-file-renaming", "false")
            put("continue", "true")
            put("pause", paused.toString())
            if (headers.isNotEmpty()) put("header", JsonArray(headers.map { (name, value) ->
                require(name.matches(Regex("[!#$%&'*+.^_`|~0-9a-zA-Z-]+")) && value.none { it == '\r' || it == '\n' || it == '\u0000' })
                JsonPrimitive("$name: $value")
            }))
        }
        val actual = (call("aria2.addUri", listOf(JsonArray(listOf(JsonPrimitive(url))), options)) as? JsonPrimitive)?.contentOrNull
        if (!gid.equals(actual, true)) throw Aria2RpcException()
    }

    suspend fun statuses(gids: List<String>): Map<String, Result<Aria2Progress>> {
        require(gids.size in 1..64 && gids.distinct().size == gids.size && gids.all(::validGid))
        val keys = JsonArray(listOf("gid", "status", "totalLength", "completedLength", "downloadSpeed", "errorCode").map(::JsonPrimitive))
        val results = batch(gids.map { "aria2.tellStatus" to listOf(JsonPrimitive(it), keys) })
        return gids.mapIndexed { index, gid -> gid to results[index].mapCatching { result ->
            val value = result as? JsonObject ?: throw Aria2RpcException()
            if ((value["gid"] as? JsonPrimitive)?.contentOrNull?.equals(gid, true) != true) throw Aria2RpcException()
            val status = Aria2Status.entries.firstOrNull { it.name.equals((value["status"] as? JsonPrimitive)?.contentOrNull, true) } ?: throw Aria2RpcException()
            fun length(name: String): Long = (value[name] as? JsonPrimitive)?.longOrNull?.takeIf { it >= 0 } ?: throw Aria2RpcException()
            Aria2Progress(gid, status, length("totalLength"), length("completedLength"), length("downloadSpeed"), (value["errorCode"] as? JsonPrimitive)?.intOrNull)
        } }.toMap()
    }

    suspend fun pause(gid: String) = control("aria2.forcePause", gid, expected = gid)
    suspend fun resume(gid: String) = control("aria2.unpause", gid, expected = gid)
    suspend fun cancel(gid: String) = control("aria2.forceRemove", gid, expected = gid)
    suspend fun forgetResult(gid: String) = control("aria2.removeDownloadResult", gid, expected = "OK")

    private suspend fun control(method: String, gid: String, expected: String) {
        require(validGid(gid))
        if ((call(method, listOf(JsonPrimitive(gid))) as? JsonPrimitive)?.content?.equals(expected, true) != true) throw Aria2RpcException()
    }

    private suspend fun call(method: String, params: List<JsonElement>): JsonElement {
        val request = request(method, params)
        return result(exchange(request) as? JsonObject ?: throw Aria2RpcException(), request["id"].toString()).getOrThrow()
    }

    private suspend fun batch(calls: List<Pair<String, List<JsonElement>>>): List<Result<JsonElement>> {
        val requests = calls.map { (method, params) -> request(method, params) }
        val response = exchange(JsonArray(requests)) as? JsonArray ?: throw Aria2RpcException()
        if (response.size != requests.size) throw Aria2RpcException()
        val byId = response.map { it as? JsonObject ?: throw Aria2RpcException() }.associateBy { it["id"].toString() }
        if (byId.size != response.size) throw Aria2RpcException()
        return requests.map { request ->
            val id = request["id"].toString()
            byId[id]?.let { result(it, id) } ?: Result.failure(Aria2RpcException())
        }
    }

    private fun request(method: String, params: List<JsonElement>) = buildJsonObject {
        put("jsonrpc", "2.0")
        put("id", idsLock.withLock { "yokan-${++nextId}" })
        put("method", method)
        put("params", JsonArray((if (secret.isNotBlank()) listOf(JsonPrimitive("token:$secret")) else emptyList()) + params))
    }

    private fun result(response: JsonObject, id: String): Result<JsonElement> {
        if ((response["jsonrpc"] as? JsonPrimitive)?.contentOrNull != "2.0" || response["id"].toString() != id) return Result.failure(Aria2RpcException())
        response["error"]?.let { error ->
            return Result.failure(Aria2RpcException(((error as? JsonObject)?.get("code") as? JsonPrimitive)?.intOrNull))
        }
        return response["result"]?.let(Result.Companion::success) ?: Result.failure(Aria2RpcException())
    }

    private suspend fun exchange(body: JsonElement): JsonElement = withTimeoutOrNull(15_000) {
        val chunks = mutableListOf<ByteArray>()
        var size = 0
        val response = http.stream(HttpRequest(endpoint, method = "POST", headers = mapOf("Content-Type" to "application/json"), body = body.toString())) { chunk ->
            size += chunk.size
            if (size > 1024 * 1024) throw Aria2RpcException()
            chunks += chunk
        }
        if (response.statusCode !in 200..299) throw Aria2RpcException(response.statusCode)
        val bytes = ByteArray(size)
        var offset = 0
        chunks.forEach { chunk -> chunk.copyInto(bytes, offset); offset += chunk.size }
        try { Json.parseToJsonElement(bytes.decodeToString()) }
        catch (cancel: CancellationException) { throw cancel }
        catch (_: Exception) { throw Aria2RpcException() }
    } ?: throw Aria2RpcException()

    companion object {
        fun validGid(gid: String) = gid.matches(Regex("[0-9a-fA-F]{16}")) && gid.any { it != '0' }
        fun validEndpoint(raw: String): Boolean = try {
            val url = Url(raw)
            url.protocol.name in setOf("http", "https") && url.host.isNotBlank() && url.user.isNullOrEmpty() && url.password.isNullOrEmpty() &&
                url.fragment.isEmpty() && url.parameters.entries().isEmpty()
        } catch (_: Exception) { false }
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/download/DownloadAutomation.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/download/DownloadAutomation.kt) · implementation · 233 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: data class DownloadCleanupItem(val chapterId: Long, val title: String, val chapter: String)
16: class DownloadAutomation(
24: private data class ExecutionKey(val policy: DbDownloadPolicy, val location: String, val destination: String?, val folders: List<DbLocalFolder>)
38: fun recordDiscoveredChapters(chapterIds: Set<Long>) {
49: fun chapterOpened(chapterId: Long): Job {
59: fun chapterClosed(chapterId: Long): Job {
70: fun chaptersMarked(chapterIds: Set<Long>, read: Boolean, consumed: Boolean): Job {
96: fun downloadCompleted(chapterId: Long): Job = scope.launch { guarded {
104: suspend fun reconcile() {
127: private suspend fun drainPendingNew() = gate.withLock {
152: private fun automaticStillAllowed(id: Long): Boolean {
162: private fun enqueue(chapterId: Long) {
166: private fun protectedIds(): Set<Long> = activeLock.withLock { openChapters.keys.toSet() } +
169: fun previewReadCleanup(): List<DownloadCleanupItem> {
184: suspend fun cleanupReadDownloads(chapterIds: Set<Long>): Int = owned {
190: private fun explicitCleanupSnapshot(authorizedIds: Set<Long>? = null): YokanDatabaseSnapshot {
197: suspend fun cleanup(titleId: Long, reason: DownloadCleanupReason): Int = owned { cleanup(titleId, reason, null) }
199: private suspend fun cleanup(titleId: Long, reason: DownloadCleanupReason, authorizedIds: Set<Long>?): Int = gate.withLock {
200: fun candidates(): List<Long> = downloadCleanupCandidates(
208: fun stillEligible() = id in candidates()
226: private suspend fun guarded(block: suspend () -> Unit) {
232: private suspend fun <T> owned(action: suspend () -> T): T = scope.runJoined { action() }
```

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

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.download

import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.services.logging.AppLogger
import eu.friedcutlet.yokan.services.runJoined
import eu.friedcutlet.yokan.util.PlatformLock
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock

data class DownloadCleanupItem(val chapterId: Long, val title: String, val chapter: String)

/** Profile-owned policy execution. Queue manifests remain the sole owner of actual transfers. */
class DownloadAutomation(
    private val database: YokanDatabase,
    private val downloader: DownloadService,
    private val scope: CoroutineScope,
) {
    private val gate = Mutex()
    private val activeLock = PlatformLock()
    private val openChapters = mutableMapOf<Long, Int>()
    private data class ExecutionKey(val policy: DbDownloadPolicy, val location: String, val destination: String?, val folders: List<DbLocalFolder>)

    init {
        scope.launch {
            database.snapshots().map { snapshot -> snapshot.settings.let {
                ExecutionKey(it.features.downloads, it.downloadLocation, it.downloadLocalFolderName, it.namedLocalFolders.orEmpty())
            } }.distinctUntilChanged().collect {
                guarded { drainPendingNew() }
            }
        }
        scope.launch { guarded { reconcile() } }
    }

    /** Called within the updater's transaction, so a crash cannot lose newly discovered work. */
    fun recordDiscoveredChapters(chapterIds: Set<Long>) {
        if (chapterIds.isEmpty()) return
        database.batch {
            val settings = database.settings()
            val policy = settings.features.downloads
            if (policy.autoDownloadNew) database.updateSettings(settings.copy(features = settings.features.copy(downloads = policy.copy(
                pendingNewChapterIds = policy.pendingNewChapterIds + chapterIds,
            ))))
        }
    }

    fun chapterOpened(chapterId: Long): Job {
        activeLock.withLock { openChapters[chapterId] = (openChapters[chapterId] ?: 0) + 1 }
        return scope.launch { guarded { gate.withLock {
            downloadAheadCandidates(database.snapshot(), chapterId).forEach { id ->
                ensureActive()
                if (id in downloadAheadCandidates(database.snapshot(), chapterId)) enqueue(id)
            }
        } } }
    }

    fun chapterClosed(chapterId: Long): Job {
        activeLock.withLock {
            val count = (openChapters[chapterId] ?: 0) - 1
            if (count <= 0) openChapters.remove(chapterId) else openChapters[chapterId] = count
        }
        return scope.launch { guarded { database.chapter(chapterId)?.mangaId?.let {
            cleanup(it, DownloadCleanupReason.Consumption)
            cleanup(it, DownloadCleanupReason.ManualMark)
        } } }
    }

    fun chaptersMarked(chapterIds: Set<Long>, read: Boolean, consumed: Boolean): Job {
        database.batch {
            val settings = database.settings()
            val policy = settings.features.downloads
            val eligibleReceipts = if (read && ((consumed && (policy.cleanupAfterConsumption || settings.deleteDownloadAfterReading)) || (!consumed && policy.cleanupAfterManualMark))) {
                database.downloads().mapNotNullTo(mutableSetOf()) { it.chapterId }.intersect(chapterIds)
            } else emptySet()
            val updated = when {
                !read -> policy.consumedChapterIds - chapterIds
                consumed -> policy.consumedChapterIds + eligibleReceipts
                else -> policy.consumedChapterIds
            }
            val manual = when {
                !read -> policy.manuallyMarkedChapterIds - chapterIds
                !consumed -> policy.manuallyMarkedChapterIds + eligibleReceipts
                else -> policy.manuallyMarkedChapterIds
            }
            if (updated != policy.consumedChapterIds || manual != policy.manuallyMarkedChapterIds) database.updateSettings(settings.copy(features = settings.features.copy(downloads = policy.copy(consumedChapterIds = updated, manuallyMarkedChapterIds = manual))))
        }
        return scope.launch { guarded {
            if (read) chapterIds.mapNotNull { database.chapter(it)?.mangaId }.distinct().forEach {
                cleanup(it, if (consumed) DownloadCleanupReason.Consumption else DownloadCleanupReason.ManualMark)
            }
        } }
    }

    fun downloadCompleted(chapterId: Long): Job = scope.launch { guarded {
        database.chapter(chapterId)?.mangaId?.let {
            cleanup(it, DownloadCleanupReason.Consumption)
            cleanup(it, DownloadCleanupReason.ManualMark)
        }
    } }

    /** Restart recovery and an explicit reconciliation entry point; safe to repeat. */
    suspend fun reconcile() {
        drainPendingNew()
        database.batch {
            val settings = database.settings()
            val policy = settings.features.downloads
            if (policy.consumedChapterIds.isNotEmpty() || policy.manuallyMarkedChapterIds.isNotEmpty()) {
                val valid = database.downloads().mapNotNullTo(mutableSetOf()) { row ->
                    row.chapterId?.takeIf { id -> database.chapter(id)?.mangaId?.let(database::manga)?.isLocalArchive == false }
                }
                val consumed = policy.consumedChapterIds.intersect(valid)
                val manual = policy.manuallyMarkedChapterIds.intersect(valid)
                if (consumed != policy.consumedChapterIds || manual != policy.manuallyMarkedChapterIds) database.updateSettings(settings.copy(features = settings.features.copy(downloads = policy.copy(consumedChapterIds = consumed, manuallyMarkedChapterIds = manual))))
            }
        }
        val snapshot = database.snapshot()
        val policy = snapshot.settings.features.downloads
        val receipts = policy.consumedChapterIds + policy.manuallyMarkedChapterIds
        snapshot.chapters.filter { it.id in receipts }.mapNotNull { it.mangaId }.distinct().forEach {
            cleanup(it, DownloadCleanupReason.Consumption)
            cleanup(it, DownloadCleanupReason.ManualMark)
        }
    }

    private suspend fun drainPendingNew() = gate.withLock {
        val snapshot = database.snapshot()
        val pending = snapshot.settings.features.downloads.pendingNewChapterIds
        pending.chunked(32).forEach { chunk ->
            val eligible = automaticDownloadCandidates(database.snapshot(), chunk.toSet()).toSet()
            val acknowledged = mutableSetOf<Long>()
            try {
                chunk.forEach { id ->
                    currentCoroutineContext().ensureActive()
                    if (id in eligible && automaticStillAllowed(id)) enqueue(id)
                    acknowledged += id
                }
            } finally {
                // Queue admissions are durable before receipts are acknowledged. Interrupted chunks
                // can replay safely because persisted queue rows are excluded on the next run.
                database.batch {
                    val settings = database.settings()
                    val policy = settings.features.downloads
                    if (acknowledged.isNotEmpty()) database.updateSettings(settings.copy(features = settings.features.copy(downloads = policy.copy(pendingNewChapterIds = policy.pendingNewChapterIds - acknowledged))))
                }
            }
            yield()
        }
    }

    private fun automaticStillAllowed(id: Long): Boolean {
        val policy = database.settings().features.downloads
        if (!policy.autoDownloadNew) return false
        val chapter = database.chapter(id) ?: return false
        val title = chapter.mangaId?.let(database::manga) ?: return false
        val source = title.sourceId?.let(database::source) ?: return false
        return source.isActive && source.isAdded && downloadPolicyAllows(title, chapter, policy) &&
            database.downloads().none { it.chapterId == id }
    }

    private fun enqueue(chapterId: Long) {
        chapterDownloadRequest(database, chapterId)?.let { downloader.enqueue(it) }
    }

    private fun protectedIds(): Set<Long> = activeLock.withLock { openChapters.keys.toSet() } +
        downloader.activeDownloads().filterNot { it.isCompleted }.mapNotNull { it.taskId.removePrefix("chapter-").toLongOrNull() }

    fun previewReadCleanup(): List<DownloadCleanupItem> {
        val snapshot = explicitCleanupSnapshot()
        val chapters = snapshot.chapters.associateBy { it.id }
        val byTitle = snapshot.chapters.groupBy { it.mangaId }
        val downloadsByTitle = snapshot.downloads.groupBy { chapters[it.chapterId]?.mangaId }
        val protected = protectedIds()
        return snapshot.mangas.flatMap { title ->
            val titleSnapshot = snapshot.copy(mangas = listOf(title), chapters = byTitle[title.id].orEmpty(), downloads = downloadsByTitle[title.id].orEmpty())
            downloadCleanupCandidates(titleSnapshot, title.id, DownloadCleanupReason.ManualMark, protected).mapNotNull { id ->
                chapters[id]?.let { DownloadCleanupItem(id, title.name.orEmpty(), it.name.orEmpty()) }
            }
        }
    }

    /** A confirmation authorizes only previewed IDs; fresh protections can further reduce that set. */
    suspend fun cleanupReadDownloads(chapterIds: Set<Long>): Int = owned {
        chapterIds.mapNotNull { database.chapter(it)?.mangaId }.distinct().sumOf {
            cleanup(it, DownloadCleanupReason.ManualMark, chapterIds)
        }
    }

    private fun explicitCleanupSnapshot(authorizedIds: Set<Long>? = null): YokanDatabaseSnapshot {
        val snapshot = database.snapshot()
        val settings = snapshot.settings
        val ids = authorizedIds ?: snapshot.chapters.filter { it.isRead }.mapTo(mutableSetOf()) { it.id }
        return snapshot.copy(settings = settings.copy(features = settings.features.copy(downloads = settings.features.downloads.copy(cleanupAfterManualMark = true, manuallyMarkedChapterIds = ids))))
    }

    suspend fun cleanup(titleId: Long, reason: DownloadCleanupReason): Int = owned { cleanup(titleId, reason, null) }

    private suspend fun cleanup(titleId: Long, reason: DownloadCleanupReason, authorizedIds: Set<Long>?): Int = gate.withLock {
        fun candidates(): List<Long> = downloadCleanupCandidates(
            if (authorizedIds == null) database.snapshot() else explicitCleanupSnapshot(authorizedIds), titleId, reason, protectedIds(),
        ).filter { authorizedIds == null || it in authorizedIds }
        val ids = candidates()
        var deleted = 0
        ids.forEach { id ->
            currentCoroutineContext().ensureActive()
            val before = database.snapshot().downloads.firstOrNull { it.chapterId == id && it.isDownload == true } ?: return@forEach
            fun stillEligible() = id in candidates()
            if (!stillEligible()) return@forEach
            downloader.deleteCompletedArtifacts(downloadTaskId(id, before.id), ::stillEligible, onDeleted = { database.batch {
                val current = database.download(before.id)
                if (current != null && current == before) {
                    database.removeDownload(current.id)
                    database.chapter(id)?.let { database.upsertChapter(it.copy(archivePath = "", downloadSize = null)) }
                    val settings = database.settings()
                    val policy = settings.features.downloads
                    if (id in policy.consumedChapterIds || id in policy.manuallyMarkedChapterIds) database.updateSettings(settings.copy(features = settings.features.copy(downloads = policy.copy(consumedChapterIds = policy.consumedChapterIds - id, manuallyMarkedChapterIds = policy.manuallyMarkedChapterIds - id))))
                    deleted++
                }
            } })
            yield()
        }
        deleted
    }

    private suspend fun guarded(block: suspend () -> Unit) {
        try { block() } catch (cancel: CancellationException) { throw cancel }
        catch (failure: Exception) { AppLogger.warn("[download-policy] ${failure::class.simpleName}: ${failure.message.orEmpty()}") }
    }

    /** UI callers cannot let filesystem work outlive this profile's retirement barrier. */
    private suspend fun <T> owned(action: suspend () -> T): T = scope.runJoined { action() }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/download/DownloadKeepAlive.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/download/DownloadKeepAlive.kt) · implementation · 15 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: expect fun keepDownloadsAlive(downloads: DownloadService, database: YokanDatabase, scope: CoroutineScope, profileId: ProfileId = ProfileId.Default)
15: internal fun needsKeepAlive(status: DownloadQueueStatus): Boolean = status.pending > 0 && !status.waitingForWifi
```

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

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.download

import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.domain.ProfileId
import kotlinx.coroutines.CoroutineScope

/**
 * Keeps [downloads] running after the app leaves the screen, for as long as [scope] lives. On Android a
 * foreground service runs while [needsKeepAlive], and a network-constrained job resumes the queue if the
 * process is killed anyway; the other platforms do nothing.
 */
expect fun keepDownloadsAlive(downloads: DownloadService, database: YokanDatabase, scope: CoroutineScope, profileId: ProfileId = ProfileId.Default)

/** Work is pending and not parked waiting for Wi-Fi; a parked queue continues through the resume job. */
internal fun needsKeepAlive(status: DownloadQueueStatus): Boolean = status.pending > 0 && !status.waitingForWifi
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/download/DownloadMetadataExport.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/download/DownloadMetadataExport.kt) · implementation · 45 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 suspend fun writeMetadata(files: LocalFileService, request: DownloadRequest, location: String) {
28: internal suspend fun writeTitleMetadata(files: LocalFileService, http: HttpService, request: DownloadRequest, titleLocation: String) {
```

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

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.download

import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.files.CHAPTER_METADATA_FILE
import eu.friedcutlet.yokan.services.files.LocalFileService
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.logging.AppLogger
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive

/** Writes [request]'s metadata, keys sorted, as [CHAPTER_METADATA_FILE] in [location]; a failed write is logged. */
internal suspend fun writeMetadata(files: LocalFileService, request: DownloadRequest, location: String) {
    if (request.metadata.isEmpty()) return
    val json = JsonObject(
        request.metadata.entries
            .sortedBy { it.key }
            .associate { (key, value) -> key to JsonPrimitive(value) },
    ).toString()
    catchingNonCancellation {
        files.writeBytesAsync("$location/$CHAPTER_METADATA_FILE", json.encodeToByteArray())
    }.onFailure {
        AppLogger.warn("Failed to export metadata for ${request.taskId}: ${it.message}")
    }
}

/** [writeMetadata] for the title folder, plus its cover as `cover.jpg` unless one is already there. */
internal suspend fun writeTitleMetadata(files: LocalFileService, http: HttpService, request: DownloadRequest, titleLocation: String) {
    if (request.metadata.isEmpty()) return
    writeMetadata(files, request, titleLocation)
    val coverUrl = request.metadata["customCoverFromTracker"]
        ?: request.metadata["imageUrl"]
        ?: return
    if (coverUrl.isBlank()) return
    val coverPath = "$titleLocation/cover.jpg"
    if (files.exists(coverPath)) return
    catchingNonCancellation {
        val response = http.request(HttpRequest(url = coverUrl))
        if (response.statusCode in 200..299 && response.bodyBytes.isNotEmpty()) {
            files.writeBytesAsync(coverPath, response.bodyBytes)
        }
    }.onFailure {
        AppLogger.warn("Failed to export cover for ${request.taskId}: ${it.message}")
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/download/DownloadPaths.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/download/DownloadPaths.kt) · implementation · 39 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: fun downloadStorageRoot(configuredRoot: String?, files: LocalFileService): String =
11: fun downloadStorageRootCandidates(configuredRoot: String?, files: LocalFileService): List<String> {
17: internal fun downloadChapterLocation(
33: internal fun downloadSourceLabel(sourceName: String?, sourceLang: String?, titleSource: String): String =
36: internal fun sanitizeDownloadName(value: String): String = value.trim().replace(UnsafeFileNameChars, "_").take(120)
```

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

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.download

import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.services.files.LocalFileService
import eu.friedcutlet.yokan.services.files.downloadItemTypeFolder

fun downloadStorageRoot(configuredRoot: String?, files: LocalFileService): String =
    (configuredRoot?.takeIf { it.isNotBlank() } ?: files.downloadRoot).trimEnd('/', '\\')

fun downloadStorageRootCandidates(configuredRoot: String?, files: LocalFileService): List<String> {
    val root = downloadStorageRoot(configuredRoot, files)
    return listOf(root, "$root/downloads").distinct()
}

/** Chapter folder a download writes to: `<storageRoot>/<type>/<source>/<manga>/<scanlator_><chapter>`. */
internal fun downloadChapterLocation(
    storageRoot: String,
    itemType: DbItemType,
    sourceLabel: String,
    mangaName: String,
    scanlator: String,
    chapterName: String,
): String {
    val source = sanitizeDownloadName(sourceLabel.ifBlank { "Source" })
    val manga = sanitizeDownloadName(mangaName.ifBlank { "Unknown" })
    val scanlatorPrefix = if (scanlator.isNotBlank()) "${sanitizeDownloadName(scanlator)}_" else ""
    val chapter = sanitizeDownloadName(chapterName.ifBlank { "Chapter" })
    return "$storageRoot/${downloadItemTypeFolder(itemType)}/$source/$manga/$scanlatorPrefix$chapter"
}

/** The source folder label of a chapter download: "Name (LANG)", else the title's own source name. */
internal fun downloadSourceLabel(sourceName: String?, sourceLang: String?, titleSource: String): String =
    sourceName?.let { "$it (${sourceLang.orEmpty().uppercase()})" } ?: titleSource

internal fun sanitizeDownloadName(value: String): String = value.trim().replace(UnsafeFileNameChars, "_").take(120)
    .let { if (it.isBlank() || it == "." || it == "..") "_" else it }

private val UnsafeFileNameChars = Regex("[\\\\/:*?\"<>|\\u0000]")
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/download/DownloadPolicy.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/download/DownloadPolicy.kt) · implementation · 83 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: enum class DownloadCleanupReason { Consumption, ManualMark }
11: internal fun downloadPolicyAllows(title: DbManga, chapter: DbChapter, policy: DbDownloadPolicy): Boolean =
18: internal fun downloadReadingSequence(snapshot: YokanDatabaseSnapshot, title: DbManga, raw: List<DbChapter> = snapshot.chapters.filter { it.mangaId == title.id }, selectReleases: Boolean = true): List<DbChapter> {
25: internal fun automaticDownloadCandidates(snapshot: YokanDatabaseSnapshot, chapterIds: Set<Long>): List<Long> {
42: internal fun downloadAheadCandidates(snapshot: YokanDatabaseSnapshot, currentId: Long): List<Long> {
62: internal fun downloadCleanupCandidates(snapshot: YokanDatabaseSnapshot, titleId: Long, reason: DownloadCleanupReason, protectedIds: Set<Long>): List<Long> {
80: fun identity(chapter: DbChapter): Any = chapterReleaseIdentity(title.name.orEmpty(), chapter.name.orEmpty(), chapter.number, chapter.season, chapter.numberingName) ?: chapter.id
```

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

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.download

import eu.friedcutlet.yokan.data.toDomainChapter
import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.domain.chapterReadingOrder
import eu.friedcutlet.yokan.domain.chapterReleaseIdentity
import eu.friedcutlet.yokan.domain.selectChapterReleases

enum class DownloadCleanupReason { Consumption, ManualMark }

internal fun downloadPolicyAllows(title: DbManga, chapter: DbChapter, policy: DbDownloadPolicy): Boolean =
    title.favorite && !title.isLocalArchive && title.sourceId != null &&
        (policy.includeCategoryIds.isEmpty() || title.categories.orEmpty().any(policy.includeCategoryIds::contains)) &&
        title.categories.orEmpty().none(policy.excludeCategoryIds::contains) &&
        (!policy.unreadOnly || !chapter.isRead) && (policy.includeFiller || !chapter.effectiveFiller)

/** Same release selection and chronological order used by the reader, independent of UI state. */
internal fun downloadReadingSequence(snapshot: YokanDatabaseSnapshot, title: DbManga, raw: List<DbChapter> = snapshot.chapters.filter { it.mangaId == title.id }, selectReleases: Boolean = true): List<DbChapter> {
    val chapters = raw.map(::toDomainChapter)
    val selected = if (selectReleases) selectChapterReleases(title.name.orEmpty(), chapters, snapshot.settings.chapterReleasePreference(title.id).toPolicy()) else chapters
    val byId = raw.associateBy { it.id }
    return chapterReadingOrder(title.name.orEmpty(), selected).mapNotNull { byId[it.id] }
}

internal fun automaticDownloadCandidates(snapshot: YokanDatabaseSnapshot, chapterIds: Set<Long>): List<Long> {
    val policy = snapshot.settings.features.downloads
    if (!policy.autoDownloadNew) return emptyList()
    val recorded = snapshot.downloads.mapNotNullTo(mutableSetOf()) { it.chapterId }
    val sources = snapshot.sources.filter { it.isActive && it.isAdded }.mapTo(mutableSetOf()) { it.id }
    val byId = snapshot.chapters.associateBy { it.id }
    val byTitle = snapshot.chapters.groupBy { it.mangaId }
    val titles = snapshot.mangas.associateBy { it.id }
    return chapterIds.mapNotNull { byId[it]?.mangaId }.distinct().flatMap { titleId ->
        val title = titles[titleId] ?: return@flatMap emptyList()
        if (title.sourceId !in sources) return@flatMap emptyList()
        downloadReadingSequence(snapshot, title, byTitle[titleId].orEmpty()).filter {
            it.id in chapterIds && it.id !in recorded && downloadPolicyAllows(title, it, policy)
        }.map { it.id }
    }
}

internal fun downloadAheadCandidates(snapshot: YokanDatabaseSnapshot, currentId: Long): List<Long> {
    if (snapshot.settings.incognitoMode) return emptyList()
    val policy = snapshot.settings.features.downloads
    if (policy.aheadManga <= 0 && policy.aheadAnime <= 0 && policy.aheadNovel <= 0) return emptyList()
    val current = snapshot.chapters.firstOrNull { it.id == currentId } ?: return emptyList()
    val title = snapshot.mangas.firstOrNull { it.id == current.mangaId } ?: return emptyList()
    val count = policy.ahead(title.itemType)
    if (count == 0 || !downloadPolicyAllows(title, current.copy(isRead = false, isFiller = false, fillerOverride = null), policy)) return emptyList()
    if (snapshot.sources.none { it.id == title.sourceId && it.isActive && it.isAdded }) return emptyList()
    val sequence = downloadReadingSequence(snapshot, title)
    val identity = chapterReleaseIdentity(title.name.orEmpty(), current.name.orEmpty(), current.number, current.season, current.numberingName)
    val index = sequence.indexOfFirst { it.id == currentId || (identity != null && chapterReleaseIdentity(title.name.orEmpty(), it.name.orEmpty(), it.number, it.season, it.numberingName) == identity) }
    if (index < 0) return emptyList()
    val recorded = snapshot.downloads.mapNotNullTo(mutableSetOf()) { it.chapterId }
    // Existing queued/downloaded chapters count toward the requested ahead window; cancellation
    // and paused rows are preserved rather than silently replaced by automation.
    return sequence.drop(index + 1).filter { !it.isRead && (policy.includeFiller || !it.effectiveFiller) }
        .take(count).filter { it.id !in recorded }.map { it.id }
}

internal fun downloadCleanupCandidates(snapshot: YokanDatabaseSnapshot, titleId: Long, reason: DownloadCleanupReason, protectedIds: Set<Long>): List<Long> {
    val policy = snapshot.settings.features.downloads
    val enabled = when (reason) {
        DownloadCleanupReason.Consumption -> policy.cleanupAfterConsumption || snapshot.settings.deleteDownloadAfterReading
        DownloadCleanupReason.ManualMark -> policy.cleanupAfterManualMark
    }
    if (!enabled) return emptyList()
    val title = snapshot.mangas.firstOrNull { it.id == titleId } ?: return emptyList()
    if (title.isLocalArchive || title.categories.orEmpty().any(policy.cleanupExcludedCategoryIds::contains)) return emptyList()
    val completed = snapshot.downloads.filter { it.isDownload == true && it.isStartDownload != true && !it.isPaused }
        .mapNotNullTo(mutableSetOf()) { it.chapterId }
    // An opened alternate release remains eligible even when the preferred reader release differs.
    val consumed = downloadReadingSequence(snapshot, title, selectReleases = false).filter {
        it.isRead && it.id in when (reason) {
            DownloadCleanupReason.Consumption -> policy.consumedChapterIds
            DownloadCleanupReason.ManualMark -> policy.manuallyMarkedChapterIds
        }
    }
    fun identity(chapter: DbChapter): Any = chapterReleaseIdentity(title.name.orEmpty(), chapter.name.orEmpty(), chapter.number, chapter.season, chapter.numberingName) ?: chapter.id
    val keep = consumed.asReversed().map(::identity).distinct().take(policy.keepLastConsumed.coerceIn(0, 1000)).toSet()
    return consumed.filter { it.id in completed && identity(it) !in keep && it.id !in protectedIds && (!policy.protectBookmarks || !it.isBookmarked) }.map { it.id }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/download/DownloadQueueOrder.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/download/DownloadQueueOrder.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
12: object DownloadQueueOrder {
13: fun sorted(items: List<DbDownload>, order: List<Long>): List<DbDownload> {
```

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

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.download

import eu.friedcutlet.yokan.database.DbDownload

/**
 * Arranges queued downloads by the user's manual priority order, matching
 * Mangayomi's `DownloadQueueOrder`.
 *
 * Downloads present in [order] come first in their recorded order. Downloads
 * absent from [order] come after, maintaining their natural incoming order.
 */
object DownloadQueueOrder {
    fun sorted(items: List<DbDownload>, order: List<Long>): List<DbDownload> {
        if (order.isEmpty()) return items
        val rank = order.withIndex().associate { it.value to it.index }
        val indexed = items.withIndex().toList()
        return indexed.sortedWith { a, b ->
            val ra = rank[a.value.id] ?: (order.size + a.index)
            val rb = rank[b.value.id] ?: (order.size + b.index)
            ra.compareTo(rb)
        }.map { it.value }
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/download/DownloadService.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/download/DownloadService.kt) · implementation · 314 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
33: interface DownloadService {
38: suspend fun initialize(poolSize: Int = 6)
43: fun enqueue(request: DownloadRequest, onProgress: (DownloadProgress) -> Unit = {})
44: fun cancel(taskId: String)
46: fun cancelAll() = Unit
47: fun pause(taskId: String)
48: fun resume(taskId: String)
50: fun retry(taskId: String): Boolean
51: fun storageLocation(taskId: String): String?
53: fun deleteArtifacts(taskId: String)
55: suspend fun deleteArtifactsAsync(taskId: String, onDeleted: () -> Unit = {}): Boolean { deleteArtifacts(taskId); onDeleted(); return true }
57: suspend fun deleteCompletedArtifacts(taskId: String, stillEligible: () -> Boolean = { true }, onDeleted: () -> Unit = {}): Boolean = false
58: fun activeDownloads(): List<DownloadProgress>
59: fun reorderQueue(order: List<Long>) = Unit
66: data class DownloadQueueStatus(
71: data class DownloadProgress(
86: fun downloadTaskId(chapterId: Long?, downloadId: Long): String =
91: data class DownloadRequest(
107: data class VideoTrackFile(
113: class ChapterDownloads(
128: fun enqueue(manga: Manga, chapter: Chapter, destinationRoot: String?) {
147: private fun notifyFailure(manga: Manga, chapter: Chapter, message: String) {
161: fun deleteForChapters(chapterIds: Set<Long>): Int {
168: suspend fun deleteForChaptersAwait(chapterIds: Set<Long>): Int = owned {
177: fun deleteForManga(mangaIds: Set<Long>): Int {
183: suspend fun deleteForMangaAwait(mangaIds: Set<Long>): Set<Long> = owned {
211: fun cancel(downloadId: Long) {
217: fun remove(downloadId: Long) {
221: fun reorderQueue(newOrder: List<Long>) {
226: fun openLocation(downloadId: Long): Boolean {
232: private fun find(downloadId: Long): DbDownload? = repository.downloads().firstOrNull { it.id == downloadId }
234: private fun removeRecord(download: DbDownload) {
238: private suspend fun removeRecordAwait(download: DbDownload): Boolean {
256: private suspend fun <T> owned(action: suspend () -> T): T = scope.runJoined { action() }
258: private fun notifyRemovalFailure(taskId: String) {
269: internal fun chapterDownloadRequest(database: YokanDatabase, chapterId: Long, destinationRoot: String? = null): DownloadRequest? {
293: private fun DbSettings.selectedDownloadRoot(): String? {
298: private fun downloadMetadata(manga: Manga, sourceName: String?, chapter: DbChapter): Map<String, String> =
```

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

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.download

import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.data.YokanRepository
import eu.friedcutlet.yokan.data.toDomain
import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbDownload
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.database.configuredLocalFolders
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.services.files.LocalFileService
import eu.friedcutlet.yokan.services.logging.AppLogger
import eu.friedcutlet.yokan.services.notifications.NotificationChannel
import eu.friedcutlet.yokan.services.notifications.NotificationPayload
import eu.friedcutlet.yokan.services.notifications.NotificationService
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import eu.friedcutlet.yokan.services.blockingDispatcher
import eu.friedcutlet.yokan.services.files.resolveConfiguredLocalArchivePath
import eu.friedcutlet.yokan.services.runJoined

private val EmptyActiveDownloads = MutableStateFlow<List<DownloadProgress>>(emptyList())

private val IdleDownloadQueue = MutableStateFlow(DownloadQueueStatus())

interface DownloadService {
    val activeDownloadProgress: StateFlow<List<DownloadProgress>>
        get() = EmptyActiveDownloads
    val queueStatus: StateFlow<DownloadQueueStatus>
        get() = IdleDownloadQueue
    suspend fun initialize(poolSize: Int = 6)
    /**
     * Records and queues [request] before returning, so downloads keep the order they were requested in. With
     * Wi-Fi-only on a metered network it stays queued, waiting for Wi-Fi.
     */
    fun enqueue(request: DownloadRequest, onProgress: (DownloadProgress) -> Unit = {})
    fun cancel(taskId: String)
    /** Cancels every queued and running download. */
    fun cancelAll() = Unit
    fun pause(taskId: String)
    fun resume(taskId: String)
    /** Queues a stopped download again; false when it can't be rebuilt (its chapter is gone). */
    fun retry(taskId: String): Boolean
    fun storageLocation(taskId: String): String?
    /** Deletes the task's files: the chapter folder, its `.cbz` archive and its `_subtitles` folder. */
    fun deleteArtifacts(taskId: String)
    /** Manual removal joins transfer workers and awaits durable filesystem deletion. */
    suspend fun deleteArtifactsAsync(taskId: String, onDeleted: () -> Unit = {}): Boolean { deleteArtifacts(taskId); onDeleted(); return true }
    /** Automated cleanup must refuse active work and report file deletion failures. */
    suspend fun deleteCompletedArtifacts(taskId: String, stillEligible: () -> Boolean = { true }, onDeleted: () -> Unit = {}): Boolean = false
    fun activeDownloads(): List<DownloadProgress>
    fun reorderQueue(order: List<Long>) = Unit
}

/**
 * The queue at a glance: [pending] chapters queued or running, not counting ones the user paused.
 * [waitingForWifi] is true while Wi-Fi-only holds that work on a metered network.
 */
data class DownloadQueueStatus(
    val pending: Int = 0,
    val waitingForWifi: Boolean = false,
)

data class DownloadProgress(
    val taskId: String,
    val succeeded: Int,
    val failed: Int,
    val total: Int,
    val itemType: DbItemType,
    val isCompleted: Boolean = false,
    val isPaused: Boolean = false,
    val storageLocation: String? = null,
    val bytesDownloaded: Long = 0L,
    val mangaName: String = "",
    val chapterName: String = "",
)

/** Stable download identity used by enqueue, queue controls, recovery, and file cleanup. */
fun downloadTaskId(chapterId: Long?, downloadId: Long): String =
    chapterId?.let { "chapter-$it" } ?: "download-$downloadId"

/** A chapter download; its pages are resolved from [chapterId] when the download starts. */
@kotlinx.serialization.Serializable
data class DownloadRequest(
    val taskId: String,
    val chapterId: Long,
    val itemType: DbItemType,
    val subtitles: List<VideoTrackFile> = emptyList(),
    val mangaName: String = "",
    val chapterName: String = "",
    val sourceLabel: String = "",
    val scanlator: String = "",
    val destinationRoot: String? = null,
    val metadata: Map<String, String> = emptyMap(),
    val retries: Int = 3,
    val sourceId: Long? = null,
)

@kotlinx.serialization.Serializable
data class VideoTrackFile(
    val file: String,
    val label: String,
)

/** App-scoped chapter download actions: the single enqueue path plus queue and file cleanup. */
class ChapterDownloads(
    private val repository: YokanRepository,
    private val database: YokanDatabase,
    private val downloader: DownloadService,
    private val notifications: NotificationService,
    private val settings: SettingsStore,
    private val localFiles: LocalFileService,
    private val scope: CoroutineScope,
    private val externalDownloads: ExternalDownloads? = null,
) {
    /**
     * Records and queues [chapter] right away, in call order; its pages are resolved when the download
     * starts. A null [destinationRoot] means the download folder selected in settings. Failures surface
     * as a download notification.
     */
    fun enqueue(manga: Manga, chapter: Chapter, destinationRoot: String?) {
        runCatching {
            val request = checkNotNull(chapterDownloadRequest(database, chapter.id, destinationRoot)) {
                "${chapter.name.ifBlank { "The chapter" }} is no longer in the library"
            }
            if (destinationRoot == null && externalDownloads != null && request.itemType != DbItemType.Novel && database.settings().features.externalDownloads.preferred == eu.friedcutlet.yokan.database.PreferredDownloader.Aria2) {
                scope.launch {
                    try {
                        if (!externalDownloads.enqueue(request)) downloader.enqueue(request)
                    } catch (cancel: CancellationException) { throw cancel }
                    catch (_: Exception) { notifyFailure(manga, chapter, "External download failed. Check the server settings and remote queue.") }
                }
            } else downloader.enqueue(request)
        }.onFailure { error ->
            AppLogger.warn("[download] enqueue chapter ${chapter.id} failed: ${error.message?.lineSequence()?.firstOrNull() ?: error::class.simpleName}")
            notifyFailure(manga, chapter, error.message ?: "Download failed")
        }
    }

    private fun notifyFailure(manga: Manga, chapter: Chapter, message: String) {
        runCatching {
            notifications.notify(
                NotificationPayload(
                    channel = NotificationChannel.Downloads,
                    title = manga.name.ifBlank { "Download failed" },
                    message = message,
                    tag = "chapter-${chapter.id}",
                ),
            )
        }
    }

    /** Removes the download records and files of [chapterIds]; returns at least their count. */
    fun deleteForChapters(chapterIds: Set<Long>): Int {
        if (chapterIds.isEmpty()) return 0
        val matching = repository.downloads().filter { it.chapterId != null && it.chapterId in chapterIds }
        matching.forEach(::removeRecord)
        return matching.size.coerceAtLeast(chapterIds.size)
    }

    suspend fun deleteForChaptersAwait(chapterIds: Set<Long>): Int = owned {
        var removed = 0
        repository.downloads().filter { it.chapterId in chapterIds }.forEach {
            if (removeRecordAwait(it)) removed++
        }
        removed
    }

    /** Deletes every download of [mangaIds]; local-archive titles lose their files and library entry. */
    fun deleteForManga(mangaIds: Set<Long>): Int {
        scope.launch { deleteForMangaAwait(mangaIds) }
        return mangaIds.sumOf { repository.chapters(it).size.coerceAtLeast(1) }
    }

    /** Returns titles whose files/records were removed; dependent title deletion must await this. */
    suspend fun deleteForMangaAwait(mangaIds: Set<Long>): Set<Long> = owned {
        val successful = mutableSetOf<Long>()
        mangaIds.forEach { mangaId ->
            val chapters = repository.chapters(mangaId)
            val chapterIds = chapters.mapTo(mutableSetOf()) { it.id }
            val rows = repository.downloads().filter { it.chapterId in chapterIds }
            var removed = true
            // Keep every database parent alive until the filesystem work has finished.
            rows.forEach { if (!removeRecordAwait(it)) removed = false }
            if (repository.manga(mangaId)?.isLocalArchive == true) {
                try {
                    val paths = chapters.map { it.archivePath }.filter(String::isNotBlank).map {
                        resolveConfiguredLocalArchivePath(it, localFiles, database.settings()).substringBefore('#')
                    }.distinct()
                    withContext(blockingDispatcher) {
                        localFiles.prepare()
                        paths.forEach { if (!localFiles.deleteRecursivelyAsync(it)) removed = false }
                    }
                    if (removed) repository.removeLibraryEntries(setOf(mangaId))
                } catch (cancel: CancellationException) { throw cancel }
                catch (_: Exception) { removed = false }
                if (!removed) notifyRemovalFailure("title-$mangaId")
            }
            if (removed) successful += mangaId
        }
        successful
    }

    fun cancel(downloadId: Long) {
        val download = find(downloadId) ?: return
        repository.cancelDownload(downloadId)
        downloader.cancel(downloadTaskId(download.chapterId, download.id))
    }

    fun remove(downloadId: Long) {
        find(downloadId)?.let(::removeRecord)
    }

    fun reorderQueue(newOrder: List<Long>) {
        settings.updateDb { it.copy(downloadQueueOrder = newOrder) }
        downloader.reorderQueue(newOrder)
    }

    fun openLocation(downloadId: Long): Boolean {
        val download = find(downloadId) ?: return false
        val location = downloader.storageLocation(downloadTaskId(download.chapterId, download.id)) ?: return false
        return localFiles.openLocation(location)
    }

    private fun find(downloadId: Long): DbDownload? = repository.downloads().firstOrNull { it.id == downloadId }

    private fun removeRecord(download: DbDownload) {
        scope.launch { removeRecordAwait(download) }
    }

    private suspend fun removeRecordAwait(download: DbDownload): Boolean {
        val taskId = downloadTaskId(download.chapterId, download.id)
        return try {
            var removed = false
            val deleted = downloader.deleteArtifactsAsync(taskId, onDeleted = { database.batch {
                val current = database.download(download.id)
                if (current != null && current.chapterId == download.chapterId && current.isStartDownload != true) {
                    repository.removeDownload(download.id)
                    download.chapterId?.let { repository.clearChapterDownloads(setOf(it)) }
                    removed = true
                }
            } })
            if (!deleted) notifyRemovalFailure(taskId)
            deleted && removed
        } catch (cancel: CancellationException) { throw cancel }
        catch (_: Exception) { notifyRemovalFailure(taskId); false }
    }

    private suspend fun <T> owned(action: suspend () -> T): T = scope.runJoined { action() }

    private fun notifyRemovalFailure(taskId: String) {
        AppLogger.warn("[download] File removal failed; download records preserved")
        runCatching { notifications.notify(NotificationPayload(NotificationChannel.Downloads, "Download removal failed", "Files could not be removed. Retry after checking storage access.", tag = taskId)) }
    }
}

/**
 * The download request for [chapterId], rebuilt from the database so enqueue, retry and restart recovery
 * all describe a chapter the same way; null when the chapter or its title is gone. A null
 * [destinationRoot] means the download folder selected in settings.
 */
internal fun chapterDownloadRequest(database: YokanDatabase, chapterId: Long, destinationRoot: String? = null): DownloadRequest? {
    val chapter = database.chapter(chapterId) ?: return null
    val title = chapter.mangaId?.let(database::manga) ?: return null
    val settings = database.settings()
    val manga = title.toDomain(settings)
    val source = manga.sourceId?.let(database::source)
    return DownloadRequest(
        taskId = downloadTaskId(chapter.id, 0),
        chapterId = chapter.id,
        itemType = title.itemType,
        mangaName = manga.name,
        chapterName = chapter.name.orEmpty(),
        sourceLabel = downloadSourceLabel(source?.name, source?.lang, manga.source),
        scanlator = chapter.scanlator,
        destinationRoot = destinationRoot ?: settings.selectedDownloadRoot(),
        sourceId = source?.id ?: manga.sourceId,
        metadata = downloadMetadata(manga, source?.name, chapter),
    )
}

/**
 * The configured download folder picked in settings, else the first one; null means the default root.
 * SAF (`content://`) folders are read-only local folders, so they are never picked.
 */
private fun DbSettings.selectedDownloadRoot(): String? {
    val folders = configuredLocalFolders().filterNot { it.path.startsWith("content://") }
    return (folders.firstOrNull { it.name == downloadLocalFolderName } ?: folders.firstOrNull())?.path
}

private fun downloadMetadata(manga: Manga, sourceName: String?, chapter: DbChapter): Map<String, String> =
    buildMap {
        put("name", manga.name)
        manga.description.takeIf { it.isNotBlank() }?.let { put("description", it) }
        manga.author?.takeIf { it.isNotBlank() }?.let { put("author", it) }
        manga.artist?.takeIf { it.isNotBlank() }?.let { put("artist", it) }
        put("status", manga.status.label)
        put("itemType", manga.itemType.name)
        put("source", sourceName ?: manga.source)
        put("language", manga.lang)
        manga.imageUrl?.takeIf { it.isNotBlank() }?.let { put("imageUrl", it) }
        manga.customCoverFromTracker?.takeIf { it.isNotBlank() }?.let { put("customCoverFromTracker", it) }
        manga.genres.takeIf { it.isNotEmpty() }?.let { put("genre", it.joinToString(", ")) }
        put("chapterName", chapter.name.orEmpty())
        chapter.scanlator.takeIf { it.isNotBlank() }?.let { put("scanlator", it) }
        chapter.dateUpload.takeIf { it.isNotBlank() }?.let { put("chapterDate", it) }
    }
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/download/EinkPageTranscoder.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/download/EinkPageTranscoder.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
8: internal expect fun transcodeEinkPage(bytes: ByteArray, maxShortSide: Int): ByteArray?
13: internal fun ByteArray.isGif(): Boolean =
```

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

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.download

/**
 * Re-encodes a downloaded manga page as a grayscale JPEG whose short side is at most [maxShortSide]
 * (see [eu.friedcutlet.yokan.database.einkScaledSize]). Null keeps the original bytes: undecodable or
 * animated images, or a result that would not be smaller.
 */
internal expect fun transcodeEinkPage(bytes: ByteArray, maxShortSide: Int): ByteArray?

internal const val EinkJpegQuality = 85

/** GIFs may be animated; the decoders below would keep only the first frame. */
internal fun ByteArray.isGif(): Boolean =
    size >= 4 && this[0] == 'G'.code.toByte() && this[1] == 'I'.code.toByte() && this[2] == 'F'.code.toByte() && this[3] == '8'.code.toByte()
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/download/ExternalDownloads.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/download/ExternalDownloads.kt) · implementation · 295 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
18: class ExternalDownloads(
47: fun hasWork() = preferences().jobs.any { needsPolling(it, _jobs.subscriptionCount.value > 0) }
61: suspend fun enqueue(request: DownloadRequest): Boolean = owned {
93: suspend fun testConnection(): String = owned {
101: suspend fun setIntent(id: String, intent: RemoteDownloadIntent) = owned {
111: suspend fun retry(id: String) = owned {
141: suspend fun remove(id: String, forgetUnverified: Boolean = false) = owned {
151: suspend fun reconcile(id: String? = null) = owned { gate.withLock { reconcileLocked(id) } }
153: private suspend fun reconcileLocked(id: String? = null) {
194: private suspend fun reconcileJob(client: Aria2RpcClient, original: DbRemoteDownloadJob): DbRemoteDownloadJob {
247: private suspend fun save(jobs: List<DbRemoteDownloadJob>, durable: Boolean) {
257: private fun preferences() = database.settings().features.externalDownloads
258: private fun requireSourceIdentity(job: DbRemoteDownloadJob) {
264: private class AccountChanged : IllegalStateException()
265: private fun requireCurrent(job: DbRemoteDownloadJob) {
269: private suspend fun <T> owned(action: suspend () -> T): T = scope.runJoined { action() }
272: private fun needsPolling(job: DbRemoteDownloadJob, watched: Boolean): Boolean {
286: fun validConfiguration(prefs: DbExternalDownloads): Boolean = validEndpoint(prefs.endpoint) && validDirectory(prefs.directory)
287: fun validEndpoint(value: String): Boolean = Aria2RpcClient.validEndpoint(value)
288: fun validDirectory(value: String): Boolean = value.isNotBlank() && value.none { it.code < 32 } && value.replace('\\', '/').split('/').none { it == ".." }
289: internal fun accountBinding(prefs: DbExternalDownloads): String = sha256((prefs.endpoint + "\u0000" + prefs.secret).encodeToByteArray()).toHexString()
290: private fun resourceBinding(page: DbPageUrl): String = sha256((page.url + "\u0000" + page.headers.orEmpty().entries.sortedBy { it.key.lowercase() }.joinToString("\u0000") { it.key.lowercase() + ":" + it.value }).encodeToByteArray()).toHexString()
291: private fun newGid(): String = Random.nextBytes(8).toHexString().takeUnless { it.all { c -> c == '0' } } ?: newGid()
292: private fun publicDownloadUri(url: String): Boolean = catchingNonCancellation { Url(url).let { it.protocol.name in setOf("http", "https") && it.host.isNotBlank() && it.user.isNullOrEmpty() && it.password.isNullOrEmpty() } }.getOrDefault(false)
293: private fun extension(url: String, type: DbItemType): String = url.substringBefore('?').substringBefore('#').substringAfterLast('/').substringAfterLast('.', "").lowercase().takeIf { it in setOf("jpg", "jpeg", "png", "gif", "webp", "bmp", "avif", "mp4", "mkv", "webm", "mov", "avi", "m4v") } ?: if (type == DbItemType.Anime) "mp4" else "jpg"
```

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

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.download

import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.runJoined
import eu.friedcutlet.yokan.util.sha256
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.util.nowMillis
import io.ktor.http.Url
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlin.random.Random

/** Profile-owned remote queue. Remote completion never writes a local archive/download mark. */
class ExternalDownloads(
    private val database: YokanDatabase,
    private val http: HttpService,
    private val scope: CoroutineScope,
    private val resolvePages: suspend (Long, Boolean) -> List<DbPageUrl>,
    private val clock: () -> Long = ::nowMillis,
    private val pollMillis: Long = 2000,
    startPolling: Boolean = true,
) {
    private val owner = requireNotNull(scope.coroutineContext[Job])
    private val gate = Mutex()
    private val wake = Channel<Unit>(Channel.CONFLATED)
    private val _jobs = MutableStateFlow(preferences().jobs)
    val jobs = _jobs.asStateFlow()
    private var lastProgressSave = 0L
    private var jobCursor = 0
    private val fileCursors = mutableMapOf<String, Int>()

    init {
        if (startPolling) {
            scope.launch {
                database.snapshots().map { it.settings.features.externalDownloads.copy(jobs = emptyList()) }.distinctUntilChanged().collect {
                    wake.trySend(Unit)
                }
            }
            scope.launch { _jobs.subscriptionCount.map { it > 0 }.distinctUntilChanged().collect { if (it) wake.trySend(Unit) } }
            scope.launch {
                var backoff = pollMillis
                while (currentCoroutineContext().isActive) {
                    fun hasWork() = preferences().jobs.any { needsPolling(it, _jobs.subscriptionCount.value > 0) }
                    val signalled = if (hasWork()) withTimeoutOrNull(backoff) { wake.receive(); true } ?: false else { wake.receive(); true }
                    if (!signalled && !hasWork()) continue
                    try {
                        gate.withLock { reconcileLocked() }
                        backoff = pollMillis
                    } catch (cancel: CancellationException) { throw cancel }
                    catch (_: Exception) { backoff = (backoff * 2).coerceAtMost(60_000) }
                }
            }
        }
    }

    /** Returns false for content that must use managed local storage (novels and HLS playlists). */
    suspend fun enqueue(request: DownloadRequest): Boolean = owned {
        gate.withLock {
            val prefs = preferences()
            require(validConfiguration(prefs)) { "Configure the external downloader server and directory first" }
            if (request.itemType == DbItemType.Novel) return@withLock false
            val chapter = database.chapter(request.chapterId) ?: error("Chapter no longer exists")
            val title = chapter.mangaId?.let(database::manga) ?: error("Title no longer exists")
            require(!title.isLocalArchive)
            if (prefs.jobs.any { it.chapterId == request.chapterId && it.endpoint == prefs.endpoint && it.accountBinding == accountBinding(prefs) && (!it.terminal || it.complete) }) return@withLock true
            val pages = withTimeoutOrNull(60_000) { resolvePages(request.chapterId, false) } ?: error("Source resolution timed out")
            require(pages.isNotEmpty() && pages.size <= 2000) { "No downloadable files resolved" }
            if (pages.any { it.url.substringBefore('?').substringBefore('#').endsWith(".m3u8", true) }) return@withLock false
            require(pages.all { publicDownloadUri(it.url) }) { "External downloads require direct HTTP image or video files" }
            val id = newGid()
            val remoteDirectory = prefs.directory.trimEnd('/', '\\') + "/Yokan/${request.itemType.name}/${sanitizeDownloadName(request.mangaName).take(50)}/${sanitizeDownloadName(request.chapterName).take(50)}_$id"
            val job = DbRemoteDownloadJob(id, request.chapterId, request.itemType, request.mangaName, request.chapterName,
                prefs.endpoint, accountBinding(prefs), remoteDirectory,
                pages.mapIndexed { index, page -> DbRemoteDownloadFile(newGid(), "${(index + 1).toString().padStart(4, '0')}.${extension(page.url, request.itemType)}", page.url, page.headers.orEmpty(), resourceBinding = resourceBinding(page)) },
                createdAt = clock(), mangaId = title.id, sourceId = title.sourceId, mangaLink = title.link, chapterUrl = chapter.url, sourceTitleName = title.name.orEmpty(), sourceChapterName = chapter.name.orEmpty())
            // Resolving can suspend while settings/the chapter change. Recheck before durable admission.
            require(preferences().let { it.endpoint == prefs.endpoint && accountBinding(it) == job.accountBinding }) { "External downloader account changed" }
            require(database.chapter(request.chapterId)?.mangaId == chapter.mangaId && database.manga(title.id) != null) { "Chapter no longer exists" }
            val existing = preferences().jobs
            require(existing.count { !it.terminal } < 100) { "External download queue is full" }
            val retained = (existing.filterNot { it.terminal }.plus(existing.filter { it.terminal }.takeLast(155)) + job)
            require(DatabaseJson.encodeToString(DbExternalDownloads.serializer(), prefs.copy(jobs = retained)).encodeToByteArray().size <= 2 * 1024 * 1024) { "External download queue exceeds its storage limit" }
            save(retained, durable = true)
            wake.trySend(Unit)
            true
        }
    }

    suspend fun testConnection(): String = owned {
        val prefs = preferences()
        require(Aria2RpcClient.validEndpoint(prefs.endpoint)) { "Invalid external downloader URL" }
        val version = Aria2RpcClient(http, prefs.endpoint, prefs.secret).version()
        require(preferences().let { it.endpoint == prefs.endpoint && accountBinding(it) == accountBinding(prefs) })
        version
    }

    suspend fun setIntent(id: String, intent: RemoteDownloadIntent) = owned {
        gate.withLock {
            val current = preferences().jobs
            require(current.any { it.id == id })
            save(current.map { if (it.id == id) it.copy(intent = intent, problem = RemoteDownloadProblem.None) else it }, durable = true)
            wake.trySend(Unit)
        }
    }

    /** Only confirmed stopped remote files get a new identity; ambiguous work is never duplicated. */
    suspend fun retry(id: String) = owned {
        gate.withLock {
            val original = preferences().jobs.firstOrNull { it.id == id } ?: error("Remote download no longer exists")
            requireCurrent(original)
            requireSourceIdentity(original)
            val candidates = original.files.filter { it.state in setOf(RemoteDownloadState.Error, RemoteDownloadState.Removed, RemoteDownloadState.Attention, RemoteDownloadState.Submitting) }
            require(candidates.isNotEmpty())
            val prefs = preferences()
            val client = Aria2RpcClient(http, prefs.endpoint, prefs.secret)
            val statuses = candidates.chunked(64).flatMap { client.statuses(it.map { file -> file.gid }).entries }.associate { it.key to it.value.getOrThrow() }
            val pages = withTimeoutOrNull(60_000) { resolvePages(original.chapterId, true) } ?: error("Source resolution timed out")
            require(pages.size == original.files.size && pages.all { publicDownloadUri(it.url) && !it.url.substringBefore('?').endsWith(".m3u8", true) }) { "Download files changed; enqueue the chapter again" }
            requireCurrent(original)
            requireSourceIdentity(original)
            val files = original.files.mapIndexed { index, file ->
                val remote = statuses[file.gid] ?: return@mapIndexed file
                if (remote.status in setOf(Aria2Status.Error, Aria2Status.Removed)) {
                    val gid = newGid()
                    val resource = resourceBinding(pages[index])
                    val name = if (file.resourceBinding.isNotBlank() && resource == file.resourceBinding) file.name else "${(index + 1).toString().padStart(4, '0')}_r_$gid.${extension(pages[index].url, original.itemType)}"
                    DbRemoteDownloadFile(gid, name, pages[index].url, pages[index].headers.orEmpty(), resourceBinding = resource)
                }
                else file.copy(state = RemoteDownloadState.valueOf(remote.status.name), url = "", headers = emptyMap(), totalBytes = remote.totalBytes, completedBytes = remote.completedBytes)
            }
            save(preferences().jobs.map { if (it.id == id) original.copy(files = files, intent = RemoteDownloadIntent.Run, problem = RemoteDownloadProblem.None) else it }, durable = true)
            wake.trySend(Unit)
        }
    }

    /** Removes the local receipt only after every remote task is confirmed stopped/completed. */
    suspend fun remove(id: String, forgetUnverified: Boolean = false) = owned {
        gate.withLock {
            val current = preferences().jobs
            val job = current.firstOrNull { it.id == id } ?: return@withLock
            require(job.terminal || forgetUnverified) { "Cancel the remote download before removing its receipt" }
            save(current.filterNot { it.id == id }, durable = true)
        }
    }

    /** Also exposed to foreground refresh and deterministic recovery tests. */
    suspend fun reconcile(id: String? = null) = owned { gate.withLock { reconcileLocked(id) } }

    private suspend fun reconcileLocked(id: String? = null) {
        owner.ensureActive()
        val prefs = preferences()
        if (prefs.jobs.isEmpty()) return
        fileCursors.keys.retainAll(prefs.jobs.mapTo(mutableSetOf()) { it.id })
        val binding = accountBinding(prefs)
        val client = if (validEndpoint(prefs.endpoint)) Aria2RpcClient(http, prefs.endpoint, prefs.secret) else null
        var work = _jobs.value.associateBy { it.id }.let { live -> prefs.jobs.map { live[it.id] ?: it } }
        val bound = work.map { job ->
            if (job.terminal) job
            else if (client == null || job.endpoint != prefs.endpoint || job.accountBinding != binding) job.copy(problem = RemoteDownloadProblem.ServerChanged)
            else if (job.problem == RemoteDownloadProblem.ServerChanged) job.copy(problem = RemoteDownloadProblem.None)
            else job
        }
        if (bound != work) { work = bound; save(work, durable = true) }
        if (client == null) return
        var failed = false
        var statusChanged = false
        // Work is bounded per pass; rotate jobs so a large chapter cannot starve later requests.
        val candidates = work.filter { !it.terminal && it.endpoint == prefs.endpoint && it.accountBinding == binding }.sortedBy { it.createdAt }
        val ordered = if (id != null) candidates.filter { it.id == id } else if (candidates.isEmpty()) emptyList() else List(minOf(4, candidates.size)) { candidates[(jobCursor + it) % candidates.size] }
        jobCursor = if (candidates.isEmpty()) 0 else (jobCursor + ordered.size) % candidates.size
        for (old in ordered) {
            var job = old
            try {
                job = reconcileJob(client, job)
                if (job.problem == RemoteDownloadProblem.Connection) failed = true
            } catch (cancel: CancellationException) { throw cancel }
            catch (_: AccountChanged) { job = job.copy(problem = RemoteDownloadProblem.ServerChanged) }
            catch (_: Exception) { failed = true; job = job.copy(problem = RemoteDownloadProblem.Connection) }
            statusChanged = statusChanged || job.copy(files = job.files.map { it.copy(totalBytes = 0, completedBytes = 0) }) != old.copy(files = old.files.map { it.copy(totalBytes = 0, completedBytes = 0) })
            work = work.map { if (it.id == job.id) job else it }
            // Acknowledgements are durable before another job's remote side effects.
            if (statusChanged) { save(work, durable = true); statusChanged = false }
            else _jobs.update { work }
            if (failed) break
        }
        if (clock() - lastProgressSave >= 15_000) { save(work, durable = false); lastProgressSave = clock() }
        if (failed) error("External download server unavailable")
    }

    private suspend fun reconcileJob(client: Aria2RpcClient, original: DbRemoteDownloadJob): DbRemoteDownloadJob {
        var job = original.copy(problem = RemoteDownloadProblem.None)
        val files = job.files.toMutableList()
        val eligible = files.filter { it.state !in setOf(RemoteDownloadState.Pending, RemoteDownloadState.Complete, RemoteDownloadState.Removed) }
        val cursor = fileCursors[job.id] ?: 0
        val query = if (eligible.isEmpty()) emptyList() else List(minOf(64, eligible.size)) { eligible[(cursor + it) % eligible.size] }
        fileCursors[job.id] = if (eligible.isEmpty()) 0 else (cursor + query.size) % eligible.size
        for (batch in query.chunked(64)) {
            requireCurrent(job)
            val statuses = client.statuses(batch.map { it.gid })
            for (file in batch) {
                val index = files.indexOfFirst { it.gid == file.gid }
                val result = statuses.getValue(file.gid)
                val status = result.getOrNull()
                if (status == null) {
                    // Never re-admit an uncertain/missing GID automatically, even after server restart.
                    files[index] = file.copy(state = RemoteDownloadState.Attention)
                    job = job.copy(problem = RemoteDownloadProblem.MissingOrRejected)
                    continue
                }
                files[index] = file.copy(state = RemoteDownloadState.valueOf(status.status.name), totalBytes = status.totalBytes,
                    completedBytes = status.completedBytes, errorCode = status.errorCode, url = "", headers = emptyMap())
                when {
                    job.intent == RemoteDownloadIntent.Cancel && status.status == Aria2Status.Error -> files[index] = files[index].copy(state = RemoteDownloadState.Removed)
                    job.intent == RemoteDownloadIntent.Cancel && status.status !in setOf(Aria2Status.Complete, Aria2Status.Removed) -> { requireCurrent(job); client.cancel(file.gid) }
                    job.intent == RemoteDownloadIntent.Pause && status.status in setOf(Aria2Status.Active, Aria2Status.Waiting) -> { requireCurrent(job); client.pause(file.gid) }
                    job.intent == RemoteDownloadIntent.Run && status.status == Aria2Status.Paused -> { requireCurrent(job); client.resume(file.gid) }
                }
            }
        }
        if (files.any { it.state == RemoteDownloadState.Attention }) return job.copy(files = files.toList(), problem = RemoteDownloadProblem.MissingOrRejected)
        val pending = files.withIndex().filter { it.value.state == RemoteDownloadState.Pending }.take(4)
        for ((index, file) in pending) {
            if (job.intent == RemoteDownloadIntent.Cancel) { files[index] = file.copy(state = RemoteDownloadState.Removed, url = "", headers = emptyMap()); continue }
            if (job.intent == RemoteDownloadIntent.Pause) continue
            files[index] = file.copy(state = RemoteDownloadState.Submitting)
            job = job.copy(files = files.toList())
            val all = preferences().jobs.map { if (it.id == job.id) job else it }
            save(all, durable = true)
            try {
                requireCurrent(job)
                client.addUri(file.gid, file.url, job.directory, file.name, file.headers)
                files[index] = file.copy(state = RemoteDownloadState.Waiting, url = "", headers = emptyMap())
            } catch (cancel: CancellationException) { throw cancel }
            catch (changed: AccountChanged) { throw changed }
            catch (_: Exception) {
                // Persist Submitting: the request may have reached the server even when its reply did not.
                return job.copy(files = files.toList(), problem = RemoteDownloadProblem.Connection)
            }
        }
        return job.copy(files = files.toList())
    }

    private suspend fun save(jobs: List<DbRemoteDownloadJob>, durable: Boolean) {
        owner.ensureActive()
        if (preferences().jobs != jobs) database.batch {
            val current = database.settings()
            database.updateSettings(current.copy(features = current.features.copy(externalDownloads = current.features.externalDownloads.copy(jobs = jobs))))
        }
        _jobs.update { jobs }
        if (durable) database.awaitPersistence()
    }

    private fun preferences() = database.settings().features.externalDownloads
    private fun requireSourceIdentity(job: DbRemoteDownloadJob) {
        val chapter = database.chapter(job.chapterId)
        val title = chapter?.mangaId?.let(database::manga)
        require(chapter != null && title != null && title.id == job.mangaId && title.sourceId == job.sourceId && title.link == job.mangaLink && chapter.url == job.chapterUrl && title.itemType == job.itemType && !title.isLocalArchive &&
            (!job.mangaLink.isNullOrBlank() || job.chapterUrl.isNotBlank() || (title.name.orEmpty() == job.sourceTitleName && chapter.name.orEmpty() == job.sourceChapterName))) { "Source identity changed; enqueue the chapter again" }
    }
    private class AccountChanged : IllegalStateException()
    private fun requireCurrent(job: DbRemoteDownloadJob) {
        owner.ensureActive()
        if (preferences().let { it.endpoint != job.endpoint || accountBinding(it) != job.accountBinding }) throw AccountChanged()
    }
    private suspend fun <T> owned(action: suspend () -> T): T = scope.runJoined { action() }

    companion object {
        private fun needsPolling(job: DbRemoteDownloadJob, watched: Boolean): Boolean {
            if (job.problem == RemoteDownloadProblem.ServerChanged) return false
            val uncertain = job.files.any { it.state == RemoteDownloadState.Attention }
            return job.files.any { file ->
                when (file.state) {
                    RemoteDownloadState.Pending -> !uncertain && job.intent != RemoteDownloadIntent.Pause
                    RemoteDownloadState.Submitting -> true
                    RemoteDownloadState.Active, RemoteDownloadState.Waiting -> watched || job.intent != RemoteDownloadIntent.Run
                    RemoteDownloadState.Paused -> watched || job.intent != RemoteDownloadIntent.Pause
                    RemoteDownloadState.Error -> job.intent == RemoteDownloadIntent.Cancel
                    else -> false
                }
            }
        }
        fun validConfiguration(prefs: DbExternalDownloads): Boolean = validEndpoint(prefs.endpoint) && validDirectory(prefs.directory)
        fun validEndpoint(value: String): Boolean = Aria2RpcClient.validEndpoint(value)
        fun validDirectory(value: String): Boolean = value.isNotBlank() && value.none { it.code < 32 } && value.replace('\\', '/').split('/').none { it == ".." }
        internal fun accountBinding(prefs: DbExternalDownloads): String = sha256((prefs.endpoint + "\u0000" + prefs.secret).encodeToByteArray()).toHexString()
        private fun resourceBinding(page: DbPageUrl): String = sha256((page.url + "\u0000" + page.headers.orEmpty().entries.sortedBy { it.key.lowercase() }.joinToString("\u0000") { it.key.lowercase() + ":" + it.value }).encodeToByteArray()).toHexString()
        private fun newGid(): String = Random.nextBytes(8).toHexString().takeUnless { it.all { c -> c == '0' } } ?: newGid()
        private fun publicDownloadUri(url: String): Boolean = catchingNonCancellation { Url(url).let { it.protocol.name in setOf("http", "https") && it.host.isNotBlank() && it.user.isNullOrEmpty() && it.password.isNullOrEmpty() } }.getOrDefault(false)
        private fun extension(url: String, type: DbItemType): String = url.substringBefore('?').substringBefore('#').substringAfterLast('/').substringAfterLast('.', "").lowercase().takeIf { it in setOf("jpg", "jpeg", "png", "gif", "webp", "bmp", "avif", "mp4", "mkv", "webm", "mov", "avi", "m4v") } ?: if (type == DbItemType.Anime) "mp4" else "jpg"
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/download/HlsPlaylist.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/download/HlsPlaylist.kt) · implementation · 155 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
22: internal fun resolveHlsUrl(base: String, reference: String): String? = runCatching {
30: internal fun hlsBestVariantUrl(playlist: String, playlistUrl: String): String? {
50: internal fun hlsAttribute(line: String, name: String): String? =
54: internal fun hlsWithUri(line: String, uri: String): String =
62: internal suspend fun PageTransfer.downloadHlsPlaylist(
150: private suspend fun HttpService.fetchText(url: String, headers: Map<String, String>): HttpResponse? =
155: private fun HttpResponse.isPlaylist(): Boolean = statusCode in 200..299 && body.startsWith("#EXTM3U")
```

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

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.download

import eu.friedcutlet.yokan.database.DbPageUrl
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.util.PlatformLock
import io.ktor.http.URLBuilder
import io.ktor.http.takeFrom
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.withPermit
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull

/**
 * [reference] from a playlist (absolute, protocol-relative, root-relative or relative) resolved against
 * [base]; null when either is not a URL. The base's query and fragment never carry over.
 */
internal fun resolveHlsUrl(base: String, reference: String): String? = runCatching {
    URLBuilder(base).apply {
        parameters.clear()
        fragment = ""
    }.takeFrom(reference).buildString()
}.getOrNull()

/** The highest-BANDWIDTH variant of a master playlist resolved against [playlistUrl]; null for a media playlist. */
internal fun hlsBestVariantUrl(playlist: String, playlistUrl: String): String? {
    var bestBandwidth = -1L
    var bestUri: String? = null
    var bandwidth: Long? = null
    for (rawLine in playlist.lines()) {
        val line = rawLine.trim()
        if (line.startsWith("#EXT-X-STREAM-INF")) {
            bandwidth = hlsAttribute(line, "BANDWIDTH")?.toLongOrNull() ?: 0L
        } else if (bandwidth != null && line.isNotEmpty() && !line.startsWith("#")) {
            if (bandwidth > bestBandwidth) {
                bestBandwidth = bandwidth
                bestUri = line
            }
            bandwidth = null
        }
    }
    return bestUri?.let { resolveHlsUrl(playlistUrl, it) }
}

/** Attribute [name] of an HLS tag line, unquoted; quoted values may contain commas. */
internal fun hlsAttribute(line: String, name: String): String? =
    Regex("""[:,]$name=("[^"]*"|[^,]*)""").find(line)?.groupValues?.get(1)?.removeSurrounding("\"")

/** [line] with its `URI="…"` attribute pointing at [uri]. */
internal fun hlsWithUri(line: String, uri: String): String =
    line.replace(Regex("""URI="[^"]*"""")) { "URI=\"$uri\"" }

/**
 * Saves an HLS stream as `<name>.m3u8` with its segments, keys and init maps rewritten to local files; a
 * master playlist is followed to its highest-bandwidth variant. Every file is retried and marked like a
 * page, so a restart only fetches what is missing. Null once saved, else the failing HTTP status.
 */
internal suspend fun PageTransfer.downloadHlsPlaylist(
    page: DbPageUrl,
    location: String,
    name: String,
    retries: Int,
    permits: Semaphore,
    onBytes: (Long) -> Unit,
    onTransfer: (Long) -> Unit,
): Int? {
    val headers = page.headers.orEmpty()
    var playlistUrl = page.url
    var response = http.fetchText(playlistUrl, headers) ?: return 0
    if (response.isPlaylist()) {
        hlsBestVariantUrl(response.body, playlistUrl)?.let { variant ->
            playlistUrl = variant
            response = http.fetchText(variant, headers) ?: return 0
        }
    }
    val playlist = response.body
    if (!response.isPlaylist() || playlist.lines().none { it.isNotBlank() && !it.trim().startsWith("#") }) {
        return response.statusCode
    }
    // Remote URL → local file name; keys and byte-range segments repeat the same URL.
    val localNames = mutableMapOf<String, String>()
    val rewritten = mutableListOf<String>()
    var segments = 0
    for (rawLine in playlist.lines()) {
        val line = rawLine.trim()
        val tagUri = if (line.startsWith("#EXT-X-KEY") || line.startsWith("#EXT-X-MAP")) hlsAttribute(line, "URI") else null
        val reference = tagUri ?: line.takeUnless { it.isEmpty() || it.startsWith("#") }
        if (reference == null) {
            rewritten += line
            continue
        }
        val remote = resolveHlsUrl(playlistUrl, reference) ?: return 0
        val localName = localNames[remote] ?: run {
            val fileName = when {
                tagUri == null -> "${name}_seg_${padIndex(segments++)}.ts"
                line.startsWith("#EXT-X-KEY") -> "${name}_key_${localNames.size}.key"
                else -> "${name}_map_${localNames.size}.mp4"
            }
            fileName.also { localNames[remote] = it }
        }
        rewritten += if (tagUri == null) localName else hlsWithUri(line, localName)
    }
    val pending = ArrayDeque(localNames.entries.toList())
    val progress = mutableMapOf<String, Long>()
    val failures = mutableListOf<Int>()
    // Guards pending, progress and failures across the parallel workers below.
    val lock = PlatformLock()
    coroutineScope {
        repeat(minOf(PAGE_PARALLELISM, pending.size)) {
            launch {
                while (true) {
                    val resource = lock.withLock { pending.removeFirstOrNull() } ?: break
                    val path = "$location/${resource.value}"
                    val savedSize = withContext(ioDispatcher) {
                        if (files.exists(path) && files.exists("$path.complete")) files.directorySize(path) else null
                    }
                    val update: (Long) -> Unit = { bytes ->
                        lock.withLock {
                            progress[resource.key] = bytes
                            onTransfer(progress.values.sum())
                        }
                    }
                    if (savedSize != null) {
                        update(savedSize)
                    } else {
                        val status = permits.withPermit {
                            attemptDownload(resource.key, headers, path, retries, onBytes = {}, onTransfer = update)
                        }
                        if (status != null) lock.withLock { failures += status }
                    }
                }
            }
        }
    }
    failures.firstOrNull()?.let { return it }
    onBytes(lock.withLock { progress.values.sum() })
    withContext(ioDispatcher) {
        val playlistPath = "$location/$name.m3u8"
        files.writeBytesAsync(playlistPath, rewritten.joinToString("\n").encodeToByteArray())
        files.writeBytesAsync("$playlistPath.complete", ByteArray(0))
    }
    onBytes(playlist.length.toLong())
    return null
}

private suspend fun HttpService.fetchText(url: String, headers: Map<String, String>): HttpResponse? =
    catchingNonCancellation {
        withTimeoutOrNull(DOWNLOAD_CONNECTION_TIMEOUT_MS) { request(HttpRequest(url = url, headers = headers)) }
    }.getOrNull()

private fun HttpResponse.isPlaylist(): Boolean = statusCode in 200..299 && body.startsWith("#EXTM3U")
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/download/ImageDataSaver.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/download/ImageDataSaver.kt) · implementation · 163 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
23: data class SavedImageRequest(val url: String, val headers: Map<String, String>, val cacheVariant: String)
26: class ImageDataSaver(
33: private data class Cached(val value: SavedImageRequest, val expires: Long)
37: suspend fun resolve(original: String, headers: Map<String, String>, sourceId: Long?, settings: DbImageDataSaver, download: Boolean): SavedImageRequest? {
70: fun failed(request: SavedImageRequest) = lock.withLock {
76: private suspend fun resolveResmush(original: String, settings: DbImageDataSaver, variant: String): SavedImageRequest? = resolving.withPermit {
121: fun eligible(original: String, headers: Map<String, String>, sourceId: Long?, settings: DbImageDataSaver, download: Boolean): Boolean {
136: fun variant(settings: DbImageDataSaver): String = "saver-v1:${settings.provider}:${settings.quality.coerceIn(1, 100)}:${settings.format}:${settings.grayscale}:${settings.bandwidthHeroUrl}"
138: fun validEndpoint(raw: String): Boolean = publicHttpsUrl(raw)?.parameters?.entries()?.isEmpty() == true
141: private fun resmushDestination(raw: String, quality: Int): String? {
153: private fun publicHttpsUrl(raw: String): Url? {
```

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

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.download

import eu.friedcutlet.yokan.database.DbImageDataSaver
import eu.friedcutlet.yokan.database.ImageSaverFormat
import eu.friedcutlet.yokan.database.ImageSaverProvider
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.http.cookies.CookieJar
import eu.friedcutlet.yokan.util.PlatformLock
import eu.friedcutlet.yokan.util.nowMillis
import io.ktor.http.URLBuilder
import io.ktor.http.Url
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.withPermit
import kotlinx.coroutines.withTimeoutOrNull
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.longOrNull

data class SavedImageRequest(val url: String, val headers: Map<String, String>, val cacheVariant: String)

/** No source credentials are sent to a compression provider. Failures use the original image. */
class ImageDataSaver(
    private val http: HttpService,
    private val jar: CookieJar,
    private val clock: () -> Long = ::nowMillis,
) {
    private val lock = PlatformLock()
    private val resolving = Semaphore(2)
    private data class Cached(val value: SavedImageRequest, val expires: Long)
    private val cache = linkedMapOf<String, Cached>()
    private val cooldown = linkedMapOf<String, Long>()

    suspend fun resolve(original: String, headers: Map<String, String>, sourceId: Long?, settings: DbImageDataSaver, download: Boolean): SavedImageRequest? {
        if (!eligible(original, headers, sourceId, settings, download) || jar.cookieHeader(original) != null) return null
        val variant = variant(settings)
        if (lock.withLock { (cooldown[variant] ?: 0) > clock() }) return null
        val url = Url(original)
        val direct = when (settings.provider) {
            ImageSaverProvider.Off -> return null
            ImageSaverProvider.Wsrv -> URLBuilder("https://wsrv.nl/").apply {
                parameters.append("url", original)
                parameters.append("q", settings.quality.coerceIn(1, 100).toString())
                parameters.append("n", "-1")
                when (settings.format) {
                    ImageSaverFormat.Jpeg -> { parameters.append("output", "jpg"); parameters.append("bg", "white") }
                    ImageSaverFormat.Webp -> parameters.append("output", "webp")
                    ImageSaverFormat.Original -> Unit
                }
                if (settings.grayscale) parameters.append("filt", "greyscale")
            }.buildString()
            ImageSaverProvider.BandwidthHero -> {
                val endpoint = publicHttpsUrl(settings.bandwidthHeroUrl) ?: return null
                if (endpoint.parameters.entries().isNotEmpty()) return null
                URLBuilder(endpoint).apply {
                    parameters.append("url", original)
                    parameters.append("l", settings.quality.coerceIn(1, 100).toString())
                    parameters.append("bw", if (settings.grayscale) "1" else "0")
                    if (settings.format == ImageSaverFormat.Jpeg || (settings.format == ImageSaverFormat.Original && url.encodedPath.substringAfterLast('.').lowercase() in setOf("jpg", "jpeg"))) parameters.append("jpeg", "1")
                }.buildString()
            }
            ImageSaverProvider.Resmush -> return resolveResmush(original, settings, variant)
        }
        return SavedImageRequest(direct, ProviderHeaders, variant)
    }

    fun failed(request: SavedImageRequest) = lock.withLock {
        cooldown[request.cacheVariant] = clock() + 60_000
        while (cooldown.size > 16) cooldown.remove(cooldown.keys.first())
        cache.entries.removeAll { it.value.value.cacheVariant == request.cacheVariant }
    }

    private suspend fun resolveResmush(original: String, settings: DbImageDataSaver, variant: String): SavedImageRequest? = resolving.withPermit {
        val key = "$variant|$original"
        lock.withLock { cache[key]?.takeIf { it.expires > clock() }?.value }?.let { return@withPermit it }
        val result = try {
            withTimeoutOrNull(10_000) {
                val url = URLBuilder("https://api.resmush.it/ws.php").apply {
                    parameters.append("img", original)
                    parameters.append("qlty", settings.quality.coerceIn(1, 100).toString())
                    parameters.append("exif", "true")
                }.buildString()
                val body = mutableListOf<ByteArray>()
                var size = 0
                val response = http.stream(HttpRequest(url, headers = ProviderHeaders)) { bytes ->
                    size += bytes.size
                    check(size <= 32 * 1024) { "Image optimizer response exceeds limit" }
                    body += bytes
                }
                check(response.statusCode in 200..299)
                val bytes = ByteArray(size)
                var offset = 0
                body.forEach { it.copyInto(bytes, offset); offset += it.size }
                val json = Json.parseToJsonElement(bytes.decodeToString()).jsonObject
                check(json["error"]?.jsonPrimitive?.longOrNull in listOf(null, 0L))
                val destination = resmushDestination(json["dest"]?.jsonPrimitive?.contentOrNull.orEmpty(), settings.quality)
                check(destination != null)
                val srcSize = json["src_size"]?.jsonPrimitive?.longOrNull
                val destSize = json["dest_size"]?.jsonPrimitive?.longOrNull
                check(srcSize == null || destSize == null || (destSize > 0 && destSize < srcSize))
                SavedImageRequest(destination, ProviderHeaders, variant)
            }
        } catch (cancel: CancellationException) { throw cancel }
        catch (_: Exception) { null }
        if (result == null) {
            failed(SavedImageRequest("", emptyMap(), variant))
        } else lock.withLock {
            cache[key] = Cached(result, clock() + 60_000)
            while (cache.size > 128) cache.remove(cache.keys.first())
        }
        result
    }

    companion object {
        val ProviderHeaders = mapOf("User-Agent" to "Yokan (+https://github.com/Schnitzel5/yokan)", "Referer" to "https://github.com/Schnitzel5/yokan")
        private val allowedQueryKeys = setOf("w", "h", "width", "height", "q", "quality", "format", "fm", "fit", "auto", "dpr", "ixlib", "v", "resize", "output")

        fun eligible(original: String, headers: Map<String, String>, sourceId: Long?, settings: DbImageDataSaver, download: Boolean): Boolean {
            if (settings.provider == ImageSaverProvider.Off || (download && !settings.forDownloads) || (!download && !settings.forReader)) return false
            if (sourceId in settings.excludedSourceIds || (sourceId == null && settings.excludedSourceIds.isNotEmpty())) return false
            if (headers.any { (name, value) -> value.isNotBlank() && name.lowercase() !in setOf("referer", "user-agent", "accept", "accept-language", "accept-encoding", "cache-control", "pragma") }) return false
            val url = publicHttpsUrl(original) ?: return false
            // Browser-local media uses HTTPS on hosted installs, but must never leave the device.
            if (url.encodedPath.split('/').any { it == "__yokan_files__" }) return false
            if (url.parameters.entries().any { (key, values) -> key.lowercase() !in allowedQueryKeys || values.any { it.length > 128 } }) return false
            val extension = url.encodedPath.substringAfterLast('.').lowercase()
            if (settings.skipJpeg && extension in setOf("jpg", "jpeg")) return false
            if (settings.skipGif && extension == "gif") return false
            if (settings.provider == ImageSaverProvider.Resmush && extension !in setOf("jpg", "jpeg", "png", "gif", "tif", "tiff", "bmp")) return false
            return true
        }

        fun variant(settings: DbImageDataSaver): String = "saver-v1:${settings.provider}:${settings.quality.coerceIn(1, 100)}:${settings.format}:${settings.grayscale}:${settings.bandwidthHeroUrl}"

        fun validEndpoint(raw: String): Boolean = publicHttpsUrl(raw)?.parameters?.entries()?.isEmpty() == true

        /** Its API still returns HTTP CDN URLs. A documented HTTPS image proxy also works in browsers. */
        private fun resmushDestination(raw: String, quality: Int): String? {
            val url = try { Url(raw) } catch (_: Exception) { return null }
            if (url.host != "resmush.it" && !url.host.endsWith(".resmush.it")) return null
            if (publicHttpsUrl(raw) != null) return raw
            if (url.protocol.name != "http" || url.port != 80 || !url.user.isNullOrEmpty() || !url.password.isNullOrEmpty() || url.fragment.isNotEmpty()) return null
            return URLBuilder("https://wsrv.nl/").apply {
                parameters.append("url", raw)
                parameters.append("q", quality.coerceIn(1, 100).toString())
                parameters.append("n", "-1")
            }.buildString()
        }

        private fun publicHttpsUrl(raw: String): Url? {
            val url = try { Url(raw) } catch (_: Exception) { return null }
            val host = url.host.lowercase().trimEnd('.')
            return url.takeIf {
                it.protocol.name == "https" && it.port == 443 && it.user.isNullOrEmpty() && it.password.isNullOrEmpty() && it.fragment.isEmpty() &&
                    host.contains('.') && host.any(Char::isLetter) && !host.contains(':') &&
                    host != "localhost" && listOf(".localhost", ".local", ".internal", ".lan", ".home", ".onion").none(host::endsWith)
            }
        }
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/download/PageTransfer.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/download/PageTransfer.kt) · implementation · 177 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
27: internal class PageTransfer(
46: suspend fun savedPages(location: String, pageCount: Int, splitHeight: Int?): Map<Int, Long> {
71: suspend fun downloadPage(
115: suspend fun attemptDownload(
161: suspend fun promoteWithMarker(temporaryPath: String, targetPath: String, marker: String): Boolean =
169: private suspend fun safeDelete(path: String): Boolean = catchingNonCancellation { files.deleteRecursivelyAsync(path) }.getOrDefault(false)
172: internal fun padIndex(index: Int): String = index.toString().padStart(4, '0')
174: private fun String.fileExtension(): String {
```

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

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.download

import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbPageUrl
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.files.LocalFileService
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.http.header
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.delay
import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.withPermit
import kotlinx.coroutines.withContext

/** Page file extensions kept from the URL; anything else is saved as `.jpg` so the reader lists it. */
private val PageFileExtensions = setOf(
    "png", "jpg", "jpeg", "gif", "webp", "bmp", "avif",
    "mp4", "mkv", "mov", "webm", "avi", "m4v", "ts",
    "txt", "html", "xhtml",
)

/**
 * Fetches and stores single chapter files (pages, HLS streams, novel text) with `.part` files and
 * `.complete` markers. Holds no queue state: progress reaches the caller only through its callbacks.
 */
internal class PageTransfer(
    private val database: YokanDatabase,
    val http: HttpService,
    val files: LocalFileService,
    imageHttp: HttpService,
    private val imageDataSaver: ImageDataSaver?,
    /** Blocking file work: page writes, promotion and splitting. */
    val ioDispatcher: CoroutineDispatcher,
    /** Suspends while the network may not be used; called before every attempt. */
    private val awaitAllowedNetwork: suspend () -> Unit,
) {
    private val transfers = ResumableDownload(http, files)
    private val imageTransfers = ResumableDownload(imageHttp, files)
    private val splitPages = SplitPageStore(files)

    /**
     * Sizes of the pages an earlier run saved in [location] (page file plus `.complete` marker) by index.
     * Files of indices beyond [pageCount] are deleted, so a shorter page list leaves no stale pages behind.
     */
    suspend fun savedPages(location: String, pageCount: Int, splitHeight: Int?): Map<Int, Long> {
        val entries = files.listFiles(location)
        val names = entries.mapTo(HashSet()) { it.name }
        val saved = mutableMapOf<Int, Long>()
        entries.filter { it.name.endsWith(".split.json") }.forEach { entry ->
            val base = entry.name.removeSuffix(".split.json")
            val index = base.toIntOrNull()?.minus(1) ?: return@forEach
            if (index in 0 until pageCount) splitPages.savedSize(location, base)?.let { saved[index] = it }
        }
        entries.forEach { entry ->
            val index = entry.name.takeWhile(Char::isDigit).toIntOrNull()?.minus(1) ?: return@forEach
            val isPageFile = entry.name.substringBeforeLast('.').all(Char::isDigit)
            if (index >= pageCount) {
                safeDelete(entry.path)
            } else if (index !in saved && isPageFile && "${entry.name}.complete" in names && files.exists(entry.path)) {
                saved[index] = if (splitHeight != null) splitPages.process(entry.path, splitHeight) else entry.sizeBytes
            }
        }
        return saved
    }

    /**
     * Saves page [index] of [request] into [location], holding one of the chapter's [permits] while it
     * transfers. Null once saved, else the failing HTTP status (0 without a response).
     */
    suspend fun downloadPage(
        request: DownloadRequest,
        location: String,
        permits: Semaphore,
        page: DbPageUrl,
        index: Int,
        onBytes: (Long) -> Unit,
        onTransfer: (Long) -> Unit,
    ): Int? {
        val name = padIndex(index + 1)
        val retries = request.retries
        if (page.url.endsWith(".m3u8", ignoreCase = true) || page.url.contains(".m3u8?", ignoreCase = true)) {
            return downloadHlsPlaylist(page, location, name, retries, permits, onBytes, onTransfer)
        }
        val settings = database.settings()
        // E-ink devices store manga pages at panel size in grayscale; the page keeps its name, readers sniff the format.
        val shrink: ((ByteArray) -> ByteArray?)? = if (request.itemType == DbItemType.Manga && settings.einkMode && settings.einkOptimizeDownloads) {
            { bytes -> transcodeEinkPage(bytes, settings.einkPreset.width) }
        } else null
        return permits.withPermit {
            val path = "$location/$name${page.url.fileExtension()}"
            var storedBytes = 0L
            val sourceId = request.sourceId ?: database.chapter(request.chapterId)?.mangaId?.let(database::manga)?.sourceId
            val optimized = if (request.itemType == DbItemType.Manga) imageDataSaver?.resolve(page.url, page.headers.orEmpty(), sourceId, settings.features.imageDataSaver, download = true) else null
            var status = if (optimized != null) attemptDownload(optimized.url, optimized.headers, path, 0, { storedBytes = it }, shrink, onTransfer, imageTransfers, requireImageResponse = true) else 0
            if (optimized == null || status != null) {
                if (optimized != null) imageDataSaver?.failed(optimized)
                status = attemptDownload(page.url, page.headers.orEmpty(), path, retries, { storedBytes = it }, shrink, onTransfer)
            }
            if (status == null) {
                if (request.itemType == DbItemType.Manga && settings.features.downloads.splitTallImages) {
                    storedBytes = withContext(ioDispatcher) { splitPages.process(path, settings.features.downloads.splitImageHeight) }
                }
                onBytes(storedBytes)
            }
            status
        }
    }

    /**
     * Streams [url] to [targetPath] through a `.part` file, then writes its `.complete` marker. Exceptions,
     * empty bodies, 408, 429 and 5xx are retried up to [retries] times with backoff (Retry-After when sent);
     * any other status fails at once. Null once saved, else the last HTTP status (0 without a response).
     */
    suspend fun attemptDownload(
        url: String,
        headers: Map<String, String>,
        targetPath: String,
        retries: Int,
        onBytes: (Long) -> Unit,
        transform: ((ByteArray) -> ByteArray?)? = null,
        onTransfer: (Long) -> Unit = {},
        transferService: ResumableDownload = transfers,
        requireImageResponse: Boolean = false,
    ): Int? = withContext(ioDispatcher) {
        val marker = "$targetPath.complete"
        val temporaryPath = "$targetPath.part"
        if (!safeDelete(marker) || files.exists(marker)) return@withContext 0
        var status = 0
        var retryAfter: String? = null
        for (attempt in 0..retries.coerceAtLeast(0)) {
            if (attempt > 0) delay(downloadRetryDelayMs(attempt, retryAfter))
            awaitAllowedNetwork()
            val transfer = transferService.transfer(url, headers, temporaryPath, validateResponse = { head ->
                if (requireImageResponse) check(head.headers.header("Content-Type")?.startsWith("image/", true) == true) { "Optimizer did not return an image" }
            }, onProgress = onTransfer)
            var downloadedBytes = transfer.bytes
            val response = transfer.response
            status = response?.statusCode ?: 0
            retryAfter = response?.headers?.header("Retry-After")
            if (transfer.complete) {
                transform?.let { shrink ->
                    catchingNonCancellation { shrink(files.readBytesAsync(temporaryPath, MaxSplitImageBytes)) }.getOrNull()?.let { smaller ->
                        files.writeBytesAsync(temporaryPath, smaller)
                        downloadedBytes = smaller.size.toLong()
                    }
                }
            }
            if (transfer.complete && promoteWithMarker(temporaryPath, targetPath, marker)) {
                safeDelete("$temporaryPath.resume")
                onTransfer(downloadedBytes)
                onBytes(downloadedBytes)
                return@withContext null
            }
            if (response != null && status !in 200..299 && !isRetryableDownloadStatus(status)) return@withContext status
        }
        status
    }

    /** The marker is only ever written after the page was promoted to its final name. */
    suspend fun promoteWithMarker(temporaryPath: String, targetPath: String, marker: String): Boolean =
        catchingNonCancellation {
            files.promoteAsync(temporaryPath, targetPath) && run {
                files.writeBytesAsync(marker, ByteArray(0))
                true
            }
        }.getOrDefault(false)

    private suspend fun safeDelete(path: String): Boolean = catchingNonCancellation { files.deleteRecursivelyAsync(path) }.getOrDefault(false)
}

internal fun padIndex(index: Int): String = index.toString().padStart(4, '0')

private fun String.fileExtension(): String {
    val extension = substringBefore('?').substringBefore('#').substringAfterLast('/').substringAfterLast('.', "").lowercase()
    return if (extension in PageFileExtensions) ".$extension" else ".jpg"
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/download/PersistentDownloadService.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/download/PersistentDownloadService.kt) · implementation · 935 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
61: class PersistentDownloadService(
90: private data class QueuedDownload(
100: private class PageTally(val total: Int) {
130: override suspend fun initialize(poolSize: Int) = ensureInitialized()
136: private fun ensureInitialized() {
165: override fun enqueue(request: DownloadRequest, onProgress: (DownloadProgress) -> Unit) {
174: private fun queueTask(
252: private fun isAlreadyDownloaded(existing: DbDownload?, location: String): Boolean {
263: override fun cancel(taskId: String) {
276: override fun cancelAll() {
280: override fun pause(taskId: String) {
293: override fun resume(taskId: String) {
306: private fun persistPause(taskId: String, isPaused: Boolean) {
315: override fun retry(taskId: String): Boolean {
325: private fun persistedDownload(taskId: String): DbDownload? {
334: override fun storageLocation(taskId: String): String? {
345: override fun deleteArtifacts(taskId: String) {
355: override suspend fun deleteArtifactsAsync(taskId: String, onDeleted: () -> Unit): Boolean {
362: override suspend fun deleteCompletedArtifacts(taskId: String, stillEligible: () -> Boolean, onDeleted: () -> Unit): Boolean =
365: private suspend fun deleteManagedArtifacts(taskId: String, completedOnly: Boolean, stillEligible: () -> Boolean, onDeleted: () -> Unit): Boolean {
398: private fun isManagedChapterLocation(location: String, type: DbItemType): Boolean {
410: private fun derivedStorageLocations(taskId: String): List<String> {
435: override fun activeDownloads(): List<DownloadProgress> = stateLock.withLock { active.values.toList() }
437: override fun reorderQueue(order: List<Long>) {
445: private fun reorderQueueInternal(order: List<Long>) {
462: private fun processQueue() {
495: private fun isNetworkHeld(): Boolean = database.settings().downloadOnlyOnWifi && !network.unmetered.value
498: private suspend fun awaitAllowedNetwork() {
505: private fun releaseWatcher(): Job = scope.launch(start = CoroutineStart.LAZY) {
512: private fun notifyWaitingForWifi(waiting: Boolean) {
530: private fun worker(task: QueuedDownload): Job {
566: private fun markStopped(taskId: String) {
577: private suspend fun runDownload(task: QueuedDownload) {
637: private suspend fun resolvedPages(chapterId: Long, forceRefresh: Boolean): List<DbPageUrl>? =
649: private suspend fun downloadPages(
688: private suspend fun downloadSubtitles(task: QueuedDownload, tally: PageTally) {
703: private suspend fun finishCompleted(task: QueuedDownload, tally: PageTally) = withContext(NonCancellable) {
729: private fun finishFailed(
762: private fun notify(request: DownloadRequest, title: String, message: String) {
775: private fun setDownloadMark(chapterId: Long, archivePath: String, downloadSize: String?) {
783: private fun shouldArchiveChapter(request: DownloadRequest): Boolean =
787: private fun publishLocked(task: QueuedDownload, tally: PageTally, complete: Boolean = false, force: Boolean = true): DownloadProgress {
810: private fun report(task: QueuedDownload, tally: PageTally, persist: Boolean, complete: Boolean = false) {
818: private fun recordPage(task: QueuedDownload, tally: PageTally, saved: Boolean, bytes: Long = 0L) {
832: private fun persistProgress(task: QueuedDownload, progress: DownloadProgress, complete: Boolean) {
851: private fun publishActiveDownloadsLocked() {
855: private fun resolveStorageLocation(request: DownloadRequest): String {
870: private fun String.chapterIdOrNull(): Long? = removePrefix("chapter-").takeIf { it != this }?.toLongOrNull()
878: internal fun isRetryableDownloadStatus(status: Int): Boolean = status == 408 || status == 429 || status in 500..599
888: internal fun downloadRetryDelayMs(attempt: Int, retryAfter: String?, random: Random = Random.Default): Long {
898: internal fun downloadSizeLabel(bytes: Long): String {
903: internal fun resolveDownloadSourceKey(
927: internal fun downloadStartDelayMs(
```

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

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.download

import eu.friedcutlet.yokan.database.DatabaseJson
import eu.friedcutlet.yokan.database.DbDownload
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbPageUrl
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.database.configuredLocalFolders
import eu.friedcutlet.yokan.services.blockingDispatcher
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.files.LocalArchiveService
import eu.friedcutlet.yokan.services.files.LocalFileService
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.logging.AppLogger
import eu.friedcutlet.yokan.services.notifications.NotificationChannel
import eu.friedcutlet.yokan.services.notifications.NotificationPayload
import eu.friedcutlet.yokan.services.notifications.NotificationService
import eu.friedcutlet.yokan.services.system.NetworkMonitor
import eu.friedcutlet.yokan.services.system.UnmeteredNetwork
import eu.friedcutlet.yokan.util.PlatformLock
import eu.friedcutlet.yokan.util.nowMillis
import kotlin.random.Random
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.withPermit
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
import eu.friedcutlet.yokan.services.files.downloadItemTypeFolder

internal const val DOWNLOAD_CONNECTION_TIMEOUT_MS = 30_000L

internal const val DOWNLOAD_PREPARATION_TIMEOUT_MS = 45_000L

/** Pages of one chapter fetched at once; chapters of one source still download one at a time. */
internal const val PAGE_PARALLELISM = 3

/** Page statuses that mean the URL expired or moved: the chapter's pages are re-resolved once. */
private val ExpiredPageStatuses = setOf(401, 403, 404, 410)

/** Tag of the single "waiting for Wi-Fi" notification, however many chapters wait. */
internal const val WAITING_FOR_WIFI_NOTIFICATION_TAG = "downloads-waiting-for-wifi"

class PersistentDownloadService(
    private val database: YokanDatabase,
    private val http: HttpService,
    private val files: LocalFileService,
    private val archives: LocalArchiveService,
    /** Owner-provided; download workers live and die with it. */
    private val scope: CoroutineScope,
    /** A chapter's pages, resolved when its download starts; `forceRefresh` skips any saved list. */
    private val resolvePages: suspend (chapterId: Long, forceRefresh: Boolean) -> List<DbPageUrl>,
    private val notifications: NotificationService? = null,
    /** With Wi-Fi-only on, the queue waits while this reports a metered network. */
    private val network: NetworkMonitor = UnmeteredNetwork,
    /** Blocking file work: page writes, promotion, metadata and CBZ zipping. */
    private val ioDispatcher: CoroutineDispatcher = blockingDispatcher,
    private val resolveNovelText: (suspend (chapterId: Long) -> String)? = null,
    private val onCompleted: (chapterId: Long) -> Unit = {},
    private val imageDataSaver: ImageDataSaver? = null,
    imageHttp: HttpService = http,
) : DownloadService {
    private val pageTransfer = PageTransfer(database, http, files, imageHttp, imageDataSaver, ioDispatcher, awaitAllowedNetwork = { awaitAllowedNetwork() })
    private val _activeDownloadProgress = MutableStateFlow<List<DownloadProgress>>(emptyList())
    override val activeDownloadProgress = _activeDownloadProgress.asStateFlow()
    private val _queueStatus = MutableStateFlow(DownloadQueueStatus())
    override val queueStatus = _queueStatus.asStateFlow()

    /** True while Wi-Fi-only is on and the network is metered: nothing starts and running chapters wait at their next page. */
    private val networkHeld: Flow<Boolean> =
        combine(network.unmetered, database.snapshots().map { it.settings.downloadOnlyOnWifi }) { unmetered, wifiOnly -> wifiOnly && !unmetered }

    private data class QueuedDownload(
        val request: DownloadRequest,
        val downloadId: Long,
        val onProgress: (DownloadProgress) -> Unit,
        val location: String,
        val sourceKey: String,
        val transferPermits: Semaphore = Semaphore(PAGE_PARALLELISM),
    )

    /** Page counts of one chapter run; mutated only under [stateLock]. */
    private class PageTally(val total: Int) {
        var succeeded = 0
        var failed = 0
        var bytes = 0L
        val inFlightBytes = mutableMapOf<Int, Long>()
        var lastProgressAt = 0L
    }

    private val stateLock = PlatformLock()
    private val queue = ArrayDeque<QueuedDownload>()
    private val jobs = mutableMapOf<String, Job>()
    private val active = mutableMapOf<String, DownloadProgress>()
    /** Download row per task, indexed once at start so [enqueue] never scans every row. */
    private val taskDownloadIds = mutableMapOf<String, Long>()
    /** Known or derived file locations; a null value caches "no files found". */
    // ponytail: files removed outside the app keep their cached location until restart.
    private val taskStorageLocations = mutableMapOf<String, String?>()
    /** Running tasks the user cancelled; their row is marked stopped once the worker has ended. */
    private val cancelled = mutableSetOf<String>()
    private val paused = mutableSetOf<String>()
    /** Running tasks stopped by [pause]; they return to the front of the queue once the worker has ended. */
    private val requeueOnStop = mutableSetOf<String>()
    private val lastRequests = mutableMapOf<String, DownloadRequest>()
    private val activeSources = mutableSetOf<String>()
    private val deleting = mutableSetOf<String>()
    private val admitting = mutableSetOf<String>()
    private var running = 0
    private var initialized = false
    private var manualQueueOrder: List<Long> = emptyList()

    override suspend fun initialize(poolSize: Int) = ensureInitialized()

    /**
     * Indexes the download rows once and re-queues the ones a previous session left started; rows that
     * can't be rebuilt (chapter gone) become retryable instead.
     */
    private fun ensureInitialized() {
        val interrupted = stateLock.withLock {
            if (initialized) return@withLock emptyList<DbDownload>()
            initialized = true
            database.downloads().filter { download ->
                taskDownloadIds[downloadTaskId(download.chapterId, download.id)] = download.id
                download.isStartDownload == true && download.isDownload != true
            }
        }
        interrupted.forEach { download ->
            val request = download.requestJson?.let { json ->
                runCatching { DatabaseJson.decodeFromString<DownloadRequest>(json) }.getOrNull()
                    ?.takeIf { it.chapterId == download.chapterId }
            } ?: download.chapterId?.let { chapterDownloadRequest(database, it) }
            val queued = request != null && runCatching { queueTask(request, onProgress = {}, knownLocation = download.storageLocation ?: storageLocation(request.taskId), initiallyPaused = download.isPaused, deferStart = true) }
                .onFailure { AppLogger.warn("[download] could not resume ${request.taskId}: ${it.message.orEmpty()}") }
                .getOrDefault(false)
            if (!queued) database.batch {
                val chapterId = download.chapterId ?: return@batch
                val chapter = database.chapter(chapterId) ?: return@batch
                if (chapter.mangaId?.let(database::manga) == null) return@batch
                database.download(download.id)?.let { current ->
                    database.upsertDownload(current.copy(isStartDownload = false, isPaused = false))
                }
            }
        }
        if (interrupted.isNotEmpty()) processQueue()
    }

    override fun enqueue(request: DownloadRequest, onProgress: (DownloadProgress) -> Unit) {
        queueTask(request, onProgress, knownLocation = null)
    }

    /**
     * Records and queues [request] before returning, so the queue keeps call order; with Wi-Fi-only on a
     * metered network it waits in the queue. False when it was skipped: already queued or running, or
     * already downloaded.
     */
    private fun queueTask(
        request: DownloadRequest,
        onProgress: (DownloadProgress) -> Unit,
        knownLocation: String?,
        initiallyPaused: Boolean = false,
        deferStart: Boolean = false,
    ): Boolean {
        ensureInitialized()
        val taskId = request.taskId.ifBlank { downloadTaskId(request.chapterId, 0) }
        val location = knownLocation ?: resolveStorageLocation(request)
        // SAF tree grants are read-only here (AndroidSafLocalFileService), so every page would fail.
        require(!location.startsWith("content://")) {
            "Downloads can't be saved to a folder picked through the system file picker. Choose another download folder in settings."
        }
        val admitted = stateLock.withLock {
            if (taskId in admitting || taskId in deleting || taskId in jobs || queue.any { it.request.taskId == taskId }) false
            else { admitting += taskId; true }
        }
        if (!admitted) return false
        try {
        val validated = database.batch {
            val chapter = database.chapter(request.chapterId) ?: return@batch null
            val manga = chapter.mangaId?.let(database::manga) ?: return@batch null
            val sourceIds = listOfNotNull(manga.sourceId, request.sourceId?.takeIf { it > 0L }).distinct()
            if (sourceIds.any { database.source(it) == null }) return@batch null
            val existing = database.downloads().firstOrNull { it.chapterId == chapter.id }
            existing to Unit
        } ?: return false
        if (isAlreadyDownloaded(validated.first, location)) return false
        val admission = database.batch {
            val chapter = database.chapter(request.chapterId) ?: return@batch null
            val manga = chapter.mangaId?.let(database::manga) ?: return@batch null
            val sourceIds = listOfNotNull(manga.sourceId, request.sourceId?.takeIf { it > 0L }).distinct()
            if (sourceIds.any { database.source(it) == null }) return@batch null
            val existing = database.downloads().firstOrNull { it.chapterId == chapter.id }
            val row = database.upsertDownload(
                DbDownload(
                    id = existing?.id ?: 0,
                    chapterId = chapter.id,
                    succeeded = 0,
                    failed = 0,
                    total = existing?.total,
                    isDownload = false,
                    isStartDownload = true,
                    isPaused = initiallyPaused,
                    storageLocation = location,
                    requestJson = DatabaseJson.encodeToString(request.copy(taskId = taskId)),
                ),
            )
            row
        } ?: return false
        val normalized = request.copy(taskId = taskId)
        val download = admission
        val task = QueuedDownload(normalized, download.id, onProgress, location, resolveDownloadSourceKey(normalized, download.id, database))
        val registered = stateLock.withLock {
            if (taskId in deleting || taskId in jobs || queue.any { it.request.taskId == taskId }) return@withLock false
            taskDownloadIds[taskId] = download.id
            taskStorageLocations[taskId] = location
            lastRequests[taskId] = normalized
            if (initiallyPaused) {
                paused += taskId
                active[taskId] = DownloadProgress(taskId, 0, 0, download.total ?: 0,
                    request.itemType, isPaused = true, storageLocation = location)
                publishActiveDownloadsLocked()
            } else paused.remove(taskId)
            queue += task
            true
        }
        if (!registered) return false
        if (!deferStart) processQueue()
        return true
        } finally { stateLock.withLock { admitting.remove(taskId) } }
    }

    /**
     * True when [existing] finished and its files are still there; its chapter is re-marked in case the mark
     * was cleared (e.g. by a backup restore). A finished row whose files are gone loses its stale mark.
     */
    private fun isAlreadyDownloaded(existing: DbDownload?, location: String): Boolean {
        if (existing?.isDownload != true) return false
        val chapter = existing.chapterId?.let(database::chapter) ?: return false
        val path = listOf(chapter.archivePath, location, "$location.cbz").firstOrNull { it.isNotBlank() && files.exists(it) }
        when {
            path == null -> if (chapter.archivePath.isNotBlank() || chapter.downloadSize != null) setDownloadMark(chapter.id, "", null)
            chapter.archivePath.isBlank() -> setDownloadMark(chapter.id, path, downloadSizeLabel(files.directorySize(path)))
        }
        return path != null
    }

    override fun cancel(taskId: String) {
        val job = stateLock.withLock {
            queue.removeAll { it.request.taskId == taskId }
            paused.remove(taskId)
            requeueOnStop.remove(taskId)
            active.remove(taskId)
            publishActiveDownloadsLocked()
            jobs[taskId]?.also { cancelled += taskId }
        }
        if (job != null) job.cancel() else markStopped(taskId)
        processQueue()
    }

    override fun cancelAll() {
        stateLock.withLock { queue.map { it.request.taskId } + jobs.keys }.forEach(::cancel)
    }

    override fun pause(taskId: String) {
        val job = stateLock.withLock {
            paused += taskId
            active[taskId]?.let { active[taskId] = it.copy(isPaused = true) }
            publishActiveDownloadsLocked()
            jobs[taskId]?.also { requeueOnStop += taskId }
        }
        persistPause(taskId, true)
        // Saved pages keep their markers, so the run after resume only fetches the rest.
        job?.cancel()
        processQueue()
    }

    override fun resume(taskId: String) {
        val resumed = stateLock.withLock {
            paused.remove(taskId).also { wasPaused ->
                if (wasPaused) active[taskId]?.let { active[taskId] = it.copy(isPaused = false) }
                publishActiveDownloadsLocked()
            }
        }
        if (resumed) {
            persistPause(taskId, false)
            processQueue()
        }
    }

    private fun persistPause(taskId: String, isPaused: Boolean) {
        val id = stateLock.withLock { taskDownloadIds[taskId] } ?: return
        database.batch {
            database.download(id)?.takeIf { it.isDownload != true }?.let { row ->
                database.upsertDownload(row.copy(isPaused = isPaused))
            }
        }
    }

    override fun retry(taskId: String): Boolean {
        val request = stateLock.withLock { lastRequests[taskId] }
            ?: persistedDownload(taskId)?.requestJson?.let {
                runCatching { DatabaseJson.decodeFromString<DownloadRequest>(it) }.getOrNull()
            }
            ?: taskId.chapterIdOrNull()?.let { chapterDownloadRequest(database, it) }
            ?: return false
        return queueTask(request, onProgress = {}, knownLocation = storageLocation(taskId))
    }

    private fun persistedDownload(taskId: String): DbDownload? {
        stateLock.withLock { taskDownloadIds[taskId] }?.let(database::download)?.let { return it }
        return database.downloads().firstOrNull { row ->
            downloadTaskId(row.chapterId, row.id) == taskId || row.requestJson?.let { json ->
                runCatching { DatabaseJson.decodeFromString<DownloadRequest>(json).taskId == taskId }.getOrDefault(false)
            } == true
        }
    }

    override fun storageLocation(taskId: String): String? {
        stateLock.withLock { taskStorageLocations.containsKey(taskId) to taskStorageLocations[taskId] }
            .let { (known, location) -> if (known) return location }
        val persisted = persistedDownload(taskId)?.storageLocation
        if (!persisted.isNullOrBlank()) return persisted
        val found = derivedStorageLocations(taskId).firstOrNull { files.exists(it) || files.exists("$it.cbz") }
        return stateLock.withLock {
            if (taskId in taskStorageLocations) taskStorageLocations[taskId] else found.also { taskStorageLocations[taskId] = it }
        }
    }

    override fun deleteArtifacts(taskId: String) {
        val known = stateLock.withLock { taskStorageLocations.remove(taskId) }
        val locations = known?.let(::listOf) ?: derivedStorageLocations(taskId)
        locations.filter { it.isNotBlank() }.forEach { location ->
            files.deleteRecursively(location)
            files.deleteRecursively("$location.cbz")
            files.deleteRecursively("${location}_subtitles")
        }
    }

    override suspend fun deleteArtifactsAsync(taskId: String, onDeleted: () -> Unit): Boolean {
        val worker = stateLock.withLock { jobs[taskId] }
        cancel(taskId)
        worker?.join()
        return deleteManagedArtifacts(taskId, completedOnly = false, stillEligible = { true }, onDeleted)
    }

    override suspend fun deleteCompletedArtifacts(taskId: String, stillEligible: () -> Boolean, onDeleted: () -> Unit): Boolean =
        deleteManagedArtifacts(taskId, completedOnly = true, stillEligible, onDeleted)

    private suspend fun deleteManagedArtifacts(taskId: String, completedOnly: Boolean, stillEligible: () -> Boolean, onDeleted: () -> Unit): Boolean {
        val accepted = stateLock.withLock {
            if (taskId in admitting || taskId in deleting || taskId in jobs || queue.any { it.request.taskId == taskId }) false
            else { deleting += taskId; true }
        }
        if (!accepted) return false
        return try { withContext(ioDispatcher) {
            files.prepare()
            val row = persistedDownload(taskId)
            if (row == null) return@withContext false
            if ((completedOnly && (row.isDownload != true || row.isPaused || row.isStartDownload == true)) || !stillEligible()) return@withContext false
            val locations = listOfNotNull(storageLocation(taskId)).ifEmpty { derivedStorageLocations(taskId) }.distinct()
            val chapter = taskId.chapterIdOrNull()?.let(database::chapter) ?: return@withContext false
            val title = chapter.mangaId?.let(database::manga) ?: return@withContext false
            if ((completedOnly && title.isLocalArchive) || locations.isEmpty() || locations.any { !isManagedChapterLocation(it, title.itemType) }) return@withContext false
            val paths = locations.flatMap { listOf(it, "$it.cbz", "${it}_subtitles") }
            for (path in paths) {
                ensureActive()
                if (!stillEligible()) return@withContext false
                val parent = files.canonicalPath(path.substringBeforeLast('/')) ?: return@withContext false
                val canonical = files.canonicalPath(path) ?: return@withContext false
                if (canonical.replace('\\', '/').trimEnd('/') != "${parent.replace('\\', '/').trimEnd('/')}/${path.substringAfterLast('/')}") return@withContext false
                if (files.exists(path) && (!files.deleteRecursivelyAsync(path) || files.exists(path))) return@withContext false
            }
            stateLock.withLock { taskStorageLocations.remove(taskId) }
            // Keep the task reservation through the database commit; a retry cannot recreate files
            // between deletion and clearing the old download row.
            onDeleted()
            true
        } } finally { stateLock.withLock { deleting.remove(taskId) } }
    }

    /** Refuse root/title folders and traversal even if an imported manifest has a bad path. */
    private fun isManagedChapterLocation(location: String, type: DbItemType): Boolean {
        val path = location.replace('\\', '/').trimEnd('/')
        val segments = path.split('/')
        val marker = segments.indexOfLast { it == downloadItemTypeFolder(type) }
        return marker >= 0 && segments.size - marker == 4 &&
            segments.none { it == "." || it == ".." } && segments.takeLast(3).none { it.isBlank() }
    }

    /**
     * Where a chapter download from an earlier session lives: the chapter's recorded download path, then the
     * folder [enqueue] would build from its chapter and title rows under every root a download may target.
     */
    private fun derivedStorageLocations(taskId: String): List<String> {
        val chapterId = taskId.chapterIdOrNull() ?: return emptyList()
        val chapter = database.chapter(chapterId) ?: return emptyList()
        val manga = chapter.mangaId?.let(database::manga) ?: return emptyList()
        val source = manga.sourceId?.let(database::source)
        val sourceLabel = downloadSourceLabel(source?.name, source?.lang, manga.source.orEmpty())
        val settings = database.settings()
        // ponytail: a one-off destinationRoot outside these roots is only known in-session (taskStorageLocations).
        val roots = settings.configuredLocalFolders().map { it.path } + settings.downloadLocation + files.downloadRoot
        val recorded = chapter.archivePath.takeIf { it.isNotBlank() && !manga.isLocalArchive }?.removeSuffix(".cbz")
        return listOfNotNull(recorded) + roots.filter { it.isNotBlank() }
            .map { downloadStorageRoot(it, files) }
            .distinct()
            .map { root ->
                downloadChapterLocation(
                    root,
                    manga.itemType,
                    sourceLabel,
                    manga.name.orEmpty(),
                    chapter.scanlator,
                    chapter.name.orEmpty(),
                )
            }
    }

    override fun activeDownloads(): List<DownloadProgress> = stateLock.withLock { active.values.toList() }

    override fun reorderQueue(order: List<Long>) {
        stateLock.withLock {
            manualQueueOrder = order
            reorderQueueInternal(order)
        }
        processQueue()
    }

    private fun reorderQueueInternal(order: List<Long>) {
        if (order.isEmpty() || queue.size < 2) return
        val rank = order.withIndex().associate { it.value to it.index }
        val indexed = queue.withIndex().toList()
        val sorted = indexed.sortedWith { a, b ->
            val ra = rank[a.value.downloadId] ?: (order.size + a.index)
            val rb = rank[b.value.downloadId] ?: (order.size + b.index)
            ra.compareTo(rb)
        }.map { it.value }
        queue.clear()
        queue.addAll(sorted)
    }

    /**
     * Starts queued chapters up to the concurrency limit, unless the network is held, and publishes
     * [queueStatus]. Once work waits for Wi-Fi, one notification shows and a watcher resumes the queue.
     */
    private fun processQueue() {
        val toStart = stateLock.withLock {
            val settings = database.settings()
            val effectiveOrder = if (manualQueueOrder.isNotEmpty()) manualQueueOrder else settings.downloadQueueOrder
            reorderQueueInternal(effectiveOrder)
            val maxConcurrent = if (settings.allowConcurrentDownloads) {
                settings.concurrentDownloads.coerceAtLeast(1)
            } else {
                1
            }
            val held = isNetworkHeld()
            buildList {
                while (!held && running < maxConcurrent) {
                    val index = queue.indexOfFirst { it.request.taskId !in paused && it.sourceKey !in activeSources }
                    if (index < 0) break
                    val task = queue.removeAt(index)
                    activeSources += task.sourceKey
                    running += 1
                    add(worker(task).also { jobs[task.request.taskId] = it })
                }
                val pending = running + queue.count { it.request.taskId !in paused }
                val status = DownloadQueueStatus(pending, waitingForWifi = held && pending > 0)
                // Under the lock, so the notification always matches the last published status.
                if (status.waitingForWifi != _queueStatus.value.waitingForWifi) {
                    notifyWaitingForWifi(status.waitingForWifi)
                    if (status.waitingForWifi) add(releaseWatcher())
                }
                _queueStatus.value = status
            }
        }
        toStart.forEach(Job::start)
    }

    private fun isNetworkHeld(): Boolean = database.settings().downloadOnlyOnWifi && !network.unmetered.value

    /** Waits while the network is held, so a running chapter stops at its next page and continues on Wi-Fi. */
    private suspend fun awaitAllowedNetwork() {
        if (!isNetworkHeld()) return
        processQueue() // Publishes the wait: the screen label, the notification and the release watcher.
        networkHeld.first { !it }
    }

    /** Resumes the queue once Wi-Fi returns or Wi-Fi-only is turned off; ends when nothing waits any more. */
    private fun releaseWatcher(): Job = scope.launch(start = CoroutineStart.LAZY) {
        while (_queueStatus.value.waitingForWifi) {
            networkHeld.first { !it }
            processQueue()
        }
    }

    private fun notifyWaitingForWifi(waiting: Boolean) {
        runCatching {
            if (waiting) {
                notifications?.notify(
                    NotificationPayload(
                        channel = NotificationChannel.Downloads,
                        title = "Downloads waiting for Wi-Fi",
                        message = "They continue on Wi-Fi. Turn off Only on Wi-Fi in download settings to use mobile data.",
                        tag = WAITING_FOR_WIFI_NOTIFICATION_TAG,
                    ),
                )
            } else {
                notifications?.cancel(NotificationChannel.Downloads, WAITING_FOR_WIFI_NOTIFICATION_TAG)
            }
        }
    }

    /** The task's worker, created lazily so it is registered in [jobs] before it can run or finish. */
    private fun worker(task: QueuedDownload): Job {
        val taskId = task.request.taskId
        return scope.launch(start = CoroutineStart.LAZY) {
            try {
                runDownload(task)
            } catch (stop: CancellationException) {
                // A stray timeout from deeper code is a failure; only a stopped worker ends silently.
                if (!isActive) throw stop
                AppLogger.error("[download] $taskId failed: ${stop.message.orEmpty()}")
                finishFailed(task, PageTally(0))
            } catch (error: Throwable) {
                AppLogger.error("[download] $taskId failed: ${error.message.orEmpty()}")
                finishFailed(task, PageTally(0))
            } finally {
                // A pause that lands while the chapter is being finished must not queue it again.
                val finished = database.download(task.downloadId)?.isDownload == true
                val userCancelled = stateLock.withLock {
                    jobs.remove(taskId)
                    running = (running - 1).coerceAtLeast(0)
                    activeSources.remove(task.sourceKey)
                    if (requeueOnStop.remove(taskId) && !finished) {
                        queue.addFirst(task)
                        false
                    } else {
                        active.remove(taskId)
                        publishActiveDownloadsLocked()
                        cancelled.remove(taskId)
                    }
                }
                // Written after the worker has stopped so no late progress write can mark the row started again.
                if (userCancelled) markStopped(taskId)
                processQueue()
            }
        }
    }

    private fun markStopped(taskId: String) {
        val downloadId = stateLock.withLock { taskDownloadIds[taskId] } ?: return
        database.batch {
            val download = database.download(downloadId) ?: return@batch
            val chapterId = download.chapterId ?: return@batch
            val chapter = database.chapter(chapterId) ?: return@batch
            if (chapter.mangaId?.let(database::manga) == null) return@batch
            database.upsertDownload(download.copy(isStartDownload = false, isPaused = false))
        }
    }

    private suspend fun runDownload(task: QueuedDownload) {
        files.prepare()
        val request = task.request
        val delayMs = downloadStartDelayMs(database.settings().downloadDelaySeconds)
        if (delayMs > 0L) delay(delayMs)
        report(task, PageTally(0), persist = false)
        if (request.itemType == DbItemType.Novel && resolveNovelText != null) {
            val text = catchingNonCancellation {
                withTimeoutOrNull(DOWNLOAD_PREPARATION_TIMEOUT_MS) { resolveNovelText.invoke(request.chapterId) }
                    ?.takeIf(String::isNotBlank) ?: error("No novel text resolved")
            }.getOrElse { return finishFailed(task, PageTally(1), "Failed loading novel text") }
            val target = "${task.location}/0001.html"
            withContext(ioDispatcher) {
                val partial = "$target.part"
                files.writeBytesAsync(partial, text.encodeToByteArray())
                check(pageTransfer.promoteWithMarker(partial, target, "$target.complete")) { "Cannot save novel text" }
            }
            val tally = PageTally(1).apply { succeeded = 1; bytes = text.encodeToByteArray().size.toLong() }
            return finishCompleted(task, tally)
        }
        var pages = resolvedPages(request.chapterId, forceRefresh = false)
            ?: run {
                AppLogger.warn("[download] ${request.taskId} failed: no pages resolved")
                return finishFailed(task, PageTally(0), "Failed loading pages for ${request.chapterName.ifBlank { "chapter" }}")
            }
        var refreshed = false
        var tally = PageTally(pages.size)
        while (true) {
            report(task, tally, persist = true)
            val splitHeight = database.settings().features.downloads.takeIf { request.itemType == DbItemType.Manga && it.splitTallImages }?.splitImageHeight
            val saved = withContext(ioDispatcher) { pageTransfer.savedPages(task.location, pages.size, splitHeight) }
            val expired = downloadPages(task, tally, pages, pages.indices, saved, countExpired = refreshed)
            if (expired.isEmpty()) break
            refreshed = true
            val fresh = resolvedPages(request.chapterId, forceRefresh = true)
            when {
                fresh == null -> expired.forEach { recordPage(task, tally, saved = false) }
                // The chapter changed: start over. Saved pages are kept by index, extra indices are dropped.
                // ponytail: a source that inserts a page mid-chapter shifts the kept ones; clear all markers if that shows up.
                fresh.size != pages.size -> {
                    pages = fresh
                    tally = PageTally(fresh.size)
                    continue
                }
                else -> {
                    pages = fresh
                    downloadPages(task, tally, pages, expired, emptyMap(), countExpired = true)
                }
            }
            break
        }
        downloadSubtitles(task, tally)
        if (tally.failed > 0 || tally.succeeded < tally.total) {
            AppLogger.warn("[download] ${request.taskId} failed: ${tally.succeeded}/${tally.total} pages saved, ${tally.failed} failed")
            return finishFailed(task, tally)
        }
        finishCompleted(task, tally)
    }

    /** The chapter's pages, else null (logged) when they can't be resolved or there are none. */
    private suspend fun resolvedPages(chapterId: Long, forceRefresh: Boolean): List<DbPageUrl>? =
        catchingNonCancellation {
            withTimeoutOrNull(DOWNLOAD_PREPARATION_TIMEOUT_MS) { resolvePages(chapterId, forceRefresh) }
                ?: error("Timed out loading pages")
        }.onFailure { AppLogger.warn("[download] resolving pages of chapter $chapterId failed: ${it.message.orEmpty()}") }
            .getOrNull()
            ?.takeIf { it.isNotEmpty() }

    /**
     * Downloads [indices] of [pages], [PAGE_PARALLELISM] at a time, counting pages found in [saved] without
     * fetching them. Returns the indices whose URL looked expired, uncounted, unless [countExpired].
     */
    private suspend fun downloadPages(
        task: QueuedDownload,
        tally: PageTally,
        pages: List<DbPageUrl>,
        indices: Iterable<Int>,
        saved: Map<Int, Long>,
        countExpired: Boolean,
    ): List<Int> {
        val permits = Semaphore(PAGE_PARALLELISM)
        val expired = mutableListOf<Int>()
        coroutineScope {
            indices.forEach { index ->
                launch {
                    permits.withPermit {
                        saved[index]?.let { size -> return@withPermit recordPage(task, tally, saved = true, bytes = size) }
                        var bytes = 0L
                        val status = pageTransfer.downloadPage(task.request, task.location, task.transferPermits, pages[index], index, onBytes = { bytes += it }, onTransfer = { current ->
                            stateLock.withLock {
                                tally.inFlightBytes[index] = current
                                val now = nowMillis()
                                if (now - tally.lastProgressAt >= 200) {
                                    tally.lastProgressAt = now
                                    publishLocked(task, tally)
                                }
                            }
                        })
                        stateLock.withLock { tally.inFlightBytes.remove(index) }
                        when {
                            status == null -> recordPage(task, tally, saved = true, bytes = bytes)
                            status in ExpiredPageStatuses && !countExpired -> stateLock.withLock { expired += index }
                            else -> recordPage(task, tally, saved = false)
                        }
                    }
                }
            }
        }
        return expired.sorted()
    }

    private suspend fun downloadSubtitles(task: QueuedDownload, tally: PageTally) {
        task.request.subtitles.forEachIndexed { index, sub ->
            if (sub.file.isBlank()) return@forEachIndexed
            val subtitlePath = "${task.location}_subtitles/${index.toString().padStart(2, '0')}_${sub.label.ifBlank { "subtitle" }}.${sub.file.substringAfterLast('.', "srt").lowercase()}"
            catchingNonCancellation {
                val response = withTimeoutOrNull(DOWNLOAD_CONNECTION_TIMEOUT_MS) { http.request(HttpRequest(url = sub.file)) }
                if (response != null && response.statusCode in 200..299 && response.bodyBytes.isNotEmpty()) {
                    withContext(ioDispatcher) { files.writeBytesAsync(subtitlePath, response.bodyBytes) }
                    stateLock.withLock { tally.bytes += response.bodyBytes.size }
                }
            }
        }
    }

    /** Not cancellable: once the pages are in, a pause or cancel can't leave a zipped chapter unmarked. */
    private suspend fun finishCompleted(task: QueuedDownload, tally: PageTally) = withContext(NonCancellable) {
        val request = task.request
        val archive = withContext(ioDispatcher) {
            writeMetadata(files, request, task.location)
            writeTitleMetadata(files, http, request, task.location.substringBeforeLast('/', task.location))
            if (!shouldArchiveChapter(request)) return@withContext null
            runCatching { archives.zipDirectoryToCbzAsync(task.location, deleteSource = true) }
                .onSuccess { path -> path?.let { AppLogger.info("[download] CBZ created for ${request.mangaName} chapter ${request.chapterName}: $it") } }
                .onFailure { AppLogger.warn("[download] CBZ failed for ${request.taskId}, keeping the folder: ${it.message.orEmpty()}") }
                .getOrNull()
        }
        files.awaitPersistence()
        // The reader and chapter list read this mark; deleting the download clears it (clearChapterDownloads).
        // The mark stays on this device: sync and backup restore treat it as device-local (SyncPaths, BackupService).
        setDownloadMark(request.chapterId, archive ?: task.location, downloadSizeLabel(tally.bytes))
        report(task, tally, persist = true, complete = true)
        AppLogger.info("[download] ${request.taskId} completed: ${tally.succeeded} pages, ${downloadSizeLabel(tally.bytes)}")
        notify(request, request.mangaName.ifBlank { "Download finished" }, "${request.chapterName.ifBlank { "Chapter" }} • ${tally.succeeded} pages")
        stateLock.withLock {
            active.remove(request.taskId)
            lastRequests.remove(request.taskId)
            publishActiveDownloadsLocked()
        }
        onCompleted(request.chapterId)
    }

    private fun finishFailed(
        task: QueuedDownload,
        tally: PageTally,
        message: String = "Failed downloading ${task.request.chapterName.ifBlank { "chapter" }}",
    ) {
        val progress = stateLock.withLock {
            tally.failed = tally.failed.coerceAtLeast(1)
            publishLocked(task, tally)
        }
        database.batch {
            val chapter = database.chapter(task.request.chapterId) ?: return@batch
            if (chapter.mangaId?.let(database::manga) == null) return@batch
            database.download(task.downloadId)?.let { download ->
                database.upsertDownload(
                    download.copy(
                        succeeded = progress.succeeded,
                        failed = progress.failed,
                        total = progress.total,
                        isDownload = false,
                        isStartDownload = false,
                    ),
                )
            }
        }
        runCatching { task.onProgress(progress) }
            .onFailure { AppLogger.warn("Download progress callback failed: ${it.message.orEmpty()}") }
        notify(task.request, task.request.mangaName.ifBlank { "Download failed" }, message)
        stateLock.withLock {
            active.remove(task.request.taskId)
            publishActiveDownloadsLocked()
        }
    }

    private fun notify(request: DownloadRequest, title: String, message: String) {
        runCatching {
            notifications?.notify(
                NotificationPayload(
                    channel = NotificationChannel.Downloads,
                    title = title,
                    message = message,
                    tag = request.taskId,
                ),
            )
        }
    }

    private fun setDownloadMark(chapterId: Long, archivePath: String, downloadSize: String?) {
        database.batch {
            val chapter = database.chapter(chapterId) ?: return@batch
            if (chapter.mangaId?.let(database::manga) == null) return@batch
            database.upsertChapter(chapter.copy(archivePath = archivePath, downloadSize = downloadSize, updatedAt = nowMillis()))
        }
    }

    private fun shouldArchiveChapter(request: DownloadRequest): Boolean =
        request.itemType == DbItemType.Manga && database.settings().saveAsCBZArchive

    /** Publishes [tally] as the task's live progress; the caller holds [stateLock]. */
    private fun publishLocked(task: QueuedDownload, tally: PageTally, complete: Boolean = false, force: Boolean = true): DownloadProgress {
        val progress = DownloadProgress(
            taskId = task.request.taskId,
            succeeded = tally.succeeded,
            failed = tally.failed,
            total = tally.total,
            itemType = task.request.itemType,
            isCompleted = complete || (tally.total > 0 && tally.succeeded + tally.failed >= tally.total),
            isPaused = task.request.taskId in paused,
            storageLocation = task.location,
            bytesDownloaded = tally.bytes + tally.inFlightBytes.values.sum(),
            mangaName = task.request.mangaName,
            chapterName = task.request.chapterName,
        )
        active[task.request.taskId] = progress
        val now = nowMillis()
        if (force || progress.isCompleted || now - tally.lastProgressAt >= 200) {
            tally.lastProgressAt = now
            publishActiveDownloadsLocked()
        }
        return progress
    }

    private fun report(task: QueuedDownload, tally: PageTally, persist: Boolean, complete: Boolean = false) {
        val progress = stateLock.withLock { publishLocked(task, tally, complete) }
        if (persist) persistProgress(task, progress, complete)
        runCatching { task.onProgress(progress) }
            .onFailure { AppLogger.warn("Download progress callback failed: ${it.message.orEmpty()}") }
    }

    /** Counts one page; the row is written on the persist interval and on the chapter's first failure. */
    private fun recordPage(task: QueuedDownload, tally: PageTally, saved: Boolean, bytes: Long = 0L) {
        val progress = stateLock.withLock {
            if (saved) tally.succeeded += 1 else tally.failed += 1
            tally.bytes += bytes
            publishLocked(task, tally, force = !saved)
        }
        val processed = progress.succeeded + progress.failed
        if (processed % PROGRESS_PERSIST_INTERVAL == 0 || (!saved && progress.failed == 1)) {
            persistProgress(task, progress, complete = false)
        }
        runCatching { task.onProgress(progress) }
            .onFailure { AppLogger.warn("Download progress callback failed: ${it.message.orEmpty()}") }
    }

    private fun persistProgress(task: QueuedDownload, progress: DownloadProgress, complete: Boolean) {
        database.batch {
            val chapter = database.chapter(task.request.chapterId) ?: return@batch
            if (chapter.mangaId?.let(database::manga) == null) return@batch
            database.download(task.downloadId)?.let { download ->
                database.upsertDownload(
                    download.copy(
                        succeeded = progress.succeeded,
                        failed = progress.failed,
                        total = progress.total,
                        isDownload = complete,
                        isStartDownload = !progress.isCompleted,
                        isPaused = !complete && download.isPaused,
                    ),
                )
            }
        }
    }

    private fun publishActiveDownloadsLocked() {
        _activeDownloadProgress.update { active.values.sortedBy(DownloadProgress::taskId) }
    }

    private fun resolveStorageLocation(request: DownloadRequest): String {
        val customRoot = request.destinationRoot
            ?.takeIf { it.isNotBlank() }
            ?: database.settings().downloadLocation.takeIf { it.isNotBlank() }
            ?: files.downloadRoot
        return downloadChapterLocation(
            downloadStorageRoot(customRoot, files),
            request.itemType,
            request.sourceLabel,
            request.mangaName,
            request.scanlator,
            request.chapterName,
        )
    }

    private fun String.chapterIdOrNull(): Long? = removePrefix("chapter-").takeIf { it != this }?.toLongOrNull()

    private companion object {
        const val PROGRESS_PERSIST_INTERVAL = 5
    }
}

/** Transient statuses worth retrying; any other 4xx fails at once. */
internal fun isRetryableDownloadStatus(status: Int): Boolean = status == 408 || status == 429 || status in 500..599

private const val RETRY_BASE_DELAY_MS = 1_000L

private const val MAX_RETRY_AFTER_MS = 60_000L

/**
 * Wait before retry [attempt] (1-based): the server's Retry-After seconds when sent (capped at a minute),
 * else exponential backoff from one second with equal jitter.
 */
internal fun downloadRetryDelayMs(attempt: Int, retryAfter: String?, random: Random = Random.Default): Long {
    // ponytail: an HTTP-date Retry-After falls back to backoff; parse it if a CDN sends one.
    retryAfter?.trim()?.toLongOrNull()?.let { seconds -> return (seconds * 1_000L).coerceIn(0L, MAX_RETRY_AFTER_MS) }
    val base = RETRY_BASE_DELAY_MS shl (attempt - 1).coerceIn(0, 6)
    return base / 2 + random.nextLong(base / 2 + 1)
}

private const val BYTES_PER_MIB = 1_048_576L

/** Size shown next to a downloaded chapter, e.g. `12.3 MB`. */
internal fun downloadSizeLabel(bytes: Long): String {
    val tenths = (bytes.coerceAtLeast(0L) * 10 + BYTES_PER_MIB / 2) / BYTES_PER_MIB
    return "${tenths / 10}.${tenths % 10} MB"
}

internal fun resolveDownloadSourceKey(
    request: DownloadRequest,
    downloadId: Long = 0L,
    database: YokanDatabase? = null,
): String {
    if (request.sourceId != null && request.sourceId > 0L) {
        return "source-${request.sourceId}"
    }
    if (database != null && request.chapterId > 0L) {
        val chapter = database.chapter(request.chapterId)
        val manga = chapter?.mangaId?.let { database.manga(it) }
        if (manga != null) {
            val sId = manga.sourceId
            val source = manga.source
            if (sId != null && sId > 0L) return "source-$sId"
            if (!source.isNullOrBlank()) return "source-${source.trim()}|${manga.lang.orEmpty()}"
        }
    }
    if (request.sourceLabel.isNotBlank()) {
        return "source-${request.sourceLabel.trim()}"
    }
    return if (downloadId > 0L) "download-$downloadId" else request.taskId.ifBlank { "download-${request.chapterId}" }
}

internal fun downloadStartDelayMs(
    baseSeconds: Int,
    random: kotlin.random.Random = kotlin.random.Random.Default,
): Long {
    if (baseSeconds <= 0) return 0L
    val base = baseSeconds * 1000L
    val jitter = (base * (0.25 + random.nextDouble() * 0.75)).toLong()
    return base + jitter
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/download/ProfileDownloadBindings.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/download/ProfileDownloadBindings.kt) · implementation · 62 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 class ProfileDownloadBindings {
19: fun install(id: ProfileId, downloads: DownloadService, ownerScope: CoroutineScope, hideContent: () -> Boolean = { false }): Binding {
31: fun resolve(owner: String?, token: String?): Binding? {
37: class Binding internal constructor(
50: fun cancelAll() { scope.launch { downloads.cancelAll() } }
51: fun retire() { job.cancel() }
53: suspend fun run(action: suspend (DownloadService) -> Unit): ProfileWorkResult<Unit> {
```

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

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.download

import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.services.runJoined
import eu.friedcutlet.yokan.services.scheduling.ProfileWorkResult
import eu.friedcutlet.yokan.util.PlatformLock
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.launch

/** Process-local capabilities. Notification actions never bootstrap or reopen a profile. */
internal class ProfileDownloadBindings {
    private val lock = PlatformLock()
    private val bindings = mutableMapOf<ProfileId, Binding>()

    fun install(id: ProfileId, downloads: DownloadService, ownerScope: CoroutineScope, hideContent: () -> Boolean = { false }): Binding {
        val parent = requireNotNull(ownerScope.coroutineContext[Job])
        require(parent.isActive) { "Download owner is retired" }
        val binding = Binding(id, downloads, CoroutineScope(ownerScope.coroutineContext + SupervisorJob(parent)), hideContent)
        val previous = lock.withLock { bindings.put(id, binding) }
        previous?.retire()
        binding.job.invokeOnCompletion {
            lock.withLock { if (bindings[id] === binding) bindings.remove(id) }
        }
        return binding
    }

    fun resolve(owner: String?, token: String?): Binding? {
        if (owner == null || token == null) return null
        val id = try { ProfileId(owner) } catch (_: IllegalArgumentException) { return null }
        return lock.withLock { bindings[id]?.takeIf { it.token == token && it.isActive } }
    }

    class Binding internal constructor(
        val id: ProfileId,
        val downloads: DownloadService,
        private val scope: CoroutineScope,
        /** Notification privacy of the owning profile (Security → hide notification content). */
        val hideContent: () -> Boolean = { false },
    ) {
        // Distinguishes two sessions for the same profile; it is not a credential or a persistent ID.
        val token: String = ProfileId.random().value
        val actionIdentity: String get() = "yokan://downloads/${id.value}/$token"
        internal val job = requireNotNull(scope.coroutineContext[Job])
        val isActive: Boolean get() = job.isActive

        fun cancelAll() { scope.launch { downloads.cancelAll() } }
        fun retire() { job.cancel() }

        suspend fun run(action: suspend (DownloadService) -> Unit): ProfileWorkResult<Unit> {
            currentCoroutineContext().ensureActive()
            if (!isActive) return ProfileWorkResult.Skipped
            scope.runJoined { action(downloads) }
            return ProfileWorkResult.Completed(Unit)
        }
    }

    companion object { const val TokenKey = "yokan.download_session" }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/download/ResumableDownload.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/download/ResumableDownload.kt) · implementation · 108 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: private data class PartialDownload(val url: String, val etag: String, val total: Long)
16: internal data class DownloadTransfer(val response: HttpStreamResponse?, val bytes: Long, val complete: Boolean)
19: internal class ResumableDownload(private val http: HttpService, private val files: LocalFileService) {
20: suspend fun transfer(
```

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

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.download

import eu.friedcutlet.yokan.database.DatabaseJson
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.files.LocalFileService
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.http.HttpStreamResponse
import eu.friedcutlet.yokan.services.http.header
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString

@Serializable
private data class PartialDownload(val url: String, val etag: String, val total: Long)

internal data class DownloadTransfer(val response: HttpStreamResponse?, val bytes: Long, val complete: Boolean)

/** Retains only partial representations validated by a strong ETag and a known total length. */
internal class ResumableDownload(private val http: HttpService, private val files: LocalFileService) {
    suspend fun transfer(
        url: String,
        headers: Map<String, String>,
        path: String,
        validateResponse: (HttpStreamResponse) -> Unit = {},
        onProgress: (Long) -> Unit,
    ): DownloadTransfer {
        val manifest = "$path.resume"
        var saved = catchingNonCancellation {
            DatabaseJson.decodeFromString<PartialDownload>(files.readBytesAsync(manifest, 64 * 1024).decodeToString())
        }.getOrNull()?.takeIf { it.url == url && it.total > 0 && it.etag.startsWith('"') }
        var offset = if (saved != null && files.exists(path)) files.directorySize(path) else 0L
        if (saved == null || offset <= 0 || offset >= saved.total) {
            saved = null
            offset = 0
            check(files.deleteRecursivelyAsync(path)) { "Cannot reset partial download" }
            files.deleteRecursivelyAsync(manifest)
        }
        // One immediate full retry when a server ignores Range or the representation has changed.
        repeat(2) {
            val partial = saved
            val start = offset
            var received = 0L
            var response: HttpStreamResponse? = null
            var validated = false
            var restart = false
            val result = catchingNonCancellation {
                val stream: suspend (suspend (ByteArray) -> Unit) -> HttpStreamResponse = { write ->
                    val requestHeaders = headers.filterKeys {
                        !it.equals("Range", true) && !it.equals("If-Range", true) && !it.equals("Accept-Encoding", true)
                    } + mapOf("Accept-Encoding" to "identity") + if (partial != null) {
                        mapOf("Range" to "bytes=$start-", "If-Range" to partial.etag)
                    } else emptyMap()
                    http.stream(HttpRequest(url = url, headers = requestHeaders, onStreamResponse = { head ->
                        response = head
                        if (head.statusCode in 200..299) validateResponse(head)
                        if (head.statusCode in 200..299) {
                            val range = head.headers.header("Content-Range")
                            val expectedRange = partial?.let { "bytes $start-${it.total - 1}/${it.total}" }
                            val encoding = head.headers.header("Content-Encoding")
                            if ((partial != null && (head.statusCode != 206 || range != expectedRange ||
                                    head.headers.header("ETag")?.let { it != partial.etag } == true)) ||
                                (partial == null && head.statusCode == 206) ||
                                (encoding != null && !encoding.equals("identity", true))
                            ) {
                                restart = true
                                error("Response does not match the saved partial representation")
                            }
                            validated = true
                            val etag = head.headers.header("ETag")?.takeIf { it.startsWith('"') && it.endsWith('"') }
                            val total = partial?.total ?: head.headers.header("Content-Length")?.toLongOrNull()
                            if (etag != null && total != null && total > 0) {
                                files.writeBytesAsync(manifest, DatabaseJson.encodeToString(PartialDownload(url, etag, total)).encodeToByteArray())
                            }
                        } else if (partial != null && head.statusCode == 416) {
                            restart = true
                            error("Saved range is no longer available")
                        }
                    })) { chunk ->
                        check(partial == null || validated) { "Transport must validate range headers before appending" }
                        write(chunk)
                        received += chunk.size
                        onProgress(start + received)
                    }
                }
                if (partial == null) files.writeChunks(path, stream) else files.appendChunks(path, stream)
            }
            if (restart) {
                check(files.deleteRecursivelyAsync(path)) { "Cannot reset partial download" }
                files.deleteRecursivelyAsync(manifest)
                saved = null
                offset = 0
                onProgress(0)
            } else {
                val final = result.getOrNull() ?: response
                val expected = partial?.let { it.total - start } ?: final?.headers?.header("Content-Length")?.toLongOrNull()
                val complete = result.isSuccess && final?.statusCode in 200..299 && received > 0 &&
                    (expected == null || expected == received) && (partial == null || validated) &&
                    (final?.statusCode != 206 || validated)
                if (!complete && final?.statusCode in 200..299 && expected != null && received > expected) {
                    files.deleteRecursivelyAsync(path)
                    files.deleteRecursivelyAsync(manifest)
                }
                return DownloadTransfer(final, start + received, complete)
            }
        }
        return DownloadTransfer(null, 0, false)
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/download/SplitPageStore.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/download/SplitPageStore.kt) · implementation · 88 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 class SplitPageStore(
21: private data class Manifest(val version: Int = 1, val original: String, val sizes: List<Long>)
23: suspend fun savedSize(directory: String, base: String): Long? {
42: suspend fun process(path: String, maximumHeight: Int): Long = imageProcessingPermit.withPermit {
77: private suspend fun discardUncommitted(directory: String, base: String) {
83: private suspend fun remove(path: String) {
87: private fun tilePath(directory: String, base: String, index: Int) = "$directory/${base}_s${(index + 1).toString().padStart(4, '0')}.jpg"
```

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

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.download

import eu.friedcutlet.yokan.database.DatabaseJson
import eu.friedcutlet.yokan.services.files.LocalFileService
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.withPermit
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString

private val imageProcessingPermit = Semaphore(1)

/** A page is resumable only after all its tiles and the bounded manifest are durable. */
internal class SplitPageStore(
    private val files: LocalFileService,
    private val splitter: suspend (ByteArray, Int, suspend (Int, ByteArray) -> Unit) -> Boolean = ::splitTallImage,
) {
    @Serializable
    private data class Manifest(val version: Int = 1, val original: String, val sizes: List<Long>)

    suspend fun savedSize(directory: String, base: String): Long? {
        val path = "$directory/$base.split.json"
        if (!files.exists(path)) return null
        val manifest = try {
            DatabaseJson.decodeFromString<Manifest>(files.readBytesAsync(path, 16 * 1024).decodeToString())
        } catch (cancel: CancellationException) { throw cancel }
        catch (_: Exception) { return null }
        if (manifest.version != 1 || manifest.sizes.size !in 2..MaxSplitTiles ||
            !manifest.original.matches(Regex("${Regex.escape(base)}\\.[a-zA-Z0-9]{1,8}"))) return null
        if (!manifest.sizes.withIndex().all { (index, size) ->
            val tile = tilePath(directory, base, index)
            size > 0 && files.exists(tile) && files.directorySize(tile) == size
        }) return null
        // A crash after committing the manifest can leave the original behind. Finish that commit.
        remove("$directory/${manifest.original}")
        remove("$directory/${manifest.original}.complete")
        return manifest.sizes.sum()
    }

    suspend fun process(path: String, maximumHeight: Int): Long = imageProcessingPermit.withPermit {
        val directory = path.substringBeforeLast('/')
        val name = path.substringAfterLast('/')
        val base = name.substringBeforeLast('.')
        require(base.isNotEmpty() && base.all(Char::isDigit))
        savedSize(directory, base)?.let { return@withPermit it }
        discardUncommitted(directory, base)
        val originalSize = files.directorySize(path)
        if (originalSize <= 0 || originalSize > MaxSplitImageBytes) return@withPermit originalSize
        val sizes = mutableListOf<Long>()
        val split = try {
            val bytes = files.readBytesAsync(path, MaxSplitImageBytes)
            if (bytes.mayBeAnimatedImage()) false else splitter(bytes, maximumHeight) { index, tile ->
                currentCoroutineContext().ensureActive()
                check(index == sizes.size && index < MaxSplitTiles && tile.isNotEmpty())
                val target = tilePath(directory, base, index)
                files.writeBytesAsync("$target.part", tile)
                check(files.promoteAsync("$target.part", target)) { "Cannot save split image" }
                sizes += tile.size.toLong()
            }
        } catch (cancel: CancellationException) { throw cancel }
        catch (_: Exception) { false }
        if (!split || sizes.size < 2) {
            discardUncommitted(directory, base)
            return@withPermit originalSize
        }
        val manifestPath = "$directory/$base.split.json"
        files.writeBytesAsync("$manifestPath.part", DatabaseJson.encodeToString(Manifest(original = name, sizes = sizes)).encodeToByteArray())
        check(files.promoteAsync("$manifestPath.part", manifestPath)) { "Cannot commit split image" }
        remove(path)
        remove("$path.complete")
        sizes.sum()
    }

    /** Removes only this page's deterministic outputs, never paths supplied by a manifest. */
    private suspend fun discardUncommitted(directory: String, base: String) {
        val tiles = Regex("${Regex.escape(base)}_s[0-9]{4}\\.jpg(?:\\.part)?")
        files.listFiles(directory).filter { it.name.matches(tiles) || it.name == "$base.split.json" || it.name == "$base.split.json.part" }
            .forEach { remove(it.path) }
    }

    private suspend fun remove(path: String) {
        if (files.exists(path)) check(files.deleteRecursivelyAsync(path) && !files.exists(path)) { "Cannot remove incomplete split image" }
    }

    private fun tilePath(directory: String, base: String, index: Int) = "$directory/${base}_s${(index + 1).toString().padStart(4, '0')}.jpg"
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/download/TallImageSplitter.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/download/TallImageSplitter.kt) · implementation · 47 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 data class TallImageRegion(val top: Int, val height: Int)
10: internal fun tallImageRegions(width: Int, height: Int, maximumHeight: Int): List<TallImageRegion> {
23: internal fun ByteArray.mayBeAnimatedImage(): Boolean {
43: internal expect suspend fun splitTallImage(
```

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

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.download

internal const val MaxSplitImageBytes = 32L * 1024 * 1024
internal const val MaxSplitImagePixels = 24_000_000L
internal const val MaxSplitTiles = 128

internal data class TallImageRegion(val top: Int, val height: Int)

/** Keep page order and every pixel; refuse excessive allocations before decoding. */
internal fun tallImageRegions(width: Int, height: Int, maximumHeight: Int): List<TallImageRegion> {
    val tileHeight = maximumHeight.coerceIn(1024, 8192)
    if (width <= 0 || height <= tileHeight || height.toLong() <= width.toLong() * 2 ||
        width.toLong() * height > MaxSplitImagePixels) return emptyList()
    val count = (height.toLong() + tileHeight - 1) / tileHeight
    if (count > MaxSplitTiles) return emptyList()
    return List(count.toInt()) { index ->
        val top = index * tileHeight
        TallImageRegion(top, minOf(tileHeight, height - top))
    }
}

/** Animated formats must retain their original frames, even when the first frame is tall. */
internal fun ByteArray.mayBeAnimatedImage(): Boolean {
    if (isGif()) return true
    if (size >= 21 && decodeToString(0, 4) == "RIFF" && decodeToString(8, 12) == "WEBP") {
        return decodeToString(12, 16) == "VP8X" && (this[20].toInt() and 2) != 0
    }
    // APNG's animation control chunk precedes IDAT; inspect chunks, not incidental pixel bytes.
    if (size >= 8 && this[0] == 0x89.toByte() && decodeToString(1, 4) == "PNG") {
        var offset = 8
        while (offset.toLong() + 12 <= size) {
            val length = (0..3).fold(0L) { value, i -> (value shl 8) or (this[offset + i].toLong() and 255) }
            val kind = decodeToString(offset + 4, offset + 8)
            if (kind == "acTL") return true
            if (kind == "IDAT" || length > size.toLong() - offset - 12) return false
            offset += length.toInt() + 12
        }
    }
    return false
}

/** Emits one JPEG at a time, avoiding a chapter-sized list of decoded/encoded images. */
internal expect suspend fun splitTallImage(
    bytes: ByteArray,
    maximumHeight: Int,
    writeTile: suspend (index: Int, bytes: ByteArray) -> Unit,
): Boolean
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/downloads/DownloadManagerCard.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/downloads/DownloadManagerCard.kt) · implementation · 117 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
21: internal fun DownloadManagerCard(
```

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

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.screens.downloads

import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.DragHandle
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.*

@Composable
internal fun DownloadManagerCard(
    row: DownloadManagerRow,
    title: String,
    subtitle: String,
    missingDetails: Boolean,
    onCancel: () -> Unit,
    onPause: () -> Unit,
    onResume: () -> Unit,
    onRetry: () -> Unit,
    onOpen: () -> Unit,
    onDelete: () -> Unit,
    modifier: Modifier = Modifier,
    waitingForWifi: Boolean = false,
    dragHandle: Modifier? = null,
    isDragging: Boolean = false,
    onMoveUp: (() -> Unit)? = null,
    onMoveDown: (() -> Unit)? = null,
) {
    val attention = row.section == DownloadSection.NeedsAttention
    // Retry rebuilds the request from the chapter row, so it needs the chapter still in the library.
    val canRetry = row.canRetry && !missingDetails
    val status = stringResource(when {
        row.section == DownloadSection.Completed -> Res.string.dm_completed
        attention && row.failed > 0 -> Res.string.dm_failed
        attention -> Res.string.dm_interrupted
        waitingForWifi && row.live?.isPaused != true && row.live?.isCompleted != true -> Res.string.dm_waiting_wifi
        row.queued -> Res.string.dm_queued
        row.live?.isCompleted == true -> Res.string.dm_finishing
        row.live?.isPaused == true -> Res.string.dm_paused
        else -> Res.string.dm_downloading
    })
    Surface(
        modifier = modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 5.dp),
        shape = MaterialTheme.shapes.large,
        color = MaterialTheme.colorScheme.surfaceContainer,
        border = BorderStroke(1.dp, if (attention) MaterialTheme.colorScheme.error.copy(alpha = .4f) else MaterialTheme.colorScheme.outlineVariant),
        shadowElevation = if (isDragging) 6.dp else 0.dp,
    ) {
        Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
            Row(verticalAlignment = Alignment.CenterVertically) {
                if (dragHandle != null) {
                    val description = stringResource(Res.string.dm_reorder)
                    Box(Modifier.size(48.dp).then(dragHandle).semantics { contentDescription = description }, contentAlignment = Alignment.Center) {
                        Icon(Icons.Default.DragHandle, null, tint = MaterialTheme.colorScheme.onSurfaceVariant)
                    }
                }
                Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) {
                    Text(title, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
                    Text(subtitle, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
                }
            }
            FlowRow(horizontalArrangement = Arrangement.spacedBy(12.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
                Text(status, style = MaterialTheme.typography.labelLarge,
                    color = if (attention) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.primary)
                if (row.total > 0) {
                    Text(stringResource(Res.string.dm_count, row.succeeded, row.total), style = MaterialTheme.typography.bodySmall)
                } else {
                    Text(stringResource(Res.string.dm_unknown_total, row.succeeded), style = MaterialTheme.typography.bodySmall)
                }
                if (row.failed > 0) Text(stringResource(Res.string.dm_failed_count, row.failed), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error)
            }
            if (row.section == DownloadSection.InProgress) {
                val fraction = row.fraction
                if (fraction != null) {
                    Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
                        LinearProgressIndicator(progress = { fraction }, modifier = Modifier.weight(1f))
                        Text(stringResource(Res.string.dm_percent, (fraction * 100).toInt()), style = MaterialTheme.typography.labelMedium)
                    }
                } else if (row.live != null && !row.live.isPaused) {
                    LinearProgressIndicator(modifier = Modifier.fillMaxWidth())
                }
            }
            if (missingDetails) Text(stringResource(Res.string.dm_missing), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
            if (attention && !canRetry) Text(stringResource(Res.string.dm_restart_hint), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
            if (row.section == DownloadSection.Completed && row.location == null) Text(stringResource(Res.string.dm_location_unknown), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
            FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
                if (row.live != null && !row.live.isCompleted) {
                    OutlinedButton(onClick = if (row.live.isPaused) onResume else onPause) {
                        Text(stringResource(if (row.live.isPaused) Res.string.resume else Res.string.tts_pause))
                    }
                }
                if (canRetry) OutlinedButton(onClick = onRetry) { Text(stringResource(Res.string.retry)) }
                if (row.location != null) TextButton(onClick = onOpen) { Text(stringResource(Res.string.action_open)) }
                if (row.section == DownloadSection.InProgress) TextButton(onClick = onCancel) { Text(stringResource(Res.string.action_cancel)) }
                if (row.record != null && row.section != DownloadSection.InProgress) {
                    TextButton(onClick = onDelete, colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.error)) {
                        Text(stringResource(if (row.location == null) Res.string.dm_delete_record else Res.string.dm_delete_files))
                    }
                }
                if (dragHandle != null) {
                    IconButton(onClick = { onMoveUp?.invoke() }, enabled = onMoveUp != null) { Icon(Icons.Default.KeyboardArrowUp, stringResource(Res.string.dm_move_up)) }
                    IconButton(onClick = { onMoveDown?.invoke() }, enabled = onMoveDown != null) { Icon(Icons.Default.KeyboardArrowDown, stringResource(Res.string.dm_move_down)) }
                }
            }
        }
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/downloads/DownloadManagerRows.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/downloads/DownloadManagerRows.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
7: internal enum class DownloadSection { InProgress, NeedsAttention, Completed }
9: internal data class DownloadManagerRow(
34: internal fun downloadManagerRows(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/downloads/DownloadManagerRows.kt) · SHA-256 `2ee92dc321c957ddc09ff1bef78efaabfe0cdf76b4a042377137cf1aba733018`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.screens.downloads

import eu.friedcutlet.yokan.database.DbDownload
import eu.friedcutlet.yokan.services.download.DownloadProgress
import eu.friedcutlet.yokan.services.download.downloadTaskId

internal enum class DownloadSection { InProgress, NeedsAttention, Completed }

internal data class DownloadManagerRow(
    val taskId: String,
    val record: DbDownload?,
    val live: DownloadProgress?,
    val location: String?,
) {
    val succeeded: Int get() = (live?.succeeded ?: record?.succeeded ?: 0).coerceAtLeast(0)
    val failed: Int get() = (live?.failed ?: record?.failed ?: 0).coerceAtLeast(0)
    val total: Int get() = live?.total ?: record?.total ?: 0
    val fraction: Float? get() = total.takeIf { it > 0 }?.let { (succeeded.toFloat() / it).coerceIn(0f, 1f) }
    // The current service retains a location with each in-memory request, including queued ones.
    // ponytail: no persisted request/queue API; require session evidence rather than trust a stale start flag.
    val queued: Boolean get() = live == null && record?.isStartDownload == true &&
        record.isDownload != true && succeeded == 0 && failed == 0 && !location.isNullOrBlank()
    val section: DownloadSection get() = when {
        live != null && !live.isCompleted -> DownloadSection.InProgress
        live != null && failed > 0 -> DownloadSection.NeedsAttention
        record?.isDownload == true && failed == 0 -> DownloadSection.Completed
        live != null || queued -> DownloadSection.InProgress
        else -> DownloadSection.NeedsAttention
    }
    // Retry rebuilds the request from the chapter, so any stopped chapter download can retry, also after a restart.
    val canRetry: Boolean get() = section == DownloadSection.NeedsAttention && record?.chapterId != null
}

internal fun downloadManagerRows(
    records: List<DbDownload>,
    active: List<DownloadProgress>,
    location: (String) -> String?,
): List<DownloadManagerRow> {
    val saved = records.associateBy { downloadTaskId(it.chapterId, it.id) }
    val live = active.associateBy { it.taskId }
    return (saved.keys + live.keys).map { taskId ->
        DownloadManagerRow(taskId, saved[taskId], live[taskId], location(taskId)?.takeIf { it.isNotBlank() })
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/downloads/DownloadQueueScreen.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/downloads/DownloadQueueScreen.kt) · implementation · 213 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
63: internal fun DownloadQueueRoute(onBack: () -> Unit) {
93: internal fun DownloadQueueScreen(
114: fun card(entry: DownloadQueueEntry, dragHandle: Modifier? = null, dragging: Boolean = false) {
```

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

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.screens.downloads

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Download
import androidx.compose.material3.FilterChip
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.heading
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.ui.components.EmptyState
import eu.friedcutlet.yokan.ui.components.ReorderableColumn
import eu.friedcutlet.yokan.ui.screens.settings.SettingsScaffold
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_cancel
import yokan.composeapp.generated.resources.delete
import yokan.composeapp.generated.resources.dm_action_failed
import yokan.composeapp.generated.resources.dm_all
import yokan.composeapp.generated.resources.dm_attention
import yokan.composeapp.generated.resources.dm_completed
import yokan.composeapp.generated.resources.dm_confirm_files
import yokan.composeapp.generated.resources.dm_confirm_record
import yokan.composeapp.generated.resources.dm_delete_files
import yokan.composeapp.generated.resources.dm_delete_record
import yokan.composeapp.generated.resources.dm_empty
import yokan.composeapp.generated.resources.dm_empty_all
import yokan.composeapp.generated.resources.dm_empty_history
import yokan.composeapp.generated.resources.dm_empty_progress
import yokan.composeapp.generated.resources.dm_history
import yokan.composeapp.generated.resources.dm_progress
import yokan.composeapp.generated.resources.dm_queue_hint
import yokan.composeapp.generated.resources.dm_summary
import yokan.composeapp.generated.resources.dm_title
import yokan.composeapp.generated.resources.dm_unknown_chapter
import yokan.composeapp.generated.resources.dm_unknown_title
import yokan.composeapp.generated.resources.dm_retry_unavailable
import yokan.composeapp.generated.resources.dm_waiting_wifi_hint
import yokan.composeapp.generated.resources.ok
import eu.friedcutlet.yokan.ui.screens.settings.downloads.remoteDownloadItems

@Composable
internal fun DownloadQueueRoute(onBack: () -> Unit) {
    val model = viewModel {
        DownloadQueueViewModel(
            repository = YokanRuntime.repository,
            downloader = YokanRuntime.services.downloader,
            chapterDownloads = YokanRuntime.chapterDownloads,
            localFiles = YokanRuntime.localFiles,
            settings = YokanRuntime.settings,
        )
    }
    val state by model.state.collectAsStateWithLifecycle()
    val externalModel = viewModel { eu.friedcutlet.yokan.ui.screens.settings.downloads.ExternalDownloadsViewModel(YokanRuntime.services.externalDownloads) }
    val external by externalModel.state.collectAsStateWithLifecycle()
    DownloadQueueScreen(
        title = stringResource(Res.string.dm_title),
        state = state,
        onBack = onBack,
        onMove = model::move,
        onCancel = model::cancel,
        onPause = model::pause,
        onResume = model::resume,
        onRetry = model::retry,
        onOpen = model::open,
        onDelete = model::delete,
        onDismissActionFailed = model::dismissActionFailed,
        externalItems = { remoteDownloadItems(external, externalModel::act) },
    )
}

@Composable
internal fun DownloadQueueScreen(
    title: String,
    state: DownloadQueueState,
    onBack: () -> Unit,
    onMove: (from: Int, to: Int) -> Unit,
    onCancel: (DownloadManagerRow) -> Unit,
    onPause: (DownloadManagerRow) -> Unit,
    onResume: (DownloadManagerRow) -> Unit,
    onRetry: (DownloadManagerRow) -> Unit,
    onOpen: (DownloadManagerRow) -> Unit,
    onDelete: (DownloadManagerRow) -> Unit,
    onDismissActionFailed: () -> Unit,
    externalItems: androidx.compose.foundation.lazy.LazyListScope.() -> Unit = {},
) {
    val entries = state.entries
    val queued = state.queued
    var filter by rememberSaveable { mutableStateOf(0) }
    var deletion by remember { mutableStateOf<Pair<DownloadManagerRow, String>?>(null) }
    val sections = DownloadSection.entries.filter { filter == 0 || (it == DownloadSection.InProgress) == (filter == 1) }

    @Composable
    fun card(entry: DownloadQueueEntry, dragHandle: Modifier? = null, dragging: Boolean = false) {
        val row = entry.row
        val name = entry.mangaName ?: entry.chapterName ?: stringResource(Res.string.dm_unknown_title)
        val subtitle = listOfNotNull(entry.chapterName ?: stringResource(Res.string.dm_unknown_chapter), entry.source).joinToString(" · ")
        val index = queued.indexOfFirst { it.row.taskId == row.taskId }
        DownloadManagerCard(
            row = row, title = name, subtitle = subtitle, missingDetails = entry.missingDetails,
            onCancel = { onCancel(row) },
            onPause = { onPause(row) }, onResume = { onResume(row) },
            onRetry = { onRetry(row) },
            onOpen = { onOpen(row) },
            onDelete = { deletion = row to name }, dragHandle = dragHandle, isDragging = dragging,
            waitingForWifi = state.waitingForWifi,
            onMoveUp = if (index > 0) ({ onMove(index, index - 1) }) else null,
            onMoveDown = if (index >= 0 && index < queued.lastIndex) ({ onMove(index, index + 1) }) else null,
        )
    }

    SettingsScaffold(title, onBack) {
        item(key = "summary", contentType = "header") {
            Surface(Modifier.fillMaxWidth().padding(16.dp), shape = MaterialTheme.shapes.large, color = MaterialTheme.colorScheme.primaryContainer) {
                Column(Modifier.padding(20.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
                    Icon(Icons.Filled.Download, null, tint = MaterialTheme.colorScheme.onPrimaryContainer)
                    Text(stringResource(Res.string.dm_title), style = MaterialTheme.typography.headlineSmall, color = MaterialTheme.colorScheme.onPrimaryContainer)
                    Text(stringResource(Res.string.dm_summary, entries.count { it.row.section == DownloadSection.InProgress }, entries.count { it.row.section == DownloadSection.NeedsAttention }, entries.count { it.row.section == DownloadSection.Completed }),
                        style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onPrimaryContainer)
                    if (state.waitingForWifi) {
                        Text(stringResource(Res.string.dm_waiting_wifi_hint), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onPrimaryContainer)
                    }
                }
            }
        }
        item(key = "filters", contentType = "filters") {
            FlowRow(Modifier.padding(horizontal = 16.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                listOf(Res.string.dm_all, Res.string.dm_progress, Res.string.dm_history).forEachIndexed { index, label ->
                    FilterChip(selected = filter == index, onClick = { filter = index }, label = { Text(stringResource(label)) })
                }
            }
        }
        if (entries.none { it.row.section in sections }) {
            item(key = "empty", contentType = "empty") { EmptyState(icon = Icons.Filled.Download, title = stringResource(Res.string.dm_empty), modifier = Modifier.fillMaxWidth().padding(vertical = 32.dp, horizontal = 16.dp), subtitle = stringResource(when (filter) {
                1 -> Res.string.dm_empty_progress
                2 -> Res.string.dm_empty_history
                else -> Res.string.dm_empty_all
            })) }
        }
        sections.forEach { section ->
            val members = entries.filter { it.row.section == section }
            if (members.isNotEmpty()) {
                item(key = "section-$section", contentType = "section") {
                    val label = stringResource(when (section) {
                        DownloadSection.InProgress -> Res.string.dm_progress
                        DownloadSection.NeedsAttention -> Res.string.dm_attention
                        DownloadSection.Completed -> Res.string.dm_completed
                    })
                    Text("$label · ${members.size}", style = MaterialTheme.typography.titleSmall,
                        modifier = Modifier.padding(horizontal = 20.dp, vertical = 12.dp).semantics { heading() })
                }
                members.filterNot { it.row.queued }.forEach { entry ->
                    item(key = entry.row.taskId, contentType = "download") { card(entry) }
                }
                if (section == DownloadSection.InProgress && queued.isNotEmpty()) {
                    item(key = "queue", contentType = "queue") {
                        Text(stringResource(Res.string.dm_queue_hint), style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(horizontal = 20.dp, vertical = 8.dp))
                        ReorderableColumn(items = queued, key = { it.row.taskId }, onMove = onMove) { entry, handle, dragging -> card(entry, handle, dragging) }
                    }
                }
            }
        }
        externalItems()
        item(key = "bottom-space") { Spacer(Modifier.height(24.dp)) }
    }
    deletion?.let { (row, name) ->
        androidx.compose.material3.AlertDialog(
            onDismissRequest = { deletion = null },
            title = { Text(stringResource(if (row.location == null) Res.string.dm_delete_record else Res.string.dm_delete_files)) },
            text = { Text(stringResource(if (row.location == null) Res.string.dm_confirm_record else Res.string.dm_confirm_files, name)) },
            dismissButton = { TextButton(onClick = { deletion = null }) { Text(stringResource(Res.string.action_cancel)) } },
            confirmButton = {
                TextButton(onClick = {
                    onDelete(row)
                    deletion = null
                }, colors = androidx.compose.material3.ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.error)) {
                    Text(stringResource(Res.string.delete))
                }
            },
        )
    }
    state.actionError?.let { error ->
        androidx.compose.material3.AlertDialog(
            onDismissRequest = onDismissActionFailed,
            text = {
                val message = if (error == DownloadActionError.RetryUnavailable) Res.string.dm_retry_unavailable else Res.string.dm_action_failed
                Text(stringResource(message))
            },
            confirmButton = { TextButton(onClick = onDismissActionFailed) { Text(stringResource(Res.string.ok)) } },
        )
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/downloads/DownloadQueueViewModel.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/downloads/DownloadQueueViewModel.kt) · implementation · 177 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
28: internal data class DownloadQueueEntry(
36: internal enum class DownloadActionError { Failed, RetryUnavailable }
38: internal data class DownloadQueueState(
47: internal class DownloadQueueViewModel(
82: fun move(from: Int, to: Int) {
93: fun cancel(row: DownloadManagerRow) {
97: fun pause(row: DownloadManagerRow) = downloader.pause(row.taskId)
99: fun resume(row: DownloadManagerRow) = downloader.resume(row.taskId)
101: fun retry(row: DownloadManagerRow) {
107: fun open(row: DownloadManagerRow) {
113: fun delete(row: DownloadManagerRow) {
119: fun dismissActionFailed() = _state.update { it.copy(actionError = null) }
121: private fun failed() = _state.update { it.copy(actionError = DownloadActionError.Failed) }
123: private fun queueState(
135: private fun currentRows() = downloadManagerRows(repository.downloads(), downloader.activeDownloads(), downloader::storageLocation)
138: internal fun downloadQueueEntries(
145: internal class DownloadQueueEntryBuilder {
151: fun build(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/downloads/DownloadQueueViewModel.kt) · SHA-256 `7c64b6fb5e48b004c9467a17fcb3a604890d430daea624f32b8c6403bac1862f`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.screens.downloads

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.data.YokanRepository
import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot
import eu.friedcutlet.yokan.services.download.ChapterDownloads
import eu.friedcutlet.yokan.services.download.DownloadProgress
import eu.friedcutlet.yokan.services.download.DownloadQueueOrder
import eu.friedcutlet.yokan.services.download.DownloadService
import eu.friedcutlet.yokan.services.files.LocalFileService
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch

/** A download row with the names it shows; null names render as "unknown". */
internal data class DownloadQueueEntry(
    val row: DownloadManagerRow,
    val mangaName: String?,
    val chapterName: String?,
    val source: String?,
    val missingDetails: Boolean,
)

internal enum class DownloadActionError { Failed, RetryUnavailable }

internal data class DownloadQueueState(
    val entries: List<DownloadQueueEntry> = emptyList(),
    /** Queued entries in the user's queue order. */
    val queued: List<DownloadQueueEntry> = emptyList(),
    /** Wi-Fi-only holds the pending downloads on a metered network. */
    val waitingForWifi: Boolean = false,
    val actionError: DownloadActionError? = null,
)

internal class DownloadQueueViewModel(
    private val repository: YokanRepository,
    private val downloader: DownloadService,
    private val chapterDownloads: ChapterDownloads,
    private val localFiles: LocalFileService,
    settings: SettingsStore,
    private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,
) : ViewModel() {
    private val entryBuilder = DownloadQueueEntryBuilder()
    // Seeded synchronously so the first frame never flashes the empty state.
    private val _state = MutableStateFlow(
        queueState(
            repository.snapshots.value,
            downloader.activeDownloadProgress.value,
            settings.db.value.downloadQueueOrder,
            downloader.queueStatus.value.waitingForWifi,
        ),
    )
    val state: StateFlow<DownloadQueueState> = _state.asStateFlow()

    init {
        viewModelScope.launch {
            combine(
                repository.snapshots.distinctUntilChanged { old, new ->
                    old.downloads === new.downloads && old.chapters === new.chapters && old.mangas === new.mangas
                },
                downloader.activeDownloadProgress,
                settings.db.map { it.downloadQueueOrder }.distinctUntilChanged(),
                downloader.queueStatus.map { it.waitingForWifi }.distinctUntilChanged(),
            ) { snapshot, active, order, waitingForWifi -> queueState(snapshot, active, order, waitingForWifi) }
                .flowOn(workDispatcher)
                .collect { built -> _state.update { built.copy(actionError = it.actionError) } }
        }
    }

    fun move(from: Int, to: Int) {
        // Recheck after a drag: a worker may have started while the gesture was in flight.
        val current = currentRows()
        val ids = _state.value.queued.mapNotNull { it.row.record?.id }.toMutableList()
        if (from !in ids.indices || to !in ids.indices || ids.any { id -> current.none { it.record?.id == id && it.queued } }) return
        ids.add(to, ids.removeAt(from))
        chapterDownloads.reorderQueue(ids)
        // Publish the new order now so the dropped row never snaps back for a frame.
        _state.update { state -> state.copy(queued = ids.mapNotNull { id -> state.queued.find { it.row.record?.id == id } }) }
    }

    fun cancel(row: DownloadManagerRow) {
        row.record?.let { chapterDownloads.cancel(it.id) } ?: downloader.cancel(row.taskId)
    }

    fun pause(row: DownloadManagerRow) = downloader.pause(row.taskId)

    fun resume(row: DownloadManagerRow) = downloader.resume(row.taskId)

    fun retry(row: DownloadManagerRow) {
        val retried = runCatching { downloader.retry(row.taskId) }
        if (retried.isFailure) return failed()
        if (!retried.getOrDefault(false)) _state.update { it.copy(actionError = DownloadActionError.RetryUnavailable) }
    }

    fun open(row: DownloadManagerRow) {
        val opened = runCatching { row.location?.let(localFiles::openLocation) == true }.getOrDefault(false)
        if (!opened) failed()
    }

    /** Deletes [row] as confirmed; refuses when it changed since (a new request or a moved location). */
    fun delete(row: DownloadManagerRow) {
        if (currentRows().find { it.taskId == row.taskId } != row) return failed()
        val record = row.record ?: return
        if (runCatching { chapterDownloads.remove(record.id) }.isFailure) failed()
    }

    fun dismissActionFailed() = _state.update { it.copy(actionError = null) }

    private fun failed() = _state.update { it.copy(actionError = DownloadActionError.Failed) }

    private fun queueState(
        snapshot: YokanDatabaseSnapshot,
        active: List<DownloadProgress>,
        order: List<Long>,
        waitingForWifi: Boolean,
    ): DownloadQueueState {
        val entries = entryBuilder.build(snapshot, active, downloader::storageLocation)
        val byRecordId = entries.filter { it.row.queued }.mapNotNull { entry -> entry.row.record?.let { it.id to entry } }.toMap()
        val queued = DownloadQueueOrder.sorted(byRecordId.values.mapNotNull { it.row.record }, order).mapNotNull { byRecordId[it.id] }
        return DownloadQueueState(entries, queued, waitingForWifi)
    }

    private fun currentRows() = downloadManagerRows(repository.downloads(), downloader.activeDownloads(), downloader::storageLocation)
}

internal fun downloadQueueEntries(
    snapshot: YokanDatabaseSnapshot,
    active: List<DownloadProgress>,
    location: (String) -> String?,
): List<DownloadQueueEntry> = DownloadQueueEntryBuilder().build(snapshot, active, location)

/** Owned by one collector; progress changes reuse the library lookups. */
internal class DownloadQueueEntryBuilder {
    private var previous: YokanDatabaseSnapshot? = null
    private var chapters = emptyMap<Long, DbChapter>()
    private var mangas = emptyMap<Long, DbManga>()
    private var previousEntries = emptyMap<String, DownloadQueueEntry>()

    fun build(
        snapshot: YokanDatabaseSnapshot,
        active: List<DownloadProgress>,
        location: (String) -> String?,
    ): List<DownloadQueueEntry> {
        val detailsChanged = snapshot.chapters !== previous?.chapters || snapshot.mangas !== previous?.mangas
        if (snapshot.chapters !== previous?.chapters) chapters = snapshot.chapters.associateBy { it.id }
        if (snapshot.mangas !== previous?.mangas) mangas = snapshot.mangas.associateBy { it.id }
        previous = snapshot
        val entries = downloadManagerRows(snapshot.downloads, active, location).map { row ->
            val cached = previousEntries[row.taskId]
            if (!detailsChanged && cached?.row == row) return@map cached
            val chapterId = row.record?.chapterId ?: row.taskId.takeIf { it.startsWith("chapter-") }?.removePrefix("chapter-")?.toLongOrNull()
            val chapter = chapterId?.let(chapters::get)
            val manga = chapter?.mangaId?.let(mangas::get)
            DownloadQueueEntry(
                row = row,
                mangaName = manga?.name?.takeIf { it.isNotBlank() },
                chapterName = chapter?.name?.takeIf { it.isNotBlank() },
                source = manga?.source?.takeIf { it.isNotBlank() },
                missingDetails = chapter == null || manga == null,
            )
        }
        previousEntries = entries.associateBy { it.row.taskId }
        return entries
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/download/Aria2RpcClientTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/download/Aria2RpcClientTest.kt) · test / fixture · 102 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 Aria2RpcClientTest {
92: private fun progress(gid: String) = buildJsonObject { put("gid", gid); put("status", "active"); put("totalLength", "100"); put("completedLength", "50"); put("downloadSpeed", "10") }
93: private fun client(action: (JsonObject) -> JsonElement): Aria2RpcClient {
```

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

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.download

import eu.friedcutlet.yokan.services.http.*
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.json.*
import kotlin.test.*

class Aria2RpcClientTest {
    @Test fun rpcTimeoutIsAnOrdinaryFailureAndDoesNotCancelTheQueueOwner() = runTest {
        val hanging = HttpService { kotlinx.coroutines.awaitCancellation() }
        assertFailsWith<Aria2RpcException> { Aria2RpcClient(hanging, "https://aria.example.org/jsonrpc", "").version() }
        assertTrue(kotlinx.coroutines.currentCoroutineContext()[kotlinx.coroutines.Job]?.isActive == true)
    }
    private val gid = "1234567890abcdef"
    private val otherGid = "abcdef1234567890"

    @Test fun admissionUsesPersistableIdentityTokenHeadersAndNoOverwriteOptions() = runTest {
        val client = client { request ->
            assertEquals("aria2.addUri", request["method"]?.jsonPrimitive?.content)
            val params = request.getValue("params").jsonArray
            assertEquals("token:private-token", params[0].jsonPrimitive.content)
            assertEquals("https://images.example.org/page.jpg", params[1].jsonArray[0].jsonPrimitive.content)
            val options = params[2].jsonObject
            assertEquals(gid, options["gid"]?.jsonPrimitive?.content)
            assertEquals("false", options["allow-overwrite"]?.jsonPrimitive?.content)
            assertEquals("false", options["auto-file-renaming"]?.jsonPrimitive?.content)
            assertEquals("true", options["continue"]?.jsonPrimitive?.content)
            assertEquals("Referer: https://source.example.org", options["header"]?.jsonArray?.single()?.jsonPrimitive?.content)
            JsonPrimitive(gid)
        }
        client.addUri(gid, "https://images.example.org/page.jpg", "/downloads/Title", "0001.jpg", mapOf("Referer" to "https://source.example.org"))
    }

    @Test fun controlsOnlyTouchTheRequestedGidAndNeverGlobalQueue() = runTest {
        val methods = mutableListOf<String>()
        val client = client { request ->
            val method = request.getValue("method").jsonPrimitive.content
            methods += method
            assertEquals(gid, request.getValue("params").jsonArray.last().jsonPrimitive.content)
            JsonPrimitive(if (method == "aria2.removeDownloadResult") "OK" else gid)
        }
        client.pause(gid); client.resume(gid); client.cancel(gid); client.forgetResult(gid)
        assertEquals(listOf("aria2.forcePause", "aria2.unpause", "aria2.forceRemove", "aria2.removeDownloadResult"), methods)
    }

    @Test fun batchResponsesAreMatchedByIdentityAndKeepPerFileFailures() = runTest {
        val transport = HttpService { request ->
            val requests = Json.parseToJsonElement(requireNotNull(request.body)).jsonArray
            val response = JsonArray(requests.reversed().map { element ->
                val call = element.jsonObject
                val requested = call["params"]?.jsonArray?.get(1)?.jsonPrimitive?.content
                buildJsonObject {
                    put("jsonrpc", "2.0"); put("id", call.getValue("id"))
                    if (requested == otherGid) put("error", buildJsonObject { put("code", 1); put("message", "secret message must not leak") })
                    else put("result", progress(gid))
                }
            })
            HttpResponse(200, response.toString())
        }
        val result = Aria2RpcClient(transport, "https://aria.example.org/jsonrpc", "token").statuses(listOf(gid, otherGid))
        assertEquals(Aria2Status.Active, result.getValue(gid).getOrThrow().status)
        assertEquals(50L, result.getValue(gid).getOrThrow().completedBytes)
        val error = assertIs<Aria2RpcException>(result.getValue(otherGid).exceptionOrNull())
        assertEquals(1, error.code)
        assertFalse(error.message.orEmpty().contains("secret"))
    }

    @Test fun invalidIdentitiesPathsAndHeaderInjectionAreRejectedBeforeNetwork() = runTest {
        val client = client { error("Must not contact server") }
        for (bad in listOf("1", "0000000000000000", "../other", "gggggggggggggggg")) assertFailsWith<IllegalArgumentException> { client.cancel(bad) }
        for (name in listOf("../page.jpg", "page\n.jpg", "..", "")) assertFailsWith<IllegalArgumentException> { client.addUri(gid, "https://source.example.org/page", "/downloads", name, emptyMap()) }
        assertFailsWith<IllegalArgumentException> { client.addUri(gid, "https://source.example.org/page", "/downloads", "page.jpg", mapOf("Referer" to "ok\r\nCookie: secret")) }
        assertFalse(Aria2RpcClient.validEndpoint("https://user:secret@aria.example.org/jsonrpc"))
        assertFalse(Aria2RpcClient.validEndpoint("https://aria.example.org/jsonrpc?token=secret"))
        assertTrue(Aria2RpcClient.validEndpoint("http://localhost:6800/jsonrpc"))
    }

    @Test fun mismatchedResponseIdentityAndUnexpectedAdmissionGidFail() = runTest {
        assertFailsWith<Aria2RpcException> { client { JsonPrimitive(otherGid) }.addUri(gid, "https://source.example.org/page", "/downloads", "page.jpg", emptyMap()) }
        val transport = HttpService { HttpResponse(200, "{\"jsonrpc\":\"2.0\",\"id\":\"other-request\",\"result\":{\"version\":\"1.37\"}}") }
        assertFailsWith<Aria2RpcException> { Aria2RpcClient(transport, "https://aria.example.org/jsonrpc", "").version() }
    }

    @Test fun oversizedResponseAndCancellationDoNotBecomeSuccessfulRequests() = runTest {
        val oversized = HttpService { HttpResponse(200, " ".repeat(1024 * 1024 + 1)) }
        assertFailsWith<Aria2RpcException> { Aria2RpcClient(oversized, "https://aria.example.org/jsonrpc", "").version() }
        val cancelled = HttpService { throw CancellationException("profile retired") }
        assertFailsWith<CancellationException> { Aria2RpcClient(cancelled, "https://aria.example.org/jsonrpc", "").version() }
    }

    private fun progress(gid: String) = buildJsonObject { put("gid", gid); put("status", "active"); put("totalLength", "100"); put("completedLength", "50"); put("downloadSpeed", "10") }
    private fun client(action: (JsonObject) -> JsonElement): Aria2RpcClient {
        val http = HttpService { request ->
            assertEquals("POST", request.method)
            assertEquals("application/json", request.headers["Content-Type"])
            val call = Json.parseToJsonElement(requireNotNull(request.body)).jsonObject
            HttpResponse(200, buildJsonObject { put("jsonrpc", "2.0"); put("id", call.getValue("id")); put("result", action(call)) }.toString())
        }
        return Aria2RpcClient(http, "https://aria.example.org/jsonrpc", "private-token")
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/download/ChapterDownloadsTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/download/ChapterDownloadsTest.kt) · test / fixture · 270 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
24: class ChapterDownloadsTest {
31: override suspend fun request(request: eu.friedcutlet.yokan.services.http.HttpRequest): eu.friedcutlet.yokan.services.http.HttpResponse = error("Manual routing must persist before any RPC")
88: fun deleteChaptersRemovesSpecifiedChapters() {
106: fun deleteForChaptersClearsDownloadRecordsAndDownloadSize() = runTest {
130: fun deleteForMangaDeletesAllChaptersOfSeries() = runTest {
158: fun enqueueRecordsTheChapterRightAwayWithoutResolvingPages() = runTest {
175: fun enqueueWithoutDestinationUsesTheSelectedDownloadFolder() = runTest {
192: fun enqueueNeverPicksASystemPickerFolderAsTheDownloadRoot() = runTest {
211: private fun enqueueSnapshot(): YokanDatabaseSnapshot {
222: private fun TestScope.fixture(snapshot: YokanDatabaseSnapshot): Fixture {
238: private class Fixture(
246: private class RecordingDownloadService : DownloadService {
251: override suspend fun initialize(poolSize: Int) = Unit
252: override fun enqueue(request: DownloadRequest, onProgress: (DownloadProgress) -> Unit) {
255: override fun cancel(taskId: String) = Unit
256: override fun pause(taskId: String) = Unit
257: override fun resume(taskId: String) = Unit
258: override fun retry(taskId: String): Boolean = false
259: override fun storageLocation(taskId: String): String? = null
260: override fun deleteArtifacts(taskId: String) {
263: override suspend fun deleteArtifactsAsync(taskId: String, onDeleted: () -> Unit): Boolean {
269: override fun activeDownloads(): List<DownloadProgress> = emptyList()
```

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

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.download

import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.services.notifications.NoNotifications
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbDownload
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbLocalFolder
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import eu.friedcutlet.yokan.services.files.NoFiles
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.advanceUntilIdle

class ChapterDownloadsTest {
    @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
    @Test fun preferredRemoteRoutingPreservesExplicitLocalDestinationAndHlsFallback() = runTest {
        val f = fixture(enqueueSnapshot())
        f.database.updateSettings(f.database.settings().let { old -> old.copy(features = old.features.copy(externalDownloads = eu.friedcutlet.yokan.database.DbExternalDownloads(eu.friedcutlet.yokan.database.PreferredDownloader.Aria2, "https://aria.example.org/jsonrpc", "secret", "/remote"))) })
        var url = "https://images.example.org/page.jpg"
        val http = object : eu.friedcutlet.yokan.services.http.HttpService {
            override suspend fun request(request: eu.friedcutlet.yokan.services.http.HttpRequest): eu.friedcutlet.yokan.services.http.HttpResponse = error("Manual routing must persist before any RPC")
        }
        val remote = ExternalDownloads(f.database, http, this, { _, _ -> listOf(eu.friedcutlet.yokan.database.DbPageUrl(url = url)) }, startPolling = false)
        val actions = ChapterDownloads(f.repository, f.database, f.downloader, NoNotifications, SettingsStore(f.repository, backgroundScope) {}, NoFiles, this, remote)
        val title = requireNotNull(f.repository.manga(1)); val chapter = f.repository.chapters(1).single { it.id == 10L }
        actions.enqueue(title, chapter, null)
        advanceUntilIdle()
        assertEquals(1, remote.jobs.value.size)
        assertTrue(f.downloader.requests.isEmpty())
        actions.enqueue(title, chapter, "/explicit-local")
        assertEquals("/explicit-local", f.downloader.requests.single().destinationRoot)
        remote.remove(remote.jobs.value.single().id, forgetUnverified = true)
        url = "https://video.example.org/master.m3u8"
        actions.enqueue(title, chapter, null)
        advanceUntilIdle()
        assertEquals(2, f.downloader.requests.size)
        assertTrue(remote.jobs.value.isEmpty())
    }
    @Test fun awaitingTitleRemovalKeepsDatabaseParentsAvailableAndReportsFailure() = runTest {
        val f = fixture(seedDatabaseSnapshot().copy(
            mangas = listOf(DbManga(id = 1, name = "Title", favorite = true)),
            chapters = listOf(DbChapter(id = 10, mangaId = 1, archivePath = "/saved")),
            downloads = listOf(DbDownload(id = 100, chapterId = 10, isDownload = true)),
        ))
        f.downloader.deletionAllowed = false
        assertEquals(emptySet(), f.downloads.deleteForMangaAwait(setOf(1)))
        assertTrue(f.database.downloads().isNotEmpty())
        assertTrue(f.database.manga(1) != null)
        f.downloader.deletionAllowed = true
        assertEquals(setOf(1L), f.downloads.deleteForMangaAwait(setOf(1)))
        assertTrue(f.database.downloads().isEmpty())
        assertTrue(f.database.manga(1) != null, "The caller removes the title only after deletion finishes")
        f.repository.removeLibraryEntries(setOf(1))
        assertEquals(false, f.database.manga(1)?.favorite)
    }
    @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
    @Test fun asynchronousRemovalClearsRecordsOnlyAfterSuccessfulFileDeletion() = runTest {
        val snapshot = seedDatabaseSnapshot().copy(
            mangas = listOf(DbManga(id = 1, name = "Title")),
            chapters = listOf(DbChapter(id = 10, mangaId = 1, archivePath = "/saved", downloadSize = "5 MB")),
            downloads = listOf(DbDownload(id = 100, chapterId = 10, isDownload = true)),
        )
        val f = fixture(snapshot)
        f.downloader.deletionAllowed = false
        f.downloads.deleteForChapters(setOf(10))
        advanceUntilIdle()
        assertEquals(true, f.database.download(100)?.isDownload)
        assertEquals("/saved", f.database.chapter(10)?.archivePath)
        f.downloader.deletionAllowed = true
        f.downloads.deleteForChapters(setOf(10))
        assertEquals(true, f.database.download(100)?.isDownload)
        advanceUntilIdle()
        assertNull(f.database.download(100))
        assertEquals("", f.database.chapter(10)?.archivePath)
        assertNull(f.database.chapter(10)?.downloadSize)
    }
    @Test
    fun deleteChaptersRemovesSpecifiedChapters() {
        val manga = DbManga(id = 1, name = "Test Manga", link = "/test", itemType = DbItemType.Manga)
        val chapter1 = DbChapter(id = 10, mangaId = 1, url = "/c1", name = "Ch 1")
        val chapter2 = DbChapter(id = 20, mangaId = 1, url = "/c2", name = "Ch 2")
        val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(
            mangas = listOf(manga),
            chapters = listOf(chapter1, chapter2),
        ))
        val repository = DefaultYokanRepository(database)

        repository.deleteChapters(setOf(10))

        assertEquals(1, database.chapters().size)
        assertEquals(20, database.chapters().single().id)
    }

    @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
    @Test
    fun deleteForChaptersClearsDownloadRecordsAndDownloadSize() = runTest {
        val manga = DbManga(id = 1, name = "Test Manga", link = "/test", itemType = DbItemType.Manga, favorite = true)
        val chapter1 = DbChapter(id = 10, mangaId = 1, url = "/c1", name = "Ch 1", downloadSize = "15 MB")
        val chapter2 = DbChapter(id = 20, mangaId = 1, url = "/c2", name = "Ch 2", downloadSize = "20 MB")
        val download1 = DbDownload(id = 100, chapterId = 10, isDownload = true, succeeded = 10, total = 10)
        val download2 = DbDownload(id = 200, chapterId = 20, isDownload = true, succeeded = 12, total = 12)
        val fixture = fixture(seedDatabaseSnapshot().copy(
            mangas = listOf(manga),
            chapters = listOf(chapter1, chapter2),
            downloads = listOf(download1, download2),
        ))

        val removed = fixture.downloads.deleteForChapters(setOf(10))
        advanceUntilIdle()

        assertEquals(1, removed)
        assertNull(fixture.database.chapter(10)?.downloadSize)
        assertEquals("20 MB", fixture.database.chapter(20)?.downloadSize)
        assertEquals(listOf(200L), fixture.database.downloads().map { it.id })
        assertEquals(listOf(downloadTaskId(10, 100)), fixture.downloader.deletedArtifacts)
    }

    @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
    @Test
    fun deleteForMangaDeletesAllChaptersOfSeries() = runTest {
        val manga1 = DbManga(id = 1, name = "Manga 1", link = "/m1", itemType = DbItemType.Manga, favorite = true)
        val manga2 = DbManga(id = 2, name = "Manga 2", link = "/m2", itemType = DbItemType.Manga, favorite = true)
        val fixture = fixture(seedDatabaseSnapshot().copy(
            mangas = listOf(manga1, manga2),
            chapters = listOf(
                DbChapter(id = 10, mangaId = 1, url = "/c1", name = "Ch 1", downloadSize = "5 MB"),
                DbChapter(id = 20, mangaId = 1, url = "/c2", name = "Ch 2", downloadSize = "5 MB"),
                DbChapter(id = 30, mangaId = 2, url = "/c3", name = "Ch 3", downloadSize = "10 MB"),
            ),
            downloads = listOf(
                DbDownload(id = 101, chapterId = 10, isDownload = true),
                DbDownload(id = 102, chapterId = 20, isDownload = true),
                DbDownload(id = 103, chapterId = 30, isDownload = true),
            ),
        ))

        val count = fixture.downloads.deleteForManga(setOf(1))
        advanceUntilIdle()

        assertTrue(count >= 2)
        assertNull(fixture.database.chapter(10)?.downloadSize)
        assertNull(fixture.database.chapter(20)?.downloadSize)
        assertEquals("10 MB", fixture.database.chapter(30)?.downloadSize)
        assertEquals(listOf(103L), fixture.database.downloads().map { it.id })
    }

    @Test
    fun enqueueRecordsTheChapterRightAwayWithoutResolvingPages() = runTest {
        val fixture = fixture(enqueueSnapshot())
        val manga = checkNotNull(fixture.repository.manga(1))
        val chapter = fixture.repository.chapters(1).single()

        fixture.downloads.enqueue(manga, chapter, destinationRoot = "/custom")

        val request = fixture.downloader.requests.single()
        assertEquals(downloadTaskId(10, 0), request.taskId)
        assertEquals(10L, request.chapterId)
        assertEquals("/custom", request.destinationRoot)
        // The title's installed source labels the download.
        assertEquals("Src (EN)", request.sourceLabel)
        assertEquals(5L, request.sourceId)
    }

    @Test
    fun enqueueWithoutDestinationUsesTheSelectedDownloadFolder() = runTest {
        val seed = enqueueSnapshot()
        val fixture = fixture(seed.copy(
            settings = seed.settings.copy(
                namedLocalFolders = listOf(DbLocalFolder("a", "/a"), DbLocalFolder("b", "/b")),
                downloadLocalFolderName = "b",
            ),
        ))
        val manga = checkNotNull(fixture.repository.manga(1))
        val chapter = fixture.repository.chapters(1).single()

        fixture.downloads.enqueue(manga, chapter, destinationRoot = null)

        assertEquals("/b", fixture.downloader.requests.single().destinationRoot)
    }

    @Test
    fun enqueueNeverPicksASystemPickerFolderAsTheDownloadRoot() = runTest {
        val seed = enqueueSnapshot()
        val fixture = fixture(seed.copy(
            settings = seed.settings.copy(
                namedLocalFolders = listOf(
                    DbLocalFolder("saf", "content://com.android.externalstorage.documents/tree/primary%3AComics"),
                    DbLocalFolder("disk", "/disk"),
                ),
                downloadLocalFolderName = "saf",
            ),
        ))
        val manga = checkNotNull(fixture.repository.manga(1))
        val chapter = fixture.repository.chapters(1).single()

        fixture.downloads.enqueue(manga, chapter, destinationRoot = null)

        assertEquals("/disk", fixture.downloader.requests.single().destinationRoot)
    }

    private fun enqueueSnapshot(): YokanDatabaseSnapshot {
        val seed = seedDatabaseSnapshot()
        return seed.copy(
            sources = listOf(DbSource(id = 5, name = "Src", lang = "en", itemType = DbItemType.Manga, isAdded = true)),
            mangas = listOf(
                DbManga(id = 1, name = "Title", link = "/t", source = "Src", sourceId = 5, itemType = DbItemType.Manga, favorite = true),
            ),
            chapters = listOf(DbChapter(id = 10, mangaId = 1, url = "/c1", name = "Ch 1")),
        )
    }

    private fun TestScope.fixture(snapshot: YokanDatabaseSnapshot): Fixture {
        val database = InMemoryYokanDatabase(snapshot)
        val repository = DefaultYokanRepository(database)
        val downloader = RecordingDownloadService()
        val downloads = ChapterDownloads(
            repository = repository,
            database = database,
            downloader = downloader,
            notifications = NoNotifications,
            settings = SettingsStore(repository, backgroundScope, onSchedulingChanged = {}),
            localFiles = NoFiles,
            scope = this,
        )
        return Fixture(database, repository, downloader, downloads)
    }

    private class Fixture(
        val database: InMemoryYokanDatabase,
        val repository: DefaultYokanRepository,
        val downloader: RecordingDownloadService,
        val downloads: ChapterDownloads,
    )
}

private class RecordingDownloadService : DownloadService {
    val requests = mutableListOf<DownloadRequest>()
    val deletedArtifacts = mutableListOf<String>()
    var deletionAllowed = true

    override suspend fun initialize(poolSize: Int) = Unit
    override fun enqueue(request: DownloadRequest, onProgress: (DownloadProgress) -> Unit) {
        requests += request
    }
    override fun cancel(taskId: String) = Unit
    override fun pause(taskId: String) = Unit
    override fun resume(taskId: String) = Unit
    override fun retry(taskId: String): Boolean = false
    override fun storageLocation(taskId: String): String? = null
    override fun deleteArtifacts(taskId: String) {
        deletedArtifacts += taskId
    }
    override suspend fun deleteArtifactsAsync(taskId: String, onDeleted: () -> Unit): Boolean {
        if (!deletionAllowed) return false
        deleteArtifacts(taskId)
        onDeleted()
        return true
    }
    override fun activeDownloads(): List<DownloadProgress> = emptyList()
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/download/DownloadAutomationTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/download/DownloadAutomationTest.kt) · test / fixture · 211 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
12: class DownloadAutomationTest {
177: private fun consumedDatabase(policy: DbDownloadPolicy) = InMemoryYokanDatabase(policySnapshot(policy).let { it.copy(
183: internal class PolicyDownloads(private val database: YokanDatabase) : DownloadService {
190: override suspend fun initialize(poolSize: Int) = Unit
191: override fun enqueue(request: DownloadRequest, onProgress: (DownloadProgress) -> Unit) {
197: override suspend fun deleteCompletedArtifacts(taskId: String, stillEligible: () -> Boolean, onDeleted: () -> Unit): Boolean {
204: override fun cancel(taskId: String) = Unit
205: override fun pause(taskId: String) = Unit
206: override fun resume(taskId: String) = Unit
207: override fun retry(taskId: String) = false
208: override fun storageLocation(taskId: String): String? = null
209: override fun deleteArtifacts(taskId: String) = error("Unsafe deletion must not be used by automation")
210: override fun activeDownloads(): List<DownloadProgress> = emptyList()
```

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

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.download

import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.data.DefaultYokanRepository
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import kotlin.test.*

@OptIn(ExperimentalCoroutinesApi::class)
class DownloadAutomationTest {
    @Test fun savingProgressOnAnAlreadyReadChapterDoesNotFabricateConsumption() = runTest {
        val database = consumedDatabase(DbDownloadPolicy(cleanupAfterConsumption = true))
        val downloads = PolicyDownloads(database)
        val automation = DownloadAutomation(database, downloads, backgroundScope)
        val repository = DefaultYokanRepository(database, automation)
        repository.chapterOpened(10)
        repository.setChaptersRead(setOf(10), true, lastPageRead = "1")
        repository.chapterClosed(10)
        runCurrent()
        assertTrue(downloads.deleted.isEmpty())
        repository.recordChapterConsumption(setOf(10))
        runCurrent()
        assertEquals(listOf("chapter-10"), downloads.deleted)
    }
    @Test fun manualAndConsumptionTogglesRemainIndependentAndManualCleanupWaitsForClose() = runTest {
        val database = consumedDatabase(DbDownloadPolicy(cleanupAfterManualMark = true))
        val downloads = PolicyDownloads(database)
        val automation = DownloadAutomation(database, downloads, backgroundScope)
        automation.chapterOpened(10).join()
        automation.chaptersMarked(setOf(10), true, consumed = true).join()
        automation.chapterClosed(10).join()
        assertTrue(downloads.deleted.isEmpty(), "Consumption does not trigger the manual-mark policy")
        automation.chapterOpened(10).join()
        automation.chaptersMarked(setOf(10), true, consumed = false).join()
        assertTrue(downloads.deleted.isEmpty(), "An open chapter remains protected")
        assertEquals(setOf(10L), database.settings().features.downloads.manuallyMarkedChapterIds)
        automation.chapterClosed(10).join()
        assertEquals(listOf("chapter-10"), downloads.deleted)
        assertTrue(database.settings().features.downloads.manuallyMarkedChapterIds.isEmpty())
    }
    @Test fun downloadFinishingAfterConsumptionIsCleanedAndReceiptDoesNotAccumulate() = runTest {
        val database = InMemoryYokanDatabase(policySnapshot(DbDownloadPolicy(cleanupAfterConsumption = true)).copy(
            downloads = listOf(DbDownload(id = 10, chapterId = 10, isDownload = false, isStartDownload = true)),
        ))
        val downloads = PolicyDownloads(database)
        val automation = DownloadAutomation(database, downloads, backgroundScope)
        automation.chapterOpened(10).join()
        database.upsertChapter(database.chapter(10)!!.copy(isRead = true))
        automation.chaptersMarked(setOf(10), true, consumed = true).join()
        automation.chapterClosed(10).join()
        assertTrue(downloads.deleted.isEmpty())
        database.upsertDownload(database.download(10)!!.copy(isDownload = true, isStartDownload = false))
        automation.downloadCompleted(10).join()
        assertEquals(listOf("chapter-10"), downloads.deleted)
        assertNull(database.download(10))
        assertTrue(database.settings().features.downloads.consumedChapterIds.isEmpty())
    }

    @Test fun disabledCleanupDoesNotPersistAConsumptionLedger() = runTest {
        val database = consumedDatabase(DbDownloadPolicy())
        val settings = database.settings()
        val automation = DownloadAutomation(database, PolicyDownloads(database), backgroundScope)
        automation.chaptersMarked(setOf(10), true, consumed = true).join()
        assertEquals(settings, database.settings())
        assertTrue(database.settings().features.downloads.consumedChapterIds.isEmpty())
    }
    @Test fun updaterReceiptsRecoverAndNeverDuplicateQueueRows() = runTest {
        val policy = DbDownloadPolicy(autoDownloadNew = true, pendingNewChapterIds = setOf(10, 11))
        val database = InMemoryYokanDatabase(policySnapshot(policy))
        val downloads = PolicyDownloads(database)
        val automation = DownloadAutomation(database, downloads, backgroundScope)
        automation.reconcile()
        automation.reconcile()
        assertEquals(listOf(10L, 11L), downloads.enqueued)
        assertEquals(emptySet(), database.settings().features.downloads.pendingNewChapterIds)
        assertEquals(2, database.downloads().size)
    }

    @Test fun failedAdmissionRetainsReceiptAndPreviouslyAdmittedWorkIsAcknowledged() = runTest {
        val database = InMemoryYokanDatabase(policySnapshot(DbDownloadPolicy(autoDownloadNew = true, pendingNewChapterIds = setOf(10, 11))))
        val downloads = PolicyDownloads(database).apply { failChapter = 11 }
        val automation = DownloadAutomation(database, downloads, backgroundScope)
        assertFailsWith<IllegalStateException> { automation.reconcile() }
        assertEquals(setOf(11L), database.settings().features.downloads.pendingNewChapterIds)
        downloads.failChapter = null
        automation.reconcile()
        assertEquals(listOf(10L, 11L), downloads.enqueued)
    }

    @Test fun disabledAutomationDropsPendingWorkWithoutQueueingOldReleasesOnEnable() = runTest {
        val database = InMemoryYokanDatabase(policySnapshot(DbDownloadPolicy(pendingNewChapterIds = setOf(10))))
        val downloads = PolicyDownloads(database)
        val automation = DownloadAutomation(database, downloads, backgroundScope)
        automation.reconcile()
        automation.recordDiscoveredChapters(setOf(11))
        assertTrue(downloads.enqueued.isEmpty())
        assertTrue(database.settings().features.downloads.pendingNewChapterIds.isEmpty())
    }

    @Test fun activeChapterAndMultipleReaderOwnersRemainProtectedUntilLastClose() = runTest {
        val database = consumedDatabase(DbDownloadPolicy(cleanupAfterConsumption = true, consumedChapterIds = setOf(10)))
        val downloads = PolicyDownloads(database)
        val automation = DownloadAutomation(database, downloads, backgroundScope)
        automation.chapterOpened(10).join()
        automation.chapterOpened(10).join()
        assertEquals(0, automation.cleanup(1, DownloadCleanupReason.Consumption))
        automation.chapterClosed(10).join()
        assertTrue(downloads.deleted.isEmpty())
        automation.chapterClosed(10).join()
        assertEquals(listOf("chapter-10"), downloads.deleted)
        assertNull(database.download(10))
        assertEquals("", database.chapter(10)!!.archivePath)
    }

    @Test fun manualReadNeverCreatesConsumptionProofAndUnreadRemovesIt() = runTest {
        val database = consumedDatabase(DbDownloadPolicy(cleanupAfterConsumption = true))
        val downloads = PolicyDownloads(database)
        val automation = DownloadAutomation(database, downloads, backgroundScope)
        automation.chaptersMarked(setOf(10), true, consumed = false).join()
        assertTrue(downloads.deleted.isEmpty())
        assertTrue(database.settings().features.downloads.consumedChapterIds.isEmpty())
        automation.chapterOpened(10).join()
        automation.chaptersMarked(setOf(10), true, consumed = true).join()
        assertEquals(setOf(10L), database.settings().features.downloads.consumedChapterIds)
        automation.chaptersMarked(setOf(10), false, consumed = false).join()
        assertTrue(database.settings().features.downloads.consumedChapterIds.isEmpty())
    }

    @Test fun fileFailureAndCancellationNeverClearDownloadMarkers() = runTest {
        val database = consumedDatabase(DbDownloadPolicy())
        val downloads = PolicyDownloads(database).apply { deletionSucceeds = false }
        val automation = DownloadAutomation(database, downloads, backgroundScope)
        assertEquals(0, automation.cleanupReadDownloads(setOf(10)))
        assertTrue(database.download(10)!!.isDownload == true)
        assertTrue(database.chapter(10)!!.archivePath.isNotBlank())
        downloads.cancelDeletion = true
        assertFailsWith<CancellationException> { automation.cleanupReadDownloads(setOf(10)) }
        assertTrue(database.download(10)!!.isDownload == true)
    }

    @Test fun explicitCleanupOnlyDeletesPreviewedIdsAndRechecksNewBookmarks() = runTest {
        val database = consumedDatabase(DbDownloadPolicy())
        val downloads = PolicyDownloads(database)
        val automation = DownloadAutomation(database, downloads, backgroundScope)
        val preview = automation.previewReadCleanup()
        assertEquals(listOf(10L), preview.map { it.chapterId })
        database.upsertChapter(database.chapter(10)!!.copy(isBookmarked = true))
        database.upsertChapter(database.chapter(11)!!.copy(isRead = true))
        database.upsertDownload(DbDownload(id = 11, chapterId = 11, isDownload = true))
        assertEquals(0, automation.cleanupReadDownloads(preview.mapTo(mutableSetOf()) { it.chapterId }))
        assertTrue(downloads.deleted.isEmpty())
        assertTrue(database.download(11)!!.isDownload == true)
    }

    @Test fun sourceRemovalDuringAdmissionDoesNotQueueLaterChapters() = runTest {
        val database = InMemoryYokanDatabase(policySnapshot(DbDownloadPolicy(autoDownloadNew = true, pendingNewChapterIds = setOf(10, 11))))
        val downloads = PolicyDownloads(database).apply { afterEnqueue = { database.upsertSource(database.source(7)!!.copy(isActive = false)) } }
        val automation = DownloadAutomation(database, downloads, backgroundScope)
        automation.reconcile()
        assertEquals(listOf(10L), downloads.enqueued)
    }

    @Test fun observerDrainsDurableDiscoveryHandoffAndPreservesOtherFeatureSettings() = runTest {
        val database = InMemoryYokanDatabase(policySnapshot(DbDownloadPolicy(autoDownloadNew = true)))
        val automation = DownloadAutomation(database, PolicyDownloads(database), backgroundScope)
        runCurrent()
        database.updateSettings(database.settings().copy(features = database.settings().features.copy(home = DbHomePreferences(itemsPerShelf = 21))))
        automation.recordDiscoveredChapters(setOf(10))
        runCurrent()
        assertEquals(10L, database.downloads().single().chapterId)
        assertEquals(21, database.settings().home.itemsPerShelf)
        assertTrue(database.settings().features.downloads.pendingNewChapterIds.isEmpty())
    }

    private fun consumedDatabase(policy: DbDownloadPolicy) = InMemoryYokanDatabase(policySnapshot(policy).let { it.copy(
        chapters = it.chapters.map { c -> if (c.id == 10L) c.copy(isRead = true, archivePath = "/downloads/Manga/Src/Title/Chapter 10") else c },
        downloads = listOf(DbDownload(id = 10, chapterId = 10, isDownload = true)),
    ) })
}

internal class PolicyDownloads(private val database: YokanDatabase) : DownloadService {
    val enqueued = mutableListOf<Long>()
    val deleted = mutableListOf<String>()
    var failChapter: Long? = null
    var deletionSucceeds = true
    var cancelDeletion = false
    var afterEnqueue: () -> Unit = {}
    override suspend fun initialize(poolSize: Int) = Unit
    override fun enqueue(request: DownloadRequest, onProgress: (DownloadProgress) -> Unit) {
        check(request.chapterId != failChapter) { "Storage unavailable" }
        enqueued += request.chapterId
        database.upsertDownload(DbDownload(chapterId = request.chapterId, isStartDownload = true))
        afterEnqueue()
    }
    override suspend fun deleteCompletedArtifacts(taskId: String, stillEligible: () -> Boolean, onDeleted: () -> Unit): Boolean {
        if (cancelDeletion) throw CancellationException("Profile retired")
        if (!deletionSucceeds || !stillEligible()) return false
        deleted += taskId
        onDeleted()
        return true
    }
    override fun cancel(taskId: String) = Unit
    override fun pause(taskId: String) = Unit
    override fun resume(taskId: String) = Unit
    override fun retry(taskId: String) = false
    override fun storageLocation(taskId: String): String? = null
    override fun deleteArtifacts(taskId: String) = error("Unsafe deletion must not be used by automation")
    override fun activeDownloads(): List<DownloadProgress> = emptyList()
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/download/DownloadConcurrencyAndSerializationTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/download/DownloadConcurrencyAndSerializationTest.kt) · test / fixture · 538 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
35: class DownloadConcurrencyAndSerializationTest {
38: private fun TestScope.downloader(
53: private fun databaseWithDownloadParents(
68: private class PromotionFailingFiles(private var failuresRemaining: Int) : MemoryFiles() {
69: override fun promote(sourcePath: String, targetPath: String): Boolean {
79: fun resolveDownloadSourceKeyPrefersSourceIdThenDatabaseThenLabelThenId() {
138: fun downloadStartDelayCalculatesBaseAndJitter() {
143: override fun nextBits(bitCount: Int): Int = 0
144: override fun nextDouble(): Double = 0.0
147: override fun nextBits(bitCount: Int): Int = 0
148: override fun nextDouble(): Double = 1.0
160: fun perSourceSerializationPreventsConcurrentDownloadsFromSameSource() = runTest {
179: override suspend fun request(request: HttpRequest): HttpResponse =
182: override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse {
263: fun allowConcurrentDownloadsFalseEnforcesGlobalSingleConcurrency() = runTest {
281: override suspend fun request(request: HttpRequest): HttpResponse =
284: override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse {
334: fun stalledStreamFailsTheChapterInsteadOfStayingInProgress() = runTest {
339: override suspend fun request(request: HttpRequest) = HttpResponse(statusCode = 200, headers = emptyMap(), body = "")
340: override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse {
360: fun downloadQueueOrderSortsExplicitIdsFirstThenArrivalOrder() {
376: fun downloadServiceReorderQueuePrioritizesMovedTask() = runTest {
394: override suspend fun request(request: HttpRequest) =
397: override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse {
477: fun promotionExceptionReportsFailureAndQueueContinues() = runTest {
494: override suspend fun request(request: HttpRequest) =
497: override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/download/DownloadConcurrencyAndSerializationTest.kt) · SHA-256 `9283d5ac205c90bb0bf65826e254dab9b34596bd446b9116b638be40c5d30be5`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.download

import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbPageUrl
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.domain.Source
import eu.friedcutlet.yokan.services.files.LocalFileService
import eu.friedcutlet.yokan.services.files.MemoryFiles
import eu.friedcutlet.yokan.services.files.NoArchives
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.http.HttpStreamResponse
import kotlin.random.Random
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.delay
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.withTimeout

@OptIn(ExperimentalCoroutinesApi::class)
class DownloadConcurrencyAndSerializationTest {

    /** A downloader whose chapters each resolve to the single page URL in [pages]. */
    private fun TestScope.downloader(
        database: InMemoryYokanDatabase,
        http: HttpService,
        pages: Map<Long, String>,
        files: LocalFileService = MemoryFiles(),
    ) = PersistentDownloadService(
        database = database,
        http = http,
        files = files,
        archives = NoArchives,
        scope = this,
        resolvePages = { chapterId, _ -> listOf(DbPageUrl(url = pages.getValue(chapterId))) },
        ioDispatcher = StandardTestDispatcher(testScheduler),
    )

    private fun databaseWithDownloadParents(
        snapshot: eu.friedcutlet.yokan.database.YokanDatabaseSnapshot,
        chapterSources: Map<Long, Long>,
    ) = InMemoryYokanDatabase(
        snapshot.copy(
            sources = snapshot.sources + chapterSources.values.distinct().map { id -> DbSource(id = id, name = "Source $id") },
            mangas = snapshot.mangas + chapterSources.map { (chapterId, sourceId) ->
                DbManga(id = chapterId, name = "Title $chapterId", sourceId = sourceId, itemType = DbItemType.Manga)
            },
            chapters = snapshot.chapters + chapterSources.map { (id, _) ->
                DbChapter(id = id, mangaId = id, name = "Chapter $id", url = "/chapter/$id")
            },
        ),
    )

    private class PromotionFailingFiles(private var failuresRemaining: Int) : MemoryFiles() {
        override fun promote(sourcePath: String, targetPath: String): Boolean {
            if (failuresRemaining > 0) {
                failuresRemaining -= 1
                error("simulated promotion failure")
            }
            return super.promote(sourcePath, targetPath)
        }
    }

    @Test
    fun resolveDownloadSourceKeyPrefersSourceIdThenDatabaseThenLabelThenId() {
        val seed = seedDatabaseSnapshot()
        val database = InMemoryYokanDatabase(
            seed.copy(
                mangas = listOf(
                    DbManga(id = 10L, name = "Test Manga", source = "MangaDex", lang = "en", sourceId = 42L, itemType = DbItemType.Manga),
                    DbManga(id = 11L, name = "No SourceId Manga", source = "CustomSource", lang = "fr", sourceId = null, itemType = DbItemType.Manga),
                ),
                chapters = listOf(
                    DbChapter(id = 100L, mangaId = 10L, name = "Chapter 1", url = "/1"),
                    DbChapter(id = 101L, mangaId = 11L, name = "Chapter 1", url = "/1"),
                ),
            ),
        )

        // 1. Explicit sourceId in request takes highest precedence
        val reqExplicit = DownloadRequest(
            taskId = "task-1",
            chapterId = 100L,
            itemType = DbItemType.Manga,
            sourceId = 999L,
        )
        assertEquals("source-999", resolveDownloadSourceKey(reqExplicit, 1L, database))

        // 2. Resolved from database manga.sourceId
        val reqFromDb = DownloadRequest(
            taskId = "task-2",
            chapterId = 100L,
            itemType = DbItemType.Manga,
        )
        assertEquals("source-42", resolveDownloadSourceKey(reqFromDb, 2L, database))

        // 3. Resolved from database manga.source|lang when sourceId is null
        val reqNoSourceId = DownloadRequest(
            taskId = "task-3",
            chapterId = 101L,
            itemType = DbItemType.Manga,
        )
        assertEquals("source-CustomSource|fr", resolveDownloadSourceKey(reqNoSourceId, 3L, database))

        // 4. Fallback to sourceLabel when not in database
        val reqLabel = DownloadRequest(
            taskId = "task-4",
            chapterId = 9999L,
            itemType = DbItemType.Manga,
            sourceLabel = "FallbackSource",
        )
        assertEquals("source-FallbackSource", resolveDownloadSourceKey(reqLabel, 4L, database))

        // 5. Fallback to downloadId when unknown
        val reqUnknown = DownloadRequest(
            taskId = "",
            chapterId = 0L,
            itemType = DbItemType.Manga,
        )
        assertEquals("download-7", resolveDownloadSourceKey(reqUnknown, 7L, database))
    }

    @Test
    fun downloadStartDelayCalculatesBaseAndJitter() {
        assertEquals(0L, downloadStartDelayMs(0))
        assertEquals(0L, downloadStartDelayMs(-1))

        val mockRandomMin = object : Random() {
            override fun nextBits(bitCount: Int): Int = 0
            override fun nextDouble(): Double = 0.0
        }
        val mockRandomMax = object : Random() {
            override fun nextBits(bitCount: Int): Int = 0
            override fun nextDouble(): Double = 1.0
        }

        // Base 2 seconds = 2000 ms. Jitter ranges from 25% (500 ms) to 100% (2000 ms).
        val minDelay = downloadStartDelayMs(2, mockRandomMin)
        val maxDelay = downloadStartDelayMs(2, mockRandomMax)

        assertEquals(2500L, minDelay)
        assertEquals(4000L, maxDelay)
    }

    @Test
    fun perSourceSerializationPreventsConcurrentDownloadsFromSameSource() = runTest {
        val seed = seedDatabaseSnapshot()
        val database = databaseWithDownloadParents(
            seed.copy(
                settings = seed.settings.copy(
                    allowConcurrentDownloads = true,
                    concurrentDownloads = 4,
                    downloadDelaySeconds = 0,
                ),
            ),
            mapOf(10L to 100L, 11L to 100L, 20L to 200L),
        )

        val ch10Started = CompletableDeferred<Unit>()
        val ch10Blocker = CompletableDeferred<Unit>()
        val ch11Started = CompletableDeferred<Unit>()
        val ch20Started = CompletableDeferred<Unit>()

        val blockingHttp = object : HttpService {
            override suspend fun request(request: HttpRequest): HttpResponse =
                HttpResponse(statusCode = 200, headers = emptyMap(), body = "")

            override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse {
                if (request.url.contains("ch10")) {
                    ch10Started.complete(Unit)
                    ch10Blocker.await()
                } else if (request.url.contains("ch11")) {
                    ch11Started.complete(Unit)
                } else if (request.url.contains("ch20")) {
                    ch20Started.complete(Unit)
                }
                onChunk("test-content".encodeToByteArray())
                return HttpStreamResponse(statusCode = 200, headers = emptyMap())
            }
        }

        val downloader = downloader(
            database,
            blockingHttp,
            mapOf(
                10L to "https://example.com/ch10/page1.jpg",
                11L to "https://example.com/ch11/page1.jpg",
                20L to "https://example.com/ch20/page1.jpg",
            ),
        )
        downloader.initialize(poolSize = 4)

        // Enqueue Chapter 10 (Source 100)
        downloader.enqueue(
            DownloadRequest(
                taskId = "task-10",
                chapterId = 10L,
                itemType = DbItemType.Manga,
                chapterName = "Chapter 10",
                sourceId = 100L,
            ),
        ) {}

        // Enqueue Chapter 11 (Same Source 100)
        downloader.enqueue(
            DownloadRequest(
                taskId = "task-11",
                chapterId = 11L,
                itemType = DbItemType.Manga,
                chapterName = "Chapter 11",
                sourceId = 100L,
            ),
        ) {}

        // Enqueue Chapter 20 (Different Source 200)
        downloader.enqueue(
            DownloadRequest(
                taskId = "task-20",
                chapterId = 20L,
                itemType = DbItemType.Manga,
                chapterName = "Chapter 20",
                sourceId = 200L,
            ),
        ) {}

        // Wait for ch10 to start
        withTimeout(5_000) { ch10Started.await() }
        assertFalse(downloader.activeDownloadProgress.value.single { it.taskId == "task-10" }.isPaused)
        downloader.pause("task-10")
        assertTrue(downloader.activeDownloadProgress.value.single { it.taskId == "task-10" }.isPaused)
        downloader.resume("task-10")
        assertFalse(downloader.activeDownloadProgress.value.single { it.taskId == "task-10" }.isPaused)

        // Chapter 20 (different source) should run in parallel even while Chapter 10 is blocked
        withTimeout(5_000) { ch20Started.await() }

        // Chapter 11 (same source 100) MUST NOT have started while Chapter 10 is active
        assertFalse(ch11Started.isCompleted, "Chapter 11 from the same source should be serialized and not start yet")

        // Unblock Chapter 10
        ch10Blocker.complete(Unit)

        // Now Chapter 11 should start
        withTimeout(5_000) { ch11Started.await() }
        assertTrue(ch11Started.isCompleted)
    }

    @Test
    fun allowConcurrentDownloadsFalseEnforcesGlobalSingleConcurrency() = runTest {
        val seed = seedDatabaseSnapshot()
        val database = databaseWithDownloadParents(
            seed.copy(
                settings = seed.settings.copy(
                    allowConcurrentDownloads = false, // Concurrency disabled
                    concurrentDownloads = 5,
                    downloadDelaySeconds = 0,
                ),
            ),
            mapOf(1L to 100L, 2L to 200L),
        )

        val task1Started = CompletableDeferred<Unit>()
        val task1Blocker = CompletableDeferred<Unit>()
        val task2Started = CompletableDeferred<Unit>()

        val blockingHttp = object : HttpService {
            override suspend fun request(request: HttpRequest): HttpResponse =
                HttpResponse(statusCode = 200, headers = emptyMap(), body = "")

            override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse {
                if (request.url.contains("task1")) {
                    task1Started.complete(Unit)
                    task1Blocker.await()
                } else if (request.url.contains("task2")) {
                    task2Started.complete(Unit)
                }
                onChunk("test-content".encodeToByteArray())
                return HttpStreamResponse(statusCode = 200, headers = emptyMap())
            }
        }

        val downloader = downloader(database, blockingHttp, mapOf(1L to "https://example.com/task1/p.jpg", 2L to "https://example.com/task2/p.jpg"))
        downloader.initialize(poolSize = 1)

        downloader.enqueue(
            DownloadRequest(
                taskId = "task-1",
                chapterId = 1L,
                itemType = DbItemType.Manga,
                chapterName = "Task 1",
                sourceId = 100L,
            ),
        ) {}

        downloader.enqueue(
            DownloadRequest(
                taskId = "task-2",
                chapterId = 2L,
                itemType = DbItemType.Manga,
                chapterName = "Task 2",
                sourceId = 200L, // Different source
            ),
        ) {}

        withTimeout(5_000) { task1Started.await() }

        // Give a short delay to see if task2 starts
        delay(100)
        assertFalse(task2Started.isCompleted, "Task 2 must not start while Task 1 is running when concurrency is disabled")

        // Unblock task 1
        task1Blocker.complete(Unit)

        // Now task 2 runs
        withTimeout(5_000) { task2Started.await() }
        assertTrue(task2Started.isCompleted)
    }

    @Test
    fun stalledStreamFailsTheChapterInsteadOfStayingInProgress() = runTest {
        val database = databaseWithDownloadParents(seedDatabaseSnapshot(), mapOf(555L to 100L))
        var attempts = 0
        // What Ktor's socket timeout surfaces when a connection stops sending mid-page.
        val stallingHttp = object : HttpService {
            override suspend fun request(request: HttpRequest) = HttpResponse(statusCode = 200, headers = emptyMap(), body = "")
            override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse {
                attempts += 1
                onChunk("partial".encodeToByteArray())
                throw IllegalStateException("Socket timeout has expired")
            }
        }
        val downloader = downloader(database, stallingHttp, mapOf(555L to "https://example.com/p1.jpg"))

        downloader.enqueue(DownloadRequest(taskId = "stall-task", chapterId = 555L, itemType = DbItemType.Manga, retries = 1))
        advanceUntilIdle()

        assertEquals(2, attempts)
        val downloadRecord = database.downloads().single { it.chapterId == 555L }
        assertFalse(downloadRecord.isDownload == true, "isDownload should be false on failure")
        assertFalse(downloadRecord.isStartDownload == true, "isStartDownload should be false on failure")
        assertTrue((downloadRecord.failed ?: 0) >= 1, "failed count should be at least 1")
        assertTrue(downloader.activeDownloads().isEmpty(), "a failed chapter must not stay in progress")
    }

    @Test
    fun downloadQueueOrderSortsExplicitIdsFirstThenArrivalOrder() {
        val d1 = eu.friedcutlet.yokan.database.DbDownload(id = 10L, chapterId = 10L)
        val d2 = eu.friedcutlet.yokan.database.DbDownload(id = 20L, chapterId = 20L)
        val d3 = eu.friedcutlet.yokan.database.DbDownload(id = 30L, chapterId = 30L)
        val d4 = eu.friedcutlet.yokan.database.DbDownload(id = 40L, chapterId = 40L)
        val items = listOf(d1, d2, d3, d4)

        // Empty order preserves incoming list
        assertEquals(items, DownloadQueueOrder.sorted(items, emptyList()))

        // Manual order [30, 10] puts 30 and 10 first, then 20 and 40 in original order
        val sorted = DownloadQueueOrder.sorted(items, listOf(30L, 10L))
        assertEquals(listOf(30L, 10L, 20L, 40L), sorted.map { it.id })
    }

    @Test
    fun downloadServiceReorderQueuePrioritizesMovedTask() = runTest {
        val seed = seedDatabaseSnapshot()
        val database = databaseWithDownloadParents(
            seed.copy(
                settings = seed.settings.copy(
                    allowConcurrentDownloads = false,
                    concurrentDownloads = 1,
                    downloadDelaySeconds = 0,
                ),
            ),
            mapOf(1L to 100L, 2L to 100L, 3L to 100L),
        )

        val task1Started = CompletableDeferred<Unit>()
        val task1Blocker = CompletableDeferred<Unit>()
        val executionOrder = mutableListOf<String>()

        val testHttp = object : HttpService {
            override suspend fun request(request: HttpRequest) =
                HttpResponse(statusCode = 200, headers = emptyMap(), body = "")

            override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse {
                if (request.url.contains("task1")) {
                    executionOrder.add("task1")
                    task1Started.complete(Unit)
                    task1Blocker.await()
                } else if (request.url.contains("task2")) {
                    executionOrder.add("task2")
                } else if (request.url.contains("task3")) {
                    executionOrder.add("task3")
                }
                onChunk("ok".encodeToByteArray())
                return HttpStreamResponse(statusCode = 200, headers = emptyMap())
            }
        }

        val downloader = downloader(
            database,
            testHttp,
            mapOf(
                1L to "https://example.com/task1/1.jpg",
                2L to "https://example.com/task2/1.jpg",
                3L to "https://example.com/task3/1.jpg",
            ),
        )
        downloader.initialize(poolSize = 1)

        val task2Done = CompletableDeferred<Unit>()
        val task3Done = CompletableDeferred<Unit>()

        // 1. Enqueue task 1 (starts immediately and blocks)
        downloader.enqueue(
            DownloadRequest(
                taskId = "task1",
                chapterId = 1L,
                itemType = DbItemType.Manga,
                chapterName = "Task 1",
            ),
        ) {}

        withTimeout(5_000) { task1Started.await() }

        // 2. Enqueue task 2 and task 3 (they wait in queue)
        downloader.enqueue(
            DownloadRequest(
                taskId = "task2",
                chapterId = 2L,
                itemType = DbItemType.Manga,
                chapterName = "Task 2",
            ),
        ) { if (it.isCompleted) task2Done.complete(Unit) }

        downloader.enqueue(
            DownloadRequest(
                taskId = "task3",
                chapterId = 3L,
                itemType = DbItemType.Manga,
                chapterName = "Task 3",
            ),
        ) { if (it.isCompleted) task3Done.complete(Unit) }

        // Find downloadId for task 3 to prioritize it over task 2
        val d3 = database.downloads().first { it.chapterId == 3L }
        val d2 = database.downloads().first { it.chapterId == 2L }

        // 3. Reorder queue putting task 3 ahead of task 2
        downloader.reorderQueue(listOf(d3.id, d2.id))

        // 4. Release task 1
        task1Blocker.complete(Unit)

        withTimeout(5_000) {
            task3Done.await()
            task2Done.await()
        }

        // Task 3 must have run BEFORE Task 2
        assertEquals(listOf("task1", "task3", "task2"), executionOrder)
    }

    @Test
    fun promotionExceptionReportsFailureAndQueueContinues() = runTest {
        val seed = seedDatabaseSnapshot()
        val database = databaseWithDownloadParents(
            seed.copy(
                settings = seed.settings.copy(
                    allowConcurrentDownloads = false,
                    concurrentDownloads = 1,
                    downloadDelaySeconds = 0,
                ),
            ),
            mapOf(1L to 100L, 2L to 100L),
        )
        val files = PromotionFailingFiles(failuresRemaining = 1)
        val failed = CompletableDeferred<DownloadProgress>()
        val completed = CompletableDeferred<Unit>()
        val executionOrder = mutableListOf<String>()
        val http = object : HttpService {
            override suspend fun request(request: HttpRequest) =
                HttpResponse(statusCode = 200, headers = emptyMap(), body = "")

            override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse {
                executionOrder += request.url.substringAfter("/task").substringBefore('/')
                onChunk("ok".encodeToByteArray())
                return HttpStreamResponse(statusCode = 200, headers = emptyMap())
            }
        }
        val downloader = downloader(
            database,
            http,
            mapOf(1L to "https://example.com/task1/1.jpg", 2L to "https://example.com/task2/1.jpg"),
            files,
        )
        downloader.initialize(poolSize = 1)

        downloader.enqueue(
            DownloadRequest(
                taskId = "task1",
                chapterId = 1L,
                itemType = DbItemType.Manga,
                retries = 0,
            ),
        ) { progress ->
            if (progress.failed > 0 && !failed.isCompleted) failed.complete(progress)
        }
        downloader.enqueue(
            DownloadRequest(
                taskId = "task2",
                chapterId = 2L,
                itemType = DbItemType.Manga,
                retries = 0,
            ),
        ) { progress ->
            if (progress.isCompleted && progress.failed == 0 && !completed.isCompleted) completed.complete(Unit)
        }

        withTimeout(5_000) {
            failed.await()
            completed.await()
        }
        assertEquals(listOf("1", "2"), executionOrder)
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/download/DownloadKeepAliveTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/download/DownloadKeepAliveTest.kt) · test / fixture · 17 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
7: class DownloadKeepAliveTest {
9: fun processStaysForegroundOnlyWhileDownloadsArePendingAndNotWaitingForWifi() {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/download/DownloadKeepAliveTest.kt) · SHA-256 `6fa37ed7abfc4141600a56da2ee08e7ecb83b2caa3517a2e0c713e51ac5e48fc`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.download

import kotlin.test.Test
import kotlin.test.assertFalse
import kotlin.test.assertTrue

class DownloadKeepAliveTest {
    @Test
    fun processStaysForegroundOnlyWhileDownloadsArePendingAndNotWaitingForWifi() {
        assertFalse(needsKeepAlive(DownloadQueueStatus()), "an empty or fully paused queue lets the service stop")
        assertTrue(needsKeepAlive(DownloadQueueStatus(pending = 1)))
        assertFalse(
            needsKeepAlive(DownloadQueueStatus(pending = 3, waitingForWifi = true)),
            "a queue waiting for Wi-Fi resumes through the network-constrained job instead",
        )
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/download/DownloadMetadataExportTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/download/DownloadMetadataExportTest.kt) · test / fixture · 69 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 DownloadMetadataExportTest {
22: fun controlCharactersInMetadataStillWriteParseableJson() = runTest {
34: fun cancellationDuringMetadataWritePropagates() = runTest {
36: override fun writeBytes(path: String, bytes: ByteArray) = throw CancellationException("stopped")
43: fun cancellationDuringPromotionPropagatesInsteadOfFailingThePage() = runTest {
45: override fun promote(sourcePath: String, targetPath: String): Boolean = throw CancellationException("stopped")
61: private fun request(metadata: Map<String, String>) = DownloadRequest(
```

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

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.download

import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import eu.friedcutlet.yokan.services.files.MemoryFiles
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.RecordingHttpService
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive

class DownloadMetadataExportTest {
    @Test
    fun controlCharactersInMetadataStillWriteParseableJson() = runTest {
        val files = MemoryFiles()
        val metadata = mapOf("name" to "Title\u0001 \"quoted\"\n", "author" to "A\\B")

        writeMetadata(files, request(metadata), "/downloads/Title/Chapter")

        val json = Json.parseToJsonElement(files.readBytes("/downloads/Title/Chapter/metadata.json").decodeToString()).jsonObject
        assertEquals(listOf("author", "name"), json.keys.toList())
        assertEquals(metadata, json.mapValues { it.value.jsonPrimitive.content })
    }

    @Test
    fun cancellationDuringMetadataWritePropagates() = runTest {
        val files = object : MemoryFiles() {
            override fun writeBytes(path: String, bytes: ByteArray) = throw CancellationException("stopped")
        }

        assertFailsWith<CancellationException> { writeMetadata(files, request(mapOf("name" to "Title")), "/downloads/Title") }
    }

    @Test
    fun cancellationDuringPromotionPropagatesInsteadOfFailingThePage() = runTest {
        val files = object : MemoryFiles() {
            override fun promote(sourcePath: String, targetPath: String): Boolean = throw CancellationException("stopped")
        }
        val transfer = PageTransfer(
            database = InMemoryYokanDatabase(seedDatabaseSnapshot()),
            http = RecordingHttpService { HttpResponse(statusCode = 404, body = "") },
            files = files,
            imageHttp = RecordingHttpService { HttpResponse(statusCode = 404, body = "") },
            imageDataSaver = null,
            ioDispatcher = StandardTestDispatcher(testScheduler),
            awaitAllowedNetwork = {},
        )

        assertFailsWith<CancellationException> { transfer.promoteWithMarker("/d/0001.jpg.part", "/d/0001.jpg", "/d/0001.jpg.complete") }
        assertFalse(files.exists("/d/0001.jpg.complete"))
    }

    private fun request(metadata: Map<String, String>) = DownloadRequest(
        taskId = "metadata-task",
        chapterId = 1L,
        itemType = DbItemType.Manga,
        mangaName = "Title",
        chapterName = "Chapter",
        metadata = metadata,
    )
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/download/DownloadPolicyTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/download/DownloadPolicyTest.kt) · test / fixture · 147 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
6: class DownloadPolicyTest {
138: internal fun policySnapshot(policy: DbDownloadPolicy = DbDownloadPolicy()): YokanDatabaseSnapshot = seedDatabaseSnapshot().copy(
146: internal fun YokanDatabaseSnapshot.withPolicy(policy: DbDownloadPolicy): YokanDatabaseSnapshot =
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/download/DownloadPolicyTest.kt) · SHA-256 `60b9e294f93b16c2140fa5bc8049d386cf2eff8d1bbfa0b8e09bfdb3e98d9e16`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.download

import eu.friedcutlet.yokan.database.*
import kotlin.test.*

class DownloadPolicyTest {
    @Test fun downloadNamesNeverCreateParentOrCurrentDirectorySegments() {
        assertEquals("_", sanitizeDownloadName(".."))
        assertEquals("_", sanitizeDownloadName(" . "))
        assertEquals("_", sanitizeDownloadName(" "))
        assertEquals("Title_Chapter", sanitizeDownloadName("Title/Chapter"))
    }
    @Test fun defaultsDoNotDownloadOrDeleteAnything() {
        val snapshot = policySnapshot()
        assertEquals(emptyList(), automaticDownloadCandidates(snapshot, setOf(10, 11)))
        assertEquals(emptyList(), downloadAheadCandidates(snapshot, 10))
        assertEquals(emptyList(), downloadCleanupCandidates(snapshot, 1, DownloadCleanupReason.Consumption, emptySet()))
    }

    @Test fun automaticDownloadsApplyCategoriesUnreadFillerAndSourceRules() {
        val policy = DbDownloadPolicy(autoDownloadNew = true, includeCategoryIds = setOf(5))
        val snapshot = policySnapshot(policy).let { it.copy(chapters = it.chapters.map { c -> when (c.id) {
            11L -> c.copy(isRead = true)
            12L -> c.copy(isFiller = true)
            else -> c
        } }) }
        assertEquals(listOf(10L, 13L, 14L), automaticDownloadCandidates(snapshot, snapshot.chapters.mapTo(mutableSetOf()) { it.id }))
        assertEquals(emptyList(), automaticDownloadCandidates(snapshot.withPolicy(policy.copy(excludeCategoryIds = setOf(5))), setOf(10)))
        assertEquals(emptyList(), automaticDownloadCandidates(snapshot.copy(sources = snapshot.sources.map { it.copy(isActive = false) }), setOf(10)))
        assertEquals(emptyList(), automaticDownloadCandidates(snapshot.copy(mangas = snapshot.mangas.map { it.copy(favorite = false) }), setOf(10)))
        assertEquals(emptyList(), automaticDownloadCandidates(snapshot.copy(mangas = snapshot.mangas.map { it.copy(isLocalArchive = true) }), setOf(10)))
        assertEquals(listOf(11L, 12L), automaticDownloadCandidates(snapshot.withPolicy(policy.copy(unreadOnly = false, includeFiller = true)), setOf(11, 12)))
    }

    @Test fun stoppedPausedFailedAndCompletedRowsAreNeverAutomaticallyRequeued() {
        val snapshot = policySnapshot(DbDownloadPolicy(autoDownloadNew = true)).copy(downloads = listOf(
            DbDownload(id = 1, chapterId = 10, isPaused = true),
            DbDownload(id = 2, chapterId = 11, failed = 1),
            DbDownload(id = 3, chapterId = 12, isDownload = true),
            DbDownload(id = 4, chapterId = 13, isStartDownload = false),
        ))
        assertEquals(listOf(14L), automaticDownloadCandidates(snapshot, setOf(10, 11, 12, 13, 14)))
    }

    @Test fun aheadUsesReadingOrderAndExistingRowsCountTowardWindow() {
        val snapshot = policySnapshot(DbDownloadPolicy(aheadManga = 2)).let { it.copy(
            chapters = it.chapters.reversed(),
            downloads = listOf(DbDownload(chapterId = 11, isPaused = true)),
        ) }
        assertEquals(listOf(12L), downloadAheadCandidates(snapshot, 10))
        assertEquals(emptyList(), downloadAheadCandidates(snapshot.copy(settings = snapshot.settings.copy(incognitoMode = true)), 10))
    }

    @Test fun aheadAppliesPerMediaCountsAndSkipsReadAndFiller() {
        for (type in DbItemType.entries) {
            val snapshot = policySnapshot(DbDownloadPolicy(aheadManga = 2, aheadAnime = 2, aheadNovel = 2)).let { it.copy(
                mangas = it.mangas.map { m -> m.copy(itemType = type) },
                chapters = it.chapters.map { c -> when (c.id) { 11L -> c.copy(isRead = true); 12L -> c.copy(isFiller = true); else -> c } },
            ) }
            assertEquals(listOf(13L, 14L), downloadAheadCandidates(snapshot, 10), type.name)
        }
    }

    @Test fun manualFillerMarksOverrideTheSourceValueForAutomaticAndAheadDownloads() {
        val policy = DbDownloadPolicy(autoDownloadNew = true, includeCategoryIds = setOf(5), aheadManga = 2)
        val snapshot = policySnapshot(policy).let { it.copy(chapters = it.chapters.map { c -> when (c.id) {
            11L -> c.copy(fillerOverride = true)
            12L -> c.copy(isFiller = true, fillerOverride = false)
            else -> c
        } }) }
        assertEquals(listOf(10L, 12L, 13L, 14L), automaticDownloadCandidates(snapshot, snapshot.chapters.mapTo(mutableSetOf()) { it.id }))
        assertEquals(listOf(12L, 13L), downloadAheadCandidates(snapshot, 10))
        // A manually marked filler that is currently open still drives download-ahead.
        assertEquals(listOf(12L, 13L), downloadAheadCandidates(snapshot, 11))
        assertEquals(listOf(11L, 12L), automaticDownloadCandidates(snapshot.withPolicy(policy.copy(includeFiller = true)), setOf(11, 12)))
    }

    @Test fun cleanupRequiresConsumptionProofAndRespectsRetentionAndBookmarks() {
        val policy = DbDownloadPolicy(cleanupAfterConsumption = true, consumedChapterIds = setOf(10, 11, 12, 13, 14), keepLastConsumed = 1)
        val snapshot = policySnapshot(policy).let { it.copy(
            chapters = it.chapters.map { c -> c.copy(isRead = true, isBookmarked = c.id == 11L) },
            downloads = it.chapters.map { c -> DbDownload(id = c.id, chapterId = c.id, isDownload = true) },
        ) }
        assertEquals(listOf(10L, 12L), downloadCleanupCandidates(snapshot, 1, DownloadCleanupReason.Consumption, setOf(13)))
        assertEquals(emptyList(), downloadCleanupCandidates(snapshot.withPolicy(policy.copy(consumedChapterIds = emptySet())), 1, DownloadCleanupReason.Consumption, emptySet()))
        assertEquals(emptyList(), downloadCleanupCandidates(snapshot.withPolicy(policy.copy(cleanupExcludedCategoryIds = setOf(5))), 1, DownloadCleanupReason.Consumption, emptySet()))
        assertEquals(emptyList(), downloadCleanupCandidates(snapshot.copy(mangas = snapshot.mangas.map { it.copy(isLocalArchive = true) }), 1, DownloadCleanupReason.Consumption, emptySet()))
    }

    @Test fun manualCleanupIsIndependentAndProtectsIncompleteOrPausedWork() {
        val snapshot = policySnapshot(DbDownloadPolicy(cleanupAfterManualMark = true, manuallyMarkedChapterIds = setOf(10, 11, 12, 13))).let { it.copy(
            chapters = it.chapters.map { c -> c.copy(isRead = true) },
            downloads = listOf(
                DbDownload(chapterId = 10, isDownload = true),
                DbDownload(chapterId = 11, isDownload = true, isStartDownload = true),
                DbDownload(chapterId = 12, isDownload = true, isPaused = true),
                DbDownload(chapterId = 13, isDownload = false),
            ),
        ) }
        assertEquals(listOf(10L), downloadCleanupCandidates(snapshot, 1, DownloadCleanupReason.ManualMark, emptySet()))
        assertEquals(emptyList(), downloadCleanupCandidates(snapshot, 1, DownloadCleanupReason.Consumption, emptySet()))
    }

    @Test fun legacyDeletePreferenceUsesNewProtections() {
        val snapshot = policySnapshot(DbDownloadPolicy(consumedChapterIds = setOf(10))).let { it.copy(
            settings = it.settings.copy(deleteDownloadAfterReading = true),
            chapters = it.chapters.map { c -> c.copy(isRead = true) },
            downloads = listOf(DbDownload(chapterId = 10, isDownload = true)),
        ) }
        assertEquals(listOf(10L), downloadCleanupCandidates(snapshot, 1, DownloadCleanupReason.Consumption, emptySet()))
    }

    @Test fun automaticDownloadsUseConfiguredReleasePriorityRatherThanEveryDuplicate() {
        val snapshot = policySnapshot(DbDownloadPolicy(autoDownloadNew = true)).let { it.copy(
            chapters = listOf(
                DbChapter(id = 10, mangaId = 1, name = "Chapter 1", scanlator = "Other"),
                DbChapter(id = 11, mangaId = 1, name = "Chapter 1", scanlator = "Preferred"),
            ),
            settings = it.settings.copy(chapterReleasePreferences = listOf(DbChapterReleasePreference(mangaId = 1, scanlatorPriority = listOf("Preferred"), skipDuplicateReleases = true))),
        ) }
        assertEquals(listOf(11L), automaticDownloadCandidates(snapshot, setOf(10, 11)))
    }

    @Test fun cleanupIncludesConsumedAlternatesAndRetentionKeepsEveryVariantOfRetainedChapter() {
        val snapshot = policySnapshot(DbDownloadPolicy(cleanupAfterConsumption = true, consumedChapterIds = setOf(10, 11, 12), keepLastConsumed = 1)).let { it.copy(
            chapters = listOf(
                DbChapter(id = 10, mangaId = 1, name = "Chapter 1", scanlator = "Other", isRead = true),
                DbChapter(id = 11, mangaId = 1, name = "Chapter 2", scanlator = "Preferred", isRead = true),
                DbChapter(id = 12, mangaId = 1, name = "Chapter 2", scanlator = "Other", isRead = true),
            ),
            downloads = (10L..12L).map { id -> DbDownload(id = id, chapterId = id, isDownload = true) },
            settings = it.settings.copy(chapterReleasePreferences = listOf(DbChapterReleasePreference(mangaId = 1, scanlatorPriority = listOf("Preferred"), skipDuplicateReleases = true))),
        ) }
        assertEquals(listOf(10L), downloadCleanupCandidates(snapshot, 1, DownloadCleanupReason.Consumption, emptySet()))
    }
}

internal fun policySnapshot(policy: DbDownloadPolicy = DbDownloadPolicy()): YokanDatabaseSnapshot = seedDatabaseSnapshot().copy(
    settings = DbSettings(features = DbFeaturePreferences(downloads = policy)),
    mangas = listOf(DbManga(id = 1, name = "Title", sourceId = 7, favorite = true, categories = listOf(5), itemType = DbItemType.Manga)),
    sources = listOf(DbSource(id = 7, name = "Source", isAdded = true)),
    chapters = (10L..14L).map { DbChapter(id = it, mangaId = 1, name = "Chapter $it", url = "/$it") },
    downloads = emptyList(),
)

internal fun YokanDatabaseSnapshot.withPolicy(policy: DbDownloadPolicy): YokanDatabaseSnapshot =
    copy(settings = settings.copy(features = settings.features.copy(downloads = policy)))
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/download/ExternalDownloadsTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/download/ExternalDownloadsTest.kt) · test / fixture · 326 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
13: class ExternalDownloadsTest {
246: private class Fixture(private val test: TestScope, private val polling: Boolean = false) {
256: override suspend fun awaitPersistence() { check(!failPersistence) { "disk failure" }; durable += prefs().jobs }
266: fun newService(database: YokanDatabase = db) = ExternalDownloads(database, server, scope, { _, forced -> beforeResolve(); forcedRefresh = forced; pages }, clock = { test.testScheduler.currentTime }, startPolling = polling)
267: fun prefs() = memory.settings().features.externalDownloads
268: fun job() = prefs().jobs.single()
269: fun updatePrefs(change: (DbExternalDownloads) -> DbExternalDownloads) { val old = memory.settings(); memory.updateSettings(old.copy(features = old.features.copy(externalDownloads = change(prefs())))) }
272: private class Server : HttpService {
282: override suspend fun request(request: HttpRequest): HttpResponse {
287: private fun answer(call: JsonObject): JsonObject {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/download/ExternalDownloadsTest.kt) · SHA-256 `2e06aed2cd74af479b5bdd50cec8d6b710d11f0aea483510635f9f470f8e2d48`.

### Complete file

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

package eu.friedcutlet.yokan.services.download

import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.services.http.*
import kotlinx.coroutines.*
import kotlinx.coroutines.test.*
import kotlinx.coroutines.flow.collect
import kotlinx.serialization.json.*
import kotlin.test.*

class ExternalDownloadsTest {
    @Test fun oldServerReceiptsCannotDelayNewServerAdmissions() = runTest {
        val f = Fixture(this)
        for (id in 1L..6L) {
            f.db.upsertChapter(DbChapter(id = id, mangaId = 1, name = "Chapter $id"))
            f.service.enqueue(f.request.copy(chapterId = id))
        }
        f.updatePrefs { it.copy(endpoint = "https://new-aria.example.org/jsonrpc", secret = "new-account") }
        f.service.enqueue(f.request)
        f.service.reconcile()
        assertEquals(1, f.server.adds)
        assertEquals(6, f.prefs().jobs.count { it.problem == RemoteDownloadProblem.ServerChanged })
        assertEquals(listOf("token:new-account"), f.server.tokens)
    }
    @Test fun idleQueueDoesNotPollAndPersistedProgressDoesNotCreateATightRequestLoop() = runTest {
        val f = Fixture(this, polling = true)
        runCurrent()
        advanceTimeBy(10_000); runCurrent()
        assertTrue(f.server.methods.isEmpty())
        backgroundScope.launch { f.service.jobs.collect {} }
        f.service.enqueue(f.request); runCurrent()
        assertEquals(1, f.server.adds)
        val afterAdmission = f.server.methods.size
        advanceTimeBy(1999); runCurrent()
        assertEquals(afterAdmission, f.server.methods.size)
        advanceTimeBy(1); runCurrent()
        assertEquals(afterAdmission + 1, f.server.methods.size)
    }

    @Test fun acceptedServerWorkDoesNotPollWhenQueueIsNotVisible() = runTest {
        val f = Fixture(this, polling = true)
        f.service.enqueue(f.request); runCurrent()
        assertEquals(1, f.server.methods.size)
        advanceTimeBy(20_000); runCurrent()
        assertEquals(1, f.server.methods.size)
        val watching = backgroundScope.launch { f.service.jobs.collect {} }
        runCurrent()
        assertEquals(2, f.server.methods.size)
        watching.cancelAndJoin()
        advanceTimeBy(20_000); runCurrent()
        assertEquals(2, f.server.methods.size)
    }

    @Test fun retiringOneProfileDoesNotAffectAnotherProfilesRemoteQueue() = runTest {
        val first = Fixture(this); val second = Fixture(this)
        first.updatePrefs { it.copy(secret = "profile-one") }
        second.updatePrefs { it.copy(secret = "profile-two") }
        first.service.enqueue(first.request); first.service.reconcile()
        second.service.enqueue(second.request); second.service.reconcile()
        assertNotEquals(first.job().accountBinding, second.job().accountBinding)
        assertNotEquals(first.job().files.single().gid, second.job().files.single().gid)
        first.owner.cancelAndJoin()
        assertFailsWith<CancellationException> { first.service.reconcile() }
        second.server.states[second.job().files.single().gid] = "complete"
        second.service.reconcile()
        assertTrue(second.job().complete)
        assertTrue(first.server.tokens.all { it == "token:profile-one" })
        assertTrue(second.server.tokens.all { it == "token:profile-two" })
    }
    @Test fun admissionsAreDurableAndCompletionNeverCreatesLocalOfflineMarks() = runTest {
        val f = Fixture(this)
        f.server.onAdd = { gid -> assertTrue(f.durable.any { jobs -> jobs.any { job -> job.files.any { it.gid == gid && it.state == RemoteDownloadState.Submitting } } }) }
        assertTrue(f.service.enqueue(f.request))
        val receipt = f.job()
        assertEquals(RemoteDownloadState.Pending, receipt.files.single().state)
        f.service.reconcile()
        assertEquals(RemoteDownloadState.Waiting, f.job().files.single().state)
        assertTrue(f.job().files.single().url.isBlank())
        f.server.states[f.job().files.single().gid] = "complete"
        f.service.reconcile()
        assertTrue(f.job().complete)
        assertTrue(f.db.downloads().isEmpty())
        assertEquals("", f.db.chapter(1)?.archivePath)
        assertEquals(1, f.server.adds)
    }

    @Test fun lostAdmissionReplyIsRecoveredByGidInsteadOfSubmittingAnotherTask() = runTest {
        val f = Fixture(this)
        f.server.loseAddReply = true
        f.service.enqueue(f.request)
        assertFails { f.service.reconcile() }
        assertEquals(RemoteDownloadState.Submitting, f.job().files.single().state)
        val encoded = DatabaseJson.encodeToString(DbSettings.serializer(), f.db.settings())
        val restarted = InMemoryYokanDatabase(f.db.snapshot().copy(settings = DatabaseJson.decodeFromString(DbSettings.serializer(), encoded)))
        val recovered = f.newService(restarted)
        recovered.reconcile()
        val restored = restarted.settings().features.externalDownloads.jobs.single()
        assertEquals(RemoteDownloadState.Active, restored.files.single().state)
        assertEquals(1, f.server.adds)
        assertTrue(restored.files.single().headers.isEmpty())
    }

    @Test fun unverifiedMissingTaskRequiresAttentionAndNeverBlindlyRetries() = runTest {
        val f = Fixture(this)
        f.server.rejectBeforeAdmission = true
        f.service.enqueue(f.request)
        assertFails { f.service.reconcile() }
        val recovered = f.newService()
        recovered.reconcile()
        assertEquals(RemoteDownloadState.Attention, f.job().files.single().state)
        assertEquals(RemoteDownloadProblem.MissingOrRejected, f.job().problem)
        assertFails { recovered.retry(f.job().id) }
        recovered.reconcile()
        assertEquals(1, f.server.adds)
    }

    @Test fun pauseResumeCancelAndRemovalOnlyTouchOwnedRemoteTasks() = runTest {
        val f = Fixture(this)
        f.service.enqueue(f.request); f.service.reconcile()
        val id = f.job().id
        val gid = f.job().files.single().gid
        f.server.states["1111111111111111"] = "active"
        f.service.setIntent(id, RemoteDownloadIntent.Pause); f.service.reconcile(id)
        assertEquals("paused", f.server.states[gid])
        f.service.setIntent(id, RemoteDownloadIntent.Run); f.service.reconcile(id)
        assertEquals("waiting", f.server.states[gid])
        f.service.setIntent(id, RemoteDownloadIntent.Cancel); f.service.reconcile(id); f.service.reconcile(id)
        assertEquals("removed", f.server.states[gid])
        assertTrue(f.job().terminal)
        f.service.remove(id)
        assertTrue(f.service.jobs.value.isEmpty())
        assertEquals("active", f.server.states["1111111111111111"])
        assertFalse(f.server.methods.any { it.endsWith("All") })
    }

    @Test fun accountChangesBlockOldControlsAndRestoringItResumesReconciliation() = runTest {
        val f = Fixture(this)
        f.service.enqueue(f.request); f.service.reconcile()
        val original = f.prefs()
        f.updatePrefs { it.copy(endpoint = "https://other.example.org/jsonrpc", secret = "different") }
        val requests = f.server.methods.size
        f.service.reconcile()
        assertEquals(requests, f.server.methods.size)
        assertEquals(RemoteDownloadProblem.ServerChanged, f.job().problem)
        f.updatePrefs { original.copy(jobs = it.jobs) }
        f.service.reconcile()
        assertEquals(RemoteDownloadProblem.None, f.job().problem)
    }

    @Test fun accountChangeDuringStatusQueryPreventsFollowingControlCommands() = runTest {
        val f = Fixture(this)
        f.service.enqueue(f.request); f.service.reconcile()
        f.service.setIntent(f.job().id, RemoteDownloadIntent.Pause)
        f.server.onStatus = { f.updatePrefs { it.copy(secret = "new account") } }
        f.service.reconcile()
        assertEquals(RemoteDownloadProblem.ServerChanged, f.job().problem)
        assertFalse("aria2.forcePause" in f.server.methods)
    }

    @Test fun confirmedErroredFilesRetryWithFreshUrlsAndNewIds() = runTest {
        val f = Fixture(this)
        f.service.enqueue(f.request); f.service.reconcile()
        val old = f.job().files.single().gid
        val oldName = f.job().files.single().name
        f.server.states[old] = "error"
        f.service.reconcile()
        assertEquals(RemoteDownloadState.Error, f.job().files.single().state)
        f.pages = listOf(DbPageUrl(url = "https://images.example.org/fresh.png", headers = mapOf("Referer" to "https://source.example.org/new")))
        f.service.retry(f.job().id)
        assertTrue(f.forcedRefresh)
        assertNotEquals(old, f.job().files.single().gid)
        assertNotEquals(oldName, f.job().files.single().name, "Changed resources must not append to an old partial file")
        f.service.reconcile()
        assertEquals(2, f.server.adds)
        assertEquals("error", f.server.states[old])
        assertEquals("https://images.example.org/fresh.png", f.server.lastUrl)
    }

    @Test fun replacingLibraryRowsWithReusedIdsCannotRetryAnOldRemoteJob() = runTest {
        val f = Fixture(this)
        f.service.enqueue(f.request); f.service.reconcile()
        f.server.states[f.job().files.single().gid] = "error"; f.service.reconcile()
        f.db.upsertManga(requireNotNull(f.db.manga(1)).copy(link = "https://other.example.org/title"))
        assertFailsWith<IllegalArgumentException> { f.service.retry(f.job().id) }
        assertEquals(1, f.server.adds)
    }

    @Test fun duplicateManualRequestsAreDeduplicatedAndHlsAndNovelsUseLocalBackend() = runTest {
        val f = Fixture(this)
        f.service.enqueue(f.request); f.service.enqueue(f.request)
        assertEquals(1, f.prefs().jobs.size)
        assertFalse(f.service.enqueue(f.request.copy(itemType = DbItemType.Novel)))
        val hls = Fixture(this)
        hls.pages = listOf(DbPageUrl(url = "https://video.example.org/master.m3u8?key=abc"))
        assertFalse(hls.service.enqueue(hls.request.copy(itemType = DbItemType.Anime)))
        assertTrue(hls.prefs().jobs.isEmpty())
    }

    @Test fun persistenceFailurePreventsRemoteAdmission() = runTest {
        val f = Fixture(this)
        f.failPersistence = true
        assertFails { f.service.enqueue(f.request) }
        assertFails { f.service.reconcile() }
        assertEquals(0, f.server.adds)
    }

    @Test fun ownerRetirementJoinsSourceWorkAndPreventsLateAdmission() = runTest {
        val f = Fixture(this)
        val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>()
        f.beforeResolve = { entered.complete(Unit); withContext(NonCancellable) { release.await() } }
        val task = async { f.service.enqueue(f.request) }
        entered.await()
        val retiring = launch { f.owner.cancelAndJoin() }
        runCurrent(); assertFalse(retiring.isCompleted)
        release.complete(Unit); retiring.join()
        assertFailsWith<CancellationException> { task.await() }
        assertTrue(f.prefs().jobs.isEmpty())
        assertEquals(0, f.server.adds)
        assertFailsWith<CancellationException> { f.service.testConnection() }
    }

    @Test fun queuePassesAreBoundedAndLargeChaptersDoNotStarveOtherJobs() = runTest {
        val f = Fixture(this)
        f.pages = (1..20).map { DbPageUrl(url = "https://images.example.org/$it.jpg") }
        f.service.enqueue(f.request)
        f.db.upsertChapter(DbChapter(id = 2, mangaId = 1, name = "Second"))
        f.service.enqueue(f.request.copy(chapterId = 2))
        f.service.reconcile()
        assertEquals(8, f.server.adds)
        assertTrue(f.prefs().jobs.all { it.files.count { file -> file.state == RemoteDownloadState.Waiting } == 4 })
    }

    @Test fun removingReceiptNeverCancelsOrDeletesServerFiles() = runTest {
        val f = Fixture(this)
        f.service.enqueue(f.request); f.service.reconcile()
        val gid = f.job().files.single().gid
        assertFails { f.service.remove(f.job().id) }
        f.service.remove(f.job().id, forgetUnverified = true)
        assertTrue(f.prefs().jobs.isEmpty())
        assertEquals("active", f.server.states[gid])
        assertFalse("aria2.forceRemove" in f.server.methods)
    }

    private class Fixture(private val test: TestScope, private val polling: Boolean = false) {
        val memory = InMemoryYokanDatabase(emptySnapshot()).apply {
            upsertSource(DbSource(id = 1, name = "Source"))
            upsertManga(DbManga(id = 1, name = "Title", sourceId = 1))
            upsertChapter(DbChapter(id = 1, mangaId = 1, name = "Chapter"))
            updateSettings(settings().let { it.copy(features = it.features.copy(externalDownloads = DbExternalDownloads(PreferredDownloader.Aria2, "https://aria.example.org/jsonrpc", "secret", "/downloads"))) })
        }
        val durable = mutableListOf<List<DbRemoteDownloadJob>>()
        var failPersistence = false
        val db = object : YokanDatabase by memory {
            override suspend fun awaitPersistence() { check(!failPersistence) { "disk failure" }; durable += prefs().jobs }
        }
        val owner = SupervisorJob(test.backgroundScope.coroutineContext[Job])
        private val scope = CoroutineScope(test.backgroundScope.coroutineContext + owner)
        val server = Server()
        var pages = listOf(DbPageUrl(url = "https://images.example.org/page.jpg", headers = mapOf("Referer" to "https://source.example.org")))
        var beforeResolve: suspend () -> Unit = {}
        var forcedRefresh = false
        val request = DownloadRequest("chapter-1", 1, DbItemType.Manga, mangaName = "Title", chapterName = "Chapter", sourceId = 1)
        val service = newService()
        fun newService(database: YokanDatabase = db) = ExternalDownloads(database, server, scope, { _, forced -> beforeResolve(); forcedRefresh = forced; pages }, clock = { test.testScheduler.currentTime }, startPolling = polling)
        fun prefs() = memory.settings().features.externalDownloads
        fun job() = prefs().jobs.single()
        fun updatePrefs(change: (DbExternalDownloads) -> DbExternalDownloads) { val old = memory.settings(); memory.updateSettings(old.copy(features = old.features.copy(externalDownloads = change(prefs())))) }
    }

    private class Server : HttpService {
        val states = mutableMapOf<String, String>()
        val methods = mutableListOf<String>()
        val tokens = mutableListOf<String>()
        var adds = 0
        var lastUrl = ""
        var loseAddReply = false
        var rejectBeforeAdmission = false
        var onAdd: (String) -> Unit = {}
        var onStatus: () -> Unit = {}
        override suspend fun request(request: HttpRequest): HttpResponse {
            val body = Json.parseToJsonElement(requireNotNull(request.body))
            val response = if (body is JsonArray) JsonArray(body.map { answer(it.jsonObject) }) else answer(body.jsonObject)
            return HttpResponse(200, response.toString())
        }
        private fun answer(call: JsonObject): JsonObject {
            val method = call.getValue("method").jsonPrimitive.content
            methods += method
            tokens += call.getValue("params").jsonArray.first().jsonPrimitive.content
            val params = call.getValue("params").jsonArray.drop(1)
            var missing = false
            val result: JsonElement = when (method) {
                "aria2.addUri" -> {
                    adds++
                    if (rejectBeforeAdmission) error("Connection failed before submission")
                    val options = params[1].jsonObject
                    val gid = options.getValue("gid").jsonPrimitive.content
                    onAdd(gid)
                    states[gid] = "active"; lastUrl = params[0].jsonArray.single().jsonPrimitive.content
                    if (loseAddReply) { loseAddReply = false; error("Lost acknowledgement") }
                    JsonPrimitive(gid)
                }
                "aria2.tellStatus" -> {
                    onStatus()
                    val gid = params[0].jsonPrimitive.content
                    val status = states[gid]
                    if (status == null) { missing = true; JsonNull } else buildJsonObject {
                        put("gid", gid); put("status", status); put("totalLength", "100"); put("completedLength", if (status == "complete") "100" else "50"); put("downloadSpeed", "10"); put("errorCode", if (status == "error") "3" else "0")
                    }
                }
                "aria2.forcePause", "aria2.unpause", "aria2.forceRemove" -> {
                    val gid = params[0].jsonPrimitive.content
                    states[gid] = when (method) { "aria2.forcePause" -> "paused"; "aria2.unpause" -> "waiting"; else -> "removed" }
                    JsonPrimitive(gid)
                }
                "aria2.getVersion" -> buildJsonObject { put("version", "1.37.0") }
                else -> error("Unexpected method $method")
            }
            return buildJsonObject {
                put("jsonrpc", "2.0"); put("id", call.getValue("id"))
                if (missing) put("error", buildJsonObject { put("code", 1); put("message", "GID not found") }) else put("result", result)
            }
        }
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/download/HlsPlaylistTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/download/HlsPlaylistTest.kt) · test / fixture · 43 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
7: class HlsPlaylistTest {
11: fun segmentReferencesResolveLikeABrowser() {
20: fun masterPlaylistPicksTheHighestBandwidthVariant() {
36: fun keyUriIsReadAndRewrittenInPlace() {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/download/HlsPlaylistTest.kt) · SHA-256 `604095e1f54be65d6b9eced8f2f51d56f8ab4b602aba26431ed6ad08b5a864a5`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.download

import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull

class HlsPlaylistTest {
    private val playlist = "https://cdn.test/show/1080/index.m3u8?token=abc"

    @Test
    fun segmentReferencesResolveLikeABrowser() {
        assertEquals("https://cdn.test/show/1080/seg0.ts", resolveHlsUrl(playlist, "seg0.ts"))
        assertEquals("https://cdn.test/keys/k.bin", resolveHlsUrl(playlist, "/keys/k.bin"))
        assertEquals("https://edge.test/a/seg1.ts?sig=1", resolveHlsUrl(playlist, "https://edge.test/a/seg1.ts?sig=1"))
        assertEquals("https://edge.test/seg2.ts", resolveHlsUrl(playlist, "//edge.test/seg2.ts"))
        assertEquals("https://cdn.test/show/1080/seg3.ts?part=2", resolveHlsUrl(playlist, "seg3.ts?part=2"))
    }

    @Test
    fun masterPlaylistPicksTheHighestBandwidthVariant() {
        val master = """
            #EXTM3U
            #EXT-X-STREAM-INF:BANDWIDTH=2500000,CODECS="avc1.4d401f,mp4a.40.2",RESOLUTION=1280x720
            720/index.m3u8
            #EXT-X-STREAM-INF:AVERAGE-BANDWIDTH=9000000,BANDWIDTH=5000000,RESOLUTION=1920x1080
            /hd/1080.m3u8
            #EXT-X-STREAM-INF:BANDWIDTH=800000
            480/index.m3u8
        """.trimIndent()

        assertEquals("https://cdn.test/hd/1080.m3u8", hlsBestVariantUrl(master, playlist))
        assertNull(hlsBestVariantUrl("#EXTM3U\n#EXTINF:4,\nseg0.ts", playlist))
    }

    @Test
    fun keyUriIsReadAndRewrittenInPlace() {
        val key = """#EXT-X-KEY:METHOD=AES-128,URI="https://keys.test/k?id=1,2",IV=0x10"""

        assertEquals("https://keys.test/k?id=1,2", hlsAttribute(key, "URI"))
        assertEquals("AES-128", hlsAttribute(key, "METHOD"))
        assertEquals("""#EXT-X-KEY:METHOD=AES-128,URI="0001_key_0.key",IV=0x10""", hlsWithUri(key, "0001_key_0.key"))
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/download/ImageDataSaverTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/download/ImageDataSaverTest.kt) · test / fixture · 144 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
11: class ImageDataSaverTest {
143: private fun saver(http: HttpService = HttpService { error("Unexpected HTTP call") }) = ImageDataSaver(http, CookieJar(InMemoryYokanDatabase(emptySnapshot())))
```

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

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.download

import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.services.http.*
import eu.friedcutlet.yokan.services.http.cookies.CookieJar
import io.ktor.http.Url
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.test.runTest
import kotlin.test.*

class ImageDataSaverTest {
    private val original = "https://images.example.org/page.png?w=900&format=png"
    private val wsrv = DbImageDataSaver(provider = ImageSaverProvider.Wsrv, forDownloads = true)

    @Test fun wsrvUsesDocumentedParametersWithoutSourceHeaders() = runTest {
        val saver = saver()
        val request = assertNotNull(saver.resolve(original, mapOf("Referer" to "https://source.example.org", "User-Agent" to "source-agent"), 1L, wsrv.copy(quality = 62, format = ImageSaverFormat.Jpeg, grayscale = true), true))
        val url = Url(request.url)
        assertEquals("wsrv.nl", url.host)
        assertEquals(original, url.parameters["url"])
        assertEquals("62", url.parameters["q"])
        assertEquals("jpg", url.parameters["output"])
        assertEquals("greyscale", url.parameters["filt"])
        assertEquals("-1", url.parameters["n"])
        assertFalse(request.headers.values.any { it == "source-agent" || it == "https://source.example.org" })
    }

    @Test fun bandwidthHeroColorAndOutputMatchItsProtocol() = runTest {
        val settings = wsrv.copy(provider = ImageSaverProvider.BandwidthHero, bandwidthHeroUrl = "https://compress.example.org/api", format = ImageSaverFormat.Webp)
        val color = Url(assertNotNull(saver().resolve(original, emptyMap(), 1L, settings, true)).url)
        assertEquals("0", color.parameters["bw"])
        assertNull(color.parameters["jpeg"])
        val gray = Url(assertNotNull(saver().resolve(original, emptyMap(), 1L, settings.copy(grayscale = true, format = ImageSaverFormat.Jpeg), true)).url)
        assertEquals("1", gray.parameters["bw"])
        assertEquals("1", gray.parameters["jpeg"])
    }

    @Test fun disabledUseModesSourceExclusionsAndKnownFormatsBypassCompression() = runTest {
        assertNull(saver().resolve(original, emptyMap(), 1L, DbImageDataSaver(), false))
        assertNull(saver().resolve(original, emptyMap(), 1L, wsrv.copy(forDownloads = false), true))
        assertNull(saver().resolve(original, emptyMap(), 1L, wsrv.copy(forReader = false), false))
        assertNull(saver().resolve(original, emptyMap(), 1L, wsrv.copy(excludedSourceIds = setOf(1L)), true))
        assertNull(saver().resolve(original, emptyMap(), null, wsrv.copy(excludedSourceIds = setOf(2L)), true))
        assertNotNull(saver().resolve(original, emptyMap(), 1L, wsrv.copy(excludedSourceIds = setOf(2L)), true))
        assertNull(saver().resolve("https://images.example.org/a.JPEG", emptyMap(), 1L, wsrv.copy(skipJpeg = true), true))
        assertNull(saver().resolve("https://images.example.org/a.gif", emptyMap(), 1L, wsrv, true))
    }

    @Test fun sourceCookiesAndCredentialHeadersNeverReachAProvider() = runTest {
        val db = InMemoryYokanDatabase(emptySnapshot())
        val jar = CookieJar(db)
        jar.put("images.example.org", "session=secret")
        val saver = ImageDataSaver(HttpService { error("Must not contact provider") }, jar)
        assertNull(saver.resolve(original, emptyMap(), 1L, wsrv, true))
        for (header in listOf("Cookie", "Authorization", "Proxy-Authorization", "X-Api-Key", "X-Auth-Token")) {
            assertNull(saver().resolve(original, mapOf(header to "secret"), 1L, wsrv, true))
        }
    }

    @Test fun privateCredentialedAndSignedUrlsStayOriginal() = runTest {
        val urls = listOf("http://images.example.org/a.png", "file:///page.png", "https://localhost/a.png", "https://192.168.1.2/a.png", "https://[::1]/a.png", "https://nas.local/a.png", "https://nas.internal/a.png", "https://user:secret@images.example.org/a.png", "https://images.example.org/a.png?token=secret", "https://images.example.org/a.png?X-Amz-Signature=secret", "https://images.example.org/a.png?unknown=secret", "https://images.example.org/a.png#secret")
        urls.forEach { assertNull(saver().resolve(it, emptyMap(), 1L, wsrv, true), it) }
    }

    @Test fun endpointValidationRejectsSecretsAndPrivateServers() {
        assertTrue(ImageDataSaver.validEndpoint("https://compress.example.org/proxy"))
        listOf("http://compress.example.org", "https://localhost", "https://a:b@compress.example.org", "https://compress.example.org?key=secret").forEach { assertFalse(ImageDataSaver.validEndpoint(it)) }
    }

    @Test fun browserLocalMediaNeverReachesAnOptimizerEvenOnPublicHttpsDeployments() = runTest {
        var calls = 0
        val saver = saver(HttpService { calls++; error("Local media must not reach a provider") })
        val urls = listOf(
            "https://reader.example.org/__yokan_files__/yokan/downloads/local-imports/one/manga/Private%20title/page.png",
            "https://reader.example.org/app/__yokan_files__/yokan/profiles/p_00000000000000000000000000000001/downloads/local-imports/one/manga/page.png",
        )
        for (provider in listOf(ImageSaverProvider.Wsrv, ImageSaverProvider.Resmush, ImageSaverProvider.BandwidthHero)) {
            val settings = wsrv.copy(provider = provider, forReader = true, bandwidthHeroUrl = "https://compress.example.org/proxy")
            for (url in urls) for (download in listOf(false, true)) {
                assertFalse(ImageDataSaver.eligible(url, emptyMap(), null, settings, download))
                assertNull(saver.resolve(url, emptyMap(), null, settings, download))
            }
            assertTrue(ImageDataSaver.eligible(original, emptyMap(), null, settings, download = false))
        }
        assertEquals(0, calls)
    }

    @Test fun providerFailureCooldownIsBoundedAndRecovers() = runTest {
        var now = 10L
        val saver = ImageDataSaver(HttpService { error("unused") }, CookieJar(InMemoryYokanDatabase(emptySnapshot())), { now })
        val optimized = assertNotNull(saver.resolve(original, emptyMap(), 1L, wsrv, true))
        saver.failed(optimized)
        assertNull(saver.resolve(original, emptyMap(), 1L, wsrv, true))
        now += 60_001
        assertNotNull(saver.resolve(original, emptyMap(), 1L, wsrv, true))
    }

    @Test fun resmushResolvesJsonWithOwnHeadersAndCachesBriefly() = runTest {
        var calls = 0
        val settings = wsrv.copy(provider = ImageSaverProvider.Resmush, quality = 95)
        val saver = saver(HttpService { request ->
            calls++
            val url = Url(request.url)
            assertEquals(original, url.parameters["img"])
            assertEquals("95", url.parameters["qlty"])
            assertEquals("true", url.parameters["exif"])
            assertEquals(ImageDataSaver.ProviderHeaders, request.headers)
            HttpResponse(200, "{\"dest\":\"https://api.resmush.it/output/a.png\",\"src_size\":100,\"dest_size\":50}")
        })
        assertEquals("https://api.resmush.it/output/a.png", assertNotNull(saver.resolve(original, emptyMap(), 1L, settings, true)).url)
        assertNotNull(saver.resolve(original, emptyMap(), 1L, settings, true))
        assertEquals(1, calls)
    }

    @Test fun resmushRejectsErrorsOversizedJsonUntrustedDestinationsAndLargerImages() = runTest {
        val settings = wsrv.copy(provider = ImageSaverProvider.Resmush)
        val responses = listOf(HttpResponse(503, "busy"), HttpResponse(200, "{\"error\":401}"), HttpResponse(200, "{\"dest\":\"https://unrelated.example.org/a.png\"}"), HttpResponse(200, "{\"dest\":\"https://api.resmush.it/a.png\",\"src_size\":10,\"dest_size\":20}"), HttpResponse(200, " ".repeat(32 * 1024 + 1)))
        responses.forEach { response -> assertNull(saver(HttpService { response }).resolve(original, emptyMap(), 1L, settings, true)) }
        assertNull(saver().resolve("https://images.example.org/a.webp", emptyMap(), 1L, settings, true))
    }

    @Test fun resmushHttpCdnIsDeliveredOverHttpsWithoutDisablingCertificateChecks() = runTest {
        val cdn = "http://hel2.static.resmush.it/id/a.png"
        val saver = saver(HttpService { HttpResponse(200, "{\"dest\":\"$cdn\",\"src_size\":100,\"dest_size\":50}") })
        val result = assertNotNull(saver.resolve(original, emptyMap(), 1L, wsrv.copy(provider = ImageSaverProvider.Resmush, quality = 95), true))
        val url = Url(result.url)
        assertEquals("https", url.protocol.name)
        assertEquals("wsrv.nl", url.host)
        assertEquals(cdn, url.parameters["url"])
        assertEquals("95", url.parameters["q"])
    }

    @Test fun cancellationPropagatesInsteadOfSilentlyFallingBack() = runTest {
        val saver = saver(HttpService { throw CancellationException("retired") })
        assertFailsWith<CancellationException> { saver.resolve(original, emptyMap(), 1L, wsrv.copy(provider = ImageSaverProvider.Resmush), true) }
    }

    @Test fun cacheVariantChangesWithCompressionButNotCredentials() {
        val keys = listOf(wsrv, wsrv.copy(quality = 30), wsrv.copy(format = ImageSaverFormat.Jpeg), wsrv.copy(grayscale = true)).map(ImageDataSaver::variant)
        assertEquals(keys.size, keys.distinct().size)
    }

    private fun saver(http: HttpService = HttpService { error("Unexpected HTTP call") }) = ImageDataSaver(http, CookieJar(InMemoryYokanDatabase(emptySnapshot())))
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/download/PersistentDownloadFileIntegrityTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/download/PersistentDownloadFileIntegrityTest.kt) · test / fixture · 277 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
27: class PersistentDownloadFileIntegrityTest {
62: fun interruptedDownloadCanBeRetriedByFreshDownloader() = runTest {
85: fun staleCompletionMarkerAndMissingFinalAreNotAccepted() = runTest {
103: fun failedPromotionDoesNotCreateCompletionMarker() = runTest {
119: fun failedTemporaryWriteDoesNotCreateCompletionMarker() = runTest {
135: fun completedDownloadIsLocatedAndDeletedAfterRestart() = runTest {
160: fun pageIsWrittenThroughOneOpenFile() = runTest {
163: override suspend fun request(request: HttpRequest) = HttpResponse(statusCode = 200, body = "")
164: override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse {
180: private fun request(retries: Int = 1) = DownloadRequest(
190: private fun database(): InMemoryYokanDatabase {
201: private fun TestScope.downloader(database: InMemoryYokanDatabase, http: HttpService, files: IntegrityFiles, saver: ImageDataSaver? = null, imageHttp: HttpService = http) = PersistentDownloadService(
213: private fun streamingHttp(next: () -> Pair<ByteArray, Throwable?>): HttpService = object : HttpService {
214: override suspend fun request(request: HttpRequest) =
217: override suspend fun stream(
228: private suspend fun awaitCompletion(
239: private class IntegrityFiles : MemoryFiles() {
244: override fun writeBytes(path: String, bytes: ByteArray) {
250: override fun appendBytes(path: String, bytes: ByteArray) {
256: override suspend fun <T> writeChunks(path: String, block: suspend (write: suspend (ByteArray) -> Unit) -> T): T {
264: override fun promote(sourcePath: String, targetPath: String): Boolean {
270: override fun deleteRecursively(path: String): Boolean {
275: fun fileEnding(suffix: String): ByteArray = files.entries.first { it.key.endsWith(suffix) }.value
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/download/PersistentDownloadFileIntegrityTest.kt) · SHA-256 `8eca298fd97779792cbe6801225560873b7b974dd2deedb5f142e8d40d8307e9`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.download

import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbPageUrl
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import eu.friedcutlet.yokan.services.files.MemoryFiles
import eu.friedcutlet.yokan.services.files.NoArchives
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.http.HttpStreamResponse
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.withTimeout

class PersistentDownloadFileIntegrityTest {
    @Test fun imageSaverDownloadsThroughRawTransportWithoutContactingSource() = runTest {
        val files = IntegrityFiles()
        val database = database()
        database.updateSettings(database.settings().let { it.copy(features = it.features.copy(imageDataSaver = eu.friedcutlet.yokan.database.DbImageDataSaver(provider = eu.friedcutlet.yokan.database.ImageSaverProvider.Wsrv, forDownloads = true))) })
        var providerCalls = 0
        val raw = HttpService { request ->
            providerCalls++
            assertTrue(request.url.startsWith("https://wsrv.nl/"))
            assertFalse(request.headers.keys.any { it.equals("Cookie", true) || it.equals("Authorization", true) })
            HttpResponse(200, headers = mapOf("Content-Type" to "image/webp"), bodyBytes = byteArrayOf(1, 2, 3))
        }
        val source = HttpService { error("Should use compressed image") }
        val saver = ImageDataSaver(raw, eu.friedcutlet.yokan.services.http.cookies.CookieJar(database))
        val result = awaitCompletion(downloader(database, source, files, saver, raw), request())
        assertTrue(result.isCompleted)
        assertEquals(1, providerCalls)
        assertContentEquals(byteArrayOf(1, 2, 3), files.fileEnding("/0001.jpg"))
    }

    @Test fun providerErrorOrNonImageBodyFallsBackBeforeCreatingCompletionMarker() = runTest {
        for (response in listOf(HttpResponse(503, "unavailable"), HttpResponse(200, "not an image", headers = mapOf("Content-Type" to "text/html")))) {
            val files = IntegrityFiles()
            val database = database()
            database.updateSettings(database.settings().let { it.copy(features = it.features.copy(imageDataSaver = eu.friedcutlet.yokan.database.DbImageDataSaver(provider = eu.friedcutlet.yokan.database.ImageSaverProvider.Wsrv, forDownloads = true))) })
            val raw = HttpService { response }
            val saver = ImageDataSaver(raw, eu.friedcutlet.yokan.services.http.cookies.CookieJar(database))
            val source = streamingHttp { byteArrayOf(8, 9) to null }
            val result = awaitCompletion(downloader(database, source, files, saver, raw), request())
            assertTrue(result.isCompleted)
            assertContentEquals(byteArrayOf(8, 9), files.fileEnding("/0001.jpg"))
            assertEquals(1, files.events.count { it.startsWith("write:") && it.endsWith(".complete") })
        }
    }
    @Test
    fun interruptedDownloadCanBeRetriedByFreshDownloader() = runTest {
        val files = IntegrityFiles()
        var streamCount = 0
        val http = streamingHttp {
            if (streamCount++ == 0) {
                byteArrayOf(1, 2) to IllegalStateException("interrupted")
            } else {
                byteArrayOf(1, 2, 3, 4) to null
            }
        }
        val request = request(retries = 0)
        val database = database()

        awaitCompletion(downloader(database, http, files), request)
        assertFalse(files.paths.any { it.endsWith(".complete") })

        val retry = downloader(database, http, files)
        awaitCompletion(retry, request)
        assertContentEquals(byteArrayOf(1, 2, 3, 4), files.fileEnding("/0001.jpg"))
        assertTrue(files.paths.any { it.endsWith("/0001.jpg.complete") })
    }

    @Test
    fun staleCompletionMarkerAndMissingFinalAreNotAccepted() = runTest {
        val files = IntegrityFiles()
        val request = request()
        val marker = "/downloads/Manga/Source (EN)/Title/Chapter/0001.jpg.complete"
        files.files[marker] = ByteArray(0)
        val database = database()

        awaitCompletion(
            downloader(database, streamingHttp { byteArrayOf(9, 8, 7) to null }, files),
            request,
        )

        assertTrue(files.paths.contains(marker))
        assertContentEquals(byteArrayOf(9, 8, 7), files.fileEnding("/0001.jpg"))
        assertTrue(files.events.indexOf("delete:$marker") < files.events.indexOf("write:$marker"))
    }

    @Test
    fun failedPromotionDoesNotCreateCompletionMarker() = runTest {
        val files = IntegrityFiles().apply { promotionSucceeds = false }
        val request = request(retries = 0)
        val database = database()

        val progress = awaitCompletion(
            downloader(database, streamingHttp { byteArrayOf(4, 5) to null }, files),
            request,
        )

        assertTrue(progress.failed >= 1)
        assertFalse(files.paths.any { it.endsWith(".complete") })
        assertFalse(files.paths.any { it.endsWith("/0001.jpg") })
    }

    @Test
    fun failedTemporaryWriteDoesNotCreateCompletionMarker() = runTest {
        val files = IntegrityFiles().apply { failWrites = true }
        val request = request(retries = 0)
        val database = database()

        val progress = awaitCompletion(
            downloader(database, streamingHttp { byteArrayOf(6, 7) to null }, files),
            request,
        )

        assertTrue(progress.failed >= 1)
        assertFalse(files.paths.any { it.endsWith(".complete") })
        assertFalse(files.paths.any { it.endsWith("/0001.jpg") })
    }

    @Test
    fun completedDownloadIsLocatedAndDeletedAfterRestart() = runTest {
        val files = IntegrityFiles()
        val database = InMemoryYokanDatabase(seedDatabaseSnapshot())
        database.upsertSource(DbSource(id = 7L, name = "Src", lang = "en"))
        database.upsertManga(DbManga(id = 3L, name = "Title", sourceId = 7L))
        database.upsertChapter(DbChapter(id = 1L, mangaId = 3L, name = "Ch 1", scanlator = "Team"))
        val request = request().copy(
            taskId = downloadTaskId(1L, 0L),
            mangaName = "Title",
            chapterName = "Ch 1",
            sourceLabel = "Src (EN)",
            scanlator = "Team",
        )
        val http = streamingHttp { byteArrayOf(1) to null }
        awaitCompletion(downloader(database, http, files), request)
        val location = "/downloads/Manga/Src (EN)/Title/Team_Ch 1"
        assertTrue(files.paths.any { it.startsWith("$location/") })

        val restarted = downloader(database, http, files)
        assertEquals(location, restarted.storageLocation(request.taskId))
        restarted.deleteArtifacts(request.taskId)
        assertFalse(files.paths.any { it.startsWith(location) })
    }

    @Test
    fun pageIsWrittenThroughOneOpenFile() = runTest {
        val files = IntegrityFiles()
        val http = object : HttpService {
            override suspend fun request(request: HttpRequest) = HttpResponse(statusCode = 200, body = "")
            override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse {
                listOf(byteArrayOf(1), byteArrayOf(2), byteArrayOf(3)).forEach { onChunk(it) }
                return HttpStreamResponse(statusCode = 200)
            }
        }

        awaitCompletion(
            downloader(database(), http, files),
            request(),
        )

        assertContentEquals(byteArrayOf(1, 2, 3), files.fileEnding("/0001.jpg"))
        assertEquals(1, files.events.count { it.startsWith("open:") })
        assertFalse(files.events.any { it.startsWith("append:") })
    }

    private fun request(retries: Int = 1) = DownloadRequest(
        taskId = "integrity-task",
        chapterId = 1L,
        itemType = DbItemType.Manga,
        mangaName = "Title",
        chapterName = "Chapter",
        sourceLabel = "Source (EN)",
        retries = retries,
    )

    private fun database(): InMemoryYokanDatabase {
        val seed = seedDatabaseSnapshot()
        return InMemoryYokanDatabase(
            seed.copy(
                sources = listOf(DbSource(id = 7L, name = "Source", lang = "en")),
                mangas = listOf(DbManga(id = 3L, name = "Title", sourceId = 7L)),
                chapters = listOf(DbChapter(id = 1L, mangaId = 3L, name = "Chapter", url = "/chapter")),
            ),
        )
    }

    private fun TestScope.downloader(database: InMemoryYokanDatabase, http: HttpService, files: IntegrityFiles, saver: ImageDataSaver? = null, imageHttp: HttpService = http) = PersistentDownloadService(
        database = database,
        http = http,
        files = files,
        archives = NoArchives,
        scope = this,
        resolvePages = { _, _ -> listOf(DbPageUrl(url = "https://example.test/page.jpg")) },
        ioDispatcher = StandardTestDispatcher(testScheduler),
        imageDataSaver = saver,
        imageHttp = imageHttp,
    )

    private fun streamingHttp(next: () -> Pair<ByteArray, Throwable?>): HttpService = object : HttpService {
        override suspend fun request(request: HttpRequest) =
            HttpResponse(statusCode = 200, headers = emptyMap(), body = "")

        override suspend fun stream(
            request: HttpRequest,
            onChunk: suspend (ByteArray) -> Unit,
        ): HttpStreamResponse {
            val (bytes, failure) = next()
            onChunk(bytes)
            failure?.let { throw it }
            return HttpStreamResponse(statusCode = 200, headers = emptyMap())
        }
    }

    private suspend fun awaitCompletion(
        service: PersistentDownloadService,
        request: DownloadRequest,
    ): DownloadProgress {
        val result = CompletableDeferred<DownloadProgress>()
        service.enqueue(request) { progress ->
            if ((progress.isCompleted || progress.failed > 0) && !result.isCompleted) result.complete(progress)
        }
        return withTimeout(5_000) { result.await() }
    }

    private class IntegrityFiles : MemoryFiles() {
        val events = mutableListOf<String>()
        var promotionSucceeds = true
        var failWrites = false

        override fun writeBytes(path: String, bytes: ByteArray) {
            events += "write:$path"
            check(!failWrites || !path.endsWith(".part")) { "simulated temporary write failure" }
            super.writeBytes(path, bytes)
        }

        override fun appendBytes(path: String, bytes: ByteArray) {
            events += "append:$path"
            super.appendBytes(path, bytes)
        }

        /** Buffers like an open file handle; the bytes land when the block ends. */
        override suspend fun <T> writeChunks(path: String, block: suspend (write: suspend (ByteArray) -> Unit) -> T): T {
            events += "open:$path"
            var written = ByteArray(0)
            val result = block { written += it }
            writeBytes(path, written)
            return result
        }

        override fun promote(sourcePath: String, targetPath: String): Boolean {
            if (!promotionSucceeds) return false
            files[targetPath] = files.remove(sourcePath) ?: return false
            return true
        }

        override fun deleteRecursively(path: String): Boolean {
            events += "delete:$path"
            return super.deleteRecursively(path)
        }

        fun fileEnding(suffix: String): ByteArray = files.entries.first { it.key.endsWith(suffix) }.value
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/download/PersistentDownloadServiceTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/download/PersistentDownloadServiceTest.kt) · test / fixture · 671 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
45: class PersistentDownloadServiceTest {
49: fun pagesResolveWhenEachChapterStartsAndRowsKeepRequestOrder() = runTest {
73: fun expiredPageUrlIsResolvedAgainOnceAndRetried() = runTest {
92: fun changedPageCountRestartsTheChapterAndDropsStalePages() = runTest {
114: fun retryAfterRestartRebuildsTheRequestFromTheChapter() = runTest {
135: fun interruptedDownloadResumesOnStartup() = runTest {
147: fun enqueueRetryAndStartupDoNotRecreateRowsForDeletedParents() = runTest {
171: fun deletingParentAtFinalizationDoesNotRestoreChapterOrDownloadAndOtherTypeContinues() = runTest {
205: fun duplicateEnqueueIsSkippedWhileQueuedOrDownloaded() = runTest {
227: fun pagesDownloadInParallelAndEveryPageIsCounted() = runTest {
255: fun clientErrorsFailAtOnceWhileRetryAfterIsHonoured() = runTest {
284: fun retryDelayUsesRetryAfterElseJitteredExponentialBackoff() {
297: fun completedDownloadMarksItsChapterWithTheArchiveTheReaderOpens() = runTest {
314: fun pausingWhileTheChapterIsArchivedStillFinishesItOnce() = runTest {
334: fun pausingARunningChapterFreesItsSourceAndResumeContinuesIt() = runTest {
359: fun contentUriDownloadFoldersAreRejectedBeforeAnythingIsRecorded() = runTest {
371: fun hlsPageFollowsTheBestVariantAndSavesKeyAndSegmentsLocally() = runTest {
420: fun wifiOnlyKeepsDownloadsQueuedOnAMeteredNetworkUntilWifiReturns() = runTest {
449: fun meteredNetworkPausesARunningChapterAtItsNextPageAndTurningWifiOnlyOffResumesIt() = runTest {
476: fun restartPreservesPausedQueueAndExactDestination() = runTest {
502: fun hlsSegmentsUseBoundedConcurrencyAndCountSavedBytes() = runTest {
529: fun automatedDeletionChecksEligibilityAndLeavesIncompleteTransfersUntouched() = runTest {
543: fun automatedDeletionRefusesMalformedRootAndTitleLocations() = runTest {
556: fun automatedDeletionReportsFilesystemFailureAndRejectsRedirectedPaths() = runTest {
570: fun novelDownloadSavesChapterHtmlAndIsReadableWithoutPageListCalls() = runTest {
588: private fun request(database: InMemoryYokanDatabase, chapterId: Long): DownloadRequest =
591: private fun database(settings: (DbSettings) -> DbSettings = { it }): InMemoryYokanDatabase {
606: private fun TestScope.service(
628: private class FakeNetwork(unmetered: Boolean) : NetworkMonitor {
632: private class Reply(val status: Int, val body: ByteArray = byteArrayOf(1), val headers: Map<String, String> = emptyMap())
635: private class ScriptedHttp(
641: override suspend fun request(request: HttpRequest): HttpResponse = text(request)
643: override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse {
651: private class RecordingArchives(private val onZip: () -> Unit = {}) : LocalArchiveService {
653: override fun listPages(archivePath: String) = emptyList<DbPageUrl>()
654: override fun listEpubChapters(archivePath: String) = emptyList<LocalEpubChapter>()
655: override fun readEpubChapter(archivePath: String, index: Int) = ""
656: override fun readEpubResource(archivePath: String, resourcePath: String): ByteArray? = null
657: override fun zipDirectoryToCbz(directoryPath: String, deleteSource: Boolean): String {
665: private class GuardedFiles : MemoryFiles() {
669: override fun canonicalPath(path: String): String? = redirectedPaths[path] ?: path
670: override fun deleteRecursively(path: String): Boolean = !rejectDeletion && super.deleteRecursively(path)
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/download/PersistentDownloadServiceTest.kt) · SHA-256 `57c73645eaaaf20bcec32e671abd98fe886a52d3dbe0d33048a4d9c7153231c8`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.download

import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.services.notifications.RecordingNotifications
import eu.friedcutlet.yokan.database.DbDownload
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbPageUrl
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import eu.friedcutlet.yokan.services.files.LocalArchiveService
import eu.friedcutlet.yokan.services.files.LocalEpubChapter
import eu.friedcutlet.yokan.services.files.LocalFileService
import eu.friedcutlet.yokan.services.files.MemoryFiles
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.http.HttpStreamResponse
import eu.friedcutlet.yokan.services.notifications.NotificationChannel
import eu.friedcutlet.yokan.services.notifications.NotificationPayload
import eu.friedcutlet.yokan.services.notifications.NotificationService
import eu.friedcutlet.yokan.services.system.NetworkMonitor
import eu.friedcutlet.yokan.services.system.UnmeteredNetwork
import kotlin.random.Random
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.currentTime
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest

@OptIn(ExperimentalCoroutinesApi::class)
class PersistentDownloadServiceTest {
    private val location = "/downloads/Manga/Src (EN)/Title/Ch 10"

    @Test
    fun pagesResolveWhenEachChapterStartsAndRowsKeepRequestOrder() = runTest {
        val database = database()
        val release = CompletableDeferred<Unit>()
        val resolved = mutableListOf<Long>()
        val http = ScriptedHttp { request -> if ("c11" in request.url) release.await(); Reply(200) }
        val service = service(database, http) { chapterId, _ ->
            resolved += chapterId
            listOf(DbPageUrl(url = "https://img.test/c$chapterId/1.jpg"))
        }

        service.enqueue(request(database, 11))
        service.enqueue(request(database, 10))

        assertEquals(listOf(11L, 10L), database.downloads().map { it.chapterId })
        assertEquals(emptyList(), resolved)
        runCurrent()
        // One chapter per source: the second chapter is not resolved until the first one is done.
        assertEquals(listOf(11L), resolved)
        release.complete(Unit)
        advanceUntilIdle()
        assertEquals(listOf(11L, 10L), resolved)
    }

    @Test
    fun expiredPageUrlIsResolvedAgainOnceAndRetried() = runTest {
        val database = database()
        val http = ScriptedHttp { request -> Reply(if ("old" in request.url) 403 else 200) }
        val refreshes = mutableListOf<Boolean>()
        val service = service(database, http) { _, forceRefresh ->
            refreshes += forceRefresh
            listOf(DbPageUrl(url = if (forceRefresh) "https://img.test/new/1.jpg" else "https://img.test/old/1.jpg"))
        }

        service.enqueue(request(database, 10))
        advanceUntilIdle()

        assertEquals(listOf(false, true), refreshes)
        // A 403 is never retried against the same URL.
        assertEquals(listOf("https://img.test/old/1.jpg", "https://img.test/new/1.jpg"), http.requested)
        assertEquals(true, database.downloads().single().isDownload)
    }

    @Test
    fun changedPageCountRestartsTheChapterAndDropsStalePages() = runTest {
        val database = database()
        val files = MemoryFiles()
        val http = ScriptedHttp { request -> Reply(if ("old" in request.url) 410 else 200) }
        val service = service(database, http, files) { _, forceRefresh ->
            if (forceRefresh) {
                listOf(DbPageUrl(url = "https://img.test/new/1.jpg"))
            } else {
                listOf(DbPageUrl(url = "https://img.test/old/1.jpg"), DbPageUrl(url = "https://img.test/kept/2.jpg"))
            }
        }

        service.enqueue(request(database, 10))
        advanceUntilIdle()

        assertEquals(true, database.downloads().single().isDownload)
        assertEquals(1, database.downloads().single().total)
        assertTrue("$location/0001.jpg" in files.paths)
        assertFalse(files.paths.any { it.startsWith("$location/0002") })
    }

    @Test
    fun retryAfterRestartRebuildsTheRequestFromTheChapter() = runTest {
        val database = database()
        val files = MemoryFiles()
        var status = 400
        val http = ScriptedHttp { Reply(status) }
        val pages: suspend (Long, Boolean) -> List<DbPageUrl> = { _, _ -> listOf(DbPageUrl(url = "https://img.test/1.jpg")) }
        service(database, http, files, resolve = pages).enqueue(request(database, 10))
        advanceUntilIdle()
        assertEquals(false, database.downloads().single().isStartDownload)

        status = 200
        val restarted = service(database, http, files, resolve = pages)

        assertTrue(restarted.retry(downloadTaskId(10, 0)))
        assertFalse(restarted.retry(downloadTaskId(999, 0)))
        advanceUntilIdle()
        assertEquals(true, database.downloads().single().isDownload)
        assertEquals(location, database.chapter(10)?.archivePath)
    }

    @Test
    fun interruptedDownloadResumesOnStartup() = runTest {
        val database = database()
        database.upsertDownload(DbDownload(chapterId = 10, succeeded = 1, total = 3, isDownload = false, isStartDownload = true))
        val service = service(database, ScriptedHttp { Reply(200) }) { _, _ -> listOf(DbPageUrl(url = "https://img.test/1.jpg")) }

        service.initialize()
        advanceUntilIdle()

        assertEquals(true, database.downloads().single().isDownload)
    }

    @Test
    fun enqueueRetryAndStartupDoNotRecreateRowsForDeletedParents() = runTest {
        val database = database()
        val staleRequest = request(database, 10)
        val service = service(database, ScriptedHttp { Reply(400) }) { _, _ -> listOf(DbPageUrl(url = "https://img.test/1.jpg")) }

        service.enqueue(staleRequest)
        advanceUntilIdle()
        database.upsertDownload(DbDownload(id = 99, chapterId = 10, isStartDownload = true))
        database.batch {
            database.removeChapter(10)
            database.removeManga(1)
            database.removeDownload(99)
        }
        service.enqueue(staleRequest)
        assertFalse(service.retry(downloadTaskId(10, 0)))

        service(database, ScriptedHttp { Reply(200) }) { _, _ -> listOf(DbPageUrl(url = "https://img.test/1.jpg")) }.initialize()

        assertEquals(null, database.download(99))
        assertEquals(null, database.chapter(10))
        assertEquals(null, database.manga(1))
    }

    @Test
    fun deletingParentAtFinalizationDoesNotRestoreChapterOrDownloadAndOtherTypeContinues() = runTest {
        val database = database()
        val gate = CompletableDeferred<Unit>()
        val entered = CompletableDeferred<Unit>()
        val http = ScriptedHttp { request ->
            if ("c10" in request.url) {
                entered.complete(Unit)
                gate.await()
            }
            Reply(200)
        }
        val service = service(database, http) { chapterId, _ -> listOf(DbPageUrl(url = "https://img.test/c$chapterId/1.jpg")) }
        service.enqueue(request(database, 10))
        service.enqueue(request(database, 11))
        runCurrent()
        entered.await()
        database.batch {
            database.removeChapter(10)
            database.removeManga(1)
        }
        database.upsertSource(DbSource(id = 8, name = "Other source", lang = "en"))
        database.upsertManga(DbManga(id = 2, name = "Other", sourceId = 8, itemType = DbItemType.Anime))
        database.upsertChapter(DbChapter(id = 20, mangaId = 2, url = "/c20", name = "Other chapter"))
        service.enqueue(request(database, 20))
        gate.complete(Unit)
        advanceUntilIdle()

        assertEquals(null, database.chapter(10))
        assertEquals(null, database.manga(1))
        assertEquals(false, database.downloads().first { it.chapterId == 10L }.isDownload)
        assertEquals(true, database.downloads().first { it.chapterId == 20L }.isDownload)
    }

    @Test
    fun duplicateEnqueueIsSkippedWhileQueuedOrDownloaded() = runTest {
        val database = database()
        val files = MemoryFiles()
        val http = ScriptedHttp { Reply(200) }
        val service = service(database, http, files) { _, _ -> listOf(DbPageUrl(url = "https://img.test/1.jpg")) }

        service.enqueue(request(database, 10))
        service.enqueue(request(database, 10))
        advanceUntilIdle()
        service.enqueue(request(database, 10))
        advanceUntilIdle()

        assertEquals(1, http.requested.size)
        assertEquals(1, database.downloads().size)
        files.deleteRecursively(location)
        service.enqueue(request(database, 10))
        advanceUntilIdle()
        assertEquals(2, http.requested.size)
        assertEquals(location, database.chapter(10)?.archivePath)
    }

    @Test
    fun pagesDownloadInParallelAndEveryPageIsCounted() = runTest {
        val database = database()
        val gate = CompletableDeferred<Unit>()
        var inFlight = 0
        var maxInFlight = 0
        val http = ScriptedHttp {
            inFlight += 1
            maxInFlight = maxOf(maxInFlight, inFlight)
            gate.await()
            inFlight -= 1
            Reply(200)
        }
        val service = service(database, http) { _, _ -> (1..7).map { DbPageUrl(url = "https://img.test/$it.jpg") } }

        service.enqueue(request(database, 10))
        runCurrent()
        assertEquals(PAGE_PARALLELISM, inFlight)
        gate.complete(Unit)
        advanceUntilIdle()

        assertEquals(PAGE_PARALLELISM, maxInFlight)
        val row = database.downloads().single()
        assertEquals(7, row.succeeded)
        assertEquals(7, row.total)
        assertEquals(true, row.isDownload)
    }

    @Test
    fun clientErrorsFailAtOnceWhileRetryAfterIsHonoured() = runTest {
        val database = database()
        val calls = mutableListOf<Pair<String, Long>>()
        var throttled = false
        val http = ScriptedHttp { request ->
            calls += request.url to currentTime
            when {
                "bad" in request.url -> Reply(400)
                !throttled -> Reply(429, headers = mapOf("retry-after" to "7")).also { throttled = true }
                else -> Reply(200)
            }
        }
        val pages = mapOf(10L to "https://img.test/bad.jpg", 11L to "https://img.test/busy.jpg")
        val service = service(database, http) { chapterId, _ -> listOf(DbPageUrl(url = pages.getValue(chapterId))) }

        service.enqueue(request(database, 10))
        advanceUntilIdle()
        service.enqueue(request(database, 11))
        advanceUntilIdle()

        assertEquals(1, calls.count { "bad" in it.first })
        val busy = calls.filter { "busy" in it.first }.map { it.second }
        assertEquals(2, busy.size)
        assertEquals(7_000L, busy[1] - busy[0])
        assertEquals(false, database.downloads().first { it.chapterId == 10L }.isDownload)
        assertEquals(true, database.downloads().first { it.chapterId == 11L }.isDownload)
    }

    @Test
    fun retryDelayUsesRetryAfterElseJitteredExponentialBackoff() {
        assertEquals(3_000L, downloadRetryDelayMs(1, "3"))
        assertEquals(60_000L, downloadRetryDelayMs(1, "3600"))
        repeat(20) {
            val random = Random(it)
            assertTrue(downloadRetryDelayMs(1, null, random) in 500L..1_000L)
            assertTrue(downloadRetryDelayMs(3, "Wed, 21 Oct 2015 07:28:00 GMT", random) in 2_000L..4_000L)
        }
        assertTrue(isRetryableDownloadStatus(408) && isRetryableDownloadStatus(429) && isRetryableDownloadStatus(503))
        assertFalse(isRetryableDownloadStatus(404) || isRetryableDownloadStatus(400))
    }

    @Test
    fun completedDownloadMarksItsChapterWithTheArchiveTheReaderOpens() = runTest {
        val database = database { it.copy(saveAsCBZArchive = true) }
        val archives = RecordingArchives()
        val service = service(database, ScriptedHttp { Reply(200, ByteArray(2_000_000)) }, archives = archives) { _, _ ->
            listOf(DbPageUrl(url = "https://img.test/1.jpg"))
        }

        service.enqueue(request(database, 10))
        advanceUntilIdle()

        assertEquals(listOf(location), archives.zipped)
        val chapter = assertNotNull(database.chapter(10))
        assertEquals("$location.cbz", chapter.archivePath)
        assertEquals("1.9 MB", chapter.downloadSize)
    }

    @Test
    fun pausingWhileTheChapterIsArchivedStillFinishesItOnce() = runTest {
        val database = database { it.copy(saveAsCBZArchive = true) }
        lateinit var service: PersistentDownloadService
        var pauses = 0
        val archives = RecordingArchives(onZip = { if (pauses++ == 0) service.pause(downloadTaskId(10, 0)) })
        val http = ScriptedHttp { Reply(200) }
        service = service(database, http, archives = archives) { _, _ -> listOf(DbPageUrl(url = "https://img.test/1.jpg")) }

        service.enqueue(request(database, 10))
        advanceUntilIdle()
        service.resume(downloadTaskId(10, 0))
        advanceUntilIdle()

        assertEquals("$location.cbz", database.chapter(10)?.archivePath)
        assertEquals(true, database.downloads().single().isDownload)
        assertEquals(1, http.requested.size, "a finished chapter is not fetched again")
        assertEquals(1, archives.zipped.size)
    }

    @Test
    fun pausingARunningChapterFreesItsSourceAndResumeContinuesIt() = runTest {
        val database = database()
        val stalledOnce = mutableSetOf<String>()
        val http = ScriptedHttp { request ->
            if ("c10" in request.url && stalledOnce.add(request.url)) {
                awaitCancellation()
            }
            Reply(200)
        }
        val service = service(database, http) { chapterId, _ -> listOf(DbPageUrl(url = "https://img.test/c$chapterId/1.jpg")) }
        service.enqueue(request(database, 10))
        service.enqueue(request(database, 11))
        runCurrent()

        service.pause(downloadTaskId(10, 0))
        advanceUntilIdle()

        assertEquals(true, database.downloads().first { it.chapterId == 11L }.isDownload)
        assertEquals(false, database.downloads().first { it.chapterId == 10L }.isDownload)
        service.resume(downloadTaskId(10, 0))
        advanceUntilIdle()
        assertEquals(true, database.downloads().first { it.chapterId == 10L }.isDownload)
    }

    @Test
    fun contentUriDownloadFoldersAreRejectedBeforeAnythingIsRecorded() = runTest {
        val database = database()
        val service = service(database, ScriptedHttp { Reply(200) }) { _, _ -> emptyList() }

        assertFailsWith<IllegalArgumentException> {
            service.enqueue(request(database, 10).copy(destinationRoot = "content://com.android.externalstorage.documents/tree/primary%3AComics"))
        }

        assertEquals(emptyList(), database.downloads())
    }

    @Test
    fun hlsPageFollowsTheBestVariantAndSavesKeyAndSegmentsLocally() = runTest {
        val database = database()
        val files = MemoryFiles()
        val playlists = mapOf(
            "https://cdn.test/show/master.m3u8?token=a" to """
                #EXTM3U
                #EXT-X-STREAM-INF:BANDWIDTH=800000,CODECS="avc1,mp4a"
                low/index.m3u8
                #EXT-X-STREAM-INF:AVERAGE-BANDWIDTH=9000000,BANDWIDTH=2000000
                high/index.m3u8
            """.trimIndent(),
            "https://cdn.test/show/high/index.m3u8" to """
                #EXTM3U
                #EXT-X-KEY:METHOD=AES-128,URI="/keys/k1.bin",IV=0x1
                seg0.ts
                #EXT-X-KEY:METHOD=AES-128,URI="/keys/k1.bin",IV=0x2
                https://other.test/seg1.ts
            """.trimIndent(),
        )
        var segmentFailures = 1
        val http = ScriptedHttp(
            text = { request -> playlists[request.url]?.let { HttpResponse(200, it) } ?: HttpResponse(404, "") },
        ) { request ->
            if ("seg0" in request.url && segmentFailures-- > 0) Reply(503) else Reply(200)
        }
        val service = service(database, http, files) { _, _ -> listOf(DbPageUrl(url = "https://cdn.test/show/master.m3u8?token=a")) }

        service.enqueue(request(database, 10))
        advanceUntilIdle()

        assertEquals(true, database.downloads().single().isDownload)
        assertEquals(
            listOf("https://cdn.test/keys/k1.bin", "https://cdn.test/show/high/seg0.ts", "https://cdn.test/show/high/seg0.ts", "https://other.test/seg1.ts").sorted(),
            http.requested.sorted(),
        )
        assertEquals(
            """
                #EXTM3U
                #EXT-X-KEY:METHOD=AES-128,URI="0001_key_0.key",IV=0x1
                0001_seg_0000.ts
                #EXT-X-KEY:METHOD=AES-128,URI="0001_key_0.key",IV=0x2
                0001_seg_0001.ts
            """.trimIndent(),
            files.readBytes("$location/0001.m3u8").decodeToString(),
        )
        assertTrue("$location/0001.m3u8.complete" in files.paths)
    }

    @Test
    fun wifiOnlyKeepsDownloadsQueuedOnAMeteredNetworkUntilWifiReturns() = runTest {
        val database = database { it.copy(downloadOnlyOnWifi = true) }
        val network = FakeNetwork(unmetered = false)
        val notifications = RecordingNotifications()
        val http = ScriptedHttp { Reply(200) }
        val service = service(database, http, network = network, notifications = notifications) { chapterId, _ ->
            listOf(DbPageUrl(url = "https://img.test/c$chapterId/1.jpg"))
        }

        service.enqueue(request(database, 10))
        service.enqueue(request(database, 11))
        service.pause(downloadTaskId(11, 0))
        advanceUntilIdle()

        assertEquals(DownloadQueueStatus(pending = 1, waitingForWifi = true), service.queueStatus.value)
        assertEquals(emptyList(), http.requested)
        assertEquals(listOf(true, true), database.downloads().map { it.isStartDownload })
        assertEquals(1, notifications.posted.count { it.tag == WAITING_FOR_WIFI_NOTIFICATION_TAG }, "one notification, not one per chapter")

        network.unmetered.value = true
        advanceUntilIdle()

        assertEquals(DownloadQueueStatus(), service.queueStatus.value)
        assertEquals(true, database.downloads().first { it.chapterId == 10L }.isDownload)
        assertEquals(false, database.downloads().first { it.chapterId == 11L }.isDownload, "a paused chapter stays paused")
        assertEquals(listOf<String?>(WAITING_FOR_WIFI_NOTIFICATION_TAG), notifications.cancelled.map { it.second })
    }

    @Test
    fun meteredNetworkPausesARunningChapterAtItsNextPageAndTurningWifiOnlyOffResumesIt() = runTest {
        val database = database { it.copy(downloadOnlyOnWifi = true) }
        val network = FakeNetwork(unmetered = true)
        val http = ScriptedHttp { request ->
            // The phone leaves Wi-Fi while the first page is downloading.
            if (request.url.endsWith("/1.jpg")) network.unmetered.value = false
            Reply(200)
        }
        val pages = (1..3).map { DbPageUrl(url = "https://img.test/$it.jpg") }
        val service = service(database, http, network = network) { _, _ -> pages }

        service.enqueue(request(database, 10))
        advanceUntilIdle()

        assertEquals(listOf("https://img.test/1.jpg"), http.requested)
        assertEquals(1, service.activeDownloads().single().succeeded)
        assertEquals(DownloadQueueStatus(pending = 1, waitingForWifi = true), service.queueStatus.value)

        database.updateSettings(database.settings().copy(downloadOnlyOnWifi = false))
        advanceUntilIdle()

        assertEquals(pages.map { it.url }, http.requested.sorted(), "the saved page is not fetched again")
        assertEquals(true, database.downloads().single().isDownload)
        assertEquals(DownloadQueueStatus(), service.queueStatus.value)
    }

    @Test
    fun restartPreservesPausedQueueAndExactDestination() = runTest {
        val database = database()
        val request = request(database, 10).copy(destinationRoot = "/one-off", retries = 1)
        database.upsertDownload(eu.friedcutlet.yokan.database.DbDownload(
            id = 50, chapterId = 10, isStartDownload = true, isPaused = true,
            storageLocation = "/one-off/exact/chapter",
            requestJson = eu.friedcutlet.yokan.database.DatabaseJson.encodeToString(DownloadRequest.serializer(), request),
        ))
        val files = MemoryFiles()
        val http = ScriptedHttp { Reply(200) }
        val downloader = service(database, http, files) { _, _ -> listOf(DbPageUrl("https://test/page.jpg")) }
        assertEquals("/one-off/exact/chapter", downloader.storageLocation(request.taskId))
        downloader.initialize()
        advanceUntilIdle()
        assertTrue(http.requested.isEmpty())
        assertTrue(downloader.activeDownloads().single().isPaused)
        assertTrue(database.download(50)?.isPaused == true)

        downloader.resume(request.taskId)
        advanceUntilIdle()
        assertEquals(true, database.download(50)?.isDownload)
        assertEquals(false, database.download(50)?.isPaused)
        assertTrue(files.paths.any { it.startsWith("/one-off/exact/chapter/") })
    }

    @Test
    fun hlsSegmentsUseBoundedConcurrencyAndCountSavedBytes() = runTest {
        val database = database()
        val playlist = "#EXTM3U\n" + (1..8).joinToString("\n") { "segment$it.ts" }
        var inFlight = 0
        var maximum = 0
        val http = ScriptedHttp(text = { HttpResponse(200, playlist) }) {
            inFlight++
            maximum = maxOf(maximum, inFlight)
            kotlinx.coroutines.delay(10)
            inFlight--
            Reply(200, byteArrayOf(1, 2, 3))
        }
        val files = MemoryFiles()
        val downloadRequest = request(database, 10)
        files.writeBytes("$location/0001_seg_0000.ts", byteArrayOf(1, 2, 3))
        files.writeBytes("$location/0001_seg_0000.ts.complete", byteArrayOf())
        val downloader = service(database, http, files) { _, _ -> listOf(DbPageUrl("https://test/video.m3u8")) }
        var downloadedBytes = 0L
        downloader.enqueue(downloadRequest) { downloadedBytes = it.bytesDownloaded }
        advanceUntilIdle()
        assertEquals(PAGE_PARALLELISM, maximum)
        assertEquals(7, http.requested.size)
        assertEquals(24L + playlist.length, downloadedBytes)
        assertEquals(true, database.downloads().single().isDownload)
    }

    @Test
    fun automatedDeletionChecksEligibilityAndLeavesIncompleteTransfersUntouched() = runTest {
        val database = database()
        val files = MemoryFiles().apply { writeBytes("$location/0001.jpg", byteArrayOf(1)) }
        val downloader = service(database, ScriptedHttp { Reply(200) }, files) { _, _ -> emptyList() }
        database.upsertDownload(DbDownload(chapterId = 10, storageLocation = location, isDownload = false))
        assertFalse(downloader.deleteCompletedArtifacts("chapter-10"))
        database.upsertDownload(database.downloads().single().copy(isDownload = true))
        assertFalse(downloader.deleteCompletedArtifacts("chapter-10", stillEligible = { false }))
        assertTrue(files.exists(location))
        assertTrue(downloader.deleteCompletedArtifacts("chapter-10"))
        assertFalse(files.exists(location))
    }

    @Test
    fun automatedDeletionRefusesMalformedRootAndTitleLocations() = runTest {
        for (bad in listOf("/", "/downloads", "/downloads/Manga/Src (EN)/Title", "/downloads/Manga/Src (EN)/Title/../other", "")) {
            val database = database()
            val files = MemoryFiles().apply { writeBytes("/downloads/important.jpg", byteArrayOf(1)) }
            val downloader = service(database, ScriptedHttp { Reply(200) }, files) { _, _ -> emptyList() }
            database.upsertDownload(DbDownload(chapterId = 10, storageLocation = bad, isDownload = true))
            // Blank locations fall back to the derived chapter folder, never the root.
            if (bad.isNotBlank()) assertFalse(downloader.deleteCompletedArtifacts("chapter-10"), bad)
            assertTrue(files.exists("/downloads/important.jpg"))
        }
    }

    @Test
    fun automatedDeletionReportsFilesystemFailureAndRejectsRedirectedPaths() = runTest {
        val database = database()
        val files = GuardedFiles().apply { writeBytes("$location/0001.jpg", byteArrayOf(1)); rejectDeletion = true }
        val downloader = service(database, ScriptedHttp { Reply(200) }, files) { _, _ -> emptyList() }
        database.upsertDownload(DbDownload(chapterId = 10, storageLocation = location, isDownload = true))
        assertFalse(downloader.deleteCompletedArtifacts("chapter-10"))
        assertTrue(files.exists(location))
        files.rejectDeletion = false
        files.redirectedPaths[location] = "/downloads"
        assertFalse(downloader.deleteCompletedArtifacts("chapter-10"))
        assertTrue(files.exists(location))
    }

    @Test
    fun novelDownloadSavesChapterHtmlAndIsReadableWithoutPageListCalls() = runTest {
        val database = database()
        database.upsertManga(database.manga(1)!!.copy(itemType = DbItemType.Novel))
        val files = MemoryFiles()
        val downloader = PersistentDownloadService(
            database, ScriptedHttp { error("No image fetch expected") }, files, RecordingArchives(), this,
            resolvePages = { _, _ -> error("Novels use htmlContent") },
            ioDispatcher = StandardTestDispatcher(testScheduler),
            resolveNovelText = { "<p>Offline novel</p>" },
        )
        downloader.enqueue(request(database, 10))
        advanceUntilIdle()
        val chapter = database.chapter(10)!!
        assertTrue(database.downloads().single().isDownload == true)
        assertEquals("<p>Offline novel</p>", files.readBytes("${chapter.archivePath}/0001.html").decodeToString())
        assertTrue(files.exists("${chapter.archivePath}/0001.html.complete"))
    }

    private fun request(database: InMemoryYokanDatabase, chapterId: Long): DownloadRequest =
        checkNotNull(chapterDownloadRequest(database, chapterId))

    private fun database(settings: (DbSettings) -> DbSettings = { it }): InMemoryYokanDatabase {
        val seed = seedDatabaseSnapshot()
        return InMemoryYokanDatabase(
            seed.copy(
                settings = settings(seed.settings),
                sources = listOf(DbSource(id = 7, name = "Src", lang = "en")),
                mangas = listOf(DbManga(id = 1, name = "Title", sourceId = 7, itemType = DbItemType.Manga)),
                chapters = listOf(
                    DbChapter(id = 10, mangaId = 1, url = "/c10", name = "Ch 10"),
                    DbChapter(id = 11, mangaId = 1, url = "/c11", name = "Ch 11"),
                ),
            ),
        )
    }

    private fun TestScope.service(
        database: InMemoryYokanDatabase,
        http: HttpService,
        files: LocalFileService = MemoryFiles(),
        archives: LocalArchiveService = RecordingArchives(),
        network: NetworkMonitor = UnmeteredNetwork,
        notifications: NotificationService? = null,
        resolve: suspend (Long, Boolean) -> List<DbPageUrl>,
    ) = PersistentDownloadService(
        database = database,
        http = http,
        files = files,
        archives = archives,
        // Not backgroundScope: advanceUntilIdle() does not wait for background work.
        scope = this,
        resolvePages = resolve,
        notifications = notifications,
        network = network,
        ioDispatcher = StandardTestDispatcher(testScheduler),
    )
}

private class FakeNetwork(unmetered: Boolean) : NetworkMonitor {
    override val unmetered = MutableStateFlow(unmetered)
}

private class Reply(val status: Int, val body: ByteArray = byteArrayOf(1), val headers: Map<String, String> = emptyMap())

/** Streams scripted replies and records every streamed URL; [text] answers playlist requests. */
private class ScriptedHttp(
    private val text: (HttpRequest) -> HttpResponse = { HttpResponse(statusCode = 404, body = "") },
    private val reply: suspend (HttpRequest) -> Reply,
) : HttpService {
    val requested = mutableListOf<String>()

    override suspend fun request(request: HttpRequest): HttpResponse = text(request)

    override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse {
        requested += request.url
        val answer = reply(request)
        onChunk(answer.body)
        return HttpStreamResponse(statusCode = answer.status, headers = answer.headers)
    }
}

private class RecordingArchives(private val onZip: () -> Unit = {}) : LocalArchiveService {
    val zipped = mutableListOf<String>()
    override fun listPages(archivePath: String) = emptyList<DbPageUrl>()
    override fun listEpubChapters(archivePath: String) = emptyList<LocalEpubChapter>()
    override fun readEpubChapter(archivePath: String, index: Int) = ""
    override fun readEpubResource(archivePath: String, resourcePath: String): ByteArray? = null
    override fun zipDirectoryToCbz(directoryPath: String, deleteSource: Boolean): String {
        zipped += directoryPath
        onZip()
        return "$directoryPath.cbz"
    }
}

/** Lets a test refuse deletion or resolve a path elsewhere, as a hostile filesystem would. */
private class GuardedFiles : MemoryFiles() {
    var rejectDeletion = false
    val redirectedPaths = mutableMapOf<String, String>()

    override fun canonicalPath(path: String): String? = redirectedPaths[path] ?: path
    override fun deleteRecursively(path: String): Boolean = !rejectDeletion && super.deleteRecursively(path)
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/download/ProfileDownloadBindingsTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/download/ProfileDownloadBindingsTest.kt) · test / fixture · 172 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
31: class ProfileDownloadBindingsTest {
154: private class FakeDownloads : DownloadService {
156: override suspend fun initialize(poolSize: Int) = Unit
157: override fun enqueue(request: DownloadRequest, onProgress: (DownloadProgress) -> Unit) = Unit
158: override fun cancel(taskId: String) = Unit
159: override fun cancelAll() { cancels++ }
160: override fun pause(taskId: String) = Unit
161: override fun resume(taskId: String) = Unit
162: override fun retry(taskId: String) = false
163: override fun storageLocation(taskId: String): String? = null
164: override fun deleteArtifacts(taskId: String) = Unit
165: override fun activeDownloads(): List<DownloadProgress> = emptyList()
```

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

### Complete file

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

package eu.friedcutlet.yokan.services.download

import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.services.scheduling.ProfileWorkNamespace
import eu.friedcutlet.yokan.services.scheduling.ProfileWorkResult
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.SupervisorJob
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.assertFalse
import kotlin.test.assertFailsWith
import kotlin.test.assertNotEquals
import kotlin.test.assertNull
import kotlin.test.assertSame
import kotlin.test.assertTrue

class ProfileDownloadBindingsTest {
    @Test fun alreadyExpiredCallerCannotDispatchIntoALiveDownloadOwner() = runTest {
        val registry = ProfileDownloadBindings(); val parent = SupervisorJob()
        val binding = registry.install(A, FakeDownloads(), CoroutineScope(parent + UnconfinedTestDispatcher(testScheduler)))
        var effects = 0
        val caller = launch {
            currentCoroutineContext().cancel()
            assertFailsWith<CancellationException> { binding.run { effects++ } }
        }
        caller.join()
        assertEquals(0, effects); assertTrue(binding.isActive)
        assertSame(binding, registry.resolve(A.value, binding.token))
        parent.cancelAndJoin()
    }

    @Test fun cancelActionsReachOnlyTheirRecordedLiveOwner() = runTest {
        val registry = ProfileDownloadBindings()
        val a = FakeDownloads(); val b = FakeDownloads()
        val parentA = SupervisorJob(); val parentB = SupervisorJob()
        val scopeA = CoroutineScope(parentA + StandardTestDispatcher(testScheduler))
        val scopeB = CoroutineScope(parentB + StandardTestDispatcher(testScheduler))
        val left = registry.install(A, a, scopeA); val right = registry.install(B, b, scopeB)
        registry.resolve(A.value, left.token)?.cancelAll(); testScheduler.runCurrent()
        assertEquals(1, a.cancels); assertEquals(0, b.cancels)
        assertNull(registry.resolve(B.value, left.token)); assertNull(registry.resolve(A.value, right.token))
        parentA.cancelAndJoin()
        assertNull(registry.resolve(A.value, left.token)); assertSame(right, registry.resolve(B.value, right.token))
        right.cancelAll(); testScheduler.runCurrent(); assertEquals(1, b.cancels)
        parentB.cancelAndJoin()
    }

    @Test fun oldActionsAndCleanupCannotAffectAReplacementSessionForTheSameProfile() = runTest {
        val registry = ProfileDownloadBindings()
        val parentOld = SupervisorJob(); val parentNew = SupervisorJob()
        val oldDownloads = FakeDownloads(); val newDownloads = FakeDownloads()
        val old = registry.install(A, oldDownloads, CoroutineScope(parentOld + StandardTestDispatcher(testScheduler)))
        val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>()
        val mirror = launch {
            old.run { try { entered.complete(Unit); awaitCancellation() } finally { withContext(NonCancellable) { release.await() } } }
        }
        entered.await()
        val next = registry.install(A, newDownloads, CoroutineScope(parentNew + StandardTestDispatcher(testScheduler)))
        assertNotEquals(old.token, next.token); assertNotEquals(old.actionIdentity, next.actionIdentity)
        assertNull(registry.resolve(A.value, old.token)); assertSame(next, registry.resolve(A.value, next.token))
        old.cancelAll(); testScheduler.runCurrent()
        assertEquals(0, oldDownloads.cancels); assertEquals(0, newDownloads.cancels)
        release.complete(Unit); mirror.join(); parentOld.cancelAndJoin()
        assertSame(next, registry.resolve(A.value, next.token))
        next.cancelAll(); testScheduler.runCurrent(); assertEquals(1, newDownloads.cancels)
        parentNew.cancelAndJoin()
    }

    @Test fun expiredServiceMirrorJoinsCleanupWithoutCancelingTheDownloadOwner() = runTest {
        val registry = ProfileDownloadBindings(); val parent = SupervisorJob()
        val scope = CoroutineScope(parent + StandardTestDispatcher(testScheduler))
        val binding = registry.install(A, FakeDownloads(), scope)
        val downloading = scope.launch { awaitCancellation() }
        val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>()
        var finalized = false
        val mirror = launch {
            binding.run { try { entered.complete(Unit); awaitCancellation() } finally { withContext(NonCancellable) { release.await(); finalized = true } } }
        }
        entered.await(); mirror.cancel(); testScheduler.runCurrent()
        assertFalse(mirror.isCompleted); assertFalse(finalized); assertTrue(downloading.isActive)
        release.complete(Unit); mirror.join()
        assertTrue(finalized); assertTrue(downloading.isActive); assertTrue(binding.isActive)
        assertSame(binding, registry.resolve(A.value, binding.token))
        parent.cancelAndJoin()
    }

    @Test fun ownerRetirementRejectsActionsImmediatelyAndJoinsMirrorFinalizers() = runTest {
        val registry = ProfileDownloadBindings(); val parent = SupervisorJob()
        val downloads = FakeDownloads()
        val binding = registry.install(A, downloads, CoroutineScope(parent + StandardTestDispatcher(testScheduler)))
        val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>()
        var finalized = false
        val mirror = launch {
            binding.run { try { entered.complete(Unit); awaitCancellation() } finally { withContext(NonCancellable) { release.await(); finalized = true } } }
        }
        entered.await(); parent.cancel(); testScheduler.runCurrent()
        assertNull(registry.resolve(A.value, binding.token)); assertFalse(parent.isCompleted)
        binding.cancelAll(); testScheduler.runCurrent(); assertEquals(0, downloads.cancels)
        release.complete(Unit); parent.join(); mirror.join()
        assertTrue(finalized); assertTrue(parent.isCompleted)
        assertEquals(ProfileWorkResult.Skipped, binding.run { error("Retired work") })
    }

    @Test fun retirementBeforeDispatchNeverRunsAQueuedCancelAction() = runTest {
        val registry = ProfileDownloadBindings(); val parent = SupervisorJob(); val downloads = FakeDownloads()
        val binding = registry.install(A, downloads, CoroutineScope(parent + StandardTestDispatcher(testScheduler)))
        binding.cancelAll(); parent.cancelAndJoin()
        assertEquals(0, downloads.cancels); assertNull(registry.resolve(A.value, binding.token))
    }

    @Test fun missingMalformedAndUnknownActionsNeverBootstrapOrFallBack() = runTest {
        val registry = ProfileDownloadBindings(); val parent = SupervisorJob()
        val binding = registry.install(ProfileId.Default, FakeDownloads(), CoroutineScope(parent + StandardTestDispatcher(testScheduler)))
        for (owner in listOf(null, "", "../default", A.value)) assertNull(registry.resolve(owner, binding.token))
        assertNull(registry.resolve("default", null)); assertNull(registry.resolve("default", "old"))
        assertSame(binding, registry.resolve("default", binding.token))
        parent.cancelAndJoin()
    }

    @Test fun retiredInstallationCannotDisplaceALiveCapability() = runTest {
        val registry = ProfileDownloadBindings(); val parent = SupervisorJob(); val retired = SupervisorJob()
        val binding = registry.install(A, FakeDownloads(), CoroutineScope(parent + StandardTestDispatcher(testScheduler)))
        retired.cancelAndJoin()
        assertFailsWith<IllegalArgumentException> { registry.install(A, FakeDownloads(), CoroutineScope(retired + StandardTestDispatcher(testScheduler))) }
        assertSame(binding, registry.resolve(A.value, binding.token))
        parent.cancelAndJoin()
    }

    @Test fun resumeNamesAndActionIdentitiesPartitionIdenticalChapterQueues() = runTest {
        val registry = ProfileDownloadBindings(); val parent = SupervisorJob()
        val scope = CoroutineScope(parent + StandardTestDispatcher(testScheduler))
        val ids = listOf(ProfileId.Default, A, B)
        val names = ids.map { ProfileWorkNamespace(it).uniqueName("yokan.download_resume") }
        val bindings = ids.map { registry.install(it, FakeDownloads(), scope) }
        assertEquals("yokan.download_resume", names.first()); assertEquals(3, names.distinct().size)
        assertEquals(3, bindings.map { it.actionIdentity }.distinct().size)
        parent.cancelAndJoin()
    }

    private class FakeDownloads : DownloadService {
        var cancels = 0
        override suspend fun initialize(poolSize: Int) = Unit
        override fun enqueue(request: DownloadRequest, onProgress: (DownloadProgress) -> Unit) = Unit
        override fun cancel(taskId: String) = Unit
        override fun cancelAll() { cancels++ }
        override fun pause(taskId: String) = Unit
        override fun resume(taskId: String) = Unit
        override fun retry(taskId: String) = false
        override fun storageLocation(taskId: String): String? = null
        override fun deleteArtifacts(taskId: String) = Unit
        override fun activeDownloads(): List<DownloadProgress> = emptyList()
    }

    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/services/download/ResumableDownloadTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/download/ResumableDownloadTest.kt) · test / fixture · 100 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
14: class ResumableDownloadTest {
15: private fun transport(block: suspend (HttpRequest, suspend (ByteArray) -> Unit) -> HttpStreamResponse) = object : HttpService {
16: override suspend fun request(request: HttpRequest) = error("Unexpected buffered request")
17: override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit) = block(request, onChunk)
20: private suspend fun partial(files: LocalFileService, validator: Boolean = true) {
34: fun resumesValidatedBytesAcrossTransferInstances() = runTest {
52: fun ignoredRangeRestartsWithoutAppendingDifferentRepresentation() = runTest {
70: fun missingValidatorRestartsAndTruncatedSuccessIsNotComplete() = runTest {
85: fun invalidContentRangeNeverAppends() = runTest {
```

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

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.download

import eu.friedcutlet.yokan.services.files.LocalFileService
import eu.friedcutlet.yokan.services.files.MemoryFiles
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.http.HttpStreamResponse
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import kotlinx.coroutines.test.runTest

class ResumableDownloadTest {
    private fun transport(block: suspend (HttpRequest, suspend (ByteArray) -> Unit) -> HttpStreamResponse) = object : HttpService {
        override suspend fun request(request: HttpRequest) = error("Unexpected buffered request")
        override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit) = block(request, onChunk)
    }

    private suspend fun partial(files: LocalFileService, validator: Boolean = true) {
        val http = transport { request, write ->
            request.onStreamResponse?.invoke(HttpStreamResponse(200, buildMap {
                put("Content-Length", "6")
                if (validator) put("ETag", "\"v1\"")
            }))
            write("abc".encodeToByteArray())
            error("Connection lost")
        }
        val result = ResumableDownload(http, files).transfer("https://test/video", emptyMap(), "/video.part") {}
        assertFalse(result.complete)
    }

    @Test
    fun resumesValidatedBytesAcrossTransferInstances() = runTest {
        val files = MemoryFiles()
        partial(files)
        val http = transport { request, write ->
            assertEquals("bytes=3-", request.headers["Range"])
            assertEquals("\"v1\"", request.headers["If-Range"])
            val response = HttpStreamResponse(206, mapOf("Content-Range" to "bytes 3-5/6", "ETag" to "\"v1\"", "Content-Length" to "3"))
            request.onStreamResponse?.invoke(response)
            write("def".encodeToByteArray())
            response
        }
        val result = ResumableDownload(http, files).transfer("https://test/video", emptyMap(), "/video.part") {}
        assertTrue(result.complete)
        assertEquals(6L, result.bytes)
        assertEquals("abcdef", files.readBytes("/video.part").decodeToString())
    }

    @Test
    fun ignoredRangeRestartsWithoutAppendingDifferentRepresentation() = runTest {
        val files = MemoryFiles()
        partial(files)
        var calls = 0
        val http = transport { request, write ->
            calls++
            if (calls == 2) assertFalse("Range" in request.headers)
            val response = HttpStreamResponse(200, mapOf("Content-Length" to "6", "ETag" to "\"v2\""))
            request.onStreamResponse?.invoke(response)
            write("uvwxyz".encodeToByteArray())
            response
        }
        assertTrue(ResumableDownload(http, files).transfer("https://test/video", emptyMap(), "/video.part") {}.complete)
        assertEquals(2, calls)
        assertEquals("uvwxyz", files.readBytes("/video.part").decodeToString())
    }

    @Test
    fun missingValidatorRestartsAndTruncatedSuccessIsNotComplete() = runTest {
        val files = MemoryFiles()
        partial(files, validator = false)
        val http = transport { request, write ->
            assertFalse("Range" in request.headers)
            val response = HttpStreamResponse(200, mapOf("Content-Length" to "6"))
            request.onStreamResponse?.invoke(response)
            write("xy".encodeToByteArray())
            response
        }
        assertFalse(ResumableDownload(http, files).transfer("https://test/video", emptyMap(), "/video.part") {}.complete)
        assertEquals("xy", files.readBytes("/video.part").decodeToString())
    }

    @Test
    fun invalidContentRangeNeverAppends() = runTest {
        val files = MemoryFiles()
        partial(files)
        var calls = 0
        val http = transport { request, write ->
            calls++
            val response = if (calls == 1) HttpStreamResponse(206, mapOf("Content-Range" to "bytes 2-5/6"))
                else HttpStreamResponse(200, mapOf("Content-Length" to "6"))
            request.onStreamResponse?.invoke(response)
            write("uvwxyz".encodeToByteArray())
            response
        }
        assertTrue(ResumableDownload(http, files).transfer("https://test/video", emptyMap(), "/video.part") {}.complete)
        assertEquals("uvwxyz", files.readBytes("/video.part").decodeToString())
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/download/SplitPageStoreTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/download/SplitPageStoreTest.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
10: class SplitPageStoreTest {
124: private class Files : LocalFileService {
132: fun withOriginal() = apply { writeBytes("/chapter/0001.jpg", byteArrayOf(9, 8, 7)); writeBytes("/chapter/0001.jpg.complete", ByteArray(0)) }
133: override fun writeBytes(path: String, bytes: ByteArray) { data[path] = bytes.copyOf() }
134: override fun readBytes(path: String) = requireNotNull(data[path]).copyOf()
135: override fun exists(path: String) = path in data
136: override fun promote(sourcePath: String, targetPath: String): Boolean {
141: override fun deleteRecursively(path: String): Boolean {
146: override fun directorySize(path: String) = reportedSize ?: data[path]?.size?.toLong() ?: 0L
147: override fun canonicalPath(path: String) = path
148: override fun openLocation(path: String) = false
149: override fun listLocalEntries(root: String) = emptyList<LocalEntry>()
150: override fun listFiles(root: String) = data.entries.filter { it.key.substringBeforeLast('/') == root }
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/download/SplitPageStoreTest.kt) · SHA-256 `38206e6f8395f8b034b30bac45b8ffc546b291e818612309cab621294837338d`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.download

import eu.friedcutlet.yokan.services.files.LocalEntry
import eu.friedcutlet.yokan.services.files.LocalFileEntry
import eu.friedcutlet.yokan.services.files.LocalFileService
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.test.runTest
import kotlin.test.*

class SplitPageStoreTest {
    @Test fun regionsCoverEveryPixelInOrderWithoutExceedingLimits() {
        assertEquals(listOf(TallImageRegion(0, 4096), TallImageRegion(4096, 4096), TallImageRegion(8192, 809)), tallImageRegions(800, 9001, 4096))
        assertTrue(tallImageRegions(800, 1024, 4096).isEmpty())
        assertTrue(tallImageRegions(4000, 7000, 4096).isEmpty())
        assertTrue(tallImageRegions(Int.MAX_VALUE, Int.MAX_VALUE, 4096).isEmpty())
        assertTrue(tallImageRegions(1000, 24001, 4096).isEmpty())
        assertEquals(1024, tallImageRegions(400, 3000, -1).first().height)
    }

    @Test fun committedTilesResumeWithoutFetchingOrDecodingOriginal() = runTest {
        val files = Files().withOriginal()
        var decodes = 0
        val store = SplitPageStore(files) { _, _, tile ->
            decodes++
            tile(0, byteArrayOf(1, 2))
            tile(1, byteArrayOf(3, 4, 5))
            true
        }
        assertEquals(5L, store.process("/chapter/0001.jpg", 4096))
        assertFalse(files.exists("/chapter/0001.jpg"))
        assertFalse(files.exists("/chapter/0001.jpg.complete"))
        assertEquals(listOf("0001.split.json", "0001_s0001.jpg", "0001_s0002.jpg"), files.listFiles("/chapter").map { it.name }.sorted())
        assertEquals(5L, SplitPageStore(files).savedSize("/chapter", "0001"))
        assertEquals(1, decodes)
    }

    @Test fun failedDecodeCleansTilesAndKeepsOriginal() = runTest {
        val files = Files().withOriginal()
        val store = SplitPageStore(files) { _, _, tile ->
            tile(0, byteArrayOf(1))
            error("bad codec")
        }
        assertEquals(3L, store.process("/chapter/0001.jpg", 4096))
        assertEquals(setOf("/chapter/0001.jpg", "/chapter/0001.jpg.complete"), files.data.keys)
        assertContentEquals(byteArrayOf(9, 8, 7), files.readBytes("/chapter/0001.jpg"))
    }

    @Test fun cancelledSplitRetainsOriginalAndOrphansAreReplacedOnRetry() = runTest {
        val files = Files().withOriginal()
        val cancelled = SplitPageStore(files) { _, _, tile ->
            tile(0, byteArrayOf(1))
            throw CancellationException("pause")
        }
        assertFailsWith<CancellationException> { cancelled.process("/chapter/0001.jpg", 4096) }
        assertTrue(files.exists("/chapter/0001.jpg.complete"))
        val retry = SplitPageStore(files) { _, _, tile ->
            tile(0, byteArrayOf(4, 5))
            tile(1, byteArrayOf(6))
            true
        }
        assertEquals(3L, retry.process("/chapter/0001.jpg", 4096))
        assertContentEquals(byteArrayOf(4, 5), files.readBytes("/chapter/0001_s0001.jpg"))
    }

    @Test fun promotionFailureKeepsOriginalAndNeverCommitsPartialManifest() = runTest {
        val files = Files().withOriginal().apply { failedPromotionSuffix = "_s0002.jpg" }
        val store = SplitPageStore(files) { _, _, tile -> tile(0, byteArrayOf(1)); tile(1, byteArrayOf(2)); true }
        assertEquals(3L, store.process("/chapter/0001.jpg", 4096))
        assertFalse(files.exists("/chapter/0001.split.json"))
        assertEquals(2, files.data.size)
    }

    @Test fun manifestCommitFailureCanBeRetriedWithoutLosingOriginal() = runTest {
        val files = Files().withOriginal().apply { failedPromotionSuffix = ".split.json" }
        val store = SplitPageStore(files) { _, _, tile -> tile(0, byteArrayOf(1)); tile(1, byteArrayOf(2)); true }
        assertFailsWith<IllegalStateException> { store.process("/chapter/0001.jpg", 4096) }
        assertNull(store.savedSize("/chapter", "0001"))
        assertTrue(files.exists("/chapter/0001.jpg"))
        files.failedPromotionSuffix = null
        assertEquals(2L, store.process("/chapter/0001.jpg", 4096))
    }

    @Test fun committedManifestFinishesOriginalDeletionAfterCrash() = runTest {
        val files = Files().withOriginal().apply { refuseOriginalDeletion = true }
        val store = SplitPageStore(files) { _, _, tile -> tile(0, byteArrayOf(1)); tile(1, byteArrayOf(2)); true }
        assertFailsWith<IllegalStateException> { store.process("/chapter/0001.jpg", 4096) }
        assertTrue(files.exists("/chapter/0001.split.json"))
        files.refuseOriginalDeletion = false
        assertEquals(2L, SplitPageStore(files).savedSize("/chapter", "0001"))
        assertFalse(files.exists("/chapter/0001.jpg"))
    }

    @Test fun corruptMissingOrTruncatedTilesNeverCountAsSaved() = runTest {
        val files = Files().withOriginal()
        val store = SplitPageStore(files) { _, _, tile -> tile(0, byteArrayOf(1)); tile(1, byteArrayOf(2, 3)); true }
        store.process("/chapter/0001.jpg", 4096)
        files.writeBytes("/chapter/0001_s0002.jpg", byteArrayOf(2))
        assertNull(store.savedSize("/chapter", "0001"))
        files.writeBytes("/chapter/0001.split.json", "{\"version\":1,\"original\":\"../other.jpg\",\"sizes\":[1,1]}".encodeToByteArray())
        assertNull(store.savedSize("/chapter", "0001"))
    }

    @Test fun animationsAndOversizedEncodedImagesBypassDecoder() = runTest {
        val files = Files()
        val store = SplitPageStore(files) { _, _, _ -> error("must not decode") }
        files.writeBytes("/chapter/0001.gif", "GIF89a".encodeToByteArray())
        assertEquals(6L, store.process("/chapter/0001.gif", 4096))
        files.reportedSize = MaxSplitImageBytes + 1
        assertEquals(MaxSplitImageBytes + 1, store.process("/chapter/0001.gif", 4096))
    }

    @Test fun webpAndPngAnimationHeadersAreDetected() {
        val webp = ByteArray(21)
        "RIFF".encodeToByteArray().copyInto(webp)
        "WEBPVP8X".encodeToByteArray().copyInto(webp, 8)
        webp[20] = 2
        assertTrue(webp.mayBeAnimatedImage())
        webp[20] = 0
        assertFalse(webp.mayBeAnimatedImage())
        val apng = byteArrayOf(0x89.toByte(), 80, 78, 71, 13, 10, 26, 10) + ByteArray(4) + "acTL".encodeToByteArray() + ByteArray(4)
        assertTrue(apng.mayBeAnimatedImage())
    }

    private class Files : LocalFileService {
        val data = linkedMapOf<String, ByteArray>()
        var failedPromotionSuffix: String? = null
        var refuseOriginalDeletion = false
        var reportedSize: Long? = null
        override val downloadRoot = "/downloads"
        override val backupRoot = "/backups"
        override val cacheRoot = "/cache"
        fun withOriginal() = apply { writeBytes("/chapter/0001.jpg", byteArrayOf(9, 8, 7)); writeBytes("/chapter/0001.jpg.complete", ByteArray(0)) }
        override fun writeBytes(path: String, bytes: ByteArray) { data[path] = bytes.copyOf() }
        override fun readBytes(path: String) = requireNotNull(data[path]).copyOf()
        override fun exists(path: String) = path in data
        override fun promote(sourcePath: String, targetPath: String): Boolean {
            if (failedPromotionSuffix?.let(targetPath::endsWith) == true) return false
            data[targetPath] = data.remove(sourcePath) ?: return false
            return true
        }
        override fun deleteRecursively(path: String): Boolean {
            if (refuseOriginalDeletion && path.endsWith("/0001.jpg")) return false
            data.remove(path)
            return true
        }
        override fun directorySize(path: String) = reportedSize ?: data[path]?.size?.toLong() ?: 0L
        override fun canonicalPath(path: String) = path
        override fun openLocation(path: String) = false
        override fun listLocalEntries(root: String) = emptyList<LocalEntry>()
        override fun listFiles(root: String) = data.entries.filter { it.key.substringBeforeLast('/') == root }
            .map { LocalFileEntry(it.key, it.key.substringAfterLast('/'), it.value.size.toLong(), 0L) }
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/downloads/DownloadManagerRowsTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/downloads/DownloadManagerRowsTest.kt) · test / fixture · 95 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 DownloadManagerRowsTest {
11: private fun row(saved: DbDownload = record, progress: DownloadProgress? = null, location: String? = null) =
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/downloads/DownloadManagerRowsTest.kt) · SHA-256 `00504abd1c25f09e4d2c6b2fa1c2436c35d7e33d66342e27fad31c7f6f0151a6`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.screens.downloads

import eu.friedcutlet.yokan.database.DbDownload
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.services.download.DownloadProgress
import kotlin.test.*

class DownloadManagerRowsTest {
    private val record = DbDownload(id = 1, chapterId = 10, succeeded = 2, failed = 0, total = 10, isStartDownload = true)
    private val live = DownloadProgress("chapter-10", 4, 0, 10, DbItemType.Manga)
    private fun row(saved: DbDownload = record, progress: DownloadProgress? = null, location: String? = null) =
        downloadManagerRows(listOf(saved), listOfNotNull(progress)) { location }.single()

    @Test fun cachedDetailsFollowRenamesAndOtherRowsKeepTheirIdentity() {
        val snapshot = eu.friedcutlet.yokan.database.seedDatabaseSnapshot().copy(
            mangas = listOf(eu.friedcutlet.yokan.database.DbManga(id = 1, name = "Old title")),
            chapters = listOf(eu.friedcutlet.yokan.database.DbChapter(id = 10, mangaId = 1, name = "Old chapter")),
            downloads = listOf(record, DbDownload(id = 2, chapterId = 20, isDownload = true)),
        )
        val builder = DownloadQueueEntryBuilder()
        val before = builder.build(snapshot, listOf(live)) { null }
        val progressed = builder.build(snapshot, listOf(live.copy(succeeded = 8))) { null }
        assertEquals(8, progressed.first().row.succeeded)
        assertSame(before.last(), progressed.last())
        val renamed = builder.build(snapshot.copy(
            mangas = listOf(snapshot.mangas.single().copy(name = "New title")),
            chapters = listOf(snapshot.chapters.single().copy(name = "New chapter")),
        ), listOf(live)) { null }
        assertEquals("New title", renamed.first().mangaName)
        assertEquals("New chapter", renamed.first().chapterName)
    }

    @Test fun liveWinsAndTaskIdsAreDeduplicated() {
        val rows = downloadManagerRows(listOf(record, record.copy(id = 2)), listOf(live, live.copy(succeeded = 6))) { null }
        assertEquals(1, rows.size)
        assertEquals(6, rows.single().succeeded)
        assertEquals(.6f, rows.single().fraction)
        assertEquals(DownloadSection.InProgress, rows.single().section)
        assertFalse(rows.single().queued)
    }

    @Test fun failuresAreAttentionOnlyWhenTerminal() {
        assertEquals(DownloadSection.InProgress, row(progress = live.copy(failed = 1)).section)
        val terminal = row(progress = live.copy(succeeded = 9, failed = 1, isCompleted = true), location = "/downloads/chapter")
        assertEquals(DownloadSection.NeedsAttention, terminal.section)
        assertTrue(terminal.canRetry)
        assertFalse(terminal.queued)
        assertEquals(DownloadSection.NeedsAttention, row(record.copy(isStartDownload = false, failed = 1)).section)
    }

    @Test fun onlySuccessfulRecordsAreCompleted() {
        assertEquals(DownloadSection.InProgress, row(progress = live.copy(succeeded = 10, isCompleted = true)).section)
        assertEquals(DownloadSection.Completed, row(record.copy(isDownload = true, succeeded = 10)).section)
        assertEquals(DownloadSection.NeedsAttention, row(record.copy(isDownload = true, failed = 1)).section)
        assertEquals(DownloadSection.InProgress, row(record.copy(isDownload = true), live).section)
    }

    @Test fun restartRowsRetryFromTheirChapterButCannotReorder() {
        for (saved in listOf(record, record.copy(total = 0), record.copy(isStartDownload = false), record.copy(failed = 2))) {
            val restarted = row(saved)
            assertEquals(DownloadSection.NeedsAttention, restarted.section)
            assertTrue(restarted.canRetry)
            assertFalse(restarted.queued)
        }
        assertFalse(row(DbDownload(id = 3, failed = 1)).canRetry)
        assertTrue(row(record.copy(succeeded = 0), location = "/session/request").queued)
        assertFalse(row(location = "/session/request").queued)
        assertFalse(row(progress = live.copy(isPaused = true), location = "/session/request").queued)
        assertFalse(row(record.copy(isDownload = true), location = "/session/request").queued)
    }

    @Test fun unknownTotalNeverProducesAPercentage() {
        assertNull(row(record.copy(total = null)).fraction)
        assertNull(row(progress = live.copy(total = 0)).fraction)
        assertNull(row(progress = live.copy(total = -1)).fraction)
        assertEquals(1f, row(progress = live.copy(succeeded = 20)).fraction)
    }

    @Test fun orphanAndLiveOnlyRowsArePreserved() {
        val rows = downloadManagerRows(listOf(DbDownload(id = 3), record.copy(chapterId = 999)), listOf(live)) { null }
        assertEquals(setOf("download-3", "chapter-999", "chapter-10"), rows.map { it.taskId }.toSet())
        assertNull(rows.last().record)
        assertEquals(DownloadSection.NeedsAttention, rows.first().section)
    }

    @Test fun sessionFailuresAndCancelledRequestsCanRetryButNotReorder() {
        for (saved in listOf(record.copy(isStartDownload = false), record.copy(isStartDownload = false, failed = 3))) {
            val stopped = row(saved, location = "/session/request")
            assertEquals(DownloadSection.NeedsAttention, stopped.section)
            assertTrue(stopped.canRetry)
            assertFalse(stopped.queued)
        }
        assertFalse(row(record.copy(isDownload = true), location = "/session/request").canRetry)
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/downloads/DownloadQueueViewModelTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/downloads/DownloadQueueViewModelTest.kt) · test / fixture · 119 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
27: class DownloadQueueViewModelTest {
41: fun tearDown() = host.close()
43: private fun TestScope.viewModel(settings: SettingsStore): DownloadQueueViewModel = host.create {
55: fun queuedDownloadsShowTheirNamesAndFollowDatabaseChanges() = runTest(dispatcher) {
70: fun movingAQueuedRowPublishesAndPersistsTheNewOrder() = runTest(dispatcher) {
84: fun retryReportsUnavailableAndFailedRetriesUntilDismissed() = runTest(dispatcher) {
100: private fun queued(id: Long, chapterId: Long) = DbDownload(id = id, chapterId = chapterId, isStartDownload = true)
103: private class FakeDownloads : DownloadService {
107: override suspend fun initialize(poolSize: Int) = Unit
108: override fun enqueue(request: DownloadRequest, onProgress: (DownloadProgress) -> Unit) = Unit
109: override fun cancel(taskId: String) = Unit
110: override fun pause(taskId: String) = Unit
111: override fun resume(taskId: String) = Unit
112: override fun retry(taskId: String): Boolean = if (retryFails) error("retry failed") else false
113: override fun storageLocation(taskId: String): String = "/downloads/$taskId"
114: override fun deleteArtifacts(taskId: String) = Unit
115: override fun activeDownloads(): List<DownloadProgress> = emptyList()
116: override fun reorderQueue(order: List<Long>) {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/downloads/DownloadQueueViewModelTest.kt) · SHA-256 `635c3970043407bf15fd8a1739681a8505b2850812b3c946ceb47226a034e6e3`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.screens.downloads

import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbDownload
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.emptySnapshot
import eu.friedcutlet.yokan.services.download.ChapterDownloads
import eu.friedcutlet.yokan.services.download.DownloadProgress
import eu.friedcutlet.yokan.services.download.DownloadRequest
import eu.friedcutlet.yokan.services.download.DownloadService
import eu.friedcutlet.yokan.services.files.NoFiles
import eu.friedcutlet.yokan.services.notifications.NoNotifications
import eu.friedcutlet.yokan.ui.ViewModelTestHost
import kotlin.test.AfterTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest

@OptIn(ExperimentalCoroutinesApi::class)
class DownloadQueueViewModelTest {
    private val host = ViewModelTestHost()
    private val dispatcher = host.dispatcher
    private val database = InMemoryYokanDatabase(
        emptySnapshot().copy(
            mangas = listOf(DbManga(id = 1, name = "Title", source = "Source")),
            chapters = listOf(DbChapter(id = 11, mangaId = 1, name = "One"), DbChapter(id = 12, mangaId = 1, name = "Two")),
            downloads = listOf(queued(1, 11), queued(2, 12)),
        ),
    )
    private val repository = DefaultYokanRepository(database)
    private val downloader = FakeDownloads()

    @AfterTest
    fun tearDown() = host.close()

    private fun TestScope.viewModel(settings: SettingsStore): DownloadQueueViewModel = host.create {
        DownloadQueueViewModel(
            repository = repository,
            downloader = downloader,
            chapterDownloads = ChapterDownloads(repository, database, downloader, NoNotifications, settings, NoFiles, backgroundScope),
            localFiles = NoFiles,
            settings = settings,
            workDispatcher = dispatcher,
        )
    }

    @Test
    fun queuedDownloadsShowTheirNamesAndFollowDatabaseChanges() = runTest(dispatcher) {
        val vm = viewModel(SettingsStore(repository, backgroundScope) {})
        runCurrent()

        assertEquals(listOf("One", "Two"), vm.state.value.queued.map { it.chapterName })
        assertEquals("Title", vm.state.value.queued.first().mangaName)

        database.upsertDownload(queued(3, 13))
        runCurrent()

        assertEquals(listOf(1L, 2L, 3L), vm.state.value.queued.map { it.row.record?.id })
        assertEquals(true, vm.state.value.queued.last().missingDetails)
    }

    @Test
    fun movingAQueuedRowPublishesAndPersistsTheNewOrder() = runTest(dispatcher) {
        val settings = SettingsStore(repository, backgroundScope) {}
        val vm = viewModel(settings)
        runCurrent()

        vm.move(from = 0, to = 1)
        runCurrent()

        assertEquals(listOf(2L, 1L), vm.state.value.queued.map { it.row.record?.id })
        assertEquals(listOf(2L, 1L), settings.db.value.downloadQueueOrder)
        assertEquals(listOf(2L, 1L), downloader.order)
    }

    @Test
    fun retryReportsUnavailableAndFailedRetriesUntilDismissed() = runTest(dispatcher) {
        val vm = viewModel(SettingsStore(repository, backgroundScope) {})
        runCurrent()
        val row = vm.state.value.queued.first().row

        vm.retry(row)
        assertEquals(DownloadActionError.RetryUnavailable, vm.state.value.actionError)
        downloader.retryFails = true
        vm.retry(row)
        assertEquals(DownloadActionError.Failed, vm.state.value.actionError)
        vm.dismissActionFailed()

        assertNull(vm.state.value.actionError)
    }
}

private fun queued(id: Long, chapterId: Long) = DbDownload(id = id, chapterId = chapterId, isStartDownload = true)

/** Keeps every request "queued": a location but no live progress. */
private class FakeDownloads : DownloadService {
    var retryFails = false
    var order: List<Long> = emptyList()

    override suspend fun initialize(poolSize: Int) = Unit
    override fun enqueue(request: DownloadRequest, onProgress: (DownloadProgress) -> Unit) = Unit
    override fun cancel(taskId: String) = Unit
    override fun pause(taskId: String) = Unit
    override fun resume(taskId: String) = Unit
    override fun retry(taskId: String): Boolean = if (retryFails) error("retry failed") else false
    override fun storageLocation(taskId: String): String = "/downloads/$taskId"
    override fun deleteArtifacts(taskId: String) = Unit
    override fun activeDownloads(): List<DownloadProgress> = emptyList()
    override fun reorderQueue(order: List<Long>) {
        this.order = order
    }
}
```
[complete-source-end]: #

## `composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/download/DownloadKeepAlive.desktop.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/download/DownloadKeepAlive.desktop.kt) · implementation · 8 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: actual fun keepDownloadsAlive(downloads: DownloadService, database: YokanDatabase, scope: CoroutineScope, profileId: ProfileId) = Unit
```

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

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.download

import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.domain.ProfileId
import kotlinx.coroutines.CoroutineScope

/** The desktop process lives until the user quits it. */
actual fun keepDownloadsAlive(downloads: DownloadService, database: YokanDatabase, scope: CoroutineScope, profileId: ProfileId) = Unit
```
[complete-source-end]: #

## `composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/download/EinkPageTranscoderTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/download/EinkPageTranscoderTest.kt) · test / fixture · 46 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
13: class EinkPageTranscoderTest {
37: private fun colorPage(width: Int, height: Int): ByteArray {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/download/EinkPageTranscoderTest.kt) · SHA-256 `5d072c8bbfe19ed0218a56f381db4cda88690313c47a6eae86edae1bfcf4874b`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.download

import org.jetbrains.skia.Bitmap
import org.jetbrains.skia.Color
import org.jetbrains.skia.EncodedImageFormat
import org.jetbrains.skia.Image
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue

class EinkPageTranscoderTest {
    @Test fun colorPageBecomesSmallerGrayscaleJpegAtPanelSize() {
        val page = colorPage(2000, 2880)
        val result = assertNotNull(transcodeEinkPage(page, 1264))
        assertTrue(result.size < page.size)
        assertEquals(0xFF.toByte(), result[0]); assertEquals(0xD8.toByte(), result[1]) // JPEG SOI
        Image.makeFromEncoded(result).use { image ->
            assertEquals(1264, image.width)
            assertEquals(1820, image.height)
            val pixels = Bitmap.makeFromImage(image)
            listOf(10 to 10, 632 to 900, 1200 to 1800).forEach { (x, y) ->
                val color = pixels.getColor(x, y)
                assertEquals(Color.getR(color), Color.getG(color))
                assertEquals(Color.getG(color), Color.getB(color))
            }
        }
    }

    @Test fun gifsAndUndecodableBytesAreKept() {
        assertNull(transcodeEinkPage("GIF89a-animated".encodeToByteArray(), 1264))
        assertNull(transcodeEinkPage(byteArrayOf(1, 2, 3, 4, 5), 1264))
    }

    /** Noisy color pixels, like scanned artwork: PNG cannot shrink them, so the size check is meaningful. */
    private fun colorPage(width: Int, height: Int): ByteArray {
        val random = kotlin.random.Random(7)
        val pixels = ByteArray(width * height * 4) { if (it % 4 == 3) -1 else random.nextInt(256).toByte() }
        val bitmap = Bitmap().apply {
            allocPixels(org.jetbrains.skia.ImageInfo.makeN32(width, height, org.jetbrains.skia.ColorAlphaType.OPAQUE))
            installPixels(pixels)
        }
        return Image.makeFromBitmap(bitmap).use { assertNotNull(it.encodeToData(EncodedImageFormat.PNG)).bytes }
    }
}
```
[complete-source-end]: #

## `composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/download/TallImageSplitterTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/download/TallImageSplitterTest.kt) · test / fixture · 46 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
11: class TallImageSplitterTest {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/download/TallImageSplitterTest.kt) · SHA-256 `4f037d80570e2e15222a7b2f06a3ae7ea7bd66f7afce92e016d759d33c905bc4`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.download

import java.awt.Color
import java.awt.image.BufferedImage
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import javax.imageio.ImageIO
import kotlinx.coroutines.test.runTest
import kotlin.test.*

class TallImageSplitterTest {
    @Test fun realCodecPreservesTileOrderWidthAndLastRow() = runTest {
        val image = BufferedImage(128, 2501, BufferedImage.TYPE_INT_RGB)
        val graphics = image.createGraphics()
        try {
            graphics.color = Color.RED; graphics.fillRect(0, 0, 128, 1024)
            graphics.color = Color.GREEN; graphics.fillRect(0, 1024, 128, 1024)
            graphics.color = Color.BLUE; graphics.fillRect(0, 2048, 128, 453)
        } finally { graphics.dispose() }
        val bytes = ByteArrayOutputStream().use { ImageIO.write(image, "png", it); it.toByteArray() }
        val tiles = mutableListOf<BufferedImage>()
        assertTrue(splitTallImage(bytes, 1024) { index, encoded ->
            assertEquals(tiles.size, index)
            tiles += requireNotNull(ImageIO.read(ByteArrayInputStream(encoded)))
        })
        assertEquals(listOf(1024, 1024, 453), tiles.map { it.height })
        assertTrue(tiles.all { it.width == 128 })
        val colors = tiles.map { Color(it.getRGB(64, it.height - 1)) }
        assertTrue(colors[0].red > 240 && colors[0].green < 15)
        assertTrue(colors[1].green > 240 && colors[1].blue < 15)
        assertTrue(colors[2].blue > 240 && colors[2].red < 15)
    }

    @Test fun transparentPagesUseWhiteBackground() = runTest {
        val image = BufferedImage(64, 2049, BufferedImage.TYPE_INT_ARGB)
        val bytes = ByteArrayOutputStream().use { ImageIO.write(image, "png", it); it.toByteArray() }
        var count = 0
        assertTrue(splitTallImage(bytes, 1024) { _, encoded ->
            val tile = requireNotNull(ImageIO.read(ByteArrayInputStream(encoded)))
            val color = Color(tile.getRGB(0, 0))
            assertTrue(color.red > 250 && color.green > 250 && color.blue > 250)
            count++
        })
        assertEquals(3, count)
    }
}
```
[complete-source-end]: #

## `composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/download/DownloadKeepAlive.ios.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/download/DownloadKeepAlive.ios.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
9: actual fun keepDownloadsAlive(downloads: DownloadService, database: YokanDatabase, scope: CoroutineScope, profileId: ProfileId) = Unit
```

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

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.download

import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.domain.ProfileId
import kotlinx.coroutines.CoroutineScope

// ponytail: iOS suspends the app soon after it leaves the screen; interrupted downloads resume on the next
// launch. A background URLSession would be the upgrade.
actual fun keepDownloadsAlive(downloads: DownloadService, database: YokanDatabase, scope: CoroutineScope, profileId: ProfileId) = Unit
```
[complete-source-end]: #

## `composeApp/src/skikoMain/kotlin/eu/friedcutlet/yokan/services/download/EinkPageTranscoder.skiko.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/skikoMain/kotlin/eu/friedcutlet/yokan/services/download/EinkPageTranscoder.skiko.kt) · implementation · 48 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 actual fun transcodeEinkPage(bytes: ByteArray, maxShortSide: Int): ByteArray? {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/skikoMain/kotlin/eu/friedcutlet/yokan/services/download/EinkPageTranscoder.skiko.kt) · SHA-256 `c020d3c8d4d5dc9368a3ef779b30d394ba56486d2ce8ac25d3857740db825d55`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.download

import eu.friedcutlet.yokan.database.einkScaledSize
import org.jetbrains.skia.ColorAlphaType
import org.jetbrains.skia.ColorType
import org.jetbrains.skia.EncodedImageFormat
import org.jetbrains.skia.FilterMipmap
import org.jetbrains.skia.FilterMode
import org.jetbrains.skia.Image
import org.jetbrains.skia.ImageInfo
import org.jetbrains.skia.MipmapMode
import org.jetbrains.skia.Rect
import org.jetbrains.skia.Surface

internal actual fun transcodeEinkPage(bytes: ByteArray, maxShortSide: Int): ByteArray? {
    if (bytes.isGif()) return null
    // Skia objects are not AutoCloseable on every target, so they are closed explicitly.
    val image = runCatching { Image.makeFromEncoded(bytes) }.getOrNull() ?: return null
    val encoded: ByteArray? = try {
        val (width, height) = einkScaledSize(image.width, image.height, maxShortSide)
        // A GRAY_8 target converts to luminance while drawing and encodes a single-channel JPEG.
        val surface = Surface.makeRaster(ImageInfo(width, height, ColorType.GRAY_8, ColorAlphaType.OPAQUE))
        try {
            surface.canvas.clear(org.jetbrains.skia.Color.WHITE)
            surface.canvas.drawImageRect(
                image,
                Rect.makeWH(image.width.toFloat(), image.height.toFloat()),
                Rect.makeWH(width.toFloat(), height.toFloat()),
                FilterMipmap(FilterMode.LINEAR, MipmapMode.LINEAR),
                null,
                true,
            )
            val snapshot = surface.makeImageSnapshot()
            try {
                snapshot.encodeToData(EncodedImageFormat.JPEG, EinkJpegQuality)?.bytes
            } finally {
                snapshot.close()
            }
        } finally {
            surface.close()
        }
    } catch (_: Exception) {
        null
    } finally {
        image.close()
    }
    return encoded?.takeIf { it.isNotEmpty() && it.size < bytes.size }
}
```
[complete-source-end]: #

## `composeApp/src/skikoMain/kotlin/eu/friedcutlet/yokan/services/download/TallImageSplitter.skiko.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/skikoMain/kotlin/eu/friedcutlet/yokan/services/download/TallImageSplitter.skiko.kt) · implementation · 51 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
17: internal actual suspend fun splitTallImage(bytes: ByteArray, maximumHeight: Int, writeTile: suspend (index: Int, bytes: ByteArray) -> Unit): Boolean {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/skikoMain/kotlin/eu/friedcutlet/yokan/services/download/TallImageSplitter.skiko.kt) · SHA-256 `864b6d74d16334b24af528c68b02b80caa98baa887a7820c54add238f45c40ec`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.download

import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import org.jetbrains.skia.Color
import org.jetbrains.skia.Codec
import org.jetbrains.skia.Data
import org.jetbrains.skia.EncodedImageFormat
import org.jetbrains.skia.EncodedOrigin
import org.jetbrains.skia.FilterMipmap
import org.jetbrains.skia.FilterMode
import org.jetbrains.skia.Image
import org.jetbrains.skia.MipmapMode
import org.jetbrains.skia.Rect
import org.jetbrains.skia.Surface

internal actual suspend fun splitTallImage(bytes: ByteArray, maximumHeight: Int, writeTile: suspend (index: Int, bytes: ByteArray) -> Unit): Boolean {
    if (bytes.size > MaxSplitImageBytes || bytes.mayBeAnimatedImage()) return false
    val data = Data.makeFromBytes(bytes)
    val regions = try {
        val codec = Codec.makeFromData(data)
        try {
            if (codec.frameCount > 1 || codec.encodedOrigin != EncodedOrigin.TOP_LEFT) return false
            tallImageRegions(codec.width, codec.height, maximumHeight)
        } finally { codec.close() }
    } finally { data.close() }
    if (regions.isEmpty()) return false
    val image = Image.makeFromEncoded(bytes)
    try {
        regions.forEachIndexed { index, region ->
            currentCoroutineContext().ensureActive()
            val surface = Surface.makeRasterN32Premul(image.width, region.height)
            val encoded = try {
                surface.canvas.clear(Color.WHITE)
                surface.canvas.drawImageRect(
                    image,
                    Rect.makeXYWH(0f, region.top.toFloat(), image.width.toFloat(), region.height.toFloat()),
                    Rect.makeWH(image.width.toFloat(), region.height.toFloat()),
                    FilterMipmap(FilterMode.NEAREST, MipmapMode.NONE), null, true,
                )
                val snapshot = surface.makeImageSnapshot()
                try {
                    val data = checkNotNull(snapshot.encodeToData(EncodedImageFormat.JPEG, 90))
                    try { data.bytes } finally { data.close() }
                } finally { snapshot.close() }
            } finally { surface.close() }
            writeTile(index, encoded)
        }
        return true
    } finally { image.close() }
}
```
[complete-source-end]: #

## `composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/download/DownloadKeepAlive.wasm.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/download/DownloadKeepAlive.wasm.kt) · implementation · 8 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: actual fun keepDownloadsAlive(downloads: DownloadService, database: YokanDatabase, scope: CoroutineScope, profileId: ProfileId) = Unit
```

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

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.download

import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.domain.ProfileId
import kotlinx.coroutines.CoroutineScope

/** Downloads live with the browser tab. */
actual fun keepDownloadsAlive(downloads: DownloadService, database: YokanDatabase, scope: CoroutineScope, profileId: ProfileId) = Unit
```
[complete-source-end]: #

## `composeApp/src/wasmJsTest/kotlin/eu/friedcutlet/yokan/services/download/TallImageSplitterBrowserTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/wasmJsTest/kotlin/eu/friedcutlet/yokan/services/download/TallImageSplitterBrowserTest.kt) · test / fixture · 27 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 TallImageSplitterBrowserTest {
```

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

### Complete file

```kotlin
@file:OptIn(kotlin.io.encoding.ExperimentalEncodingApi::class)

package eu.friedcutlet.yokan.services.download

import kotlinx.coroutines.test.runTest
import org.jetbrains.skia.Image
import kotlin.io.encoding.Base64
import kotlin.test.*

class TallImageSplitterBrowserTest {
    @Test fun browserSkiaCodecSplitsRealPngAndEncodesReadableJpegTiles() = runTest {
        // 16 x 2501 RGB PNG: 1024 red rows, 1024 green rows, 453 blue rows.
        val bytes = Base64.decode("iVBORw0KGgoAAAANSUhEUgAAABAAAAnFCAIAAABH+qB5AAABjElEQVR4nO3OwQkAQAgDwfTf9NnBgS8FB/LMwOYlrfXeAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPAHG5sAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAQ2BjEwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADACCuvUvMZAkz4pAAAAAElFTkSuQmCC")
        val heights = mutableListOf<Int>()
        assertTrue(splitTallImage(bytes, 1024) { index, encoded ->
            assertEquals(heights.size, index)
            assertEquals(0xff.toByte(), encoded[0])
            assertEquals(0xd8.toByte(), encoded[1])
            val image = Image.makeFromEncoded(encoded)
            try {
                assertEquals(16, image.width)
                heights += image.height
            } finally { image.close() }
        })
        assertEquals(listOf(1024, 1024, 453), heights)
    }
}
```
[complete-source-end]: #

