Skip to content

StreamVault is a TV-first free IPTV player for Android TV built with Kotlin, Jetpack Compose, Room, Hilt, and Media3.

feat: Enhance catalog fixture with deterministic media and download completion

David Nashashcddef1526924
diff --git a/docs/COMPOSE_REDUCTION_AND_UI_ARCHITECTURE_PLAN.md b/docs/COMPOSE_REDUCTION_AND_UI_ARCHITECTURE_PLAN.md
index e80b21e0..fab03ec4 100644
--- a/docs/COMPOSE_REDUCTION_AND_UI_ARCHITECTURE_PLAN.md
+++ b/docs/COMPOSE_REDUCTION_AND_UI_ARCHITECTURE_PLAN.md
@@ -988,8 +988,11 @@ paths, plus reversible quick-filter save/reload/remove persistence. The full
favorite/saved/Search path, Movies full-library entry/back,
`Load more (60/63)` → `Pagination Movie 63`, Infinite scroll off/on
restoration, and the Settings-owned Dashboard shelf customization
- cancel/save/reset flow. Series pagination, browse reorder, download/Cast
- completion, direct-Favorites, and accessibility journeys,
+ cancel/save/reset flow. Series pagination, browse reorder, movie download
+ completion, and direct Favorites test-host rendering/Back cancellation are
+ covered; Catalog RTL/large-text semantics and reduced-motion instrumentation
+ also pass. Cast receiver chooser, touch/device variants, and accessibility
+ service journeys,
successful
diagnostic Dashboard benchmark rerun after populating a scrollable seeded
Home shelf, open paired benchmark gate, refreshed release-like profiles, and
diff --git a/docs/COMPOSE_REDUCTION_PHASE5_CATALOG_REPORT.md b/docs/COMPOSE_REDUCTION_PHASE5_CATALOG_REPORT.md
index 4b519f29..9ff045b6 100644
--- a/docs/COMPOSE_REDUCTION_PHASE5_CATALOG_REPORT.md
+++ b/docs/COMPOSE_REDUCTION_PHASE5_CATALOG_REPORT.md
@@ -1,6 +1,6 @@
# Compose Reduction Phase 5 — Catalog execution report
-Date: 2026-09-03
+Date: 2026-09-04
Status: structurally extracted; connected Catalog goldens now pass
## Outcome
@@ -87,6 +87,9 @@ Target: `emulator-5554`, `Television_1080p(AVD) - 16`, API 36, AOSP TV x86,
- Feature connected suite: 5/5 passed after correcting the golden harness to
capture the full unpadded 1920x1080 Canvas surface and re-recording reviewed
feature-only baselines.
+- Latest direct-Favorites-host-inclusive Catalog connected rerun: 6/6 passed;
+ this added the real Favorites composable host and Activity Back cancellation
+ regression on the same target.
- App `AppNavigationContractTest`: 3/3 passed.
- App `PlatformCompatibilityMatrixTest`: 4/4 passed.
- No Catalog-caused fatal exception was reported by these runs.
@@ -116,17 +119,39 @@ by `tools/catalog_connected_validation.py`. This remains diagnostic evidence,
not a production-provider pass.
The same semantic harness now also opens Settings Browsing, switches Infinite
-scroll off, proves the selected Movies library reaches `Load more (60/63)`,
-activates the control to render `Pagination Movie 63`, and restores Infinite
-scroll on. It then opens the Settings-owned Dashboard shelf customization
-dialog through TV focus, proves cancel leaves the persisted seven-shelf order
-unchanged, saves a six-shelf edit, and resets/saves the default order again.
-The rerun and surface list are recorded in
-`validation/phase5_catalog/task14-xtream-fixture-journeys.md`. Movie
-pagination and the Movies browse return path are covered; Series pagination,
-browse reorder, download completion, Cast chooser, direct Favorites-host,
-touch/phone/tablet, RTL, reduced-motion/accessibility, and the paired
-performance matrix remain open.
+scroll off, proves the selected Movies and Series libraries reach `Load more
+(60/63)`, activates the controls to render `Pagination Movie 63` and
+`Pagination Series 63`, and restores Infinite scroll on. It then opens the
+Settings-owned Dashboard shelf customization dialog through TV focus, proves
+cancel leaves the persisted seven-shelf order unchanged, saves a six-shelf
+edit, and resets/saves the default order again. The latest rerun also enters
+the Favorites reorder surface for both Movies and Series, moves each fixture
+pair in both directions, verifies the saved order after leaving edit mode,
+re-enters to prove persistence, and restores the original order. Its report
+is `build/catalog-validation-download-completion-retry/report.json`; the full
+surface list is recorded in
+`validation/phase5_catalog/task14-xtream-fixture-journeys.md`. Movie and
+Series pagination, browse reorder, the Movies browse return path, and
+download completion are covered. A direct test host now renders the real
+Favorites composable and verifies Activity Back cancels reorder; the host is
+not a production route. A focused Catalog behavior test now covers merged card
+semantics and RTL placement at 1.5x font scale, and the full Catalog
+instrumentation suite passes with animator scale 0. Cast chooser,
+touch/phone/tablet, the full production accessibility-service journey, and
+the paired performance matrix remain open. The same 7-test Catalog
+instrumentation suite also passed with the API 36 AOSP TalkBack service
+enabled. The fixture journey reached the Catalog reorder surface under
+TalkBack, but the semantic ADB harness could not maintain its D-pad focus
+path consistently (`Reorder Items` on one run, the first browse card on the
+next); direct TalkBack instrumentation evidence is therefore positive, while
+the production fixture accessibility journey remains unclosed.
+The direct Favorites composable remains intentionally unregistered by the
+Catalog architecture plan; its direct host now exercises the real reorder
+panel and BackHandler, while the ViewModel cancel/Back path restores the
+preview without persisting it, with focused host and unit regressions.
+Copy URL is independently covered by a focused Robolectric clipboard-read
+regression; the API 36 shell limitation remains documented as a device-shell
+evidence limitation.
## Build isolation and performance
@@ -151,6 +176,8 @@ fixture had no scrollable content and failed before metrics with
is diagnostic after-run evidence only: no cache-equivalent pre-extraction run
was captured, and the public M3U fixture still lacks VOD/series content, so the
formal paired performance gate remains open.
+That benchmark comparison is explicitly deferred until the computer/device has
+stable capacity for matched baseline and current runs.
## Profiles and known failures
@@ -181,8 +208,10 @@ execution-time project access.
## Next acceptance work
1. Use the checked-in Xtream fixture (or approved provider data) to execute the
- remaining browse, detail-action, direct Favorites, and accessibility
- journeys, and keep the fixture invocation in the validation protocol.
+ remaining browse, detail-action, and production accessibility-service journeys,
+ and keep the fixture invocation in the validation protocol. Direct TalkBack
+ Catalog instrumentation is already passing; the end-to-end fixture harness
+ still needs a stable TalkBack-compatible focus path.
2. Capture a cache-equivalent pre-extraction run and pair it with the
successful Dashboard benchmark evidence, using the same seeded content,
device, iteration count, and compilation mode. Keep app lint remediation and
diff --git a/docs/COMPOSE_REDUCTION_PHASE5_ROADMAP.md b/docs/COMPOSE_REDUCTION_PHASE5_ROADMAP.md
index ce9bb7b3..99d8df37 100644
--- a/docs/COMPOSE_REDUCTION_PHASE5_ROADMAP.md
+++ b/docs/COMPOSE_REDUCTION_PHASE5_ROADMAP.md
@@ -123,9 +123,14 @@ and `tools/catalog_connected_validation.py` provides a semantic ADB journey
for the fixture-backed Home/Movies/Series/detail/favorite/saved/Search path,
Movies full-library entry/back, Movies `Load more (60/63)` → `Pagination Movie
63`, Infinite scroll off/on restoration, and Settings-owned Dashboard shelf
-customization cancel/save/reset flow. Series pagination, browse reorder,
-download/Cast completion, direct-Favorites, and accessibility journeys remain
-open.
+ customization cancel/save/reset flow. Series pagination, browse reorder,
+ movie download completion, and direct Favorites test-host rendering/Back
+ cancellation are covered. Catalog RTL/large-text semantics and a reduced-
+ motion connected run also pass. The same Catalog instrumentation suite
+ passes with AOSP TalkBack enabled, but the fixture-driven production
+ TalkBack traversal loses semantic D-pad focus in the current ADB harness.
+ Cast receiver chooser, touch/device variants, and a complete production
+ accessibility-service audit remain open.
A focused Dashboard macrobenchmark rerun passed 1/1 with five warm iterations
once public-M3U live-channel activity populated a scrollable Home shelf
(`frameCount` min/median/max 88/91/98; `frameOverrunMs` P50/P90/P95/P99
@@ -133,5 +138,8 @@ once public-M3U live-channel activity populated a scrollable Home shelf
slices; the rerun is diagnostic after-run evidence, not a cache-equivalent
paired comparison. The paired comparison and repository-wide app lint remain
open.
+The paired Dashboard comparison is intentionally deferred until the
+benchmark environment has stable capacity for matched baseline and current
+runs.
The release-like profile workflow now passes with feature Catalog descriptors.
System remains unstarted.
diff --git a/docs/superpowers/plans/2026-09-02-catalog-feature-extraction.md b/docs/superpowers/plans/2026-09-02-catalog-feature-extraction.md
index 2ec2fffe..1073b437 100644
--- a/docs/superpowers/plans/2026-09-02-catalog-feature-extraction.md
+++ b/docs/superpowers/plans/2026-09-02-catalog-feature-extraction.md
@@ -37,14 +37,23 @@ Search in the production activity; its semantic evidence is in
and `tools/catalog_connected_validation.py` provides a semantic ADB journey
for the fixture-backed Home/Movies/Series/detail/favorite/saved/Search path,
Movies full-library entry/back, the `Load more (60/63)` → `Pagination Movie 63`
-second-page transition with Infinite scroll restored on, and the Settings-owned
-Dashboard shelf customization cancel/save/reset flow. The remaining Series
-pagination, browse reorder, action/direct-Favorites/accessibility journeys;
-repository-wide app lint remains open.
+second-page transition with Infinite scroll restored on, the `Pagination Series
+63` second-page transition, Movie/Series Favorites browse reorder
+save/persistence/restore, and the Settings-owned Dashboard shelf
+customization cancel/save/reset flow. Download completion is now covered by
+the fixture-backed production Downloads journey. RTL/large-text semantics and
+ the reduced-motion Catalog instrumentation run also pass. The same 7-test
+ Catalog instrumentation suite passes with AOSP TalkBack enabled, but the
+ fixture-driven production TalkBack traversal loses semantic D-pad focus in
+ the current ADB harness. Cast receiver chooser, the remaining production
+ accessibility journey, cache-equivalent performance, and repository-wide
+ app lint remain open.
A focused Dashboard macrobenchmark rerun now passes after public-M3U
live-channel activity populates a scrollable seeded Home shelf, but it is
diagnostic after-run evidence rather than the required cache-equivalent paired
-comparison. These limitations are documented in
+comparison. The paired Dashboard benchmark is explicitly deferred until the
+computer/device has capacity for the baseline and current runs. These
+limitations are documented in
`docs/COMPOSE_REDUCTION_PHASE5_CATALOG_REPORT.md`. Do not interpret this
status as completion of Phase 5.
@@ -1069,9 +1078,16 @@ Favorites: direct test-host rendering and reorder/save/cancel because no route e
Expected: no crash, stuck focus, lost top navigation, wrong return destination, duplicate callback, incorrect list identity, or new error state.
-- [ ] **Step 5: Exercise phone/tablet and accessibility variants when available**
+- [ ] **Step 5: Exercise phone/tablet and remaining accessibility variants when available**
-Run representative browse/detail/search journeys in touch mode, RTL locale, and reduced-motion/animation-disabled configuration. If a device/configuration is unavailable, record it as unavailable rather than passed.
+Run representative browse/detail/search journeys in touch mode, phone/tablet
+profiles, and through an accessibility service when available. The Catalog
+behavior test covers RTL/large-text semantics, the connected suite has passed
+with animations disabled and with AOSP TalkBack enabled, and the fixture
+journey has exposed a TalkBack-sensitive semantic D-pad harness limitation;
+retain that evidence rather than treating it as a production accessibility
+pass. If a device/configuration is unavailable, record it as unavailable
+rather than passed.
- [ ] **Step 6: Capture and scan logs**
@@ -1138,10 +1154,16 @@ Expected: Catalog and required app integration tasks run; sibling feature Kotlin
Expected: PASS. Record duration and artifact sizes; compare clean-build regression against the plan's 5% guardrail with measurement noise disclosed.
-- [ ] **Step 4: Run the Dashboard Macrobenchmark comparison**
+- [ ] **Step 4: Run the Dashboard Macrobenchmark comparison (deferred)**
Run the existing seeded `dashboardVerticalScroll` benchmark with the same emulator/device, iteration count, compilation mode, and package used by the baseline. Record frame count and P50/P90/P99 overrun metrics before/after. Do not infer a runtime win from unmatched device/build conditions.
+This gate is intentionally deferred in the current Catalog continuation because
+the computer is under heavy load. The diagnostic after-run benchmark evidence
+already recorded in `performance-after.md` is not a substitute for the paired
+comparison; resume this step only when the baseline and current runs can be
+completed on the same device under stable load.
+
- [ ] **Step 5: Regenerate and inspect profiles**
Run the existing baseline-profile generator, then build release. Search generated sources/output for stale app Catalog descriptors and new feature Catalog descriptors.
@@ -1215,23 +1237,31 @@ If generated profile paths differ, stage only files produced by the verified gen
Prove Home/Movies/Series/detail/favorite/saved/Search, Movies full-library
entry/back, Settings Infinite scroll off, `Load more (60/63)` activation
- through `Pagination Movie 63`, restoration of Infinite scroll on, and
- Dashboard customization cancel/save/reset. Persist UIAutomator snapshots and
- a JSON report under ignored `build/` output.
+ through `Pagination Movie 63`, restoration of Infinite scroll on, Dashboard
+ customization cancel/save/reset, and Movie/Series Favorites browse reorder
+ with save, persistence, and restore. The journey also downloads `Fixture Movie
+ One` and proves the production Downloads card reaches `Completed` with an
+ output path. Persist UIAutomator snapshots and a JSON report under ignored
+ `build/` output.
- [x] **Step 3: Run the TV journey and record bounded evidence**
- The API 36 AOSP TV run passed 5/5 feature connected tests and the semantic
- journey in `build/catalog-validation-pagination-final-15`. The fixture was
- stopped and its temporary local properties are removed after validation.
+ The API 36 AOSP TV run passed 7/7 feature connected tests and the latest
+ fixture-backed semantic journey in
+ `build/catalog-validation-download-completion-retry`. It proved Movie and
+ Series selected-library pagination, Favorites browse reorder persistence, and
+ fixture-backed movie download completion. A focused direct host test also
+ rendered the real Favorites composable and verified Activity Back cancels
+ reorder without introducing a production route. The fixture was stopped and
+ its temporary local properties were removed after validation.
- [ ] **Step 4: Finish the remaining Catalog acceptance gates**
- Execute Series selected-library pagination, browse reorder, download
- completion, Cast receiver chooser, direct Favorites-host reorder/save/cancel,
- touch/phone/tablet/RTL/reduced-motion/accessibility variants, and a
- cache-equivalent Dashboard performance comparison. Keep app lint and other
- Phase 5 gates separate from Catalog ownership.
+ Execute the Cast receiver chooser, touch/phone/tablet and remaining
+ production accessibility variants. The cache-equivalent Dashboard
+ performance comparison is deferred until the benchmark environment has
+ stable capacity; keep app lint and other Phase 5 gates separate from Catalog
+ ownership.
## Exit Criteria
diff --git a/feature/catalog/build.gradle.kts b/feature/catalog/build.gradle.kts
index 3ef87600..ffa893d5 100644
--- a/feature/catalog/build.gradle.kts
+++ b/feature/catalog/build.gradle.kts
@@ -202,4 +202,8 @@ dependencies {
androidTestImplementation(libs.androidx.test.ext.junit)
androidTestImplementation(libs.androidx.test.runner)
androidTestImplementation(libs.truth)
+ androidTestImplementation(libs.mockito.kotlin) {
+ exclude(group = "org.mockito", module = "mockito-core")
+ }
+ androidTestImplementation("org.mockito:mockito-android:5.18.0")
}
diff --git a/feature/catalog/src/androidTest/java/com/streamvault/feature/catalog/presentation/CatalogPresentationBehaviorTest.kt b/feature/catalog/src/androidTest/java/com/streamvault/feature/catalog/presentation/CatalogPresentationBehaviorTest.kt
index 4822aac7..5c0a1d1e 100644
--- a/feature/catalog/src/androidTest/java/com/streamvault/feature/catalog/presentation/CatalogPresentationBehaviorTest.kt
+++ b/feature/catalog/src/androidTest/java/com/streamvault/feature/catalog/presentation/CatalogPresentationBehaviorTest.kt
@@ -1,11 +1,29 @@
package com.streamvault.feature.catalog.presentation
import androidx.compose.ui.test.assertIsSelected
+import androidx.compose.ui.test.assertHasClickAction
+import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.junit4.createComposeRule
+import androidx.compose.ui.test.onNodeWithContentDescription
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performSemanticsAction
import androidx.compose.ui.semantics.SemanticsActions
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.runtime.CompositionLocalProvider
+import androidx.compose.ui.platform.LocalDensity
+import androidx.compose.ui.platform.LocalLayoutDirection
+import androidx.compose.ui.unit.Density
+import androidx.compose.ui.unit.LayoutDirection
+import androidx.compose.ui.unit.dp
import androidx.tv.material3.MaterialTheme
+import com.google.common.truth.Truth.assertThat
+import com.streamvault.core.ui.theme.StreamVaultTheme
+import com.streamvault.domain.model.Movie
+import com.streamvault.domain.model.Series
+import com.streamvault.feature.catalog.presentation.components.MovieCard
+import com.streamvault.feature.catalog.presentation.components.SeriesCard
import com.streamvault.feature.catalog.presentation.components.SelectionChip
import com.streamvault.feature.catalog.presentation.components.SelectionChipRow
import org.junit.Rule
@@ -37,4 +55,55 @@ class CatalogPresentationBehaviorTest {
composeRule.onNodeWithText("Movies").performSemanticsAction(SemanticsActions.OnClick)
composeRule.runOnIdle { assertEquals("movies", selectedKey) }
}
+
+ @Test
+ fun catalogCards_keepAccessibleSemantics_inRtlAndLargeFont() {
+ composeRule.setContent {
+ CompositionLocalProvider(
+ LocalLayoutDirection provides LayoutDirection.Rtl,
+ LocalDensity provides Density(density = 1f, fontScale = 1.5f)
+ ) {
+ StreamVaultTheme {
+ MaterialTheme {
+ Row(
+ modifier = androidx.compose.ui.Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.spacedBy(16.dp)
+ ) {
+ MovieCard(
+ movie = Movie(
+ id = 1L,
+ name = "The Night Shift",
+ year = "2026",
+ isFavorite = true
+ ),
+ onClick = {}
+ )
+ SeriesCard(
+ series = Series(
+ id = 2L,
+ name = "The Long Road",
+ genre = "Drama",
+ isFavorite = true
+ ),
+ onClick = {}
+ )
+ }
+ }
+ }
+ }
+ }
+
+ val movieNode = composeRule.onNodeWithContentDescription(
+ "The Night Shift. 2026. Favorite"
+ )
+ val seriesNode = composeRule.onNodeWithContentDescription(
+ "The Long Road. Drama. Favorite"
+ )
+ movieNode.assertIsDisplayed().assertHasClickAction()
+ seriesNode.assertIsDisplayed().assertHasClickAction()
+
+ val movieBounds = movieNode.fetchSemanticsNode().boundsInRoot
+ val seriesBounds = seriesNode.fetchSemanticsNode().boundsInRoot
+ assertThat(movieBounds.left).isGreaterThan(seriesBounds.left)
+ }
}
diff --git a/feature/catalog/src/androidTest/java/com/streamvault/feature/catalog/presentation/favorites/FavoritesScreenHostTest.kt b/feature/catalog/src/androidTest/java/com/streamvault/feature/catalog/presentation/favorites/FavoritesScreenHostTest.kt
new file mode 100644
index 00000000..54e2e342
--- /dev/null
+++ b/feature/catalog/src/androidTest/java/com/streamvault/feature/catalog/presentation/favorites/FavoritesScreenHostTest.kt
@@ -0,0 +1,152 @@
+package com.streamvault.feature.catalog.presentation.favorites
+
+import android.content.Context
+import androidx.activity.ComponentActivity
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.ui.test.junit4.createAndroidComposeRule
+import androidx.compose.ui.test.assertIsDisplayed
+import androidx.compose.ui.test.onNodeWithText
+import androidx.compose.ui.Modifier
+import androidx.test.core.app.ApplicationProvider
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.tv.material3.MaterialTheme
+import com.google.common.truth.Truth.assertThat
+import com.streamvault.core.navigation.AppDestination
+import com.streamvault.data.local.dao.ChannelPreferenceDao
+import com.streamvault.data.local.dao.SearchHistoryDao
+import com.streamvault.data.preferences.PreferencesCorruptionRecovery
+import com.streamvault.data.preferences.PreferencesRepository
+import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.Favorite
+import com.streamvault.domain.model.LegacyProvider
+import com.streamvault.domain.model.Movie
+import com.streamvault.domain.model.ProviderType
+import com.streamvault.domain.repository.ChannelRepository
+import com.streamvault.domain.repository.FavoriteRepository
+import com.streamvault.domain.repository.MovieRepository
+import com.streamvault.domain.repository.PlaybackHistoryRepository
+import com.streamvault.domain.repository.ProviderRepository
+import com.streamvault.domain.repository.SeriesRepository
+import com.streamvault.domain.usecase.GetContinueWatching
+import com.streamvault.feature.catalog.api.CatalogScaffoldContent
+import kotlinx.coroutines.flow.flowOf
+import org.junit.Rule
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.mockito.kotlin.any
+import org.mockito.kotlin.anyOrNull
+import org.mockito.kotlin.mock
+import org.mockito.kotlin.whenever
+
+@RunWith(AndroidJUnit4::class)
+@OptIn(androidx.compose.ui.test.ExperimentalTestApi::class)
+class FavoritesScreenHostTest {
+
+ @get:Rule
+ val composeRule = createAndroidComposeRule<ComponentActivity>()
+
+ @Test
+ fun directHostRendersFavoritesAndBackCancelsReorder() {
+ val provider = LegacyProvider(
+ id = 7L,
+ name = "Fixture provider",
+ type = ProviderType.XTREAM_CODES,
+ serverUrl = "http://fixture.test"
+ )
+ val first = Favorite(
+ id = 101L,
+ providerId = provider.id,
+ contentId = 1001L,
+ contentType = ContentType.MOVIE,
+ position = 0
+ )
+ val second = first.copy(
+ id = 102L,
+ contentId = 1002L,
+ position = 1
+ )
+ val favoriteRepository: FavoriteRepository = mock()
+ val channelRepository: ChannelRepository = mock()
+ val movieRepository: MovieRepository = mock()
+ val seriesRepository: SeriesRepository = mock()
+ val playbackHistoryRepository: PlaybackHistoryRepository = mock()
+ val providerRepository: ProviderRepository = mock()
+ val channelPreferenceDao: ChannelPreferenceDao = mock()
+ val searchHistoryDao: SearchHistoryDao = mock()
+ val appContext = ApplicationProvider.getApplicationContext<Context>()
+ val preferencesRepository = PreferencesRepository(
+ context = appContext,
+ channelPreferenceDao = channelPreferenceDao,
+ searchHistoryDao = searchHistoryDao,
+ corruptionRecovery = PreferencesCorruptionRecovery(appContext)
+ )
+ whenever(providerRepository.getProviders()).thenReturn(flowOf(listOf(provider)))
+ whenever(providerRepository.getActiveProvider()).thenReturn(flowOf(provider))
+ whenever(favoriteRepository.getFavorites(any<List<Long>>(), anyOrNull()))
+ .thenReturn(flowOf(listOf(first, second)))
+ whenever(favoriteRepository.getGroups(any<List<Long>>(), any()))
+ .thenReturn(flowOf(emptyList()))
+ whenever(favoriteRepository.getGroupFavoriteCounts(any<List<Long>>(), any()))
+ .thenReturn(flowOf(emptyMap()))
+ whenever(movieRepository.getMoviesByIds(any<List<Long>>())).thenReturn(
+ flowOf(
+ listOf(
+ Movie(id = 1001L, name = "First fixture movie", providerId = provider.id),
+ Movie(id = 1002L, name = "Second fixture movie", providerId = provider.id)
+ )
+ )
+ )
+ whenever(playbackHistoryRepository.getRecentlyWatched(any()))
+ .thenReturn(flowOf(emptyList()))
+ whenever(playbackHistoryRepository.getRecentlyWatchedByProvider(any(), any()))
+ .thenReturn(flowOf(emptyList()))
+ val viewModel = FavoritesViewModel(
+ appContext = appContext,
+ favoriteRepository = favoriteRepository,
+ channelRepository = channelRepository,
+ movieRepository = movieRepository,
+ seriesRepository = seriesRepository,
+ playbackHistoryRepository = playbackHistoryRepository,
+ providerRepository = providerRepository,
+ preferencesRepository = preferencesRepository,
+ getContinueWatching = GetContinueWatching(playbackHistoryRepository)
+ )
+
+ composeRule.setContent {
+ MaterialTheme {
+ FavoritesScreen(
+ onItemClick = {},
+ onHistoryClick = {},
+ currentDestination = AppDestination.Home,
+ onDestinationRequested = {},
+ scaffold = testScaffold,
+ viewModel = viewModel
+ )
+ }
+ }
+
+ composeRule.waitUntil(timeoutMillis = 5_000) {
+ viewModel.uiState.value.sections.singleOrNull()?.items?.size == 2
+ }
+ composeRule.onNodeWithText("Saved").assertIsDisplayed()
+
+ val firstUiModel = viewModel.uiState.value.sections.single().items.first()
+ viewModel.enterReorderMode("global", firstUiModel)
+ composeRule.waitUntil(timeoutMillis = 5_000) { viewModel.uiState.value.isReorderMode }
+ composeRule.onNodeWithText("Reorder mode").assertIsDisplayed()
+ composeRule.activity.onBackPressedDispatcher.onBackPressed()
+
+ composeRule.waitUntil(timeoutMillis = 5_000) { !viewModel.uiState.value.isReorderMode }
+ assertThat(viewModel.uiState.value.isReorderMode).isFalse()
+ }
+
+ private companion object {
+ val testScaffold: CatalogScaffoldContent = { _, title, _, _, _, _, _, content ->
+ Column(modifier = Modifier.fillMaxSize()) {
+ androidx.tv.material3.Text(title)
+ content()
+ }
+ }
+ }
+}
diff --git a/feature/catalog/src/main/java/com/streamvault/feature/catalog/presentation/components/CatalogCards.kt b/feature/catalog/src/main/java/com/streamvault/feature/catalog/presentation/components/CatalogCards.kt
index 9aa330b5..08eddc8a 100644
--- a/feature/catalog/src/main/java/com/streamvault/feature/catalog/presentation/components/CatalogCards.kt
+++ b/feature/catalog/src/main/java/com/streamvault/feature/catalog/presentation/components/CatalogCards.kt
@@ -1,6 +1,7 @@
package com.streamvault.feature.catalog.presentation.components
import androidx.compose.animation.core.animateFloatAsState
+import androidx.compose.animation.core.snap
import androidx.compose.animation.core.tween
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
@@ -52,6 +53,7 @@ import coil3.compose.AsyncImage
import com.streamvault.feature.catalog.R
import com.streamvault.core.ui.image.rememberCrossfadeImageModel
import com.streamvault.core.ui.image.ChannelLogoBadge
+import com.streamvault.core.ui.accessibility.rememberReducedMotionEnabled
import com.streamvault.feature.catalog.presentation.components.MoviePosterCard
import com.streamvault.feature.catalog.presentation.components.SeriesPosterCard
import com.streamvault.core.ui.components.shell.StatusPill
@@ -92,6 +94,7 @@ fun FocusableCard(
var isFocused by remember { mutableStateOf(false) }
val sounds = rememberTvInteractionSounds()
val focusRequester = remember { androidx.compose.ui.focus.FocusRequester() }
+ val reducedMotionEnabled = rememberReducedMotionEnabled()
val scale by animateFloatAsState(
targetValue = if (isFocused) {
@@ -99,7 +102,7 @@ fun FocusableCard(
} else {
if (isDragging) FocusSpec.FocusedScale else 1f
},
- animationSpec = tween(durationMillis = 160),
+ animationSpec = if (reducedMotionEnabled) snap() else tween(durationMillis = 160),
label = "cardScale"
)
diff --git a/feature/catalog/src/main/java/com/streamvault/feature/catalog/presentation/components/CatalogEpisodeRowCard.kt b/feature/catalog/src/main/java/com/streamvault/feature/catalog/presentation/components/CatalogEpisodeRowCard.kt
index ee6630f3..de98fda8 100644
--- a/feature/catalog/src/main/java/com/streamvault/feature/catalog/presentation/components/CatalogEpisodeRowCard.kt
+++ b/feature/catalog/src/main/java/com/streamvault/feature/catalog/presentation/components/CatalogEpisodeRowCard.kt
@@ -1,6 +1,7 @@
package com.streamvault.feature.catalog.presentation.components
import androidx.compose.animation.core.animateFloatAsState
+import androidx.compose.animation.core.snap
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
@@ -53,6 +54,7 @@ import androidx.tv.material3.Text
import coil3.compose.AsyncImage
import com.streamvault.feature.catalog.R
import com.streamvault.core.ui.image.ChannelLogoBadge
+import com.streamvault.core.ui.accessibility.rememberReducedMotionEnabled
import com.streamvault.feature.catalog.presentation.components.channelProgressFraction
import com.streamvault.core.ui.image.rememberCrossfadeImageModel
import com.streamvault.core.ui.design.AppColors
@@ -234,9 +236,10 @@ fun LiveChannelRowSurface(
append(catchUpLabel)
}
}
+ val reducedMotionEnabled = rememberReducedMotionEnabled()
val scale by animateFloatAsState(
targetValue = if (isDragging) FocusSpec.FocusedScale else 1f,
- animationSpec = AppMotion.FocusSpec,
+ animationSpec = if (reducedMotionEnabled) snap() else AppMotion.FocusSpec,
label = "liveRowScale"
)
diff --git a/feature/catalog/src/main/java/com/streamvault/feature/catalog/presentation/components/CatalogReorderTopBar.kt b/feature/catalog/src/main/java/com/streamvault/feature/catalog/presentation/components/CatalogReorderTopBar.kt
index a79c43d0..ea41a7fb 100644
--- a/feature/catalog/src/main/java/com/streamvault/feature/catalog/presentation/components/CatalogReorderTopBar.kt
+++ b/feature/catalog/src/main/java/com/streamvault/feature/catalog/presentation/components/CatalogReorderTopBar.kt
@@ -2,6 +2,8 @@
import androidx.compose.foundation.BorderStroke
import androidx.compose.animation.AnimatedVisibility
+import androidx.compose.animation.EnterTransition
+import androidx.compose.animation.ExitTransition
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.foundation.background
@@ -26,6 +28,7 @@ import com.streamvault.core.ui.theme.TextSecondary
import com.streamvault.core.ui.interaction.TvClickableSurface
import com.streamvault.core.ui.interaction.TvButton
import com.streamvault.core.ui.interaction.TvIconButton
+import com.streamvault.core.ui.accessibility.rememberReducedMotionEnabled
@Composable
fun ReorderTopBar(
@@ -36,10 +39,11 @@ fun ReorderTopBar(
subtitle: String? = null,
modifier: Modifier = Modifier
) {
+ val reducedMotionEnabled = rememberReducedMotionEnabled()
AnimatedVisibility(
visible = visible,
- enter = slideInVertically(initialOffsetY = { -it }),
- exit = slideOutVertically(targetOffsetY = { -it }),
+ enter = if (reducedMotionEnabled) EnterTransition.None else slideInVertically(initialOffsetY = { -it }),
+ exit = if (reducedMotionEnabled) ExitTransition.None else slideOutVertically(targetOffsetY = { -it }),
modifier = modifier
.fillMaxWidth()
.padding(bottom = 20.dp)
diff --git a/feature/catalog/src/main/java/com/streamvault/feature/catalog/presentation/favorites/FavoritesScreen.kt b/feature/catalog/src/main/java/com/streamvault/feature/catalog/presentation/favorites/FavoritesScreen.kt
index cb0115ac..006257c4 100644
--- a/feature/catalog/src/main/java/com/streamvault/feature/catalog/presentation/favorites/FavoritesScreen.kt
+++ b/feature/catalog/src/main/java/com/streamvault/feature/catalog/presentation/favorites/FavoritesScreen.kt
@@ -2,7 +2,10 @@ package com.streamvault.feature.catalog.presentation.favorites
import androidx.activity.compose.BackHandler
import androidx.compose.animation.AnimatedVisibility
+import androidx.compose.animation.EnterTransition
+import androidx.compose.animation.ExitTransition
import androidx.compose.animation.core.animateFloatAsState
+import androidx.compose.animation.core.snap
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInHorizontally
@@ -79,6 +82,7 @@ import kotlinx.coroutines.launch
import com.streamvault.core.ui.interaction.TvClickableSurface
import com.streamvault.core.ui.interaction.TvButton
import com.streamvault.core.ui.interaction.TvIconButton
+import com.streamvault.core.ui.accessibility.rememberReducedMotionEnabled
@Composable
fun FavoritesScreen(
@@ -94,6 +98,7 @@ fun FavoritesScreen(
val listState = rememberLazyListState()
val scope = rememberCoroutineScope()
val snackbarHostState = remember { SnackbarHostState() }
+ val reducedMotionEnabled = rememberReducedMotionEnabled()
val homeShelfGlobalTitle = stringResource(R.string.saved_preset_home_shelf_global_title)
val homeShelfGlobalSubtitle = stringResource(R.string.saved_preset_home_shelf_global_subtitle)
val providerScopedSections = remember(
@@ -603,7 +608,8 @@ fun FavoritesScreen(
onMoveUp = { viewModel.moveItem(-1) },
onMoveDown = { viewModel.moveItem(1) },
onConfirm = { viewModel.saveReorder() },
- onCancel = { viewModel.exitReorderMode() }
+ onCancel = viewModel::cancelReorderMode,
+ reducedMotionEnabled = reducedMotionEnabled
)
}
}
@@ -611,8 +617,8 @@ fun FavoritesScreen(
androidx.compose.animation.AnimatedVisibility(
visible = uiState.isReorderMode && activeReorderSection != null,
- enter = slideInHorizontally(initialOffsetX = { it }) + fadeIn(),
- exit = slideOutHorizontally(targetOffsetX = { it }) + fadeOut(),
+ enter = if (reducedMotionEnabled) EnterTransition.None else slideInHorizontally(initialOffsetX = { it }) + fadeIn(),
+ exit = if (reducedMotionEnabled) ExitTransition.None else slideOutHorizontally(targetOffsetX = { it }) + fadeOut(),
modifier = Modifier
.align(Alignment.TopEnd)
.padding(top = 24.dp)
@@ -685,7 +691,7 @@ fun FavoritesScreen(
}
if (uiState.isReorderMode) {
- BackHandler(onBack = viewModel::exitReorderMode)
+ BackHandler(onBack = viewModel::cancelReorderMode)
}
}
@@ -1035,9 +1041,14 @@ private fun FavoriteRow(
onMoveUp: () -> Unit,
onMoveDown: () -> Unit,
onConfirm: () -> Unit,
- onCancel: () -> Unit
+ onCancel: () -> Unit,
+ reducedMotionEnabled: Boolean
) {
- val scale by animateFloatAsState(if (isReorderingThis) 1.03f else 1f, label = "favoriteRowScale")
+ val scale by animateFloatAsState(
+ targetValue = if (isReorderingThis) 1.03f else 1f,
+ animationSpec = if (reducedMotionEnabled) snap() else androidx.compose.animation.core.spring(),
+ label = "favoriteRowScale"
+ )
TvClickableSurface(
onClick = onClick,
diff --git a/feature/catalog/src/main/java/com/streamvault/feature/catalog/presentation/favorites/FavoritesViewModel.kt b/feature/catalog/src/main/java/com/streamvault/feature/catalog/presentation/favorites/FavoritesViewModel.kt
index 3685ccbd..30b3679a 100644
--- a/feature/catalog/src/main/java/com/streamvault/feature/catalog/presentation/favorites/FavoritesViewModel.kt
+++ b/feature/catalog/src/main/java/com/streamvault/feature/catalog/presentation/favorites/FavoritesViewModel.kt
@@ -142,6 +142,7 @@ class FavoritesViewModel @Inject constructor(
private val _uiState = MutableStateFlow(FavoritesUiState())
val uiState: StateFlow<FavoritesUiState> = _uiState.asStateFlow()
+ private var reorderOriginalSections: List<FavoriteSectionUiModel>? = null
init {
val providerIdsFlow = providerRepository.getProviders()
@@ -336,6 +337,7 @@ class FavoritesViewModel @Inject constructor(
}
fun enterReorderMode(sectionKey: String, item: FavoriteUiModel) {
+ reorderOriginalSections = _uiState.value.sections
_uiState.update {
it.copy(
isReorderMode = true,
@@ -345,8 +347,21 @@ class FavoritesViewModel @Inject constructor(
}
}
+ fun cancelReorderMode() {
+ val originalSections = reorderOriginalSections
+ reorderOriginalSections = null
+ _uiState.update {
+ it.copy(
+ sections = originalSections ?: it.sections,
+ isReorderMode = false,
+ reorderSectionKey = null,
+ reorderItem = null
+ )
+ }
+ }
+
fun exitReorderMode() {
- _uiState.update { it.copy(isReorderMode = false, reorderSectionKey = null, reorderItem = null) }
+ cancelReorderMode()
}
fun selectFilter(filter: SavedLibraryFilter) {
@@ -569,7 +584,7 @@ class FavoritesViewModel @Inject constructor(
viewModelScope.launch {
when (val result = favoriteRepository.reorderFavorites(section.items.map { it.favorite })) {
- is Result.Success -> exitReorderMode()
+ is Result.Success -> completeReorderMode()
is Result.Error -> _uiState.update {
it.copy(userMessage = "Unable to save reorder: ${result.errorMessageOrNull() ?: "Unknown error"}")
}
@@ -578,6 +593,11 @@ class FavoritesViewModel @Inject constructor(
}
}
+ private fun completeReorderMode() {
+ reorderOriginalSections = null
+ _uiState.update { it.copy(isReorderMode = false, reorderSectionKey = null, reorderItem = null) }
+ }
+
private fun observeFavoriteItems(favoritesFlow: Flow<List<Favorite>>): Flow<List<FavoriteUiModel>> {
return favoritesFlow.flatMapLatest { favorites ->
val orderedFavorites = favorites.sortedBy { it.position }
diff --git a/feature/catalog/src/main/java/com/streamvault/feature/catalog/presentation/movies/MovieDetailScreen.kt b/feature/catalog/src/main/java/com/streamvault/feature/catalog/presentation/movies/MovieDetailScreen.kt
index 376c4738..5e9cbe8f 100644
--- a/feature/catalog/src/main/java/com/streamvault/feature/catalog/presentation/movies/MovieDetailScreen.kt
+++ b/feature/catalog/src/main/java/com/streamvault/feature/catalog/presentation/movies/MovieDetailScreen.kt
@@ -570,12 +570,12 @@ private fun MovieVersionSelector(
}
}
-private fun copyStreamUrlToClipboard(context: android.content.Context, url: String?) {
+internal fun copyStreamUrlToClipboard(context: android.content.Context, url: String?) {
if (url.isNullOrBlank()) {
Toast.makeText(context, context.getString(R.string.stream_url_copy_failed), Toast.LENGTH_SHORT).show()
return
}
- context.getSystemService(ClipboardManager::class.java)
+ (context.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager)
?.setPrimaryClip(ClipData.newPlainText(context.getString(R.string.stream_url_clip_label), url))
Toast.makeText(context, context.getString(R.string.stream_url_copied), Toast.LENGTH_SHORT).show()
}
diff --git a/feature/catalog/src/main/java/com/streamvault/feature/catalog/presentation/movies/MoviesScreen.kt b/feature/catalog/src/main/java/com/streamvault/feature/catalog/presentation/movies/MoviesScreen.kt
index c74db8e0..bb3f1fc4 100644
--- a/feature/catalog/src/main/java/com/streamvault/feature/catalog/presentation/movies/MoviesScreen.kt
+++ b/feature/catalog/src/main/java/com/streamvault/feature/catalog/presentation/movies/MoviesScreen.kt
@@ -34,6 +34,7 @@ import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.input.key.onKeyEvent
import androidx.compose.ui.input.key.onPreviewKeyEvent
+import androidx.compose.ui.input.key.type
import com.streamvault.core.ui.components.SearchInput
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalConfiguration
@@ -88,7 +89,10 @@ import com.streamvault.domain.model.VodViewMode
import com.streamvault.feature.catalog.presentation.vod.HandleVodUserMessage
import com.streamvault.feature.catalog.presentation.vod.ProtectedVodPinDialog
import com.streamvault.feature.catalog.presentation.vod.VodBrowseDefaults
+import com.streamvault.feature.catalog.presentation.vod.VodReorderMoveDirection
+import com.streamvault.feature.catalog.presentation.vod.shouldShowVodPreview
import com.streamvault.feature.catalog.presentation.vod.vodActiveFilterSortDetail
+import com.streamvault.feature.catalog.presentation.vod.vodReorderMoveDirection
import kotlinx.coroutines.delay
@OptIn(ExperimentalFoundationApi::class)
@@ -252,6 +256,8 @@ fun MoviesScreen(
onLoadMore = viewModel::loadMoreSelectedCategory,
onLoadMorePreviewRows = viewModel::loadMorePreviewRows,
onDismissReorder = viewModel::exitCategoryReorderMode,
+ onMoveReorderItemUp = viewModel::moveItemUp,
+ onMoveReorderItemDown = viewModel::moveItemDown,
onToggleCategoryPinned = viewModel::toggleCategoryPinned,
initialFocusRequester = initialContentFocusRequester
)
@@ -353,6 +359,8 @@ private fun MoviesVodContent(
onLoadMore: () -> Unit,
onLoadMorePreviewRows: () -> Unit,
onDismissReorder: () -> Unit,
+ onMoveReorderItemUp: (Movie) -> Unit,
+ onMoveReorderItemDown: (Movie) -> Unit,
onToggleCategoryPinned: (Category) -> Unit,
initialFocusRequester: FocusRequester
) {
@@ -504,12 +512,14 @@ private fun MoviesVodContent(
onOpenFresh = onOpenFresh,
onLoadMore = onLoadMore,
onDismissReorder = onDismissReorder,
+ onMoveReorderItemUp = onMoveReorderItemUp,
+ onMoveReorderItemDown = onMoveReorderItemDown,
initialFocusRequester = initialFocusRequester
)
return
}
- if (uiState.selectedCategory == null) {
+ if (shouldShowVodPreview(uiState.selectedCategory, uiState.isReorderMode)) {
val previewListState = androidx.compose.foundation.lazy.rememberLazyListState()
InfiniteScrollEffect(
listState = previewListState,
@@ -928,6 +938,27 @@ private fun MoviesVodContent(
modifier = Modifier
.fillMaxWidth()
.aspectRatio(2f / 3f)
+ .then(
+ if (isDraggingThis) {
+ Modifier.onKeyEvent { event ->
+ if (event.type != androidx.compose.ui.input.key.KeyEventType.KeyDown) {
+ false
+ } else {
+ when (vodReorderMoveDirection(event.nativeKeyEvent.keyCode)) {
+ VodReorderMoveDirection.EARLIER -> {
+ onMoveReorderItemUp(movie)
+ true
+ }
+ VodReorderMoveDirection.LATER -> {
+ onMoveReorderItemDown(movie)
+ true
+ }
+ null -> false
+ }
+ }
+ }
+ } else Modifier
+ )
.then(if (!showSearchBar && movie.id == initialGridMovieId) Modifier.focusRequester(initialFocusRequester) else Modifier),
onClick = {
if (uiState.isReorderMode) {
@@ -982,6 +1013,8 @@ private fun MoviesVodClassicContent(
onOpenFresh: () -> Unit,
onLoadMore: () -> Unit,
onDismissReorder: () -> Unit,
+ onMoveReorderItemUp: (Movie) -> Unit,
+ onMoveReorderItemDown: (Movie) -> Unit,
initialFocusRequester: FocusRequester
) {
val allLabel = stringResource(R.string.vod_classic_all)
@@ -1286,10 +1319,31 @@ private fun MoviesVodClassicContent(
isLocked = isLocked,
isReorderMode = uiState.isReorderMode,
isDragging = isDraggingThis,
- modifier = Modifier
- .fillMaxWidth()
- .aspectRatio(2f / 3f)
- .then(if (!showSearchBar && movie.id == initialGridMovieId) Modifier.focusRequester(initialFocusRequester) else Modifier),
+ modifier = Modifier
+ .fillMaxWidth()
+ .aspectRatio(2f / 3f)
+ .then(
+ if (isDraggingThis) {
+ Modifier.onKeyEvent { event ->
+ if (event.type != androidx.compose.ui.input.key.KeyEventType.KeyDown) {
+ false
+ } else {
+ when (vodReorderMoveDirection(event.nativeKeyEvent.keyCode)) {
+ VodReorderMoveDirection.EARLIER -> {
+ onMoveReorderItemUp(movie)
+ true
+ }
+ VodReorderMoveDirection.LATER -> {
+ onMoveReorderItemDown(movie)
+ true
+ }
+ null -> false
+ }
+ }
+ }
+ } else Modifier
+ )
+ .then(if (!showSearchBar && movie.id == initialGridMovieId) Modifier.focusRequester(initialFocusRequester) else Modifier),
onClick = {
if (uiState.isReorderMode) {
draggingMovie = if (isDraggingThis) null else movie
diff --git a/feature/catalog/src/main/java/com/streamvault/feature/catalog/presentation/series/SeriesScreen.kt b/feature/catalog/src/main/java/com/streamvault/feature/catalog/presentation/series/SeriesScreen.kt
index c1d84d53..e1228a50 100644
--- a/feature/catalog/src/main/java/com/streamvault/feature/catalog/presentation/series/SeriesScreen.kt
+++ b/feature/catalog/src/main/java/com/streamvault/feature/catalog/presentation/series/SeriesScreen.kt
@@ -36,6 +36,7 @@ import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.input.key.onKeyEvent
import androidx.compose.ui.input.key.onPreviewKeyEvent
+import androidx.compose.ui.input.key.type
import com.streamvault.core.ui.components.SearchInput
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalConfiguration
@@ -88,7 +89,10 @@ import com.streamvault.domain.model.VodViewMode
import com.streamvault.feature.catalog.presentation.vod.HandleVodUserMessage
import com.streamvault.feature.catalog.presentation.vod.ProtectedVodPinDialog
import com.streamvault.feature.catalog.presentation.vod.VodBrowseDefaults
+import com.streamvault.feature.catalog.presentation.vod.VodReorderMoveDirection
+import com.streamvault.feature.catalog.presentation.vod.shouldShowVodPreview
import com.streamvault.feature.catalog.presentation.vod.vodActiveFilterSortDetail
+import com.streamvault.feature.catalog.presentation.vod.vodReorderMoveDirection
import kotlinx.coroutines.delay
@OptIn(ExperimentalFoundationApi::class)
@@ -252,6 +256,8 @@ fun SeriesScreen(
onLoadMore = viewModel::loadMoreSelectedCategory,
onLoadMorePreviewRows = viewModel::loadMorePreviewRows,
onDismissReorder = viewModel::exitCategoryReorderMode,
+ onMoveReorderItemUp = viewModel::moveItemUp,
+ onMoveReorderItemDown = viewModel::moveItemDown,
onToggleCategoryPinned = viewModel::toggleCategoryPinned,
initialFocusRequester = initialContentFocusRequester
)
@@ -351,6 +357,8 @@ private fun SeriesVodContent(
onLoadMore: () -> Unit,
onLoadMorePreviewRows: () -> Unit,
onDismissReorder: () -> Unit,
+ onMoveReorderItemUp: (Series) -> Unit,
+ onMoveReorderItemDown: (Series) -> Unit,
onToggleCategoryPinned: (Category) -> Unit,
initialFocusRequester: FocusRequester
) {
@@ -504,12 +512,14 @@ private fun SeriesVodContent(
onOpenFresh = onOpenFresh,
onLoadMore = onLoadMore,
onDismissReorder = onDismissReorder,
+ onMoveReorderItemUp = onMoveReorderItemUp,
+ onMoveReorderItemDown = onMoveReorderItemDown,
initialFocusRequester = initialFocusRequester
)
return
}
- if (uiState.selectedCategory == null) {
+ if (shouldShowVodPreview(uiState.selectedCategory, uiState.isReorderMode)) {
val previewListState = androidx.compose.foundation.lazy.rememberLazyListState()
InfiniteScrollEffect(
listState = previewListState,
@@ -934,6 +944,27 @@ private fun SeriesVodContent(
modifier = Modifier
.fillMaxWidth()
.aspectRatio(2f / 3f)
+ .then(
+ if (isDraggingThis) {
+ Modifier.onKeyEvent { event ->
+ if (event.type != androidx.compose.ui.input.key.KeyEventType.KeyDown) {
+ false
+ } else {
+ when (vodReorderMoveDirection(event.nativeKeyEvent.keyCode)) {
+ VodReorderMoveDirection.EARLIER -> {
+ onMoveReorderItemUp(series)
+ true
+ }
+ VodReorderMoveDirection.LATER -> {
+ onMoveReorderItemDown(series)
+ true
+ }
+ null -> false
+ }
+ }
+ }
+ } else Modifier
+ )
.then(if (!showSearchBar && series.id == initialGridSeriesId) Modifier.focusRequester(initialFocusRequester) else Modifier),
onClick = {
if (uiState.isReorderMode) {
@@ -989,6 +1020,8 @@ private fun SeriesVodClassicContent(
onOpenFresh: () -> Unit,
onLoadMore: () -> Unit,
onDismissReorder: () -> Unit,
+ onMoveReorderItemUp: (Series) -> Unit,
+ onMoveReorderItemDown: (Series) -> Unit,
initialFocusRequester: FocusRequester
) {
val allLabel = stringResource(R.string.vod_classic_all)
@@ -1293,10 +1326,31 @@ private fun SeriesVodClassicContent(
isLocked = isLocked,
isReorderMode = uiState.isReorderMode,
isDragging = isDraggingThis,
- modifier = Modifier
- .fillMaxWidth()
- .aspectRatio(2f / 3f)
- .then(if (!showSearchBar && series.id == initialGridSeriesId) Modifier.focusRequester(initialFocusRequester) else Modifier),
+ modifier = Modifier
+ .fillMaxWidth()
+ .aspectRatio(2f / 3f)
+ .then(
+ if (isDraggingThis) {
+ Modifier.onKeyEvent { event ->
+ if (event.type != androidx.compose.ui.input.key.KeyEventType.KeyDown) {
+ false
+ } else {
+ when (vodReorderMoveDirection(event.nativeKeyEvent.keyCode)) {
+ VodReorderMoveDirection.EARLIER -> {
+ onMoveReorderItemUp(series)
+ true
+ }
+ VodReorderMoveDirection.LATER -> {
+ onMoveReorderItemDown(series)
+ true
+ }
+ null -> false
+ }
+ }
+ }
+ } else Modifier
+ )
+ .then(if (!showSearchBar && series.id == initialGridSeriesId) Modifier.focusRequester(initialFocusRequester) else Modifier),
onClick = {
if (uiState.isReorderMode) {
draggingSeries = if (isDraggingThis) null else series
diff --git a/feature/catalog/src/main/java/com/streamvault/feature/catalog/presentation/vod/VodBrowseStateHelpers.kt b/feature/catalog/src/main/java/com/streamvault/feature/catalog/presentation/vod/VodBrowseStateHelpers.kt
index f2f6697d..a25fcd99 100644
--- a/feature/catalog/src/main/java/com/streamvault/feature/catalog/presentation/vod/VodBrowseStateHelpers.kt
+++ b/feature/catalog/src/main/java/com/streamvault/feature/catalog/presentation/vod/VodBrowseStateHelpers.kt
@@ -38,6 +38,27 @@ fun incrementVodSelectedCategoryLoadLimit(
selectedCategoryLoadLimit.update { it + VodBrowseDefaults.SELECTED_CATEGORY_PAGE_SIZE }
}
+/**
+ * Modern VOD preview shelves are the browse surface only when no category is
+ * selected. Reorder mode is a distinct grid surface even when it was entered
+ * from the preview's category picker.
+ */
+fun shouldShowVodPreview(selectedCategory: String?, isReorderMode: Boolean): Boolean =
+ selectedCategory == null && !isReorderMode
+
+enum class VodReorderMoveDirection {
+ EARLIER,
+ LATER
+}
+
+fun vodReorderMoveDirection(keyCode: Int): VodReorderMoveDirection? = when (keyCode) {
+ android.view.KeyEvent.KEYCODE_DPAD_UP,
+ android.view.KeyEvent.KEYCODE_DPAD_LEFT -> VodReorderMoveDirection.EARLIER
+ android.view.KeyEvent.KEYCODE_DPAD_DOWN,
+ android.view.KeyEvent.KEYCODE_DPAD_RIGHT -> VodReorderMoveDirection.LATER
+ else -> null
+}
+
inline fun <State> setVodSearchQuery(
query: String,
searchQuery: MutableStateFlow<String>,
diff --git a/feature/catalog/src/main/java/com/streamvault/feature/catalog/presentation/vod/VodCatalogBuilders.kt b/feature/catalog/src/main/java/com/streamvault/feature/catalog/presentation/vod/VodCatalogBuilders.kt
index 7542ea36..78b72037 100644
--- a/feature/catalog/src/main/java/com/streamvault/feature/catalog/presentation/vod/VodCatalogBuilders.kt
+++ b/feature/catalog/src/main/java/com/streamvault/feature/catalog/presentation/vod/VodCatalogBuilders.kt
@@ -39,7 +39,9 @@ suspend fun <Item> buildVodPreviewCatalog(
.map(Favorite::contentId)
.toList()
if (favoritesIds.isNotEmpty()) {
- val preview = loadItemsByIds(favoritesIds.take(VodBrowseDefaults.PREVIEW_ROW_LIMIT))
+ val previewIds = favoritesIds.take(VodBrowseDefaults.PREVIEW_ROW_LIMIT)
+ val preview = loadItemsByIds(previewIds)
+ .orderByRequestedIds(previewIds, itemIds)
.filterNot { item -> itemCategoryId(item) in hiddenProviderCategoryIds }
.let { items -> markVodFavorites(items, globalFavoriteIds, itemIds, copyWithFavorite) }
if (preview.isNotEmpty()) {
@@ -104,6 +106,16 @@ suspend fun <Item> buildVodPreviewCatalog(
)
}
+private fun <Item> List<Item>.orderByRequestedIds(
+ requestedIds: List<Long>,
+ itemIds: (Item) -> List<Long>
+): List<Item> {
+ val positions = requestedIds.withIndex().associate { it.value to it.index }
+ return sortedBy { item ->
+ itemIds(item).mapNotNull(positions::get).minOrNull() ?: Int.MAX_VALUE
+ }
+}
+
fun <Item> buildVodSearchCatalog(
items: List<Item>,
allFavorites: List<Favorite>,
diff --git a/feature/catalog/src/test/java/com/streamvault/feature/catalog/presentation/favorites/FavoritesViewModelTest.kt b/feature/catalog/src/test/java/com/streamvault/feature/catalog/presentation/favorites/FavoritesViewModelTest.kt
index 17e76478..0f43a54f 100644
--- a/feature/catalog/src/test/java/com/streamvault/feature/catalog/presentation/favorites/FavoritesViewModelTest.kt
+++ b/feature/catalog/src/test/java/com/streamvault/feature/catalog/presentation/favorites/FavoritesViewModelTest.kt
@@ -3,6 +3,12 @@ package com.streamvault.feature.catalog.presentation.favorites
import android.content.Context
import com.google.common.truth.Truth.assertThat
import com.streamvault.data.preferences.PreferencesRepository
+import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.Favorite
+import com.streamvault.domain.model.LegacyProvider
+import com.streamvault.domain.model.Movie
+import com.streamvault.domain.model.ProviderType
+import com.streamvault.domain.model.Result
import com.streamvault.domain.repository.ChannelRepository
import com.streamvault.domain.repository.FavoriteRepository
import com.streamvault.domain.repository.MovieRepository
@@ -10,19 +16,25 @@ import com.streamvault.domain.repository.PlaybackHistoryRepository
import com.streamvault.domain.repository.ProviderRepository
import com.streamvault.domain.repository.SeriesRepository
import com.streamvault.feature.catalog.presentation.CatalogMainDispatcherRule
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.flowOf
+import kotlinx.coroutines.test.advanceUntilIdle
+import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.kotlin.any
import org.mockito.kotlin.anyOrNull
+import org.mockito.kotlin.never
import org.mockito.kotlin.mock
+import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
-import org.robolectric.RuntimeEnvironment
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
+@OptIn(ExperimentalCoroutinesApi::class)
class FavoritesViewModelTest {
@get:Rule
@@ -36,22 +48,31 @@ class FavoritesViewModelTest {
private val providerRepository: ProviderRepository = mock()
private val preferencesRepository: PreferencesRepository = mock()
private val getContinueWatching: com.streamvault.domain.usecase.GetContinueWatching = mock()
+ private val providers = MutableStateFlow<List<LegacyProvider>>(emptyList())
+ private val activeProvider = MutableStateFlow<LegacyProvider?>(null)
+ private val favorites = MutableStateFlow<List<Favorite>>(emptyList())
+ private val appContext: Context = mock()
private lateinit var viewModel: FavoritesViewModel
@Before
fun setUp() {
- whenever(providerRepository.getProviders()).thenReturn(flowOf(emptyList()))
- whenever(providerRepository.getActiveProvider()).thenReturn(flowOf(null))
- whenever(favoriteRepository.getFavorites(any<List<Long>>(), anyOrNull())).thenReturn(flowOf(emptyList()))
+ whenever(providerRepository.getProviders()).thenReturn(providers)
+ whenever(providerRepository.getActiveProvider()).thenReturn(activeProvider)
+ whenever(favoriteRepository.getFavorites(any<List<Long>>(), anyOrNull())).thenReturn(favorites)
whenever(favoriteRepository.getGroups(any<List<Long>>(), any())).thenReturn(flowOf(emptyList()))
whenever(favoriteRepository.getGroupFavoriteCounts(any<List<Long>>(), any()))
.thenReturn(flowOf(emptyMap()))
whenever(preferencesRepository.promotedLiveGroupIds).thenReturn(flowOf(emptySet()))
whenever(playbackHistoryRepository.getRecentlyWatched(any())).thenReturn(flowOf(emptyList()))
+ whenever(playbackHistoryRepository.getRecentlyWatchedByProvider(any(), any())).thenReturn(flowOf(emptyList()))
+ whenever(getContinueWatching.invoke(any<Set<Long>>(), any(), any(), any()))
+ .thenReturn(flowOf(com.streamvault.domain.usecase.ContinueWatchingResult.Items(emptyList())))
+ whenever(appContext.getString(any())).thenAnswer { "resource-${it.arguments[0]}" }
+ whenever(appContext.getString(any(), any())).thenAnswer { "resource-${it.arguments[0]}" }
viewModel = FavoritesViewModel(
- appContext = RuntimeEnvironment.getApplication() as Context,
+ appContext = appContext,
favoriteRepository = favoriteRepository,
channelRepository = channelRepository,
movieRepository = movieRepository,
@@ -80,4 +101,124 @@ class FavoritesViewModelTest {
.isEqualTo(SavedLibraryProviderScope.ALL_PROVIDERS)
assertThat(viewModel.uiState.value.selectedSort).isEqualTo(SavedLibrarySort.TITLE)
}
+
+ @Test
+ fun `canceling reorder restores the original order without persisting the preview`() = runTest {
+ val provider = LegacyProvider(
+ id = 7L,
+ name = "Fixture",
+ type = ProviderType.XTREAM_CODES,
+ serverUrl = "http://fixture.test"
+ )
+ val firstFavorite = Favorite(
+ id = 101L,
+ providerId = provider.id,
+ contentId = 1001L,
+ contentType = ContentType.MOVIE,
+ position = 0
+ )
+ val secondFavorite = firstFavorite.copy(
+ id = 102L,
+ contentId = 1002L,
+ position = 1
+ )
+ whenever(movieRepository.getMoviesByIds(any())).thenReturn(
+ flowOf(
+ listOf(
+ Movie(id = firstFavorite.contentId, name = "First", providerId = provider.id),
+ Movie(id = secondFavorite.contentId, name = "Second", providerId = provider.id)
+ )
+ )
+ )
+ whenever(favoriteRepository.reorderFavorites(any())).thenReturn(Result.success(Unit))
+
+ providers.value = listOf(provider)
+ activeProvider.value = provider
+ favorites.value = listOf(firstFavorite, secondFavorite)
+ viewModel = FavoritesViewModel(
+ appContext = appContext,
+ favoriteRepository = favoriteRepository,
+ channelRepository = channelRepository,
+ movieRepository = movieRepository,
+ seriesRepository = seriesRepository,
+ playbackHistoryRepository = playbackHistoryRepository,
+ providerRepository = providerRepository,
+ preferencesRepository = preferencesRepository,
+ getContinueWatching = getContinueWatching,
+ )
+ advanceUntilIdle()
+
+ val originalOrder = viewModel.uiState.value.sections.single().items.map { it.favorite.id }
+ val firstItem = viewModel.uiState.value.sections.single().items.first()
+ viewModel.enterReorderMode("global", firstItem)
+ viewModel.moveItem(1)
+ assertThat(viewModel.uiState.value.sections.single().items.map { it.favorite.id })
+ .containsExactly(102L, 101L)
+ .inOrder()
+
+ viewModel.cancelReorderMode()
+ advanceUntilIdle()
+
+ assertThat(viewModel.uiState.value.sections.single().items.map { it.favorite.id })
+ .containsExactlyElementsIn(originalOrder)
+ .inOrder()
+ assertThat(viewModel.uiState.value.isReorderMode).isFalse()
+ verify(favoriteRepository, never()).reorderFavorites(any())
+ }
+
+ @Test
+ fun `saving reorder sends the preview order and exits edit mode`() = runTest {
+ val provider = LegacyProvider(
+ id = 7L,
+ name = "Fixture",
+ type = ProviderType.XTREAM_CODES,
+ serverUrl = "http://fixture.test"
+ )
+ val firstFavorite = Favorite(
+ id = 101L,
+ providerId = provider.id,
+ contentId = 1001L,
+ contentType = ContentType.MOVIE,
+ position = 0
+ )
+ val secondFavorite = firstFavorite.copy(
+ id = 102L,
+ contentId = 1002L,
+ position = 1
+ )
+ whenever(movieRepository.getMoviesByIds(any())).thenReturn(
+ flowOf(
+ listOf(
+ Movie(id = firstFavorite.contentId, name = "First", providerId = provider.id),
+ Movie(id = secondFavorite.contentId, name = "Second", providerId = provider.id)
+ )
+ )
+ )
+ whenever(favoriteRepository.reorderFavorites(any())).thenReturn(Result.success(Unit))
+
+ providers.value = listOf(provider)
+ activeProvider.value = provider
+ favorites.value = listOf(firstFavorite, secondFavorite)
+ viewModel = FavoritesViewModel(
+ appContext = appContext,
+ favoriteRepository = favoriteRepository,
+ channelRepository = channelRepository,
+ movieRepository = movieRepository,
+ seriesRepository = seriesRepository,
+ playbackHistoryRepository = playbackHistoryRepository,
+ providerRepository = providerRepository,
+ preferencesRepository = preferencesRepository,
+ getContinueWatching = getContinueWatching,
+ )
+ advanceUntilIdle()
+
+ val firstItem = viewModel.uiState.value.sections.single().items.first()
+ viewModel.enterReorderMode("global", firstItem)
+ viewModel.moveItem(1)
+ viewModel.saveReorder()
+ advanceUntilIdle()
+
+ assertThat(viewModel.uiState.value.isReorderMode).isFalse()
+ verify(favoriteRepository).reorderFavorites(listOf(secondFavorite, firstFavorite))
+ }
}
diff --git a/feature/catalog/src/test/java/com/streamvault/feature/catalog/presentation/movies/MovieDetailClipboardTest.kt b/feature/catalog/src/test/java/com/streamvault/feature/catalog/presentation/movies/MovieDetailClipboardTest.kt
new file mode 100644
index 00000000..703446dd
--- /dev/null
+++ b/feature/catalog/src/test/java/com/streamvault/feature/catalog/presentation/movies/MovieDetailClipboardTest.kt
@@ -0,0 +1,31 @@
+package com.streamvault.feature.catalog.presentation.movies
+
+import android.content.ClipboardManager
+import android.content.Context
+import com.google.common.truth.Truth.assertThat
+import org.mockito.kotlin.any
+import org.mockito.kotlin.mock
+import org.mockito.kotlin.whenever
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.RuntimeEnvironment
+
+@RunWith(RobolectricTestRunner::class)
+class MovieDetailClipboardTest {
+
+ @Test
+ fun `copy URL writes the resolved stream URL to the primary clipboard`() {
+ val application = RuntimeEnvironment.getApplication()
+ val clipboard = application.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
+ val context: Context = mock()
+ whenever(context.getString(any())).thenReturn("Stream URL")
+ whenever(context.getSystemService(Context.CLIPBOARD_SERVICE)).thenReturn(clipboard)
+ val streamUrl = "https://fixture.test/movie/1001.m3u8"
+ copyStreamUrlToClipboard(context, streamUrl)
+
+ assertThat(clipboard).isNotNull()
+ assertThat(clipboard.primaryClip?.getItemAt(0)?.text?.toString())
+ .isEqualTo(streamUrl)
+ }
+}
diff --git a/feature/catalog/src/test/java/com/streamvault/feature/catalog/presentation/vod/CatalogVodHelpersTest.kt b/feature/catalog/src/test/java/com/streamvault/feature/catalog/presentation/vod/CatalogVodHelpersTest.kt
index a8699f94..67a6dd06 100644
--- a/feature/catalog/src/test/java/com/streamvault/feature/catalog/presentation/vod/CatalogVodHelpersTest.kt
+++ b/feature/catalog/src/test/java/com/streamvault/feature/catalog/presentation/vod/CatalogVodHelpersTest.kt
@@ -1,12 +1,37 @@
package com.streamvault.feature.catalog.presentation.vod
+import android.view.KeyEvent
import com.google.common.truth.Truth.assertThat
+import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.Favorite
import com.streamvault.domain.model.LibraryFilterType
import com.streamvault.domain.model.LibrarySortBy
+import com.streamvault.domain.model.Movie
import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.runBlocking
import org.junit.Test
class CatalogVodHelpersTest {
+ @Test
+ fun modernPreview_isHiddenWhileReorderingWithoutSelectedCategory() {
+ assertThat(shouldShowVodPreview(selectedCategory = null, isReorderMode = false)).isEqualTo(true)
+ assertThat(shouldShowVodPreview(selectedCategory = null, isReorderMode = true)).isEqualTo(false)
+ assertThat(shouldShowVodPreview(selectedCategory = "Favorites", isReorderMode = true)).isEqualTo(false)
+ }
+
+ @Test
+ fun reorderMoveDirection_treatsGridArrowsAsEarlierOrLater() {
+ assertThat(vodReorderMoveDirection(KeyEvent.KEYCODE_DPAD_UP))
+ .isEqualTo(VodReorderMoveDirection.EARLIER)
+ assertThat(vodReorderMoveDirection(KeyEvent.KEYCODE_DPAD_LEFT))
+ .isEqualTo(VodReorderMoveDirection.EARLIER)
+ assertThat(vodReorderMoveDirection(KeyEvent.KEYCODE_DPAD_DOWN))
+ .isEqualTo(VodReorderMoveDirection.LATER)
+ assertThat(vodReorderMoveDirection(KeyEvent.KEYCODE_DPAD_RIGHT))
+ .isEqualTo(VodReorderMoveDirection.LATER)
+ assertThat(vodReorderMoveDirection(KeyEvent.KEYCODE_BACK)).isNull()
+ }
+
@Test
fun reorderMovement_preservesIdentityAndNoOpEdges() {
val items = listOf("a", "b", "c")
@@ -58,4 +83,32 @@ class CatalogVodHelpersTest {
assertThat(matchesVodGroupMembership(null, 7L)).isFalse()
assertThat(matchesVodGroupMembership(7L, 8L)).isFalse()
}
+
+ @Test
+ fun previewFavorites_preservesFavoritePositionWhenLoaderReturnsDifferentOrder() = runBlocking {
+ val movieOne = Movie(id = 1L, name = "Movie One")
+ val movieTwo = Movie(id = 2L, name = "Movie Two")
+ val result = buildVodPreviewCatalog(
+ allFavorites = listOf(
+ Favorite(id = 1L, providerId = 1L, contentId = 1L, contentType = ContentType.MOVIE, position = 1024),
+ Favorite(id = 2L, providerId = 1L, contentId = 2L, contentType = ContentType.MOVIE, position = 0)
+ ),
+ customCategories = emptyList(),
+ providerCategories = emptyList(),
+ providerCategoryCounts = emptyMap(),
+ libraryCount = 2,
+ hiddenProviderCategoryIds = emptySet(),
+ loadItemsByIds = { listOf(movieOne, movieTwo) },
+ providerPreviews = emptyMap(),
+ itemIds = Movie::letId,
+ itemCategoryId = Movie::categoryId,
+ copyWithFavorite = { movie, isFavorite -> movie.copy(isFavorite = isFavorite) }
+ )
+
+ assertThat(result.grouped[VodBrowseDefaults.FAVORITES_CATEGORY].orEmpty().map(Movie::id))
+ .containsExactly(2L, 1L)
+ .inOrder()
+ }
}
+
+private fun Movie.letId(): List<Long> = listOf(id)
diff --git a/tools/catalog_connected_validation.py b/tools/catalog_connected_validation.py
index ce366633..b65ea0c7 100644
--- a/tools/catalog_connected_validation.py
+++ b/tools/catalog_connected_validation.py
@@ -114,6 +114,69 @@ def extract_ui_strings(dump: str) -> set[str]:
return values
+def download_card_is_completed(dump: str, title: str) -> bool:
+ """Return whether the title's clickable Downloads card shows completion and an output path."""
+
+ try:
+ root = ET.fromstring(dump)
+ except ET.ParseError as exc:
+ raise CatalogValidationError(f"UIAutomator returned invalid XML: {exc}") from exc
+
+ for card in root.iter("node"):
+ if card.attrib.get("clickable") != "true":
+ continue
+ values = {
+ value
+ for node in card.iter("node")
+ for value in (
+ (node.attrib.get("text") or "").strip(),
+ (node.attrib.get("content-desc") or "").strip(),
+ )
+ if value
+ }
+ if title not in values or "Completed" not in values:
+ continue
+ if any(value.startswith("/") and "Download" in value for value in values):
+ return True
+ return False
+
+
+def ordered_markers(dump: str, markers: Sequence[str]) -> list[str]:
+ """Return matching semantic markers in their top-to-bottom UI order."""
+
+ nodes = _parse_nodes(dump)
+ matches: list[tuple[int, int, str]] = []
+ for marker in markers:
+ matching_nodes = [
+ node
+ for node in nodes
+ if marker in {node.text, node.content_description}
+ and node.bounds is not None
+ ]
+ if matching_nodes:
+ left, top, _, _ = matching_nodes[0].bounds # type: ignore[misc]
+ matches.append((top, left, marker))
+ return [marker for _, _, marker in sorted(matches)]
+
+
+def ordered_reorder_markers(dump: str, markers: Sequence[str]) -> list[str]:
+ """Return reorder-card markers from left to right in the visible grid."""
+
+ nodes = _parse_nodes(dump)
+ matches: list[tuple[int, int, str]] = []
+ for marker in markers:
+ matching_nodes = [
+ node
+ for node in nodes
+ if marker in {node.text, node.content_description}
+ and node.bounds is not None
+ ]
+ if matching_nodes:
+ left, top, _, _ = matching_nodes[0].bounds # type: ignore[misc]
+ matches.append((left, top, marker))
+ return [marker for _, _, marker in sorted(matches)]
+
+
def assert_snapshot(
dump: str,
*,
@@ -240,6 +303,28 @@ class AdbClient:
f"Latest dump is in {self.output_directory}."
)
+ def wait_for_marker_order(
+ self,
+ label: str,
+ markers: Sequence[str],
+ expected: Sequence[str],
+ *,
+ timeout: float = DEFAULT_TIMEOUT_SECONDS,
+ ) -> str:
+ """Wait until visible markers have the expected top-to-bottom order."""
+
+ deadline = time.monotonic() + timeout
+ last_dump = ""
+ while time.monotonic() < deadline:
+ last_dump = self.snapshot(label)
+ if ordered_reorder_markers(last_dump, markers) == list(expected):
+ return last_dump
+ time.sleep(0.5)
+ raise CatalogValidationError(
+ f"Timed out waiting for {label}; expected order: {', '.join(expected)}. "
+ f"Latest dump is in {self.output_directory}."
+ )
+
def wait_for_any(
self,
label: str,
@@ -260,6 +345,25 @@ class AdbClient:
f"Latest dump is in {self.output_directory}."
)
+ def wait_for_download_completed(
+ self,
+ label: str,
+ title: str,
+ *,
+ timeout: float = DEFAULT_TIMEOUT_SECONDS,
+ ) -> str:
+ deadline = time.monotonic() + timeout
+ last_dump = ""
+ while time.monotonic() < deadline:
+ last_dump = self.snapshot(label)
+ if download_card_is_completed(last_dump, title):
+ return last_dump
+ time.sleep(0.5)
+ raise CatalogValidationError(
+ f"Timed out waiting for completed download card '{title}'. "
+ f"Latest dump is in {self.output_directory}."
+ )
+
def tap_marker(self, marker: str, *, timeout: float = DEFAULT_TIMEOUT_SECONDS) -> None:
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
@@ -357,6 +461,121 @@ class AdbClient:
self.key("KEYCODE_DPAD_RIGHT")
raise CatalogValidationError("Could not focus a matching detail action.")
+ def focus_and_long_press_marker(
+ self,
+ marker: str,
+ *,
+ timeout: float = DEFAULT_TIMEOUT_SECONDS,
+ ) -> None:
+ """Focus a visible TV surface and hold its activation key."""
+
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ dump = self.snapshot(f"focus_long_press_{_safe_name(marker)}")
+ if _focused_target_contains(dump, marker):
+ self.shell(
+ "input",
+ "keyevent",
+ "--duration",
+ "1400",
+ "KEYCODE_DPAD_CENTER",
+ )
+ return
+ self.key("KEYCODE_DPAD_DOWN")
+ raise CatalogValidationError(f"Could not focus marker '{marker}' for long press.")
+
+ def focus_and_activate_browse_action(
+ self,
+ marker: str,
+ *,
+ timeout: float = DEFAULT_TIMEOUT_SECONDS,
+ ) -> None:
+ """Focus and activate an action chip in the modern browse row."""
+
+ compiled = [re.compile(re.escape(marker), re.IGNORECASE)]
+ deadline = time.monotonic() + timeout
+ # The centered projection of the hero enters the action row at Top Rated
+ # on the TV emulator. Move left through the semantic row until the
+ # requested action is focused.
+ self.key("KEYCODE_DPAD_DOWN")
+ dump = self.snapshot(f"focus_browse_action_{_safe_name(marker)}")
+ focused_bounds = _focused_target_bounds(dump)
+ if focused_bounds and focused_bounds[2] - focused_bounds[0] > 1000:
+ # Direct navigation can leave focus on the top navigation item. In
+ # that state the first Down enters the hero and the second enters
+ # the action row.
+ self.key("KEYCODE_DPAD_DOWN")
+ dump = self.snapshot(f"focus_browse_action_{_safe_name(marker)}")
+ focused_bounds = _focused_target_bounds(dump)
+ horizontal_direction = (
+ "KEYCODE_DPAD_RIGHT"
+ if focused_bounds and focused_bounds[0] < 700
+ else "KEYCODE_DPAD_LEFT"
+ )
+ for _ in range(8):
+ if time.monotonic() >= deadline:
+ break
+ if _focused_target_matches(dump, compiled):
+ self.key("KEYCODE_DPAD_CENTER")
+ return
+ self.key(horizontal_direction)
+ dump = self.snapshot(f"focus_browse_action_{_safe_name(marker)}")
+ raise CatalogValidationError(f"Could not focus browse action '{marker}'.")
+
+ def focus_and_activate_reorder_card(
+ self,
+ marker: str,
+ *,
+ timeout: float = DEFAULT_TIMEOUT_SECONDS,
+ ) -> None:
+ """Focus and select a card in the reorder grid."""
+
+ compiled = [re.compile(re.escape(marker), re.IGNORECASE)]
+ deadline = time.monotonic() + timeout
+ # Reorder mode initially focuses the Home shell item. Down reaches the
+ # card aligned with that item; the neighboring card is one Left away.
+ directions = (
+ "KEYCODE_DPAD_DOWN",
+ "KEYCODE_DPAD_LEFT",
+ "KEYCODE_DPAD_RIGHT",
+ "KEYCODE_DPAD_DOWN",
+ "KEYCODE_DPAD_UP",
+ "KEYCODE_DPAD_LEFT",
+ "KEYCODE_DPAD_RIGHT",
+ )
+ for direction in directions:
+ if time.monotonic() >= deadline:
+ break
+ self.key(direction)
+ dump = self.snapshot(f"focus_reorder_card_{_safe_name(marker)}")
+ if _focused_target_matches(dump, compiled):
+ self.key("KEYCODE_DPAD_CENTER")
+ # The click callback updates the Compose selection state
+ # asynchronously; let that state reach the card before the
+ # movement key is sent by the journey.
+ time.sleep(0.4)
+ return
+ raise CatalogValidationError(f"Could not focus reorder card '{marker}'.")
+
+ def focus_and_activate_reorder_save(self, *, timeout: float = DEFAULT_TIMEOUT_SECONDS) -> None:
+ """Leave the selected card and activate the reorder dialog's save action."""
+
+ deadline = time.monotonic() + timeout
+ # Center clears the selected-card state. Up enters the footer rail on
+ # Cancel, then Right reaches Save Order.
+ self.key("KEYCODE_DPAD_CENTER")
+ time.sleep(0.4)
+ self.key("KEYCODE_DPAD_UP")
+ for _ in range(4):
+ if time.monotonic() >= deadline:
+ break
+ dump = self.snapshot("focus_reorder_save")
+ if _focused_target_contains(dump, "Save Order"):
+ self.key("KEYCODE_DPAD_CENTER")
+ return
+ self.key("KEYCODE_DPAD_RIGHT")
+ raise CatalogValidationError("Could not focus the reorder Save Order action.")
+
def focus_and_activate_dialog_action(
self,
patterns: Sequence[str],
@@ -530,6 +749,23 @@ def _focused_target_contains(dump: str, marker: str) -> bool:
return _focused_target_matches(dump, [re.compile(re.escape(marker), re.IGNORECASE)])
+def _focused_target_bounds(dump: str) -> tuple[int, int, int, int] | None:
+ try:
+ root = ET.fromstring(dump)
+ except ET.ParseError as exc:
+ raise CatalogValidationError(f"UIAutomator returned invalid XML: {exc}") from exc
+ parents = {child: parent for parent in root.iter() for child in parent}
+ focused = next((node for node in root.iter("node") if node.attrib.get("focused") == "true"), None)
+ if focused is None:
+ return None
+ target = focused
+ while target is not None and target.attrib.get("clickable") != "true":
+ target = parents.get(target)
+ if target is None:
+ return None
+ return parse_bounds(target.attrib.get("bounds") or "")
+
+
def _focused_target_matches(dump: str, patterns: Sequence[re.Pattern[str]]) -> bool:
try:
root = ET.fromstring(dump)
@@ -555,6 +791,347 @@ def _focused_target_matches(dump: str, patterns: Sequence[re.Pattern[str]]) -> b
)
+def selected_library_pagination_contract(content_type: str) -> dict[str, str]:
+ """Return the semantic markers for a selected-library pagination journey."""
+
+ contracts = {
+ "movies": {
+ "route": "movies",
+ "entry_marker": "Browse Full Movie Library",
+ "fixture_marker": "Fixture Movie One",
+ "loaded_marker": "Pagination Movie 63",
+ "page_marker": "Load more (60/63)",
+ },
+ "series": {
+ "route": "series",
+ "entry_marker": "Browse Full Series Library",
+ "fixture_marker": "Fixture Series One",
+ "loaded_marker": "Pagination Series 63",
+ "page_marker": "Load more (60/63)",
+ },
+ }
+ try:
+ return contracts[content_type]
+ except KeyError as exc:
+ raise CatalogValidationError(
+ f"Unknown selected-library pagination content type '{content_type}'."
+ ) from exc
+
+
+def browse_reorder_contract(content_type: str) -> dict[str, str]:
+ """Return the semantic markers for a browse reorder journey."""
+
+ contracts = {
+ "movies": {
+ "route": "movies",
+ "category_marker": "★ Favorites",
+ "options_marker": "Reorder Items",
+ "mode_marker": "Reordering ★ Favorites",
+ "first_marker": "Fixture Movie One",
+ "second_marker": "Fixture Movie Two",
+ },
+ "series": {
+ "route": "series",
+ "category_marker": "★ Favorites",
+ "options_marker": "Reorder Items",
+ "mode_marker": "Reordering ★ Favorites",
+ "first_marker": "Fixture Series One",
+ "second_marker": "Fixture Series Two",
+ },
+ }
+ try:
+ return contracts[content_type]
+ except KeyError as exc:
+ raise CatalogValidationError(
+ f"Unknown browse reorder content type '{content_type}'."
+ ) from exc
+
+
+def reorder_move_action(
+ current_order: Sequence[str],
+ target_order: Sequence[str],
+ first_marker: str,
+ second_marker: str,
+) -> tuple[str, str]:
+ """Return the card marker and D-pad direction needed to swap two cards."""
+
+ if len(current_order) != 2 or len(target_order) != 2:
+ raise ValueError("reorder validation expects exactly two visible cards")
+ if list(current_order) == list(target_order):
+ raise ValueError("reorder validation requires different current and target orders")
+ if list(current_order) != [first_marker, second_marker] and list(current_order) != [second_marker, first_marker]:
+ raise ValueError("reorder validation received unknown current markers")
+ if list(target_order) != list(reversed(current_order)):
+ raise ValueError("reorder validation expects the target order to be the reverse")
+
+ if list(current_order) == [first_marker, second_marker]:
+ return second_marker, "KEYCODE_DPAD_UP"
+ return second_marker, "KEYCODE_DPAD_DOWN"
+
+
+def run_selected_library_pagination(
+ client: AdbClient,
+ package: str,
+ activity: str,
+ content_type: str,
+ timeout: float,
+) -> list[str]:
+ """Prove the second page of one selected Catalog library."""
+
+ contract = selected_library_pagination_contract(content_type)
+ prefix = f"{content_type}_pagination"
+ client.navigate(contract["route"], package, activity)
+ client.wait_for(
+ f"{prefix}_route",
+ required=(
+ f"streamvault.destination:{contract['route']}",
+ contract["fixture_marker"],
+ ),
+ timeout=timeout,
+ )
+ client.focus_and_activate_browse_entry(contract["entry_marker"], timeout=timeout)
+ client.wait_for(
+ f"{prefix}_library",
+ required=("Filters & Sort", contract["fixture_marker"]),
+ timeout=timeout,
+ )
+ for _ in range(20):
+ client.shell("input", "swipe", "960", "900", "960", "250", "500")
+ client.wait_for(
+ f"{prefix}_ready",
+ required=(contract["page_marker"],),
+ timeout=timeout,
+ )
+ client.focus_and_activate_load_more(timeout=timeout)
+ for _ in range(4):
+ client.shell("input", "swipe", "960", "900", "960", "250", "500")
+ client.wait_for(
+ f"{prefix}_loaded",
+ required=(contract["loaded_marker"],),
+ forbidden=(contract["page_marker"],),
+ timeout=timeout,
+ )
+ return [
+ f"{prefix}_route",
+ f"{prefix}_library",
+ f"{prefix}_ready",
+ f"{prefix}_loaded",
+ ]
+
+
+def ensure_secondary_favorite(
+ client: AdbClient,
+ package: str,
+ activity: str,
+ content_type: str,
+ timeout: float,
+) -> list[str]:
+ """Ensure the second fixture item is favorited for a two-card reorder proof."""
+
+ contract = browse_reorder_contract(content_type)
+ category_marker = "Fixture Movies" if content_type == "movies" else "Fixture Series"
+ prefix = f"{content_type}_second_favorite"
+ # A detail Back can restore the Favorites grid as the selected surface.
+ # Recreate the activity through Home so the next route starts on the modern
+ # preview and exposes its Categories action consistently.
+ client.navigate("home", package, activity)
+ client.wait_for(
+ f"{prefix}_initial_home",
+ required=("streamvault.destination:home", "Fixture Movie One"),
+ timeout=timeout,
+ )
+ client.navigate(contract["route"], package, activity)
+ client.wait_for(
+ f"{prefix}_route",
+ required=(
+ f"streamvault.destination:{contract['route']}",
+ contract["first_marker"],
+ contract["second_marker"],
+ ),
+ timeout=timeout,
+ )
+ client.focus_and_activate_browse_action("Categories", timeout=timeout)
+ client.wait_for(
+ f"{prefix}_picker",
+ required=("Browse categories", category_marker),
+ timeout=timeout,
+ )
+ client.focus_and_activate_marker(category_marker, timeout=timeout)
+ client.wait_for(
+ f"{prefix}_category",
+ required=(
+ f"streamvault.destination:{contract['route']}",
+ contract["first_marker"],
+ contract["second_marker"],
+ ),
+ timeout=timeout,
+ )
+ client.focus_and_activate_browse_card(contract["second_marker"], timeout=timeout)
+ detail_required = (
+ (contract["second_marker"], "Copy URL")
+ if content_type == "movies"
+ else (contract["second_marker"], "Season 1")
+ )
+ client.wait_for(f"{prefix}_detail", required=detail_required, timeout=timeout)
+ _ensure_favorite(client, timeout=timeout)
+ client.key("KEYCODE_BACK")
+ client.wait_for(
+ f"{prefix}_after_detail",
+ required=(
+ f"streamvault.destination:{contract['route']}",
+ contract["second_marker"],
+ ),
+ timeout=timeout,
+ )
+ client.navigate("home", package, activity)
+ client.wait_for(
+ f"{prefix}_home",
+ required=("streamvault.destination:home", "Fixture Movie One"),
+ timeout=timeout,
+ )
+ return [
+ f"{prefix}_initial_home",
+ f"{prefix}_route",
+ f"{prefix}_picker",
+ f"{prefix}_category",
+ f"{prefix}_detail",
+ f"{prefix}_after_detail",
+ f"{prefix}_home",
+ ]
+
+
+def run_browse_reorder(
+ client: AdbClient,
+ package: str,
+ activity: str,
+ content_type: str,
+ timeout: float,
+) -> list[str]:
+ """Prove browse reorder changes, persists, and can be restored."""
+
+ contract = browse_reorder_contract(content_type)
+ prefix = f"{content_type}_browse_reorder"
+
+ def enter_reorder(stage: str) -> str:
+ client.navigate(contract["route"], package, activity)
+ client.wait_for(
+ f"{prefix}_{stage}_route",
+ required=(
+ f"streamvault.destination:{contract['route']}",
+ contract["first_marker"],
+ contract["second_marker"],
+ ),
+ timeout=timeout,
+ )
+ client.focus_and_activate_browse_action("Categories", timeout=timeout)
+ client.wait_for(
+ f"{prefix}_{stage}_picker",
+ required=("Browse categories", contract["category_marker"]),
+ timeout=timeout,
+ )
+ client.focus_and_long_press_marker(contract["category_marker"], timeout=timeout)
+ client.wait_for(
+ f"{prefix}_{stage}_options",
+ required=(contract["category_marker"], contract["options_marker"]),
+ timeout=timeout,
+ )
+ client.focus_and_activate_dialog_action((rf"^{re.escape(contract['options_marker'])}$",), timeout=timeout)
+ return client.wait_for(
+ f"{prefix}_{stage}_mode",
+ required=(
+ contract["mode_marker"],
+ contract["first_marker"],
+ contract["second_marker"],
+ ),
+ timeout=timeout,
+ )
+
+ mode_dump = enter_reorder("initial")
+ original_order = ordered_reorder_markers(
+ mode_dump,
+ (contract["first_marker"], contract["second_marker"]),
+ )
+ valid_orders = [
+ [contract["first_marker"], contract["second_marker"]],
+ [contract["second_marker"], contract["first_marker"]],
+ ]
+ if original_order not in valid_orders:
+ raise CatalogValidationError(
+ f"Unexpected {content_type} reorder order: {', '.join(original_order)}."
+ )
+
+ changed_order = valid_orders[1] if original_order == valid_orders[0] else valid_orders[0]
+ move_marker, move_direction = reorder_move_action(
+ original_order,
+ changed_order,
+ contract["first_marker"],
+ contract["second_marker"],
+ )
+ client.focus_and_activate_reorder_card(move_marker, timeout=timeout)
+ client.key(move_direction)
+ client.wait_for_marker_order(
+ f"{prefix}_changed",
+ (contract["first_marker"], contract["second_marker"]),
+ changed_order,
+ timeout=timeout,
+ )
+ client.focus_and_activate_reorder_save(timeout=timeout)
+ saved_dump = client.wait_for_marker_order(
+ f"{prefix}_saved",
+ (contract["first_marker"], contract["second_marker"]),
+ changed_order,
+ timeout=timeout,
+ )
+ if contract["mode_marker"] in extract_ui_strings(saved_dump):
+ raise CatalogValidationError(f"{content_type} reorder remained in edit mode after Save Order.")
+
+ persisted_dump = enter_reorder("persisted")
+ persisted_order = ordered_reorder_markers(
+ persisted_dump,
+ (contract["first_marker"], contract["second_marker"]),
+ )
+ if persisted_order != changed_order:
+ raise CatalogValidationError(
+ f"{content_type} reorder did not persist: expected {', '.join(changed_order)}, "
+ f"got {', '.join(persisted_order)}."
+ )
+
+ move_marker, move_direction = reorder_move_action(
+ changed_order,
+ original_order,
+ contract["first_marker"],
+ contract["second_marker"],
+ )
+ client.focus_and_activate_reorder_card(move_marker, timeout=timeout)
+ client.key(move_direction)
+ client.wait_for_marker_order(
+ f"{prefix}_restored",
+ (contract["first_marker"], contract["second_marker"]),
+ original_order,
+ timeout=timeout,
+ )
+ client.focus_and_activate_reorder_save(timeout=timeout)
+ restored_saved_dump = client.wait_for_marker_order(
+ f"{prefix}_restored_saved",
+ (contract["first_marker"], contract["second_marker"]),
+ original_order,
+ timeout=timeout,
+ )
+ if contract["mode_marker"] in extract_ui_strings(restored_saved_dump):
+ raise CatalogValidationError(f"{content_type} reorder remained in edit mode after restore Save Order.")
+ return [
+ f"{prefix}_initial_route",
+ f"{prefix}_initial_picker",
+ f"{prefix}_initial_options",
+ f"{prefix}_initial_mode",
+ f"{prefix}_changed",
+ f"{prefix}_saved",
+ f"{prefix}_persisted_mode",
+ f"{prefix}_restored",
+ f"{prefix}_restored_saved",
+ ]
+
+
def run_journey(client: AdbClient, package: str, activity: str, timeout: float) -> list[str]:
client.shell("am", "force-stop", package)
client.shell("am", "start", "-W", "-n", f"{package}/{activity}")
@@ -591,9 +1168,29 @@ def run_journey(client: AdbClient, package: str, activity: str, timeout: float)
client.shell("input", "swipe", "960", "250", "960", "900", "500")
client.focus_and_activate_browse_card("Fixture Movie One", timeout=timeout)
client.wait_for("movie_detail", required=("Fixture Movie One", "Play", "Copy URL", "Download", "Cast"), timeout=timeout)
+ client.focus_and_activate_matching((r"^Download$",), timeout=timeout)
_ensure_favorite(client, timeout=timeout)
client.key("KEYCODE_BACK")
client.wait_for("movies_after_detail", required=("streamvault.destination:movies", "Fixture Movie One"), timeout=timeout)
+ client.navigate("downloads", package, activity)
+ client.wait_for_download_completed(
+ "movie_download_completed",
+ "Fixture Movie One",
+ timeout=timeout,
+ )
+ movie_second_favorite_surfaces = ensure_secondary_favorite(
+ client,
+ package,
+ activity,
+ "movies",
+ timeout,
+ )
+ client.navigate("movies", package, activity)
+ client.wait_for(
+ "movies_before_saved",
+ required=("streamvault.destination:movies", "Fixture Movie One", "Fixture Movie Two"),
+ timeout=timeout,
+ )
client.tap_marker("Saved")
client.wait_for("movies_saved", required=("streamvault.destination:movies", "Fixture Movie One", "Saved"), timeout=timeout)
@@ -617,6 +1214,34 @@ def run_journey(client: AdbClient, package: str, activity: str, timeout: float)
client.key("KEYCODE_BACK")
client.wait_for("series_after_detail", required=("streamvault.destination:series", "Fixture Series One"), timeout=timeout)
+ series_second_favorite_surfaces = ensure_secondary_favorite(
+ client,
+ package,
+ activity,
+ "series",
+ timeout,
+ )
+ movie_browse_reorder_surfaces = run_browse_reorder(
+ client,
+ package,
+ activity,
+ "movies",
+ timeout,
+ )
+ client.navigate("home", package, activity)
+ client.wait_for(
+ "home_before_series_reorder",
+ required=("streamvault.destination:home", "Fixture Movie One"),
+ timeout=timeout,
+ )
+ series_browse_reorder_surfaces = run_browse_reorder(
+ client,
+ package,
+ activity,
+ "series",
+ timeout,
+ )
+
# Detail screens intentionally omit the shell; the preceding Back returns to Series browse
# before the normal top-navigation path is exercised here.
client.navigate("search", package, activity)
@@ -657,34 +1282,16 @@ def run_journey(client: AdbClient, package: str, activity: str, timeout: float)
)
client.open_settings_browsing(timeout=timeout)
client.set_infinite_scroll(False, timeout=timeout)
- client.navigate("movies", package, activity)
- client.wait_for(
- "movies_pagination_route",
- required=("streamvault.destination:movies", "Fixture Movie One"),
- timeout=timeout,
- )
- client.focus_and_activate_browse_entry(timeout=timeout)
- client.wait_for(
- "movies_pagination_library",
- required=("Filters & Sort", "Fixture Movie One"),
- timeout=timeout,
- )
- for _ in range(20):
- client.shell("input", "swipe", "960", "900", "960", "250", "500")
- client.wait_for(
- "movies_pagination_ready",
- required=("Load more (60/63)",),
- timeout=timeout,
- )
- client.focus_and_activate_load_more(timeout=timeout)
- for _ in range(4):
- client.shell("input", "swipe", "960", "900", "960", "250", "500")
+ run_selected_library_pagination(client, package, activity, "movies", timeout)
+ # Recreate the activity between deep selected-library grids so the Series
+ # route starts from a deterministic shell focus position.
+ client.navigate("home", package, activity)
client.wait_for(
- "movies_pagination_loaded",
- required=("Pagination Movie 63",),
- forbidden=("Load more (60/63)",),
+ "home_before_series_pagination",
+ required=("streamvault.destination:home", "Fixture Movie One"),
timeout=timeout,
)
+ run_selected_library_pagination(client, package, activity, "series", timeout)
# After appending the second page, focus can remain inside the deep grid
# and repeated DPAD_UP presses do not reliably reach the shell rail. Reset
# the top-level surface through the production activity entry point before
@@ -762,9 +1369,16 @@ def run_journey(client: AdbClient, package: str, activity: str, timeout: float)
"movies_full_library",
"movies_after_full_library",
"movie_detail",
+ "movie_download_completed",
+ "movies_before_saved",
+ *movie_second_favorite_surfaces,
"movies_saved",
"series_browse",
"series_detail",
+ *series_second_favorite_surfaces,
+ *movie_browse_reorder_surfaces,
+ "home_before_series_reorder",
+ *series_browse_reorder_surfaces,
"search_fixture",
"search_fixture_content",
"settings_route",
@@ -774,6 +1388,11 @@ def run_journey(client: AdbClient, package: str, activity: str, timeout: float)
"movies_pagination_library",
"movies_pagination_ready",
"movies_pagination_loaded",
+ "series_pagination_route",
+ "series_pagination_library",
+ "series_pagination_ready",
+ "series_pagination_loaded",
+ "home_before_series_pagination",
"home_after_pagination",
"settings_route_after_pagination",
"settings_route_before_customization",
diff --git a/tools/catalog_xtream_fixture.py b/tools/catalog_xtream_fixture.py
index 056bd399..189633c1 100644
--- a/tools/catalog_xtream_fixture.py
+++ b/tools/catalog_xtream_fixture.py
@@ -20,6 +20,7 @@ from urllib.parse import parse_qs, urlparse
DEFAULT_PORT = 8765
ASSET_BASE = f"http://10.0.2.2:{DEFAULT_PORT}/assets"
+MEDIA_BYTES = b"StreamVault Catalog fixture media bytes\n"
LIVE_CATEGORIES = [
{"category_id": "101", "category_name": "Fixture Live", "parent_id": 0, "is_adult": 0},
@@ -341,6 +342,17 @@ class Handler(BaseHTTPRequestHandler):
self.end_headers()
self.wfile.write(body)
return
+ if parsed.path.startswith(("/movie/", "/series/")):
+ path_parts = parsed.path.strip("/").split("/")
+ if len(path_parts) == 4 and path_parts[3].endswith(".mp4"):
+ self.log_message("media=%s", path_parts[0])
+ body = MEDIA_BYTES
+ self.send_response(200)
+ self.send_header("Content-Type", "video/mp4")
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+ return
if parsed.path.startswith("/assets/"):
label = parsed.path.rsplit("/", 1)[-1].replace(".svg", "").replace("-", " ").title()
body = (
diff --git a/tools/tests/test_catalog_connected_validation.py b/tools/tests/test_catalog_connected_validation.py
index 2db502b3..caa6e997 100644
--- a/tools/tests/test_catalog_connected_validation.py
+++ b/tools/tests/test_catalog_connected_validation.py
@@ -5,8 +5,13 @@ import unittest
from tools.catalog_connected_validation import (
_focused_target_matches,
assert_snapshot,
+ browse_reorder_contract,
+ download_card_is_completed,
extract_ui_strings,
parse_bounds,
+ reorder_move_action,
+ ordered_reorder_markers,
+ selected_library_pagination_contract,
)
@@ -33,6 +38,30 @@ class CatalogConnectedValidationTest(unittest.TestCase):
with self.assertRaisesRegex(AssertionError, "forbidden marker 'Sync needed'"):
assert_snapshot(dump, forbidden=("Sync needed",))
+ def test_download_completion_requires_title_status_and_output_path_in_one_card(self):
+ completed_dump = """<hierarchy>
+ <node text="Completed" />
+ <node clickable="true">
+ <node text="Fixture Movie One" />
+ <node text="/storage/emulated/0/Android/data/com.streamvault.app.debug/files/Download/StreamVault/Fixture Movie One.mp4" />
+ <node text="Completed" />
+ </node>
+ <node clickable="true">
+ <node text="Fixture Movie Two" />
+ <node text="/storage/emulated/0/Android/data/com.streamvault.app.debug/files/Download/StreamVault/Fixture Movie Two.mp4" />
+ </node>
+ </hierarchy>"""
+ incomplete_dump = """<hierarchy>
+ <node text="Completed" />
+ <node clickable="true">
+ <node text="Fixture Movie One" />
+ <node text="/storage/emulated/0/Android/data/com.streamvault.app.debug/files/Download/StreamVault/Fixture Movie One.mp4" />
+ </node>
+ </hierarchy>"""
+
+ self.assertTrue(download_card_is_completed(completed_dump, "Fixture Movie One"))
+ self.assertFalse(download_card_is_completed(incomplete_dump, "Fixture Movie One"))
+
def test_focused_target_matches_walks_to_clickable_parent(self):
dump = """<hierarchy>
<node text="" clickable="true" focused="false" bounds="[0,0][300,100]">
@@ -42,6 +71,70 @@ class CatalogConnectedValidationTest(unittest.TestCase):
self.assertTrue(_focused_target_matches(dump, [re.compile(r"^Save Order$")]))
+ def test_series_selected_library_pagination_contract_uses_series_markers(self):
+ self.assertEqual(
+ {
+ "route": "series",
+ "entry_marker": "Browse Full Series Library",
+ "fixture_marker": "Fixture Series One",
+ "loaded_marker": "Pagination Series 63",
+ "page_marker": "Load more (60/63)",
+ },
+ selected_library_pagination_contract("series"),
+ )
+
+ def test_browse_reorder_contract_uses_content_specific_markers(self):
+ self.assertEqual(
+ {
+ "route": "movies",
+ "category_marker": "★ Favorites",
+ "options_marker": "Reorder Items",
+ "mode_marker": "Reordering ★ Favorites",
+ "first_marker": "Fixture Movie One",
+ "second_marker": "Fixture Movie Two",
+ },
+ browse_reorder_contract("movies"),
+ )
+ self.assertEqual(
+ {
+ "route": "series",
+ "category_marker": "★ Favorites",
+ "options_marker": "Reorder Items",
+ "mode_marker": "Reordering ★ Favorites",
+ "first_marker": "Fixture Series One",
+ "second_marker": "Fixture Series Two",
+ },
+ browse_reorder_contract("series"),
+ )
+
+ def test_reorder_move_action_handles_either_persisted_order(self):
+ first = "Fixture Movie One"
+ second = "Fixture Movie Two"
+
+ self.assertEqual(
+ (second, "KEYCODE_DPAD_UP"),
+ reorder_move_action([first, second], [second, first], first, second),
+ )
+ self.assertEqual(
+ (second, "KEYCODE_DPAD_DOWN"),
+ reorder_move_action([second, first], [first, second], first, second),
+ )
+
+ def test_reorder_marker_order_uses_grid_columns_when_focus_bounds_differ(self):
+ dump = """<hierarchy>
+ <node content-desc="Fixture Movie Two" clickable="true" focused="true" bounds="[362,467][656,910]">
+ <node text="Fixture Movie Two" bounds="[391,852][596,880]" />
+ </node>
+ <node content-desc="Fixture Movie One" clickable="true" bounds="[68,480][346,897]">
+ <node text="Fixture Movie One" bounds="[96,843][289,869]" />
+ </node>
+ </hierarchy>"""
+
+ self.assertEqual(
+ ["Fixture Movie One", "Fixture Movie Two"],
+ ordered_reorder_markers(dump, ("Fixture Movie One", "Fixture Movie Two")),
+ )
+
if __name__ == "__main__":
unittest.main()
diff --git a/tools/tests/test_catalog_xtream_fixture.py b/tools/tests/test_catalog_xtream_fixture.py
index c8002fff..28a3b486 100644
--- a/tools/tests/test_catalog_xtream_fixture.py
+++ b/tools/tests/test_catalog_xtream_fixture.py
@@ -40,6 +40,22 @@ class CatalogXtreamFixtureTest(unittest.TestCase):
server.server_close()
thread.join(timeout=2)
+ def test_http_handler_serves_deterministic_movie_media(self):
+ server = FIXTURE.ThreadingHTTPServer(("127.0.0.1", 0), FIXTURE.Handler)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ try:
+ url = f"http://127.0.0.1:{server.server_address[1]}/movie/fixture/fixture/1001.mp4"
+ with urlopen(url, timeout=2) as response:
+ self.assertEqual(200, response.status)
+ self.assertEqual("video/mp4", response.headers["Content-Type"])
+ body = response.read()
+ self.assertEqual(FIXTURE.MEDIA_BYTES, body)
+ finally:
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=2)
+
if __name__ == "__main__":
unittest.main()
diff --git a/validation/phase5_catalog/task14-xtream-fixture-journeys.md b/validation/phase5_catalog/task14-xtream-fixture-journeys.md
index f43a9d83..d837944b 100644
--- a/validation/phase5_catalog/task14-xtream-fixture-journeys.md
+++ b/validation/phase5_catalog/task14-xtream-fixture-journeys.md
@@ -1,6 +1,6 @@
# Phase 5 Catalog - temporary Xtream fixture journeys
-Date: 2026-09-03
+Date: 2026-09-04
Target: `emulator-5554` (`Television_1080p(AVD) - 16`), API 36, AOSP TV on x86,
physical 1920x1080 at 320 dpi.
@@ -20,9 +20,11 @@ The fixture returns one live channel, 63 movies, 63 series, movie metadata,
and one season with two episodes per series. The first two movie/series items
remain stable fixture titles for detail and Search assertions; the remaining
items are generated in pagination categories so the selected-library flow can
-prove a second page. All observed player-API, XMLTV, and image requests
-returned HTTP 200. No credentials or raw provider URLs are included in this
-evidence.
+prove a second page. It also serves deterministic 40-byte MP4 fixture content
+for the provider movie/series transfer paths, allowing the production download
+service to reach `Completed`. All observed player-API, XMLTV, image, and
+download requests returned HTTP 200. No credentials or raw provider URLs are
+included in this evidence.
## Rerun protocol
@@ -47,20 +49,23 @@ It writes UIAutomator snapshots and `report.json` under the ignored
`build/catalog-validation` directory. The harness uses the production TV
focus/input path and does not mutate `local.properties`.
-## Harness result (2026-09-03)
+## Harness result (2026-09-04)
The command passed on `emulator-5554` (API 36 AOSP TV, 1920x1080) with
`com.streamvault.app.debug`. It proved these surfaces in one run: Home,
Movies browse and full-library entry/back, movie detail and favourite toggle,
-the Movies `Saved` filter, Series browse, series detail with Season 1 and both
+the movie Download action followed by the production Downloads card reaching
+`Completed` with a non-empty output path, the Movies `Saved` filter, Series browse, series detail with Season 1 and both
episodes, Search with the five grouped fixture results, Settings Browsing, and
the VOD pagination toggle. With Infinite scroll disabled, the selected Movies
library reached `Load more (60/63)`; semantic focus activated it and the next
-page rendered through `Pagination Movie 63` with the button gone. Infinite
-scroll was restored to enabled before the Dashboard customization checks.
-The report and UI dumps are local ignored artifacts under
-`build/catalog-validation-pagination-final-15`; no provider credentials or raw
-URLs are checked in.
+page rendered through `Pagination Movie 63` with the button gone. The same
+selected-library path then proved Series `Load more (60/63)` through
+`Pagination Series 63`, again with the load-more card gone. Infinite scroll was
+restored to enabled before the Dashboard customization checks. The latest
+report and UI dumps are local ignored artifacts under
+`build/catalog-validation-download-completion-retry`; no provider credentials
+or raw URLs are checked in.
The same run passed the Settings-owned Dashboard shelf customization dialog.
It opened the dialog through semantic Settings targets, removed a shelf and
@@ -81,12 +86,20 @@ mapping used by `10.0.2.2`.
| Movies browse | `streamvault.destination:movies`; two titles, one category, Top Rated/Newest shelves, and both movie cards rendered. |
| Movies full-library entry/back | Browse hero activated `Browse Full Movie Library`; the selected library rendered `Filters & Sort` and returned to the modern browse surface through Back. |
| Movies pagination | With Infinite scroll off, the selected library rendered `Load more (60/63)` after 20 swipes; activation appended the second page through `Pagination Movie 63` and removed the button. Infinite scroll was then restored on. |
+| Series pagination | With Infinite scroll off, the selected library rendered `Load more (60/63)` after 20 swipes; activation appended the second page through `Pagination Series 63` and removed the button. |
| Movie detail | `Fixture Movie One` rendered rating, release date, duration, genre, director, cast, plot, Play/Copy URL/Download/Cast/Trailer actions, and favourite toggle. |
+| Download completion | The movie Download action reached the production Downloads route; the `Fixture Movie One` card showed `Completed`, a non-empty output path under the app Downloads directory, and the fixture served the deterministic 40-byte body. |
| Movies saved filter | Movies `Saved` filter rendered exactly `Fixture Movie One` after the detail toggle. |
| Series browse | `streamvault.destination:series`; two titles, one category, and both series cards rendered. |
| Series detail | `Fixture Series One` rendered metadata, Season 1, and `Episodes (2)` with `Pilot` and `Second Signal`. |
| Series saved filter | Series `Saved` filter rendered exactly `Fixture Series One` after the detail toggle. |
+| Movies browse reorder | The Favorites reorder surface moved the two fixture movies, saved the changed order, re-entered to prove persistence, and restored the original order. |
+| Series browse reorder | The Favorites reorder surface moved the two fixture series, saved the changed order, re-entered to prove persistence, and restored the original order. |
| Search | `streamvault.destination:search`; query `Fixture` rendered `5 results` grouped as Live TV 1, Movies 2, and Series 2. The movie and series rows were confirmed after scrolling. |
+| Direct Favorites host | A focused API 36 TV instrumentation test hosted the real `FavoritesScreen` without adding a production route, rendered the Saved shell and reorder panel, and dispatched Activity Back through the registered `BackHandler` to cancel reorder. |
+| RTL and large text | `CatalogPresentationBehaviorTest` rendered Movie and Series cards under `LayoutDirection.Rtl` and a 1.5x font scale; merged content descriptions and click actions remained available, and the first RTL card was placed to the right of the second. |
+| Reduced motion | The full 7-test Catalog instrumentation suite passed on the same API 36 TV emulator with `settings global animator_duration_scale=0`; the setting was restored to `1` after the run. |
+| TalkBack service | The full 7-test Catalog instrumentation suite passed with the API 36 AOSP TalkBack service enabled and was rerun after restoring the service. The production fixture harness reached Catalog reorder, but its semantic D-pad path lost focus under TalkBack: one run timed out waiting for `Reorder Items`, and a warmed rerun timed out focusing `Fixture Movie One`. The app exposed `Reorder Items` in the captured accessibility tree and a manual D-pad long press opened it; the end-to-end TalkBack fixture journey therefore remains a harness limitation rather than a passing production audit. |
The D-pad path was used for route changes and detail activation; scrolling was
used only to expose lower search and episode rows. UIAutomator dumps captured
@@ -97,32 +110,39 @@ in because they contain no additional contract beyond the semantic dumps.
## Detail action probes
On the movie detail surface, D-pad activation reached Copy URL, Download, and
-Cast without a Catalog crash or lost focus. The Download probe started and
-stopped `DownloadForegroundService`; the fixture intentionally does not serve
-media-file transfer URLs, so a completed download is not claimed. The Cast
-probe had no receiver available on the emulator and did not produce a chooser;
+Cast without a Catalog crash or lost focus. Download reached the production
+Downloads screen and completed through the deterministic fixture media
+endpoint. The Cast probe had no receiver available on the emulator and did not produce a chooser;
receiver-backed Cast behavior remains open. Copy URL activation was dispatched
-but the API 36 shell does not expose a supported clipboard-read command for
-independent verification.
+and the helper is now independently verified by a focused Robolectric test
+that reads the primary `ClipboardManager` clip. The API 36 shell still does
+not expose a supported clipboard-read command for a second device-shell
+assertion.
## Interpretation and remaining gates
This run demonstrates that the extracted Catalog production activity can load
-seeded VOD/series data, navigate detail and season/episode surfaces, toggle
-movie and series favourites, apply saved filters, and search across all three
-content types. It narrows the previous Task 12 blocker: the checkout lacked a
-fixture capable of exercising these paths, not a Catalog UI path. The checked-
-in fixture now makes this diagnostic run rerunnable.
+seeded VOD/series data, navigate detail and season/episode surfaces, paginate
+both selected Movie and Series libraries, reorder and persist Movie and Series
+Favorites shelves, toggle movie and series favourites, apply saved filters,
+search across all three content types, and complete a fixture-backed movie
+download through the production Downloads screen. It narrows the
+previous Task 12 blocker: the checkout lacked a
+fixture capable of exercising these paths, not a Catalog UI path. The
+checked-in fixture now makes this diagnostic run rerunnable.
The run does not close the full Phase 5 acceptance gate. The public M3U flow
remains live-only, and the following journeys still need to be executed against
the checked-in fixture (or approved provider data):
-- browse reorder and the Series selected-library load-more path;
-- download completion and Cast receiver chooser;
-- direct Favorites host rendering and reorder/save/cancel;
-- touch-mode, phone/tablet, RTL, reduced-motion, and accessibility variants;
-- cache-equivalent before/after Dashboard performance comparison.
+- Cast receiver chooser;
+- touch-mode, phone/tablet, and a complete production accessibility-service
+ journey; RTL/large-text semantics, reduced-motion instrumentation, and the
+ direct TalkBack Catalog instrumentation suite are covered by the checks
+ above, but the fixture-driven TalkBack traversal still needs a stable
+ semantic D-pad harness path;
+- cache-equivalent before/after Dashboard performance comparison (deferred
+ until the benchmark environment has stable capacity).
The original public-M3U smoke evidence and connected test counts remain in
`task12-device-journeys.md` and `task12-connected-validation.md`.