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
Section titled “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/), andHomeRowsViewModel(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 inMovieWideLayout,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 toMediaRepositoryImpl) over domain ports indomain/.../domain/ports/(ItemPort,ItemListPort,ItemExtrasPort), implemented byJellyfinCataloginserver/jellyfin/. - Optional external ratings on movie and show screens go through
ExternalRatingsLoader(modes/film/) andExternalRatings/ExternalRatingsService(application/.../ratings/), backed byratings/mdblist/(MdbListClient,FileRatingsCache). - Test fast:
./gradlew :modes:film:testDebugUnitTest.
What it does
Section titled “What it does”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).
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, #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, #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, #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, #571, #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).
Home while the server is away
Section titled “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) and Home showed an error page instead. Since #1054 Home shows the downloads of the current server while the server is away, and keeps the error page (#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):getSuggestions,getResumeItems,getNextUpItemsandgetHomeLibrariesgo throughserverOrStoredItemsand return anItemsResultwithfromStore. 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.storedHomeRowmakes a row answerable only whenStoredItemLists.hasDownloadssays something of the server is downloaded; then an empty row is an answer too.getLatestMediaof 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), andlibraryContentsby download date for the Latest rows.RoomStoredListsreads the rows and the user’s play states; which of them Continue Watching and Next Up hold isWatchRowsandPlayState.hasResumePositionindomain(rule R14), not a query or the ViewModel. Only finished downloads (DownloadState), of the current server, with the current user’s data (#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.downloadsOnlysays which it is; phoneHomeScreenthen showsDownloadsOnlyLineover the rows, under the unreachable banner. - A load the store answered is not written to
HomeCache, andHomeCacheis not read while the server is known away. - While the server is known away (
serverAway == true, which only the phone reports)runLoadstarts neitherrefreshUserImagenorrefreshServerName: 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.onServerAwayChangedreloads 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 afterServerAwayReload.STORE_RETRY_DELAY_MS, as on Media (#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).HomeRowsViewModelkeeps askinggetUserViews, nevergetHomeLibraries: it stores what it lists.
Libraries, My media, Collections, and Favourites
Section titled “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, #781), and Music Videos and Home Videos when such downloads exist (StoredLibraries.OF_MOVIE_KIND, #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). 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, #672). LibraryViewModel.loadItemsIfNeeded() caches a LoadKey(parentId, libraryType, indexed) so Back navigation keeps the loaded grid while process death reloads it (#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, #782, #866).
Item detail screens and external ratings
Section titled “Item detail screens and external ratings”MovieViewModel, ShowViewModel, SeasonViewModel, EpisodeViewModel, and PersonViewModel load their primary item and cast/crew concurrently inside coroutineScope (#252, #262, #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, #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). 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, #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).
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, #769).
Where the code is
Section titled “Where the code is”| Path | What |
|---|---|
modes/film/.../home/HomeViewModel.kt, HomeState.kt, HomeCache.kt, 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, HomeRowsStore.kt, homerows/HomeRowsViewModel.kt |
Per-user/server Home row layout resolution, storage, and settings editor (#142) |
modes/film/.../library/LibraryViewModel.kt, IndexedItemsPagingSource.kt, ItemsPagingSource.kt, LetterIndex.kt |
Library ViewModel, Paging 3 sources (with/without placeholders), A–Z LetterIndex |
modes/film/.../media/MediaViewModel.kt, favorites/FavoritesViewModel.kt, collection/CollectionViewModel.kt |
Libraries tab, Favourites, and BoxSet collections |
modes/film/.../movie/MovieViewModel.kt, show/ShowViewModel.kt, season/SeasonViewModel.kt, episode/EpisodeViewModel.kt, person/PersonViewModel.kt |
Item detail ViewModels (concurrent loading, downloads/episodes, in-place user data) |
modes/film/.../DetailSections.kt, RelatedItems.kt, ExternalRatingsLoader.kt |
Detail metadata toggles, deferred extras/collections/similar rows, and external ratings state |
app/phone/.../presentation/film/ |
Phone/tablet screens (HomeScreen, LibraryScreen, MediaScreen, FavoritesScreen, CollectionScreen, MovieScreen, ShowScreen, SeasonScreen, EpisodeScreen, PersonScreen, ItemExtras) |
app/phone/.../film/components/ItemButtonsBar.kt, LetterFastScroller.kt, ExternalRatingsRow.kt |
Phone action bar, A–Z fast scroller bubble, and external ratings chips |
app/tv/.../ce/presentation/film/ |
TV screens (HomeScreen, LibraryScreen, FavoritesScreen, CollectionScreen, MovieScreen, ShowScreen, SeasonScreen, PersonScreen, DetailMetadata) |
domain/.../ports/ItemPort.kt, ItemListPort.kt, ItemExtrasPort.kt |
Server-agnostic catalog, list, and extras ports |
application/.../repository/ItemCatalog.kt, ItemLists.kt, ItemExtras.kt, MediaRepositoryImpl.kt, ReloadPolicy.kt |
Repository role interfaces, Room/server composition, and staleness policy |
application/.../repository/StoredItemLists.kt, data/.../database/RoomStoredLists.kt, 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 |
Jellyfin SDK adapter for ItemPort, ItemListPort, ItemExtrasPort, and ServerInfoPort |
application/.../ratings/ExternalRatings.kt, ExternalRatingsService.kt, ratings/mdblist/, core/.../di/ExternalRatingsModule.kt |
External ratings service, MDBList HTTP client (MdbListClient), disk cache (FileRatingsCache), and Hilt binding |
- R1, R2: no Jellyfin SDK types or
JellyfinApioutsideserver/jellyfin/. All catalog, list, and extras calls go throughItemCatalog,ItemLists, andItemExtras(MediaRepositoryImpl) overItemPort,ItemListPort, andItemExtrasPort(JellyfinCatalog). - R4: no production file outside
data/importsServerDatabaseDao.MediaRepositoryImplreads offline items and stored libraries throughStoredItemsandStoredItemLists. - R9: only the apps (
app/phone,app/tv) depend ondata/andratings/mdblist/.modes/film/sees onlyExternalRatingsinapplication/. - R10:
ItemId,ServerId,UserId, andMediaSourceIdare value classes (Ids.kt); never pass bareStringorjava.util.UUIDids outsideserver/jellyfin/. - Structured concurrency & test dispatchers: concurrent
asyncblocks in ViewModels must sit insidecoroutineScope { }so failures stay insidetry/catchinstead of crashingviewModelScope(HomeViewModel,ShowViewModel,SeasonViewModel,PersonViewModel).modes/film/tests inject dispatchers (loadDispatcher,defaultDispatcher,ioDispatcher,sectionsDispatcher) so background work never outlives a test (#809). - TV focus & no offline mode: TV screens in
app/tv/.../ce/presentation/film/restore focus viaFocusPosition/RestoreFocus(ADR 0003) and omit offline banners and Room fallbacks (ADR 0007).
How to test it
Section titled “How to test it”./gradlew :modes:film:testDebugUnitTest./gradlew :ratings:mdblist:testDebugUnitTestUnit, 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),StoredHomeRowsTestandStoredListsFallbackTest(./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:testand recorded/live Jellyfin in:server:jellyfin:testDebugUnitTest).
What unit tests do not cover:
- Live Jellyfin server semantics for
JellyfinCatalogqueries (e.g.,getSuggestions,getResumeItems,getNextUp,getLatestMedia,nameLessThansorting edge cases,getSimilarItems,getExtras,getItemCollections,getThemeSongs) beyond recorded contract fixtures. - Live
api.mdblist.comresponses (MdbListClientTestruns 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), 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
LetterFastScrollerdrags, and TV D-pad focus navigation acrossTvItemsRowandLibraryScreen.
Before a PR
Section titled “Before a PR”./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 changedIf 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
Section titled “Decisions and history”- #135 / #154, #672 / #697: indexed library paging (
IndexedItemsPagingSource),LetterIndexfrom 26nameLessThancounts, and A–Z fast scroller on TV and phone/tablet. - #142 / #166, #431 / #487: per-user/server Home row ordering and visibility (
HomeRows,HomeRowsStore,HomeRowsViewModel) with instant refresh viaDataChangeEvents. - #251 / #268, #270, #252 / #262, #274:
ReloadPolicy(60sstaleness +DataChangeEvents),HomeCacheJSON cold-start snapshot, concurrent Home and detail loading, in-place played/favourite updates, andPERSON_ITEMS_LIMIT(100). - #331 / #730: optional MDBList ratings (
ExternalRatings,ExternalRatingsLoader,MdbListClient,FileRatingsCache). - #332 / #335:
DetailSectionstoggles,RelatedItems(extras,collections,similar), andAfterFirstFramedeferred loading. - #371 / #482:
LibraryViewModel.loadItemsIfNeeded()tracksLoadKeyin the ViewModel so process death reloads the grid. - #608 / #610:
WIDE_ROW_IMAGE_TYPES(ImageType.THUMB) anduseEpisodeImagespreference on Continue Watching and Next Up. - #640 / #683, #688 / #692: animated Home row card updates on phone and TV.
- #671 / #701: Home Videos and Music Videos support in
LibraryViewModel. - #775 / #778, #784: Room download fallbacks on phone
MediaScreen,FavoritesScreen, andLibraryScreen(StoredLibraries,ServerAwayReload). - #1054: Home shows the downloads while the server is away, as the old Offline Mode did (
ItemsResultfor 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 / #842, #866 / #873, #872 / #881:
HomeViewModeluser-switch generation/lock/clientActsFor,HomeState.shownTo,SessionUser, and user-switch guards onMediaViewModelandFavoritesViewModel. - #967 / #1009, #968 / #1001: repository/server catalog split into
ItemCatalog,ItemLists,ItemExtrasoverItemPort,ItemListPort,ItemExtrasPort;ItemsPagingSourceandIndexedItemsPagingSourcemoved fromapplicationintomodes/film.
Pitfalls
Section titled “Pitfalls”- Bare
asyncinsideviewModelScope.launchcrashes on network error. Concurrentasyncblocks inHomeViewModel,ShowViewModel,SeasonViewModel, andPersonViewModelmust stay wrapped incoroutineScope { }so a child failure is caught instead of cancellingviewModelScopeand crashing the process. - Including
ItemKind.PHOTObreaksIndexedItemsPagingSource.LibraryViewModelleaves photos out ofHomeVideos,Mixed, andFoldersbecause every returned item must map to a supportedItemor the indexed pager’s total count and offsets drift (#671). - Episodes omit
canDownloadunlessEpisodeField.CAN_DOWNLOADis requested.ShowViewModel(showEpisodeFields) andSeasonViewModel(seasonEpisodeFields) explicitly request it; dropping that field silently disables episode/season downloads (SeasonEpisodeFieldsTest). - Room updates the current user before
ServerSessionswitches.HomeViewModelwaits forclientActsFor(userId)and gates state emissions byLoadGeneration, whileHomeScreen,MediaScreen, andFavoritesScreenapply.shownTo(userId)so the previous user’s items never flash for a frame (#810, #866, #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.
HomeViewModeltherefore never applies aRowAnswer.FromStoreby itself: only all of them, when no row of the load is the server’s (#1054). A new Home row needs both answers (the server’s and the store’s) and goes throughanswered. getHomeLibrariesin the editor of Home’s rows.HomeRowsViewModelstores the rows it lists; given the stored libraries while the server is away, a save would drop the user’s real Latest rows. It asksgetUserViews(#1054).- Replacing
LibraryViewModel.loadItemsIfNeeded()with a screenrememberSaveableflag breaks process-death restoration. Saved Compose state survives process death while the recreated ViewModel has emptyitems, leaving a spinner forever ifLoadKeyis bypassed (#371). ExternalRatingsServicecaches empty results on disk and keeps back-offs in memory only.FileRatingsCachepersists empty lists forNotFoundor titles with no supported scores (EMPTY_TTL_MS), andExternalRatingsLoaderclearsloadedForonly when!source.canRequest(lookup)so transient errors/429s/invalid keys can retry once allowed;rejectedKeyandblockedUntilreset on process restart (#331).LetterIndexhides itself if counts disagree withtotal.LetterIndex.buildreturnsnullwhen the 26nameLessThancounts are non-monotonic or exceedtotal, andLibraryViewModelinvalidates the cached index when the first page’stotalchanges (#135, #672).
Source: docs/areas/home-and-library.md · raw Markdown