# Home and library

Status: built across phone/tablet and Android TV (shared ViewModels in `modes/film`, separate layouts in `app/phone` and `app/tv`), including customisable Home rows, cold-start Home cache, indexed A–Z library paging, Room download fallbacks on phone (Home included since #1054), detail extras/related rows, and optional MDBList external ratings. As of 2026-11-29 (`main` at `ac5326010` plus the pull request of #1054).

## Start here

- Shared ViewModels and domain logic live in `modes/film/`: `HomeViewModel` (`home/`), `LibraryViewModel` (`library/`), `MediaViewModel` (`media/`), `FavoritesViewModel` (`favorites/`), `CollectionViewModel` (`collection/`), `MovieViewModel` (`movie/`), `ShowViewModel` (`show/`), `SeasonViewModel` (`season/`), `EpisodeViewModel` (`episode/`), `PersonViewModel` (`person/`), and `HomeRowsViewModel` (`homerows/`).
- Phone/tablet screens and shared film components live in `app/phone/.../presentation/film/` (`HomeScreen`, `LibraryScreen`, `MediaScreen`, `FavoritesScreen`, `CollectionScreen`, `MovieScreen`, `ShowScreen`, `SeasonScreen`, `EpisodeScreen`, `PersonScreen`, `ItemButtonsBar`, `LetterFastScroller`, `ExternalRatingsRow`, plus wide layouts in `MovieWideLayout`, `ShowWideLayout`, `SeasonWideLayout`).
- TV CE screens live in `app/tv/.../ce/presentation/film/` (`HomeScreen`, `LibraryScreen`, `FavoritesScreen`, `CollectionScreen`, `MovieScreen`, `ShowScreen`, `SeasonScreen`, `PersonScreen`, `DetailMetadata`).
- Data path: ViewModels read repository role interfaces in `application/.../repository/` (`ItemCatalog`, `ItemLists`, `ItemExtras`, bound to `MediaRepositoryImpl`) over domain ports in `domain/.../domain/ports/` (`ItemPort`, `ItemListPort`, `ItemExtrasPort`), implemented by `JellyfinCatalog` in `server/jellyfin/`.
- Optional external ratings on movie and show screens go through `ExternalRatingsLoader` (`modes/film/`) and `ExternalRatings` / `ExternalRatingsService` (`application/.../ratings/`), backed by `ratings/mdblist/` (`MdbListClient`, `FileRatingsCache`).
- Test fast: `./gradlew :modes:film:testDebugUnitTest`.

## What it does

### Home

`HomeViewModel` loads the active server name and current user, then fetches Suggestions (`getSuggestions`), Continue Watching (`getResumeItems`), Next Up (`getNextUpItems`), the libraries (`getHomeLibraries`) and each visible library's Latest row (`getLatestMedia`) concurrently inside `coroutineScope` (`HomeViewModel.runLoad`). Each library's Latest row updates `HomeState.views` as soon as it completes (`loadLatest`) so a slow library does not hold back the rest ([#251](https://github.com/midasvo/ephyra/issues/251)).

Row visibility and order are per user and server via `HomeRows` and `HomeRowsStore` (`HomeRowsProfile`, stored under `pref_ce_home_rows_<serverId>_<userId>`, falling back to `LegacyHomeSwitches` until changed) and edited in `HomeRowsViewModel` ([#142](https://github.com/midasvo/ephyra/issues/142), [#431](https://github.com/midasvo/ephyra/issues/431)). `HomeState.orderedRows()` returns the loaded sections in `rowOrder`. When `appPreferences.homeCache` is enabled, `HomeCache` stores the latest rows per server and user in `filesDir/home-cache/<serverId>_<userId>.json` (`VERSION = 2`) so a cold start renders them immediately before the network refresh arrives ([#251](https://github.com/midasvo/ephyra/issues/251), [#608](https://github.com/midasvo/ephyra/issues/608)).

`HomeViewModel.followCurrentUser()` observes `observeCurrentServerId()` and `observeCurrentUser()`. On a user switch, `onCurrentUser` increments `generation` under `switchLock`, invalidates `ReloadPolicy`, cancels the previous `loadJob`, resets state, and waits up to `CLIENT_SWITCH_WAIT_MS` (`3_000L` ms) for `CurrentAccount.getUserId()` to match (`clientActsFor`). In the UI, `HomeState.shownTo(userId)` and `SessionUser.recheck()` prevent rendering a single frame of the previous user's rows ([#810](https://github.com/midasvo/ephyra/issues/810), [#872](https://github.com/midasvo/ephyra/issues/872)). Phone `HomeScreen` reloads via `ReloadOnResume` + `ReloadPolicy` (`DEFAULT_MAX_AGE_MS = 60_000L` ms plus `DataChangeEvents`) and `ReloadWhenServerAwayChanges` (`HomeViewModel.onServerAwayChanged`), showing `ServerOrErrorCard` beneath `HomeHeader` when rows are already on screen ([#392](https://github.com/midasvo/ephyra/issues/392), [#571](https://github.com/midasvo/ephyra/issues/571), [#775](https://github.com/midasvo/ephyra/issues/775)) or `ErrorState` / `EmptyState` when empty. When every attempted row fails (`error != null`), `HomeViewModel.runLoad` clears stale and cached online rows (and skips `HomeCache` while the server is already known away) so `ErrorState` replaces online content instead of keeping it on screen. TV `HomeScreen` adds a backdrop hero tracking focused cards (`HeroFocus`) and opens episodes into their season ([#130](https://github.com/midasvo/ephyra/issues/130)).

#### Home while the server is away

Until v2.7.0 an Offline Mode filled Home from the downloads; v2.8.0 removed the mode ([#281](https://github.com/midasvo/ephyra/issues/281)) and Home showed an error page instead. Since [#1054](https://github.com/midasvo/ephyra/issues/1054) Home shows the downloads of the current server while the server is away, and keeps the error page ([#1055](https://github.com/midasvo/ephyra/issues/1055)) when nothing of it is downloaded (always so on TV, which has no downloads).

- The fallback is in `MediaRepositoryImpl`, as for the favourites ([#775](https://github.com/midasvo/ephyra/issues/775)): `getSuggestions`, `getResumeItems`, `getNextUpItems` and `getHomeLibraries` go through `serverOrStoredItems` and return an `ItemsResult` with `fromStore`. The store answers at once while the server is known to be away (`KnownServerState`), else only when the request gets no answer; a slow server is waited for and an error it answered with (an HTTP status) comes through. `storedHomeRow` makes a row answerable only when `StoredItemLists.hasDownloads` says something of the server is downloaded; then an empty row is an answer too. `getLatestMedia` of a stored library (`StoredLibraries`) is always Room's.
- The stored rows are `StoredItemLists.homeSuggestions` (ten downloaded movies and shows, picked at random), `resumeItems` (downloads with a resume position, the last played first), `nextUp` (per show the downloaded episode after the last played one, or the first when none is played; specials left out), and `libraryContents` by download date for the Latest rows. `RoomStoredLists` reads the rows and the user's play states; which of them Continue Watching and Next Up hold is `WatchRows` and `PlayState.hasResumePosition` in `domain` (rule R14), not a query or the ViewModel. Only finished downloads (`DownloadState`), of the current server, with the current user's data ([#718](https://github.com/midasvo/ephyra/issues/718)).
- Home shows either the server's rows or the downloads. A row the server answered shows at once (`HomeViewModel.answered`); a row the store answered is held (`RowAnswer.FromStore`) until every row is in, and the stored rows go on screen together only when no row of that load came from the server, replacing whatever was there (the server's rows, or the remembered rows of a cold start). In a load the server answered part of, a row the store answered counts as failed and keeps what it showed. The first server row of a later load takes the downloads off screen (`HomeState.forServerRows`). `HomeState.downloadsOnly` says which it is; phone `HomeScreen` then shows `DownloadsOnlyLine` over the rows, under the unreachable banner.
- A load the store answered is not written to `HomeCache`, and `HomeCache` is not read while the server is known away.
- While the server is known away (`serverAway == true`, which only the phone reports) `runLoad` starts neither `refreshUserImage` nor `refreshServerName`: the stored rows go on screen once every row is in, and against a server that drops packets the two requests would hold them back until the connect timeout. The load after the server's return asks both.
- `HomeViewModel.onServerAwayChanged` reloads when the server goes away (the downloads replace the server's rows) and when it comes back. Rows the store answered before the server was known to be away get one more quiet try after `ServerAwayReload.STORE_RETRY_DELAY_MS`, as on Media ([#779](https://github.com/midasvo/ephyra/issues/779)). An error page left by an error the server answered with (a proxy in front of a server that is down) reloads quietly once the server is known away.
- Rows the user turned off stay off. The stored libraries are not in the user's order (it names the server's libraries): their Latest rows are shown unless every Latest row is hidden (`HomeRows.showsStoredLatest`) and go where the first Latest row is (`orderedRows`). `HomeRowsViewModel` keeps asking `getUserViews`, never `getHomeLibraries`: it stores what it lists.

### Libraries, My media, Collections, and Favourites

`MediaViewModel` loads libraries (`ItemLists.getLibraries()`) with `ReloadPolicy`, user-switch clearing (`shownTo`), and `ServerAwayReload` so phone `MediaScreen` switches to Room's synthetic Movies and Shows libraries while the server is unreachable ([#775](https://github.com/midasvo/ephyra/issues/775), [#781](https://github.com/midasvo/ephyra/issues/781)), and Music Videos and Home Videos when such downloads exist (`StoredLibraries.OF_MOVIE_KIND`, [#1076](https://github.com/midasvo/ephyra/issues/1076)). Favourites and search, online and stored, include music videos and home videos.

`LibraryViewModel` maps `CollectionType` (`Movies`, `TvShows`, `BoxSets`, `MusicVideos`, `HomeVideos`, `Mixed`, `Folders`) to `ItemKind` filters and `recursive` flags (`HomeVideos`, `Mixed`, and `Folders` include `ItemKind.FOLDER` and query non-recursively; [#671](https://github.com/midasvo/ephyra/issues/671)). Both phone and TV `LibraryScreen` pass `indexed = true` to `LibraryViewModel.setup`, which builds `indexedItemsPager` (`IndexedItemsPagingSource`, `LIBRARY_PAGE_SIZE = 40`, `enablePlaceholders = true`, `jumpThreshold = 120`) over `ItemLists.getItemsPage(..., includeTotal = true)` on the first page; unindexed callers use `itemsPager` (`ItemsPagingSource`). When sorted by `SortBy.NAME` on an indexed grid, `loadLetterIndex` queries 26 `ItemLists.getItemCount(..., nameLessThan = boundary)` counts in parallel (`LetterIndex.BOUNDARIES`, `'a'..'z'`) after the first page reports `total`, feeding phone `LetterFastScroller` and TV's A–Z jump bar ([#135](https://github.com/midasvo/ephyra/issues/135), [#672](https://github.com/midasvo/ephyra/issues/672)). `LibraryViewModel.loadItemsIfNeeded()` caches a `LoadKey(parentId, libraryType, indexed)` so Back navigation keeps the loaded grid while process death reloads it ([#371](https://github.com/midasvo/ephyra/issues/371)).

`CollectionViewModel` loads a box set (`ItemLists.getItems` sorted by `SortBy.RELEASE_DATE`) and splits items into `Movie`, `Show`, and `Episode` `CollectionSection` groups. `FavoritesViewModel` fetches `ItemLists.getFavoriteItems()`, groups by kind, guards user switches (`shownTo`), and integrates with `ServerAwayReload` and `ReloadAfterSync` on phone ([#775](https://github.com/midasvo/ephyra/issues/775), [#782](https://github.com/midasvo/ephyra/issues/782), [#866](https://github.com/midasvo/ephyra/issues/866)).

### Item detail screens and external ratings

`MovieViewModel`, `ShowViewModel`, `SeasonViewModel`, `EpisodeViewModel`, and `PersonViewModel` load their primary item and cast/crew concurrently inside `coroutineScope` ([#252](https://github.com/midasvo/ephyra/issues/252), [#262](https://github.com/midasvo/ephyra/issues/262), [#274](https://github.com/midasvo/ephyra/issues/274)). `MovieViewModel`, `ShowViewModel`, `SeasonViewModel`, and `EpisodeViewModel` manage freshness with `ReloadPolicy` and update played and favourite flags in place (`reloadPolicy.changedHere()`). In `ItemCatalog` (`MediaRepositoryImpl`), `getItem`, `getMovie`, `getShow`, `getSeason`, and `getEpisode` fall back to Room (`StoredItems`) for the current server when unreachable ([#281](https://github.com/midasvo/ephyra/issues/281), [#718](https://github.com/midasvo/ephyra/issues/718)); `ShowViewModel` and `SeasonViewModel` also use `offline = true` and `serverOrStoredList` for stored seasons and episodes.

`DetailSections` (read through `DetailPageSettings.sections`, #969) strips disabled metadata (`Movie.shownIn`, `Show.shownIn`, `Episode.shownIn`, `RelatedItemsRequest.shownIn`) before state emission ([#332](https://github.com/midasvo/ephyra/issues/332)). After the first frame (`AfterFirstFrame`), `MovieViewModel.loadRelated` and `ShowViewModel.loadRelated` launch `launchRelatedItems` (`ItemExtras`: local trailers/special features, item collections on movies, and similar items, gated by `ServerCapabilities`) and `ExternalRatingsLoader.load` ([#331](https://github.com/midasvo/ephyra/issues/331), [#769](https://github.com/midasvo/ephyra/issues/769)).

`ExternalRatingsLoader` keeps row height stable during loading via `ExternalRatingsState.Pending` when `ExternalRatings.mightHaveRatings` is true, and suppresses MDBList's Rotten Tomatoes chip when `criticRating` from Jellyfin is already shown (`rottenTomatoes = sections.criticRating && item.criticRating == null`). `ExternalRatingsService` coordinates `RatingsProvider` (`MdbListClient` calling `api.mdblist.com` for IMDb, Rotten Tomatoes, Metacritic, and Letterboxd using TMDB/IMDb/TVDB IDs) and `RatingsCache` (`FileRatingsCache` under `cacheDir/external_ratings`), deduplicating concurrent lookups per title and keeping 429/failure/invalid-key back-offs in memory ([#331](https://github.com/midasvo/ephyra/issues/331)).

On phone, `ItemButtonsBar` renders Play / Resume / Play from beginning / Shuffle (`onShuffleClick`), trailer menu, played toggle, favourite toggle, download/delete buttons (hiding server-only actions when `LocalServerStatus.current.confirmedUnreachable`), `VersionDialog` for multi-source items, and `DownloaderCard`. On TV, `ShowScreen` also triggers `ShowViewModel.loadThemeSong` when `tvThemeMusic` and `ServerCapabilities.themeSongs` are enabled ([#141](https://github.com/midasvo/ephyra/issues/141), [#769](https://github.com/midasvo/ephyra/issues/769)).

## Where the code is

| Path | What |
|---|---|
| [`modes/film/.../home/HomeViewModel.kt`](../../modes/film/src/main/java/dev/jdtech/jellyfin/film/presentation/home/HomeViewModel.kt), [`HomeState.kt`](../../modes/film/src/main/java/dev/jdtech/jellyfin/film/presentation/home/HomeState.kt), [`HomeCache.kt`](../../modes/film/src/main/java/dev/jdtech/jellyfin/film/presentation/home/HomeCache.kt), [`HomeRowsOrder.kt`](../../modes/film/src/main/java/dev/jdtech/jellyfin/film/presentation/home/HomeRowsOrder.kt) | Home state, parallel row loading, the downloads while the server is away (`RowAnswer`, `downloadsOnly`), user-switch guard, cold-start JSON cache, row ordering |
| [`modes/film/.../domain/homerows/HomeRows.kt`](../../modes/film/src/main/java/dev/jdtech/jellyfin/film/domain/homerows/HomeRows.kt), [`HomeRowsStore.kt`](../../modes/film/src/main/java/dev/jdtech/jellyfin/film/domain/homerows/HomeRowsStore.kt), [`homerows/HomeRowsViewModel.kt`](../../modes/film/src/main/java/dev/jdtech/jellyfin/film/presentation/homerows/HomeRowsViewModel.kt) | Per-user/server Home row layout resolution, storage, and settings editor (#142) |
| [`modes/film/.../library/LibraryViewModel.kt`](../../modes/film/src/main/java/dev/jdtech/jellyfin/film/presentation/library/LibraryViewModel.kt), [`IndexedItemsPagingSource.kt`](../../modes/film/src/main/java/dev/jdtech/jellyfin/film/presentation/library/IndexedItemsPagingSource.kt), [`ItemsPagingSource.kt`](../../modes/film/src/main/java/dev/jdtech/jellyfin/film/presentation/library/ItemsPagingSource.kt), [`LetterIndex.kt`](../../modes/film/src/main/java/dev/jdtech/jellyfin/film/presentation/library/LetterIndex.kt) | Library ViewModel, Paging 3 sources (with/without placeholders), A–Z `LetterIndex` |
| [`modes/film/.../media/MediaViewModel.kt`](../../modes/film/src/main/java/dev/jdtech/jellyfin/film/presentation/media/MediaViewModel.kt), [`favorites/FavoritesViewModel.kt`](../../modes/film/src/main/java/dev/jdtech/jellyfin/film/presentation/favorites/FavoritesViewModel.kt), [`collection/CollectionViewModel.kt`](../../modes/film/src/main/java/dev/jdtech/jellyfin/film/presentation/collection/CollectionViewModel.kt) | Libraries tab, Favourites, and BoxSet collections |
| [`modes/film/.../movie/MovieViewModel.kt`](../../modes/film/src/main/java/dev/jdtech/jellyfin/film/presentation/movie/MovieViewModel.kt), [`show/ShowViewModel.kt`](../../modes/film/src/main/java/dev/jdtech/jellyfin/film/presentation/show/ShowViewModel.kt), [`season/SeasonViewModel.kt`](../../modes/film/src/main/java/dev/jdtech/jellyfin/film/presentation/season/SeasonViewModel.kt), [`episode/EpisodeViewModel.kt`](../../modes/film/src/main/java/dev/jdtech/jellyfin/film/presentation/episode/EpisodeViewModel.kt), [`person/PersonViewModel.kt`](../../modes/film/src/main/java/dev/jdtech/jellyfin/film/presentation/person/PersonViewModel.kt) | Item detail ViewModels (concurrent loading, downloads/episodes, in-place user data) |
| [`modes/film/.../DetailSections.kt`](../../modes/film/src/main/java/dev/jdtech/jellyfin/film/presentation/DetailSections.kt), [`RelatedItems.kt`](../../modes/film/src/main/java/dev/jdtech/jellyfin/film/presentation/RelatedItems.kt), [`ExternalRatingsLoader.kt`](../../modes/film/src/main/java/dev/jdtech/jellyfin/film/presentation/ExternalRatingsLoader.kt) | Detail metadata toggles, deferred extras/collections/similar rows, and external ratings state |
| [`app/phone/.../presentation/film/`](../../app/phone/src/main/java/dev/jdtech/jellyfin/presentation/film/) | Phone/tablet screens (`HomeScreen`, `LibraryScreen`, `MediaScreen`, `FavoritesScreen`, `CollectionScreen`, `MovieScreen`, `ShowScreen`, `SeasonScreen`, `EpisodeScreen`, `PersonScreen`, `ItemExtras`) |
| [`app/phone/.../film/components/ItemButtonsBar.kt`](../../app/phone/src/main/java/dev/jdtech/jellyfin/presentation/film/components/ItemButtonsBar.kt), [`LetterFastScroller.kt`](../../app/phone/src/main/java/dev/jdtech/jellyfin/presentation/film/components/LetterFastScroller.kt), [`ExternalRatingsRow.kt`](../../app/phone/src/main/java/dev/jdtech/jellyfin/presentation/film/components/ExternalRatingsRow.kt) | Phone action bar, A–Z fast scroller bubble, and external ratings chips |
| [`app/tv/.../ce/presentation/film/`](../../app/tv/src/main/java/dev/jdtech/jellyfin/ce/presentation/film/) | TV screens (`HomeScreen`, `LibraryScreen`, `FavoritesScreen`, `CollectionScreen`, `MovieScreen`, `ShowScreen`, `SeasonScreen`, `PersonScreen`, `DetailMetadata`) |
| [`domain/.../ports/ItemPort.kt`](../../domain/src/main/kotlin/dev/jdtech/jellyfin/domain/ports/ItemPort.kt), [`ItemListPort.kt`](../../domain/src/main/kotlin/dev/jdtech/jellyfin/domain/ports/ItemListPort.kt), [`ItemExtrasPort.kt`](../../domain/src/main/kotlin/dev/jdtech/jellyfin/domain/ports/ItemExtrasPort.kt) | Server-agnostic catalog, list, and extras ports |
| [`application/.../repository/ItemCatalog.kt`](../../application/src/main/kotlin/dev/jdtech/jellyfin/repository/ItemCatalog.kt), [`ItemLists.kt`](../../application/src/main/kotlin/dev/jdtech/jellyfin/repository/ItemLists.kt), [`ItemExtras.kt`](../../application/src/main/kotlin/dev/jdtech/jellyfin/repository/ItemExtras.kt), [`MediaRepositoryImpl.kt`](../../application/src/main/kotlin/dev/jdtech/jellyfin/repository/MediaRepositoryImpl.kt), [`ReloadPolicy.kt`](../../application/src/main/kotlin/dev/jdtech/jellyfin/repository/ReloadPolicy.kt) | Repository role interfaces, Room/server composition, and staleness policy |
| [`application/.../repository/StoredItemLists.kt`](../../application/src/main/kotlin/dev/jdtech/jellyfin/repository/StoredItemLists.kt), [`data/.../database/RoomStoredLists.kt`](../../data/src/main/java/dev/jdtech/jellyfin/database/RoomStoredLists.kt), [`domain/.../userdata/WatchRows.kt`](../../domain/src/main/kotlin/dev/jdtech/jellyfin/domain/userdata/WatchRows.kt) | The lists Room answers while the server is away (favourites, search, stored libraries, Home's rows) and the rules of Continue Watching and Next Up over the downloads |
| [`server/jellyfin/.../JellyfinCatalog.kt`](../../server/jellyfin/src/main/java/dev/jdtech/jellyfin/server/jellyfin/JellyfinCatalog.kt) | Jellyfin SDK adapter for `ItemPort`, `ItemListPort`, `ItemExtrasPort`, and `ServerInfoPort` |
| [`application/.../ratings/ExternalRatings.kt`](../../application/src/main/kotlin/dev/jdtech/jellyfin/ratings/ExternalRatings.kt), [`ExternalRatingsService.kt`](../../application/src/main/kotlin/dev/jdtech/jellyfin/ratings/ExternalRatingsService.kt), [`ratings/mdblist/`](../../ratings/mdblist/src/main/java/dev/jdtech/jellyfin/ratings/mdblist/), [`core/.../di/ExternalRatingsModule.kt`](../../core/src/main/java/dev/jdtech/jellyfin/di/ExternalRatingsModule.kt) | External ratings service, MDBList HTTP client (`MdbListClient`), disk cache (`FileRatingsCache`), and Hilt binding |

## Rules

- **R1, R2**: no Jellyfin SDK types or `JellyfinApi` outside `server/jellyfin/`. All catalog, list, and extras calls go through `ItemCatalog`, `ItemLists`, and `ItemExtras` (`MediaRepositoryImpl`) over `ItemPort`, `ItemListPort`, and `ItemExtrasPort` (`JellyfinCatalog`).
- **R4**: no production file outside `data/` imports `ServerDatabaseDao`. `MediaRepositoryImpl` reads offline items and stored libraries through `StoredItems` and `StoredItemLists`.
- **R9**: only the apps (`app/phone`, `app/tv`) depend on `data/` and `ratings/mdblist/`. `modes/film/` sees only `ExternalRatings` in `application/`.
- **R10**: `ItemId`, `ServerId`, `UserId`, and `MediaSourceId` are value classes (`Ids.kt`); never pass bare `String` or `java.util.UUID` ids outside `server/jellyfin/`.
- **Structured concurrency & test dispatchers**: concurrent `async` blocks in ViewModels must sit inside `coroutineScope { }` so failures stay inside `try/catch` instead of crashing `viewModelScope` (`HomeViewModel`, `ShowViewModel`, `SeasonViewModel`, `PersonViewModel`). `modes/film/` tests inject dispatchers (`loadDispatcher`, `defaultDispatcher`, `ioDispatcher`, `sectionsDispatcher`) so background work never outlives a test ([#809](https://github.com/midasvo/ephyra/issues/809)).
- **TV focus & no offline mode**: TV screens in `app/tv/.../ce/presentation/film/` restore focus via `FocusPosition` / `RestoreFocus` ([ADR 0003](../tv-research/adr/0003-focus-restore.md)) and omit offline banners and Room fallbacks ([ADR 0007](../tv-research/adr/0007-no-offline-on-tv.md)).

## How to test it

```bash
./gradlew :modes:film:testDebugUnitTest
./gradlew :ratings:mdblist:testDebugUnitTest
```

Unit, Robolectric, and contract tests covering this area:
- `modes/film`: `HomeRowsTest`, `HomeRowsOrderTest`, `HomeRowsViewModelTest`, `HomeViewModelOfflineCrashTest`, `HomeViewModelOfflineRowsTest` (away with nothing downloaded), `HomeViewModelDownloadsAwayTest` (away with downloads), `HomeViewModelPartialFailureTest`, `HomeViewModelServerNameTest`, `HomeViewModelUserSwitchTest`, `LoadDataConcurrencyMechanismTest`, `IndexedItemsPagingSourceTest`, `ItemsPagingSourceTest`, `LetterIndexTest`, `LibraryLoadOnceTest`, `MediaViewModelUserSwitchTest`, `FavoritesViewModelUserSwitchTest`, `ShowLoadingTest`, `SeasonLoadingTest`, `SeasonEpisodeFieldsTest`, `ThemeSongPreferenceTest`, `CastAndCrewPreferenceTest`, `ExternalRatingsLoadingTest`, `RelatedItemsLoadingTest`.
- `domain`, `application`, `data`: `WatchRowsTest` (`./gradlew :domain:test`), `MediaRepositoryImplTest` (`./gradlew :application:test`), `StoredHomeRowsTest` and `StoredListsFallbackTest` (`./gradlew :data:testDebugUnitTest`) for the rows Room answers while the server is away.
- `ratings/mdblist`: `MdbListClientTest`, `FileRatingsCacheTest`.
- `app/phone` & `app/tv`: Robolectric layout, fast-scroller, hero, and TV focus-restore tests (`HomeScreenLayoutTest`, `HomeCacheIdsTest`, `LetterFastScrollerTest`, `ItemButtonsBarWatchedTest`, `HomeRowUpdateTest`, `LibraryFocusRestoreTest`, `CollectionFocusRestoreTest`, `FavoritesFocusRestoreTest`, `PersonFocusRestoreTest`, `DetailDownToRowTest`, `DetailOverviewTest`, `TvCreditsTest`).
- `testing`: `ItemContract`, `ItemListContract`, `ItemExtrasContract` (run against fakes in `:testing:test` and recorded/live Jellyfin in `:server:jellyfin:testDebugUnitTest`).

**What unit tests do not cover:**
- Live Jellyfin server semantics for `JellyfinCatalog` queries (e.g., `getSuggestions`, `getResumeItems`, `getNextUp`, `getLatestMedia`, `nameLessThan` sorting edge cases, `getSimilarItems`, `getExtras`, `getItemCollections`, `getThemeSongs`) beyond recorded contract fixtures.
- Live `api.mdblist.com` responses (`MdbListClientTest` runs against mock HTTP responses).
- Home with the server away on a device: download a movie and episodes as a user of your own, cut the server off (`iptables`, or airplane mode; see [the downloads guide](downloads.md)), and look at Home, the banner and the rows; bring it back and watch the server's rows return.
- Real device scrolling/fling smoothness, Paging 3 placeholder swaps during fast `LetterFastScroller` drags, and TV D-pad focus navigation across `TvItemsRow` and `LibraryScreen`.

## Before a PR

```bash
./gradlew ktfmtCheck
./gradlew :modes:film:testDebugUnitTest :ratings:mdblist:testDebugUnitTest
./gradlew :app:phone:compileLibreDebugKotlin :app:tv:compileLibreDebugKotlin
./gradlew :domain:test :application:test :data:testDebugUnitTest   # when a row Room answers changed
```

If user-visible strings changed, run `python3 .claude/skills/translate-strings/scripts/check-translations.py`. For doc or map changes, run `python3 .claude/skills/start-work/scripts/check-docs.py`.

## Decisions and history

- [#135](https://github.com/midasvo/ephyra/issues/135) / [#154](https://github.com/midasvo/ephyra/pull/154), [#672](https://github.com/midasvo/ephyra/issues/672) / [#697](https://github.com/midasvo/ephyra/pull/697): indexed library paging (`IndexedItemsPagingSource`), `LetterIndex` from 26 `nameLessThan` counts, and A–Z fast scroller on TV and phone/tablet.
- [#142](https://github.com/midasvo/ephyra/issues/142) / [#166](https://github.com/midasvo/ephyra/pull/166), [#431](https://github.com/midasvo/ephyra/issues/431) / [#487](https://github.com/midasvo/ephyra/pull/487): per-user/server Home row ordering and visibility (`HomeRows`, `HomeRowsStore`, `HomeRowsViewModel`) with instant refresh via `DataChangeEvents`.
- [#251](https://github.com/midasvo/ephyra/issues/251) / [#268](https://github.com/midasvo/ephyra/pull/268), [#270](https://github.com/midasvo/ephyra/pull/270), [#252](https://github.com/midasvo/ephyra/issues/252) / [#262](https://github.com/midasvo/ephyra/pull/262), [#274](https://github.com/midasvo/ephyra/pull/274): `ReloadPolicy` (`60s` staleness + `DataChangeEvents`), `HomeCache` JSON cold-start snapshot, concurrent Home and detail loading, in-place played/favourite updates, and `PERSON_ITEMS_LIMIT` (`100`).
- [#331](https://github.com/midasvo/ephyra/issues/331) / [#730](https://github.com/midasvo/ephyra/pull/730): optional MDBList ratings (`ExternalRatings`, `ExternalRatingsLoader`, `MdbListClient`, `FileRatingsCache`).
- [#332](https://github.com/midasvo/ephyra/issues/332) / [#335](https://github.com/midasvo/ephyra/pull/335): `DetailSections` toggles, `RelatedItems` (`extras`, `collections`, `similar`), and `AfterFirstFrame` deferred loading.
- [#371](https://github.com/midasvo/ephyra/issues/371) / [#482](https://github.com/midasvo/ephyra/pull/482): `LibraryViewModel.loadItemsIfNeeded()` tracks `LoadKey` in the ViewModel so process death reloads the grid.
- [#608](https://github.com/midasvo/ephyra/issues/608) / [#610](https://github.com/midasvo/ephyra/pull/610): `WIDE_ROW_IMAGE_TYPES` (`ImageType.THUMB`) and `useEpisodeImages` preference on Continue Watching and Next Up.
- [#640](https://github.com/midasvo/ephyra/issues/640) / [#683](https://github.com/midasvo/ephyra/pull/683), [#688](https://github.com/midasvo/ephyra/issues/688) / [#692](https://github.com/midasvo/ephyra/pull/692): animated Home row card updates on phone and TV.
- [#671](https://github.com/midasvo/ephyra/issues/671) / [#701](https://github.com/midasvo/ephyra/pull/701): Home Videos and Music Videos support in `LibraryViewModel`.
- [#775](https://github.com/midasvo/ephyra/issues/775) / [#778](https://github.com/midasvo/ephyra/pull/778), [#784](https://github.com/midasvo/ephyra/pull/784): Room download fallbacks on phone `MediaScreen`, `FavoritesScreen`, and `LibraryScreen` (`StoredLibraries`, `ServerAwayReload`).
- [#1054](https://github.com/midasvo/ephyra/issues/1054): Home shows the downloads while the server is away, as the old Offline Mode did (`ItemsResult` for Home's rows, `StoredItemLists.homeSuggestions` / `resumeItems` / `nextUp`, `WatchRows`, `HomeState.downloadsOnly`). Not brought back from the old Home: its own "nothing downloaded" text (the error page of #1055 says the server is away and leads to Downloads), and the Latest rows sorted by name (they are the newest downloads first).
- [#810](https://github.com/midasvo/ephyra/issues/810) / [#842](https://github.com/midasvo/ephyra/pull/842), [#866](https://github.com/midasvo/ephyra/issues/866) / [#873](https://github.com/midasvo/ephyra/pull/873), [#872](https://github.com/midasvo/ephyra/issues/872) / [#881](https://github.com/midasvo/ephyra/pull/881): `HomeViewModel` user-switch generation/lock/`clientActsFor`, `HomeState.shownTo`, `SessionUser`, and user-switch guards on `MediaViewModel` and `FavoritesViewModel`.
- [#967](https://github.com/midasvo/ephyra/issues/967) / [#1009](https://github.com/midasvo/ephyra/pull/1009), [#968](https://github.com/midasvo/ephyra/issues/968) / [#1001](https://github.com/midasvo/ephyra/pull/1001): repository/server catalog split into `ItemCatalog`, `ItemLists`, `ItemExtras` over `ItemPort`, `ItemListPort`, `ItemExtrasPort`; `ItemsPagingSource` and `IndexedItemsPagingSource` moved from `application` into `modes/film`.

## Pitfalls

- **Bare `async` inside `viewModelScope.launch` crashes on network error.** Concurrent `async` blocks in `HomeViewModel`, `ShowViewModel`, `SeasonViewModel`, and `PersonViewModel` must stay wrapped in `coroutineScope { }` so a child failure is caught instead of cancelling `viewModelScope` and crashing the process.
- **Including `ItemKind.PHOTO` breaks `IndexedItemsPagingSource`.** `LibraryViewModel` leaves photos out of `HomeVideos`, `Mixed`, and `Folders` because every returned item must map to a supported `Item` or the indexed pager's total count and offsets drift ([#671](https://github.com/midasvo/ephyra/issues/671)).
- **Episodes omit `canDownload` unless `EpisodeField.CAN_DOWNLOAD` is requested.** `ShowViewModel` (`showEpisodeFields`) and `SeasonViewModel` (`seasonEpisodeFields`) explicitly request it; dropping that field silently disables episode/season downloads (`SeasonEpisodeFieldsTest`).
- **Room updates the current user before `ServerSession` switches.** `HomeViewModel` waits for `clientActsFor(userId)` and gates state emissions by `LoadGeneration`, while `HomeScreen`, `MediaScreen`, and `FavoritesScreen` apply `.shownTo(userId)` so the previous user's items never flash for a frame ([#810](https://github.com/midasvo/ephyra/issues/810), [#866](https://github.com/midasvo/ephyra/issues/866), [#872](https://github.com/midasvo/ephyra/issues/872)).
- **A row of the downloads next to the server's rows.** A stored row is shorter than the server's and nothing on it says so. `HomeViewModel` therefore never applies a `RowAnswer.FromStore` by itself: only all of them, when no row of the load is the server's ([#1054](https://github.com/midasvo/ephyra/issues/1054)). A new Home row needs both answers (the server's and the store's) and goes through `answered`.
- **`getHomeLibraries` in the editor of Home's rows.** `HomeRowsViewModel` stores the rows it lists; given the stored libraries while the server is away, a save would drop the user's real Latest rows. It asks `getUserViews` ([#1054](https://github.com/midasvo/ephyra/issues/1054)).
- **Replacing `LibraryViewModel.loadItemsIfNeeded()` with a screen `rememberSaveable` flag breaks process-death restoration.** Saved Compose state survives process death while the recreated ViewModel has empty `items`, leaving a spinner forever if `LoadKey` is bypassed ([#371](https://github.com/midasvo/ephyra/issues/371)).
- **`ExternalRatingsService` caches empty results on disk and keeps back-offs in memory only.** `FileRatingsCache` persists empty lists for `NotFound` or titles with no supported scores (`EMPTY_TTL_MS`), and `ExternalRatingsLoader` clears `loadedFor` only when `!source.canRequest(lookup)` so transient errors/429s/invalid keys can retry once allowed; `rejectedKey` and `blockedUntil` reset on process restart ([#331](https://github.com/midasvo/ephyra/issues/331)).
- **`LetterIndex` hides itself if counts disagree with `total`.** `LetterIndex.build` returns `null` when the 26 `nameLessThan` counts are non-monotonic or exceed `total`, and `LibraryViewModel` invalidates the cached index when the first page's `total` changes ([#135](https://github.com/midasvo/ephyra/issues/135), [#672](https://github.com/midasvo/ephyra/issues/672)).
