# Downloads

Status: built and in use on phones; the TV app has no downloads. The queue decides through the state machine of ADR 0003 since its step 3, and takes its clocks, dispatcher and scope from its constructor since step 4. Since step 5 the `Downloader` port is in `application` and answers in our own types, since step 6 the queue itself is a service of `application`, and since step 8 the rules `DownloaderImpl` held (the sweep, the paths, the finalize's steps) are in `domain` ([#970](https://github.com/midasvo/ephyra/issues/970)). As of 2026-12-02.

## Start here

- The queue is `DownloadQueue` (`application/.../application/downloads/service/`, pure Kotlin since ADR 0003 step 6); what it needs from Android goes through ports that `downloads` implements in `DownloadQueueAndroid.kt` (the pump service, the failure notification, the words, the log). The bytes are `MediaDownloadEngine` (`downloads/.../utils/download/`); the rows are `DownloaderImpl` through the roles of the download store (#967: `DownloadList`, `DownloadedItemRows`, `DownloadSources`, `DownloadMediaStreams`, `DownloadSegmentsAndTrickplay`, `DownloadUserData`, `QueuedDownloads`).
- What happens to one download is decided by the state machine in `domain` (`DownloadStage?.on`, the table in ADR 0003, #970). `DownloadQueue` sends it every event and carries out its effects. What starts next is a rule of `domain` too (`nextDownloads`, `mayStart`). A change to what the queue does is a change to a row of the table: the machine, `DownloadTransitionTest` and the ADR change together.
- Finished or not is `DownloadState` in `domain`: only it names the `.download` suffix (rule R13).
- `downloads` may not use `core`, `data` or an adapter (rule R15): what it needs from them comes through a port in `application` (the roles of the download store, `DownloadSettings`, `CurrentServerId`), and what `core` / `modes/film` need from `downloads` goes through `DownloadQueuePort`, `DownloadDeleter`, and `SmartDownloadChecker` in `application` (so `app/tv` binds `None` without linking `downloads`, #1048).
- Test fast: `./gradlew :application:test --tests '*DownloadQueue*'` for the queue (plain JVM, seconds), `./gradlew :downloads:testDebugUnitTest` for the engine and `DownloaderImpl`. On a device: user `tester` (may download) and `nodownload`, Plain Movie or Short Movie, `iptables` to cut the server.
- A download that failed for want of the server goes on by itself when the server is back (`ServerAvailability`, [#912](https://github.com/midasvo/ephyra/issues/912)); one the server refused stays failed.

## What it does

A download keeps an item (a movie or an episode) on the device so it plays without the server. A home video or a music video is a `Movie` with its own `Movie.kind` ([#1068](https://github.com/midasvo/ephyra/issues/1068), [#1076](https://github.com/midasvo/ephyra/issues/1076)): `MovieEntity.kind` keeps it (schema 22), and the Downloads screen, its storage bar, Favorites and the stored libraries list each kind apart (`movieSection` in `modes/film`). A row stored before schema 22 is a movie until `getMovie` reads it from the server, which corrects its kind (`StoredItems.correctMovieKind`). The user picks a quality in `DownloadQualityDialog`. `DownloadQueue` schedules the downloads and runs a few at a time. `MediaDownloadEngine` writes each file over OkHttp and can resume a cut-off transfer. A file is written as `<path>.download` and renamed when it is done: the name says whether it is finished (`DownloadState`). Smart downloads keep the next episodes of a show ready and remove the ones you have watched. There is no offline mode ([#281](https://github.com/midasvo/ephyra/issues/281)): when the server fails or takes over 3 s, the repository shows the Room copy of a downloaded item (`StoredFallback.kt`), and playback picks a finished download before it asks the server. While the server is away, Home, Media, Favorites and search show what is downloaded ([#775](https://github.com/midasvo/ephyra/issues/775), [#1054](https://github.com/midasvo/ephyra/issues/1054); see [the home and library guide](home-and-library.md)).

## Where the code is

| Path | What |
|---|---|
| [`application/.../application/downloads/service/DownloadQueue.kt`](../../application/src/main/kotlin/dev/jdtech/jellyfin/application/downloads/service/DownloadQueue.kt) | The scheduler: entries, slots, auto-retry, restore after process death. A service of `application` since ADR 0003 step 6, with its published view (`DownloadQueueStages.kt`), the speed (`DownloadSpeed.kt`) and the service's notice (`DownloadPumpNotice.kt`) next to it |
| [`downloads/.../core/presentation/downloader/DownloadQueueAndroid.kt`](../../downloads/src/main/java/dev/jdtech/jellyfin/core/presentation/downloader/DownloadQueueAndroid.kt) | The queue's Android side: `DownloadPumpStarter` (`DownloadPump`), `DownloadFailureNotification` (`DownloadFailureNotice`), `DownloadQueueTextsImpl` (`DownloadQueueTexts`, the words of `DownloadTexts.failureText` as a `DownloadText`), `TimberDownloadQueueLog` (`DownloadQueueLog`). The ports are in `application/.../application/downloads/port/` |
| [`application/.../application/downloads/port/Downloader.kt`](../../application/src/main/kotlin/dev/jdtech/jellyfin/application/downloads/port/Downloader.kt) | The `Downloader` port (ADR 0003 step 5): a start returns a `DownloadStart` (the download id, or a `DownloadFailure` of `domain`), the engine's state is an `EngineStatus`. No text: the queue asks its `DownloadQueueTexts` port, which `downloads` makes with `DownloadTexts.failureText` ([`DownloadFailureText.kt`](../../downloads/src/main/java/dev/jdtech/jellyfin/utils/download/DownloadFailureText.kt)). Tests fake it with `FakeDownloader` in `testing` |
| [`downloads/.../utils/DownloaderImpl.kt`](../../downloads/src/main/java/dev/jdtech/jellyfin/utils/DownloaderImpl.kt) | `Downloader`: stores the item rows, starts the engine, finalizes, deletes, runs the orphan sweep. It reads the disk and the engine and asks the rules in `domain` (ADR 0003 step 8). The engine reports an `EngineStatus` itself since ADR 0003 step 7 |
| [`downloads/.../utils/download/MediaDownloadEngine.kt`](../../downloads/src/main/java/dev/jdtech/jellyfin/utils/download/MediaDownloadEngine.kt) | The OkHttp engine: Range resume, pause on the network rule (`shouldPauseTransfer` in `domain`), HTTP errors |
| [`downloads/.../utils/download/ResumeValidators.kt`](../../downloads/src/main/java/dev/jdtech/jellyfin/utils/download/ResumeValidators.kt) | `If-Range` validator per partial file, so a changed source is not appended to ([#850](https://github.com/midasvo/ephyra/issues/850)) |
| [`downloads/.../core/presentation/downloader/SmartDownloads.kt`](../../downloads/src/main/java/dev/jdtech/jellyfin/core/presentation/downloader/SmartDownloads.kt), [`SmartDownloadPlanner.kt`](../../downloads/src/main/java/dev/jdtech/jellyfin/core/presentation/downloader/SmartDownloadPlanner.kt) | Smart downloads; the planner is pure and tested |
| [`downloads/.../core/presentation/downloader/DownloadPumpService.kt`](../../downloads/src/main/java/dev/jdtech/jellyfin/core/presentation/downloader/DownloadPumpService.kt) | Foreground service that keeps the process alive while the queue has work |
| [`downloads/.../work/`](../../downloads/src/main/java/dev/jdtech/jellyfin/work/) | `OrphanSweepWorker`, `ImagesDownloaderWorker` |
| [`downloads/.../di/`](../../downloads/src/main/java/dev/jdtech/jellyfin/di/) | The module's Hilt bindings. `DownloaderModule.provideDownloadQueue` builds the queue with the wall clock, `System.nanoTime`, `Dispatchers.IO` and a scope that lives as long as the app (ADR 0003 step 4), and with the adapters of `DownloadQueueAndroid.kt` (step 6) |
| [`domain/.../models/DownloadState.kt`](../../domain/src/main/kotlin/dev/jdtech/jellyfin/models/DownloadState.kt) | `DownloadState` and `DownloadFiles`: the only place that knows the `.download` suffix |
| [`domain/.../domain/downloads/`](../../domain/src/main/kotlin/dev/jdtech/jellyfin/domain/downloads/) | The download state machine of ADR 0003 ([#970](https://github.com/midasvo/ephyra/issues/970)): `DownloadStage`, `DownloadEvent`, `DownloadEffect` and `DownloadStage?.on`, tested row by row in `DownloadTransitionTest`; what starts next (`nextDownloads`, `NextDownloadsTest`) and the size of a capped transcode (`estimateCappedDownloadSize`). Since step 8 also `DownloaderImpl`'s rules, in `rule/`: the orphan sweep (`OrphanSweep.kt`), the paths and file names (`DownloadPaths.kt`), which streams are kept as files of their own (`SidecarStreams.kt`), `transferPercent`, `trickplaySheetCount`, the engine's network rule (`shouldPauseTransfer`) and the finalize in steps (`FinalizeSteps.kt`, tested as a table in `FinalizeStepsTest`). `DownloadQueue` decides through it since step 3 of the ADR and carries out its effects, and stores each download's stage since step 7 (`Entry` in `DownloadQueueStages.kt` keeps what the stage does not: the item, a failure's words, the numbers on screen). The screens read the stage's view, `DownloadStageView` (queued, waiting for the network, running, paused, finished, failed) |
| [`application/.../repository/DownloadSources.kt`](../../application/src/main/kotlin/dev/jdtech/jellyfin/repository/DownloadSources.kt) | One of the roles of the download store (#967: `DownloadList`, `DownloadedItemRows`, `DownloadSources`, `DownloadMediaStreams`, `DownloadSegmentsAndTrickplay`, `DownloadUserData`, `QueuedDownloads`); the row types are in `StoredDownloads.kt`; Room implementation in [`data/.../database/RoomDownloadStore.kt`](../../data/src/main/java/dev/jdtech/jellyfin/database/RoomDownloadStore.kt) |
| [`application/.../repository/DownloadSettings.kt`](../../application/src/main/kotlin/dev/jdtech/jellyfin/repository/DownloadSettings.kt), [`CurrentServerId.kt`](../../application/src/main/kotlin/dev/jdtech/jellyfin/repository/CurrentServerId.kt) | The settings the engine reads, as ports; implemented over `AppPreferences` in [`core/.../di/AppPreferencesPorts.kt`](../../core/src/main/java/dev/jdtech/jellyfin/di/AppPreferencesPorts.kt) ([#926](https://github.com/midasvo/ephyra/pull/926)) |
| [`application/.../device/StorageVolumes.kt`](../../application/src/main/kotlin/dev/jdtech/jellyfin/device/StorageVolumes.kt), [`device/.../StorageVolumesImpl.kt`](../../device/src/main/java/dev/jdtech/jellyfin/device/StorageVolumesImpl.kt) | The storage the Downloads screen's space bar measures: the chosen volume (or the first), its free space, the app's internal files. `DownloadsViewModel` takes it instead of a `Context`, and `CurrentServerId` and `DownloadSettings` instead of `AppPreferences` (#969, R23) |
| [`application/.../repository/ServerAvailability.kt`](../../application/src/main/kotlin/dev/jdtech/jellyfin/repository/ServerAvailability.kt) | The port that says the server was found to answer again; `ServerReachability` in `core` implements it, `DownloadQueue` collects it ([#912](https://github.com/midasvo/ephyra/issues/912)) |
| [`application/.../repository/StoredFallback.kt`](../../application/src/main/kotlin/dev/jdtech/jellyfin/repository/StoredFallback.kt) | The Room copy when the server fails or is slow (3 s) |
| [`downloads/.../utils/download/DownloadTexts.kt`](../../downloads/src/main/java/dev/jdtech/jellyfin/utils/download/DownloadTexts.kt) | Texts from `core`'s resources; implemented by [`app/phone/.../utils/CoreDownloadTexts.kt`](../../app/phone/src/main/java/dev/jdtech/jellyfin/utils/CoreDownloadTexts.kt) (with [`core/.../utils/DownloadErrorText.kt`](../../core/src/main/java/dev/jdtech/jellyfin/utils/DownloadErrorText.kt) for `downloadErrorText` and `DownloadText.toUiText`) |
| [`application/.../repository/DownloadQueuePort.kt`](../../application/src/main/kotlin/dev/jdtech/jellyfin/repository/DownloadQueuePort.kt), [`DownloadDeleter.kt`](../../application/src/main/kotlin/dev/jdtech/jellyfin/repository/DownloadDeleter.kt), [`SmartDownloadChecker.kt`](../../application/src/main/kotlin/dev/jdtech/jellyfin/repository/SmartDownloadChecker.kt) | Ports consumed by `core` and `modes/film`; implemented in `downloads`, bound as `.None` on TV in [`app/tv/.../di/TvDownloadsModule.kt`](../../app/tv/src/main/java/dev/jdtech/jellyfin/di/TvDownloadsModule.kt) (#1048) |
| [`core/.../presentation/downloader/DownloaderViewModel.kt`](../../core/src/main/java/dev/jdtech/jellyfin/core/presentation/downloader/DownloaderViewModel.kt) | Collects `DownloadQueuePort.queueEntries` into `DownloaderState` (the stage's view, the progress, a failure's words) for the item screens; `toDownloaderState` is the mapping, tested in `DownloaderStateTest` |
| [`modes/film/.../presentation/downloads/`](../../modes/film/src/main/java/dev/jdtech/jellyfin/film/presentation/downloads/) | `DownloadsViewModel`, `DownloadedShowViewModel` |
| [`app/phone/.../presentation/film/DownloadsScreen.kt`](../../app/phone/src/main/java/dev/jdtech/jellyfin/presentation/film/DownloadsScreen.kt), [`DownloadedShowScreen.kt`](../../app/phone/src/main/java/dev/jdtech/jellyfin/presentation/film/DownloadedShowScreen.kt) | The Downloads screens |
| [`app/phone/.../presentation/film/components/DownloadQualityDialog.kt`](../../app/phone/src/main/java/dev/jdtech/jellyfin/presentation/film/components/DownloadQualityDialog.kt) | The quality asked for each download; also `DownloadRow`, `DownloaderCard`, `DownloadProgressButton`, `ItemButtonsBar` there |
| [`core/.../core/reachability/`](../../core/src/main/java/dev/jdtech/jellyfin/core/reachability/) | `ServerReachability`: whether the server answers. Not reachable from `downloads` (R15) |

How the screens use it: they go through the queue (`DownloadQueuePort`) and `DownloadDeleter`; only `downloads` names the `Downloader` port. `DownloaderViewModel` turns the queue's entries into `DownloaderState`. The storage location is `AppPreferences.downloadStorageIndex`, so a download never asks for one; it does ask for a quality (`DownloadQualityDialog`). `ItemButtonsBar` takes `canDownload` and `isDownloaded` overrides, so a season or a show passes a value computed over its episodes instead of `item.isDownloaded()` (which reads `DownloadState`). The Downloads screens never ask the server: they read `DownloadList`, `DownloadSources` and `ItemLists.getDownloads` (`MediaRepositoryImpl` reads the movies and shows through the store role `StoredItems`, #966). Screens that need the server show the unreachable banner. Without the server, `MediaRepositoryImpl.getPlaybackSources` picks a finished download before it asks the server, and user data written meanwhile is marked `toBeSynced` (`PendingUserDataStore`) and sent later by `UserDataSync` and `SyncWorker`.

Strings: the English CE strings of the module are in `downloads/src/main/res/values/strings.xml`, their translations in `values-<lang>/strings_ce.xml`.

## Rules

- **R13**: only `DownloadState.kt` names the `.download` suffix, also inside SQL. Ask `ItemSource.downloadState` or `DownloadFiles`.
- **R15**: `downloads` does not depend on `data`, `server/jellyfin`, `core` or an app outside its tests; no file outside `downloads` names `DownloaderImpl`, `MediaDownloadEngine`, `ResumeValidatorStore`, `SharedPreferencesResumeValidatorStore`, `DownloadHttpClient` or `ImagesDownloaderWorker`. Others use `Downloader`, `DownloadQueue`, `SmartDownloads`.
- **R24**: `DownloadQueue`, its Android side `DownloadQueueAndroid.kt` (at most 150 lines, ADR 0003) and `DownloaderImpl` may not grow past their line ceilings in `architecture/size-ceilings.txt` (ADR 0003, #970). The steps of the ADR lower them.
- **R9, R4**: only the apps depend on `data`; only `data` imports `ServerDatabaseDao`. Room access goes through the roles of the download store.
- **R10**: ids are value classes (`ItemId`, `MediaSourceId`, `MediaStreamId`, … in `domain/.../models/Ids.kt`); no `java.util.UUID` and no `String` id outside the adapter. Don't add a line to `architecture/baseline/` to get past it.
- **R1, R2**: no SDK and no `JellyfinApi` here; the engine gets its URLs through the repository's roles (`PlaybackMedia`, `ItemCatalog`, `CurrentAccount`, #967).
- Project rules (`CLAUDE.md`): the `libre` flavour stays free of Google code; every CE string in 36 languages (`translate-strings` skill); a Room migration gets an independent review when no bot reviewed the PR.

## How to test it

Unit tests, pure modules first:

```bash
./gradlew :domain:test :application:test :architecture:test   # DownloadStateTest, DownloadTransitionTest, NextDownloadsTest, FinalizeStepsTest, OrphanSweepHelpersTest, DownloadPathTest, NetworkPauseTest, R13, R15, R24
./gradlew :application:test                                    # DownloadQueue*Test (the queue, plain JVM), StoredFallbackTest, MediaRepositoryImplTest (the repository over fakes)
./gradlew :downloads:testDebugUnitTest                         # MediaDownloadEngine*Test, ResumeValidatorsTest, SmartDownloadPlannerTest, OrphanSweepTest, DownloadFinalizeFailureTest, SubtitleFinalizeTest, DownloadTrickplayRestartTest, DownloadQueueAndroidTest
./gradlew :data:testDebugUnitTest                              # StoredItemFallbackTest, UnfinishedDownloadPlaybackTest (the repository over Room)
./gradlew :modes:film:testDebugUnitTest                        # DownloadsViewModelUserSwitchTest, QueueCountsTest, EpisodeDownloadSelectionTest, ActiveDownloadMappingTest, EpisodeDownloadProgressTest
./gradlew :core:testLibreDebugUnitTest                         # DownloadErrorTextTest, DownloaderStateTest (core has a libre flavour)
./gradlew :app:phone:testLibreDebugUnitTest                    # DownloadQualityDialogTest, DownloadStatusTextTest (the words of each stage), ServerUnreachableTest
```

One class: add `--tests '*MediaDownloadEngineResumeTest*'`.

`DownloadQueueCharacterisationTest` and `PendingDownloadRestoreTest` pin the rows of the download table in ADR 0003 that no other test covered, each named by its row number ([#970](https://github.com/midasvo/ephyra/issues/970)). A change that fails one of them changes what the queue does today, so it goes in a `fix` PR with its own issue, and the ADR's table changes with it. The `downloads` tests build the real stores over Room (`testImplementation(projects.data)`) and fake the settings with `TestDownloadSettings` (in `testing` since step 6). The queue tests are in `application` since ADR 0003 step 6 and run on the JVM, without Robolectric: they fake the source rows with `queueSources`, the words with `TestQueueTexts` and the failure notices with `RecordedNotices` (`QueueVirtualTime.kt`); `DownloadQueueAndroidTest` in `downloads` checks what the notice and the words become on Android. They fake the downloader with `FakeDownloader` from `testing`: set what a start returns (`startResult`, `onStart`) and what the engine reports (`progress`, `progressOf`), and read the calls it recorded.

The `DownloadQueue*Test` classes run the queue in the virtual time of `runTest` (`QueueVirtualTime.kt`, ADR 0003 step 4). `queueInVirtualTime` gives the queue the test's scheduler, `backgroundScope` and clocks that read the virtual time, and `runQueueUntil` moves that time on until the queue gets where the test expects. A backoff of minutes takes no real time, so no test sleeps. Only `DownloadQueueMachineReviewTest` still writes the queue's list by reflection, for two entries of one item that no short run of events reaches. The queue's coroutines run on the test's scope, so an exception that escapes one fails the test instead of vanishing on the queue's own scope. That includes a fake that throws `NotImplementedError`.

On a device: the test server (`docs/dev-environment.md`, `tools/test-server/setup.sh`, `test-server` skill) at `http://10.0.2.2:8096` from an emulator.

- Users: `tester` may download; `nodownload` may not (no download button: the server's `canDownload`). Use your own user when someone else tests at the same time (`python3 tools/test-server/user.py add <name>`).
- Items: Plain Movie and Short Movie (the normal case, a quick one); Versions Movie (two versions); Tracks Movie (external `.de.srt`, finalized with the video, [#573](https://github.com/midasvo/ephyra/issues/573)); Image Subs Movie and Tracks Show at a 1.5 Mbps quality (a transcoded download); Test Show, Long Season Show and Resume Show (season downloads, smart downloads); Empty Season Show (nothing to download).
- Without the server, internet still up (phone or tablet AVD): `adb root`, then `adb shell iptables -I OUTPUT -d 10.0.2.2 -p tcp --dport 8096 -j REJECT --reject-with tcp-reset`; `-D` instead of `-I` brings it back. Use the port the app is logged in on: 8097 when it goes through `forward.py` (below). That shows the unreachable banner, the stored fallback and the queue's failure path.
- A slow transfer, to pause or cut one mid-way: `python3 tools/test-server/forward.py 8097 8096 600` (600 kbit/s) and log in to `http://10.0.2.2:8097`; stop the script to cut the connection.
- No network at all: `adb shell cmd connectivity airplane-mode enable`; a queued download waits for the network ([#530](https://github.com/midasvo/ephyra/issues/530)).
- Restart during a season download with one download slot and episodes still queued. On the next start, the partial episode resumes first and the queued episodes follow in their original order. The debug build is `nl.midasvo.findroid.ce.debug`.
- Scripted taps: dump the screen (`uiautomator dump`) and check it before each tap.

## Before a PR

```bash
./gradlew ktfmtCheck
./gradlew :domain:test :application:test :architecture:test
./gradlew :downloads:testDebugUnitTest :data:testDebugUnitTest :modes:film:testDebugUnitTest
./gradlew :app:phone:compileLibreDebugKotlin
python3 .claude/skills/translate-strings/scripts/check-translations.py   # when strings changed
```

Or all of it: `./gradlew testDebugUnitTest`.

Then on an emulator: start a download, cut the server off with `iptables` (see above), bring it back, and check what the queue shows.

## Decisions and history

- [#38](https://github.com/midasvo/ephyra/pull/38): Android's DownloadManager replaced by the OkHttp engine with resume ([#26](https://github.com/midasvo/ephyra/issues/26)).
- [#116](https://github.com/midasvo/ephyra/issues/116): smart downloads.
- [#281](https://github.com/midasvo/ephyra/issues/281): no Offline Mode; stored copies while the server is away, reachability banner.
- [#560](https://github.com/midasvo/ephyra/issues/560): the pump service runs as long as the queue has work.
- [#1054](https://github.com/midasvo/ephyra/issues/1054): Home shows the downloads while the server is away (rows from `StoredItemLists`; a new DAO query, no schema change).
- [#718](https://github.com/midasvo/ephyra/issues/718) (open) and [#724](https://github.com/midasvo/ephyra/pull/724): stored copies looked up by the current server.
- [#848](https://github.com/midasvo/ephyra/issues/848): a failed finalize is not shown as completed.
- [#850](https://github.com/midasvo/ephyra/issues/850): `If-Range` on resume.
- [#897](https://github.com/midasvo/ephyra/issues/897): `DownloadState` instead of the suffix in every file (R13).
- [#899](https://github.com/midasvo/ephyra/issues/899) / [#911](https://github.com/midasvo/ephyra/pull/911): the rows behind the download store (split by role in #967).
- [#912](https://github.com/midasvo/ephyra/issues/912): a failed entry flagged `retryWhenServerReturns` goes back to Pending on `ServerAvailability.serverConfirmed` (a probe that reached the server, or a request answered while it counted as unreachable).
- [#1124](https://github.com/midasvo/ephyra/issues/1124): automatic recovery keeps the queue timestamp in memory and in the pending row. Manual Retry assigns a fresh timestamp. An entry in retry backoff becomes eligible at its scheduled time. Schema 23 records the pending row's last write in `savedAt` for the 30-day cleanup of unresolvable rows. Rows saved before the upgrade fall back to their original timestamp.
- [#901](https://github.com/midasvo/ephyra/issues/901) / [#914](https://github.com/midasvo/ephyra/pull/914): `downloads` as its own module (R15).
- [#918](https://github.com/midasvo/ephyra/issues/918) / [#926](https://github.com/midasvo/ephyra/pull/926): the engine reads its settings through `DownloadSettings` (part 2; part 1 is [#927](https://github.com/midasvo/ephyra/pull/927), and rule R17 now guards both).
- [#1002](https://github.com/midasvo/ephyra/issues/1002): `DownloadQueue.startDownload` keeps the pending row until `downloadItem` writes a source row, so a start that fails online while the server is away survives process death (`restoreAll` skips any pending row whose item already has an active source).
- ADRs: [`docs/architecture/adr/0002-hexagonal-ddd.md`](../architecture/adr/0002-hexagonal-ddd.md); T5, T7 and T9 in [`docs/architecture/5-hexagonal-ddd.md`](../architecture/5-hexagonal-ddd.md). Proposed: [`docs/architecture/adr/0003-playback-and-download-use-cases.md`](../architecture/adr/0003-playback-and-download-use-cases.md) ([#970](https://github.com/midasvo/ephyra/issues/970)), the life of one download as a state machine in `domain` and the queue as a service in `application`, without a Room schema change of its own (#1124 added schema 23 outside the series).

## Pitfalls

- **Smart Downloads keeps files held by the local playlist (#1143).** `PlaybackEvents.queuedDownloadIds` accumulates resolved downloads before and after the current item; moving to Previous must not let Smart Downloads delete Next. Holds last until player release, including across jumps and failed queue replacements, because engine queue installation is asynchronous. Smart Downloads can remove those files on its next check after release. Protection changes deletion only; played neighbours still count towards the series' progress when planning new downloads. The delete loop checks again after resolving the stored source. A new lookup can still race with a deletion already underway inside `DownloaderImpl`.
- **A failed download resumes by itself only when the server gave no answer.** `DownloadQueue` flags a failure at the start (also after an app restart with the server away) and an engine failure with no HTTP status once its three auto-retries are used (30 s, 2 min, 10 min, `afterFailure`); `ServerAvailability.serverConfirmed` puts them back to Pending ([#912](https://github.com/midasvo/ephyra/issues/912)). A refusal (an HTTP status, a failed finalize) stays failed until Retry. It only fires while the app is in front: the reachability monitor does not probe in the background. A start that failed for a local reason (storage) is flagged too and fails again at once.
- **One item id is stored for one server.** The item tables have the item id as primary key: a download of the same id from a second server replaces the first one's copy, and the queue dedups by item id ([#718](https://github.com/midasvo/ephyra/issues/718)). A restore can still bring back two live entries of one item (two partial rows): the poll matches each one to its own download ID, and a start takes the entry the pump chose, so neither takes the other's updates or retry time ([#1106](https://github.com/midasvo/ephyra/issues/1106)). Each entry keeps the download ID of its row while it waits (`Entry.resumeDownloadId`) and names it in `downloadItem`, so it resumes its own partial; a start that names none resumes the item's first partial ([#1109](https://github.com/midasvo/ephyra/issues/1109)). The poll's subtitle retry names the entry's download ID too, so it restarts that partial's failed subtitles ([#1118](https://github.com/midasvo/ephyra/issues/1118)). The download path of a movie or an episode has no source ID, so two rows the app wrote for one item can share one file: those are one download, and both entries resume the first.
- **Re-downloading does not refresh metadata**: the item inserts in `ServerDatabaseDao` use `OnConflictStrategy.IGNORE` (data-02 in [`docs/open-decisions.md`](../open-decisions.md)).
- **The engine is in-process.** It does not survive process death; `restoreAll` puts the partial downloads back as pending and resumes them by Range, and restores queued downloads whose start had not written a source row yet. Without `DownloadPumpService` the transfers stop when the app is closed.
- **Trickplay across restarts and from lists**: `downloadTrickplayData` writes each sheet to disk before inserting the `trickplayInfos` row, and `DownloaderImpl` ensures missing trickplay on resume and finalization (resolving from `ItemCatalog` when the caller or Room copy lacked it, [#1015](https://github.com/midasvo/ephyra/issues/1015)).
- **External subtitles** have their own `.download` name and finalize step ([#573](https://github.com/midasvo/ephyra/issues/573)); check them when you change finalizing. The order of both finalizes is `FinalizeSteps.kt` in `domain`, one row of `FinalizeStepsTest` per case: a change there is a change of what is kept on disk.
- **Every download needs a path of its own.** `buildDownloadPath` (in `domain`, `DownloadPaths.kt`) names a movie's folder `Name (year) [<item id>]` ([#1068](https://github.com/midasvo/ephyra/issues/1068)): without the id, two items with the same name and year (home videos have no year and often the same name) shared one file, a new download deleted the other's partial file and its finish replaced the other's finished one. An episode is `Series [<series id>]/S01/S01E05 - Name [<episode id>]` for the same reason ([#1079](https://github.com/midasvo/ephyra/issues/1079)): two shows with one name (in different libraries, or on two servers) had one path, and so did episodes without a number (all `S00E00`) with the same name. Movie, series and episode titles are cut to 180 UTF-8 bytes, so with the id a name stays under the 255 bytes of ext4. Old downloads keep the path in their rows.
- **The orphan sweep deletes files**: a finished file with no row goes after 24 h (`ORPHAN_MIN_AGE_MS`). A path change that the rows do not follow loses downloads.
- **`DownloadsViewModel`'s reads, sorting and storage walk run on `ioDispatcher`** (`Dispatchers.IO` in the app). A test passes its own test dispatcher, as `DownloadsViewModelUserSwitchTest` does: on the real IO threads a load the test had already left (cancelled by a newer one) went on after the test, and its return to `Dispatchers.Main` after `resetMain()` failed whichever `runTest` came next in the module, often `FavoritesViewModelUserSwitchTest` or `MediaViewModelUserSwitchTest` ([#921](https://github.com/midasvo/ephyra/issues/921)). A new test of a ViewModel in `modes/film` does the same: no real dispatcher, everything on the test scheduler.
- **Partial downloads resume first after a restart.** `restoreAll` assigns them an earlier queue timestamp, and restored pending rows keep their original timestamps ([#1098](https://github.com/midasvo/ephyra/issues/1098)). `DownloadQueueCharacterisationTest` checks the first start with one slot and the order of the pending entries.
- **Downgrade**: builds with the #1127 startup check preserve the database, including download rows. Use a compatible build when the launcher reports that it cannot open the saved data. APKs released before #1127 can still erase the database on downgrade, including download metadata and logins.
