From 60f49451da8e5a5a2c0a024ff9a89004cd6cfe3e Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Mon, 27 Jul 2026 23:25:42 +0200 Subject: [PATCH 01/65] docs(tv): design navigation remediation --- ...ndroid-tv-navigation-remediation-design.md | 179 ++++++++++++++++++ 1 file changed, 179 insertions(+) create mode 100644 docs/superpowers/specs/2026-07-27-android-tv-navigation-remediation-design.md diff --git a/docs/superpowers/specs/2026-07-27-android-tv-navigation-remediation-design.md b/docs/superpowers/specs/2026-07-27-android-tv-navigation-remediation-design.md new file mode 100644 index 0000000000..a2ac0d330a --- /dev/null +++ b/docs/superpowers/specs/2026-07-27-android-tv-navigation-remediation-design.md @@ -0,0 +1,179 @@ +# Android TV Navigation Remediation Design + +## Purpose + +Fix two Android TV regressions reported against v1.0.0 and reproduced on the +current client against `lib.strm.cafe`: + +1. The For You filter band cannot transfer D-pad focus into recommendation + rows. +2. Home navigation is sluggish during the first traversal after process start, + then becomes responsive after the same content is warm. + +The change is Android TV focused. Shared startup hydration may change where it +directly removes duplicate Android phone/TV work, but server APIs, server +configuration, content ordering, recommendation generation, and playback are +out of scope. + +## Verified Causes + +### For You focus + +`TvRecommendationsScreen` initially focuses the Watchlist pill but does not +provide a Down target or directional handler for any filter pill. Its +`TvMediaRow` instances also receive neither a row-container focus requester nor +a first-card focus requester. Compose's geometric search therefore leaves focus +on Watchlist, while Watchlist and Favorites work because their catalog grids +provide a different focus topology. + +### Cold Home navigation + +Several independent eager paths overlap after process start: + +- `warmAuthenticatedStartup` fetches the aggregate Home response and then + unconditionally fetches every section again with unbounded concurrency. +- `HomeViewModel` independently fetches the aggregate Home response while the + startup warmup is running. +- `TvSkylineSectionFeed` starts hero artwork and full-detail requests for as + many as sixteen cards on page entry. +- Raw focus movement starts neighbor artwork and network-first detail requests + before the existing 150 ms rested-focus decision. + +Servers with more libraries and rows amplify the first two costs, but server +size is not itself an error. The client must remain responsive for a +production-sized Home response. + +Archived PR 108 commits `49a70045` and `65c4b316` document earlier intent to +remove the page-entry fan-out and hydrate only unresolved Home sections with a +four-request bound. They are historical references, not patches to apply +blindly: current main has newer Home response handling and must retain it. + +## Design + +### 1. Explicit For You focus bridge + +`TvRecommendationsScreen` will own stable focus requesters for: + +- the filter pill that should receive Up from recommendation content; +- the first nonempty recommendation row container; and +- the first card in that row. + +Every filter pill routes Down according to the visible content: + +- For You: request the first row container, wait one frame for the row + `focusRestorer` boundary, then request its first card. +- Watchlist and Favorites: preserve their existing catalog-grid behavior. +- Loading, error, and empty states: do not target an absent row; their existing + actionable control remains reachable. + +The first For You row routes Up back to the selected filter pill. Initial entry +continues to focus Watchlist, preserving current product behavior. + +The handoff will reuse the established `TvMediaRow` requester contract rather +than introducing a second focus-navigation architecture. + +### 2. Resolve Home once, hydrate only missing sections + +Extract a small, platform-neutral Home hydration operation that: + +- accepts aggregate `ResolvedSection` values; +- preserves sections whose items are already inline; +- fetches only sections that are empty while reporting a nonzero total; +- accepts either nested response items or top-level response items; +- limits fallback requests to four concurrently; +- reports whether the snapshot was fully resolved so a partial result cannot + replace a good cache. + +`HomeViewModel` and startup warmup will share this operation. Startup warmup +will no longer refetch every inline section. + +The activity warmup remains best-effort and non-blocking. This change does not +make splash dismissal wait for Home. + +### 3. Remove page-entry detail fan-out + +`TvSkylineSectionFeed` will not eagerly fetch full detail or hero-sized artwork +for the first sixteen cards merely because rows entered composition. Startup +artwork warmup already has a bounded, paint-order budget; the Skyline will seed +the first marquee from aggregate section data and enrich around actual user +focus. + +Neighbor enrichment remains speculative but will be driven by the rested +focused identity rather than every intermediate D-pad position. It will: + +- operate on a small neighbor window; +- preserve request deduplication for the page lifetime; +- use cached item detail before network; +- cap network detail concurrency; +- cancel obsolete work when rested focus changes. + +Opening an item-detail screen keeps its existing network-first freshness +semantics. Cache-first behavior applies only to speculative marquee enrichment. + +### 4. Cache and dispatcher boundaries + +Room remains the profile/server-scoped source for offline Home and item-detail +snapshots. The fix will not alter cache schema or migration state. + +Home JSON encoding and Room access continue on the existing IO-owned startup +scope or repository suspending boundary. If tests show serialization executing +on the main dispatcher, the repository will explicitly move serialization to a +background dispatcher; otherwise no dispatcher abstraction will be added. + +## Error and Lifecycle Behavior + +- Failed speculative image/detail requests remain non-fatal and do not block + focus. +- A failed fallback section fetch leaves the prior complete Home cache intact. +- Switching server or profile continues to select the corresponding scoped + Room data. +- Leaving the Home composition cancels its speculative jobs. +- A process restart may refresh content, but it must not re-download cached + detail solely for prefetch. +- No tokens, origins, diagnostics, or production settings change. + +## Verification + +Behavioral tests will cover: + +- Down from each For You filter pill, Up return, repeated movement, and + loading/error/empty states; +- inline Home sections causing zero per-section fallback requests; +- missing sections being hydrated correctly with at most four concurrent + requests; +- partial hydration preserving cache safety; +- Skyline page entry producing no full-detail burst; +- rapid focus movement starting work only for the rested identity; +- cached detail avoiding network and bounded fallback when cache misses. + +Verification will include focused shared and Android TV unit tests, Android TV +debug/release compilation, and a controlled Shield run against +`lib.strm.cafe`. The device gate will compare cold-process and immediate warm +traversals using frame-jank percentiles and sanitized request counts. Success +requires: + +- For You Down enters its first visible recommendation card reliably; +- no page-entry sixteen-detail burst; +- no per-section N+1 when aggregate sections are inline; +- materially lower cold first-traversal request count and jank without + worsening warm traversal; +- no crash, ANR, authentication change, or server mutation. + +## Alternatives Rejected + +- **Server-side global row caps:** reduces content and masks client-side + duplicate work. +- **Longer splash or input suppression:** hides latency instead of removing it. +- **Blind cherry-pick of archived commits:** risks discarding newer response + compatibility and focus-restoration behavior. +- **Disabling all prefetch:** avoids the burst but makes every settled focus pay + full network and image latency. +- **Timeout or animation tuning:** does not address the measured cold request + fan-out. + +## Scope Boundaries + +This remediation does not change recommendation ranking, Home row composition, +server endpoints, production configuration, phone UI navigation, playback, +database schema, or authentication. It does not attempt a general Compose focus +framework or a complete image-loading redesign. From daf2933fda9cf9c12fcbf0e2d9329734f1844905 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Mon, 27 Jul 2026 23:29:40 +0200 Subject: [PATCH 02/65] docs(tv): plan navigation remediation --- ...07-27-android-tv-navigation-remediation.md | 588 ++++++++++++++++++ 1 file changed, 588 insertions(+) create mode 100644 docs/superpowers/plans/2026-07-27-android-tv-navigation-remediation.md diff --git a/docs/superpowers/plans/2026-07-27-android-tv-navigation-remediation.md b/docs/superpowers/plans/2026-07-27-android-tv-navigation-remediation.md new file mode 100644 index 0000000000..cb60407248 --- /dev/null +++ b/docs/superpowers/plans/2026-07-27-android-tv-navigation-remediation.md @@ -0,0 +1,588 @@ +# Android TV Navigation Remediation Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Restore D-pad access to Android TV For You rows and remove the duplicate, eager cold-start work that makes first Home traversal sluggish on production-sized servers. + +**Architecture:** A shared pure Home hydrator will consume inline aggregate sections and make at most four fallback requests for genuinely unresolved sections. Android TV will use an explicit two-frame focus bridge into recommendation rows and a small pure prefetch policy that permits neighbor work only after focus has settled; speculative detail reads become cache-first while item-detail screens remain network-first. + +**Tech Stack:** Kotlin Multiplatform, Kotlin coroutines and `kotlinx-coroutines-test`, Compose for TV focus APIs, Ktor `MockEngine`, Room-backed cache ports, Gradle Android unit/release tasks, ADB/gfxinfo for the final Shield smoke. + +## Global Constraints + +- Do not change server APIs, server configuration, recommendation ranking, Home row composition, authentication, playback, or database schema. +- Preserve Watchlist and Favorites behavior and the existing initial Watchlist focus. +- Preserve partial-refresh cache safety: an incomplete network result must not overwrite a complete cached Home. +- Keep item-detail screens network-first; cache-first semantics apply only to speculative marquee enrichment. +- Limit fallback Home hydration and speculative detail fan-out to four concurrent requests. +- Do not hide latency with a longer splash, input suppression, animation tuning, or server-side content caps. +- No production data mutation is permitted during verification. + +--- + +### Task 1: Share bounded, inline-first Home hydration + +**Files:** +- Create: `shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeSectionHydrator.kt` +- Create: `shared/src/commonTest/kotlin/org/siloserver/silo/viewmodel/HomeSectionHydratorTest.kt` +- Modify: `shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeViewModel.kt:15-175` +- Modify: `android-shared/src/androidMain/kotlin/org/siloserver/silo/common/startup/StartupWarmup.kt:1-163` +- Test: `shared/src/commonTest/kotlin/org/siloserver/silo/viewmodel/HomeViewModelTest.kt` + +**Interfaces:** +- Consumes: `ResolvedSection`, `HomeSectionItemsResponse`, `ApiResult`, and the existing `SectionRepository.getHomeSectionItems(String)`. +- Produces: + +```kotlin +internal data class HomeSectionHydration( + val sections: List, + val fullyResolved: Boolean, +) + +internal suspend fun hydrateHomeSections( + sections: List, + maxConcurrency: Int = 4, + fetchItems: suspend (String) -> ApiResult, +): HomeSectionHydration +``` + +- [ ] **Step 1: Write the failing inline-section, response-shape, and concurrency tests** + +Create `HomeSectionHydratorTest` with literal fixtures and tests proving: + +```kotlin +@Test +fun inlineSectionsRequireNoFallbackRequests() = runTest { + var calls = 0 + val result = hydrateHomeSections(listOf(section("inline", total = 1, items = listOf(item("a"))))) { + calls += 1 + error("fallback must not run") + } + assertEquals(0, calls) + assertEquals(listOf("a"), result.sections.single().items.map { it.contentId }) + assertTrue(result.fullyResolved) +} + +@Test +fun topLevelFallbackItemsHydrateTheOriginalSection() = runTest { + val result = hydrateHomeSections(listOf(section("missing", total = 1))) { + ApiResult.Success(HomeSectionItemsResponse(items = listOf(item("b")))) + } + assertEquals("missing", result.sections.single().id) + assertEquals(listOf("b"), result.sections.single().items.map { it.contentId }) + assertTrue(result.fullyResolved) +} + +@Test +fun failedFallbackMarksSnapshotPartialAndOmitsEmptySection() = runTest { + val result = hydrateHomeSections(listOf(section("missing", total = 1))) { + ApiResult.NetworkError(IllegalStateException("offline")) + } + assertTrue(result.sections.isEmpty()) + assertFalse(result.fullyResolved) +} +``` + +Add a fourth test with twelve unresolved sections, two +`CompletableDeferred` gates, and atomic active/maximum counters. Hold the +first four requests at the gate, assert no fifth request starts, release them in +batches, and finally assert `maximum == 4`, all twelve IDs were fetched exactly +once, and output order matches input order. + +- [ ] **Step 2: Run the hydrator tests and verify RED** + +Run: + +```bash +./gradlew :shared:testDebugUnitTest --tests '*HomeSectionHydratorTest' --no-daemon +``` + +Expected: compilation failure because `hydrateHomeSections` and `HomeSectionHydration` do not exist. + +- [ ] **Step 3: Implement the pure hydrator with a four-request semaphore** + +Use `kotlinx.coroutines.sync.Semaphore` and `withPermit` inside `coroutineScope`. Preserve inline sections without invoking `fetchItems`; fetch only `items.isEmpty() && totalCount > 0`; resolve nested `section.items`, nested zero-total responses, and top-level `items` with the same precedence currently used by `HomeViewModel`. + +- [ ] **Step 4: Run the hydrator tests and verify GREEN** + +Run: + +```bash +./gradlew :shared:testDebugUnitTest --tests '*HomeSectionHydratorTest' --no-daemon +``` + +Expected: all `HomeSectionHydratorTest` cases pass. + +- [ ] **Step 5: Write caller regression tests before changing either caller** + +Extend `HomeViewModelTest` so a repository returning fully inline aggregate +sections records zero `getHomeSectionItems` calls while still updating UI and +cache. Create +`android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/startup/StartupHomeHydrationTest.kt` +with Android startup-shaped fixtures that assert the same zero-call contract. + +- [ ] **Step 6: Run the caller tests and verify RED** + +Run: + +```bash +./gradlew \ + :shared:testDebugUnitTest --tests '*HomeViewModelTest*inline*' \ + :android-shared:testDebugUnitTest --tests '*StartupHomeHydrationTest' \ + --max-workers=2 --no-daemon +``` + +Expected: the startup test reports one fallback request per inline section; +the shared ViewModel assertion protects the already-correct inline behavior. + +- [ ] **Step 7: Replace duplicated resolution code in both callers** + +In `HomeViewModel.fetchSections`, call: + +```kotlin +val hydration = hydrateHomeSections(sections) { sectionId -> + sectionRepository.getHomeSectionItems(sectionId) +} +val resolved = hydration.sections +val fullyResolved = hydration.fullyResolved +``` + +In `StartupWarmup.warmHome`, call the same function and cache/warm artwork only when `fullyResolved` is true and `sections` is nonempty. This removes the unconditional per-section N+1. + +- [ ] **Step 8: Run focused caller tests** + +Run: + +```bash +./gradlew \ + :shared:testDebugUnitTest --tests '*HomeSectionHydratorTest' --tests '*HomeViewModelTest' \ + :android-shared:testDebugUnitTest --tests '*StartupHomeHydrationTest' \ + --max-workers=2 --no-daemon +``` + +Expected: all focused tests pass with no fallback request for inline sections and a maximum of four for unresolved sections. + +- [ ] **Step 9: Commit Task 1** + +```bash +git add shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeSectionHydrator.kt \ + shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeViewModel.kt \ + shared/src/commonTest/kotlin/org/siloserver/silo/viewmodel/HomeSectionHydratorTest.kt \ + shared/src/commonTest/kotlin/org/siloserver/silo/viewmodel/HomeViewModelTest.kt \ + android-shared/src/androidMain/kotlin/org/siloserver/silo/common/startup/StartupWarmup.kt \ + android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/startup/StartupHomeHydrationTest.kt +git commit -m "perf(android): hydrate inline home sections once" +``` + +### Task 2: Add cache-first speculative detail reads + +**Files:** +- Modify: `shared/src/commonMain/kotlin/org/siloserver/silo/repository/CatalogRepository.kt:110-125` +- Modify: `shared/src/commonTest/kotlin/org/siloserver/silo/repository/CatalogRepositoryDetailCacheTest.kt` + +**Interfaces:** +- Consumes: existing `CatalogCachePort.getCachedItemDetail` and network-first `getItemDetail`. +- Produces: + +```kotlin +suspend fun getItemDetailForPrefetch(contentId: String): ApiResult +``` + +- [ ] **Step 1: Write failing cache-hit and cache-miss tests** + +Extend `CatalogRepositoryDetailCacheTest`: + +```kotlin +@Test +fun prefetchUsesCachedDetailWithoutNetwork() = runTest { + val cache = FakeCache(preset = ItemDetail(contentId = "c1", type = "movie", title = "Cached")) + val result = repoThatFailsOnNetwork(cache).getItemDetailForPrefetch("c1") + assertEquals("Cached", (result as ApiResult.Success).data.title) +} + +@Test +fun prefetchFetchesAndCachesWhenDetailIsAbsent() = runTest { + val cache = FakeCache() + val result = repo(HttpStatusCode.OK, """{"content_id":"c2","type":"movie","title":"Fresh"}""", cache) + .getItemDetailForPrefetch("c2") + assertEquals("Fresh", (result as ApiResult.Success).data.title) + assertEquals("c2", cache.cachedId) +} +``` + +- [ ] **Step 2: Run the repository tests and verify RED** + +Run: + +```bash +./gradlew :shared:testDebugUnitTest --tests '*CatalogRepositoryDetailCacheTest' --no-daemon +``` + +Expected: compilation failure because `getItemDetailForPrefetch` does not exist. + +- [ ] **Step 3: Implement the minimal cache-first method** + +```kotlin +suspend fun getItemDetailForPrefetch(contentId: String): ApiResult { + catalogCache.getCachedItemDetail(contentId)?.let { return ApiResult.Success(it) } + return getItemDetail(contentId) +} +``` + +Do not change `getItemDetail`. + +- [ ] **Step 4: Run the repository tests and verify GREEN** + +Run: + +```bash +./gradlew :shared:testDebugUnitTest --tests '*CatalogRepositoryDetailCacheTest' --no-daemon +``` + +Expected: every cache test passes; the existing network-first tests remain unchanged. + +- [ ] **Step 5: Commit Task 2** + +```bash +git add shared/src/commonMain/kotlin/org/siloserver/silo/repository/CatalogRepository.kt \ + shared/src/commonTest/kotlin/org/siloserver/silo/repository/CatalogRepositoryDetailCacheTest.kt +git commit -m "perf(tv): make marquee prefetch cache first" +``` + +### Task 3: Make Skyline prefetch settled, bounded, and demand-driven + +**Files:** +- Create: `androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylinePrefetchPolicy.kt` +- Create: `androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvSkylinePrefetchPolicyTest.kt` +- Modify: `androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylineSectionFeed.kt:95-341` +- Test: `androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeEnrichmentTest.kt` + +**Interfaces:** +- Consumes: the raw focused content ID, the committed/rested marquee content ID, the focused row, and radius two. +- Produces: + +```kotlin +internal fun settledPrefetchItems( + items: List, + rawFocusedContentId: String?, + settledContentId: String?, + radius: Int = 2, +): List +``` + +The function returns an empty list unless raw and settled identities match. When they match, it returns at most two neighbors on each side, excluding the focused item. + +- [ ] **Step 1: Write the failing policy tests** + +Create literal five-card fixtures and assert: + +```kotlin +@Test +fun rapidFocusBeforeMarqueeSettlementStartsNoNeighborWork() { + assertEquals( + emptyList(), + settledPrefetchItems(items, rawFocusedContentId = "d", settledContentId = "b"), + ) +} + +@Test +fun settledFocusReturnsOnlyTwoNeighborsPerSide() { + assertEquals( + listOf("a", "b", "d", "e"), + settledPrefetchItems(items, rawFocusedContentId = "c", settledContentId = "c") + .map { it.contentId }, + ) +} +``` + +Also cover first-card and missing-ID boundaries. + +- [ ] **Step 2: Run the policy tests and verify RED** + +Run: + +```bash +./gradlew :androidTvApp:testDebugUnitTest --tests '*TvSkylinePrefetchPolicyTest' --no-daemon +``` + +Expected: compilation failure because `settledPrefetchItems` does not exist. + +- [ ] **Step 3: Implement the pure settled-focus policy** + +Use `indexOfFirst`, a clamped inclusive range, and `takeIf` identity equality. Return values in row order and exclude the focused index. + +- [ ] **Step 4: Run the policy tests and verify GREEN** + +Run the same command and confirm all boundary cases pass. + +- [ ] **Step 5: Remove unconditional page-entry preload effects** + +Delete only the two `LaunchedEffect(rows)`/`LaunchedEffect(rows, fetchDetail)` blocks that preload hero artwork and full details for two rows × eight items. Remove `HeroPreloadRowCount` and `HeroPreloadItemsPerRow`. Retain the initial aggregate-data marquee seed and startup artwork plan. + +- [ ] **Step 6: Wire cache-first settled neighbor work** + +Change the injected detail lambda to call `catalogRepository.getItemDetailForPrefetch`. Replace the raw-index neighbor calculation with `settledPrefetchItems`. Key the effect on `rows`, `focusedContentId`, `marquee.content?.contentId`, and the fetcher. A raw focus move cancels the old job immediately; the identity mismatch starts no new work until the marquee commits after its existing 150 ms rest. + +Keep the existing maximum four neighbors, request claim, stale-result guard, artwork sizing, and composition-cancellation ownership. + +- [ ] **Step 7: Add an integration-level request-budget test** + +Extend `TvFocusMarqueeEnrichmentTest` with a coroutine test that sends focus identities `a`, `b`, `c` within less than 150 ms and proves only the settled `c` policy window is returned. Mutate the equality guard locally to verify the test fails by returning the `b` window, then restore the implementation. + +- [ ] **Step 8: Run the Skyline and marquee suite** + +Run: + +```bash +./gradlew :androidTvApp:testDebugUnitTest \ + --tests '*TvSkylinePrefetchPolicyTest' \ + --tests '*TvFocusMarqueeModelTest' \ + --tests '*TvFocusMarqueeEnrichmentTest' \ + --max-workers=2 --no-daemon +``` + +Expected: all focused tests pass. + +- [ ] **Step 9: Commit Task 3** + +```bash +git add androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylinePrefetchPolicy.kt \ + androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylineSectionFeed.kt \ + androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvSkylinePrefetchPolicyTest.kt \ + androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeEnrichmentTest.kt +git commit -m "perf(tv): defer skyline work until focus settles" +``` + +### Task 4: Bridge For You filters into recommendation rows + +**Files:** +- Create: `androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvRecommendationsFocusBridge.kt` +- Create: `androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvRecommendationsFocusBridgeTest.kt` +- Modify: `androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvRecommendationsScreen.kt:64-289` + +**Interfaces:** +- Consumes: row-container/card focus request lambdas and a one-frame suspension. +- Produces: + +```kotlin +internal suspend fun requestRecommendationRowFocus( + requestRowContainer: () -> Boolean, + awaitFrame: suspend () -> Unit, + requestFirstCard: () -> Boolean, +): Boolean + +internal fun shouldBridgeRecommendationsDown( + showingRecommendations: Boolean, + hasVisibleRecommendations: Boolean, +): Boolean +``` + +The function returns false only when the row container cannot accept focus. After a successful row hop it waits one frame and targets the first card. + +- [ ] **Step 1: Write the failing focus-bridge tests** + +Create tests with a literal event list: + +```kotlin +@Test +fun handoffCrossesRowRestorerBeforeTargetingFirstCard() = runTest { + val events = mutableListOf() + val handled = requestRecommendationRowFocus( + requestRowContainer = { events += "row"; true }, + awaitFrame = { events += "frame" }, + requestFirstCard = { events += "card"; true }, + ) + assertTrue(handled) + assertEquals(listOf("row", "frame", "card"), events) +} + +@Test +fun rejectedRowHopDoesNotTargetCard() = runTest { + val events = mutableListOf() + val handled = requestRecommendationRowFocus( + requestRowContainer = { events += "row"; false }, + awaitFrame = { events += "frame" }, + requestFirstCard = { events += "card"; true }, + ) + assertFalse(handled) + assertEquals(listOf("row"), events) +} +``` + +- [ ] **Step 2: Add the failing visibility-policy tests** + +Assert that `shouldBridgeRecommendationsDown` returns true only when For You is +selected and at least one recommendation row is visible. Assert false for +Watchlist, Favorites, loading, error, and empty For You states. + +- [ ] **Step 3: Run the bridge tests and verify RED** + +Run: + +```bash +./gradlew :androidTvApp:testDebugUnitTest --tests '*TvRecommendationsFocusBridgeTest' --no-daemon +``` + +Expected: compilation failure because the bridge does not exist. + +- [ ] **Step 4: Implement the minimal bridge** + +Implement exactly the ordered row/frame/card sequence and the two-boolean +visibility policy. Do not retry or add delays; `TvMediaRow` owns the row +`focusRestorer` contract. + +- [ ] **Step 5: Run the bridge tests and verify GREEN** + +Run the same command and confirm both ordering and rejected-hop behavior pass. + +- [ ] **Step 6: Wire stable requesters into the screen** + +Add stable requesters for For You, Watchlist, Favorites, the first recommendation row container, and its first card. Render recommendation rows with indexed items so only index zero receives: + +```kotlin +firstItemFocusRequester = recommendationFirstCardFocusRequester +rowContainerFocusRequester = recommendationFirstRowContainerFocusRequester +onDirectionUp = { + selectedFilterRequester.requestFocus() +} +``` + +Each filter pill's `onDirectionDown` consults +`shouldBridgeRecommendationsDown`; Watchlist and Favorites continue to use +their existing geometric grid navigation when selected. Keep initial entry on +Watchlist. The first For You row's `onDirectionUp` requests the For You pill. + +- [ ] **Step 7: Run the complete focused TV suite** + +Run: + +```bash +./gradlew :androidTvApp:testDebugUnitTest \ + --tests '*TvRecommendationsFocusBridgeTest' \ + --tests '*TvSkylinePrefetchPolicyTest' \ + --tests '*TvFocusMarqueeModelTest' \ + --tests '*TvFocusMarqueeEnrichmentTest' \ + --max-workers=2 --no-daemon +``` + +Expected: every focused test passes. + +- [ ] **Step 8: Commit Task 4** + +```bash +git add androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvRecommendationsFocusBridge.kt \ + androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvRecommendationsScreen.kt \ + androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvRecommendationsFocusBridgeTest.kt +git commit -m "fix(tv): enter for-you rows from filter controls" +``` + +### Task 5: Full verification, production-shaped smoke, and executive summary + +**Files:** +- Create: `docs/reviews/2026-07-27-android-tv-navigation-remediation-executive-summary.md` +- Modify only if verification exposes a feature regression: files already listed in Tasks 1-4. + +**Interfaces:** +- Consumes: all prior task commits and the authenticated local Shield at `192.168.1.128:5555`. +- Produces: a concise executive summary containing impact, causes, remedy, quantified before/after evidence, rollout risk, and rollback boundary. + +- [ ] **Step 1: Run supply-chain and complete relevant unit gates** + +Run: + +```bash +./gradlew verifyDependencySupplyChainPolicy \ + :shared:testDebugUnitTest \ + :android-shared:testDebugUnitTest \ + :androidTvApp:testDebugUnitTest \ + --max-workers=2 --no-daemon +``` + +Expected: exit zero with no failed test task. + +- [ ] **Step 2: Compile debug and minified TV release** + +Run: + +```bash +./gradlew \ + :androidTvApp:assembleDebug \ + :androidTvApp:assembleRelease \ + -PallowDebugReleaseSigning=true \ + --max-workers=2 --no-daemon +``` + +Expected: both tasks exit zero. + +- [ ] **Step 3: Perform the For You device smoke** + +Install only on the explicitly selected Shield if the candidate signer is compatible with the installed package; otherwise use the dedicated TV emulator. Preserve app data with: + +```bash +adb -s 192.168.1.128:5555 install -r \ + androidTvApp/build/outputs/apk/release/androidTvApp-universal-release.apk +``` + +Verify: + +1. Enter For You from the top menu. +2. Initial focus remains Watchlist. +3. Select For You and press Down; focus reaches the first visible recommendation card. +4. Press Down/Up repeatedly; focus is not trapped and Up returns to For You. +5. Select Watchlist and Favorites; Down still enters their grids. + +- [ ] **Step 4: Repeat the cold/warm performance protocol** + +Against `lib.strm.cafe`, clear only process state with `am force-stop`, reset `dumpsys gfxinfo`, clear logcat, launch, and run the same fixed sequences used during diagnosis: + +- horizontal: five Right then five Left at 250 ms; +- vertical: three Down then three Up at 500 ms; +- repeat each immediately without process restart. + +Record total/janky frames, p50/p90/p95/p99, sanitized HTTP completion count, GC count, crash, and ANR status. Do not capture credentials or request headers. + +- [ ] **Step 5: Write the executive summary** + +Create the summary with these exact sections: + +- `Decision`: what was fixed and why it is safe to ship. +- `Customer impact`: For You accessibility and first-traversal responsiveness. +- `Verified causes`: missing focus bridge, duplicate Home hydration, eager detail fan-out. +- `Change`: inline-first bounded hydration, cache-first rested enrichment, explicit focus handoff. +- `Evidence`: before/after cold and warm measurements and test/build counts. +- `Risk and rollback`: Android TV focus/prefetch scope, no schema/server change, revert commits independently. + +- [ ] **Step 6: Review diff and obtain independent review** + +Run: + +```bash +git diff --check origin/main...HEAD +git status --short +git log --oneline origin/main..HEAD +``` + +Request focused review of correctness, coroutine cancellation, focus-restorer ordering, cache semantics, and whether tests detect realistic regressions. Fix every Critical or Important finding test-first and rerun the smallest affected gate. + +- [ ] **Step 7: Commit the verified executive summary** + +```bash +git add docs/reviews/2026-07-27-android-tv-navigation-remediation-executive-summary.md +git commit -m "docs(tv): summarize navigation remediation" +``` + +- [ ] **Step 8: Run the final fresh gate** + +Run: + +```bash +./gradlew verifyDependencySupplyChainPolicy \ + :shared:testDebugUnitTest \ + :android-shared:testDebugUnitTest \ + :androidTvApp:testDebugUnitTest \ + :androidTvApp:assembleRelease \ + -PallowDebugReleaseSigning=true \ + --max-workers=2 --no-daemon +``` + +Expected: exit zero. Confirm `git status --short` is empty before invoking `superpowers:finishing-a-development-branch`. From 0ed7ba56d03ac7cc792feccdcf3376fc64ede46b Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Mon, 27 Jul 2026 23:33:26 +0200 Subject: [PATCH 03/65] perf(android): hydrate inline home sections once --- .../silo/common/startup/StartupWarmup.kt | 24 +--- ...07-27-android-tv-navigation-remediation.md | 4 +- .../silo/viewmodel/HomeSectionHydrator.kt | 70 ++++++++++ .../silo/viewmodel/HomeViewModel.kt | 41 +----- .../silo/viewmodel/HomeSectionHydratorTest.kt | 122 ++++++++++++++++++ 5 files changed, 205 insertions(+), 56 deletions(-) create mode 100644 shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeSectionHydrator.kt create mode 100644 shared/src/commonTest/kotlin/org/siloserver/silo/viewmodel/HomeSectionHydratorTest.kt diff --git a/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/startup/StartupWarmup.kt b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/startup/StartupWarmup.kt index d059dd1557..21fdeda32f 100644 --- a/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/startup/StartupWarmup.kt +++ b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/startup/StartupWarmup.kt @@ -12,6 +12,7 @@ import org.siloserver.silo.repository.PersonalDataRepository import org.siloserver.silo.repository.ProfileRepository import org.siloserver.silo.repository.SectionRepository import org.siloserver.silo.repository.port.HomeCachePort +import org.siloserver.silo.viewmodel.hydrateHomeSections import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll @@ -138,23 +139,12 @@ private suspend fun CoroutineScope.warmHome( ) { when (val result = sectionRepository.getHomeSections()) { is ApiResult.Success -> { - val resolvedPairs: List> = - result.data.sections.map { section -> - async { - when (val itemsResult = sectionRepository.getHomeSectionItems(section.id)) { - is ApiResult.Success -> (itemsResult.data.section ?: section) to true - is ApiResult.Error, - is ApiResult.NetworkError -> section to false - } - } - }.awaitAll() - - if (resolvedPairs.all { it.second }) { - val resolved = resolvedPairs.map { it.first }.filter { it.items.isNotEmpty() } - if (resolved.isNotEmpty()) { - homeCache.cacheHome(resolved) - warmHomeArtwork(context, resolved, artworkPlan) - } + val hydration = hydrateHomeSections(result.data.sections) { sectionId -> + sectionRepository.getHomeSectionItems(sectionId) + } + if (hydration.fullyResolved && hydration.sections.isNotEmpty()) { + homeCache.cacheHome(hydration.sections) + warmHomeArtwork(context, hydration.sections, artworkPlan) } } is ApiResult.Error, diff --git a/docs/superpowers/plans/2026-07-27-android-tv-navigation-remediation.md b/docs/superpowers/plans/2026-07-27-android-tv-navigation-remediation.md index cb60407248..0bd5ef180f 100644 --- a/docs/superpowers/plans/2026-07-27-android-tv-navigation-remediation.md +++ b/docs/superpowers/plans/2026-07-27-android-tv-navigation-remediation.md @@ -34,12 +34,12 @@ - Produces: ```kotlin -internal data class HomeSectionHydration( +data class HomeSectionHydration( val sections: List, val fullyResolved: Boolean, ) -internal suspend fun hydrateHomeSections( +suspend fun hydrateHomeSections( sections: List, maxConcurrency: Int = 4, fetchItems: suspend (String) -> ApiResult, diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeSectionHydrator.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeSectionHydrator.kt new file mode 100644 index 0000000000..0a0af8dc48 --- /dev/null +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeSectionHydrator.kt @@ -0,0 +1,70 @@ +package org.siloserver.silo.viewmodel + +import org.siloserver.silo.model.section.HomeSectionItemsResponse +import org.siloserver.silo.model.section.ResolvedSection +import org.siloserver.silo.network.ApiResult +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitAll +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.sync.Semaphore +import kotlinx.coroutines.sync.withPermit + +/** Complete-or-partial result shared by startup warmup and [HomeViewModel]. */ +data class HomeSectionHydration( + val sections: List, + val fullyResolved: Boolean, +) + +/** + * Keeps aggregate Home sections that already contain items and resolves only + * genuinely missing section payloads, with bounded fallback concurrency. + */ +suspend fun hydrateHomeSections( + sections: List, + maxConcurrency: Int = 4, + fetchItems: suspend (String) -> ApiResult, +): HomeSectionHydration { + require(maxConcurrency > 0) { "maxConcurrency must be positive" } + + val unresolved = sections.filter { it.items.isEmpty() && it.totalCount > 0 } + val semaphore = Semaphore(maxConcurrency) + val fallbackById = coroutineScope { + unresolved.map { section -> + async { + section.id to semaphore.withPermit { + when (val result = fetchItems(section.id)) { + is ApiResult.Success -> resolveHomeSectionItems(section, result.data) + is ApiResult.Error, + is ApiResult.NetworkError -> null + } + } + } + }.awaitAll().toMap() + } + + return HomeSectionHydration( + sections = sections.mapNotNull { section -> + when { + section.items.isNotEmpty() -> section + section.totalCount == 0 -> null + else -> fallbackById[section.id]?.takeIf { it.items.isNotEmpty() } + } + }, + fullyResolved = unresolved.all { fallbackById[it.id] != null }, + ) +} + +private fun resolveHomeSectionItems( + original: ResolvedSection, + response: HomeSectionItemsResponse, +): ResolvedSection? { + val responseSection = response.section + return when { + responseSection != null && responseSection.items.isNotEmpty() -> responseSection + responseSection != null && responseSection.totalCount == 0 -> responseSection + responseSection != null && response.items.isNotEmpty() -> + responseSection.copy(items = response.items) + response.items.isNotEmpty() -> original.copy(items = response.items) + else -> null + } +} diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeViewModel.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeViewModel.kt index afcde02eed..701ab3937d 100644 --- a/shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeViewModel.kt +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeViewModel.kt @@ -12,8 +12,6 @@ import org.siloserver.silo.repository.port.HomeCachePort import org.siloserver.silo.repository.port.NoOpHomeCachePort import org.siloserver.silo.repository.port.NoOpUserItemStatePort import org.siloserver.silo.repository.port.UserItemStatePort -import kotlinx.coroutines.async -import kotlinx.coroutines.awaitAll import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow @@ -130,43 +128,12 @@ class HomeViewModel( // re-downloading data already in hand. Defensive fallback resolves // only sections the server left un-inlined (older deployments / a // section type that reports a non-zero total but ships no items). - val needsFetch = sections.filter { it.items.isEmpty() && it.totalCount > 0 } - val resolvedPairs: List> = if (needsFetch.isEmpty()) { - sections.map { it to true } - } else { - val byId = needsFetch.map { section -> - viewModelScope.async { - section.id to when (val itemsResult = sectionRepository.getHomeSectionItems(section.id)) { - is ApiResult.Success -> { - // The response carries items either nested under - // `section` or as a sibling top-level `items` list. - // Honor both — using only `.section` silently drops - // a successful refetch that returned items at the top - // level, leaving the section empty and filtered out. - val data = itemsResult.data - val responseSection = data.section - val hydrated = when { - responseSection != null && responseSection.items.isNotEmpty() -> - responseSection - responseSection != null && responseSection.totalCount == 0 -> - responseSection - responseSection != null && data.items.isNotEmpty() -> - responseSection.copy(items = data.items) - data.items.isNotEmpty() -> - section.copy(items = data.items) - else -> null - } - if (hydrated != null) hydrated to true else section to false - } - else -> section to false - } - } - }.awaitAll().toMap() - sections.map { section -> byId[section.id] ?: (section to true) } + val hydration = hydrateHomeSections(sections) { sectionId -> + sectionRepository.getHomeSectionItems(sectionId) } - val resolved = resolvedPairs.map { it.first }.filter { it.items.isNotEmpty() } + val resolved = hydration.sections // Don't persist a partially-resolved home over a good cached one. - val fullyResolved = resolvedPairs.all { it.second } + val fullyResolved = hydration.fullyResolved // Cache the RAW server sections (snapshot), but display with the // local optimistic overlay applied. diff --git a/shared/src/commonTest/kotlin/org/siloserver/silo/viewmodel/HomeSectionHydratorTest.kt b/shared/src/commonTest/kotlin/org/siloserver/silo/viewmodel/HomeSectionHydratorTest.kt new file mode 100644 index 0000000000..089b39af23 --- /dev/null +++ b/shared/src/commonTest/kotlin/org/siloserver/silo/viewmodel/HomeSectionHydratorTest.kt @@ -0,0 +1,122 @@ +package org.siloserver.silo.viewmodel + +import org.siloserver.silo.model.section.HomeSectionItemsResponse +import org.siloserver.silo.model.section.ResolvedSection +import org.siloserver.silo.model.section.SectionItem +import org.siloserver.silo.network.ApiResult +import kotlinx.coroutines.async +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.withTimeoutOrNull +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +class HomeSectionHydratorTest { + + @Test + fun inlineSectionsRequireNoFallbackRequests() = runTest { + var calls = 0 + + val result = hydrateHomeSections( + sections = listOf(section("inline", total = 1, items = listOf(item("a")))), + ) { + calls += 1 + error("fallback must not run") + } + + assertEquals(0, calls) + assertEquals(listOf("a"), result.sections.single().items.map { it.contentId }) + assertTrue(result.fullyResolved) + } + + @Test + fun topLevelFallbackItemsHydrateTheOriginalSection() = runTest { + val result = hydrateHomeSections(listOf(section("missing", total = 1))) { + ApiResult.Success(HomeSectionItemsResponse(items = listOf(item("b")))) + } + + assertEquals("missing", result.sections.single().id) + assertEquals(listOf("b"), result.sections.single().items.map { it.contentId }) + assertTrue(result.fullyResolved) + } + + @Test + fun nestedFallbackSectionWinsWhenItContainsItems() = runTest { + val result = hydrateHomeSections(listOf(section("missing", total = 1))) { + ApiResult.Success( + HomeSectionItemsResponse( + section = section("server", total = 1, items = listOf(item("nested"))), + items = listOf(item("top-level")), + ), + ) + } + + assertEquals("server", result.sections.single().id) + assertEquals(listOf("nested"), result.sections.single().items.map { it.contentId }) + assertTrue(result.fullyResolved) + } + + @Test + fun failedFallbackMarksSnapshotPartialAndOmitsEmptySection() = runTest { + val result = hydrateHomeSections(listOf(section("missing", total = 1))) { + ApiResult.NetworkError(IllegalStateException("offline")) + } + + assertTrue(result.sections.isEmpty()) + assertFalse(result.fullyResolved) + } + + @Test + fun fallbackHydrationNeverExceedsFourConcurrentRequests() = runTest { + val started = Channel(Channel.UNLIMITED) + val release = Channel(Channel.UNLIMITED) + var active = 0 + var maximum = 0 + val ids = (1..12).map { "section-$it" } + + val hydration = async { + hydrateHomeSections(ids.map { section(it, total = 1) }) { id -> + active += 1 + maximum = maxOf(maximum, active) + started.send(id) + release.receive() + active -= 1 + ApiResult.Success(HomeSectionItemsResponse(items = listOf(item("item-$id")))) + } + } + + val observedStarts = mutableListOf() + repeat(3) { + repeat(4) { observedStarts += started.receive() } + assertNull(withTimeoutOrNull(1) { started.receive() }) + repeat(4) { release.send(Unit) } + } + + val result = hydration.await() + assertEquals(4, maximum) + assertEquals(ids.toSet(), observedStarts.toSet()) + assertEquals(ids, result.sections.map { it.id }) + assertTrue(result.fullyResolved) + } + + private fun section( + id: String, + total: Int, + items: List = emptyList(), + ) = ResolvedSection( + id = id, + sectionType = "test", + title = id, + totalCount = total, + items = items, + ) + + private fun item(id: String) = SectionItem( + contentId = id, + type = "movie", + title = id, + ) +} From f0627c5f264a9774b50a5f3bd8d0fbd966d06e34 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Mon, 27 Jul 2026 23:34:30 +0200 Subject: [PATCH 04/65] perf(tv): make marquee prefetch cache first --- .../silo/repository/CatalogRepository.kt | 9 +++++++++ .../CatalogRepositoryDetailCacheTest.kt | 16 ++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/repository/CatalogRepository.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/repository/CatalogRepository.kt index ab244c04de..2e177478ef 100644 --- a/shared/src/commonMain/kotlin/org/siloserver/silo/repository/CatalogRepository.kt +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/repository/CatalogRepository.kt @@ -124,6 +124,15 @@ class CatalogRepository( suspend fun getCachedItemDetail(contentId: String): ItemDetail? = catalogCache.getCachedItemDetail(contentId) + /** + * Cache-first detail for speculative UI enrichment. Unlike a detail screen, + * prefetch must not re-download metadata that is already durable locally. + */ + suspend fun getItemDetailForPrefetch(contentId: String): ApiResult { + catalogCache.getCachedItemDetail(contentId)?.let { return ApiResult.Success(it) } + return getItemDetail(contentId) + } + /** Fetches playback-oriented detail (versions, user progress, intro/credits markers). */ suspend fun getWatchDetail(contentId: String): ApiResult = catalogApi.getWatchDetail(contentId) diff --git a/shared/src/commonTest/kotlin/org/siloserver/silo/repository/CatalogRepositoryDetailCacheTest.kt b/shared/src/commonTest/kotlin/org/siloserver/silo/repository/CatalogRepositoryDetailCacheTest.kt index a964afad2a..3de6207a52 100644 --- a/shared/src/commonTest/kotlin/org/siloserver/silo/repository/CatalogRepositoryDetailCacheTest.kt +++ b/shared/src/commonTest/kotlin/org/siloserver/silo/repository/CatalogRepositoryDetailCacheTest.kt @@ -74,6 +74,22 @@ class CatalogRepositoryDetailCacheTest { assertEquals("Cached", detail?.title) } + @Test + fun prefetchUsesCachedDetailWithoutNetwork() = runTest { + val cache = FakeCache(preset = ItemDetail(contentId = "c1", type = "movie", title = "Cached")) + val result = repoThatFailsOnNetwork(cache).getItemDetailForPrefetch("c1") + assertEquals("Cached", (result as ApiResult.Success).data.title) + } + + @Test + fun prefetchFetchesAndCachesWhenDetailIsAbsent() = runTest { + val cache = FakeCache() + val result = repo(HttpStatusCode.OK, """{"content_id":"c2","type":"movie","title":"Fresh"}""", cache) + .getItemDetailForPrefetch("c2") + assertEquals("Fresh", (result as ApiResult.Success).data.title) + assertEquals("c2", cache.cachedId) + } + @Test fun doesNotServeCacheOn4xx() = runTest { val cache = FakeCache(preset = ItemDetail(contentId = "c1", type = "movie", title = "Cached")) From 2060871e8ad79f206f27ed206f1ba9ff3c0de765 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Mon, 27 Jul 2026 23:36:31 +0200 Subject: [PATCH 05/65] perf(tv): defer skyline work until focus settles --- .../ui/components/TvSkylinePrefetchPolicy.kt | 20 ++++ .../tv/ui/components/TvSkylineSectionFeed.kt | 111 ++---------------- .../components/TvSkylinePrefetchPolicyTest.kt | 62 ++++++++++ 3 files changed, 94 insertions(+), 99 deletions(-) create mode 100644 androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylinePrefetchPolicy.kt create mode 100644 androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvSkylinePrefetchPolicyTest.kt diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylinePrefetchPolicy.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylinePrefetchPolicy.kt new file mode 100644 index 0000000000..250ee02784 --- /dev/null +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylinePrefetchPolicy.kt @@ -0,0 +1,20 @@ +package org.siloserver.silo.tv.ui.components + +import org.siloserver.silo.model.section.SectionItem + +internal fun settledPrefetchItems( + items: List, + rawFocusedContentId: String?, + settledContentId: String?, + radius: Int = 2, +): List { + if (rawFocusedContentId == null || rawFocusedContentId != settledContentId || radius <= 0) { + return emptyList() + } + val focusedIndex = items.indexOfFirst { it.contentId == settledContentId } + if (focusedIndex < 0) return emptyList() + + return ((focusedIndex - radius)..(focusedIndex + radius)) + .filter { it in items.indices && it != focusedIndex } + .map(items::get) +} diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylineSectionFeed.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylineSectionFeed.kt index 2e0e542f17..1486aee5bf 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylineSectionFeed.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylineSectionFeed.kt @@ -99,7 +99,7 @@ fun TvSkylineSectionFeed( val catalogRepository: CatalogRepository = koinInject() val fetchDetail: suspend (String) -> ItemDetail? = remember(catalogRepository) { { contentId -> - (catalogRepository.getItemDetail(contentId) as? ApiResult.Success)?.data + (catalogRepository.getItemDetailForPrefetch(contentId) as? ApiResult.Success)?.data } } val marquee = rememberTvFocusMarqueeState(fetchDetail = fetchDetail) @@ -118,92 +118,6 @@ fun TvSkylineSectionFeed( } } - // Warm the hero-sized backdrop/logo variants for the cards the user can - // reach first. This is intentionally opportunistic: focus transitions - // never wait on the network, but the shared Crossfade usually receives a - // memory-cached image instead of a late ThumbHash replacement. - LaunchedEffect(rows) { - val requests = rows - .take(HeroPreloadRowCount) - .flatMap { it.items.take(HeroPreloadItemsPerRow) } - .flatMap { item -> - buildList { - item.backdropUrl?.takeIf { it.isNotBlank() }?.let { url -> - add( - ImageRequest.Builder(context) - .data(url) - .size(HeroBackdropPreloadWidthPx, HeroBackdropPreloadHeightPx) - .build(), - ) - } - item.logoUrl?.takeIf { it.isNotBlank() }?.let { url -> - add( - ImageRequest.Builder(context) - .data(url) - .size(HeroLogoPreloadWidthPx, HeroLogoPreloadHeightPx) - .build(), - ) - } - } - } - .distinctBy { it.data.toString() } - - val loader = SingletonImageLoader.get(context) - coroutineScope { - requests.map { request -> - async { runCatching { loader.execute(request) } } - }.awaitAll() - } - } - - // Section payloads intentionally stay lightweight and omit the aired/cast - // line. Warm detail for the same near-viewport cards whose hero artwork is - // preloaded so normal D-pad navigation presents a complete marquee on its - // first rested frame. The shared request guard prevents this from racing or - // duplicating the focus-driven fetch for the currently displayed card. - LaunchedEffect(rows, fetchDetail) { - val loader = SingletonImageLoader.get(context) - rows - .take(HeroPreloadRowCount) - .forEach { row -> - coroutineScope { - row.items - .take(HeroPreloadItemsPerRow) - .map { item -> - async { - val contentId = item.contentId - if (!marquee.beginEnrichmentRequest(contentId)) return@async - try { - val detail = runCatching { fetchDetail(contentId) }.getOrNull() - ?: return@async - val enrichment = TvMarqueeEnrichment.from(detail) - marquee.applyEnrichment(contentId, enrichment) - - // Warm a possible episode-series art upgrade - // at the exact hero decode size as well. - enrichment.backdropUrl?.takeIf { it.isNotBlank() }?.let { url -> - runCatching { - loader.execute( - ImageRequest.Builder(context) - .data(url) - .size( - HeroBackdropPreloadWidthPx, - HeroBackdropPreloadHeightPx, - ) - .build(), - ) - } - } - } finally { - marquee.finishEnrichmentRequest(contentId) - } - } - } - .awaitAll() - } - } - } - val rowBandState = rememberLazyListState() // NOT keyed on `rows`: a quiet realtime/on-resume refetch emits a new // sections list, and resetting the focused-row index to -1 made the next @@ -269,17 +183,18 @@ fun TvSkylineSectionFeed( detailReturnPending = true } - // Keep the two cards immediately before and after focus hot. Because this - // window is established while the current card is focused, the next two - // D-pad moves in either direction already have logo/backdrop bytes and - // aired/cast enrichment in cache before their focus events arrive. - LaunchedEffect(rows, focusedRowIndex, focusedItemIndex, fetchDetail) { + // Keep a small window around RESTED focus hot. A raw D-pad move cancels the + // previous job immediately, but the new identity starts no speculative + // work until the marquee's focus-rest transaction commits it. + LaunchedEffect(rows, focusedContentId, marquee.content?.contentId, fetchDetail) { val row = rows.getOrNull(focusedRowIndex) ?: return@LaunchedEffect - if (focusedItemIndex !in row.items.indices) return@LaunchedEffect - val window = ((focusedItemIndex - HeroFocusPrefetchRadius).. - (focusedItemIndex + HeroFocusPrefetchRadius)) - .filter { it in row.items.indices && it != focusedItemIndex } - .map(row.items::get) + val window = settledPrefetchItems( + items = row.items, + rawFocusedContentId = focusedContentId, + settledContentId = marquee.content?.contentId, + radius = HeroFocusPrefetchRadius, + ) + if (window.isEmpty()) return@LaunchedEffect val loader = SingletonImageLoader.get(context) coroutineScope { @@ -725,8 +640,6 @@ private const val HeroBackdropPreloadWidthPx = 1229 private const val HeroBackdropPreloadHeightPx = 756 private const val HeroLogoPreloadWidthPx = 880 private const val HeroLogoPreloadHeightPx = 200 -private const val HeroPreloadRowCount = 2 -private const val HeroPreloadItemsPerRow = 8 private const val HeroFocusPrefetchRadius = 2 /** tvOS MediaRow cardSpacing 40pt maps to 20dp. */ diff --git a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvSkylinePrefetchPolicyTest.kt b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvSkylinePrefetchPolicyTest.kt new file mode 100644 index 0000000000..e764ac0b27 --- /dev/null +++ b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvSkylinePrefetchPolicyTest.kt @@ -0,0 +1,62 @@ +package org.siloserver.silo.tv.ui.components + +import org.siloserver.silo.model.section.SectionItem +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +class TvSkylinePrefetchPolicyTest { + private val items = listOf("a", "b", "c", "d", "e").map(::item) + + @Test + fun rapidFocusBeforeMarqueeSettlementStartsNoNeighborWork() { + assertTrue( + settledPrefetchItems( + items = items, + rawFocusedContentId = "d", + settledContentId = "b", + ).isEmpty(), + ) + } + + @Test + fun settledFocusReturnsOnlyTwoNeighborsPerSide() { + assertEquals( + listOf("a", "b", "d", "e"), + settledPrefetchItems( + items = items, + rawFocusedContentId = "c", + settledContentId = "c", + ).map { it.contentId }, + ) + } + + @Test + fun firstCardReturnsOnlyFollowingNeighbors() { + assertEquals( + listOf("b", "c"), + settledPrefetchItems( + items = items, + rawFocusedContentId = "a", + settledContentId = "a", + ).map { it.contentId }, + ) + } + + @Test + fun missingSettledIdentityStartsNoNeighborWork() { + assertTrue( + settledPrefetchItems( + items = items, + rawFocusedContentId = "missing", + settledContentId = "missing", + ).isEmpty(), + ) + } + + private fun item(id: String) = SectionItem( + contentId = id, + type = "movie", + title = id, + ) +} From 408fd3667d31d4abc8a422a19f1840573b581061 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Mon, 27 Jul 2026 23:38:17 +0200 Subject: [PATCH 06/65] fix(tv): enter for-you rows from filter controls --- .../TvRecommendationsFocusBridge.kt | 17 +++++ .../TvRecommendationsScreen.kt | 60 ++++++++++++++-- .../TvRecommendationsFocusBridgeTest.kt | 68 +++++++++++++++++++ 3 files changed, 140 insertions(+), 5 deletions(-) create mode 100644 androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvRecommendationsFocusBridge.kt create mode 100644 androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvRecommendationsFocusBridgeTest.kt diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvRecommendationsFocusBridge.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvRecommendationsFocusBridge.kt new file mode 100644 index 0000000000..e8fada8c87 --- /dev/null +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvRecommendationsFocusBridge.kt @@ -0,0 +1,17 @@ +package org.siloserver.silo.tv.ui.screens.recommendations + +internal suspend fun requestRecommendationRowFocus( + requestRowContainer: () -> Boolean, + awaitFrame: suspend () -> Unit, + requestFirstCard: () -> Boolean, +): Boolean { + if (!requestRowContainer()) return false + awaitFrame() + requestFirstCard() + return true +} + +internal fun shouldBridgeRecommendationsDown( + showingRecommendations: Boolean, + hasVisibleRecommendations: Boolean, +): Boolean = showingRecommendations && hasVisibleRecommendations diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvRecommendationsScreen.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvRecommendationsScreen.kt index 413fc4d5e9..66a7bbbef4 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvRecommendationsScreen.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvRecommendationsScreen.kt @@ -13,7 +13,7 @@ import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Bookmark import androidx.compose.material.icons.filled.Favorite @@ -24,7 +24,9 @@ import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue +import androidx.compose.runtime.withFrameNanos import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.focus.FocusRequester @@ -50,6 +52,7 @@ import org.siloserver.silo.tv.ui.theme.Spacing import org.siloserver.silo.tv.ui.util.visibleOnTv import org.siloserver.silo.viewmodel.RecommendationsViewModel import org.koin.compose.viewmodel.koinViewModel +import kotlinx.coroutines.launch private val RecommendationsFilterBandHeight = 52.dp @@ -69,8 +72,38 @@ fun TvRecommendationsScreen( ) { val state by viewModel.uiState.collectAsState() val visibleSections = remember(state.sections) { state.sections.visibleOnTv() } + val forYouFocusRequester = remember { FocusRequester() } val watchlistFocusRequester = remember { FocusRequester() } + val favoritesFocusRequester = remember { FocusRequester() } + val firstRecommendationRowFocusRequester = remember { FocusRequester() } + val firstRecommendationCardFocusRequester = remember { FocusRequester() } + val focusBridgeScope = rememberCoroutineScope() var savedListSelection by remember { mutableStateOf(null) } + val moveIntoRecommendations: () -> Boolean = { + if ( + !shouldBridgeRecommendationsDown( + showingRecommendations = savedListSelection == null, + hasVisibleRecommendations = visibleSections.isNotEmpty(), + ) + ) { + false + } else { + focusBridgeScope.launch { + requestRecommendationRowFocus( + requestRowContainer = { + runCatching { firstRecommendationRowFocusRequester.requestFocus() } + .getOrDefault(false) + }, + awaitFrame = { withFrameNanos { } }, + requestFirstCard = { + runCatching { firstRecommendationCardFocusRequester.requestFocus() } + .getOrDefault(false) + }, + ) + } + true + } + } // Match tvOS: recommendations remain the landing content when available; // an empty successful response defaults to the inline Watchlist fallback. @@ -183,16 +216,28 @@ fun TvRecommendationsScreen( bottom = 24.dp, ), ) { - items( + itemsIndexed( items = visibleSections, - key = { it.id }, - contentType = { "recommendation-section-row" }, - ) { section -> + key = { _, section -> section.id }, + contentType = { _, _ -> "recommendation-section-row" }, + ) { index, section -> TvMediaRow( title = section.title, items = section.items, onItemClick = onItemClick, style = TvRowStyle.Poster, + firstItemFocusRequester = firstRecommendationCardFocusRequester + .takeIf { index == 0 }, + rowContainerFocusRequester = firstRecommendationRowFocusRequester + .takeIf { index == 0 }, + onDirectionUp = if (index == 0) { + { + runCatching { forYouFocusRequester.requestFocus() } + .getOrDefault(false) + } + } else { + null + }, ) } item { Spacer(modifier = Modifier.height(8.dp)) } @@ -230,6 +275,8 @@ fun TvRecommendationsScreen( icon = Icons.Outlined.AutoAwesome, variant = TvPillVariant.Hollow, selected = savedListSelection == null, + focusRequester = forYouFocusRequester, + onDirectionDown = moveIntoRecommendations, heightOverride = 32.dp, horizontalPaddingOverride = 13.dp, iconSizeOverride = 10.dp, @@ -251,6 +298,7 @@ fun TvRecommendationsScreen( variant = TvPillVariant.Hollow, selected = savedListSelection == SavedListSelection.Watchlist, focusRequester = watchlistFocusRequester, + onDirectionDown = moveIntoRecommendations, heightOverride = 32.dp, horizontalPaddingOverride = 13.dp, iconSizeOverride = 10.dp, @@ -271,6 +319,8 @@ fun TvRecommendationsScreen( icon = Icons.Filled.Favorite, variant = TvPillVariant.Hollow, selected = savedListSelection == SavedListSelection.Favorites, + focusRequester = favoritesFocusRequester, + onDirectionDown = moveIntoRecommendations, heightOverride = 32.dp, horizontalPaddingOverride = 13.dp, iconSizeOverride = 10.dp, diff --git a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvRecommendationsFocusBridgeTest.kt b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvRecommendationsFocusBridgeTest.kt new file mode 100644 index 0000000000..cce86911c8 --- /dev/null +++ b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvRecommendationsFocusBridgeTest.kt @@ -0,0 +1,68 @@ +package org.siloserver.silo.tv.ui.screens.recommendations + +import kotlinx.coroutines.test.runTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class TvRecommendationsFocusBridgeTest { + + @Test + fun handoffCrossesRowRestorerBeforeTargetingFirstCard() = runTest { + val events = mutableListOf() + + val handled = requestRecommendationRowFocus( + requestRowContainer = { events += "row"; true }, + awaitFrame = { events += "frame" }, + requestFirstCard = { events += "card"; true }, + ) + + assertTrue(handled) + assertEquals(listOf("row", "frame", "card"), events) + } + + @Test + fun rejectedRowHopDoesNotTargetCard() = runTest { + val events = mutableListOf() + + val handled = requestRecommendationRowFocus( + requestRowContainer = { events += "row"; false }, + awaitFrame = { events += "frame" }, + requestFirstCard = { events += "card"; true }, + ) + + assertFalse(handled) + assertEquals(listOf("row"), events) + } + + @Test + fun forYouWithVisibleRowsUsesTheBridge() { + assertTrue( + shouldBridgeRecommendationsDown( + showingRecommendations = true, + hasVisibleRecommendations = true, + ), + ) + } + + @Test + fun savedListsKeepTheirExistingGridNavigation() { + assertFalse( + shouldBridgeRecommendationsDown( + showingRecommendations = false, + hasVisibleRecommendations = true, + ), + ) + } + + @Test + fun loadingOrEmptyForYouDoesNotTargetAnAbsentRow() { + assertFalse( + shouldBridgeRecommendationsDown( + showingRecommendations = true, + hasVisibleRecommendations = false, + ), + ) + } +} From a69b5c0e73be56345698eb1e45ee4afa13783c07 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Mon, 27 Jul 2026 23:48:52 +0200 Subject: [PATCH 07/65] fix(tv): close cold navigation review gaps --- .../tv/ui/components/TvFocusMarqueeModel.kt | 7 +- .../ui/components/TvSkylinePrefetchPolicy.kt | 16 +++++ .../tv/ui/components/TvSkylineSectionFeed.kt | 14 ++-- .../TvFocusMarqueeEnrichmentTest.kt | 18 +++++ .../components/TvSkylinePrefetchPolicyTest.kt | 32 +++++++++ .../silo/repository/SectionRepository.kt | 56 +++++++++++++-- .../repository/SectionRepositoryCacheTest.kt | 70 +++++++++++++++++++ 7 files changed, 204 insertions(+), 9 deletions(-) diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeModel.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeModel.kt index 82bc163ca5..273e67a713 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeModel.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeModel.kt @@ -287,6 +287,9 @@ class TvFocusMarqueeState internal constructor() { internal var candidate: TvMarqueeContent? by mutableStateOf(null) + internal var hasRealCardFocus: Boolean by mutableStateOf(false) + private set + /** Per-contentId enrichment cache (tvOS `enrichmentCache`) so scrubbing * back over a row never refetches item detail. Persists for the page. */ private val enrichmentCache = mutableMapOf() @@ -294,6 +297,7 @@ class TvFocusMarqueeState internal constructor() { /** Report card focus. The displayed content swaps on the next composition turn. */ fun preview(item: SectionItem, rowTitle: String) { + hasRealCardFocus = true val next = TvMarqueeContent.from(item, rowTitle) // Focus is back on the already-displayed card: cancel any pending swap // so a brief A→B→A scrub within the debounce window can't commit a @@ -377,8 +381,9 @@ fun rememberTvFocusMarqueeState( // Populate the cache and enrich the active hero when identity still // matches. Near-viewport proactive prefetch usually wins this request; the // shared claim prevents duplicates when it is already in flight. - LaunchedEffect(state.content?.contentId, fetchDetail) { + LaunchedEffect(state.content?.contentId, state.hasRealCardFocus, fetchDetail) { val fetch = fetchDetail ?: return@LaunchedEffect + if (!state.hasRealCardFocus) return@LaunchedEffect val contentId = state.content?.contentId ?: return@LaunchedEffect if (!state.beginEnrichmentRequest(contentId)) return@LaunchedEffect try { diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylinePrefetchPolicy.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylinePrefetchPolicy.kt index 250ee02784..06d1f55a83 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylinePrefetchPolicy.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylinePrefetchPolicy.kt @@ -2,6 +2,22 @@ package org.siloserver.silo.tv.ui.components import org.siloserver.silo.model.section.SectionItem +internal data class TvSkylineSettledFocus( + val rowIndex: Int, + val contentId: String, +) + +internal fun settledFocusIdentity( + rawRowIndex: Int, + rawFocusedContentId: String?, + settledContentId: String?, +): TvSkylineSettledFocus? { + if (rawRowIndex < 0 || rawFocusedContentId == null || rawFocusedContentId != settledContentId) { + return null + } + return TvSkylineSettledFocus(rawRowIndex, rawFocusedContentId) +} + internal fun settledPrefetchItems( items: List, rawFocusedContentId: String?, diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylineSectionFeed.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylineSectionFeed.kt index 1486aee5bf..0e419f970d 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylineSectionFeed.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylineSectionFeed.kt @@ -186,12 +186,18 @@ fun TvSkylineSectionFeed( // Keep a small window around RESTED focus hot. A raw D-pad move cancels the // previous job immediately, but the new identity starts no speculative // work until the marquee's focus-rest transaction commits it. - LaunchedEffect(rows, focusedContentId, marquee.content?.contentId, fetchDetail) { - val row = rows.getOrNull(focusedRowIndex) ?: return@LaunchedEffect + val settledFocus = settledFocusIdentity( + rawRowIndex = focusedRowIndex, + rawFocusedContentId = focusedContentId, + settledContentId = marquee.content?.contentId, + ) + LaunchedEffect(rows, settledFocus, fetchDetail) { + val focus = settledFocus ?: return@LaunchedEffect + val row = rows.getOrNull(focus.rowIndex) ?: return@LaunchedEffect val window = settledPrefetchItems( items = row.items, - rawFocusedContentId = focusedContentId, - settledContentId = marquee.content?.contentId, + rawFocusedContentId = focus.contentId, + settledContentId = focus.contentId, radius = HeroFocusPrefetchRadius, ) if (window.isEmpty()) return@LaunchedEffect diff --git a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeEnrichmentTest.kt b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeEnrichmentTest.kt index 91a1b946ab..caa0c97e96 100644 --- a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeEnrichmentTest.kt +++ b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeEnrichmentTest.kt @@ -4,7 +4,9 @@ import org.siloserver.silo.model.catalog.CastMember import org.siloserver.silo.model.catalog.ItemDetail import org.siloserver.silo.model.section.SectionItem import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue import org.junit.Test /** @@ -166,6 +168,22 @@ class TvFocusMarqueeEnrichmentTest { assertEquals("https://art/first.jpg", state.content?.heroBackdropUrl) } + @Test + fun `initial seed does not enable network enrichment until real focus`() { + val state = TvFocusMarqueeState() + val first = SectionItem( + contentId = "first", + type = "movie", + title = "First Movie", + ) + + state.seedInitialPreview(first, "Continue Watching") + assertFalse(state.hasRealCardFocus) + + state.preview(first, "Continue Watching") + assertTrue(state.hasRealCardFocus) + } + @Test fun `active enrichment publishes immediately`() { val state = TvFocusMarqueeState() diff --git a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvSkylinePrefetchPolicyTest.kt b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvSkylinePrefetchPolicyTest.kt index e764ac0b27..6263c01a18 100644 --- a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvSkylinePrefetchPolicyTest.kt +++ b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvSkylinePrefetchPolicyTest.kt @@ -54,6 +54,38 @@ class TvSkylinePrefetchPolicyTest { ) } + @Test + fun sameContentInDifferentRowsHasDifferentSettledIdentity() { + assertEquals( + TvSkylineSettledFocus(rowIndex = 0, contentId = "a"), + settledFocusIdentity( + rawRowIndex = 0, + rawFocusedContentId = "a", + settledContentId = "a", + ), + ) + assertEquals( + TvSkylineSettledFocus(rowIndex = 1, contentId = "a"), + settledFocusIdentity( + rawRowIndex = 1, + rawFocusedContentId = "a", + settledContentId = "a", + ), + ) + } + + @Test + fun unsettledFocusHasNoPrefetchIdentity() { + assertEquals( + null, + settledFocusIdentity( + rawRowIndex = 1, + rawFocusedContentId = "b", + settledContentId = "a", + ), + ) + } + private fun item(id: String) = SectionItem( contentId = id, type = "movie", diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/repository/SectionRepository.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/repository/SectionRepository.kt index 0f32adb409..8c178da7e6 100644 --- a/shared/src/commonMain/kotlin/org/siloserver/silo/repository/SectionRepository.kt +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/repository/SectionRepository.kt @@ -12,23 +12,71 @@ import org.siloserver.silo.network.map import org.siloserver.silo.repository.port.CatalogCachePort import org.siloserver.silo.repository.port.NoOpCatalogCachePort import org.siloserver.silo.repository.port.canServeCache +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock class SectionRepository( private val sectionApi: SectionApi, /** Offline read cache for a library's Recommended sections (Track B). No-op by default. */ private val catalogCache: CatalogCachePort = NoOpCatalogCachePort, ) { + private val homeRequestMutex = Mutex() + private var homeSectionsInFlight: CompletableDeferred>? = null + private val homeSectionItemsInFlight = + mutableMapOf>>() + /** Fetches the home screen layout configuration. */ suspend fun getHomeLayout(): ApiResult = sectionApi.getHomeLayout() /** Fetches all home screen sections (with items pre-resolved). */ - suspend fun getHomeSections(): ApiResult = - sectionApi.getHomeSections() + suspend fun getHomeSections(): ApiResult { + val (request, ownsRequest) = homeRequestMutex.withLock { + homeSectionsInFlight?.let { it to false } + ?: CompletableDeferred>().let { + homeSectionsInFlight = it + it to true + } + } + if (!ownsRequest) return request.await() + + return try { + sectionApi.getHomeSections().also(request::complete) + } catch (throwable: Throwable) { + request.completeExceptionally(throwable) + throw throwable + } finally { + homeRequestMutex.withLock { + if (homeSectionsInFlight === request) homeSectionsInFlight = null + } + } + } /** Fetches the items within a specific home section. */ - suspend fun getHomeSectionItems(sectionId: String): ApiResult = - sectionApi.getHomeSectionItems(sectionId) + suspend fun getHomeSectionItems(sectionId: String): ApiResult { + val (request, ownsRequest) = homeRequestMutex.withLock { + homeSectionItemsInFlight[sectionId]?.let { it to false } + ?: CompletableDeferred>().let { + homeSectionItemsInFlight[sectionId] = it + it to true + } + } + if (!ownsRequest) return request.await() + + return try { + sectionApi.getHomeSectionItems(sectionId).also(request::complete) + } catch (throwable: Throwable) { + request.completeExceptionally(throwable) + throw throwable + } finally { + homeRequestMutex.withLock { + if (homeSectionItemsInFlight[sectionId] === request) { + homeSectionItemsInFlight.remove(sectionId) + } + } + } + } /** Fetches a library's resolved sections (offline: last cached sections). */ suspend fun getLibrarySections(libraryId: Int): ApiResult { diff --git a/shared/src/commonTest/kotlin/org/siloserver/silo/repository/SectionRepositoryCacheTest.kt b/shared/src/commonTest/kotlin/org/siloserver/silo/repository/SectionRepositoryCacheTest.kt index 80243c20cb..79ed9b200f 100644 --- a/shared/src/commonTest/kotlin/org/siloserver/silo/repository/SectionRepositoryCacheTest.kt +++ b/shared/src/commonTest/kotlin/org/siloserver/silo/repository/SectionRepositoryCacheTest.kt @@ -13,7 +13,11 @@ import io.ktor.http.HttpHeaders import io.ktor.http.HttpStatusCode import io.ktor.http.headersOf import io.ktor.serialization.kotlinx.json.json +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitAll import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.yield import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertTrue @@ -68,4 +72,70 @@ class SectionRepositoryCacheTest { val result = repo(HttpStatusCode.NotFound, "{}", cache).getLibrarySections(7) assertTrue(result is ApiResult.Error) } + + @Test + fun concurrentHomeRequestsShareOneAggregateCall() = runTest { + var calls = 0 + val entered = CompletableDeferred() + val release = CompletableDeferred() + val client = HttpClient( + MockEngine { + calls += 1 + entered.complete(Unit) + release.await() + respond( + """{"sections":[]}""", + HttpStatusCode.OK, + headersOf(HttpHeaders.ContentType, "application/json"), + ) + }, + ) { + install(ContentNegotiation) { json(SiloJson) } + } + val repository = SectionRepository(SectionApi(client)) + + val requests = listOf( + async { repository.getHomeSections() }, + async { repository.getHomeSections() }, + ) + entered.await() + repeat(10) { yield() } + release.complete(Unit) + requests.awaitAll() + + assertEquals(1, calls) + } + + @Test + fun concurrentHomeItemRequestsShareOneCallPerSection() = runTest { + var calls = 0 + val entered = CompletableDeferred() + val release = CompletableDeferred() + val client = HttpClient( + MockEngine { + calls += 1 + entered.complete(Unit) + release.await() + respond( + """{"items":[],"total":0}""", + HttpStatusCode.OK, + headersOf(HttpHeaders.ContentType, "application/json"), + ) + }, + ) { + install(ContentNegotiation) { json(SiloJson) } + } + val repository = SectionRepository(SectionApi(client)) + + val requests = listOf( + async { repository.getHomeSectionItems("same") }, + async { repository.getHomeSectionItems("same") }, + ) + entered.await() + repeat(10) { yield() } + release.complete(Unit) + requests.awaitAll() + + assertEquals(1, calls) + } } From e7939f3c4e9ba267fd4c897dfbc689ad3bd2d4a3 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Mon, 27 Jul 2026 23:53:44 +0200 Subject: [PATCH 08/65] fix(tv): settle prefetch without caller races --- .../tv/ui/components/TvFocusMarqueeModel.kt | 27 ++++--- .../ui/components/TvSkylinePrefetchPolicy.kt | 10 ++- .../tv/ui/components/TvSkylineSectionFeed.kt | 20 +++-- .../TvFocusMarqueeEnrichmentTest.kt | 21 ++++- .../components/TvSkylinePrefetchPolicyTest.kt | 15 ++-- .../silo/repository/SectionRepository.kt | 78 ++++++++++--------- .../repository/SectionRepositoryCacheTest.kt | 35 +++++++++ 7 files changed, 143 insertions(+), 63 deletions(-) diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeModel.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeModel.kt index 273e67a713..c79442dff4 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeModel.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeModel.kt @@ -75,7 +75,11 @@ data class TvMarqueeContent( } companion object { - fun from(item: SectionItem, rowTitle: String): TvMarqueeContent { + fun from( + item: SectionItem, + rowTitle: String, + rowIdentity: String = rowTitle, + ): TvMarqueeContent { val isEpisode = item.type.equals("episode", ignoreCase = true) val meta = mutableListOf() @@ -100,7 +104,7 @@ data class TvMarqueeContent( val sectionBackdropUrl = item.backdropUrl?.takeIf { it.isNotBlank() } val sectionPosterUrl = item.posterUrl?.takeIf { it.isNotBlank() } return TvMarqueeContent( - id = "$rowTitle#${item.contentId}", + id = "$rowIdentity#${item.contentId}", title = if (isEpisode) (item.seriesTitle ?: item.title) else item.title, logoUrl = item.logoUrl?.takeIf { it.isNotBlank() }, badges = badges, @@ -287,18 +291,21 @@ class TvFocusMarqueeState internal constructor() { internal var candidate: TvMarqueeContent? by mutableStateOf(null) - internal var hasRealCardFocus: Boolean by mutableStateOf(false) + internal var focusedMarqueeId: String? by mutableStateOf(null) private set + internal val hasSettledRealFocus: Boolean + get() = focusedMarqueeId != null && focusedMarqueeId == content?.id + /** Per-contentId enrichment cache (tvOS `enrichmentCache`) so scrubbing * back over a row never refetches item detail. Persists for the page. */ private val enrichmentCache = mutableMapOf() private val enrichmentRequests = mutableSetOf() /** Report card focus. The displayed content swaps on the next composition turn. */ - fun preview(item: SectionItem, rowTitle: String) { - hasRealCardFocus = true - val next = TvMarqueeContent.from(item, rowTitle) + fun preview(item: SectionItem, rowTitle: String, rowIdentity: String = rowTitle) { + val next = TvMarqueeContent.from(item, rowTitle, rowIdentity) + focusedMarqueeId = next.id // Focus is back on the already-displayed card: cancel any pending swap // so a brief A→B→A scrub within the debounce window can't commit a // stale B after focus has returned to A. @@ -314,9 +321,9 @@ class TvFocusMarqueeState internal constructor() { * is only for page entry: once focus has produced displayed or pending * content, the seed is ignored so it never fights real navigation. */ - fun seedInitialPreview(item: SectionItem, rowTitle: String) { + fun seedInitialPreview(item: SectionItem, rowTitle: String, rowIdentity: String = rowTitle) { if (content != null || candidate != null) return - candidate = TvMarqueeContent.from(item, rowTitle) + candidate = TvMarqueeContent.from(item, rowTitle, rowIdentity) } internal fun commit(value: TvMarqueeContent?) { @@ -381,9 +388,9 @@ fun rememberTvFocusMarqueeState( // Populate the cache and enrich the active hero when identity still // matches. Near-viewport proactive prefetch usually wins this request; the // shared claim prevents duplicates when it is already in flight. - LaunchedEffect(state.content?.contentId, state.hasRealCardFocus, fetchDetail) { + LaunchedEffect(state.content?.id, state.focusedMarqueeId, fetchDetail) { val fetch = fetchDetail ?: return@LaunchedEffect - if (!state.hasRealCardFocus) return@LaunchedEffect + if (!state.hasSettledRealFocus) return@LaunchedEffect val contentId = state.content?.contentId ?: return@LaunchedEffect if (!state.beginEnrichmentRequest(contentId)) return@LaunchedEffect try { diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylinePrefetchPolicy.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylinePrefetchPolicy.kt index 06d1f55a83..2c224f4278 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylinePrefetchPolicy.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylinePrefetchPolicy.kt @@ -10,9 +10,15 @@ internal data class TvSkylineSettledFocus( internal fun settledFocusIdentity( rawRowIndex: Int, rawFocusedContentId: String?, - settledContentId: String?, + rawFocusedMarqueeId: String?, + settledMarqueeId: String?, ): TvSkylineSettledFocus? { - if (rawRowIndex < 0 || rawFocusedContentId == null || rawFocusedContentId != settledContentId) { + if ( + rawRowIndex < 0 || + rawFocusedContentId == null || + rawFocusedMarqueeId == null || + rawFocusedMarqueeId != settledMarqueeId + ) { return null } return TvSkylineSettledFocus(rawRowIndex, rawFocusedContentId) diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylineSectionFeed.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylineSectionFeed.kt index 0e419f970d..bf114b0f05 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylineSectionFeed.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylineSectionFeed.kt @@ -106,7 +106,11 @@ fun TvSkylineSectionFeed( val initialMarqueeSeed = remember(rows) { rows.firstOrNull()?.let { section -> section.items.firstOrNull()?.let { item -> - TvSkylineMarqueeSeed(item = item, rowTitle = section.title) + TvSkylineMarqueeSeed( + item = item, + rowTitle = section.title, + rowIdentity = section.id, + ) } } } @@ -114,7 +118,7 @@ fun TvSkylineSectionFeed( LaunchedEffect(initialMarqueeSeed?.item?.contentId, initialMarqueeSeed?.rowTitle) { val seed = initialMarqueeSeed ?: return@LaunchedEffect if (marquee.content == null) { - marquee.seedInitialPreview(seed.item, seed.rowTitle) + marquee.seedInitialPreview(seed.item, seed.rowTitle, seed.rowIdentity) } } @@ -165,8 +169,9 @@ fun TvSkylineSectionFeed( val rowBandScope = rememberCoroutineScope() // Skyline matches tvOS' view-aligned row stack: vertical motion is owned by // this feed, while each row's LazyRow still handles horizontal card scroll. - val onItemFocused: (SectionItem, String, Int, Int) -> Unit = { item, rowTitle, rowIndex, itemIndex -> - marquee.preview(item, rowTitle) + val onItemFocused: (SectionItem, String, String, Int, Int) -> Unit = + { item, rowTitle, rowIdentity, rowIndex, itemIndex -> + marquee.preview(item, rowTitle, rowIdentity) focusedRowIndex = rowIndex focusedItemIndex = itemIndex focusedContentId = item.contentId @@ -189,7 +194,9 @@ fun TvSkylineSectionFeed( val settledFocus = settledFocusIdentity( rawRowIndex = focusedRowIndex, rawFocusedContentId = focusedContentId, - settledContentId = marquee.content?.contentId, + rawFocusedMarqueeId = rows.getOrNull(focusedRowIndex) + ?.let { row -> focusedContentId?.let { contentId -> "${row.id}#$contentId" } }, + settledMarqueeId = marquee.content?.id, ) LaunchedEffect(rows, settledFocus, fetchDetail) { val focus = settledFocus ?: return@LaunchedEffect @@ -616,7 +623,7 @@ fun TvSkylineSectionFeed( restoreFocusRequester = detailReturnItemFocusRequester .takeIf { isReturnRow }, onItemFocusedAtIndex = { item, itemIndex -> - onItemFocused(item, section.title, rowIndex, itemIndex) + onItemFocused(item, section.title, section.id, rowIndex, itemIndex) }, cardActions = { item -> cardActions(section, item) }, ) @@ -639,6 +646,7 @@ fun ResolvedSection.isTvProgressRow(): Boolean { private data class TvSkylineMarqueeSeed( val item: SectionItem, val rowTitle: String, + val rowIdentity: String, ) // 0.64 × 1920 by 0.70 × 1080, and the 440×100dp logo cap at 2× density. diff --git a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeEnrichmentTest.kt b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeEnrichmentTest.kt index caa0c97e96..9b854e28e8 100644 --- a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeEnrichmentTest.kt +++ b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeEnrichmentTest.kt @@ -178,10 +178,27 @@ class TvFocusMarqueeEnrichmentTest { ) state.seedInitialPreview(first, "Continue Watching") - assertFalse(state.hasRealCardFocus) + state.commit(state.candidate) + assertFalse(state.hasSettledRealFocus) state.preview(first, "Continue Watching") - assertTrue(state.hasRealCardFocus) + assertTrue(state.hasSettledRealFocus) + } + + @Test + fun `new raw focus does not enrich the old seed before settlement`() { + val state = TvFocusMarqueeState() + val first = SectionItem(contentId = "first", type = "movie", title = "First") + val second = SectionItem(contentId = "second", type = "movie", title = "Second") + + state.seedInitialPreview(first, "First row", rowIdentity = "row-1") + state.commit(state.candidate) + state.preview(second, "Second row", rowIdentity = "row-2") + + assertFalse(state.hasSettledRealFocus) + + state.commit(state.candidate) + assertTrue(state.hasSettledRealFocus) } @Test diff --git a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvSkylinePrefetchPolicyTest.kt b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvSkylinePrefetchPolicyTest.kt index 6263c01a18..cca143cb65 100644 --- a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvSkylinePrefetchPolicyTest.kt +++ b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvSkylinePrefetchPolicyTest.kt @@ -55,13 +55,14 @@ class TvSkylinePrefetchPolicyTest { } @Test - fun sameContentInDifferentRowsHasDifferentSettledIdentity() { + fun sameContentInDifferentRowWaitsForRowQualifiedSettlement() { assertEquals( - TvSkylineSettledFocus(rowIndex = 0, contentId = "a"), + null, settledFocusIdentity( - rawRowIndex = 0, + rawRowIndex = 1, rawFocusedContentId = "a", - settledContentId = "a", + rawFocusedMarqueeId = "row-1#a", + settledMarqueeId = "row-0#a", ), ) assertEquals( @@ -69,7 +70,8 @@ class TvSkylinePrefetchPolicyTest { settledFocusIdentity( rawRowIndex = 1, rawFocusedContentId = "a", - settledContentId = "a", + rawFocusedMarqueeId = "row-1#a", + settledMarqueeId = "row-1#a", ), ) } @@ -81,7 +83,8 @@ class TvSkylinePrefetchPolicyTest { settledFocusIdentity( rawRowIndex = 1, rawFocusedContentId = "b", - settledContentId = "a", + rawFocusedMarqueeId = "row-1#b", + settledMarqueeId = "row-0#a", ), ) } diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/repository/SectionRepository.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/repository/SectionRepository.kt index 8c178da7e6..c451df1d79 100644 --- a/shared/src/commonMain/kotlin/org/siloserver/silo/repository/SectionRepository.kt +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/repository/SectionRepository.kt @@ -12,7 +12,12 @@ import org.siloserver.silo.network.map import org.siloserver.silo.repository.port.CatalogCachePort import org.siloserver.silo.repository.port.NoOpCatalogCachePort import org.siloserver.silo.repository.port.canServeCache -import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.Deferred +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.async import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock @@ -21,10 +26,11 @@ class SectionRepository( /** Offline read cache for a library's Recommended sections (Track B). No-op by default. */ private val catalogCache: CatalogCachePort = NoOpCatalogCachePort, ) { + private val homeRequestScope = CoroutineScope(SupervisorJob() + Dispatchers.Default) private val homeRequestMutex = Mutex() - private var homeSectionsInFlight: CompletableDeferred>? = null + private var homeSectionsInFlight: Deferred>? = null private val homeSectionItemsInFlight = - mutableMapOf>>() + mutableMapOf>>() /** Fetches the home screen layout configuration. */ suspend fun getHomeLayout(): ApiResult = @@ -32,50 +38,48 @@ class SectionRepository( /** Fetches all home screen sections (with items pre-resolved). */ suspend fun getHomeSections(): ApiResult { - val (request, ownsRequest) = homeRequestMutex.withLock { - homeSectionsInFlight?.let { it to false } - ?: CompletableDeferred>().let { - homeSectionsInFlight = it - it to true + val request = homeRequestMutex.withLock { + homeSectionsInFlight ?: run { + lateinit var created: Deferred> + created = homeRequestScope.async(start = CoroutineStart.LAZY) { + try { + sectionApi.getHomeSections() + } finally { + homeRequestMutex.withLock { + if (homeSectionsInFlight === created) homeSectionsInFlight = null + } + } } - } - if (!ownsRequest) return request.await() - - return try { - sectionApi.getHomeSections().also(request::complete) - } catch (throwable: Throwable) { - request.completeExceptionally(throwable) - throw throwable - } finally { - homeRequestMutex.withLock { - if (homeSectionsInFlight === request) homeSectionsInFlight = null + homeSectionsInFlight = created + created.start() + created } } + return request.await() } /** Fetches the items within a specific home section. */ suspend fun getHomeSectionItems(sectionId: String): ApiResult { - val (request, ownsRequest) = homeRequestMutex.withLock { - homeSectionItemsInFlight[sectionId]?.let { it to false } - ?: CompletableDeferred>().let { - homeSectionItemsInFlight[sectionId] = it - it to true - } - } - if (!ownsRequest) return request.await() - - return try { - sectionApi.getHomeSectionItems(sectionId).also(request::complete) - } catch (throwable: Throwable) { - request.completeExceptionally(throwable) - throw throwable - } finally { - homeRequestMutex.withLock { - if (homeSectionItemsInFlight[sectionId] === request) { - homeSectionItemsInFlight.remove(sectionId) + val request = homeRequestMutex.withLock { + homeSectionItemsInFlight[sectionId] ?: run { + lateinit var created: Deferred> + created = homeRequestScope.async(start = CoroutineStart.LAZY) { + try { + sectionApi.getHomeSectionItems(sectionId) + } finally { + homeRequestMutex.withLock { + if (homeSectionItemsInFlight[sectionId] === created) { + homeSectionItemsInFlight.remove(sectionId) + } + } + } } + homeSectionItemsInFlight[sectionId] = created + created.start() + created } } + return request.await() } /** Fetches a library's resolved sections (offline: last cached sections). */ diff --git a/shared/src/commonTest/kotlin/org/siloserver/silo/repository/SectionRepositoryCacheTest.kt b/shared/src/commonTest/kotlin/org/siloserver/silo/repository/SectionRepositoryCacheTest.kt index 79ed9b200f..5b2ddc7aff 100644 --- a/shared/src/commonTest/kotlin/org/siloserver/silo/repository/SectionRepositoryCacheTest.kt +++ b/shared/src/commonTest/kotlin/org/siloserver/silo/repository/SectionRepositoryCacheTest.kt @@ -16,6 +16,8 @@ import io.ktor.serialization.kotlinx.json.json import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.launch import kotlinx.coroutines.test.runTest import kotlinx.coroutines.yield import kotlin.test.Test @@ -138,4 +140,37 @@ class SectionRepositoryCacheTest { assertEquals(1, calls) } + + @Test + fun cancelingFirstHomeCallerDoesNotCancelSharedRequestOrPoisonNextCall() = runTest { + var calls = 0 + val entered = CompletableDeferred() + val release = CompletableDeferred() + val client = HttpClient( + MockEngine { + calls += 1 + entered.complete(Unit) + release.await() + respond( + """{"sections":[]}""", + HttpStatusCode.OK, + headersOf(HttpHeaders.ContentType, "application/json"), + ) + }, + ) { + install(ContentNegotiation) { json(SiloJson) } + } + val repository = SectionRepository(SectionApi(client)) + + val firstCaller = launch { repository.getHomeSections() } + entered.await() + val survivingCaller = async { repository.getHomeSections() } + repeat(10) { yield() } + firstCaller.cancelAndJoin() + release.complete(Unit) + + assertTrue(survivingCaller.await() is ApiResult.Success) + assertTrue(repository.getHomeSections() is ApiResult.Success) + assertEquals(2, calls) + } } From e32ced559a193dfd6ebb696532c905bd54cb4ba3 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 00:54:25 +0200 Subject: [PATCH 09/65] docs(tv): define navigation follow-up behavior --- ...ndroid-tv-navigation-remediation-design.md | 41 +++++++++++++++++-- 1 file changed, 38 insertions(+), 3 deletions(-) diff --git a/docs/superpowers/specs/2026-07-27-android-tv-navigation-remediation-design.md b/docs/superpowers/specs/2026-07-27-android-tv-navigation-remediation-design.md index a2ac0d330a..b69f2e7f64 100644 --- a/docs/superpowers/specs/2026-07-27-android-tv-navigation-remediation-design.md +++ b/docs/superpowers/specs/2026-07-27-android-tv-navigation-remediation-design.md @@ -72,7 +72,32 @@ continues to focus Watchlist, preserving current product behavior. The handoff will reuse the established `TvMediaRow` requester contract rather than introducing a second focus-navigation architecture. -### 2. Resolve Home once, hydrate only missing sections +### 2. Deliberate Home-to-menu focus boundary + +Rapid or held Up input must traverse Home rows one at a time and stop on the +first content row. Reaching that row as part of the same repeated-key sequence +must not immediately move focus into the top menu. A new Up press after the +remote key has been released may enter the selected top-menu item. + +The Skyline row band will continue to own off-screen row relocation. It will +serialize that relocation so overlapping key-repeat events cannot start +competing scroll jobs or consume more row transitions than completed focus +moves. The shell remains the only owner of the final content-to-menu handoff. + +### 3. Unify For You saved-list presentation + +Watchlist and Favorites chosen from the For You top-menu selector will open the +existing `TvRecommendationsScreen` with the matching saved-list pill selected. +They will therefore use the same filter band, inline grid, spacing, focus +behavior, and Back destination as choosing those pills after entering For You. + +Watchlist and Favorites chosen from the profile menu remain standalone utility +pages. This preserves their established account-navigation role and avoids +turning every saved-list deep link into a For You route. No repository, server, +or personal-data behavior changes; both presentations continue to use the +existing `WatchlistViewModel` and `FavoritesViewModel`. + +### 4. Resolve Home once, hydrate only missing sections Extract a small, platform-neutral Home hydration operation that: @@ -90,7 +115,7 @@ will no longer refetch every inline section. The activity warmup remains best-effort and non-blocking. This change does not make splash dismissal wait for Home. -### 3. Remove page-entry detail fan-out +### 5. Remove page-entry detail fan-out `TvSkylineSectionFeed` will not eagerly fetch full detail or hero-sized artwork for the first sixteen cards merely because rows entered composition. Startup @@ -110,7 +135,7 @@ focused identity rather than every intermediate D-pad position. It will: Opening an item-detail screen keeps its existing network-first freshness semantics. Cache-first behavior applies only to speculative marquee enrichment. -### 4. Cache and dispatcher boundaries +### 6. Cache and dispatcher boundaries Room remains the profile/server-scoped source for offline Home and item-detail snapshots. The fix will not alter cache schema or migration state. @@ -138,6 +163,11 @@ Behavioral tests will cover: - Down from each For You filter pill, Up return, repeated movement, and loading/error/empty states; +- rapid and held Up sequences stopping on Home's first content row, followed + by a fresh Up press entering the selected top-menu item; +- For You selector Watchlist/Favorites opening the same inline presentation + and selected pill as in-page selection, while profile-menu routes remain + standalone; - inline Home sections causing zero per-section fallback requests; - missing sections being hydrated correctly with at most four concurrent requests; @@ -170,6 +200,11 @@ requires: full network and image latency. - **Timeout or animation tuning:** does not address the measured cold request fan-out. +- **Making all Watchlist/Favorites routes inline:** would change profile-menu + and deep-link semantics to solve a mismatch limited to the For You selector. +- **Debouncing all Up input:** would make ordinary row traversal feel laggy; + only the asynchronous row relocation and content/menu boundary need + sequencing. ## Scope Boundaries From 4c411aa070d6c84c60a0c2e5da021210c0fd9ca7 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 00:56:19 +0200 Subject: [PATCH 10/65] docs(tv): plan navigation follow-up fixes --- ...07-27-android-tv-navigation-remediation.md | 367 +++++++++++++++++- 1 file changed, 357 insertions(+), 10 deletions(-) diff --git a/docs/superpowers/plans/2026-07-27-android-tv-navigation-remediation.md b/docs/superpowers/plans/2026-07-27-android-tv-navigation-remediation.md index 0bd5ef180f..dfcac6d9b5 100644 --- a/docs/superpowers/plans/2026-07-27-android-tv-navigation-remediation.md +++ b/docs/superpowers/plans/2026-07-27-android-tv-navigation-remediation.md @@ -2,9 +2,9 @@ > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. -**Goal:** Restore D-pad access to Android TV For You rows and remove the duplicate, eager cold-start work that makes first Home traversal sluggish on production-sized servers. +**Goal:** Restore predictable Android TV navigation, unify For You saved-list presentation, and remove the duplicate, eager cold-start work that makes first Home traversal sluggish on production-sized servers. -**Architecture:** A shared pure Home hydrator will consume inline aggregate sections and make at most four fallback requests for genuinely unresolved sections. Android TV will use an explicit two-frame focus bridge into recommendation rows and a small pure prefetch policy that permits neighbor work only after focus has settled; speculative detail reads become cache-first while item-detail screens remain network-first. +**Architecture:** A shared pure Home hydrator will consume inline aggregate sections and make at most four fallback requests for genuinely unresolved sections. Android TV will use explicit focus policies for recommendation entry and the Home-to-menu boundary, plus a small pure prefetch policy that permits neighbor work only after focus has settled. The For You selector will issue an explicit, repeatable inline-selection request to the existing For You screen; profile-menu saved-list routes remain standalone. **Tech Stack:** Kotlin Multiplatform, Kotlin coroutines and `kotlinx-coroutines-test`, Compose for TV focus APIs, Ktor `MockEngine`, Room-backed cache ports, Gradle Android unit/release tasks, ADB/gfxinfo for the final Shield smoke. @@ -12,6 +12,9 @@ - Do not change server APIs, server configuration, recommendation ranking, Home row composition, authentication, playback, or database schema. - Preserve Watchlist and Favorites behavior and the existing initial Watchlist focus. +- A repeated/held Up sequence stops on Home's first content row; only a fresh Up press enters the top menu. +- Watchlist and Favorites selected from the For You top-menu selector use the existing inline For You presentation. +- Watchlist and Favorites selected from the profile menu remain standalone utility pages. - Preserve partial-refresh cache safety: an incomplete network result must not overwrite a complete cached Home. - Keep item-detail screens network-first; cache-first semantics apply only to speculative marquee enrichment. - Limit fallback Home hydration and speculative detail fan-out to four concurrent requests. @@ -476,7 +479,339 @@ git add androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/re git commit -m "fix(tv): enter for-you rows from filter controls" ``` -### Task 5: Full verification, production-shaped smoke, and executive summary +### Task 5: Make the Home-to-menu boundary deliberate + +**Files:** +- Create: `androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylineUpNavigation.kt` +- Create: `androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvSkylineUpNavigationTest.kt` +- Modify: `androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylineSectionFeed.kt:277-318` +- Modify: `androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/home/TvHomeScreen.kt:38-216` +- Modify: `androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt:369-401,789-810` + +**Interfaces:** +- Consumes: `focusedRowIndex`, `rows.indices`, Android `KeyEvent.nativeKeyEvent.repeatCount`, and the existing shell-owned content-to-menu handoff. +- Produces: + +```kotlin +internal enum class TvSkylineUpAction { + EnterMenu, + StayInContent, + TryPreviousRow, +} + +internal fun tvSkylineUpAction( + currentRow: Int, + rowCount: Int, + isRepeat: Boolean, + relocationInFlight: Boolean, +): TvSkylineUpAction +``` + +The content fallback callback becomes `(isRepeat: Boolean) -> Boolean`. `true` +means the feed consumed the event; `false` means the shell may focus the top +menu. + +- [ ] **Step 1: Write the failing pure focus-boundary tests** + +Create `TvSkylineUpNavigationTest`: + +```kotlin +@Test +fun heldUpStopsOnFirstContentRow() { + assertEquals( + TvSkylineUpAction.StayInContent, + tvSkylineUpAction(currentRow = 0, rowCount = 6, isRepeat = true, relocationInFlight = false), + ) +} + +@Test +fun freshUpFromFirstContentRowMayEnterMenu() { + assertEquals( + TvSkylineUpAction.EnterMenu, + tvSkylineUpAction(currentRow = 0, rowCount = 6, isRepeat = false, relocationInFlight = false), + ) +} + +@Test +fun repeatedInputDuringOffscreenRelocationIsConsumed() { + assertEquals( + TvSkylineUpAction.StayInContent, + tvSkylineUpAction(currentRow = 4, rowCount = 6, isRepeat = true, relocationInFlight = true), + ) +} + +@Test +fun ordinaryUpWithinRowsTriesExactlyOnePreviousRow() { + assertEquals( + TvSkylineUpAction.TryPreviousRow, + tvSkylineUpAction(currentRow = 4, rowCount = 6, isRepeat = false, relocationInFlight = false), + ) +} +``` + +- [ ] **Step 2: Run the boundary tests and verify RED** + +Run: + +```bash +./gradlew :androidTvApp:testDebugUnitTest \ + --tests '*TvSkylineUpNavigationTest' \ + --max-workers=2 --no-daemon +``` + +Expected: compilation fails because `TvSkylineUpAction` and +`tvSkylineUpAction` do not exist. + +- [ ] **Step 3: Implement the pure policy** + +Create `TvSkylineUpNavigation.kt`: + +```kotlin +package org.siloserver.silo.tv.ui.components + +internal enum class TvSkylineUpAction { + EnterMenu, + StayInContent, + TryPreviousRow, +} + +internal fun tvSkylineUpAction( + currentRow: Int, + rowCount: Int, + isRepeat: Boolean, + relocationInFlight: Boolean, +): TvSkylineUpAction = when { + relocationInFlight -> TvSkylineUpAction.StayInContent + currentRow !in 0 until rowCount -> + if (isRepeat) TvSkylineUpAction.StayInContent else TvSkylineUpAction.EnterMenu + currentRow == 0 -> + if (isRepeat) TvSkylineUpAction.StayInContent else TvSkylineUpAction.EnterMenu + else -> TvSkylineUpAction.TryPreviousRow +} +``` + +- [ ] **Step 4: Run the pure tests and verify GREEN** + +Run the Step 2 command. Expected: all four tests pass. + +- [ ] **Step 5: Wire repeat identity and serialized relocation** + +Change `onContentUpFallbackChanged` through `TvHomeScreen`, +`TvHomeContent`, and `TvSkylineSectionFeed` to carry +`((isRepeat: Boolean) -> Boolean)`. + +In `TvSkylineSectionFeed`, remember `rowRelocationInFlight`. For +`TryPreviousRow`, first call `focusManager.moveFocus(FocusDirection.Up)`. If +that fails, set `rowRelocationInFlight = true`, launch exactly one +`animateScrollToItem(currentRow - 1)` job, await one frame, attempt the focus +move, and clear the flag in `finally`. `StayInContent` returns `true`; +`EnterMenu` returns `false`. + +In `TvMainShell`, pass: + +```kotlin +val isRepeat = ev.nativeKeyEvent.repeatCount > 0 +val contentHandledUp = contentUpFallback?.invoke(isRepeat) +``` + +Keep the shell's existing `focusState.requestMenuFocus()` behavior only when +the active feed returns `false`. + +- [ ] **Step 6: Run the boundary test and TV compilation** + +Run: + +```bash +./gradlew :androidTvApp:testDebugUnitTest \ + --tests '*TvSkylineUpNavigationTest' \ + :androidTvApp:compileDebugKotlin \ + --max-workers=2 --no-daemon +``` + +Expected: tests and compilation pass. + +- [ ] **Step 7: Commit Task 5** + +```bash +git add \ + androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylineUpNavigation.kt \ + androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylineSectionFeed.kt \ + androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/home/TvHomeScreen.kt \ + androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt \ + androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvSkylineUpNavigationTest.kt +git commit -m "fix(tv): stop held up at the first home row" +``` + +### Task 6: Route For You saved lists through one presentation + +**Files:** +- Create: `androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvForYouEntryRequest.kt` +- Create: `androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvForYouEntryRequestTest.kt` +- Create: `androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvForYouSelectorRoutingSourceTest.kt` +- Modify: `androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvRecommendationsScreen.kt:67-117` +- Modify: `androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt:971-976,1224-1242,1290-1307` + +**Interfaces:** +- Consumes: the existing `TvMainRoute.ForYou`, `TvRecommendationsScreen`, + `TvWatchlistInline`, `TvFavoritesInline`, and standalone profile-menu routes. +- Produces: + +```kotlin +internal enum class SavedListSelection { + Watchlist, + Favorites, +} + +internal data class TvForYouEntryRequest( + val sequence: Int = 0, + val selection: SavedListSelection? = null, +) { + fun next(selection: SavedListSelection?): TvForYouEntryRequest = + TvForYouEntryRequest(sequence = sequence + 1, selection = selection) +} +``` + +`TvRecommendationsScreen` accepts +`entryRequest: TvForYouEntryRequest = TvForYouEntryRequest()` and applies its +selection only when `entryRequest.sequence` changes. + +- [ ] **Step 1: Write the failing request-state tests** + +Create `TvForYouEntryRequestTest`: + +```kotlin +@Test +fun repeatedSelectionStillCreatesANewRequest() { + val first = TvForYouEntryRequest().next(SavedListSelection.Watchlist) + val second = first.next(SavedListSelection.Watchlist) + + assertEquals(1, first.sequence) + assertEquals(2, second.sequence) + assertEquals(SavedListSelection.Watchlist, second.selection) +} + +@Test +fun recommendationsRequestClearsSavedListSelection() { + val request = TvForYouEntryRequest( + sequence = 4, + selection = SavedListSelection.Favorites, + ).next(null) + + assertEquals(5, request.sequence) + assertNull(request.selection) +} +``` + +- [ ] **Step 2: Write the failing source-wiring test** + +Create `TvForYouSelectorRoutingSourceTest` that reads `TvMainShell.kt` and +asserts: + +```kotlin +assertTrue(shell.contains("openForYou(SavedListSelection.Watchlist)")) +assertTrue(shell.contains("openForYou(SavedListSelection.Favorites)")) +assertTrue(shell.contains("openForYou(null)")) +assertTrue(shell.contains("onWatchlist = closeMenuAnd {")) +assertTrue(shell.contains("navigateToSecondary(TvMainRoute.Watchlist.route)")) +assertTrue(shell.contains("onFavorites = closeMenuAnd {")) +assertTrue(shell.contains("navigateToSecondary(TvMainRoute.Favorites.route)")) +``` + +This locks the intended split: For You selector choices are inline, while +profile-menu choices remain standalone. + +- [ ] **Step 3: Run the request and wiring tests and verify RED** + +Run: + +```bash +./gradlew :androidTvApp:testDebugUnitTest \ + --tests '*TvForYouEntryRequestTest' \ + --tests '*TvForYouSelectorRoutingSourceTest' \ + --max-workers=2 --no-daemon +``` + +Expected: compilation fails because the request types do not exist; after those +types compile, the source assertions still fail until shell wiring changes. + +- [ ] **Step 4: Implement the repeatable entry request** + +Create `TvForYouEntryRequest.kt` with the exact interfaces above. Move +`SavedListSelection` out of `TvRecommendationsScreen.kt` into that file. + +Add the screen parameter: + +```kotlin +entryRequest: TvForYouEntryRequest = TvForYouEntryRequest(), +``` + +Initialize selection with `remember { mutableStateOf(entryRequest.selection) }` +and add: + +```kotlin +LaunchedEffect(entryRequest.sequence) { + if (entryRequest.sequence > 0) { + savedListSelection = entryRequest.selection + } +} +``` + +This permits the same top-menu choice to be selected repeatedly and does not +overwrite in-page pill changes during unrelated recompositions. + +- [ ] **Step 5: Wire only the For You selector to inline requests** + +In `TvMainShell`, remember: + +```kotlin +var forYouEntryRequest by remember { mutableStateOf(TvForYouEntryRequest()) } +val openForYou: (SavedListSelection?) -> Unit = { selection -> + forYouEntryRequest = forYouEntryRequest.next(selection) + focusState.closePanel(false) + navigateToSecondary(TvMainRoute.ForYou.route) + moveFocusToContent(TvMainRoute.ForYou.route) +} +``` + +Pass `entryRequest = forYouEntryRequest` to `TvRecommendationsScreen`. Wire +the three `TvForYouSelector` callbacks to: + +```kotlin +onWatchlist = { openForYou(SavedListSelection.Watchlist) } +onFavorites = { openForYou(SavedListSelection.Favorites) } +onRecommendations = { openForYou(null) } +``` + +Do not change `TvProfileDropdown` callbacks: they must continue navigating to +`TvMainRoute.Watchlist` and `TvMainRoute.Favorites`. + +- [ ] **Step 6: Run focused routing and existing focus tests** + +Run: + +```bash +./gradlew :androidTvApp:testDebugUnitTest \ + --tests '*TvForYouEntryRequestTest' \ + --tests '*TvForYouSelectorRoutingSourceTest' \ + --tests '*TvRecommendationsFocusBridgeTest' \ + --max-workers=2 --no-daemon +``` + +Expected: all tests pass. + +- [ ] **Step 7: Commit Task 6** + +```bash +git add \ + androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvForYouEntryRequest.kt \ + androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvRecommendationsScreen.kt \ + androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt \ + androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvForYouEntryRequestTest.kt \ + androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvForYouSelectorRoutingSourceTest.kt +git commit -m "fix(tv): unify for-you saved-list routes" +``` + +### Task 7: Full verification, production-shaped smoke, and executive summary **Files:** - Create: `docs/reviews/2026-07-27-android-tv-navigation-remediation-executive-summary.md` @@ -491,8 +826,9 @@ git commit -m "fix(tv): enter for-you rows from filter controls" Run: ```bash -./gradlew verifyDependencySupplyChainPolicy \ - :shared:testDebugUnitTest \ +./scripts/test-check-build-supply-chain.sh +./scripts/check-build-supply-chain.sh +./gradlew :shared:testDebugUnitTest \ :android-shared:testDebugUnitTest \ :androidTvApp:testDebugUnitTest \ --max-workers=2 --no-daemon @@ -529,7 +865,14 @@ Verify: 2. Initial focus remains Watchlist. 3. Select For You and press Down; focus reaches the first visible recommendation card. 4. Press Down/Up repeatedly; focus is not trapped and Up returns to For You. -5. Select Watchlist and Favorites; Down still enters their grids. +5. Select Watchlist and Favorites from the in-page pills; Down enters their inline grids. +6. Select Watchlist and Favorites from the top For You selector; each opens the + same inline For You presentation with the matching pill selected. +7. Select Watchlist and Favorites from the profile menu; each retains its + standalone utility-page presentation. +8. From several Home rows down, hold Up until the first row is reached; the + repeated sequence stays in content, and a released-then-fresh Up enters the + selected top-menu item. - [ ] **Step 4: Repeat the cold/warm performance protocol** @@ -547,8 +890,11 @@ Create the summary with these exact sections: - `Decision`: what was fixed and why it is safe to ship. - `Customer impact`: For You accessibility and first-traversal responsiveness. -- `Verified causes`: missing focus bridge, duplicate Home hydration, eager detail fan-out. -- `Change`: inline-first bounded hydration, cache-first rested enrichment, explicit focus handoff. +- `Verified causes`: missing focus bridge, duplicate Home hydration, eager detail + fan-out, an unguarded repeated-Up boundary, and two For You saved-list routes. +- `Change`: inline-first bounded hydration, cache-first rested enrichment, + deliberate focus handoff, serialized row relocation, and unified For You + selector presentation. - `Evidence`: before/after cold and warm measurements and test/build counts. - `Risk and rollback`: Android TV focus/prefetch scope, no schema/server change, revert commits independently. @@ -576,8 +922,9 @@ git commit -m "docs(tv): summarize navigation remediation" Run: ```bash -./gradlew verifyDependencySupplyChainPolicy \ - :shared:testDebugUnitTest \ +./scripts/test-check-build-supply-chain.sh +./scripts/check-build-supply-chain.sh +./gradlew :shared:testDebugUnitTest \ :android-shared:testDebugUnitTest \ :androidTvApp:testDebugUnitTest \ :androidTvApp:assembleRelease \ From 1a295a13d6146b4e154155fee5cb0eb9b1164e5f Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 00:57:24 +0200 Subject: [PATCH 11/65] docs(tv): test navigation behavior at real boundaries --- ...07-27-android-tv-navigation-remediation.md | 103 ++++++++++++------ 1 file changed, 71 insertions(+), 32 deletions(-) diff --git a/docs/superpowers/plans/2026-07-27-android-tv-navigation-remediation.md b/docs/superpowers/plans/2026-07-27-android-tv-navigation-remediation.md index dfcac6d9b5..bf7c4acd67 100644 --- a/docs/superpowers/plans/2026-07-27-android-tv-navigation-remediation.md +++ b/docs/superpowers/plans/2026-07-27-android-tv-navigation-remediation.md @@ -647,7 +647,6 @@ git commit -m "fix(tv): stop held up at the first home row" **Files:** - Create: `androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvForYouEntryRequest.kt` - Create: `androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvForYouEntryRequestTest.kt` -- Create: `androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvForYouSelectorRoutingSourceTest.kt` - Modify: `androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvRecommendationsScreen.kt:67-117` - Modify: `androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt:971-976,1224-1242,1290-1307` @@ -669,6 +668,17 @@ internal data class TvForYouEntryRequest( fun next(selection: SavedListSelection?): TvForYouEntryRequest = TvForYouEntryRequest(sequence = sequence + 1, selection = selection) } + +internal data class AppliedForYouSelection( + val selection: SavedListSelection?, + val lastAppliedSequence: Int, +) + +internal fun applyForYouEntryRequest( + currentSelection: SavedListSelection?, + lastAppliedSequence: Int, + request: TvForYouEntryRequest, +): AppliedForYouSelection ``` `TvRecommendationsScreen` accepts @@ -700,43 +710,57 @@ fun recommendationsRequestClearsSavedListSelection() { assertEquals(5, request.sequence) assertNull(request.selection) } -``` -- [ ] **Step 2: Write the failing source-wiring test** +@Test +fun unrelatedRecompositionDoesNotOverrideInPageSelection() { + val applied = applyForYouEntryRequest( + currentSelection = SavedListSelection.Favorites, + lastAppliedSequence = 3, + request = TvForYouEntryRequest( + sequence = 3, + selection = SavedListSelection.Watchlist, + ), + ) -Create `TvForYouSelectorRoutingSourceTest` that reads `TvMainShell.kt` and -asserts: + assertEquals(SavedListSelection.Favorites, applied.selection) + assertEquals(3, applied.lastAppliedSequence) +} -```kotlin -assertTrue(shell.contains("openForYou(SavedListSelection.Watchlist)")) -assertTrue(shell.contains("openForYou(SavedListSelection.Favorites)")) -assertTrue(shell.contains("openForYou(null)")) -assertTrue(shell.contains("onWatchlist = closeMenuAnd {")) -assertTrue(shell.contains("navigateToSecondary(TvMainRoute.Watchlist.route)")) -assertTrue(shell.contains("onFavorites = closeMenuAnd {")) -assertTrue(shell.contains("navigateToSecondary(TvMainRoute.Favorites.route)")) -``` +@Test +fun newerRequestAppliesRequestedInlineSelection() { + val applied = applyForYouEntryRequest( + currentSelection = null, + lastAppliedSequence = 3, + request = TvForYouEntryRequest( + sequence = 4, + selection = SavedListSelection.Watchlist, + ), + ) -This locks the intended split: For You selector choices are inline, while -profile-menu choices remain standalone. + assertEquals(SavedListSelection.Watchlist, applied.selection) + assertEquals(4, applied.lastAppliedSequence) +} +``` -- [ ] **Step 3: Run the request and wiring tests and verify RED** +- [ ] **Step 2: Run the request-state tests and verify RED** Run: ```bash ./gradlew :androidTvApp:testDebugUnitTest \ --tests '*TvForYouEntryRequestTest' \ - --tests '*TvForYouSelectorRoutingSourceTest' \ --max-workers=2 --no-daemon ``` -Expected: compilation fails because the request types do not exist; after those -types compile, the source assertions still fail until shell wiring changes. +Expected: compilation fails because the request and applied-selection types do +not exist. -- [ ] **Step 4: Implement the repeatable entry request** +- [ ] **Step 3: Implement the repeatable entry request** -Create `TvForYouEntryRequest.kt` with the exact interfaces above. Move +Create `TvForYouEntryRequest.kt` with the exact interfaces above. The apply +function returns the current selection unchanged when +`request.sequence <= lastAppliedSequence`; otherwise it returns the request's +selection and sequence. Move `SavedListSelection` out of `TvRecommendationsScreen.kt` into that file. Add the screen parameter: @@ -745,21 +769,24 @@ Add the screen parameter: entryRequest: TvForYouEntryRequest = TvForYouEntryRequest(), ``` -Initialize selection with `remember { mutableStateOf(entryRequest.selection) }` -and add: +Initialize selection and the last applied sequence with `remember`, then add: ```kotlin LaunchedEffect(entryRequest.sequence) { - if (entryRequest.sequence > 0) { - savedListSelection = entryRequest.selection - } + val applied = applyForYouEntryRequest( + currentSelection = savedListSelection, + lastAppliedSequence = lastAppliedEntrySequence, + request = entryRequest, + ) + savedListSelection = applied.selection + lastAppliedEntrySequence = applied.lastAppliedSequence } ``` This permits the same top-menu choice to be selected repeatedly and does not overwrite in-page pill changes during unrelated recompositions. -- [ ] **Step 5: Wire only the For You selector to inline requests** +- [ ] **Step 4: Wire only the For You selector to inline requests** In `TvMainShell`, remember: @@ -785,20 +812,33 @@ onRecommendations = { openForYou(null) } Do not change `TvProfileDropdown` callbacks: they must continue navigating to `TvMainRoute.Watchlist` and `TvMainRoute.Favorites`. -- [ ] **Step 6: Run focused routing and existing focus tests** +- [ ] **Step 5: Run focused routing and existing focus tests** Run: ```bash ./gradlew :androidTvApp:testDebugUnitTest \ --tests '*TvForYouEntryRequestTest' \ - --tests '*TvForYouSelectorRoutingSourceTest' \ --tests '*TvRecommendationsFocusBridgeTest' \ --max-workers=2 --no-daemon ``` Expected: all tests pass. +- [ ] **Step 6: Manually inspect the two call-site groups** + +Run: + +```bash +git diff -- \ + androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt \ + androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvRecommendationsScreen.kt +``` + +Confirm the `TvForYouSelector` callbacks all invoke `openForYou`, while the +`TvProfileDropdown` Watchlist/Favorites callbacks still navigate directly to +their standalone routes. + - [ ] **Step 7: Commit Task 6** ```bash @@ -806,8 +846,7 @@ git add \ androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvForYouEntryRequest.kt \ androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvRecommendationsScreen.kt \ androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt \ - androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvForYouEntryRequestTest.kt \ - androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvForYouSelectorRoutingSourceTest.kt + androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvForYouEntryRequestTest.kt git commit -m "fix(tv): unify for-you saved-list routes" ``` From ccf2e3760547e04ba2fd3b64ccdb8c627ea34c94 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 00:59:13 +0200 Subject: [PATCH 12/65] fix(tv): stop held up at the first home row --- .../silo/tv/ui/components/TvAlphabetRail.kt | 4 +- .../tv/ui/components/TvSkylineSectionFeed.kt | 49 ++++++++------- .../tv/ui/components/TvSkylineUpNavigation.kt | 21 +++++++ .../ui/screens/calendar/TvCalendarScreen.kt | 6 +- .../silo/tv/ui/screens/home/TvHomeScreen.kt | 4 +- .../screens/library/TvLibraryDetailScreen.kt | 6 +- .../silo/tv/ui/shell/TvMainShell.kt | 11 ++-- .../components/TvSkylineUpNavigationTest.kt | 59 +++++++++++++++++++ 8 files changed, 125 insertions(+), 35 deletions(-) create mode 100644 androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylineUpNavigation.kt create mode 100644 androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvSkylineUpNavigationTest.kt diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvAlphabetRail.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvAlphabetRail.kt index 8b620f5cb4..1a8e746adc 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvAlphabetRail.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvAlphabetRail.kt @@ -77,7 +77,7 @@ fun TvAlphabetRail( * the top menu is to register this fallback: on a letter it moves focus * up the rail; on "All" it swallows the move. */ - onUpFallbackChanged: (((() -> Boolean)?) -> Unit)? = null, + onUpFallbackChanged: ((((Boolean) -> Boolean)?) -> Unit)? = null, modifier: Modifier = Modifier, ) { val letters = remember { @@ -107,7 +107,7 @@ fun TvAlphabetRail( // old fresh-lambda + null pattern left a stale always-true fallback // registered forever, killing Up-to-menu-bar for the whole library. val railUpFallback = remember { - { + { _: Boolean -> if (!allEntryFocused) { focusManager.moveFocus(FocusDirection.Up) } diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylineSectionFeed.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylineSectionFeed.kt index bf114b0f05..250679292d 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylineSectionFeed.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylineSectionFeed.kt @@ -90,7 +90,7 @@ fun TvSkylineSectionFeed( if (it.isTvProgressRow()) TvRowStyle.Backdrop else TvRowStyle.Poster }, cardActions: (ResolvedSection, SectionItem) -> TvMediaCardActions = { _, _ -> TvMediaCardActions() }, - onContentUpFallbackChanged: (((() -> Boolean)?) -> Unit)? = null, + onContentUpFallbackChanged: ((((Boolean) -> Boolean)?) -> Unit)? = null, ) { val rows = remember(sections) { sections.filter { it.items.isNotEmpty() } } val tintState = rememberAmbientBackdropTintState() @@ -274,26 +274,35 @@ fun TvSkylineSectionFeed( } } - val currentContentUpFallback = rememberUpdatedState<() -> Boolean> { + var rowRelocationInFlight by remember { mutableStateOf(false) } + val currentContentUpFallback = rememberUpdatedState<(Boolean) -> Boolean> { isRepeat -> val currentRow = focusedRowIndex - when { - currentRow <= 0 || currentRow !in rows.indices -> - // Top row (or unfocused): report not-handled so the shell hands - // focus to the menu bar. - false - // Previous row is already laid out: move immediately so the returned - // value is HONEST — the old code launched the move asynchronously and - // returned `true` before it ran, so a failed move stranded focus - // (neither moved up nor escalated to the menu). - focusManager.moveFocus(FocusDirection.Up) -> true - else -> { + when ( + tvSkylineUpAction( + currentRow = currentRow, + rowCount = rows.size, + isRepeat = isRepeat, + relocationInFlight = rowRelocationInFlight, + ) + ) { + TvSkylineUpAction.EnterMenu -> false + TvSkylineUpAction.StayInContent -> true + TvSkylineUpAction.TryPreviousRow -> { + if (focusManager.moveFocus(FocusDirection.Up)) { + return@rememberUpdatedState true + } // Previous row is scrolled off; bring it on-screen first, then - // move once the scroll settles (animateScrollToItem suspends until - // it does, so the row is laid out before moveFocus). + // move once the scroll settles. While this job owns relocation, + // key repeats are consumed instead of launching competing jobs. + rowRelocationInFlight = true rowBandScope.launch { - rowBandState.animateScrollToItem(currentRow - 1) - withFrameNanos { } - focusManager.moveFocus(FocusDirection.Up) + try { + rowBandState.animateScrollToItem(currentRow - 1) + withFrameNanos { } + focusManager.moveFocus(FocusDirection.Up) + } finally { + rowRelocationInFlight = false + } } true } @@ -302,8 +311,8 @@ fun TvSkylineSectionFeed( // Stable per-screen registration so the shell can identify THIS feed's // ownership of the shared up-fallback slot across sibling (tab) swaps. - val contentUpFallbackRegistration: () -> Boolean = - remember { { currentContentUpFallback.value() } } + val contentUpFallbackRegistration: (Boolean) -> Boolean = + remember { { isRepeat -> currentContentUpFallback.value(isRepeat) } } DisposableEffect(onContentUpFallbackChanged, contentUpFallbackRegistration) { onContentUpFallbackChanged?.invoke(contentUpFallbackRegistration) diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylineUpNavigation.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylineUpNavigation.kt new file mode 100644 index 0000000000..922745bdad --- /dev/null +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylineUpNavigation.kt @@ -0,0 +1,21 @@ +package org.siloserver.silo.tv.ui.components + +internal enum class TvSkylineUpAction { + EnterMenu, + StayInContent, + TryPreviousRow, +} + +internal fun tvSkylineUpAction( + currentRow: Int, + rowCount: Int, + isRepeat: Boolean, + relocationInFlight: Boolean, +): TvSkylineUpAction = when { + relocationInFlight -> TvSkylineUpAction.StayInContent + currentRow !in 0 until rowCount -> + if (isRepeat) TvSkylineUpAction.StayInContent else TvSkylineUpAction.EnterMenu + currentRow == 0 -> + if (isRepeat) TvSkylineUpAction.StayInContent else TvSkylineUpAction.EnterMenu + else -> TvSkylineUpAction.TryPreviousRow +} diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/calendar/TvCalendarScreen.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/calendar/TvCalendarScreen.kt index 348ee625a2..f07c9b24fd 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/calendar/TvCalendarScreen.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/calendar/TvCalendarScreen.kt @@ -125,7 +125,7 @@ fun TvCalendarScreen( onOpenItemDetail: (contentId: String) -> Unit, onInitialContentFocus: () -> Unit = {}, focusRequest: Int = 0, - onContentUpFallbackChanged: (((() -> Boolean)?) -> Unit)? = null, + onContentUpFallbackChanged: ((((Boolean) -> Boolean)?) -> Unit)? = null, viewModel: CalendarViewModel = koinViewModel(), ) { val state by viewModel.uiState.collectAsState() @@ -679,7 +679,7 @@ internal fun shouldReturnCalendarFocusToControls( @OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class, ExperimentalTvMaterial3Api::class) @Composable private fun CalendarList( - onContentUpFallbackChanged: (((() -> Boolean)?) -> Unit)? = null, + onContentUpFallbackChanged: ((((Boolean) -> Boolean)?) -> Unit)? = null, state: org.siloserver.silo.viewmodel.CalendarUiState, listState: LazyListState, controls: @Composable () -> Unit, @@ -732,7 +732,7 @@ private fun CalendarList( // (moveFocus within content; false -> shell hands off to the menu bar). var focusedShelfIndex by remember { mutableStateOf(null) } val calendarUpFallback = remember(firstFocusableDayIndex) { - { + { _: Boolean -> if (shouldReturnCalendarFocusToControls( focusedShelfIndex = focusedShelfIndex, firstFocusableShelfIndex = firstFocusableDayIndex, diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/home/TvHomeScreen.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/home/TvHomeScreen.kt index e93f8fa45b..b37eebe3d7 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/home/TvHomeScreen.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/home/TvHomeScreen.kt @@ -54,7 +54,7 @@ fun TvHomeScreen( firstRowFocusRequester: FocusRequester? = null, firstRowContainerFocusRequester: FocusRequester? = null, shouldRefreshOnResume: () -> Boolean = { true }, - onContentUpFallbackChanged: (((() -> Boolean)?) -> Unit)? = null, + onContentUpFallbackChanged: ((((Boolean) -> Boolean)?) -> Unit)? = null, viewModel: HomeViewModel = koinViewModel(), ) { val state by viewModel.uiState.collectAsState() @@ -169,7 +169,7 @@ private fun TvHomeContent( detailReturnCardFocusRequester: FocusRequester?, firstRowFocusRequester: FocusRequester?, firstRowContainerFocusRequester: FocusRequester?, - onContentUpFallbackChanged: (((() -> Boolean)?) -> Unit)?, + onContentUpFallbackChanged: ((((Boolean) -> Boolean)?) -> Unit)?, onSetWatched: (String, Boolean) -> Unit = { _, _ -> }, onToggleFavorite: (String, Boolean) -> Unit = { _, _ -> }, onToggleWatchlist: (String, Boolean) -> Unit = { _, _ -> }, diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/library/TvLibraryDetailScreen.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/library/TvLibraryDetailScreen.kt index f747a73e67..83b2b3e118 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/library/TvLibraryDetailScreen.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/library/TvLibraryDetailScreen.kt @@ -98,7 +98,7 @@ fun TvLibraryDetailScreen( // section-apply effect on it (not just initialSection) makes re-committing // the SAME pill re-apply the section instead of being a silent no-op. sectionRequestNonce: Int = 0, - onContentUpFallbackChanged: (((() -> Boolean)?) -> Unit)? = null, + onContentUpFallbackChanged: ((((Boolean) -> Boolean)?) -> Unit)? = null, viewModel: TvLibraryDetailViewModel = koinViewModel( key = "library-$libraryId", parameters = { parametersOf(libraryId, libraryTitle, libraryType) }, @@ -241,7 +241,7 @@ private fun RecommendedTab( onRetry: () -> Unit, onInitialContentFocus: () -> Unit, focusRequest: Int, - onContentUpFallbackChanged: (((() -> Boolean)?) -> Unit)?, + onContentUpFallbackChanged: ((((Boolean) -> Boolean)?) -> Unit)?, ) { val rows = remember(state.sections) { state.sections.filter { !it.featured && it.items.isNotEmpty() } @@ -309,7 +309,7 @@ private fun LibraryTab( onSortKeySelected: (TvLibrarySortOption) -> Unit = {}, onFacetSelectionApplied: (TvCatalogFacetSelection) -> Unit = {}, /** Shell hook for overriding D-pad Up while the A–Z rail holds focus. */ - onContentUpFallbackChanged: (((() -> Boolean)?) -> Unit)? = null, + onContentUpFallbackChanged: ((((Boolean) -> Boolean)?) -> Unit)? = null, onClearAudiobookGroup: (() -> Unit)? = null, ) { val restoredGridItemFocusRequester = remember { FocusRequester() } diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt index 92b31bf9e3..a92387ce66 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt @@ -366,12 +366,12 @@ fun TvMainShell( suppressHomeRefreshAfterDetail = true onOpenItemDetail(contentId) } - var contentUpFallback by remember { mutableStateOf<(() -> Boolean)?>(null) } + var contentUpFallback by remember { mutableStateOf<((Boolean) -> Boolean)?>(null) } // Feeds that registered the up-fallback slot, were superseded by a newer // feed, and are still awaiting their (now-stale) onDispose. Tracking them // lets us ignore that late dispose instead of nulling the entering feed's // registration. - val supersededContentUpFallbacks = remember { mutableSetOf<() -> Boolean>() } + val supersededContentUpFallbacks = remember { mutableSetOf<(Boolean) -> Boolean>() } // Register/relinquish the single D-pad-Up fallback slot BY IDENTITY. A // NavHost composes the ENTERING feed (which registers its own lambda) before // it disposes the EXITING one, so a blind null-on-dispose would drop the new @@ -380,7 +380,7 @@ fun TvMainShell( // lambda on both register and dispose; we only relinquish the slot for the // feed that still owns it, ignore a superseded feed's stale dispose, and let // a newly-entering feed take the slot (retiring the previous owner). - val onContentUpFallback: ((() -> Boolean)?) -> Unit = remember { + val onContentUpFallback: (((Boolean) -> Boolean)?) -> Unit = remember { { incoming -> if (incoming != null) { when { @@ -789,7 +789,8 @@ fun TvMainShell( .onPreviewKeyEvent { ev -> when { ev.type == KeyEventType.KeyDown && ev.key == Key.DirectionUp -> { - val contentHandledUp = contentUpFallback?.invoke() + val isRepeat = ev.nativeKeyEvent.repeatCount > 0 + val contentHandledUp = contentUpFallback?.invoke(isRepeat) if (contentHandledUp != null) { if (!contentHandledUp) { focusState.requestMenuFocus() @@ -1391,7 +1392,7 @@ private fun TvLibraryTypeContent( onLibraryCollectionClick: (libraryId: Int, collectionId: String, title: String) -> Unit, onUserCollectionClick: (collectionId: String, title: String) -> Unit, onInitialContentFocus: () -> Unit, - onContentUpFallbackChanged: (((() -> Boolean)?) -> Unit)? = null, + onContentUpFallbackChanged: ((((Boolean) -> Boolean)?) -> Unit)? = null, ) { if (library == null) { // Only assert "no libraries" once loading has settled AND this type diff --git a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvSkylineUpNavigationTest.kt b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvSkylineUpNavigationTest.kt new file mode 100644 index 0000000000..3f3cfcfffc --- /dev/null +++ b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvSkylineUpNavigationTest.kt @@ -0,0 +1,59 @@ +package org.siloserver.silo.tv.ui.components + +import kotlin.test.Test +import kotlin.test.assertEquals + +class TvSkylineUpNavigationTest { + + @Test + fun heldUpStopsOnFirstContentRow() { + assertEquals( + TvSkylineUpAction.StayInContent, + tvSkylineUpAction( + currentRow = 0, + rowCount = 6, + isRepeat = true, + relocationInFlight = false, + ), + ) + } + + @Test + fun freshUpFromFirstContentRowMayEnterMenu() { + assertEquals( + TvSkylineUpAction.EnterMenu, + tvSkylineUpAction( + currentRow = 0, + rowCount = 6, + isRepeat = false, + relocationInFlight = false, + ), + ) + } + + @Test + fun repeatedInputDuringOffscreenRelocationIsConsumed() { + assertEquals( + TvSkylineUpAction.StayInContent, + tvSkylineUpAction( + currentRow = 4, + rowCount = 6, + isRepeat = true, + relocationInFlight = true, + ), + ) + } + + @Test + fun ordinaryUpWithinRowsTriesExactlyOnePreviousRow() { + assertEquals( + TvSkylineUpAction.TryPreviousRow, + tvSkylineUpAction( + currentRow = 4, + rowCount = 6, + isRepeat = false, + relocationInFlight = false, + ), + ) + } +} From 2a21361f27f179efadc18a77231e7484782dccc7 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 01:00:59 +0200 Subject: [PATCH 13/65] fix(tv): unify for-you saved-list routes --- .../recommendations/TvForYouEntryRequest.kt | 36 +++++++++++ .../TvRecommendationsScreen.kt | 20 +++++-- .../silo/tv/ui/shell/TvMainShell.kt | 28 +++++---- .../TvForYouEntryRequestTest.kt | 59 +++++++++++++++++++ 4 files changed, 124 insertions(+), 19 deletions(-) create mode 100644 androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvForYouEntryRequest.kt create mode 100644 androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvForYouEntryRequestTest.kt diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvForYouEntryRequest.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvForYouEntryRequest.kt new file mode 100644 index 0000000000..6c0b6f7f95 --- /dev/null +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvForYouEntryRequest.kt @@ -0,0 +1,36 @@ +package org.siloserver.silo.tv.ui.screens.recommendations + +enum class SavedListSelection { + Watchlist, + Favorites, +} + +data class TvForYouEntryRequest( + val sequence: Int = 0, + val selection: SavedListSelection? = null, +) { + fun next(selection: SavedListSelection?): TvForYouEntryRequest = + TvForYouEntryRequest(sequence = sequence + 1, selection = selection) +} + +internal data class AppliedForYouSelection( + val selection: SavedListSelection?, + val lastAppliedSequence: Int, +) + +internal fun applyForYouEntryRequest( + currentSelection: SavedListSelection?, + lastAppliedSequence: Int, + request: TvForYouEntryRequest, +): AppliedForYouSelection = + if (request.sequence <= lastAppliedSequence) { + AppliedForYouSelection( + selection = currentSelection, + lastAppliedSequence = lastAppliedSequence, + ) + } else { + AppliedForYouSelection( + selection = request.selection, + lastAppliedSequence = request.sequence, + ) + } diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvRecommendationsScreen.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvRecommendationsScreen.kt index 66a7bbbef4..43ea6983ef 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvRecommendationsScreen.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvRecommendationsScreen.kt @@ -22,6 +22,7 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope @@ -68,6 +69,7 @@ fun TvRecommendationsScreen( onItemClick: (contentId: String) -> Unit, onInitialContentFocus: () -> Unit = {}, focusRequest: Int = 0, + entryRequest: TvForYouEntryRequest = TvForYouEntryRequest(), viewModel: RecommendationsViewModel = koinViewModel(), ) { val state by viewModel.uiState.collectAsState() @@ -78,7 +80,8 @@ fun TvRecommendationsScreen( val firstRecommendationRowFocusRequester = remember { FocusRequester() } val firstRecommendationCardFocusRequester = remember { FocusRequester() } val focusBridgeScope = rememberCoroutineScope() - var savedListSelection by remember { mutableStateOf(null) } + var savedListSelection by remember { mutableStateOf(entryRequest.selection) } + var lastAppliedEntrySequence by remember { mutableIntStateOf(entryRequest.sequence) } val moveIntoRecommendations: () -> Boolean = { if ( !shouldBridgeRecommendationsDown( @@ -105,6 +108,16 @@ fun TvRecommendationsScreen( } } + LaunchedEffect(entryRequest.sequence) { + val applied = applyForYouEntryRequest( + currentSelection = savedListSelection, + lastAppliedSequence = lastAppliedEntrySequence, + request = entryRequest, + ) + savedListSelection = applied.selection + lastAppliedEntrySequence = applied.lastAppliedSequence + } + // Match tvOS: recommendations remain the landing content when available; // an empty successful response defaults to the inline Watchlist fallback. LaunchedEffect(state.isLoading, state.error, visibleSections) { @@ -339,8 +352,3 @@ fun TvRecommendationsScreen( } } } - -private enum class SavedListSelection { - Watchlist, - Favorites, -} diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt index a92387ce66..81d9b36b40 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt @@ -145,6 +145,8 @@ import org.siloserver.silo.tv.ui.screens.personal.TvFavoritesScreen import org.siloserver.silo.tv.ui.screens.personal.TvHistoryScreen import org.siloserver.silo.tv.ui.screens.personal.TvWatchlistScreen import org.siloserver.silo.tv.ui.screens.recommendations.TvRecommendationsScreen +import org.siloserver.silo.tv.ui.screens.recommendations.SavedListSelection +import org.siloserver.silo.tv.ui.screens.recommendations.TvForYouEntryRequest import org.siloserver.silo.tv.ui.screens.requests.TvMyRequestsScreen import org.siloserver.silo.tv.ui.screens.requests.TvRequestDetailScreen import org.siloserver.silo.tv.ui.screens.requests.TvRequestsScreen @@ -411,6 +413,7 @@ fun TvMainShell( // top), while ordinary content re-entry keeps the focusRestorer()'s // last-focused card. var contentFocusRequest by remember { mutableIntStateOf(0) } + var forYouEntryRequest by remember { mutableStateOf(TvForYouEntryRequest()) } // --- Skyline cascade panel host (Stage 4) ---------------------------------- // Mirrors tvOS `TVMainTabView.persistentPanels`. The cascade overlays are @@ -534,6 +537,12 @@ fun TvMainShell( runCatching { contentFocusRequester.requestFocus() } } } + val openForYou: (SavedListSelection?) -> Unit = { selection -> + forYouEntryRequest = forYouEntryRequest.next(selection) + focusState.closePanel(false) + navigateToSecondary(TvMainRoute.ForYou.route) + moveFocusToContent(TvMainRoute.ForYou.route) + } val onSelectRoot: (TvRootDestination) -> Unit = { dest -> val route = dest.toRoute() @@ -839,8 +848,7 @@ fun TvMainShell( moveFocusToContent(TvMainRoute.Browse.route) }, onOpenForYou = { - navigateToSecondary(TvMainRoute.ForYou.route) - moveFocusToContent(TvMainRoute.ForYou.route) + openForYou(null) }, onInitialContentFocus = { focusState.closeProfileMenuForContent() }, focusRequest = contentFocusRequest, @@ -861,8 +869,7 @@ fun TvMainShell( moveFocusToContent(TvMainRoute.Browse.route) }, onOpenForYou = { - navigateToSecondary(TvMainRoute.ForYou.route) - moveFocusToContent(TvMainRoute.ForYou.route) + openForYou(null) }, onInitialContentFocus = { focusState.closeProfileMenuForContent() }, focusRequest = contentFocusRequest, @@ -974,6 +981,7 @@ fun TvMainShell( onItemClick = onOpenItemDetail, onInitialContentFocus = { focusState.closeProfileMenuForContent() }, focusRequest = contentFocusRequest, + entryRequest = forYouEntryRequest, ) } composable(TvMainRoute.Requests.route) { @@ -1226,19 +1234,13 @@ fun TvMainShell( entersPanel = active && focusState.panelEntersFocus, focusEntryToken = focusState.panelFocusEntryToken, onWatchlist = { - focusState.closePanel(false) - navigateToSecondary(TvMainRoute.Watchlist.route) - moveFocusToContent(TvMainRoute.Watchlist.route) + openForYou(SavedListSelection.Watchlist) }, onFavorites = { - focusState.closePanel(false) - navigateToSecondary(TvMainRoute.Favorites.route) - moveFocusToContent(TvMainRoute.Favorites.route) + openForYou(SavedListSelection.Favorites) }, onRecommendations = { - focusState.closePanel(false) - navigateToSecondary(TvMainRoute.ForYou.route) - moveFocusToContent(TvMainRoute.ForYou.route) + openForYou(null) }, ) } diff --git a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvForYouEntryRequestTest.kt b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvForYouEntryRequestTest.kt new file mode 100644 index 0000000000..e6eb3c6941 --- /dev/null +++ b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvForYouEntryRequestTest.kt @@ -0,0 +1,59 @@ +package org.siloserver.silo.tv.ui.screens.recommendations + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull + +class TvForYouEntryRequestTest { + + @Test + fun repeatedSelectionStillCreatesANewRequest() { + val first = TvForYouEntryRequest().next(SavedListSelection.Watchlist) + val second = first.next(SavedListSelection.Watchlist) + + assertEquals(1, first.sequence) + assertEquals(2, second.sequence) + assertEquals(SavedListSelection.Watchlist, second.selection) + } + + @Test + fun recommendationsRequestClearsSavedListSelection() { + val request = TvForYouEntryRequest( + sequence = 4, + selection = SavedListSelection.Favorites, + ).next(null) + + assertEquals(5, request.sequence) + assertNull(request.selection) + } + + @Test + fun unrelatedRecompositionDoesNotOverrideInPageSelection() { + val applied = applyForYouEntryRequest( + currentSelection = SavedListSelection.Favorites, + lastAppliedSequence = 3, + request = TvForYouEntryRequest( + sequence = 3, + selection = SavedListSelection.Watchlist, + ), + ) + + assertEquals(SavedListSelection.Favorites, applied.selection) + assertEquals(3, applied.lastAppliedSequence) + } + + @Test + fun newerRequestAppliesRequestedInlineSelection() { + val applied = applyForYouEntryRequest( + currentSelection = null, + lastAppliedSequence = 3, + request = TvForYouEntryRequest( + sequence = 4, + selection = SavedListSelection.Watchlist, + ), + ) + + assertEquals(SavedListSelection.Watchlist, applied.selection) + assertEquals(4, applied.lastAppliedSequence) + } +} From f08aec60aca2313439169889d7fa1c866a06c97f Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 01:03:57 +0200 Subject: [PATCH 14/65] docs(tv): summarize navigation remediation --- ...avigation-remediation-executive-summary.md | 91 +++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 docs/reviews/2026-07-27-android-tv-navigation-remediation-executive-summary.md diff --git a/docs/reviews/2026-07-27-android-tv-navigation-remediation-executive-summary.md b/docs/reviews/2026-07-27-android-tv-navigation-remediation-executive-summary.md new file mode 100644 index 0000000000..772e20017d --- /dev/null +++ b/docs/reviews/2026-07-27-android-tv-navigation-remediation-executive-summary.md @@ -0,0 +1,91 @@ +# Android TV Navigation Remediation — Executive Summary + +## Decision + +Ship the cache-first Android TV navigation changes for external testing. The +change addresses the cold-start navigation slowdown and the broken `For You` +focus transition reported in issues #121 and #122 without changing server +contracts, playback behavior, or subtitle handling. + +## Customer impact + +On a large production library, the first trip across Home rows caused bursts of +detail requests and garbage collection while focus was moving. Returning over +the same rows was substantially faster because those details were then cached. +The `For You` filter-to-card transition also lacked an explicit focus bridge, +which could leave Down navigation stuck in the filter controls. + +External testing of the first build found two smaller consistency issues: +holding Up while returning through several Home rows could carry focus straight +into the top menu, and Watchlist/Favorites selected from the For You dropdown +opened visually different standalone pages from the equivalent in-page pills. + +## Verified causes + +- Home inline sections could be hydrated more than once. +- Marquee enrichment and Skyline prefetch treated a cold detail cache as an + invitation to fan out requests during focus movement. +- Skyline work could outlive or race the focus state that requested it. +- `For You` did not explicitly transfer focus between its filters and first + result card. +- The Home row fallback accepted overlapping off-screen relocation requests and + treated a repeated Up event at row zero like a deliberate fresh menu-entry + press. +- The For You dropdown routed saved lists to standalone destinations while the + in-page pills used inline grids. + +Archived PR #108 contained earlier versions of the relevant performance ideas +in commits `49a70045` and `65c4b316`, but those commits were not ancestors of +current `main`. This branch forward-ports the behavior against the current +architecture with focused tests and bounded concurrency. + +## Changes + +- Hydrate shared inline Home sections once. +- Make marquee detail enrichment cache-first. +- Start Skyline prefetch only after focus settles and cancel obsolete work. +- Add explicit, tested `For You` filter/card focus transitions. +- Serialize off-screen Up relocation, stop held/repeated Up on Home's first + content row, and require a fresh Up press to enter the top menu. +- Route For You dropdown Watchlist/Favorites choices through the same inline + presentation as their in-page pills; profile-menu entries remain standalone. +- Add regression coverage for cache misses, request bounds, stale completion, + cancellation, repeat-key boundaries, saved-list requests, and focus routing. + +## Evidence + +Production-backed emulator profiling before the change showed: + +| Scenario | Janky frames | p95 | p99 | HTTP requests | +| --- | ---: | ---: | ---: | ---: | +| Horizontal cold | 18.34% | 53 ms | 700 ms | 45 | +| Horizontal warm | 5.09% | — | — | 0 | +| Second cold | 15.13% | 42 ms | 1000 ms | 46 | +| Vertical cold | 27.34% | 250 ms | 1000 ms | 47 | +| Vertical warm | 12.97% | 34 ms | 109 ms | 4 | + +After the change, a combined cold-navigation run recorded 769 frames, 114 +janky frames (14.82%), p50 10 ms, p90 24 ms, p95 46 ms, and p99 300 ms. The +captured run contained only five combined HTTP-completion/GC log matches. + +Supply-chain policy checks, shared and TV focused unit tests, Android shared +tests, and the minified TV release assembly passed. A final independent review +approved the branch after two correction rounds. + +The device session ended before a complete Down/card/Up `For You` focus smoke +could be recorded. The focus bridge, repeat-key boundary, and saved-list +selection state are covered by behavioral unit tests, so external testing +should explicitly include those remote-control paths. + +## Risk and rollback + +Risk is concentrated in prefetch timing: slower networks may display metadata +slightly later because uncached enrichment no longer competes with active +focus navigation. Content remains available through the normal detail path. +The commits are separated by concern, so the focus bridge, repeat-key boundary, +saved-list routing, or either prefetch policy can be reverted independently if +external testing finds a regression. + +The test APKs are debug-signed release builds and cannot replace an installed +production-signed build without a matching signer. They are intended for a +compatible tester installation only. From e3dec4d5eb9765213edc46df6c0fb42d4c73b793 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 01:08:41 +0200 Subject: [PATCH 15/65] fix(tv): focus applied for-you selection --- .../recommendations/TvForYouEntryRequest.kt | 18 +++++++ .../TvRecommendationsScreen.kt | 17 ++++++- .../TvForYouEntryRequestTest.kt | 47 +++++++++++++++++++ 3 files changed, 81 insertions(+), 1 deletion(-) diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvForYouEntryRequest.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvForYouEntryRequest.kt index 6c0b6f7f95..82f08b8363 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvForYouEntryRequest.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvForYouEntryRequest.kt @@ -16,6 +16,7 @@ data class TvForYouEntryRequest( internal data class AppliedForYouSelection( val selection: SavedListSelection?, val lastAppliedSequence: Int, + val appliedRequest: Boolean, ) internal fun applyForYouEntryRequest( @@ -27,10 +28,27 @@ internal fun applyForYouEntryRequest( AppliedForYouSelection( selection = currentSelection, lastAppliedSequence = lastAppliedSequence, + appliedRequest = false, ) } else { AppliedForYouSelection( selection = request.selection, lastAppliedSequence = request.sequence, + appliedRequest = true, ) } + +internal suspend fun requestForYouEntryFocus( + selection: SavedListSelection?, + awaitFrame: suspend () -> Unit, + requestForYou: () -> Boolean, + requestWatchlist: () -> Boolean, + requestFavorites: () -> Boolean, +): Boolean { + awaitFrame() + return when (selection) { + null -> requestForYou() + SavedListSelection.Watchlist -> requestWatchlist() + SavedListSelection.Favorites -> requestFavorites() + } +} diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvRecommendationsScreen.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvRecommendationsScreen.kt index 43ea6983ef..6a33cd7db5 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvRecommendationsScreen.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvRecommendationsScreen.kt @@ -81,7 +81,7 @@ fun TvRecommendationsScreen( val firstRecommendationCardFocusRequester = remember { FocusRequester() } val focusBridgeScope = rememberCoroutineScope() var savedListSelection by remember { mutableStateOf(entryRequest.selection) } - var lastAppliedEntrySequence by remember { mutableIntStateOf(entryRequest.sequence) } + var lastAppliedEntrySequence by remember { mutableIntStateOf(0) } val moveIntoRecommendations: () -> Boolean = { if ( !shouldBridgeRecommendationsDown( @@ -116,6 +116,21 @@ fun TvRecommendationsScreen( ) savedListSelection = applied.selection lastAppliedEntrySequence = applied.lastAppliedSequence + if (applied.appliedRequest) { + requestForYouEntryFocus( + selection = applied.selection, + awaitFrame = { withFrameNanos { } }, + requestForYou = { + runCatching { forYouFocusRequester.requestFocus() }.getOrDefault(false) + }, + requestWatchlist = { + runCatching { watchlistFocusRequester.requestFocus() }.getOrDefault(false) + }, + requestFavorites = { + runCatching { favoritesFocusRequester.requestFocus() }.getOrDefault(false) + }, + ) + } } // Match tvOS: recommendations remain the landing content when available; diff --git a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvForYouEntryRequestTest.kt b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvForYouEntryRequestTest.kt index e6eb3c6941..31ab1e9a76 100644 --- a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvForYouEntryRequestTest.kt +++ b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvForYouEntryRequestTest.kt @@ -1,8 +1,11 @@ package org.siloserver.silo.tv.ui.screens.recommendations +import kotlinx.coroutines.test.runTest import kotlin.test.Test import kotlin.test.assertEquals +import kotlin.test.assertFalse import kotlin.test.assertNull +import kotlin.test.assertTrue class TvForYouEntryRequestTest { @@ -40,6 +43,7 @@ class TvForYouEntryRequestTest { assertEquals(SavedListSelection.Favorites, applied.selection) assertEquals(3, applied.lastAppliedSequence) + assertFalse(applied.appliedRequest) } @Test @@ -55,5 +59,48 @@ class TvForYouEntryRequestTest { assertEquals(SavedListSelection.Watchlist, applied.selection) assertEquals(4, applied.lastAppliedSequence) + assertTrue(applied.appliedRequest) + } + + @Test + fun sameRouteCrossSelectionFocusesNewRequestedPillAfterComposition() = runTest { + val events = mutableListOf() + + val focused = requestForYouEntryFocus( + selection = SavedListSelection.Favorites, + awaitFrame = { events += "frame" }, + requestForYou = { events += "for-you"; true }, + requestWatchlist = { events += "watchlist"; true }, + requestFavorites = { events += "favorites"; true }, + ) + + assertTrue(focused) + assertEquals(listOf("frame", "favorites"), events) + } + + @Test + fun repeatedSameRouteSelectionStillRefocusesRequestedPill() = runTest { + val request = TvForYouEntryRequest( + sequence = 8, + selection = SavedListSelection.Watchlist, + ).next(SavedListSelection.Watchlist) + val applied = applyForYouEntryRequest( + currentSelection = SavedListSelection.Watchlist, + lastAppliedSequence = 8, + request = request, + ) + val events = mutableListOf() + + if (applied.appliedRequest) { + requestForYouEntryFocus( + selection = applied.selection, + awaitFrame = { events += "frame" }, + requestForYou = { events += "for-you"; true }, + requestWatchlist = { events += "watchlist"; true }, + requestFavorites = { events += "favorites"; true }, + ) + } + + assertEquals(listOf("frame", "watchlist"), events) } } From 4eef154fc3a733f82240ee01273c9c31e11ab7ae Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 06:02:36 +0200 Subject: [PATCH 16/65] docs(tv): design active header focus and editorial hero --- ...tive-header-focus-editorial-hero-design.md | 159 ++++++++++++++++++ 1 file changed, 159 insertions(+) create mode 100644 docs/superpowers/specs/2026-07-28-android-tv-active-header-focus-editorial-hero-design.md diff --git a/docs/superpowers/specs/2026-07-28-android-tv-active-header-focus-editorial-hero-design.md b/docs/superpowers/specs/2026-07-28-android-tv-active-header-focus-editorial-hero-design.md new file mode 100644 index 0000000000..faaa51baaf --- /dev/null +++ b/docs/superpowers/specs/2026-07-28-android-tv-active-header-focus-editorial-hero-design.md @@ -0,0 +1,159 @@ +# Android TV Active Header Focus and Editorial Hero Design + +**Date:** 2026-07-28 +**Status:** Approved for implementation planning +**Scope:** Android TV browsing shell and browsing heroes only + +## Context + +External testing of the TV navigation work in PR #126 confirmed that cold +navigation and For You behavior improved. It also exposed two related +presentation defects: + +1. Pressing Up from the first content row can focus Search instead of the + currently active top-menu destination. Pressing Back from the same page + correctly focuses the active destination. +2. Browsing heroes prioritize technical stream badges such as resolution, + HDR, and audio format ahead of editorial information. This can crowd or + truncate the year, runtime, episode identity, and rating that people use to + decide what to watch. + +Issue #78 asks for richer title metadata, but its current wording refers to the +player. This change applies the approved behavior to browsing heroes only and +does not change the player or item-detail surfaces. + +## Goals + +- A fresh Up press from the first content row focuses the active top-menu + destination on Home, each library section, For You, and Calendar. +- Search receives this focus only when Search is the active route. +- Preserve the existing held-Up boundary: a held key stops on the first + content row and requires a fresh Up press before entering the menu. +- Browsing heroes describe the focused title using editorial metadata instead + of video/audio delivery characteristics. +- Keep the change inside the existing shared TV shell and marquee model. + +## Non-goals + +- No server, API, database, or payload changes. +- No Android phone changes. +- No player-overlay, playback-settings, or item-detail redesign. +- No changes to stream selection, transcoding, subtitle behavior, or technical + metadata availability outside the browsing hero. +- No new user preference or display toggle. + +## Focus Behavior + +The shell remains the single owner of content-to-menu focus transitions. When +the active content feed reports that a fresh Up press has reached its first +row, the shell requests the menu destination derived from the current route: + +- Home → Home +- Movies, Series, Music, or Audiobooks → the matching library-type pill +- For You → For You +- Calendar → Calendar +- Search → Search + +The request must target the active destination explicitly and complete through +the existing menu focus-request mechanism. It must not depend on Compose +geometric focus search or on the physical proximity of Search to the content +card. The same mapping is used by Back-to-menu behavior so the two entry paths +cannot drift. + +Repeated Up events at the first content row remain consumed. Off-screen +previous-row relocation and ordinary row-to-row Up movement are unchanged. +Panel preview, profile menu, Left/Right menu traversal, and Down-to-content +behavior are unchanged. + +## Browsing Hero Metadata + +The browsing marquee stops rendering resolution, HDR, and audio-format badges. +Technical overlay data remains in the model for other consumers but is not +converted into hero badges. + +The hero uses the following ordered editorial fields when present: + +### Movies and other non-episode titles + +1. Release year +2. Runtime +3. IMDb rating +4. Primary genre + +Content classification, such as PG-13, remains as the only badge adjacent to +that ordered metadata line. + +### Episodes + +1. Season and episode token, such as `S2 E7` +2. Episode name +3. Runtime +4. Air date when available from existing enrichment +5. Rating when present + +Content classification, such as TV-MA, remains as the only badge adjacent to +that ordered metadata line. + +The series name remains the episode hero title, with the episode name in the +metadata line. Missing values are omitted without placeholders or redundant +separators. Existing synopsis, cast enrichment, artwork, cache-first loading, +and crossfade behavior remain unchanged. + +The implementation may keep air date and cast on the existing quieter detail +line if the current payload/enrichment boundary does not expose air date early +enough for the primary metadata line. It must not add another detail request or +delay first paint to rearrange those fields. + +## Data Flow and Boundaries + +- `TvMainShell` derives the active root destination from the current route. +- `TvShellFocusState` carries the explicit menu-focus request. +- `TvTopMenuBar` resolves that destination to its existing `FocusRequester`. +- `TvSkylineSectionFeed` retains ownership of row traversal and the held-Up + boundary, but does not choose a menu target. +- `TvMarqueeContent.from` converts the existing `SectionItem` payload into + ordered editorial metadata. +- Existing detail enrichment may continue to add air-date/cast information + without blocking or re-fetching on focus. + +No parallel focus coordinator or marquee data source is introduced. + +## Error and Edge Handling + +- If the active route has no top-menu destination, preserve its existing + route-specific behavior rather than silently selecting Home. +- If a requested library pill is temporarily absent, use the existing safe + requester fallback and do not crash. +- Invalid, zero, blank, or unavailable metadata is omitted. +- Ratings and runtimes keep the existing formatting and rounding rules unless + a focused test demonstrates an incorrect value. +- Removing technical badges must not create an empty visual row; the row is + omitted when no editorial badge or metadata value exists. + +## Verification + +Focused tests should cover: + +- route-to-menu target mapping for every root destination and Search; +- the held-Up first-row boundary remains unchanged; +- movie metadata ordering and omission of resolution/HDR/audio; +- episode metadata ordering, series/episode naming, runtime, rating, and + content-classification handling; +- absent or invalid metadata without dangling separators. + +Regression verification should include the complete Android TV unit suite, +supply-chain checks, and the minified Android TV release assembly. A TV +emulator or external-device smoke should verify: + +- Up from the first row lands on the active pill across at least Home, a + library section, For You, and Calendar; +- Search is selected only on the Search route; +- held Up stops at the first content row; +- representative movie and episode heroes contain editorial metadata and no + resolution/HDR/audio badges. + +## Rollout + +Implement this as a focused follow-up on PR #126 while it remains open. Update +the tester APK after automated verification. Do not merge or deploy as part of +implementation. From b1742c4e4faa83ff83206431a49e0edd2037631d Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 06:11:00 +0200 Subject: [PATCH 17/65] docs(tv): plan active header focus and editorial hero --- ...d-tv-active-header-focus-editorial-hero.md | 560 ++++++++++++++++++ 1 file changed, 560 insertions(+) create mode 100644 docs/superpowers/plans/2026-07-28-android-tv-active-header-focus-editorial-hero.md diff --git a/docs/superpowers/plans/2026-07-28-android-tv-active-header-focus-editorial-hero.md b/docs/superpowers/plans/2026-07-28-android-tv-active-header-focus-editorial-hero.md new file mode 100644 index 0000000000..225be21d10 --- /dev/null +++ b/docs/superpowers/plans/2026-07-28-android-tv-active-header-focus-editorial-hero.md @@ -0,0 +1,560 @@ +# Android TV Active Header Focus and Editorial Hero Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Make content-to-header navigation land on the active TV section and replace browsing-hero stream badges with ordered editorial metadata. + +**Architecture:** Keep `TvMainShell` as the route-aware focus coordinator, pass its active root explicitly through `TvShellFocusState`, and let `TvTopMenuBar` apply the existing requester after one composition frame. Keep hero transformation inside `TvMarqueeContent.from`, using only existing `SectionItem` and enrichment data and leaving player/detail surfaces unchanged. + +**Tech Stack:** Kotlin 2.1, Jetpack Compose for TV, Compose focus APIs, Kotlin coroutines, Kotlin test/JUnit, Gradle. + +## Global Constraints + +- Android TV only; no Android phone behavior changes. +- No server, API, database, payload, schema, or production-configuration changes. +- No player-overlay, playback-settings, item-detail, stream-selection, transcoding, or subtitle changes. +- Preserve the held-Up boundary: repeated Up stops on the first content row and a fresh Up enters the menu. +- Search receives content-to-menu focus only while Search is the active route. +- Technical resolution, HDR, and audio data remains available to other consumers but is not rendered in browsing heroes. +- Preserve synopsis, cast/air-date enrichment, artwork, cache-first loading, and crossfade behavior. +- Missing or invalid metadata is omitted without placeholders or dangling separators. +- Do not merge or deploy; update open PR #126 only after all required verification is green. + +--- + +## File Map + +- `androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt` + derives the active root and supplies one explicit focus target to both Up and + Back paths. +- `androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvShellFocusState.kt` + carries the requested menu target without performing Compose focus itself. +- `androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuFocusRequest.kt` + provides the small frame-ordered focus application seam. +- `androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuBar.kt` + resolves the active target to an existing `FocusRequester` and applies it + after composition. +- `androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeModel.kt` + builds browsing-hero editorial metadata from `SectionItem`. +- `androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuFocusRequestTest.kt` + proves frame ordering and request-result propagation. +- `androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/shell/TvShellFocusStateTest.kt` + proves Up/Back retain the requested active root. +- `androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeModelTest.kt` + proves movie/episode metadata ordering and technical-badge removal. + +--- + +### Task 1: Make active-section header focus deterministic + +**Files:** +- Create: `androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuFocusRequest.kt` +- Create: `androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuFocusRequestTest.kt` +- Modify: `androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt:466-470,719-735,802-815` +- Modify: `androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvShellFocusState.kt:174-184,285-309` +- Modify: `androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuBar.kt:225-242` +- Modify: `androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/shell/TvShellFocusStateTest.kt:90-125,245-280` + +**Interfaces:** +- Consumes: `TvTopMenuPanel.Root(TvRootDestination)`, `TvShellFocusState.requestMenuFocus(TvTopMenuPanel?)`, and each existing top-menu `FocusRequester`. +- Produces: `internal suspend fun requestTopMenuFocusUntilApplied(awaitFrame: suspend () -> Unit, requestFocus: () -> Boolean)`. +- Produces: `TvShellFocusState.onBack(onTabRoot: Boolean, menuFocusTarget: TvTopMenuPanel? = null): TvShellBackAction`. +- Produces: one `selectedMenuFocusTarget: TvTopMenuPanel?` in `TvMainShell`, reused by content Up and Back. + +- [ ] **Step 1: Write the frame-ordering regression test** + +Create `TvTopMenuFocusRequestTest.kt`: + +```kotlin +package org.siloserver.silo.tv.ui.shell + +import kotlinx.coroutines.test.runTest +import kotlin.test.Test +import kotlin.test.assertEquals + +class TvTopMenuFocusRequestTest { + @Test + fun focusIsRequestedOnlyAfterTheTargetHasHadAFrameToCompose() = runTest { + val events = mutableListOf() + + requestTopMenuFocusUntilApplied( + awaitFrame = { events += "frame" }, + requestFocus = { events += "focus"; true }, + ) + + assertEquals(listOf("frame", "focus"), events) + } + + @Test + fun aTargetThatIsNotAttachedYetIsRetriedOnTheNextFrame() = runTest { + val events = mutableListOf() + var attempts = 0 + + requestTopMenuFocusUntilApplied( + awaitFrame = { events += "frame" }, + requestFocus = { + events += "focus" + attempts += 1 + attempts == 2 + }, + ) + + assertEquals(listOf("frame", "focus", "frame", "focus"), events) + } +} +``` + +- [ ] **Step 2: Add the active-root Back regression** + +Append to `TvShellFocusStateTest`: + +```kotlin +@Test +fun backFromRootContentRetainsTheActiveRootAsItsMenuTarget() { + val state = TvShellFocusState() + + assertEquals( + TvShellBackAction.MoveFocusToMenu, + state.onBack( + onTabRoot = true, + menuFocusTarget = moviesPanel, + ), + ) + + assertEquals(moviesPanel, state.menuFocusTarget) +} +``` + +- [ ] **Step 3: Run the focused tests and verify RED** + +Run: + +```bash +./gradlew :androidTvApp:testDebugUnitTest \ + --tests "org.siloserver.silo.tv.ui.shell.TvTopMenuFocusRequestTest" \ + --tests "org.siloserver.silo.tv.ui.shell.TvShellFocusStateTest" \ + --rerun-tasks --max-workers=2 --no-daemon +``` + +Expected: compilation fails because `requestTopMenuFocusUntilApplied` and the +`menuFocusTarget` argument do not exist. + +- [ ] **Step 4: Implement the frame-ordered focus seam** + +Create `TvTopMenuFocusRequest.kt`: + +```kotlin +package org.siloserver.silo.tv.ui.shell + +internal suspend fun requestTopMenuFocusUntilApplied( + awaitFrame: suspend () -> Unit, + requestFocus: () -> Boolean, +) { + do { + awaitFrame() + } while (!requestFocus()) +} +``` + +- [ ] **Step 5: Carry the active target through the state holder** + +Change `TvShellFocusState.onBack` to: + +```kotlin +fun onBack( + onTabRoot: Boolean, + menuFocusTarget: TvTopMenuPanel? = null, +): TvShellBackAction { + val action = tvShellBackAction( + panelOpen = openPanel != null, + profileMenuOpen = profileMenuOpen, + menuFocused = isMenuFocused, + onTabRoot = onTabRoot, + ) + when (action) { + TvShellBackAction.ClosePanel -> closePanel(returnFocusToBar = true) + TvShellBackAction.CloseProfileMenu -> dismissProfileMenu() + TvShellBackAction.MoveFocusToMenu -> requestMenuFocus(menuFocusTarget) + TvShellBackAction.MenuBack, + TvShellBackAction.DelegateToNav -> Unit + } + return action +} +``` + +Do not alter the pure `tvShellBackAction` precedence. + +- [ ] **Step 6: Derive one route-aware target and reuse it** + +Immediately after `selectedRoot` in `TvMainShell`, add: + +```kotlin +val selectedMenuFocusTarget = selectedRoot?.let(TvTopMenuPanel::Root) +``` + +Pass it to Back: + +```kotlin +focusState.onBack( + onTabRoot = selectedRoot != null, + menuFocusTarget = selectedMenuFocusTarget, +) +``` + +Use it at both first-row Up handoffs: + +```kotlin +focusState.requestMenuFocus(selectedMenuFocusTarget) +``` + +Leave `selectedMenuFocusTarget` null on Search. `TvTopMenuBar` must continue +using `isSearchActive` to select Search for that route; other secondary routes +must not silently select Home. + +- [ ] **Step 7: Apply the requester after composition and only acknowledge success** + +In `TvTopMenuBar`, replace the immediate focus call inside the +`LaunchedEffect(focusRequest, isFocusSuppressed)` with: + +```kotlin +requestTopMenuFocusUntilApplied( + awaitFrame = { androidx.compose.runtime.withFrameNanos { } }, + requestFocus = { + runCatching { requester.requestFocus() }.getOrDefault(false) + }, +) +lastHandledFocusRequest = focusRequest +``` + +Move the existing `lastHandledFocusRequest = focusRequest` assignment out of +the pre-request path. The frame loop suspends rather than spins and is cancelled +automatically if the `LaunchedEffect` keys change. Keep the explicit-target +resolution and `dwellSuppressedButton` behavior unchanged. + +- [ ] **Step 8: Run focused tests and verify GREEN** + +Run the command from Step 3. + +Expected: both test classes pass with zero failures. + +- [ ] **Step 9: Run the existing Up-navigation regression** + +Run: + +```bash +./gradlew :androidTvApp:testDebugUnitTest \ + --tests "org.siloserver.silo.tv.ui.components.TvSkylineUpNavigationTest" \ + --rerun-tasks --max-workers=2 --no-daemon +``` + +Expected: all four held-Up/row-relocation tests pass unchanged. + +- [ ] **Step 10: Commit the focus correction** + +```bash +git add \ + androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt \ + androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvShellFocusState.kt \ + androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuBar.kt \ + androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuFocusRequest.kt \ + androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/shell/TvShellFocusStateTest.kt \ + androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuFocusRequestTest.kt +git commit -m "fix(tv): restore active header focus from content" +``` + +--- + +### Task 2: Replace stream badges with editorial hero metadata + +**Files:** +- Modify: `androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeModel.kt:75-165` +- Modify: `androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeModelTest.kt:1-32` + +**Interfaces:** +- Consumes: `SectionItem.year`, `durationSeconds`, `ratingImdb`, `genres`, `contentRating`, `seriesTitle`, `seasonNumber`, `episodeNumber`, and existing `TvMarqueeEnrichment.detailLine`. +- Produces: `TvMarqueeContent.badges` containing only an optional uppercase content classification. +- Produces: ordered `TvMarqueeContent.metaParts`: movie `year → runtime → IMDb → genre`; episode `Sx Ey → episode title → runtime → IMDb`. + +- [ ] **Step 1: Replace quality-badge tests with movie editorial-metadata RED** + +Replace `TvFocusMarqueeModelTest` with: + +```kotlin +package org.siloserver.silo.tv.ui.components + +import org.siloserver.silo.model.catalog.OverlaySummary +import org.siloserver.silo.model.section.SectionItem +import kotlin.test.Test +import kotlin.test.assertEquals + +class TvFocusMarqueeModelTest { + @Test + fun movieHeroPrioritizesEditorialMetadataAndOmitsStreamQuality() { + val content = TvMarqueeContent.from( + item = SectionItem( + contentId = "movie-1", + type = "movie", + title = "Arrival", + year = 2016, + genres = listOf("Science Fiction"), + ratingImdb = 7.9, + contentRating = "PG-13", + durationSeconds = 6_960.0, + overlaySummary = OverlaySummary( + resolution = "2160p", + hdr = "Dolby Vision", + audio = "TrueHD Atmos", + ), + ), + rowTitle = "Popular", + ) + + assertEquals(listOf("PG-13"), content.badges) + assertEquals( + listOf("2016", "1h 56m", "7.9", "Science Fiction"), + content.metaParts, + ) + } + + @Test + fun episodeHeroUsesSeriesTitleAndEditorialEpisodeMetadata() { + val content = TvMarqueeContent.from( + item = SectionItem( + contentId = "episode-1", + type = "episode", + title = "Long, Long Time", + seriesTitle = "The Last of Us", + seasonNumber = 1, + episodeNumber = 3, + ratingImdb = 8.6, + contentRating = "TV-MA", + durationSeconds = 4_560.0, + overlaySummary = OverlaySummary( + resolution = "1080p", + audio = "EAC3", + ), + ), + rowTitle = "Continue Watching", + ) + + assertEquals("The Last of Us", content.title) + assertEquals(listOf("TV-MA"), content.badges) + assertEquals( + listOf("S1 E3", "Long, Long Time", "1h 16m", "8.6"), + content.metaParts, + ) + } + + @Test + fun missingEditorialMetadataProducesNoEmptyTokensOrBadges() { + val content = TvMarqueeContent.from( + item = SectionItem( + contentId = "movie-2", + type = "movie", + title = "Untitled", + overlaySummary = OverlaySummary( + resolution = "2160p", + hdr = "HDR10", + audio = "Atmos", + ), + ), + rowTitle = "Recently Added", + ) + + assertEquals(emptyList(), content.badges) + assertEquals(emptyList(), content.metaParts) + } +} +``` + +- [ ] **Step 2: Run the model test and verify RED** + +Run: + +```bash +./gradlew :androidTvApp:testDebugUnitTest \ + --tests "org.siloserver.silo.tv.ui.components.TvFocusMarqueeModelTest" \ + --rerun-tasks --max-workers=2 --no-daemon +``` + +Expected: the movie order differs, the episode lacks its rating, and technical +quality badges are still present. + +- [ ] **Step 3: Implement the approved metadata ordering** + +In `TvMarqueeContent.from`, build metadata exactly as follows: + +```kotlin +val meta = mutableListOf() +if (isEpisode) { + episodeToken(item.seasonNumber, item.episodeNumber)?.let(meta::add) + if (item.title.isNotBlank()) meta.add(item.title) + lengthText(item.durationSeconds)?.let(meta::add) + item.ratingImdb?.let { meta.add(formatRating(it)) } +} else { + if (item.year > 0) meta.add(item.year.toString()) + lengthText(item.durationSeconds)?.let(meta::add) + item.ratingImdb?.let { meta.add(formatRating(it)) } + item.genres.firstOrNull { it.isNotBlank() }?.let(meta::add) +} + +val badges = item.contentRating + ?.takeIf { it.isNotBlank() } + ?.uppercase(Locale.US) + ?.let(::listOf) + .orEmpty() +``` + +Delete `qualityBadges`, `dynamicRangeBadge`, `audioBadge`, and +`prettyResolution`; they have no remaining callers. Do not remove +`SectionItem.overlaySummary` or change shared models. + +- [ ] **Step 4: Preserve enrichment and rendering contracts** + +Verify by inspection that `TvMarqueeEnrichment.from` still emits its existing +air-date/cast `detailLine`, `TvMarqueeContent.withEnrichment` still preserves +the content identity, and `TvFocusMarquee` still omits the badge/meta row when +both lists are empty. Make no changes to those paths. + +- [ ] **Step 5: Run the focused model test and verify GREEN** + +Run the command from Step 2. + +Expected: all three tests pass with zero failures. + +- [ ] **Step 6: Commit the editorial hero correction** + +```bash +git add \ + androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeModel.kt \ + androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeModelTest.kt +git commit -m "fix(tv): show editorial metadata in browse heroes" +``` + +--- + +### Task 3: Verify, review, package, and update PR #126 + +**Files:** +- Verify only: all branch changes against `origin/main` +- Output only, not committed: Android TV universal minified release APK +- Update remotely after green: existing PR #126 description/checklist + +**Interfaces:** +- Consumes: Tasks 1 and 2 commits. +- Produces: independently reviewed, fully verified PR #126 head and a clearly named tester APK. + +- [ ] **Step 1: Run all focused regressions together** + +```bash +./gradlew :androidTvApp:testDebugUnitTest \ + --tests "org.siloserver.silo.tv.ui.shell.TvTopMenuFocusRequestTest" \ + --tests "org.siloserver.silo.tv.ui.shell.TvShellFocusStateTest" \ + --tests "org.siloserver.silo.tv.ui.components.TvSkylineUpNavigationTest" \ + --tests "org.siloserver.silo.tv.ui.components.TvFocusMarqueeModelTest" \ + --rerun-tasks --max-workers=2 --no-daemon +``` + +Expected: all selected tests pass with zero failures. + +- [ ] **Step 2: Run supply-chain policy checks** + +```bash +./scripts/test-check-build-supply-chain.sh +./scripts/check-build-supply-chain.sh +``` + +Expected: both scripts exit 0. + +- [ ] **Step 3: Run the complete fresh TV test and release gate** + +```bash +./gradlew \ + :androidTvApp:testDebugUnitTest \ + :androidTvApp:assembleRelease \ + -PallowDebugReleaseSigning=true \ + --rerun-tasks --max-workers=2 --no-daemon +``` + +Expected: `BUILD SUCCESSFUL`; all TV unit XML results have zero failures and +the minified release APK is produced. + +- [ ] **Step 4: Perform the required device/emulator smoke** + +On a dedicated Android TV emulator or tester device, without touching an +unapproved physical device: + +1. Open Home, press Down into content, move to the first row, then press a + fresh Up; verify Home receives focus. +2. Repeat for one library section, For You, and Calendar; verify the active + pill receives focus each time. +3. Hold Up from a lower row; verify focus stops on the first content row. +4. Open Search and verify its route still owns Search focus. +5. Focus one movie and one episode; verify no resolution/HDR/audio badges are + shown and the approved editorial fields appear in order. + +Record the emulator/device identity and pass/fail result in the PR. If no +approved target is available, mark this smoke as pending instead of claiming +it passed. + +- [ ] **Step 5: Request independent focused review** + +Provide the reviewer: + +- the approved spec; +- `git diff origin/main...HEAD`; +- focused and full test results; +- the focus request timing/target contract; +- movie and episode metadata order; +- explicit instruction to flag production-semantic changes outside the TV + shell/marquee scope. + +Address only verified findings, rerun the affected focused test, and repeat +review until approved. + +- [ ] **Step 6: Verify diff hygiene and branch state** + +```bash +git diff --check origin/main...HEAD +git status --short --branch +git log --oneline origin/main..HEAD +``` + +Expected: no whitespace errors, no uncommitted files, and only the documented +TV navigation/hero commits plus their specs/plans. + +- [ ] **Step 7: Copy and verify the tester APK** + +Select the universal APK from the TV release output, verify it with +`apksigner verify --verbose`, inspect package/version/ABI metadata with +`apkanalyzer`, calculate `shasum -a 256`, and copy it without overwriting prior +artifacts: + +```bash +cp androidTvApp/build/outputs/apk/release/androidTvApp-universal-release.apk \ + "/Users/jimcole/Desktop/Silo Releases/Silo-TV-Universal-0.3.11-TVFocusHeroFix-$(git rev-parse --short HEAD).apk" +``` + +If the generated filename differs, select the universal artifact explicitly; +never substitute an ABI-specific split. Report that +`-PallowDebugReleaseSigning=true` produces a debug-signed release build that +only upgrades installations signed by the same certificate. + +- [ ] **Step 8: Push and update PR #126** + +```bash +git push origin fix/tv-for-you-cold-navigation +gh pr view 126 --repo Silo-Server/silo-android \ + --json state,isDraft,baseRefName,headRefName,mergeable,statusCheckRollup +``` + +Update the PR description to include: + +- active-section focus restoration; +- editorial-only movie/episode hero metadata; +- focused/full verification evidence; +- independent review verdict; +- device-smoke result or its explicit pending status; +- tester APK signing caveat. + +Do not merge PR #126. From 2fc204c5b3210535df29a9881d1460d774b2e364 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 06:26:19 +0200 Subject: [PATCH 18/65] fix(tv): restore active header focus from content --- .../silo/tv/ui/shell/TvMainShell.kt | 10 ++++-- .../silo/tv/ui/shell/TvShellFocusState.kt | 7 ++-- .../silo/tv/ui/shell/TvTopMenuBar.kt | 9 +++-- .../silo/tv/ui/shell/TvTopMenuFocusRequest.kt | 10 ++++++ .../silo/tv/ui/shell/TvShellFocusStateTest.kt | 15 ++++++++ .../tv/ui/shell/TvTopMenuFocusRequestTest.kt | 36 +++++++++++++++++++ 6 files changed, 80 insertions(+), 7 deletions(-) create mode 100644 androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuFocusRequest.kt create mode 100644 androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuFocusRequestTest.kt diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt index 81d9b36b40..b4b41bc29a 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt @@ -466,6 +466,7 @@ fun TvMainShell( val selectedRoot by remember(currentRoute) { derivedStateOf { mapRouteToRoot(currentRoute) } } + val selectedMenuFocusTarget = selectedRoot?.let(TvTopMenuPanel::Root) // Which libraries actually HAVE collections — gates the cascade's // Collections pill so an empty library doesn't offer a dead-end section @@ -716,7 +717,10 @@ fun TvMainShell( // half (close panel / dropdown); we run only the side effect // each action needs. Keeping it here — not in the selector or // the bar — means Back can never be double-handled. - when (focusState.onBack(onTabRoot = selectedRoot != null)) { + when (focusState.onBack( + onTabRoot = selectedRoot != null, + menuFocusTarget = selectedMenuFocusTarget, + )) { // Panel/dropdown already closed by onBack(): just consume. TvShellBackAction.ClosePanel, TvShellBackAction.CloseProfileMenu -> true @@ -802,7 +806,7 @@ fun TvMainShell( val contentHandledUp = contentUpFallback?.invoke(isRepeat) if (contentHandledUp != null) { if (!contentHandledUp) { - focusState.requestMenuFocus() + focusState.requestMenuFocus(selectedMenuFocusTarget) } } else { // Try to move focus up inside content; if that @@ -810,7 +814,7 @@ fun TvMainShell( // focus to the menu bar. val moved = focusManager.moveFocus(FocusDirection.Up) if (!moved) { - focusState.requestMenuFocus() + focusState.requestMenuFocus(selectedMenuFocusTarget) } } // Always consume: we performed the move (or routed diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvShellFocusState.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvShellFocusState.kt index a22c249248..7018908d54 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvShellFocusState.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvShellFocusState.kt @@ -289,7 +289,10 @@ class TvShellFocusState { * and [TvShellBackAction.DelegateToNav] are left to the composable, which owns * the focus manager and nav controller). */ - fun onBack(onTabRoot: Boolean): TvShellBackAction { + fun onBack( + onTabRoot: Boolean, + menuFocusTarget: TvTopMenuPanel? = null, + ): TvShellBackAction { val action = tvShellBackAction( panelOpen = openPanel != null, profileMenuOpen = profileMenuOpen, @@ -299,7 +302,7 @@ class TvShellFocusState { when (action) { TvShellBackAction.ClosePanel -> closePanel(returnFocusToBar = true) TvShellBackAction.CloseProfileMenu -> dismissProfileMenu() - TvShellBackAction.MoveFocusToMenu -> requestMenuFocus() + TvShellBackAction.MoveFocusToMenu -> requestMenuFocus(menuFocusTarget) TvShellBackAction.MenuBack, TvShellBackAction.DelegateToNav -> Unit } diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuBar.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuBar.kt index 0479406ed6..5d721f6e73 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuBar.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuBar.kt @@ -233,11 +233,16 @@ fun TvTopMenuBar( LaunchedEffect(focusRequest, isFocusSuppressed) { if (isFocusSuppressed) return@LaunchedEffect if (focusRequest == lastHandledFocusRequest) return@LaunchedEffect - lastHandledFocusRequest = focusRequest val explicitFocus = focusRequestTarget?.let(::focusForPanel) dwellSuppressedButton = explicitFocus val requester = explicitFocus?.let(::requesterForFocus) ?: selectedEntryRequester() - runCatching { requester.requestFocus() } + requestTopMenuFocusUntilApplied( + awaitFrame = { androidx.compose.runtime.withFrameNanos { } }, + requestFocus = { + runCatching { requester.requestFocus() }.getOrDefault(false) + }, + ) + lastHandledFocusRequest = focusRequest } LaunchedEffect(focusedButton) { diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuFocusRequest.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuFocusRequest.kt new file mode 100644 index 0000000000..6e3ecaac94 --- /dev/null +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuFocusRequest.kt @@ -0,0 +1,10 @@ +package org.siloserver.silo.tv.ui.shell + +internal suspend fun requestTopMenuFocusUntilApplied( + awaitFrame: suspend () -> Unit, + requestFocus: () -> Boolean, +) { + do { + awaitFrame() + } while (!requestFocus()) +} diff --git a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/shell/TvShellFocusStateTest.kt b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/shell/TvShellFocusStateTest.kt index 49888569e5..52378fb061 100644 --- a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/shell/TvShellFocusStateTest.kt +++ b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/shell/TvShellFocusStateTest.kt @@ -98,6 +98,21 @@ class TvShellFocusStateTest { ) } + @Test + fun backFromRootContentRetainsTheActiveRootAsItsMenuTarget() { + val state = TvShellFocusState() + + assertEquals( + TvShellBackAction.MoveFocusToMenu, + state.onBack( + onTabRoot = true, + menuFocusTarget = moviesPanel, + ), + ) + + assertEquals(moviesPanel, state.menuFocusTarget) + } + @Test fun backOnSecondaryScreensStillDelegatesToNav() { assertEquals( diff --git a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuFocusRequestTest.kt b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuFocusRequestTest.kt new file mode 100644 index 0000000000..f70b14b841 --- /dev/null +++ b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuFocusRequestTest.kt @@ -0,0 +1,36 @@ +package org.siloserver.silo.tv.ui.shell + +import kotlinx.coroutines.test.runTest +import kotlin.test.Test +import kotlin.test.assertEquals + +class TvTopMenuFocusRequestTest { + @Test + fun focusIsRequestedOnlyAfterTheTargetHasHadAFrameToCompose() = runTest { + val events = mutableListOf() + + requestTopMenuFocusUntilApplied( + awaitFrame = { events += "frame" }, + requestFocus = { events += "focus"; true }, + ) + + assertEquals(listOf("frame", "focus"), events) + } + + @Test + fun aTargetThatIsNotAttachedYetIsRetriedOnTheNextFrame() = runTest { + val events = mutableListOf() + var attempts = 0 + + requestTopMenuFocusUntilApplied( + awaitFrame = { events += "frame" }, + requestFocus = { + events += "focus" + attempts += 1 + attempts == 2 + }, + ) + + assertEquals(listOf("frame", "focus", "frame", "focus"), events) + } +} From 0482bd9b9695604c998b1269f2adb0a99cd49a19 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 06:33:09 +0200 Subject: [PATCH 19/65] fix(tv): show editorial metadata in browse heroes --- .../tv/ui/components/TvFocusMarqueeModel.kt | 72 +++-------------- .../ui/components/TvFocusMarqueeModelTest.kt | 79 ++++++++++++++++--- 2 files changed, 76 insertions(+), 75 deletions(-) diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeModel.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeModel.kt index c79442dff4..5e49df1e08 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeModel.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeModel.kt @@ -27,10 +27,9 @@ data class TvMarqueeContent( val id: String, val title: String, val logoUrl: String?, - /** Codec/HDR + content-rating chips (`4K`, `DOLBY VISION`, `ATMOS`). */ + /** Optional uppercase content-classification chip. */ val badges: List, - /** Dot-joined meta tokens after the badges: year · genre · runtime, or - * `S2 E7 · episode title · 45 min · 23m left` for episodes. */ + /** Dot-joined editorial metadata after the badge. */ val metaParts: List, val synopsis: String?, /** A quieter detail line: cast / air-date when carried by the payload. */ @@ -87,19 +86,19 @@ data class TvMarqueeContent( episodeToken(item.seasonNumber, item.episodeNumber)?.let(meta::add) if (item.title.isNotBlank()) meta.add(item.title) lengthText(item.durationSeconds)?.let(meta::add) - timeLeftText(item.positionSeconds, item.durationSeconds)?.let(meta::add) + item.ratingImdb?.let { meta.add(formatRating(it)) } } else { if (item.year > 0) meta.add(item.year.toString()) - item.genres.firstOrNull { it.isNotBlank() }?.let(meta::add) lengthText(item.durationSeconds)?.let(meta::add) item.ratingImdb?.let { meta.add(formatRating(it)) } + item.genres.firstOrNull { it.isNotBlank() }?.let(meta::add) } - // Codec/HDR + content-rating chips (`4K · DOLBY VISION · ATMOS · - // TV-MA`) derived from the section payload's overlay summary, then - // the content rating — mirrors tvOS `TVFocusMarquee.badges(from:)`. - val badges = qualityBadges(item.overlaySummary).toMutableList() - item.contentRating?.takeIf { it.isNotBlank() }?.let { badges.add(it.uppercase()) } + val badges = item.contentRating + ?.takeIf { it.isNotBlank() } + ?.uppercase(Locale.US) + ?.let(::listOf) + .orEmpty() val sectionBackdropUrl = item.backdropUrl?.takeIf { it.isNotBlank() } val sectionPosterUrl = item.posterUrl?.takeIf { it.isNotBlank() } @@ -127,59 +126,6 @@ data class TvMarqueeContent( ) } - /** - * Headline quality trio — resolution, dynamic range, audio — uppercased - * to the Skyline badge style, from the section payload's overlay summary. - * Mirrors tvOS `TVFocusMarquee.badges(from:)`. - */ - internal fun qualityBadges(summary: org.siloserver.silo.model.catalog.OverlaySummary?): List { - if (summary == null) return emptyList() - val badges = mutableListOf() - prettyResolution(summary.resolution)?.let(badges::add) - summary.hdr?.takeIf { it.isNotBlank() }?.let { hdr -> - badges.add(dynamicRangeBadge(hdr)) - } - summary.audio?.takeIf { it.isNotBlank() }?.let { audio -> - badges.add(audioBadge(audio)) - } - return badges.distinct() - } - - private fun dynamicRangeBadge(value: String): String { - val normalized = value.trim().lowercase(Locale.US) - return when { - normalized.contains("dolby vision") || - normalized.contains("dovi") || - Regex("(^|[^a-z])dv([^a-z]|$)").containsMatchIn(normalized) -> "DOLBY VISION" - normalized.contains("hdr10+") || normalized.contains("hdr10 plus") -> "HDR10+" - normalized.contains("hdr10") -> "HDR10" - normalized.contains("hlg") -> "HLG" - else -> value.trim().uppercase(Locale.US) - } - } - - private fun audioBadge(value: String): String { - val normalized = value.trim().lowercase(Locale.US) - return when { - normalized.contains("atmos") || - Regex("(^|[^a-z])joc([^a-z]|$)").containsMatchIn(normalized) -> "ATMOS" - normalized.contains("dts-hd") || normalized.contains("dts hd") -> "DTS-HD" - normalized.contains("truehd") || normalized.contains("true hd") -> "TRUEHD" - normalized.contains("e-ac-3") || normalized.contains("eac3") -> "EAC3" - normalized.contains("ac-3") || normalized == "ac3" -> "AC3" - else -> value.trim().uppercase(Locale.US) - } - } - - private fun prettyResolution(value: String?): String? { - val v = value?.takeIf { it.isNotBlank() } ?: return null - return when (v.lowercase()) { - "2160p", "4k", "uhd" -> "4K" - "4320p", "8k" -> "8K" - else -> v.uppercase() - } - } - private fun episodeToken(season: Int?, episode: Int?): String? = when { season != null && episode != null -> "S$season E$episode" season != null -> "Season $season" diff --git a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeModelTest.kt b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeModelTest.kt index dcee0e0feb..950a3da76a 100644 --- a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeModelTest.kt +++ b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeModelTest.kt @@ -1,30 +1,85 @@ package org.siloserver.silo.tv.ui.components import org.siloserver.silo.model.catalog.OverlaySummary +import org.siloserver.silo.model.section.SectionItem import kotlin.test.Test import kotlin.test.assertEquals class TvFocusMarqueeModelTest { - - @Test fun qualityBadgesPreserveDolbyVisionAndAtmos() { - val summary = OverlaySummary( - resolution = "2160p", - hdr = "Dolby Vision", - audio = "TrueHD Atmos", + @Test + fun movieHeroPrioritizesEditorialMetadataAndOmitsStreamQuality() { + val content = TvMarqueeContent.from( + item = SectionItem( + contentId = "movie-1", + type = "movie", + title = "Arrival", + year = 2016, + genres = listOf("Science Fiction"), + ratingImdb = 7.9, + contentRating = "PG-13", + durationSeconds = 6_960.0, + overlaySummary = OverlaySummary( + resolution = "2160p", + hdr = "Dolby Vision", + audio = "TrueHD Atmos", + ), + ), + rowTitle = "Popular", ) + assertEquals(listOf("PG-13"), content.badges) assertEquals( - listOf("4K", "DOLBY VISION", "ATMOS"), - TvMarqueeContent.qualityBadges(summary), + listOf("2016", "1h 56m", "7.9", "Science Fiction"), + content.metaParts, ) } - @Test fun qualityBadgesPreserveHdr10AndDtsHd() { - val summary = OverlaySummary(hdr = "HDR10", audio = "DTS-HD") + @Test + fun episodeHeroUsesSeriesTitleAndEditorialEpisodeMetadata() { + val content = TvMarqueeContent.from( + item = SectionItem( + contentId = "episode-1", + type = "episode", + title = "Long, Long Time", + seriesTitle = "The Last of Us", + seasonNumber = 1, + episodeNumber = 3, + ratingImdb = 8.6, + contentRating = "TV-MA", + durationSeconds = 4_560.0, + overlaySummary = OverlaySummary( + resolution = "1080p", + audio = "EAC3", + ), + ), + rowTitle = "Continue Watching", + ) + assertEquals("The Last of Us", content.title) + assertEquals(listOf("TV-MA"), content.badges) assertEquals( - listOf("HDR10", "DTS-HD"), - TvMarqueeContent.qualityBadges(summary), + listOf("S1 E3", "Long, Long Time", "1h 16m", "8.6"), + content.metaParts, + ) + } + + @Test + fun missingEditorialMetadataProducesNoEmptyTokensOrBadges() { + val content = TvMarqueeContent.from( + item = SectionItem( + contentId = "movie-2", + type = "movie", + title = "Untitled", + overlaySummary = OverlaySummary( + resolution = "2160p", + hdr = "HDR10", + audio = "Atmos", + ), + ), + rowTitle = "Recently Added", ) + + assertEquals(emptyList(), content.badges) + assertEquals(emptyList(), content.metaParts) } } From 7098914766818e59c4eefffb844a1f3391490b0c Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 06:45:09 +0200 Subject: [PATCH 20/65] docs(android): extend editorial heroes to phone --- ...ive-header-focus-editorial-hero-design.md} | 110 +++++++++++++----- 1 file changed, 79 insertions(+), 31 deletions(-) rename docs/superpowers/specs/{2026-07-28-android-tv-active-header-focus-editorial-hero-design.md => 2026-07-28-android-active-header-focus-editorial-hero-design.md} (52%) diff --git a/docs/superpowers/specs/2026-07-28-android-tv-active-header-focus-editorial-hero-design.md b/docs/superpowers/specs/2026-07-28-android-active-header-focus-editorial-hero-design.md similarity index 52% rename from docs/superpowers/specs/2026-07-28-android-tv-active-header-focus-editorial-hero-design.md rename to docs/superpowers/specs/2026-07-28-android-active-header-focus-editorial-hero-design.md index faaa51baaf..ce2915649b 100644 --- a/docs/superpowers/specs/2026-07-28-android-tv-active-header-focus-editorial-hero-design.md +++ b/docs/superpowers/specs/2026-07-28-android-active-header-focus-editorial-hero-design.md @@ -1,8 +1,8 @@ -# Android TV Active Header Focus and Editorial Hero Design +# Android Active Header Focus and Editorial Hero Design -**Date:** 2026-07-28 -**Status:** Approved for implementation planning -**Scope:** Android TV browsing shell and browsing heroes only +**Date:** 2026-07-28 +**Status:** Approved for implementation planning +**Scope:** Android TV header focus; Android phone and TV browsing heroes ## Context @@ -13,14 +13,15 @@ presentation defects: 1. Pressing Up from the first content row can focus Search instead of the currently active top-menu destination. Pressing Back from the same page correctly focuses the active destination. -2. Browsing heroes prioritize technical stream badges such as resolution, - HDR, and audio format ahead of editorial information. This can crowd or - truncate the year, runtime, episode identity, and rating that people use to - decide what to watch. +2. TV browsing heroes prioritize technical stream badges such as resolution, + HDR, and audio format ahead of editorial information. Phone library heroes + already avoid those technical fields, but their generic type/year/rating + chips omit runtime, content classification, and genre. Issue #78 asks for richer title metadata, but its current wording refers to the -player. This change applies the approved behavior to browsing heroes only and -does not change the player or item-detail surfaces. +player. This change applies the approved behavior to Android phone and TV +browsing heroes only and does not change either player's or item-detail +surface. ## Goals @@ -29,18 +30,23 @@ does not change the player or item-detail surfaces. - Search receives this focus only when Search is the active route. - Preserve the existing held-Up boundary: a held key stops on the first content row and requires a fresh Up press before entering the menu. -- Browsing heroes describe the focused title using editorial metadata instead - of video/audio delivery characteristics. -- Keep the change inside the existing shared TV shell and marquee model. +- Phone and TV browsing heroes describe the title using consistent editorial + metadata instead of delivery characteristics or generic media-type labels. +- Keep TV focus behavior inside the existing shared TV shell. +- Keep hero presentation inside the existing TV marquee model and phone + featured-carousel metadata helper. ## Non-goals - No server, API, database, or payload changes. -- No Android phone changes. - No player-overlay, playback-settings, or item-detail redesign. +- No phone Home hero: Android phone Home intentionally renders rows without a + billboard, so phone changes apply only to the existing Library Recommended + featured carousel. - No changes to stream selection, transcoding, subtitle behavior, or technical metadata availability outside the browsing hero. - No new user preference or display toggle. +- No Apple-client changes. ## Focus Behavior @@ -65,13 +71,14 @@ previous-row relocation and ordinary row-to-row Up movement are unchanged. Panel preview, profile menu, Left/Right menu traversal, and Down-to-content behavior are unchanged. -## Browsing Hero Metadata +## Shared Browsing Hero Metadata -The browsing marquee stops rendering resolution, HDR, and audio-format badges. -Technical overlay data remains in the model for other consumers but is not -converted into hero badges. +The TV browsing marquee stops rendering resolution, HDR, and audio-format +badges. Technical overlay data remains in the model for other consumers but is +not converted into hero badges. The phone featured carousel continues to avoid +technical delivery data. -The hero uses the following ordered editorial fields when present: +Both Android clients use the following ordered editorial fields when present: ### Movies and other non-episode titles @@ -104,6 +111,31 @@ line if the current payload/enrichment boundary does not expose air date early enough for the primary metadata line. It must not add another detail request or delay first paint to rearrange those fields. +### TV presentation + +TV retains its existing badge-plus-metadata-line layout. Content +classification is its only hero badge; the remaining fields form the ordered +single metadata line. The existing episode series title, episode-name +placement, synopsis, and quieter air-date/cast enrichment remain unchanged. + +### Phone presentation + +Phone applies the editorial fields to the existing featured carousel used on +Library Recommended pages: + +- Remove the generic `Movie` or `Episode` type chip. +- Preserve the existing series eyebrow and title treatment, so an episode + continues to show the series name and episode name without duplication. +- Present the ordered metadata as compact chips using the existing chip visual + style. +- Allow chips to wrap onto a second line on narrow phones rather than clipping + or forcing horizontal scrolling. +- Do not add a hero to phone Home or change item-card overlays. + +Phone does not perform detail enrichment in the carousel. Air date remains +absent when it is not carried by the existing section payload; no new request +is introduced to obtain it. + ## Data Flow and Boundaries - `TvMainShell` derives the active root destination from the current route. @@ -115,8 +147,13 @@ delay first paint to rearrange those fields. ordered editorial metadata. - Existing detail enrichment may continue to add air-date/cast information without blocking or re-fetching on focus. +- `FeaturedCarousel.metadataChips` converts the same existing `SectionItem` + fields into ordered phone chips. +- The phone carousel layout owns responsive wrapping without changing its + paging, play, More Info, or backdrop behavior. -No parallel focus coordinator or marquee data source is introduced. +No parallel focus coordinator, marquee data source, or phone detail fetch is +introduced. ## Error and Edge Handling @@ -124,11 +161,13 @@ No parallel focus coordinator or marquee data source is introduced. route-specific behavior rather than silently selecting Home. - If a requested library pill is temporarily absent, use the existing safe requester fallback and do not crash. -- Invalid, zero, blank, or unavailable metadata is omitted. -- Ratings and runtimes keep the existing formatting and rounding rules unless - a focused test demonstrates an incorrect value. +- Invalid, non-finite, zero, negative, blank, or unavailable metadata is + omitted. +- Valid ratings and runtimes keep the existing formatting and rounding rules. - Removing technical badges must not create an empty visual row; the row is omitted when no editorial badge or metadata value exists. +- Phone wrapping is bounded to two lines of metadata chips; it must not cover + the carousel actions or change the carousel's page height. ## Verification @@ -136,13 +175,16 @@ Focused tests should cover: - route-to-menu target mapping for every root destination and Search; - the held-Up first-row boundary remains unchanged; -- movie metadata ordering and omission of resolution/HDR/audio; -- episode metadata ordering, series/episode naming, runtime, rating, and +- TV movie metadata ordering and omission of resolution/HDR/audio; +- TV episode metadata ordering, series/episode naming, runtime, rating, and content-classification handling; -- absent or invalid metadata without dangling separators. +- phone movie and episode chip ordering, removal of the generic type chip, + runtime/content-classification inclusion, and no technical delivery fields; +- absent, zero, negative, NaN, or infinite ratings and runtimes without empty + chips or dangling separators. -Regression verification should include the complete Android TV unit suite, -supply-chain checks, and the minified Android TV release assembly. A TV +Regression verification should include the complete Android phone and TV unit +suites, supply-chain checks, and both minified release assemblies. A TV emulator or external-device smoke should verify: - Up from the first row lands on the active pill across at least Home, a @@ -152,8 +194,14 @@ emulator or external-device smoke should verify: - representative movie and episode heroes contain editorial metadata and no resolution/HDR/audio badges. +A phone emulator smoke should verify that representative movie and episode +featured-carousel pages show the approved chips, wrap without overlapping +actions on a narrow viewport, and retain Play, More Info, paging, and artwork. + ## Rollout -Implement this as a focused follow-up on PR #126 while it remains open. Update -the tester APK after automated verification. Do not merge or deploy as part of -implementation. +Implement this as a focused follow-up on PR #126 while it remains open. The +shared hydration/navigation-performance commits already in PR #126 are its +accepted baseline and remain unchanged; this follow-up does not need to split +or reclassify them. Update both tester APKs after automated verification. Do +not merge or deploy as part of implementation. From 41bbe4ec3fd4fc7465a0ff8a79648df8e740adf1 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 06:47:55 +0200 Subject: [PATCH 21/65] docs(android): extend hero plan to phone --- ...d-tv-active-header-focus-editorial-hero.md | 422 +++++++++++++++++- 1 file changed, 398 insertions(+), 24 deletions(-) diff --git a/docs/superpowers/plans/2026-07-28-android-tv-active-header-focus-editorial-hero.md b/docs/superpowers/plans/2026-07-28-android-tv-active-header-focus-editorial-hero.md index 225be21d10..b69b3de169 100644 --- a/docs/superpowers/plans/2026-07-28-android-tv-active-header-focus-editorial-hero.md +++ b/docs/superpowers/plans/2026-07-28-android-tv-active-header-focus-editorial-hero.md @@ -1,23 +1,28 @@ -# Android TV Active Header Focus and Editorial Hero Implementation Plan +# Android Active Header Focus and Editorial Hero Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. -**Goal:** Make content-to-header navigation land on the active TV section and replace browsing-hero stream badges with ordered editorial metadata. +**Goal:** Make content-to-header navigation land on the active TV section and present ordered editorial browsing metadata on Android phone and TV. -**Architecture:** Keep `TvMainShell` as the route-aware focus coordinator, pass its active root explicitly through `TvShellFocusState`, and let `TvTopMenuBar` apply the existing requester after one composition frame. Keep hero transformation inside `TvMarqueeContent.from`, using only existing `SectionItem` and enrichment data and leaving player/detail surfaces unchanged. +**Architecture:** Keep `TvMainShell` as the route-aware focus coordinator, pass its active root explicitly through `TvShellFocusState`, and let `TvTopMenuBar` apply the existing requester after composition. Keep TV hero transformation inside `TvMarqueeContent.from` and phone hero transformation in a small pure `FeaturedCarousel` metadata helper, using only existing `SectionItem` data and leaving player/detail surfaces unchanged. -**Tech Stack:** Kotlin 2.1, Jetpack Compose for TV, Compose focus APIs, Kotlin coroutines, Kotlin test/JUnit, Gradle. +**Tech Stack:** Kotlin 2.1, Jetpack Compose/Compose for TV, Compose focus and `FlowRow` layout APIs, Kotlin coroutines, Kotlin test/JUnit, Gradle. ## Global Constraints -- Android TV only; no Android phone behavior changes. +- TV header-focus behavior is Android TV only. +- Editorial browsing-hero metadata applies to Android phone and TV. - No server, API, database, payload, schema, or production-configuration changes. - No player-overlay, playback-settings, item-detail, stream-selection, transcoding, or subtitle changes. +- No phone Home hero; phone scope is the existing Library Recommended featured carousel only. +- No Apple-client changes. - Preserve the held-Up boundary: repeated Up stops on the first content row and a fresh Up enters the menu. - Search receives content-to-menu focus only while Search is the active route. - Technical resolution, HDR, and audio data remains available to other consumers but is not rendered in browsing heroes. - Preserve synopsis, cast/air-date enrichment, artwork, cache-first loading, and crossfade behavior. -- Missing or invalid metadata is omitted without placeholders or dangling separators. +- Invalid, non-finite, zero, negative, blank, or unavailable metadata is omitted without placeholders, empty chips, or dangling separators. +- Phone metadata may wrap to at most two lines and must not overlap carousel actions or change the carousel page height. +- Shared hydration/navigation-performance changes already present in PR #126 are its accepted baseline and remain unchanged. - Do not merge or deploy; update open PR #126 only after all required verification is green. --- @@ -41,7 +46,16 @@ - `androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/shell/TvShellFocusStateTest.kt` proves Up/Back retain the requested active root. - `androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeModelTest.kt` - proves movie/episode metadata ordering and technical-badge removal. + proves TV movie/episode metadata ordering, technical-badge removal, and + invalid-value omission. +- `androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/home/FeaturedCarousel.kt` + renders phone Library Recommended hero chips in a bounded two-line + `FlowRow`. +- `androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/home/FeaturedHeroMetadata.kt` + maps existing `SectionItem` fields to ordered, testable phone hero chips. +- `androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/home/FeaturedHeroMetadataTest.kt` + proves phone movie/episode ordering, generic-type removal, and invalid-value + omission. --- @@ -433,16 +447,351 @@ git commit -m "fix(tv): show editorial metadata in browse heroes" --- -### Task 3: Verify, review, package, and update PR #126 +### Task 3: Add phone parity and reject invalid hero metadata + +**Files:** +- Create: `androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/home/FeaturedHeroMetadata.kt` +- Create: `androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/home/FeaturedHeroMetadataTest.kt` +- Modify: `androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/home/FeaturedCarousel.kt:1-65,275-375,467-505` +- Modify: `androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeModel.kt:80-100,185-215` +- Modify: `androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeModelTest.kt` + +**Interfaces:** +- Consumes: existing `SectionItem` editorial fields only. +- Produces: `internal enum class FeaturedHeroMetadataKind { Plain, Rating, Classification }`. +- Produces: `internal data class FeaturedHeroMetadataChip(val label: String, val kind: FeaturedHeroMetadataKind = FeaturedHeroMetadataKind.Plain)`. +- Produces: `internal fun featuredHeroMetadata(item: SectionItem): List`. +- Preserves: TV `TvMarqueeContent` ordering from Task 2 while filtering invalid ratings and durations. + +- [ ] **Step 1: Write phone movie and episode metadata tests** + +Create `FeaturedHeroMetadataTest.kt`: + +```kotlin +package org.siloserver.silo.android.ui.screens.home + +import org.siloserver.silo.model.catalog.OverlaySummary +import org.siloserver.silo.model.section.SectionItem +import kotlin.test.Test +import kotlin.test.assertEquals + +class FeaturedHeroMetadataTest { + @Test + fun movieUsesOrderedEditorialMetadataWithoutGenericOrTechnicalChips() { + val chips = featuredHeroMetadata( + SectionItem( + contentId = "movie-1", + type = "movie", + title = "Arrival", + year = 2016, + genres = listOf("Science Fiction"), + ratingImdb = 7.9, + contentRating = "PG-13", + durationSeconds = 6_960.0, + overlaySummary = OverlaySummary( + resolution = "2160p", + hdr = "Dolby Vision", + audio = "Atmos", + ), + ), + ) + + assertEquals( + listOf("2016", "1h 56m", "7.9", "Science Fiction", "PG-13"), + chips.map { it.label }, + ) + assertEquals( + listOf( + FeaturedHeroMetadataKind.Plain, + FeaturedHeroMetadataKind.Plain, + FeaturedHeroMetadataKind.Rating, + FeaturedHeroMetadataKind.Plain, + FeaturedHeroMetadataKind.Classification, + ), + chips.map { it.kind }, + ) + } + + @Test + fun episodeReliesOnExistingSeriesEyebrowAndTitleWithoutDuplicatingName() { + val chips = featuredHeroMetadata( + SectionItem( + contentId = "episode-1", + type = "episode", + title = "Long, Long Time", + seriesTitle = "The Last of Us", + seasonNumber = 1, + episodeNumber = 3, + ratingImdb = 8.6, + contentRating = "TV-MA", + durationSeconds = 4_560.0, + ), + ) + + assertEquals( + listOf("S1 E3", "1h 16m", "8.6", "TV-MA"), + chips.map { it.label }, + ) + } +} +``` + +- [ ] **Step 2: Write phone invalid-value tests** + +Append: + +```kotlin +@Test +fun invalidRatingsAndDurationsAreOmitted() { + listOf( + Double.NaN, + Double.POSITIVE_INFINITY, + Double.NEGATIVE_INFINITY, + 0.0, + -1.0, + ).forEachIndexed { index, invalid -> + val chips = featuredHeroMetadata( + SectionItem( + contentId = "invalid-$index", + type = "movie", + title = "Invalid", + ratingImdb = invalid, + durationSeconds = invalid, + ), + ) + + assertEquals(emptyList(), chips) + } +} +``` + +- [ ] **Step 3: Strengthen the TV invalid-value regression** + +Append to `TvFocusMarqueeModelTest`: + +```kotlin +@Test +fun invalidRatingsAndDurationsAreOmittedFromTvMetadata() { + listOf( + Double.NaN, + Double.POSITIVE_INFINITY, + Double.NEGATIVE_INFINITY, + 0.0, + -1.0, + ).forEachIndexed { index, invalid -> + val content = TvMarqueeContent.from( + item = SectionItem( + contentId = "invalid-$index", + type = "movie", + title = "Invalid", + ratingImdb = invalid, + durationSeconds = invalid, + ), + rowTitle = "Invalid", + ) + + assertEquals(emptyList(), content.metaParts) + } +} +``` + +- [ ] **Step 4: Run both focused model tests and verify RED** + +```bash +./gradlew \ + :androidApp:testDebugUnitTest \ + :androidTvApp:testDebugUnitTest \ + --tests "org.siloserver.silo.android.ui.screens.home.FeaturedHeroMetadataTest" \ + --tests "org.siloserver.silo.tv.ui.components.TvFocusMarqueeModelTest" \ + --rerun-tasks --max-workers=2 --no-daemon +``` + +Expected: phone compilation fails because the new metadata types/functions do +not exist; the TV invalid-value case also fails before the production guard is +added. If Gradle applies each `--tests` pattern to both module tasks and reports +that one module has no matching tests, run the two module/test pairs as separate +commands while retaining the same worker/no-daemon/rerun shape. + +- [ ] **Step 5: Implement the pure phone metadata mapper** + +Create `FeaturedHeroMetadata.kt`: + +```kotlin +package org.siloserver.silo.android.ui.screens.home + +import java.util.Locale +import kotlin.math.roundToInt +import org.siloserver.silo.model.section.SectionItem + +internal enum class FeaturedHeroMetadataKind { + Plain, + Rating, + Classification, +} + +internal data class FeaturedHeroMetadataChip( + val label: String, + val kind: FeaturedHeroMetadataKind = FeaturedHeroMetadataKind.Plain, +) + +internal fun featuredHeroMetadata(item: SectionItem): List { + val result = mutableListOf() + val isEpisode = item.type.equals("episode", ignoreCase = true) + + if (isEpisode) { + episodeToken(item.seasonNumber, item.episodeNumber)?.let { + result += FeaturedHeroMetadataChip(it) + } + } else if (item.year > 0) { + result += FeaturedHeroMetadataChip(item.year.toString()) + } + + formatFeaturedRuntime(item.durationSeconds)?.let { + result += FeaturedHeroMetadataChip(it) + } + item.ratingImdb + ?.takeIf { it.isFinite() && it > 0.0 } + ?.let { + result += FeaturedHeroMetadataChip( + label = String.format(Locale.US, "%.1f", it), + kind = FeaturedHeroMetadataKind.Rating, + ) + } + if (!isEpisode) { + item.genres.firstOrNull { it.isNotBlank() }?.let { + result += FeaturedHeroMetadataChip(it) + } + } + item.contentRating + ?.takeIf { it.isNotBlank() } + ?.uppercase(Locale.US) + ?.let { + result += FeaturedHeroMetadataChip( + label = it, + kind = FeaturedHeroMetadataKind.Classification, + ) + } + return result +} + +private fun episodeToken(season: Int?, episode: Int?): String? = when { + season != null && episode != null -> "S$season E$episode" + season != null -> "Season $season" + episode != null -> "Episode $episode" + else -> null +} + +private fun formatFeaturedRuntime(durationSeconds: Double?): String? { + val duration = durationSeconds?.takeIf { it.isFinite() && it > 0.0 } + ?: return null + val minutes = (duration / 60.0).roundToInt().takeIf { it > 0 } + ?: return null + if (minutes < 60) return "$minutes min" + val hours = minutes / 60 + val remainder = minutes % 60 + return if (remainder == 0) "${hours}h" else "${hours}h ${remainder}m" +} +``` + +- [ ] **Step 6: Render bounded phone chips without changing carousel actions** + +In `FeaturedCarousel.kt`: + +- import `ExperimentalLayoutApi` and `FlowRow` from + `androidx.compose.foundation.layout`; +- annotate `FeaturedCardContent` with `@OptIn(ExperimentalLayoutApi::class)`; +- replace `remember(item) { metadataChips(item) }` with + `remember(item) { featuredHeroMetadata(item) }`; +- replace the single `Row` with: + +```kotlin +FlowRow( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + maxLines = 2, +) { + chips.forEach { chip -> MetadataChip(chip) } +} +``` + +Change `MetadataChip` to accept `FeaturedHeroMetadataChip` and render the star +only for `FeaturedHeroMetadataKind.Rating`: + +```kotlin +if (chip.kind == FeaturedHeroMetadataKind.Rating) { + Icon( + imageVector = Icons.Default.Star, + contentDescription = null, + tint = Color(0xFFFFCA28), + modifier = Modifier.size(12.dp), + ) +} +Text( + text = chip.label, + style = MaterialTheme.typography.labelMedium, + fontWeight = FontWeight.SemiBold, + color = Color.White.copy(alpha = 0.94f), + maxLines = 1, +) +``` + +Delete `HeroChip`, `metadataChips`, and the duplicate item-based +`episodeToken`; keep `eyebrowFor`, paging, actions, backdrop, and carousel +geometry unchanged. + +- [ ] **Step 7: Reject invalid TV ratings and durations** + +In `TvMarqueeContent.from`, guard the rating at both movie and episode call +sites: + +```kotlin +item.ratingImdb + ?.takeIf { it.isFinite() && it > 0.0 } + ?.let { meta.add(formatRating(it)) } +``` + +Start `lengthText` with: + +```kotlin +val duration = durationSeconds?.takeIf { it.isFinite() && it > 0.0 } + ?: return null +val minutes = (duration / 60.0).roundToInt() +``` + +Use `duration` rather than the nullable input for the calculation. Do not alter +valid formatting or field order. + +- [ ] **Step 8: Run both focused model tests and verify GREEN** + +Run the module-specific commands described in Step 4. + +Expected: all phone metadata tests and all TV marquee-model tests pass. + +- [ ] **Step 9: Commit the phone-parity and invalid-value correction** + +```bash +git add \ + androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/home/FeaturedCarousel.kt \ + androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/home/FeaturedHeroMetadata.kt \ + androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/home/FeaturedHeroMetadataTest.kt \ + androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeModel.kt \ + androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeModelTest.kt +git commit -m "fix(android): align editorial browse hero metadata" +``` + +--- + +### Task 4: Verify, review, package, and update PR #126 **Files:** - Verify only: all branch changes against `origin/main` -- Output only, not committed: Android TV universal minified release APK +- Output only, not committed: Android phone and TV universal minified release APKs - Update remotely after green: existing PR #126 description/checklist **Interfaces:** -- Consumes: Tasks 1 and 2 commits. -- Produces: independently reviewed, fully verified PR #126 head and a clearly named tester APK. +- Consumes: Tasks 1–3 commits. +- Produces: independently reviewed, fully verified PR #126 head and clearly named phone/TV tester APKs. - [ ] **Step 1: Run all focused regressions together** @@ -453,6 +802,10 @@ git commit -m "fix(tv): show editorial metadata in browse heroes" --tests "org.siloserver.silo.tv.ui.components.TvSkylineUpNavigationTest" \ --tests "org.siloserver.silo.tv.ui.components.TvFocusMarqueeModelTest" \ --rerun-tasks --max-workers=2 --no-daemon + +./gradlew :androidApp:testDebugUnitTest \ + --tests "org.siloserver.silo.android.ui.screens.home.FeaturedHeroMetadataTest" \ + --rerun-tasks --max-workers=2 --no-daemon ``` Expected: all selected tests pass with zero failures. @@ -466,18 +819,20 @@ Expected: all selected tests pass with zero failures. Expected: both scripts exit 0. -- [ ] **Step 3: Run the complete fresh TV test and release gate** +- [ ] **Step 3: Run the complete fresh phone/TV test and release gate** ```bash ./gradlew \ + :androidApp:testDebugUnitTest \ :androidTvApp:testDebugUnitTest \ + :androidApp:assembleRelease \ :androidTvApp:assembleRelease \ -PallowDebugReleaseSigning=true \ --rerun-tasks --max-workers=2 --no-daemon ``` -Expected: `BUILD SUCCESSFUL`; all TV unit XML results have zero failures and -the minified release APK is produced. +Expected: `BUILD SUCCESSFUL`; all phone and TV unit XML results have zero +failures and both universal minified release APKs are produced. - [ ] **Step 4: Perform the required device/emulator smoke** @@ -497,6 +852,21 @@ Record the emulator/device identity and pass/fail result in the PR. If no approved target is available, mark this smoke as pending instead of claiming it passed. +On a dedicated phone emulator, without touching an unapproved physical device: + +1. Open a Library Recommended featured carousel containing a movie and verify + year, runtime, IMDb, genre, and classification appear without a generic + `Movie` chip. +2. Open an episode carousel page and verify the series eyebrow/title remain, + with season/episode, runtime, IMDb, and classification chips and no generic + `Episode` chip. +3. Use a narrow phone viewport and verify chips wrap to no more than two lines + without covering Play or More Info. +4. Verify carousel paging, artwork, Play, and More Info behavior remain intact. + +Record the phone emulator identity and result, or mark this smoke pending when +no approved target is available. + - [ ] **Step 5: Request independent focused review** Provide the reviewer: @@ -505,9 +875,10 @@ Provide the reviewer: - `git diff origin/main...HEAD`; - focused and full test results; - the focus request timing/target contract; -- movie and episode metadata order; -- explicit instruction to flag production-semantic changes outside the TV - shell/marquee scope. +- phone and TV movie/episode metadata ordering and invalid-value omission; +- the explicit scope boundary: Task 1 focus is TV-only, Task 2/3 hero metadata + is phone+TV, and earlier shared hydration/navigation-performance commits in + PR #126 are an accepted unchanged baseline rather than new Task 3 scope. Address only verified findings, rerun the affected focused test, and repeat review until approved. @@ -521,21 +892,23 @@ git log --oneline origin/main..HEAD ``` Expected: no whitespace errors, no uncommitted files, and only the documented -TV navigation/hero commits plus their specs/plans. +navigation/hero commits plus their specs/plans. -- [ ] **Step 7: Copy and verify the tester APK** +- [ ] **Step 7: Copy and verify both tester APKs** -Select the universal APK from the TV release output, verify it with +Select the universal APK from each release output, verify each with `apksigner verify --verbose`, inspect package/version/ABI metadata with `apkanalyzer`, calculate `shasum -a 256`, and copy it without overwriting prior artifacts: ```bash +cp androidApp/build/outputs/apk/release/androidApp-universal-release.apk \ + "/Users/jimcole/Desktop/Silo Releases/Silo-Phone-Universal-0.3.11-FocusHeroFix-$(git rev-parse --short HEAD).apk" cp androidTvApp/build/outputs/apk/release/androidTvApp-universal-release.apk \ "/Users/jimcole/Desktop/Silo Releases/Silo-TV-Universal-0.3.11-TVFocusHeroFix-$(git rev-parse --short HEAD).apk" ``` -If the generated filename differs, select the universal artifact explicitly; +If a generated filename differs, select its universal artifact explicitly; never substitute an ABI-specific split. Report that `-PallowDebugReleaseSigning=true` produces a debug-signed release build that only upgrades installations signed by the same certificate. @@ -551,10 +924,11 @@ gh pr view 126 --repo Silo-Server/silo-android \ Update the PR description to include: - active-section focus restoration; -- editorial-only movie/episode hero metadata; +- editorial-only phone and TV movie/episode hero metadata; +- invalid rating/runtime omission; - focused/full verification evidence; - independent review verdict; -- device-smoke result or its explicit pending status; -- tester APK signing caveat. +- phone and TV smoke results or their explicit pending status; +- both tester APK signing caveats. Do not merge PR #126. From 59ad7f1db7c4682acd44170c35cc7cfec3595149 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 06:56:55 +0200 Subject: [PATCH 22/65] fix(android): align editorial browse hero metadata --- .../ui/screens/home/FeaturedCarousel.kt | 55 ++++-------- .../ui/screens/home/FeaturedHeroMetadata.kt | 74 +++++++++++++++ .../screens/home/FeaturedHeroMetadataTest.kt | 89 +++++++++++++++++++ .../tv/ui/components/TvFocusMarqueeModel.kt | 13 ++- .../ui/components/TvFocusMarqueeModelTest.kt | 24 +++++ 5 files changed, 211 insertions(+), 44 deletions(-) create mode 100644 androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/home/FeaturedHeroMetadata.kt create mode 100644 androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/home/FeaturedHeroMetadataTest.kt diff --git a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/home/FeaturedCarousel.kt b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/home/FeaturedCarousel.kt index 5260f23c4d..b67512b5f9 100644 --- a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/home/FeaturedCarousel.kt +++ b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/home/FeaturedCarousel.kt @@ -9,6 +9,8 @@ import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer @@ -279,6 +281,7 @@ private fun FeaturedCard( } @Composable +@OptIn(ExperimentalLayoutApi::class) private fun FeaturedCardContent( item: SectionItem, visibility: Float, @@ -336,9 +339,14 @@ private fun FeaturedCardContent( ) } - val chips = remember(item) { metadataChips(item) } + val chips = remember(item) { featuredHeroMetadata(item) } if (chips.isNotEmpty()) { - Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + FlowRow( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + maxLines = 2, + ) { chips.forEach { chip -> MetadataChip(chip) } } } @@ -352,7 +360,7 @@ private fun FeaturedCardContent( } @Composable -private fun MetadataChip(chip: HeroChip) { +private fun MetadataChip(chip: FeaturedHeroMetadataChip) { Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(5.dp), @@ -366,16 +374,16 @@ private fun MetadataChip(chip: HeroChip) { ) .padding(horizontal = 12.dp, vertical = 6.dp), ) { - if (chip.icon != null) { + if (chip.kind == FeaturedHeroMetadataKind.Rating) { Icon( - imageVector = chip.icon, + imageVector = Icons.Default.Star, contentDescription = null, - tint = chip.iconTint ?: Color.White.copy(alpha = 0.94f), + tint = Color(0xFFFFCA28), modifier = Modifier.size(12.dp), ) } Text( - text = chip.title, + text = chip.label, style = MaterialTheme.typography.labelMedium, fontWeight = FontWeight.SemiBold, color = Color.White.copy(alpha = 0.94f), @@ -464,41 +472,8 @@ private fun FeaturedActionRow( } } -private data class HeroChip( - val title: String, - val icon: androidx.compose.ui.graphics.vector.ImageVector? = null, - val iconTint: Color? = null, -) - -private fun metadataChips(item: SectionItem): List { - val chips = mutableListOf() - chips += HeroChip(title = item.type.replaceFirstChar { it.uppercase() }) - episodeToken(item)?.let { chips += HeroChip(title = it) } - item.ratingImdb?.let { rating -> - chips += HeroChip( - title = "%.1f".format(rating), - icon = Icons.Default.Star, - iconTint = Color(0xFFFFCA28), - ) - } - if (item.year > 0) chips += HeroChip(title = item.year.toString()) - return chips -} - private fun eyebrowFor(item: SectionItem): String? { if (!item.type.equals("episode", ignoreCase = true)) return null val seriesTitle = item.seriesTitle return if (!seriesTitle.isNullOrBlank()) seriesTitle else null } - -private fun episodeToken(item: SectionItem): String? { - if (!item.type.equals("episode", ignoreCase = true)) return null - val season = item.seasonNumber - val episode = item.episodeNumber - return when { - season != null && episode != null -> "S$season E$episode" - season != null -> "Season $season" - episode != null -> "Episode $episode" - else -> null - } -} diff --git a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/home/FeaturedHeroMetadata.kt b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/home/FeaturedHeroMetadata.kt new file mode 100644 index 0000000000..59a5eade95 --- /dev/null +++ b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/home/FeaturedHeroMetadata.kt @@ -0,0 +1,74 @@ +package org.siloserver.silo.android.ui.screens.home + +import java.util.Locale +import kotlin.math.roundToInt +import org.siloserver.silo.model.section.SectionItem + +internal enum class FeaturedHeroMetadataKind { + Plain, + Rating, + Classification, +} + +internal data class FeaturedHeroMetadataChip( + val label: String, + val kind: FeaturedHeroMetadataKind = FeaturedHeroMetadataKind.Plain, +) + +internal fun featuredHeroMetadata(item: SectionItem): List { + val result = mutableListOf() + val isEpisode = item.type.equals("episode", ignoreCase = true) + + if (isEpisode) { + episodeToken(item.seasonNumber, item.episodeNumber)?.let { + result += FeaturedHeroMetadataChip(it) + } + } else if (item.year > 0) { + result += FeaturedHeroMetadataChip(item.year.toString()) + } + + formatFeaturedRuntime(item.durationSeconds)?.let { + result += FeaturedHeroMetadataChip(it) + } + item.ratingImdb + ?.takeIf { it.isFinite() && it > 0.0 } + ?.let { + result += FeaturedHeroMetadataChip( + label = String.format(Locale.US, "%.1f", it), + kind = FeaturedHeroMetadataKind.Rating, + ) + } + if (!isEpisode) { + item.genres.firstOrNull { it.isNotBlank() }?.let { + result += FeaturedHeroMetadataChip(it) + } + } + item.contentRating + ?.takeIf { it.isNotBlank() } + ?.uppercase(Locale.US) + ?.let { + result += FeaturedHeroMetadataChip( + label = it, + kind = FeaturedHeroMetadataKind.Classification, + ) + } + return result +} + +private fun episodeToken(season: Int?, episode: Int?): String? = when { + season != null && episode != null -> "S$season E$episode" + season != null -> "Season $season" + episode != null -> "Episode $episode" + else -> null +} + +private fun formatFeaturedRuntime(durationSeconds: Double?): String? { + val duration = durationSeconds?.takeIf { it.isFinite() && it > 0.0 } + ?: return null + val minutes = (duration / 60.0).roundToInt().takeIf { it > 0 } + ?: return null + if (minutes < 60) return "$minutes min" + val hours = minutes / 60 + val remainder = minutes % 60 + return if (remainder == 0) "${hours}h" else "${hours}h ${remainder}m" +} diff --git a/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/home/FeaturedHeroMetadataTest.kt b/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/home/FeaturedHeroMetadataTest.kt new file mode 100644 index 0000000000..f4f67bdb35 --- /dev/null +++ b/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/home/FeaturedHeroMetadataTest.kt @@ -0,0 +1,89 @@ +package org.siloserver.silo.android.ui.screens.home + +import org.siloserver.silo.model.catalog.OverlaySummary +import org.siloserver.silo.model.section.SectionItem +import kotlin.test.Test +import kotlin.test.assertEquals + +class FeaturedHeroMetadataTest { + @Test + fun movieUsesOrderedEditorialMetadataWithoutGenericOrTechnicalChips() { + val chips = featuredHeroMetadata( + SectionItem( + contentId = "movie-1", + type = "movie", + title = "Arrival", + year = 2016, + genres = listOf("Science Fiction"), + ratingImdb = 7.9, + contentRating = "PG-13", + durationSeconds = 6_960.0, + overlaySummary = OverlaySummary( + resolution = "2160p", + hdr = "Dolby Vision", + audio = "Atmos", + ), + ), + ) + + assertEquals( + listOf("2016", "1h 56m", "7.9", "Science Fiction", "PG-13"), + chips.map { it.label }, + ) + assertEquals( + listOf( + FeaturedHeroMetadataKind.Plain, + FeaturedHeroMetadataKind.Plain, + FeaturedHeroMetadataKind.Rating, + FeaturedHeroMetadataKind.Plain, + FeaturedHeroMetadataKind.Classification, + ), + chips.map { it.kind }, + ) + } + + @Test + fun episodeReliesOnExistingSeriesEyebrowAndTitleWithoutDuplicatingName() { + val chips = featuredHeroMetadata( + SectionItem( + contentId = "episode-1", + type = "episode", + title = "Long, Long Time", + seriesTitle = "The Last of Us", + seasonNumber = 1, + episodeNumber = 3, + ratingImdb = 8.6, + contentRating = "TV-MA", + durationSeconds = 4_560.0, + ), + ) + + assertEquals( + listOf("S1 E3", "1h 16m", "8.6", "TV-MA"), + chips.map { it.label }, + ) + } + + @Test + fun invalidRatingsAndDurationsAreOmitted() { + listOf( + Double.NaN, + Double.POSITIVE_INFINITY, + Double.NEGATIVE_INFINITY, + 0.0, + -1.0, + ).forEachIndexed { index, invalid -> + val chips = featuredHeroMetadata( + SectionItem( + contentId = "invalid-$index", + type = "movie", + title = "Invalid", + ratingImdb = invalid, + durationSeconds = invalid, + ), + ) + + assertEquals(emptyList(), chips) + } + } +} diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeModel.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeModel.kt index 5e49df1e08..fe8a3e6eb4 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeModel.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeModel.kt @@ -86,11 +86,15 @@ data class TvMarqueeContent( episodeToken(item.seasonNumber, item.episodeNumber)?.let(meta::add) if (item.title.isNotBlank()) meta.add(item.title) lengthText(item.durationSeconds)?.let(meta::add) - item.ratingImdb?.let { meta.add(formatRating(it)) } + item.ratingImdb + ?.takeIf { it.isFinite() && it > 0.0 } + ?.let { meta.add(formatRating(it)) } } else { if (item.year > 0) meta.add(item.year.toString()) lengthText(item.durationSeconds)?.let(meta::add) - item.ratingImdb?.let { meta.add(formatRating(it)) } + item.ratingImdb + ?.takeIf { it.isFinite() && it > 0.0 } + ?.let { meta.add(formatRating(it)) } item.genres.firstOrNull { it.isNotBlank() }?.let(meta::add) } @@ -141,8 +145,9 @@ data class TvMarqueeContent( } private fun lengthText(durationSeconds: Double?): String? { - if (durationSeconds == null || durationSeconds <= 0) return null - val minutes = (durationSeconds / 60.0).roundToInt() + val duration = durationSeconds?.takeIf { it.isFinite() && it > 0.0 } + ?: return null + val minutes = (duration / 60.0).roundToInt() if (minutes <= 0) return null return if (minutes >= 60) { val hours = minutes / 60 diff --git a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeModelTest.kt b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeModelTest.kt index 950a3da76a..9813e9c2f0 100644 --- a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeModelTest.kt +++ b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeModelTest.kt @@ -82,4 +82,28 @@ class TvFocusMarqueeModelTest { assertEquals(emptyList(), content.badges) assertEquals(emptyList(), content.metaParts) } + + @Test + fun invalidRatingsAndDurationsAreOmittedFromTvMetadata() { + listOf( + Double.NaN, + Double.POSITIVE_INFINITY, + Double.NEGATIVE_INFINITY, + 0.0, + -1.0, + ).forEachIndexed { index, invalid -> + val content = TvMarqueeContent.from( + item = SectionItem( + contentId = "invalid-$index", + type = "movie", + title = "Invalid", + ratingImdb = invalid, + durationSeconds = invalid, + ), + rowTitle = "Invalid", + ) + + assertEquals(emptyList(), content.metaParts) + } + } } From 9c251293dc321385ea9be205a0732cc7b14b1251 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 07:14:16 +0200 Subject: [PATCH 23/65] fix(tv): avoid home focus fallback on secondary routes --- .../silo/tv/ui/shell/TvMainShell.kt | 10 +++++++-- .../silo/tv/ui/shell/TvShellFocusState.kt | 10 +++++++++ .../silo/tv/ui/shell/TvShellFocusStateTest.kt | 22 +++++++++++++++++++ 3 files changed, 40 insertions(+), 2 deletions(-) diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt index b4b41bc29a..db279f8506 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt @@ -806,7 +806,10 @@ fun TvMainShell( val contentHandledUp = contentUpFallback?.invoke(isRepeat) if (contentHandledUp != null) { if (!contentHandledUp) { - focusState.requestMenuFocus(selectedMenuFocusTarget) + focusState.requestMenuFocusIfAvailable( + selectedMenuFocusTarget, + allowNullTarget = currentRoute == TvMainRoute.Search.route, + ) } } else { // Try to move focus up inside content; if that @@ -814,7 +817,10 @@ fun TvMainShell( // focus to the menu bar. val moved = focusManager.moveFocus(FocusDirection.Up) if (!moved) { - focusState.requestMenuFocus(selectedMenuFocusTarget) + focusState.requestMenuFocusIfAvailable( + selectedMenuFocusTarget, + allowNullTarget = currentRoute == TvMainRoute.Search.route, + ) } } // Always consume: we performed the move (or routed diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvShellFocusState.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvShellFocusState.kt index 7018908d54..8f537e5491 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvShellFocusState.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvShellFocusState.kt @@ -182,6 +182,16 @@ class TvShellFocusState { menuFocusRequest++ } + /** + * Route content focus back to the bar only when the shell has a concrete root + * target, or when a route-specific owner intentionally handles a null target + * (currently Search). Other secondary routes must not fall through to Home. + */ + fun requestMenuFocusIfAvailable(target: TvTopMenuPanel?, allowNullTarget: Boolean = false) { + if (target == null && !allowNullTarget) return + requestMenuFocus(target) + } + /** * Record whether a bar button holds focus. Focus on the bar means we are not * inside a panel, so clear any stale entered flag — otherwise a geometric diff --git a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/shell/TvShellFocusStateTest.kt b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/shell/TvShellFocusStateTest.kt index 52378fb061..4d5bc403df 100644 --- a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/shell/TvShellFocusStateTest.kt +++ b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/shell/TvShellFocusStateTest.kt @@ -113,6 +113,28 @@ class TvShellFocusStateTest { assertEquals(moviesPanel, state.menuFocusTarget) } + @Test + fun contentUpOnSecondaryRoutesDoesNotFallbackToHomeFocus() { + val state = TvShellFocusState() + val before = state.menuFocusRequest + + state.requestMenuFocusIfAvailable(target = null) + + assertEquals(before, state.menuFocusRequest) + assertNull(state.menuFocusTarget) + } + + @Test + fun contentUpOnSearchMayUseTheSearchOwnedNullTarget() { + val state = TvShellFocusState() + val before = state.menuFocusRequest + + state.requestMenuFocusIfAvailable(target = null, allowNullTarget = true) + + assertEquals(before + 1, state.menuFocusRequest) + assertNull(state.menuFocusTarget) + } + @Test fun backOnSecondaryScreensStillDelegatesToNav() { assertEquals( From a28d10fbb72a91e82efc301b0cb1629941821f36 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 07:30:15 +0200 Subject: [PATCH 24/65] docs(android): report task 4 verification --- .../task-4-report.md | 170 ++++++++++++++++++ 1 file changed, 170 insertions(+) create mode 100644 .superpowers/sdd/2026-07-28-android-tv-active-header-focus-editorial-hero/task-4-report.md diff --git a/.superpowers/sdd/2026-07-28-android-tv-active-header-focus-editorial-hero/task-4-report.md b/.superpowers/sdd/2026-07-28-android-tv-active-header-focus-editorial-hero/task-4-report.md new file mode 100644 index 0000000000..3c25dda643 --- /dev/null +++ b/.superpowers/sdd/2026-07-28-android-tv-active-header-focus-editorial-hero/task-4-report.md @@ -0,0 +1,170 @@ +# Task 4 Report: Android TV Focus and Phone/TV Hero Verification + +Date: 2026-07-28 +Worktree: `/Users/jimcole/projects/silo/silo-android/.worktrees/tv-for-you-cold-navigation` +Final local HEAD: `9c251293dc321385ea9be205a0732cc7b14b1251` + +## Summary + +Task 4 verification found one Important review issue in the previously approved Task 1 focus path. I fixed it locally in `9c251293` by preventing non-Search secondary routes from falling through to Home focus when `selectedRoot == null`. The repeat independent review approved the updated diff. + +Automated tests, supply-chain checks, release builds, APK signing verification, and artifact packaging completed. Dedicated emulator smoke did not produce a fully clean pass, so I did not push or update PR #126. + +## Local Commits Added + +- `9c251293 fix(tv): avoid home focus fallback on secondary routes` + +## Verification Commands + +Focused TV regressions: + +```bash +./gradlew :androidTvApp:testDebugUnitTest \ + --tests "org.siloserver.silo.tv.ui.shell.TvTopMenuFocusRequestTest" \ + --tests "org.siloserver.silo.tv.ui.shell.TvShellFocusStateTest" \ + --tests "org.siloserver.silo.tv.ui.components.TvSkylineUpNavigationTest" \ + --tests "org.siloserver.silo.tv.ui.components.TvFocusMarqueeModelTest" \ + --rerun-tasks --max-workers=2 --no-daemon +``` + +Result: `BUILD SUCCESSFUL`, 68 tasks executed. + +Focused phone regression: + +```bash +./gradlew :androidApp:testDebugUnitTest \ + --tests "org.siloserver.silo.android.ui.screens.home.FeaturedHeroMetadataTest" \ + --rerun-tasks --max-workers=2 --no-daemon +``` + +Result: `BUILD SUCCESSFUL`, 80 tasks executed. + +Supply-chain checks: + +```bash +./scripts/test-check-build-supply-chain.sh +./scripts/check-build-supply-chain.sh +``` + +Result: both exited 0. Self-test output: `All supply-chain policy self-tests passed`. + +Full release gate: + +```bash +./gradlew \ + :androidApp:testDebugUnitTest \ + :androidTvApp:testDebugUnitTest \ + :androidApp:assembleRelease \ + :androidTvApp:assembleRelease \ + -PallowDebugReleaseSigning=true \ + --rerun-tasks --max-workers=2 --no-daemon +``` + +Result: `BUILD SUCCESSFUL in 6m 29s`, 313 tasks executed. + +The test XML directory immediately after the full release gate only contained focused suites, so I reran the unfiltered unit-test tasks explicitly: + +```bash +./gradlew :androidApp:testDebugUnitTest :androidTvApp:testDebugUnitTest \ + --rerun-tasks --max-workers=2 --no-daemon +``` + +Result: `BUILD SUCCESSFUL in 1m 20s`, 104 tasks executed. + +XML totals after explicit unfiltered rerun: + +- `androidApp/build/test-results/testDebugUnitTest`: 85 suites, 477 tests, 0 skipped, 0 failures, 0 errors. +- `androidTvApp/build/test-results/testDebugUnitTest`: 88 suites, 646 tests, 0 skipped, 0 failures, 0 errors. + +Diff hygiene: + +```bash +git diff --check origin/main...HEAD +git status --short --branch +git log --oneline origin/main..HEAD +``` + +Result before writing this report: no whitespace errors; branch ahead of `origin/fix/tv-for-you-cold-navigation`. + +## Independent Review + +Initial review finding: + +- Important: non-Search secondary routes could call `requestMenuFocus(null)` and fall through to Home in `TvTopMenuBar`. + +Fix: + +- Added `TvShellFocusState.requestMenuFocusIfAvailable`. +- Updated content-Up routing in `TvMainShell` to allow null targeting only for Search. +- Added regression coverage in `TvShellFocusStateTest`. + +Repeat review result: + +- No blocking findings. Approved. +- Residual risk noted by reviewer: the content-Up fix is covered by state/helper unit tests, not a full Compose focus integration test. + +## Emulator Smoke + +Physical device safety: + +- ADB showed physical Shield `192.168.1.128:5555`; I did not target it. +- TV smoke used AVD `Silo_TV`, serial `emulator-5554`. +- Phone smoke used AVD `Silo_Phone`, serial `emulator-5556`. + +TV smoke on final TV APK: + +- Installed `/androidTvApp/build/outputs/apk/release/androidTvApp-universal-release.apk` on `Silo_TV`. +- Home: from content card, fresh Up focused the Home top pill. Pass. +- Movies library: from first content card, first Up left focus on the content card; second Up focused the Movies pill. Not a clean pass. +- For You: from content, fresh Up focused the For You control. Pass. +- Calendar: targeted Calendar and entered content; Up focused the in-page `Following` control rather than the top Calendar pill. Not a clean top-pill pass. +- Hold-Up from lower row: not cleanly completed after the caveats above. +- Search route focus: not completed after the caveats above. +- TV hero metadata: visual/UIAutomator dumps showed editorial hero metadata for focused content and no technical badges in the large hero; content cards still show technical badges outside the hero. + +Phone smoke on final phone APK: + +- Installed `/androidApp/build/outputs/apk/release/androidApp-universal-release.apk` on `Silo_Phone`. +- Opened Libraries > Movies. The Movies library Recommended hero displayed editorial chips `2004`, `7.3`, `War`, `R`, with no generic `Movie` chip, and Play / More Info visible. +- The selected movie did not show a runtime chip in the UIAutomator dump, so the requested movie smoke is partial rather than a full pass. +- Episode carousel page smoke was not completed. +- Narrow viewport wrapping was not completed beyond the default `1080x2400` phone emulator viewport. + +Smoke conclusion: not fully green. PR #126 was not pushed or updated. + +## APK Artifacts + +Built universal minified release APKs from local HEAD `9c251293` with `-PallowDebugReleaseSigning=true`. + +Signing caveat: these are debug-signed release builds. They only upgrade installations signed with the same debug certificate. + +Copied artifacts: + +- `/Users/jimcole/Desktop/Silo Releases/Silo-Phone-Universal-0.3.11-FocusHeroFix-9c251293.apk` +- `/Users/jimcole/Desktop/Silo Releases/Silo-TV-Universal-0.3.11-TVFocusHeroFix-9c251293.apk` + +SHA-256: + +- Phone: `0c4c68d15d47c28de41ef1fc1db080ba266f899aa2c3dad663a20fdb5dd5ed50` +- TV: `9e135e3cdad20f1b000ae2ef55573ceb6070e1412718d4ebde47a1977e492a09` + +`apksigner verify --verbose` on copied APKs: + +- Phone: verifies; v2 scheme true; number of signers 1. +- TV: verifies; v2 scheme true; number of signers 1. + +`apkanalyzer` status: + +- `/opt/homebrew/bin/apkanalyzer` failed with `IllegalStateException: Cannot locate latest build tools`, even with `ANDROID_HOME` and `ANDROID_SDK_ROOT` set. +- Used SDK `aapt` as fallback for package/version/ABI metadata. + +`aapt dump badging` metadata: + +- Phone: `applicationId=org.siloserver.silo`, `versionCode=14`, `versionName=0.3.11`, native ABIs `arm64-v8a, armeabi-v7a, x86, x86_64`. +- TV: `applicationId=org.siloserver.silo`, `versionCode=15`, `versionName=0.3.11`, native ABIs `arm64-v8a, armeabi-v7a, x86, x86_64`. + +## PR Status + +No push performed. + +No PR #126 description update performed because the required emulator smoke was not fully green. From 64785286eed6123f2ef0d24f7a269135ef21b465 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 07:45:35 +0200 Subject: [PATCH 25/65] fix(tv): return calendar controls up to active tab --- .../ui/screens/calendar/TvCalendarScreen.kt | 40 ++++++++++++++++--- .../silo/tv/ui/shell/TvMainShell.kt | 6 +++ .../calendar/TvCalendarFocusRoutingTest.kt | 13 ++++++ 3 files changed, 54 insertions(+), 5 deletions(-) diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/calendar/TvCalendarScreen.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/calendar/TvCalendarScreen.kt index f07c9b24fd..dc8037ed6c 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/calendar/TvCalendarScreen.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/calendar/TvCalendarScreen.kt @@ -124,6 +124,7 @@ import java.util.Locale fun TvCalendarScreen( onOpenItemDetail: (contentId: String) -> Unit, onInitialContentFocus: () -> Unit = {}, + onMoveUpToMenu: () -> Unit = {}, focusRequest: Int = 0, onContentUpFallbackChanged: ((((Boolean) -> Boolean)?) -> Unit)? = null, viewModel: CalendarViewModel = koinViewModel(), @@ -250,6 +251,7 @@ fun TvCalendarScreen( // naturally pushes both controls upward instead of pinning them. CalendarList( onContentUpFallbackChanged = onContentUpFallbackChanged, + onMoveUpToMenu = onMoveUpToMenu, state = state, listState = listState, controls = controls, @@ -674,12 +676,33 @@ internal fun shouldReturnCalendarFocusToControls( focusedShelfIndex == firstFocusableShelfIndex && !isReturningToControls +internal enum class CalendarUpFallbackAction { + EnterMenu, + ReturnToControls, + MoveWithinContent, +} + +internal fun calendarUpFallbackAction( + focusedShelfIndex: Int?, + firstFocusableShelfIndex: Int, + isReturningToControls: Boolean, +): CalendarUpFallbackAction = when { + shouldReturnCalendarFocusToControls( + focusedShelfIndex = focusedShelfIndex, + firstFocusableShelfIndex = firstFocusableShelfIndex, + isReturningToControls = isReturningToControls, + ) -> CalendarUpFallbackAction.ReturnToControls + focusedShelfIndex == null -> CalendarUpFallbackAction.EnterMenu + else -> CalendarUpFallbackAction.MoveWithinContent +} + // MARK: - Day list @OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class, ExperimentalTvMaterial3Api::class) @Composable private fun CalendarList( onContentUpFallbackChanged: ((((Boolean) -> Boolean)?) -> Unit)? = null, + onMoveUpToMenu: () -> Unit = {}, state: org.siloserver.silo.viewmodel.CalendarUiState, listState: LazyListState, controls: @Composable () -> Unit, @@ -733,16 +756,23 @@ private fun CalendarList( var focusedShelfIndex by remember { mutableStateOf(null) } val calendarUpFallback = remember(firstFocusableDayIndex) { { _: Boolean -> - if (shouldReturnCalendarFocusToControls( + when (calendarUpFallbackAction( focusedShelfIndex = focusedShelfIndex, firstFocusableShelfIndex = firstFocusableDayIndex, isReturningToControls = isReturningToControls, ) ) { - onMoveUpToControls() - true - } else { - focusManager.moveFocus(androidx.compose.ui.focus.FocusDirection.Up) + CalendarUpFallbackAction.EnterMenu -> { + onMoveUpToMenu() + true + } + CalendarUpFallbackAction.ReturnToControls -> { + onMoveUpToControls() + true + } + CalendarUpFallbackAction.MoveWithinContent -> { + focusManager.moveFocus(androidx.compose.ui.focus.FocusDirection.Up) + } } } } diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt index db279f8506..a86bdf0055 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt @@ -1081,7 +1081,13 @@ fun TvMainShell( focusState.closeProfileMenuForContent() calendarFocusHandoffPending = false }, + onMoveUpToMenu = { + focusState.requestMenuFocus( + TvTopMenuPanel.Root(TvRootDestination.Calendar), + ) + }, focusRequest = contentFocusRequest, + onContentUpFallbackChanged = onContentUpFallback, ) } composable(TvMainRoute.Browse.route) { diff --git a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/calendar/TvCalendarFocusRoutingTest.kt b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/calendar/TvCalendarFocusRoutingTest.kt index d3a1dac2d7..dc5de47e60 100644 --- a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/calendar/TvCalendarFocusRoutingTest.kt +++ b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/calendar/TvCalendarFocusRoutingTest.kt @@ -1,6 +1,7 @@ package org.siloserver.silo.tv.ui.screens.calendar import kotlin.test.Test +import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue @@ -20,6 +21,18 @@ class TvCalendarFocusRoutingTest { assertFalse(shouldReturnCalendarFocusToControls(null, 2, false)) } + @Test + fun controlsReturnToShellMenuTarget() { + assertEquals( + CalendarUpFallbackAction.EnterMenu, + calendarUpFallbackAction( + focusedShelfIndex = null, + firstFocusableShelfIndex = 2, + isReturningToControls = false, + ), + ) + } + @Test fun returnInFlightDoesNotRestartChoreography() { assertFalse(shouldReturnCalendarFocusToControls(2, 2, true)) From ade712c4133bfa5b501126d2755429ff1cd5e117 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 08:00:06 +0200 Subject: [PATCH 26/65] fix(shared): scope home requests to identity --- .../siloserver/silo/di/RepositoryModule.kt | 9 +++- .../silo/repository/SectionRepository.kt | 26 +++++++---- .../repository/SectionRepositoryCacheTest.kt | 46 +++++++++++++++++++ 3 files changed, 71 insertions(+), 10 deletions(-) diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/di/RepositoryModule.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/di/RepositoryModule.kt index ac8598a5b2..e5e43d5255 100644 --- a/shared/src/commonMain/kotlin/org/siloserver/silo/di/RepositoryModule.kt +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/di/RepositoryModule.kt @@ -64,7 +64,14 @@ val repositoryModule = module { } single { ProfileRepository(get(), get(), getOrNull(), get(), get(), get()) } single { CollectionRepository(get()) } - single { SectionRepository(get(), getOrNull() ?: org.siloserver.silo.repository.port.NoOpCatalogCachePort) } + single { + SectionRepository( + sectionApi = get(), + catalogCache = getOrNull() + ?: org.siloserver.silo.repository.port.NoOpCatalogCachePort, + identityTransitions = get(), + ) + } single { RecommendationRepository(get()) } single { RequestsRepository(get()) } single { RequestsFeatureStore(get()) } diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/repository/SectionRepository.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/repository/SectionRepository.kt index c451df1d79..4a26ed197e 100644 --- a/shared/src/commonMain/kotlin/org/siloserver/silo/repository/SectionRepository.kt +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/repository/SectionRepository.kt @@ -7,6 +7,8 @@ import org.siloserver.silo.model.section.LibraryCollection import org.siloserver.silo.model.section.LibraryCollectionsResponse import org.siloserver.silo.model.section.SectionsResponse import org.siloserver.silo.network.ApiResult +import org.siloserver.silo.network.DefaultIdentityTransitionBarrier +import org.siloserver.silo.network.IdentityTransitionBarrier import org.siloserver.silo.network.api.SectionApi import org.siloserver.silo.network.map import org.siloserver.silo.repository.port.CatalogCachePort @@ -25,12 +27,14 @@ class SectionRepository( private val sectionApi: SectionApi, /** Offline read cache for a library's Recommended sections (Track B). No-op by default. */ private val catalogCache: CatalogCachePort = NoOpCatalogCachePort, + private val identityTransitions: IdentityTransitionBarrier = DefaultIdentityTransitionBarrier(), ) { private val homeRequestScope = CoroutineScope(SupervisorJob() + Dispatchers.Default) private val homeRequestMutex = Mutex() - private var homeSectionsInFlight: Deferred>? = null + private val homeSectionsInFlight = + mutableMapOf>>() private val homeSectionItemsInFlight = - mutableMapOf>>() + mutableMapOf, Deferred>>() /** Fetches the home screen layout configuration. */ suspend fun getHomeLayout(): ApiResult = @@ -38,19 +42,22 @@ class SectionRepository( /** Fetches all home screen sections (with items pre-resolved). */ suspend fun getHomeSections(): ApiResult { + val identityGeneration = identityTransitions.generation.value val request = homeRequestMutex.withLock { - homeSectionsInFlight ?: run { + homeSectionsInFlight[identityGeneration] ?: run { lateinit var created: Deferred> created = homeRequestScope.async(start = CoroutineStart.LAZY) { try { sectionApi.getHomeSections() } finally { homeRequestMutex.withLock { - if (homeSectionsInFlight === created) homeSectionsInFlight = null + if (homeSectionsInFlight[identityGeneration] === created) { + homeSectionsInFlight.remove(identityGeneration) + } } } } - homeSectionsInFlight = created + homeSectionsInFlight[identityGeneration] = created created.start() created } @@ -60,21 +67,22 @@ class SectionRepository( /** Fetches the items within a specific home section. */ suspend fun getHomeSectionItems(sectionId: String): ApiResult { + val requestKey = identityTransitions.generation.value to sectionId val request = homeRequestMutex.withLock { - homeSectionItemsInFlight[sectionId] ?: run { + homeSectionItemsInFlight[requestKey] ?: run { lateinit var created: Deferred> created = homeRequestScope.async(start = CoroutineStart.LAZY) { try { sectionApi.getHomeSectionItems(sectionId) } finally { homeRequestMutex.withLock { - if (homeSectionItemsInFlight[sectionId] === created) { - homeSectionItemsInFlight.remove(sectionId) + if (homeSectionItemsInFlight[requestKey] === created) { + homeSectionItemsInFlight.remove(requestKey) } } } } - homeSectionItemsInFlight[sectionId] = created + homeSectionItemsInFlight[requestKey] = created created.start() created } diff --git a/shared/src/commonTest/kotlin/org/siloserver/silo/repository/SectionRepositoryCacheTest.kt b/shared/src/commonTest/kotlin/org/siloserver/silo/repository/SectionRepositoryCacheTest.kt index 5b2ddc7aff..cf817f74cc 100644 --- a/shared/src/commonTest/kotlin/org/siloserver/silo/repository/SectionRepositoryCacheTest.kt +++ b/shared/src/commonTest/kotlin/org/siloserver/silo/repository/SectionRepositoryCacheTest.kt @@ -2,6 +2,8 @@ package org.siloserver.silo.repository import org.siloserver.silo.model.section.ResolvedSection import org.siloserver.silo.network.ApiResult +import org.siloserver.silo.network.DefaultIdentityTransitionBarrier +import org.siloserver.silo.network.IdentityTransitionKind import org.siloserver.silo.network.SiloJson import org.siloserver.silo.network.api.SectionApi import org.siloserver.silo.repository.port.CatalogCachePort @@ -173,4 +175,48 @@ class SectionRepositoryCacheTest { assertTrue(repository.getHomeSections() is ApiResult.Success) assertEquals(2, calls) } + + @Test + fun homeRequestStartedBeforeProfileSwitchDoesNotServeOldProfileSectionsToNewProfile() = runTest { + var calls = 0 + val oldRequestEntered = CompletableDeferred() + val releaseOldRequest = CompletableDeferred() + val client = HttpClient( + MockEngine { + calls += 1 + val body = if (calls == 1) { + oldRequestEntered.complete(Unit) + releaseOldRequest.await() + """{"sections":[{"id":"old","section_type":"old","title":"Old"}]}""" + } else { + """{"sections":[{"id":"new","section_type":"new","title":"New"}]}""" + } + respond( + body, + HttpStatusCode.OK, + headersOf(HttpHeaders.ContentType, "application/json"), + ) + }, + ) { + install(ContentNegotiation) { json(SiloJson) } + } + val identityTransitions = DefaultIdentityTransitionBarrier() + val repository = SectionRepository( + sectionApi = SectionApi(client), + identityTransitions = identityTransitions, + ) + + val oldProfileRequest = async { repository.getHomeSections() } + oldRequestEntered.await() + identityTransitions.changing(IdentityTransitionKind.PROFILE_SWITCH) { } + val newProfileRequest = async { repository.getHomeSections() } + + releaseOldRequest.complete(Unit) + val oldProfileResult = oldProfileRequest.await() + val newProfileResult = newProfileRequest.await() + + assertEquals("Old", (oldProfileResult as ApiResult.Success).data.sections.single().title) + assertEquals("New", (newProfileResult as ApiResult.Success).data.sections.single().title) + assertEquals(2, calls) + } } From d6f2c15c3796b54694659829b429d52adce87972 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 08:02:35 +0200 Subject: [PATCH 27/65] fix(tv): keep repeated up in content --- .../ui/screens/calendar/TvCalendarScreen.kt | 24 +++++++++++++------ .../silo/tv/ui/shell/TvContentUpNavigation.kt | 10 ++++++++ .../silo/tv/ui/shell/TvMainShell.kt | 4 ++-- .../silo/tv/ui/shell/TvTopMenuBar.kt | 12 ++++++---- .../silo/tv/ui/shell/TvTopMenuFocusRequest.kt | 7 ++++-- .../calendar/TvCalendarFocusRoutingTest.kt | 13 ++++++++++ .../tv/ui/shell/TvContentUpNavigationTest.kt | 17 +++++++++++++ .../tv/ui/shell/TvTopMenuFocusRequestTest.kt | 18 ++++++++++++++ 8 files changed, 90 insertions(+), 15 deletions(-) create mode 100644 androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvContentUpNavigation.kt create mode 100644 androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/shell/TvContentUpNavigationTest.kt diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/calendar/TvCalendarScreen.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/calendar/TvCalendarScreen.kt index dc8037ed6c..9b35f41a7f 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/calendar/TvCalendarScreen.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/calendar/TvCalendarScreen.kt @@ -48,6 +48,7 @@ import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier @@ -679,6 +680,7 @@ internal fun shouldReturnCalendarFocusToControls( internal enum class CalendarUpFallbackAction { EnterMenu, ReturnToControls, + StayInContent, MoveWithinContent, } @@ -686,12 +688,14 @@ internal fun calendarUpFallbackAction( focusedShelfIndex: Int?, firstFocusableShelfIndex: Int, isReturningToControls: Boolean, + isRepeat: Boolean = false, ): CalendarUpFallbackAction = when { shouldReturnCalendarFocusToControls( focusedShelfIndex = focusedShelfIndex, firstFocusableShelfIndex = firstFocusableShelfIndex, isReturningToControls = isReturningToControls, - ) -> CalendarUpFallbackAction.ReturnToControls + ) -> if (isRepeat) CalendarUpFallbackAction.StayInContent else CalendarUpFallbackAction.ReturnToControls + focusedShelfIndex == null && isRepeat -> CalendarUpFallbackAction.StayInContent focusedShelfIndex == null -> CalendarUpFallbackAction.EnterMenu else -> CalendarUpFallbackAction.MoveWithinContent } @@ -754,12 +758,12 @@ private fun CalendarList( // when focus is already in the controls item, mirror the shell's default // (moveFocus within content; false -> shell hands off to the menu bar). var focusedShelfIndex by remember { mutableStateOf(null) } - val calendarUpFallback = remember(firstFocusableDayIndex) { - { _: Boolean -> + val currentCalendarUpFallback = rememberUpdatedState<(Boolean) -> Boolean> { isRepeat -> when (calendarUpFallbackAction( focusedShelfIndex = focusedShelfIndex, firstFocusableShelfIndex = firstFocusableDayIndex, isReturningToControls = isReturningToControls, + isRepeat = isRepeat, ) ) { CalendarUpFallbackAction.EnterMenu -> { @@ -770,15 +774,21 @@ private fun CalendarList( onMoveUpToControls() true } + CalendarUpFallbackAction.StayInContent -> true CalendarUpFallbackAction.MoveWithinContent -> { focusManager.moveFocus(androidx.compose.ui.focus.FocusDirection.Up) } } - } } - DisposableEffect(onContentUpFallbackChanged) { - onContentUpFallbackChanged?.invoke(calendarUpFallback) - onDispose { onContentUpFallbackChanged?.invoke(calendarUpFallback) } + // Keep the registered identity stable while its implementation reads the + // current loaded-day state. A new lambda keyed by firstFocusableDayIndex + // would otherwise leave the shell holding the pre-load callback until this + // screen disposes. + val calendarUpFallbackRegistration: (Boolean) -> Boolean = + remember { { isRepeat -> currentCalendarUpFallback.value(isRepeat) } } + DisposableEffect(onContentUpFallbackChanged, calendarUpFallbackRegistration) { + onContentUpFallbackChanged?.invoke(calendarUpFallbackRegistration) + onDispose { onContentUpFallbackChanged?.invoke(calendarUpFallbackRegistration) } } // The day-snap is the ONLY vertical scroller: with the default spec the diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvContentUpNavigation.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvContentUpNavigation.kt new file mode 100644 index 0000000000..d99ba18e30 --- /dev/null +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvContentUpNavigation.kt @@ -0,0 +1,10 @@ +package org.siloserver.silo.tv.ui.shell + +/** + * A held Up may traverse content, but it must not escape from the first + * content row into the top menu after focus movement has already failed. + */ +internal fun shouldRequestMenuAfterContentUp( + movedWithinContent: Boolean, + isRepeat: Boolean, +): Boolean = !movedWithinContent && !isRepeat diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt index a86bdf0055..fcd59b2208 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt @@ -805,7 +805,7 @@ fun TvMainShell( val isRepeat = ev.nativeKeyEvent.repeatCount > 0 val contentHandledUp = contentUpFallback?.invoke(isRepeat) if (contentHandledUp != null) { - if (!contentHandledUp) { + if (shouldRequestMenuAfterContentUp(contentHandledUp, isRepeat)) { focusState.requestMenuFocusIfAvailable( selectedMenuFocusTarget, allowNullTarget = currentRoute == TvMainRoute.Search.route, @@ -816,7 +816,7 @@ fun TvMainShell( // fails (we're already on the top row), hand // focus to the menu bar. val moved = focusManager.moveFocus(FocusDirection.Up) - if (!moved) { + if (shouldRequestMenuAfterContentUp(moved, isRepeat)) { focusState.requestMenuFocusIfAvailable( selectedMenuFocusTarget, allowNullTarget = currentRoute == TvMainRoute.Search.route, diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuBar.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuBar.kt index 5d721f6e73..eb142f2bad 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuBar.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuBar.kt @@ -26,6 +26,7 @@ import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.ExperimentalComposeUiApi @@ -229,20 +230,23 @@ fun TvTopMenuBar( // suppression lift (e.g. closing the profile dropdown, which flips // isFocusSuppressed false) does NOT also re-grab the selected tab and fight // the dedicated profile-avatar focus path below. - var lastHandledFocusRequest by remember { mutableStateOf(0) } - LaunchedEffect(focusRequest, isFocusSuppressed) { + val currentFocusRequestTarget by rememberUpdatedState(focusRequestTarget) + var lastHandledFocusRequest by remember { mutableStateOf>(0 to null) } + val focusRequestIdentity = focusRequest to focusRequestTarget + LaunchedEffect(focusRequest, focusRequestTarget, isFocusSuppressed) { if (isFocusSuppressed) return@LaunchedEffect - if (focusRequest == lastHandledFocusRequest) return@LaunchedEffect + if (focusRequestIdentity == lastHandledFocusRequest) return@LaunchedEffect val explicitFocus = focusRequestTarget?.let(::focusForPanel) dwellSuppressedButton = explicitFocus val requester = explicitFocus?.let(::requesterForFocus) ?: selectedEntryRequester() requestTopMenuFocusUntilApplied( awaitFrame = { androidx.compose.runtime.withFrameNanos { } }, + isTargetCurrent = { currentFocusRequestTarget == focusRequestTarget }, requestFocus = { runCatching { requester.requestFocus() }.getOrDefault(false) }, ) - lastHandledFocusRequest = focusRequest + lastHandledFocusRequest = focusRequestIdentity } LaunchedEffect(focusedButton) { diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuFocusRequest.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuFocusRequest.kt index 6e3ecaac94..62eb53865a 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuFocusRequest.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuFocusRequest.kt @@ -2,9 +2,12 @@ package org.siloserver.silo.tv.ui.shell internal suspend fun requestTopMenuFocusUntilApplied( awaitFrame: suspend () -> Unit, + isTargetCurrent: () -> Boolean = { true }, requestFocus: () -> Boolean, ) { - do { + while (isTargetCurrent()) { awaitFrame() - } while (!requestFocus()) + if (!isTargetCurrent()) return + if (requestFocus()) return + } } diff --git a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/calendar/TvCalendarFocusRoutingTest.kt b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/calendar/TvCalendarFocusRoutingTest.kt index dc5de47e60..0b9d200dfa 100644 --- a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/calendar/TvCalendarFocusRoutingTest.kt +++ b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/calendar/TvCalendarFocusRoutingTest.kt @@ -37,4 +37,17 @@ class TvCalendarFocusRoutingTest { fun returnInFlightDoesNotRestartChoreography() { assertFalse(shouldReturnCalendarFocusToControls(2, 2, true)) } + + @Test + fun heldUpOnCalendarControlsStaysInContent() { + assertEquals( + CalendarUpFallbackAction.StayInContent, + calendarUpFallbackAction( + focusedShelfIndex = null, + firstFocusableShelfIndex = 2, + isReturningToControls = false, + isRepeat = true, + ), + ) + } } diff --git a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/shell/TvContentUpNavigationTest.kt b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/shell/TvContentUpNavigationTest.kt new file mode 100644 index 0000000000..bc4f0e9fae --- /dev/null +++ b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/shell/TvContentUpNavigationTest.kt @@ -0,0 +1,17 @@ +package org.siloserver.silo.tv.ui.shell + +import kotlin.test.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class TvContentUpNavigationTest { + @Test + fun heldUpAfterContentCannotMoveStaysInContent() { + assertFalse(shouldRequestMenuAfterContentUp(movedWithinContent = false, isRepeat = true)) + } + + @Test + fun freshUpAfterContentCannotMoveEntersMenu() { + assertTrue(shouldRequestMenuAfterContentUp(movedWithinContent = false, isRepeat = false)) + } +} diff --git a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuFocusRequestTest.kt b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuFocusRequestTest.kt index f70b14b841..02f658073a 100644 --- a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuFocusRequestTest.kt +++ b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuFocusRequestTest.kt @@ -33,4 +33,22 @@ class TvTopMenuFocusRequestTest { assertEquals(listOf("frame", "focus", "frame", "focus"), events) } + + @Test + fun retryStopsWhenItsTargetIsNoLongerCurrent() = runTest { + val events = mutableListOf() + var targetIsCurrent = true + + requestTopMenuFocusUntilApplied( + awaitFrame = { events += "frame" }, + isTargetCurrent = { targetIsCurrent }, + requestFocus = { + events += "focus" + targetIsCurrent = false + false + }, + ) + + assertEquals(listOf("frame", "focus"), events) + } } From e922af08f85d2c0063879b2582c97c28b303ed8f Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 08:08:35 +0200 Subject: [PATCH 28/65] docs(android): design fixed library chrome inset --- ...droid-phone-library-chrome-inset-design.md | 96 +++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 docs/superpowers/specs/2026-07-28-android-phone-library-chrome-inset-design.md diff --git a/docs/superpowers/specs/2026-07-28-android-phone-library-chrome-inset-design.md b/docs/superpowers/specs/2026-07-28-android-phone-library-chrome-inset-design.md new file mode 100644 index 0000000000..f6962c839e --- /dev/null +++ b/docs/superpowers/specs/2026-07-28-android-phone-library-chrome-inset-design.md @@ -0,0 +1,96 @@ +# Android Phone Library Chrome Inset Design + +Date: 2026-07-28 + +## Goal + +Match the current iOS Libraries tab behavior on Android phone: the library +selector, actions, and Recommended / Browse / Collections tabs remain fixed at +the top, while scrollable library content occupies only the space below that +chrome. Library rows, posters, and hero content must not scroll visibly behind +the menu controls. + +This change is phone-only. It does not alter Android TV, standalone Browse or +Collections routes, Home, server APIs, navigation semantics, or the profile +menu's actions. + +## Current Behavior and Root Cause + +`LibrariesScreen` draws its tab content full-screen and then draws +`LibrariesFloatingChrome` afterward in the same root `Box`. The chrome uses a +partially transparent gradient. Recommended and Collections reserve initial +top runway inside their scroll containers, but that runway scrolls away; later +content therefore remains visible beneath the selector and tab controls. +Browse already uses fixed outer padding and does not exhibit the same underlap. + +The iOS implementation uses a top `safeAreaInset`, which reduces the space +offered to every library tab's scroll view. Its content therefore starts below +the shared chrome and cannot pass behind it. + +## Considered Approaches + +1. **Reserved top chrome slot — selected.** Keep the existing custom Android + chrome and full-screen backdrop, but place the chrome and tab-content + viewport in a vertical layout. The chrome consumes its measured height and + the content viewport receives the remaining height. This directly matches + the layout semantics of iOS `safeAreaInset` without replacing existing + controls. +2. **Stronger translucent scrim.** Leave content underneath but obscure it more + once scrolling starts. This reduces visual noise but does not fix the + reported behavior and remains inconsistent across tabs. +3. **Material `Scaffold.topBar`.** This also reserves layout space, but would + introduce a larger structural and visual migration for a custom chrome that + already works. It is unnecessary for this focused correction. + +## Layout Design + +The root retains its full-screen background and optional Recommended hero +backdrop. Above that background, a vertical foreground layout owns: + +1. `LibrariesFloatingChrome`, including the status-bar inset, library selector, + action buttons, profile popup anchor, subtab selector, and its bottom space. +2. A clipped, weighted content viewport containing loading, error, empty, + Recommended, Browse, or Collections content. + +Because the chrome participates in measurement rather than overlaying the +viewport, no tab needs a hard-coded `LibrariesChromeContentHeight` runway. +Remove the duplicate status-bar/chrome top padding from Recommended, Browse, +and Collections content. Each tab must still preserve its own internal spacing +and the existing bottom-chrome inset so its last item remains reachable. + +The optional hero artwork may continue painting behind the entire screen, +including behind the chrome. Only interactive and editorial scroll content is +confined below the chrome. This preserves the visual relationship between the +hero and header without allowing text or cards to pass under menu controls. + +## Interaction and State + +- Library switching, tab switching, search, Requests, Watch Together, + settings, profile/server switching, and sign-out behavior remain unchanged. +- Recommended retains its scroll position and hero selection behavior. +- Browse and Collections retain their filters, pagination, grids, and empty / + error states. +- The profile popup remains anchored to the profile button. Opening or closing + it must not change the content viewport or reset scroll position. +- System status-bar and display-cutout insets are consumed exactly once by the + chrome. + +## Verification + +Tests and validation must cover: + +- Structural/source coverage that all three canonical library subtabs share + one reserved chrome/content boundary. +- Recommended and Collections no longer contain scrollable top runway used to + clear the overlay. +- Browse no longer applies a second chrome/status-bar top inset. +- Loading, error, and empty states render below the chrome. +- Existing phone hero metadata and menu-order tests remain green. +- Phone release assembly succeeds. +- On a dedicated phone emulator when available: scroll Recommended, + Browse, and Collections; confirm content disappears at the chrome boundary, + the fixed chrome remains usable, and the profile popup does not move or + expose scrolling content beneath its anchor. + +Physical devices are excluded unless separately authorized. + From e156e7660eb4421d37643611246853ff0798d422 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 08:11:16 +0200 Subject: [PATCH 29/65] docs(android): plan fixed library chrome inset --- ...7-28-android-phone-library-chrome-inset.md | 349 ++++++++++++++++++ 1 file changed, 349 insertions(+) create mode 100644 docs/superpowers/plans/2026-07-28-android-phone-library-chrome-inset.md diff --git a/docs/superpowers/plans/2026-07-28-android-phone-library-chrome-inset.md b/docs/superpowers/plans/2026-07-28-android-phone-library-chrome-inset.md new file mode 100644 index 0000000000..0f8aabdc10 --- /dev/null +++ b/docs/superpowers/plans/2026-07-28-android-phone-library-chrome-inset.md @@ -0,0 +1,349 @@ +# Android Phone Library Chrome Inset Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Keep Android phone library content below the fixed library selector and subtab chrome, matching the iOS `safeAreaInset` behavior. + +**Architecture:** Preserve the full-screen backdrop in the existing root `Box`, but replace the content-first/floating-chrome overlay with a foreground `Column`: measured chrome first, then a clipped `Box` with `weight(1f)` for every library state and subtab. Remove the old per-tab status-bar/chrome runways so system insets are consumed once by the shared chrome. + +**Tech Stack:** Kotlin, Jetpack Compose, Material 3, Kotlin/JVM unit tests, Gradle. + +## Global Constraints + +- Android phone only; do not alter Android TV, server APIs, Apple code, or standalone Browse / Collections routes. +- Keep the full-screen Recommended hero backdrop; only interactive/editorial scroll content is confined below the chrome. +- Preserve library/profile menu actions, tab state, scroll state, filters, pagination, grids, hero selection, and bottom-chrome padding. +- The shared library chrome consumes status-bar/display-cutout top inset exactly once. +- Do not target physical devices; emulator validation may use only the dedicated phone emulator when available. + +--- + +### Task 1: Reserve a measured viewport below the shared library chrome + +**Files:** +- Modify: `androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibrariesScreen.kt:610-1110` +- Modify: `androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/home/FeaturedCarousel.kt:83-125` +- Create: `androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibraryChromeInsetSourceTest.kt` + +**Interfaces:** +- Consumes: existing `LibrariesFloatingChrome`, `RecommendedTabContent`, `BrowseTabContent`, `CollectionsTabContent`, `FeaturedCarousel`, and `LocalBottomChromeInset`. +- Produces: one measured `Column` boundary in `LibrariesScreen`; a `FeaturedCarousel(topInset: Dp = 16.dp)` parameter that adds only content-local breathing room. + +- [ ] **Step 1: Write the failing structural regression tests** + +Create `LibraryChromeInsetSourceTest.kt` with repository-standard source loading: + +```kotlin +package org.siloserver.silo.android.ui.screens.libraries + +import java.io.File +import kotlin.test.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class LibraryChromeInsetSourceTest { + private fun source(path: String): String { + val moduleRelative = File("src/androidMain/kotlin/$path") + val projectRelative = File("androidApp/src/androidMain/kotlin/$path") + return (moduleRelative.takeIf(File::exists) ?: projectRelative).readText() + } + + private val libraries = source( + "org/siloserver/silo/android/ui/screens/libraries/LibrariesScreen.kt", + ) + private val carousel = source( + "org/siloserver/silo/android/ui/screens/home/FeaturedCarousel.kt", + ) + + @Test + fun sharedChromeOwnsReservedSpaceBeforeEveryLibraryTab() { + val chrome = libraries.indexOf("LibrariesFloatingChrome(") + val viewport = libraries.indexOf("LibraryContentViewport(") + assertTrue(chrome >= 0) + assertTrue(viewport > chrome) + assertTrue(libraries.contains("Modifier.weight(1f).clipToBounds()")) + } + + @Test + fun tabsDoNotCarryOverlayClearanceRunways() { + assertFalse(libraries.contains("LibrariesChromeContentHeight")) + assertFalse(libraries.contains("extraTopInset = 50.dp")) + assertFalse(libraries.contains(".windowInsetsPadding(WindowInsets.statusBars)")) + assertFalse(carousel.contains("WindowInsets.statusBars")) + assertTrue(carousel.contains("topInset: androidx.compose.ui.unit.Dp = 16.dp")) + } +} +``` + +- [ ] **Step 2: Run the source test and verify RED** + +Run: + +```bash +./gradlew :androidApp:testDebugUnitTest \ + --tests org.siloserver.silo.android.ui.screens.libraries.LibraryChromeInsetSourceTest \ + --rerun-tasks --max-workers=2 --no-daemon +``` + +Expected: FAIL because `LibraryContentViewport`, the reserved weighted/clipped viewport, and the simplified carousel inset do not exist; overlay-clearance constants remain. + +- [ ] **Step 3: Put the chrome before a shared clipped viewport** + +In `LibrariesScreen`, retain backdrop drawing in the root `Box`, then render: + +```kotlin +Column(modifier = Modifier.fillMaxSize()) { + LibrariesFloatingChrome( + scrimProgress = chromeScrimProgress, + selectedLibrary = selectedLibrary, + canSwitch = state.libraries.size > 1, + activeProfile = activeProfile, + selectedTab = state.selectedTab, + onLibrarySelectorClick = onLibrarySelectorClick, + onTabSelected = viewModel::selectTab, + onSearchClick = onSearchClick, + onRequestsClick = onRequestsClick, + onWatchTogetherClick = onWatchTogetherClick, + onSettingsClick = onSettingsClick, + onSwitchProfileClick = onSwitchProfileClick, + onSwitchServerClick = onSwitchServerClick, + onSignOutClick = onSignOutClick, + ) + + LibraryContentViewport( + modifier = Modifier.weight(1f).clipToBounds(), + ) { + when { + state.isLoadingLibraries && state.libraries.isEmpty() -> { + Box( + modifier = Modifier.fillMaxSize(), + contentAlignment = Alignment.Center, + ) { + CircularProgressIndicator() + } + } + state.librariesError != null && state.libraries.isEmpty() -> { + ErrorView( + message = state.librariesError ?: "Failed to load libraries", + onRetry = viewModel::refresh, + modifier = Modifier.fillMaxSize(), + ) + } + selectedLibrary == null -> { + EmptyStateView( + title = "No libraries available", + subtitle = "Libraries visible to this profile will show up here", + icon = Icons.Default.VideoLibrary, + modifier = Modifier.fillMaxSize(), + ) + } + state.selectedTab == LibrariesSubtab.Recommended -> { + RecommendedTabContent( + state = state, + listState = recommendedListState, + onItemClick = onItemClick, + onPlayClick = onPlayClick, + onRetry = viewModel::retryCurrentTab, + onActiveBackdropChange = { url, thumbhash -> + heroBackdropUrl = url + heroBackdropThumbhash = thumbhash + }, + ) + } + state.selectedTab == LibrariesSubtab.Browse -> { + BrowseTabContent( + state = state, + onItemClick = onItemClick, + onRetry = viewModel::retryCurrentTab, + onLoadMore = viewModel::loadMoreCatalog, + onSortChanged = viewModel::selectBrowseSort, + onNamePrefixChanged = viewModel::selectNamePrefix, + onDensityChanged = viewModel::selectViewDensity, + onApplyFilter = viewModel::applyFilterState, + onSetPreserve = viewModel::setPreserveFilters, + ) + } + else -> { + CollectionsTabContent( + state = state, + onCollectionClick = { collectionId -> + state.selectedLibraryId?.let { libraryId -> + onCollectionClick(collectionId, libraryId) + } + }, + onRetry = viewModel::retryCurrentTab, + ) + } + } + } +} +``` + +Add the focused wrapper next to `LibrariesScreen`: + +```kotlin +@Composable +private fun LibraryContentViewport( + modifier: Modifier = Modifier, + content: @Composable BoxScope.() -> Unit, +) { + Box( + modifier = modifier.fillMaxWidth(), + content = content, + ) +} +``` + +Import `androidx.compose.ui.draw.clipToBounds`. + +- [ ] **Step 4: Remove duplicate top-clearance padding** + +Delete `LibrariesChromeContentHeight`. In Recommended loading/error/empty +states, remove `.padding(top = LibrariesChromeContentHeight)` and +`.windowInsetsPadding(WindowInsets.statusBars)`. Remove the `no-featured` +status-bar/chrome spacer and replace it with: + +```kotlin +item(key = "no-featured") { + Spacer(modifier = Modifier.height(16.dp)) +} +``` + +In Browse, change the outer modifier to: + +```kotlin +modifier = Modifier.fillMaxSize() +``` + +In Collections, remove `contentTopPadding` and every +`.padding(top = contentTopPadding)` while retaining existing grid/content +padding and `LocalBottomChromeInset`. + +- [ ] **Step 5: Simplify the carousel's top inset** + +In `FeaturedCarousel`, replace `extraTopInset` and the system-inset calculation: + +```kotlin +topInset: androidx.compose.ui.unit.Dp = 16.dp, +``` + +and: + +```kotlin +Spacer(modifier = Modifier.height(topInset)) +``` + +Remove the unused `WindowInsets`, `asPaddingValues`, and +`calculateTopPadding` imports. The only caller uses the 16dp default. + +- [ ] **Step 6: Run the focused test and existing phone metadata/menu regressions** + +Run: + +```bash +./gradlew :androidApp:testDebugUnitTest \ + --tests org.siloserver.silo.android.ui.screens.libraries.LibraryChromeInsetSourceTest \ + --tests org.siloserver.silo.android.ui.screens.home.FeaturedHeroMetadataTest \ + --tests org.siloserver.silo.android.ui.screens.watchtogether.WatchTogetherMenuEntrySourceTest \ + --rerun-tasks --max-workers=2 --no-daemon +``` + +Expected: BUILD SUCCESSFUL; all selected tests pass. + +- [ ] **Step 7: Inspect the scoped diff and commit** + +Run: + +```bash +git diff --check +git diff -- \ + androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibrariesScreen.kt \ + androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/home/FeaturedCarousel.kt \ + androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibraryChromeInsetSourceTest.kt +``` + +Commit: + +```bash +git add \ + androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibrariesScreen.kt \ + androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/home/FeaturedCarousel.kt \ + androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibraryChromeInsetSourceTest.kt +git commit -m "fix(android): keep library content below chrome" +``` + +### Task 2: Verify the integrated branch and publish tester artifacts + +**Files:** +- Verify only: all files changed by `origin/main...HEAD` + +**Interfaces:** +- Consumes: Task 1's fixed library viewport plus existing TV focus, editorial hero, and identity-scoped request fixes. +- Produces: independently reviewed branch, green phone/TV gates, signed universal tester APKs, and updated PR #126. + +- [ ] **Step 1: Run supply-chain policy** + +Run: + +```bash +./scripts/test-check-build-supply-chain.sh +./scripts/check-build-supply-chain.sh +``` + +Expected: self-tests pass and both commands exit 0. + +- [ ] **Step 2: Run the full phone/TV unit and release gate** + +Run: + +```bash +./gradlew \ + :androidApp:testDebugUnitTest \ + :androidTvApp:testDebugUnitTest \ + :androidApp:assembleRelease \ + :androidTvApp:assembleRelease \ + -PallowDebugReleaseSigning=true \ + --rerun-tasks --max-workers=2 --no-daemon +``` + +Expected: BUILD SUCCESSFUL; no unit-test failures; both universal release APKs exist. + +- [ ] **Step 3: Perform emulator-only visual validation when available** + +Use only `emulator-5556`. Install the debug build serial-specifically, launch the +phone app, and verify Recommended, Browse, and Collections content stops at the +fixed chrome boundary before and after scrolling. Open/close the profile menu +and verify the list position does not change. If the dedicated emulator is not +online, record the limitation; do not touch a physical device. + +- [ ] **Step 4: Obtain independent whole-branch review** + +Provide the reviewer `origin/main...HEAD`, the approved specs, focused/full test +results, and emulator evidence or limitation. Require explicit approval or fix +each verified finding test-first before publication. + +- [ ] **Step 5: Verify and copy signed universal APKs** + +Verify package/version, universal ABIs, v2 signature, size, and SHA-256 for: + +```text +androidApp/build/outputs/apk/release/androidApp-universal-release.apk +androidTvApp/build/outputs/apk/release/androidTvApp-universal-release.apk +``` + +Copy them without overwriting existing files into +`/Users/jimcole/Desktop/Silo Releases` using filenames containing `0.3.11`, +`FocusHeroLibraryInset`, and the final short commit. + +- [ ] **Step 6: Final hygiene and PR update** + +Run: + +```bash +git diff --check origin/main...HEAD +git status --short --branch +git log --oneline origin/main..HEAD +``` + +Push `fix/tv-for-you-cold-navigation`, update PR #126 with the final test, +review, emulator, and artifact evidence, and leave it open and unmerged. From 677a0e74100caffc8378ffeb082f0ceacfba009c Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 08:16:47 +0200 Subject: [PATCH 30/65] fix(android): keep library content below chrome --- .../ui/screens/home/FeaturedCarousel.kt | 13 +- .../ui/screens/libraries/LibrariesScreen.kt | 222 ++++++++---------- .../libraries/LibraryChromeInsetSourceTest.kt | 39 +++ 3 files changed, 144 insertions(+), 130 deletions(-) create mode 100644 androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibraryChromeInsetSourceTest.kt diff --git a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/home/FeaturedCarousel.kt b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/home/FeaturedCarousel.kt index b67512b5f9..4264540587 100644 --- a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/home/FeaturedCarousel.kt +++ b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/home/FeaturedCarousel.kt @@ -14,14 +14,11 @@ import androidx.compose.foundation.layout.FlowRow import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.WindowInsets -import androidx.compose.foundation.layout.asPaddingValues import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.statusBars import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.pager.HorizontalPager @@ -86,7 +83,7 @@ fun FeaturedCarousel( onInfoClick: (String) -> Unit, modifier: Modifier = Modifier, onActiveBackdropChange: ((url: String?, thumbhash: String?) -> Unit)? = null, - extraTopInset: androidx.compose.ui.unit.Dp = 0.dp, + topInset: androidx.compose.ui.unit.Dp = 16.dp, ) { if (items.isEmpty()) return @@ -101,12 +98,6 @@ fun FeaturedCarousel( val sideInset = ((screenWidthDp - cardWidth.value) / 2f).coerceAtLeast(16f).dp val cardCornerRadius = 28.dp - val statusBarTop = WindowInsets.statusBars.asPaddingValues().calculateTopPadding() - // Push the deck below the floating chrome (status bar + ~52dp chrome + breathing room). - // Callers with taller chrome (e.g. Libraries with header + tab row) pass - // additional inset via [extraTopInset]. - val deckTopInset = statusBarTop + 64.dp + extraTopInset - LaunchedEffect(pagerState, items.size) { if (items.size > 1) { while (true) { @@ -132,7 +123,7 @@ fun FeaturedCarousel( modifier = modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally, ) { - Spacer(modifier = Modifier.height(deckTopInset)) + Spacer(modifier = Modifier.height(topInset)) HorizontalPager( state = pagerState, diff --git a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibrariesScreen.kt b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibrariesScreen.kt index e0d9d3aaf4..405e0a3ae6 100644 --- a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibrariesScreen.kt +++ b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibrariesScreen.kt @@ -66,6 +66,7 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip +import androidx.compose.ui.draw.clipToBounds import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color @@ -73,7 +74,6 @@ import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.ViewModel @@ -604,11 +604,6 @@ class LibrariesViewModel( } } -// Chrome metrics: status bar + this constant ≈ visible chrome height (header -// row + tab selector). Used to push tab content below the floating chrome and -// to drive the carousel's [extraTopInset] on the Recommended tab. -private val LibrariesChromeContentHeight: Dp = 110.dp - // Distance the Recommended tab must scroll for the chrome scrim to fully // fade in. Mirrors `chromeScrimFadeDistance` on iOS. private const val ChromeFadeDistanceDp = 80f @@ -688,86 +683,105 @@ fun LibrariesScreen( ) } - when { - state.isLoadingLibraries && state.libraries.isEmpty() -> { - Box( - modifier = Modifier.fillMaxSize(), - contentAlignment = Alignment.Center, - ) { - CircularProgressIndicator() - } - } - state.librariesError != null && state.libraries.isEmpty() -> { - ErrorView( - message = state.librariesError ?: "Failed to load libraries", - onRetry = viewModel::refresh, - modifier = Modifier.fillMaxSize(), - ) - } - selectedLibrary == null -> { - EmptyStateView( - title = "No libraries available", - subtitle = "Libraries visible to this profile will show up here", - icon = Icons.Default.VideoLibrary, - modifier = Modifier.fillMaxSize(), - ) - } - else -> { - when (state.selectedTab) { - LibrariesSubtab.Recommended -> RecommendedTabContent( - state = state, - listState = recommendedListState, - onItemClick = onItemClick, - onPlayClick = onPlayClick, - onRetry = viewModel::retryCurrentTab, - onActiveBackdropChange = { url, thumbhash -> - heroBackdropUrl = url - heroBackdropThumbhash = thumbhash - }, - ) - LibrariesSubtab.Browse -> BrowseTabContent( - state = state, - onItemClick = onItemClick, - onRetry = viewModel::retryCurrentTab, - onLoadMore = viewModel::loadMoreCatalog, - onSortChanged = viewModel::selectBrowseSort, - onNamePrefixChanged = viewModel::selectNamePrefix, - onDensityChanged = viewModel::selectViewDensity, - onApplyFilter = viewModel::applyFilterState, - onSetPreserve = viewModel::setPreserveFilters, - ) - LibrariesSubtab.Collections -> CollectionsTabContent( - state = state, - onCollectionClick = { collectionId -> - state.selectedLibraryId?.let { libraryId -> - onCollectionClick(collectionId, libraryId) - } - }, - onRetry = viewModel::retryCurrentTab, - ) + Column(modifier = Modifier.fillMaxSize()) { + LibrariesFloatingChrome( + scrimProgress = chromeScrimProgress, + selectedLibrary = selectedLibrary, + canSwitch = state.libraries.size > 1, + activeProfile = activeProfile, + selectedTab = state.selectedTab, + onLibrarySelectorClick = onLibrarySelectorClick, + onTabSelected = viewModel::selectTab, + onSearchClick = onSearchClick, + onRequestsClick = onRequestsClick, + onWatchTogetherClick = onWatchTogetherClick, + onSettingsClick = onSettingsClick, + onSwitchProfileClick = onSwitchProfileClick, + onSwitchServerClick = onSwitchServerClick, + onSignOutClick = onSignOutClick, + ) + + LibraryContentViewport( + modifier = Modifier.weight(1f).clipToBounds(), + ) { + when { + state.isLoadingLibraries && state.libraries.isEmpty() -> { + Box( + modifier = Modifier.fillMaxSize(), + contentAlignment = Alignment.Center, + ) { + CircularProgressIndicator() + } + } + state.librariesError != null && state.libraries.isEmpty() -> { + ErrorView( + message = state.librariesError ?: "Failed to load libraries", + onRetry = viewModel::refresh, + modifier = Modifier.fillMaxSize(), + ) + } + selectedLibrary == null -> { + EmptyStateView( + title = "No libraries available", + subtitle = "Libraries visible to this profile will show up here", + icon = Icons.Default.VideoLibrary, + modifier = Modifier.fillMaxSize(), + ) + } + state.selectedTab == LibrariesSubtab.Recommended -> { + RecommendedTabContent( + state = state, + listState = recommendedListState, + onItemClick = onItemClick, + onPlayClick = onPlayClick, + onRetry = viewModel::retryCurrentTab, + onActiveBackdropChange = { url, thumbhash -> + heroBackdropUrl = url + heroBackdropThumbhash = thumbhash + }, + ) + } + state.selectedTab == LibrariesSubtab.Browse -> { + BrowseTabContent( + state = state, + onItemClick = onItemClick, + onRetry = viewModel::retryCurrentTab, + onLoadMore = viewModel::loadMoreCatalog, + onSortChanged = viewModel::selectBrowseSort, + onNamePrefixChanged = viewModel::selectNamePrefix, + onDensityChanged = viewModel::selectViewDensity, + onApplyFilter = viewModel::applyFilterState, + onSetPreserve = viewModel::setPreserveFilters, + ) + } + else -> { + CollectionsTabContent( + state = state, + onCollectionClick = { collectionId -> + state.selectedLibraryId?.let { libraryId -> + onCollectionClick(collectionId, libraryId) + } + }, + onRetry = viewModel::retryCurrentTab, + ) + } } } } - - LibrariesFloatingChrome( - scrimProgress = chromeScrimProgress, - selectedLibrary = selectedLibrary, - canSwitch = state.libraries.size > 1, - activeProfile = activeProfile, - selectedTab = state.selectedTab, - onLibrarySelectorClick = onLibrarySelectorClick, - onTabSelected = viewModel::selectTab, - onSearchClick = onSearchClick, - onRequestsClick = onRequestsClick, - onWatchTogetherClick = onWatchTogetherClick, - onSettingsClick = onSettingsClick, - onSwitchProfileClick = onSwitchProfileClick, - onSwitchServerClick = onSwitchServerClick, - onSignOutClick = onSignOutClick, - ) } } +@Composable +private fun LibraryContentViewport( + modifier: Modifier = Modifier, + content: @Composable BoxScope.() -> Unit, +) { + Box( + modifier = modifier.fillMaxWidth(), + content = content, + ) +} + @Composable private fun RecommendedTabContent( state: LibrariesUiState, @@ -780,20 +794,14 @@ private fun RecommendedTabContent( when { state.isLoadingSections && state.sections.isEmpty() -> { MediaRowsSkeleton( - modifier = Modifier - .fillMaxSize() - .padding(top = LibrariesChromeContentHeight) - .windowInsetsPadding(WindowInsets.statusBars), + modifier = Modifier.fillMaxSize(), ) } state.sectionsError != null && state.sections.isEmpty() -> { ErrorView( message = state.sectionsError ?: "Failed to load recommendations", onRetry = onRetry, - modifier = Modifier - .fillMaxSize() - .padding(top = LibrariesChromeContentHeight) - .windowInsetsPadding(WindowInsets.statusBars), + modifier = Modifier.fillMaxSize(), ) } state.sections.isEmpty() -> { @@ -801,10 +809,7 @@ private fun RecommendedTabContent( title = "No recommendations yet", subtitle = "Try switching libraries or browsing the full catalog", icon = libraryIcon(state.libraries.firstOrNull { it.id == state.selectedLibraryId }?.type.orEmpty()), - modifier = Modifier - .fillMaxSize() - .padding(top = LibrariesChromeContentHeight) - .windowInsetsPadding(WindowInsets.statusBars), + modifier = Modifier.fillMaxSize(), ) } else -> { @@ -826,21 +831,11 @@ private fun RecommendedTabContent( onPlayClick = onPlayClick, onInfoClick = onItemClick, onActiveBackdropChange = onActiveBackdropChange, - // Push the deck below the taller Libraries chrome - // (header + tab selector). Carousel already adds - // `statusBar + 64dp`; this covers the tab row. - extraTopInset = 50.dp, ) } } else { - // No featured → reserve runway under the chrome so the - // first row doesn't slide under the floating header. item(key = "no-featured") { - Spacer( - modifier = Modifier - .windowInsetsPadding(WindowInsets.statusBars) - .height(LibrariesChromeContentHeight + 8.dp), - ) + Spacer(modifier = Modifier.height(16.dp)) } } @@ -878,10 +873,7 @@ private fun BrowseTabContent( ) { var showFilterSheet by remember { mutableStateOf(false) } Column( - modifier = Modifier - .fillMaxSize() - .windowInsetsPadding(WindowInsets.statusBars) - .padding(top = LibrariesChromeContentHeight), + modifier = Modifier.fillMaxSize(), ) { // Sort chips + a Filter button that opens the shared FilterSheet. Genre // is now a Categories facet inside the sheet (no inline genre rail, L3), @@ -1051,24 +1043,18 @@ private fun CollectionsTabContent( onCollectionClick: (String) -> Unit, onRetry: () -> Unit, ) { - val contentTopPadding = WindowInsets.statusBars.asPaddingValues().calculateTopPadding() + - LibrariesChromeContentHeight when { state.isLoadingCollections && state.collections.isEmpty() -> { PosterGridSkeleton( progress = rememberShimmerProgress(), - modifier = Modifier - .fillMaxSize() - .padding(top = contentTopPadding), + modifier = Modifier.fillMaxSize(), ) } state.collectionsError != null && state.collections.isEmpty() -> { ErrorView( message = state.collectionsError ?: "Failed to load collections", onRetry = onRetry, - modifier = Modifier - .fillMaxSize() - .padding(top = contentTopPadding), + modifier = Modifier.fillMaxSize(), ) } state.collections.isEmpty() -> { @@ -1076,9 +1062,7 @@ private fun CollectionsTabContent( title = "No collections found", subtitle = "This library does not have any collections yet", icon = Icons.Default.VideoLibrary, - modifier = Modifier - .fillMaxSize() - .padding(top = contentTopPadding), + modifier = Modifier.fillMaxSize(), ) } else -> { @@ -1092,7 +1076,7 @@ private fun CollectionsTabContent( contentPadding = PaddingValues( start = 16.dp, end = 16.dp, - top = contentTopPadding, + top = 16.dp, bottom = 24.dp + LocalBottomChromeInset.current, ), ) { diff --git a/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibraryChromeInsetSourceTest.kt b/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibraryChromeInsetSourceTest.kt new file mode 100644 index 0000000000..17c9d6fee6 --- /dev/null +++ b/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibraryChromeInsetSourceTest.kt @@ -0,0 +1,39 @@ +package org.siloserver.silo.android.ui.screens.libraries + +import java.io.File +import kotlin.test.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class LibraryChromeInsetSourceTest { + private fun source(path: String): String { + val moduleRelative = File("src/androidMain/kotlin/$path") + val projectRelative = File("androidApp/src/androidMain/kotlin/$path") + return (moduleRelative.takeIf(File::exists) ?: projectRelative).readText() + } + + private val libraries = source( + "org/siloserver/silo/android/ui/screens/libraries/LibrariesScreen.kt", + ) + private val carousel = source( + "org/siloserver/silo/android/ui/screens/home/FeaturedCarousel.kt", + ) + + @Test + fun sharedChromeOwnsReservedSpaceBeforeEveryLibraryTab() { + val chrome = libraries.indexOf("LibrariesFloatingChrome(") + val viewport = libraries.indexOf("LibraryContentViewport(") + assertTrue(chrome >= 0) + assertTrue(viewport > chrome) + assertTrue(libraries.contains("Modifier.weight(1f).clipToBounds()")) + } + + @Test + fun tabsDoNotCarryOverlayClearanceRunways() { + assertFalse(libraries.contains("LibrariesChromeContentHeight")) + assertFalse(libraries.contains("extraTopInset = 50.dp")) + assertFalse(libraries.contains(".windowInsetsPadding(WindowInsets.statusBars)")) + assertFalse(carousel.contains("WindowInsets.statusBars")) + assertTrue(carousel.contains("topInset: androidx.compose.ui.unit.Dp = 16.dp")) + } +} From 469f217f13722c1293f06b68aa20412446a338ed Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 08:30:29 +0200 Subject: [PATCH 31/65] docs(android): trim library inset spec --- .../2026-07-28-android-phone-library-chrome-inset-design.md | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/superpowers/specs/2026-07-28-android-phone-library-chrome-inset-design.md b/docs/superpowers/specs/2026-07-28-android-phone-library-chrome-inset-design.md index f6962c839e..0182f812ca 100644 --- a/docs/superpowers/specs/2026-07-28-android-phone-library-chrome-inset-design.md +++ b/docs/superpowers/specs/2026-07-28-android-phone-library-chrome-inset-design.md @@ -93,4 +93,3 @@ Tests and validation must cover: expose scrolling content beneath its anchor. Physical devices are excluded unless separately authorized. - From b55f6a6672173d958f5d9f2ae40b7faad4c432a9 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 08:41:06 +0200 Subject: [PATCH 32/65] fix(tv): bound top menu focus retries --- .../silo/tv/ui/shell/TvTopMenuBar.kt | 6 +++- .../silo/tv/ui/shell/TvTopMenuFocusRequest.kt | 13 +++++++- .../tv/ui/shell/TvTopMenuFocusRequestTest.kt | 30 +++++++++++++++++++ 3 files changed, 47 insertions(+), 2 deletions(-) diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuBar.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuBar.kt index eb142f2bad..b9bd48a9a3 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuBar.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuBar.kt @@ -231,6 +231,7 @@ fun TvTopMenuBar( // isFocusSuppressed false) does NOT also re-grab the selected tab and fight // the dedicated profile-avatar focus path below. val currentFocusRequestTarget by rememberUpdatedState(focusRequestTarget) + val currentDestinations by rememberUpdatedState(destinations) var lastHandledFocusRequest by remember { mutableStateOf>(0 to null) } val focusRequestIdentity = focusRequest to focusRequestTarget LaunchedEffect(focusRequest, focusRequestTarget, isFocusSuppressed) { @@ -241,7 +242,10 @@ fun TvTopMenuBar( val requester = explicitFocus?.let(::requesterForFocus) ?: selectedEntryRequester() requestTopMenuFocusUntilApplied( awaitFrame = { androidx.compose.runtime.withFrameNanos { } }, - isTargetCurrent = { currentFocusRequestTarget == focusRequestTarget }, + isTargetCurrent = { + currentFocusRequestTarget == focusRequestTarget && + isTopMenuFocusTargetAvailable(focusRequestTarget, currentDestinations) + }, requestFocus = { runCatching { requester.requestFocus() }.getOrDefault(false) }, diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuFocusRequest.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuFocusRequest.kt index 62eb53865a..bc3dc2d51d 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuFocusRequest.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuFocusRequest.kt @@ -1,11 +1,22 @@ package org.siloserver.silo.tv.ui.shell +private const val TopMenuFocusMaxAttempts = 6 + +internal fun isTopMenuFocusTargetAvailable( + target: TvTopMenuPanel?, + destinations: List, +): Boolean = when (target) { + is TvTopMenuPanel.Root -> target.dest in destinations + TvTopMenuPanel.Profile, null -> true +} + internal suspend fun requestTopMenuFocusUntilApplied( awaitFrame: suspend () -> Unit, isTargetCurrent: () -> Boolean = { true }, requestFocus: () -> Boolean, ) { - while (isTargetCurrent()) { + repeat(TopMenuFocusMaxAttempts) { + if (!isTargetCurrent()) return awaitFrame() if (!isTargetCurrent()) return if (requestFocus()) return diff --git a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuFocusRequestTest.kt b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuFocusRequestTest.kt index 02f658073a..1772d7d9c3 100644 --- a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuFocusRequestTest.kt +++ b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuFocusRequestTest.kt @@ -51,4 +51,34 @@ class TvTopMenuFocusRequestTest { assertEquals(listOf("frame", "focus"), events) } + + @Test + fun retryStopsAfterSixFramesWhenTheTargetNeverAttaches() = runTest { + var frames = 0 + var attempts = 0 + + requestTopMenuFocusUntilApplied( + awaitFrame = { frames += 1 }, + requestFocus = { + attempts += 1 + attempts == 7 + }, + ) + + assertEquals(6, frames) + assertEquals(6, attempts) + } + + @Test + fun libraryTargetIsNotAvailableAfterItsDestinationDisappears() { + val movies = TvRootDestination.LibraryType(TvLibraryTabType.Movies) + + assertEquals( + false, + isTopMenuFocusTargetAvailable( + target = TvTopMenuPanel.Root(movies), + destinations = listOf(TvRootDestination.Home, TvRootDestination.Calendar), + ), + ) + } } From c9de4b7a0a0d65870f00cf0a549c9ad66e1c99e2 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 08:46:50 +0200 Subject: [PATCH 33/65] docs(android): plan release audit fixes --- .../2026-07-28-android-release-audit-fixes.md | 165 ++++++++++++++++++ 1 file changed, 165 insertions(+) create mode 100644 docs/superpowers/plans/2026-07-28-android-release-audit-fixes.md diff --git a/docs/superpowers/plans/2026-07-28-android-release-audit-fixes.md b/docs/superpowers/plans/2026-07-28-android-release-audit-fixes.md new file mode 100644 index 0000000000..efbf80f826 --- /dev/null +++ b/docs/superpowers/plans/2026-07-28-android-release-audit-fixes.md @@ -0,0 +1,165 @@ +# Android Release Audit Fixes Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Eliminate the three Important Android phone release bugs found by the final audit: stale Libraries responses, Browse content behind bottom chrome, and cross-identity cache attribution. + +**Architecture:** Libraries request families will use generation tokens owned by `LibrariesViewModel`, allowing superseded asynchronous completions to be discarded without changing repository APIs. `CatalogGrid` will accept the already-measured bottom chrome inset and reserve it for both grid content and the alphabet rail. Offline cache writes will preserve request-time identity ownership by rejecting writes after the shared identity generation changes. + +**Tech Stack:** Kotlin, coroutines/StateFlow, Jetpack Compose, Room-backed Android catalog cache, Kotlin test/coroutines-test, Gradle. + +## Global Constraints + +- Android phone and shared Android code only; no server/API/schema/protocol changes. +- Preserve existing successful response, offline fallback, paging, and identity-transition behavior. +- Tests must deterministically complete deferred requests out of order; no sleeps or widened timeouts. +- Physical devices remain excluded. +- Every production correction must be preceded by a failing regression. + +--- + +### Task 1: Make Libraries Results Current and Keep Browse Above Bottom Chrome + +**Files:** +- Modify: `androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibrariesScreen.kt` +- Modify: `androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/browse/CatalogGrid.kt` +- Test: `androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibrariesViewModelTest.kt` +- Test: `androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibraryChromeInsetSourceTest.kt` + +**Interfaces:** +- Consumes: `LocalBottomChromeInset.current`, the existing `LibrariesUiState` selected library/query fields, and existing repository suspend functions. +- Produces: monotonically increasing Recommended, Browse, and Collections request generations; `CatalogGrid(..., bottomContentInset: Dp = 0.dp)` whose grid and alphabet rail stay above that inset. + +- [ ] **Step 1: Write deferred-response regressions** + +Add deterministic tests that start request A, change library or Browse query state, start request B, complete B first, then A, and assert the final rows/grid still belong to B. Cover Recommended, Browse sort/filter, and Collections. + +- [ ] **Step 2: Verify the request regressions fail** + +Run: + +```bash +./gradlew :androidApp:testDebugUnitTest \ + --tests org.siloserver.silo.android.ui.screens.libraries.LibrariesViewModelTest \ + --rerun-tasks --max-workers=2 --no-daemon +``` + +Expected: the reverse-completion assertions fail because A overwrites B. + +- [ ] **Step 3: Implement request generations** + +Keep one counter per request family: + +```kotlin +private var recommendedRequestGeneration = 0L +private var catalogRequestGeneration = 0L +private var collectionsRequestGeneration = 0L +``` + +Increment and capture the family generation before launching work. Before every success/error/loading completion write, require both the captured generation and the captured library/query identity to remain current. Superseded requests may finish, but must not mutate `uiState`. + +- [ ] **Step 4: Write the bottom-inset regression** + +Extend `LibraryChromeInsetSourceTest` to require `BrowseTabContent` to pass `LocalBottomChromeInset.current` into `CatalogGrid`, and require `CatalogGrid` to expose and consume `bottomContentInset` in both its scroll padding and alphabet-rail bounds. + +- [ ] **Step 5: Verify the inset regression fails** + +Run: + +```bash +./gradlew :androidApp:testDebugUnitTest \ + --tests org.siloserver.silo.android.ui.screens.libraries.LibraryChromeInsetSourceTest \ + --rerun-tasks --max-workers=2 --no-daemon +``` + +Expected: failure because `CatalogGrid` currently hard-codes 8dp bottom padding and the full-height rail. + +- [ ] **Step 6: Implement the measured bottom inset** + +Add: + +```kotlin +bottomContentInset: Dp = 0.dp +``` + +to `CatalogGrid`. Add it to grid/list bottom `contentPadding`, and constrain/pad the alphabet rail so its interactive range ends above the same inset. Pass `LocalBottomChromeInset.current` from Libraries Browse; standalone callers retain the zero default. + +- [ ] **Step 7: Run focused GREEN verification and commit** + +Run both focused test classes and relevant Android compilation. Commit only Task 1 files with: + +```bash +git commit -m "fix(android): keep library results and browse chrome current" +``` + +### Task 2: Preserve Request-Time Identity for Offline Cache Writes + +**Files:** +- Modify: `android-shared/src/androidMain/kotlin/org/siloserver/silo/common/cache/RoomCatalogCacheRepository.kt` +- Modify only if required by the narrow ownership boundary: `shared/src/commonMain/kotlin/org/siloserver/silo/repository/CatalogRepository.kt` +- Modify only if required by the narrow ownership boundary: `shared/src/commonMain/kotlin/org/siloserver/silo/repository/SectionRepository.kt` +- Test: existing Room/cache repository Android unit tests and `shared/src/commonTest/kotlin/org/siloserver/silo/repository/CatalogRepositoryDetailCacheTest.kt` + +**Interfaces:** +- Consumes: `IdentityTransitionBarrier.generation` and the existing cache snapshot/provider. +- Produces: cache writes that are accepted only when the request-time identity generation is still current; reads and offline fallback remain unchanged. + +- [ ] **Step 1: Write the delayed identity-switch regression** + +Create a deferred API response under identity A, switch the barrier/snapshot to B, complete A, then assert A's response is not written or readable as B. Cover item detail and one section/catalog path that exercises the shared ownership seam. + +- [ ] **Step 2: Verify the ownership regression fails** + +Run the exact new cache/repository tests with: + +```bash +./gradlew :shared:testDebugUnitTest :android-shared:testDebugUnitTest \ + --tests '*CatalogRepositoryDetailCacheTest*' \ + --tests '*RoomCatalogCacheRepository*' \ + --rerun-tasks --max-workers=2 --no-daemon +``` + +Expected: failure showing the A response attributed to B. + +- [ ] **Step 3: Implement generation-validated writes** + +Capture `IdentityTransitionBarrier.generation` before each network-backed cacheable request. At completion, call the existing cache write only when the captured generation still equals the current generation. Do not synthesize a new identity from completion-time state and do not alter offline-read fallback semantics. + +- [ ] **Step 4: Run focused GREEN verification and commit** + +Run the new regressions plus neighboring cache/repository tests. Commit only Task 2 files with: + +```bash +git commit -m "fix(shared): keep cache writes identity scoped" +``` + +### Task 3: Integrate and Requalify the Release + +**Files:** +- Verify only: all files changed by Tasks 1 and 2. + +**Interfaces:** +- Consumes: both reviewed fix commits. +- Produces: one clean branch with green supply-chain, phone/TV unit, and phone/TV release gates. + +- [ ] **Step 1: Review each task diff independently** + +Require explicit spec-compliance and code-quality approval; fix every Critical, Important, or Minor release finding before continuing. + +- [ ] **Step 2: Run the exact release gate** + +```bash +./scripts/test-check-build-supply-chain.sh +./scripts/check-build-supply-chain.sh +./gradlew \ + :androidApp:testDebugUnitTest \ + :androidTvApp:testDebugUnitTest \ + :androidApp:assembleRelease \ + :androidTvApp:assembleRelease \ + -PallowDebugReleaseSigning=true \ + --rerun-tasks --max-workers=2 --no-daemon +``` + +- [ ] **Step 3: Perform whole-branch review and artifact verification** + +Require a clean `origin/main...HEAD` review, verify universal APK package/version/ABIs/v2 signature/size/SHA-256, copy final-hash artifacts without overwrite, then push and update PR #126 without merging. From c812e06f64eb01bea3a41593b22c43b0d1bda47d Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 08:55:43 +0200 Subject: [PATCH 34/65] fix(shared): keep cache writes identity scoped --- .../repository/RoomCatalogCacheRepository.kt | 5 +++ .../RoomCatalogCacheRepositoryTest.kt | 33 ++++++++++++++++ .../silo/android/di/AndroidModule.kt | 1 + .../siloserver/silo/tv/di/AndroidTvModule.kt | 1 + .../siloserver/silo/di/RepositoryModule.kt | 9 ++++- .../silo/repository/CatalogRepository.kt | 23 +++++++++-- .../silo/repository/SectionRepository.kt | 5 ++- .../CatalogRepositoryDetailCacheTest.kt | 38 +++++++++++++++++++ .../repository/SectionRepositoryCacheTest.kt | 35 +++++++++++++++++ 9 files changed, 144 insertions(+), 6 deletions(-) diff --git a/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/repository/RoomCatalogCacheRepository.kt b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/repository/RoomCatalogCacheRepository.kt index 34c634b768..6a1a394dc3 100644 --- a/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/repository/RoomCatalogCacheRepository.kt +++ b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/repository/RoomCatalogCacheRepository.kt @@ -9,6 +9,8 @@ import org.siloserver.silo.model.catalog.SeasonsResponse import org.siloserver.silo.model.personal.UserLibrary import org.siloserver.silo.model.section.ResolvedSection import org.siloserver.silo.network.AuthScopeSnapshot +import org.siloserver.silo.network.DefaultIdentityTransitionBarrier +import org.siloserver.silo.network.IdentityTransitionBarrier import org.siloserver.silo.repository.port.CatalogCachePort import kotlinx.serialization.json.Json @@ -21,6 +23,7 @@ import kotlinx.serialization.json.Json class RoomCatalogCacheRepository( db: SiloDatabase, private val snapshotProvider: suspend () -> AuthScopeSnapshot?, + private val identityTransitions: IdentityTransitionBarrier = DefaultIdentityTransitionBarrier(), private val now: () -> Long = { System.currentTimeMillis() }, ) : CatalogCachePort { @@ -64,8 +67,10 @@ class RoomCatalogCacheRepository( get(episodesKey(seriesId, seasonNumber))?.let { runCatching { json.decodeFromString(it) }.getOrNull() } private suspend fun put(cacheKey: String, jsonStr: String) { + val requestIdentityGeneration = identityTransitions.generation.value val snapshot = snapshotProvider() ?: return val profileId = snapshot.profileId ?: return + if (requestIdentityGeneration != identityTransitions.generation.value) return // A Room row must fit SQLite's ~2MB CursorWindow or the *read* throws // SQLiteBlobTooBigException. Big library pages can exceed it, so don't // store an unreadable row — drop any prior row for this key and skip. diff --git a/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/data/repository/RoomCatalogCacheRepositoryTest.kt b/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/data/repository/RoomCatalogCacheRepositoryTest.kt index f640352563..dde4cc1f4a 100644 --- a/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/data/repository/RoomCatalogCacheRepositoryTest.kt +++ b/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/data/repository/RoomCatalogCacheRepositoryTest.kt @@ -7,6 +7,10 @@ import org.siloserver.silo.model.catalog.BrowseItem import org.siloserver.silo.model.catalog.CatalogResponse import org.siloserver.silo.model.personal.UserLibrary import org.siloserver.silo.network.AuthScopeSnapshot +import org.siloserver.silo.network.DefaultIdentityTransitionBarrier +import org.siloserver.silo.network.IdentityTransitionKind +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.async import kotlinx.coroutines.test.runTest import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner @@ -69,4 +73,33 @@ class RoomCatalogCacheRepositoryTest { scope = null assertNull(repo.getCachedLibraries()) } + + @Test + fun writeStartedBeforeProfileSwitchIsNotAttributedToNewProfile() = runTest { + val snapshotRequested = CompletableDeferred() + val releaseSnapshot = CompletableDeferred() + val identityTransitions = DefaultIdentityTransitionBarrier() + val delayedRepo = RoomCatalogCacheRepository( + db = db, + snapshotProvider = { + snapshotRequested.complete(Unit) + releaseSnapshot.await() + scope + }, + identityTransitions = identityTransitions, + now = { 1000L }, + ) + + val oldProfileWrite = async { + delayedRepo.cacheLibraries(listOf(UserLibrary(id = 1, name = "Profile A", type = "movie"))) + } + snapshotRequested.await() + identityTransitions.changing(IdentityTransitionKind.PROFILE_SWITCH) { + scope = AuthScopeSnapshot("s1", "p2", "https://s1.example", null) + } + releaseSnapshot.complete(Unit) + oldProfileWrite.await() + + assertNull(delayedRepo.getCachedLibraries()) + } } diff --git a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/di/AndroidModule.kt b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/di/AndroidModule.kt index 0e1fbce6b5..73a2b0dca2 100644 --- a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/di/AndroidModule.kt +++ b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/di/AndroidModule.kt @@ -151,6 +151,7 @@ val androidModule = module { org.siloserver.silo.common.data.repository.RoomCatalogCacheRepository( db = get(), snapshotProvider = { tokenManager.snapshotCurrentScope() }, + identityTransitions = get(), ) } single { diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/di/AndroidTvModule.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/di/AndroidTvModule.kt index ce8e26805a..c4fc484c59 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/di/AndroidTvModule.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/di/AndroidTvModule.kt @@ -119,6 +119,7 @@ val androidTvModule = module { org.siloserver.silo.common.data.repository.RoomCatalogCacheRepository( db = get(), snapshotProvider = { tokenManager.snapshotCurrentScope() }, + identityTransitions = get(), ) } single { diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/di/RepositoryModule.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/di/RepositoryModule.kt index e5e43d5255..1577bdcea4 100644 --- a/shared/src/commonMain/kotlin/org/siloserver/silo/di/RepositoryModule.kt +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/di/RepositoryModule.kt @@ -49,7 +49,14 @@ val repositoryModule = module { // multi-server side effects when the registry is null. single { AuthRepository(get(), get(), getOrNull(), getOrNull()) } single { DeviceLoginRepository(get()) } - single { CatalogRepository(get(), getOrNull() ?: org.siloserver.silo.repository.port.NoOpCatalogCachePort) } + single { + CatalogRepository( + catalogApi = get(), + catalogCache = getOrNull() + ?: org.siloserver.silo.repository.port.NoOpCatalogCachePort, + identityTransitions = get(), + ) + } single { CalendarRepository(get()) } single { PlaybackRepository(get()) } // `getOrNull()` picks up the Room-backed ports when the Android platform diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/repository/CatalogRepository.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/repository/CatalogRepository.kt index 2e177478ef..ef2377ab0a 100644 --- a/shared/src/commonMain/kotlin/org/siloserver/silo/repository/CatalogRepository.kt +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/repository/CatalogRepository.kt @@ -11,6 +11,8 @@ import org.siloserver.silo.model.catalog.Person import org.siloserver.silo.model.catalog.SeasonsResponse import org.siloserver.silo.model.catalog.WatchDetail import org.siloserver.silo.network.ApiResult +import org.siloserver.silo.network.DefaultIdentityTransitionBarrier +import org.siloserver.silo.network.IdentityTransitionBarrier import org.siloserver.silo.network.api.CatalogApi import org.siloserver.silo.repository.port.CatalogCachePort import org.siloserver.silo.repository.port.NoOpCatalogCachePort @@ -20,6 +22,7 @@ class CatalogRepository( private val catalogApi: CatalogApi, /** Offline read cache for a library's default first page (Track B). No-op by default. */ private val catalogCache: CatalogCachePort = NoOpCatalogCachePort, + private val identityTransitions: IdentityTransitionBarrier = DefaultIdentityTransitionBarrier(), ) { /** Browse the catalog with optional filters, sorting, and pagination. */ suspend fun browse( @@ -40,6 +43,7 @@ class CatalogRepository( queryGroups: List = emptyList(), match: String? = null, ): ApiResult { + val requestIdentityGeneration = identityTransitions.generation.value val result = catalogApi.getCatalog( source = source, query = query, @@ -71,7 +75,9 @@ class CatalogRepository( } ?: return result if (result is ApiResult.Success) { - catalogCache.cacheDefaultLibraryPage(cacheableLibraryId, result.data) + if (requestIdentityGeneration == identityTransitions.generation.value) { + catalogCache.cacheDefaultLibraryPage(cacheableLibraryId, result.data) + } return result } if (result.canServeCache()) { @@ -109,9 +115,12 @@ class CatalogRepository( /** Fetches full metadata for a single catalog item (offline: last cached detail). */ suspend fun getItemDetail(contentId: String): ApiResult { + val requestIdentityGeneration = identityTransitions.generation.value val result = catalogApi.getItemDetail(contentId) if (result is ApiResult.Success) { - catalogCache.cacheItemDetail(contentId, result.data) + if (requestIdentityGeneration == identityTransitions.generation.value) { + catalogCache.cacheItemDetail(contentId, result.data) + } return result } if (result.canServeCache()) { @@ -139,9 +148,12 @@ class CatalogRepository( /** Lists seasons for a series (offline: last cached seasons). */ suspend fun getSeasons(seriesId: String): ApiResult { + val requestIdentityGeneration = identityTransitions.generation.value val result = catalogApi.getSeasons(seriesId) if (result is ApiResult.Success) { - catalogCache.cacheSeasons(seriesId, result.data) + if (requestIdentityGeneration == identityTransitions.generation.value) { + catalogCache.cacheSeasons(seriesId, result.data) + } return result } if (result.canServeCache()) { @@ -152,9 +164,12 @@ class CatalogRepository( /** Lists episodes for a specific season of a series (offline: last cached episodes). */ suspend fun getEpisodes(seriesId: String, seasonNumber: Int): ApiResult { + val requestIdentityGeneration = identityTransitions.generation.value val result = catalogApi.getEpisodes(seriesId, seasonNumber) if (result is ApiResult.Success) { - catalogCache.cacheEpisodes(seriesId, seasonNumber, result.data) + if (requestIdentityGeneration == identityTransitions.generation.value) { + catalogCache.cacheEpisodes(seriesId, seasonNumber, result.data) + } return result } if (result.canServeCache()) { diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/repository/SectionRepository.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/repository/SectionRepository.kt index 4a26ed197e..e0372e5804 100644 --- a/shared/src/commonMain/kotlin/org/siloserver/silo/repository/SectionRepository.kt +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/repository/SectionRepository.kt @@ -92,9 +92,12 @@ class SectionRepository( /** Fetches a library's resolved sections (offline: last cached sections). */ suspend fun getLibrarySections(libraryId: Int): ApiResult { + val requestIdentityGeneration = identityTransitions.generation.value val result = sectionApi.getLibrarySections(libraryId) if (result is ApiResult.Success) { - catalogCache.cacheLibrarySections(libraryId, result.data.sections) + if (requestIdentityGeneration == identityTransitions.generation.value) { + catalogCache.cacheLibrarySections(libraryId, result.data.sections) + } return result } if (result.canServeCache()) { diff --git a/shared/src/commonTest/kotlin/org/siloserver/silo/repository/CatalogRepositoryDetailCacheTest.kt b/shared/src/commonTest/kotlin/org/siloserver/silo/repository/CatalogRepositoryDetailCacheTest.kt index 3de6207a52..75c3d94355 100644 --- a/shared/src/commonTest/kotlin/org/siloserver/silo/repository/CatalogRepositoryDetailCacheTest.kt +++ b/shared/src/commonTest/kotlin/org/siloserver/silo/repository/CatalogRepositoryDetailCacheTest.kt @@ -3,6 +3,8 @@ package org.siloserver.silo.repository import org.siloserver.silo.model.catalog.ItemDetail import org.siloserver.silo.model.catalog.SeasonsResponse import org.siloserver.silo.network.ApiResult +import org.siloserver.silo.network.DefaultIdentityTransitionBarrier +import org.siloserver.silo.network.IdentityTransitionKind import org.siloserver.silo.network.SiloJson import org.siloserver.silo.network.api.CatalogApi import org.siloserver.silo.repository.port.CatalogCachePort @@ -15,6 +17,8 @@ import io.ktor.http.HttpStatusCode import io.ktor.http.headersOf import io.ktor.serialization.kotlinx.json.json import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.async import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertTrue @@ -103,4 +107,38 @@ class CatalogRepositoryDetailCacheTest { val result = repo(HttpStatusCode.ServiceUnavailable, "{}", cache).getSeasons("series-1") assertTrue(result is ApiResult.Success) } + + @Test + fun detailResponseStartedBeforeProfileSwitchIsNotCachedForNewProfile() = runTest { + val requestEntered = CompletableDeferred() + val releaseResponse = CompletableDeferred() + val client = HttpClient( + MockEngine { + requestEntered.complete(Unit) + releaseResponse.await() + respond( + """{"content_id":"c1","type":"movie","title":"Profile A"}""", + HttpStatusCode.OK, + headersOf(HttpHeaders.ContentType, "application/json"), + ) + }, + ) { + install(ContentNegotiation) { json(SiloJson) } + } + val cache = FakeCache() + val identityTransitions = DefaultIdentityTransitionBarrier() + val repository = CatalogRepository( + catalogApi = CatalogApi(client), + catalogCache = cache, + identityTransitions = identityTransitions, + ) + + val oldProfileRequest = async { repository.getItemDetail("c1") } + requestEntered.await() + identityTransitions.changing(IdentityTransitionKind.PROFILE_SWITCH) { } + releaseResponse.complete(Unit) + + assertTrue(oldProfileRequest.await() is ApiResult.Success) + assertEquals(null, cache.cachedId) + } } diff --git a/shared/src/commonTest/kotlin/org/siloserver/silo/repository/SectionRepositoryCacheTest.kt b/shared/src/commonTest/kotlin/org/siloserver/silo/repository/SectionRepositoryCacheTest.kt index cf817f74cc..efa2965ed4 100644 --- a/shared/src/commonTest/kotlin/org/siloserver/silo/repository/SectionRepositoryCacheTest.kt +++ b/shared/src/commonTest/kotlin/org/siloserver/silo/repository/SectionRepositoryCacheTest.kt @@ -219,4 +219,39 @@ class SectionRepositoryCacheTest { assertEquals("New", (newProfileResult as ApiResult.Success).data.sections.single().title) assertEquals(2, calls) } + + @Test + fun librarySectionsStartedBeforeProfileSwitchAreNotCachedForNewProfile() = runTest { + val requestEntered = CompletableDeferred() + val releaseResponse = CompletableDeferred() + val client = HttpClient( + MockEngine { + requestEntered.complete(Unit) + releaseResponse.await() + respond( + """{"sections":[{"id":"old","section_type":"old","title":"Profile A"}]}""", + HttpStatusCode.OK, + headersOf(HttpHeaders.ContentType, "application/json"), + ) + }, + ) { + install(ContentNegotiation) { json(SiloJson) } + } + val cache = FakeCache(preset = null) + val identityTransitions = DefaultIdentityTransitionBarrier() + val repository = SectionRepository( + sectionApi = SectionApi(client), + catalogCache = cache, + identityTransitions = identityTransitions, + ) + + val oldProfileRequest = async { repository.getLibrarySections(7) } + requestEntered.await() + identityTransitions.changing(IdentityTransitionKind.PROFILE_SWITCH) { } + releaseResponse.complete(Unit) + + assertTrue(oldProfileRequest.await() is ApiResult.Success) + assertEquals(null, cache.cachedFor) + assertEquals(null, cache.cachedSections) + } } From e4d4ae97f1ed8d33270f5bd5a9502d924313d42c Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 08:59:51 +0200 Subject: [PATCH 35/65] fix(android): keep library results and browse chrome current --- .../android/ui/screens/browse/CatalogGrid.kt | 7 +- .../ui/screens/libraries/LibrariesScreen.kt | 259 ++++++++++++------ .../libraries/LibrariesViewModelTest.kt | 235 ++++++++++++++++ .../libraries/LibraryChromeInsetSourceTest.kt | 11 + 4 files changed, 433 insertions(+), 79 deletions(-) create mode 100644 androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibrariesViewModelTest.kt diff --git a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/browse/CatalogGrid.kt b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/browse/CatalogGrid.kt index e14a28240b..cb77abb6d5 100644 --- a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/browse/CatalogGrid.kt +++ b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/browse/CatalogGrid.kt @@ -31,6 +31,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import org.siloserver.silo.android.ui.components.MediaCard @@ -65,6 +66,7 @@ fun CatalogGrid( selectedNamePrefix: String? = null, onNamePrefixSelected: ((String?) -> Unit)? = null, viewDensity: CatalogViewDensity = CatalogViewDensity.Normal, + bottomContentInset: Dp = 0.dp, ) { val gridState = rememberLazyGridState() val cardWidth = viewDensity.minCardWidth @@ -94,7 +96,7 @@ fun CatalogGrid( start = 16.dp, top = 8.dp, end = if (onNamePrefixSelected != null) 56.dp else 16.dp, - bottom = 8.dp, + bottom = 8.dp + bottomContentInset, ), horizontalArrangement = Arrangement.spacedBy(MediaGridDefaults.PosterGridHorizontalSpacing), verticalArrangement = Arrangement.spacedBy(MediaGridDefaults.PosterGridVerticalSpacing), @@ -142,7 +144,8 @@ fun CatalogGrid( onNamePrefixSelected = onSelected, modifier = Modifier .align(Alignment.CenterEnd) - .padding(end = 6.dp), + .padding(end = 6.dp) + .padding(bottom = bottomContentInset), ) } } diff --git a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibrariesScreen.kt b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibrariesScreen.kt index 405e0a3ae6..ce3f05ebbc 100644 --- a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibrariesScreen.kt +++ b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibrariesScreen.kt @@ -194,6 +194,9 @@ class LibrariesViewModel( private var recommendedLoadedLibraryId: Int? = null private var browseLoadedLibraryId: Int? = null private var collectionsLoadedLibraryId: Int? = null + private var recommendedRequestGeneration = 0L + private var catalogRequestGeneration = 0L + private var collectionsRequestGeneration = 0L private val pageSize = 42 init { @@ -400,41 +403,62 @@ class LibrariesViewModel( private fun loadRecommended(libraryId: Int, force: Boolean) { if (!force && recommendedLoadedLibraryId == libraryId) return recommendedLoadedLibraryId = libraryId + val requestGeneration = ++recommendedRequestGeneration viewModelScope.launch { + if (!isRecommendedRequestCurrent(requestGeneration, libraryId)) return@launch _uiState.update { - it.copy( - isLoadingSections = true, - sectionsError = null, - sections = emptyList(), - ) + if (isRecommendedRequestCurrent(requestGeneration, libraryId, it)) { + it.copy( + isLoadingSections = true, + sectionsError = null, + sections = emptyList(), + ) + } else { + it + } } when (val result = sectionRepository.getLibrarySections(libraryId)) { is ApiResult.Success -> { + if (!isRecommendedRequestCurrent(requestGeneration, libraryId)) return@launch _uiState.update { - it.copy( - isLoadingSections = false, - sections = result.data.sections.filter { section -> section.items.isNotEmpty() }, - sectionsError = null, - ) + if (isRecommendedRequestCurrent(requestGeneration, libraryId, it)) { + it.copy( + isLoadingSections = false, + sections = result.data.sections.filter { section -> section.items.isNotEmpty() }, + sectionsError = null, + ) + } else { + it + } } } is ApiResult.Error -> { + if (!isRecommendedRequestCurrent(requestGeneration, libraryId)) return@launch _uiState.update { - it.copy( - isLoadingSections = false, - sections = emptyList(), - sectionsError = result.message.ifBlank { "Failed to load recommendations" }, - ) + if (isRecommendedRequestCurrent(requestGeneration, libraryId, it)) { + it.copy( + isLoadingSections = false, + sections = emptyList(), + sectionsError = result.message.ifBlank { "Failed to load recommendations" }, + ) + } else { + it + } } } is ApiResult.NetworkError -> { + if (!isRecommendedRequestCurrent(requestGeneration, libraryId)) return@launch _uiState.update { - it.copy( - isLoadingSections = false, - sections = emptyList(), - sectionsError = "Network error: ${result.exception.message ?: "unknown"}", - ) + if (isRecommendedRequestCurrent(requestGeneration, libraryId, it)) { + it.copy( + isLoadingSections = false, + sections = emptyList(), + sectionsError = "Network error: ${result.exception.message ?: "unknown"}", + ) + } else { + it + } } } } @@ -446,18 +470,35 @@ class LibrariesViewModel( return } browseLoadedLibraryId = libraryId + val requestState = _uiState.value + val requestIdentity = CatalogRequestIdentity( + libraryId = libraryId, + browseSort = requestState.browseSort, + selectedNamePrefix = requestState.selectedNamePrefix, + filterState = requestState.filterState, + ) + val requestGeneration = ++catalogRequestGeneration + val offset = if (reset) 0 else requestState.catalogItems.size viewModelScope.launch { - val state = _uiState.value - val offset = if (reset) 0 else state.catalogItems.size + if (!isCatalogRequestCurrent(requestGeneration, requestIdentity)) return@launch - if (reset && state.availableFilters == null) { + if (reset && requestState.availableFilters == null) { launch { // includeTechnical: resolution + audio/subtitle-language facets // are only fetched on request (iOS parity). Keep the FULL // response so the filter sheet has every facet, not just genres. when (val filters = catalogRepository.getFilters(libraryId, includeTechnical = true)) { is ApiResult.Success -> { - _uiState.update { it.copy(availableFilters = filters.data) } + if (!isCatalogRequestCurrent(requestGeneration, requestIdentity)) { + return@launch + } + _uiState.update { + if (isCatalogRequestCurrent(requestGeneration, requestIdentity, it)) { + it.copy(availableFilters = filters.data) + } else { + it + } + } } else -> Unit } @@ -465,38 +506,34 @@ class LibrariesViewModel( } _uiState.update { - if (reset) { - it.copy( - isLoadingCatalog = true, - isLoadingMoreCatalog = false, - catalogError = null, - ) + if (!isCatalogRequestCurrent(requestGeneration, requestIdentity, it)) { + it + } else if (reset) { + it.copy(isLoadingCatalog = true, isLoadingMoreCatalog = false, catalogError = null) } else { - it.copy( - isLoadingMoreCatalog = true, - catalogError = null, - ) + it.copy(isLoadingMoreCatalog = true, catalogError = null) } } when ( val result = catalogRepository.browse( libraryId = libraryId, - sort = state.browseSort.sortField, - order = state.browseSort.sortOrder, + sort = requestState.browseSort.sortField, + order = requestState.browseSort.sortOrder, offset = offset, limit = pageSize, - namePrefix = state.selectedNamePrefix, + namePrefix = requestState.selectedNamePrefix, // Full facet filtering (genre/decade/rating/studio/language/...) // via the shared query builder — replaces the single-genre param. - queryGroups = CatalogFilterQueryBuilder.buildGroups(state.filterState), - match = CatalogFilterQueryBuilder.matchParam(state.filterState) - .takeIf { state.filterState.hasActiveFilters }, + queryGroups = CatalogFilterQueryBuilder.buildGroups(requestState.filterState), + match = CatalogFilterQueryBuilder.matchParam(requestState.filterState) + .takeIf { requestState.filterState.hasActiveFilters }, ) ) { is ApiResult.Success -> { // Overlay local optimistic watched/favorite (mirrors Home/Browse). val overlaid = overlayLocalState(result.data.items) + if (!isCatalogRequestCurrent(requestGeneration, requestIdentity)) return@launch // Audiobook libraries expose book-native facets // (author/narrator/series) — detected from the first item. val detectedMediaType = overlaid.firstOrNull()?.let { first -> @@ -507,33 +544,47 @@ class LibrariesViewModel( } } _uiState.update { - it.copy( - isLoadingCatalog = false, - isLoadingMoreCatalog = false, - catalogItems = if (reset) overlaid else it.catalogItems + overlaid, - catalogTotal = result.data.total, - catalogHasMore = result.data.hasMore, - browseMediaType = detectedMediaType ?: it.browseMediaType, - catalogError = null, - ) + if (isCatalogRequestCurrent(requestGeneration, requestIdentity, it)) { + it.copy( + isLoadingCatalog = false, + isLoadingMoreCatalog = false, + catalogItems = if (reset) overlaid else it.catalogItems + overlaid, + catalogTotal = result.data.total, + catalogHasMore = result.data.hasMore, + browseMediaType = detectedMediaType ?: it.browseMediaType, + catalogError = null, + ) + } else { + it + } } } is ApiResult.Error -> { + if (!isCatalogRequestCurrent(requestGeneration, requestIdentity)) return@launch _uiState.update { - it.copy( - isLoadingCatalog = false, - isLoadingMoreCatalog = false, - catalogError = result.message.ifBlank { "Failed to load catalog" }, - ) + if (isCatalogRequestCurrent(requestGeneration, requestIdentity, it)) { + it.copy( + isLoadingCatalog = false, + isLoadingMoreCatalog = false, + catalogError = result.message.ifBlank { "Failed to load catalog" }, + ) + } else { + it + } } } is ApiResult.NetworkError -> { + if (!isCatalogRequestCurrent(requestGeneration, requestIdentity)) return@launch _uiState.update { - it.copy( - isLoadingCatalog = false, - isLoadingMoreCatalog = false, - catalogError = "Network error: ${result.exception.message ?: "unknown"}", - ) + if (isCatalogRequestCurrent(requestGeneration, requestIdentity, it)) { + it.copy( + isLoadingCatalog = false, + isLoadingMoreCatalog = false, + catalogError = "Network error: ${result.exception.message ?: "unknown"}", + ) + } else { + it + } } } } @@ -565,43 +616,96 @@ class LibrariesViewModel( return } collectionsLoadedLibraryId = libraryId + val requestGeneration = ++collectionsRequestGeneration viewModelScope.launch { + if (!isCollectionsRequestCurrent(requestGeneration, libraryId)) return@launch _uiState.update { - it.copy( - isLoadingCollections = true, - collectionsError = null, - collections = emptyList(), - ) + if (isCollectionsRequestCurrent(requestGeneration, libraryId, it)) { + it.copy( + isLoadingCollections = true, + collectionsError = null, + collections = emptyList(), + ) + } else { + it + } } when (val result = sectionRepository.getLibraryCollections(libraryId)) { is ApiResult.Success -> { + if (!isCollectionsRequestCurrent(requestGeneration, libraryId)) return@launch _uiState.update { - it.copy( - isLoadingCollections = false, - collections = result.data, - collectionsError = null, - ) + if (isCollectionsRequestCurrent(requestGeneration, libraryId, it)) { + it.copy( + isLoadingCollections = false, + collections = result.data, + collectionsError = null, + ) + } else { + it + } } } is ApiResult.Error -> { + if (!isCollectionsRequestCurrent(requestGeneration, libraryId)) return@launch _uiState.update { - it.copy( - isLoadingCollections = false, - collectionsError = result.message.ifBlank { "Failed to load collections" }, - ) + if (isCollectionsRequestCurrent(requestGeneration, libraryId, it)) { + it.copy( + isLoadingCollections = false, + collectionsError = result.message.ifBlank { "Failed to load collections" }, + ) + } else { + it + } } } is ApiResult.NetworkError -> { + if (!isCollectionsRequestCurrent(requestGeneration, libraryId)) return@launch _uiState.update { - it.copy( - isLoadingCollections = false, - collectionsError = "Network error: ${result.exception.message ?: "unknown"}", - ) + if (isCollectionsRequestCurrent(requestGeneration, libraryId, it)) { + it.copy( + isLoadingCollections = false, + collectionsError = "Network error: ${result.exception.message ?: "unknown"}", + ) + } else { + it + } } } } } } + + private fun isRecommendedRequestCurrent( + generation: Long, + libraryId: Int, + state: LibrariesUiState = _uiState.value, + ): Boolean = + generation == recommendedRequestGeneration && state.selectedLibraryId == libraryId + + private fun isCatalogRequestCurrent( + generation: Long, + identity: CatalogRequestIdentity, + state: LibrariesUiState = _uiState.value, + ): Boolean = + generation == catalogRequestGeneration && + state.selectedLibraryId == identity.libraryId && + state.browseSort == identity.browseSort && + state.selectedNamePrefix == identity.selectedNamePrefix && + state.filterState == identity.filterState + + private fun isCollectionsRequestCurrent( + generation: Long, + libraryId: Int, + state: LibrariesUiState = _uiState.value, + ): Boolean = + generation == collectionsRequestGeneration && state.selectedLibraryId == libraryId + + private data class CatalogRequestIdentity( + val libraryId: Int, + val browseSort: LibraryBrowseSort, + val selectedNamePrefix: String?, + val filterState: CatalogFilterState, + ) } // Distance the Recommended tab must scroll for the chrome scrim to fully @@ -982,6 +1086,7 @@ private fun BrowseTabContent( selectedNamePrefix = state.selectedNamePrefix, onNamePrefixSelected = onNamePrefixChanged, viewDensity = state.catalogDensity, + bottomContentInset = LocalBottomChromeInset.current, modifier = Modifier.fillMaxSize(), ) } diff --git a/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibrariesViewModelTest.kt b/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibrariesViewModelTest.kt new file mode 100644 index 0000000000..28c8632d5f --- /dev/null +++ b/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibrariesViewModelTest.kt @@ -0,0 +1,235 @@ +package org.siloserver.silo.android.ui.screens.libraries + +import androidx.lifecycle.ViewModelStore +import androidx.lifecycle.viewModelScope +import io.ktor.client.HttpClient +import io.ktor.client.engine.mock.MockEngine +import io.ktor.client.engine.mock.MockRequestHandleScope +import io.ktor.client.engine.mock.respond +import io.ktor.client.plugins.contentnegotiation.ContentNegotiation +import io.ktor.http.HttpHeaders +import io.ktor.http.HttpStatusCode +import io.ktor.http.headersOf +import io.ktor.serialization.kotlinx.json.json +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.Job +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.test.setMain +import org.siloserver.silo.network.SiloJson +import org.siloserver.silo.network.api.CatalogApi +import org.siloserver.silo.network.api.PersonalDataApi +import org.siloserver.silo.network.api.SectionApi +import org.siloserver.silo.repository.CatalogRepository +import org.siloserver.silo.repository.PersonalDataRepository +import org.siloserver.silo.repository.SectionRepository +import kotlin.test.Test +import kotlin.test.assertEquals + +@OptIn(ExperimentalCoroutinesApi::class) +class LibrariesViewModelTest { + @Test + fun recommendedResponseFromPreviousLibraryCannotReplaceCurrentLibraryRows() = runTest { + val fixture = DeferredLibrariesFixture( + deferredKeys = setOf("sections:1", "sections:2"), + ) + Dispatchers.setMain(UnconfinedTestDispatcher(testScheduler)) + val viewModel = fixture.viewModel() + val store = ViewModelStore().also { it.put("libraries", viewModel) } + try { + fixture.awaitRequest("sections:1") + val staleRequest = viewModel.onlyActiveRequest() + + viewModel.selectLibrary(2) + fixture.awaitRequest("sections:2") + fixture.complete("sections:2", sectionsBody("current")) + viewModel.uiState.first { it.sections.map { section -> section.id } == listOf("current") } + + fixture.complete("sections:1", sectionsBody("stale")) + staleRequest.join() + + assertEquals(2, viewModel.uiState.value.selectedLibraryId) + assertEquals(listOf("current"), viewModel.uiState.value.sections.map { it.id }) + } finally { + store.clear() + Dispatchers.resetMain() + fixture.close() + } + } + + @Test + fun browseResponseFromPreviousSortCannotReplaceCurrentQueryGrid() = runTest { + val fixture = DeferredLibrariesFixture( + deferredKeys = setOf( + "catalog:1:added_at:desc", + "catalog:1:title:asc", + ), + ) + Dispatchers.setMain(UnconfinedTestDispatcher(testScheduler)) + val viewModel = fixture.viewModel() + val store = ViewModelStore().also { it.put("libraries", viewModel) } + try { + fixture.awaitRequest("sections:1") + viewModel.uiState.first { !it.isLoadingSections } + viewModel.selectTab(LibrariesSubtab.Browse) + fixture.awaitRequest("catalog:1:added_at:desc") + val staleRequest = viewModel.onlyActiveRequest() + + viewModel.selectBrowseSort(LibraryBrowseSort.Title) + fixture.awaitRequest("catalog:1:title:asc") + fixture.complete("catalog:1:title:asc", catalogBody("current")) + viewModel.uiState.first { + it.catalogItems.map { item -> item.contentId } == listOf("current") + } + + fixture.complete("catalog:1:added_at:desc", catalogBody("stale")) + staleRequest.join() + + assertEquals(LibraryBrowseSort.Title, viewModel.uiState.value.browseSort) + assertEquals(listOf("current"), viewModel.uiState.value.catalogItems.map { it.contentId }) + } finally { + store.clear() + Dispatchers.resetMain() + fixture.close() + } + } + + @Test + fun collectionsResponseFromPreviousLibraryCannotReplaceCurrentLibraryCollections() = runTest { + val fixture = DeferredLibrariesFixture( + deferredKeys = setOf("collections:1", "collections:2"), + ) + Dispatchers.setMain(UnconfinedTestDispatcher(testScheduler)) + val viewModel = fixture.viewModel() + val store = ViewModelStore().also { it.put("libraries", viewModel) } + try { + fixture.awaitRequest("sections:1") + viewModel.uiState.first { !it.isLoadingSections } + viewModel.selectTab(LibrariesSubtab.Collections) + fixture.awaitRequest("collections:1") + val staleRequest = viewModel.onlyActiveRequest() + + viewModel.selectLibrary(2) + fixture.awaitRequest("collections:2") + fixture.complete("collections:2", collectionsBody("current")) + viewModel.uiState.first { + it.collections.map { collection -> collection.id } == listOf("current") + } + + fixture.complete("collections:1", collectionsBody("stale")) + staleRequest.join() + + assertEquals(2, viewModel.uiState.value.selectedLibraryId) + assertEquals(listOf("current"), viewModel.uiState.value.collections.map { it.id }) + } finally { + store.clear() + Dispatchers.resetMain() + fixture.close() + } + } + + private fun LibrariesViewModel.onlyActiveRequest(): Job = + viewModelScope.coroutineContext[Job] + ?.children + ?.single { it.isActive } + ?: error("Expected exactly one active Libraries request") + + private class DeferredLibrariesFixture( + private val deferredKeys: Set, + ) { + private val requests = Channel(Channel.UNLIMITED) + private val responses = deferredKeys.associateWith { CompletableDeferred() } + private val client = HttpClient( + MockEngine { request -> + val key = when (request.url.encodedPath) { + "/api/v1/user/libraries" -> "libraries" + "/api/v1/catalog/filters" -> "filters" + "/api/v1/catalog" -> { + "catalog:${request.url.parameters["library_id"]}:" + + "${request.url.parameters["sort"]}:${request.url.parameters["order"]}" + } + else -> { + val segments = request.url.encodedPath.split('/') + val family = segments.last() + "$family:${segments[4]}" + } + } + requests.send(key) + val body = responses[key]?.await() ?: immediateBody(key) + respondJson(body) + }, + ) { + install(ContentNegotiation) { json(SiloJson) } + } + + fun viewModel() = LibrariesViewModel( + personalDataRepository = PersonalDataRepository(PersonalDataApi(client)), + sectionRepository = SectionRepository(SectionApi(client)), + catalogRepository = CatalogRepository(CatalogApi(client)), + ) + + suspend fun awaitRequest(expected: String) { + while (requests.receive() != expected) { + // Ignore setup requests and wait for the exact request under test. + } + } + + fun complete(key: String, body: String) { + checkNotNull(responses[key]) { "No deferred response for $key" }.complete(body) + } + + fun close() { + client.close() + } + + private fun immediateBody(key: String): String = when { + key == "libraries" -> """ + [ + {"id":1,"name":"First","type":"movies","sort_order":0}, + {"id":2,"name":"Second","type":"movies","sort_order":1} + ] + """.trimIndent() + key == "filters" -> + """{"genres":[],"studios":[],"networks":[],"countries":[],"content_ratings":[]}""" + key.startsWith("sections:") -> """{"sections":[]}""" + key.startsWith("collections:") -> """{"collections":[]}""" + key.startsWith("catalog:") -> catalogBody("immediate") + else -> error("Unexpected request key $key") + } + + private fun MockRequestHandleScope.respondJson(body: String) = respond( + content = body, + status = HttpStatusCode.OK, + headers = headersOf(HttpHeaders.ContentType, "application/json"), + ) + } + + companion object { + private fun sectionsBody(id: String) = """ + { + "sections":[{ + "id":"$id", + "section_type":"recently_added", + "title":"$id", + "items":[{"content_id":"$id-item","type":"movie","title":"$id"}] + }] + } + """.trimIndent() + + private fun catalogBody(id: String) = """ + { + "total":1, + "has_more":false, + "items":[{"content_id":"$id","type":"movie","title":"$id"}] + } + """.trimIndent() + + private fun collectionsBody(id: String) = + """{"collections":[{"id":"$id","name":"$id"}]}""" + } +} diff --git a/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibraryChromeInsetSourceTest.kt b/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibraryChromeInsetSourceTest.kt index 17c9d6fee6..8417e7cc58 100644 --- a/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibraryChromeInsetSourceTest.kt +++ b/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibraryChromeInsetSourceTest.kt @@ -18,6 +18,9 @@ class LibraryChromeInsetSourceTest { private val carousel = source( "org/siloserver/silo/android/ui/screens/home/FeaturedCarousel.kt", ) + private val catalogGrid = source( + "org/siloserver/silo/android/ui/screens/browse/CatalogGrid.kt", + ) @Test fun sharedChromeOwnsReservedSpaceBeforeEveryLibraryTab() { @@ -36,4 +39,12 @@ class LibraryChromeInsetSourceTest { assertFalse(carousel.contains("WindowInsets.statusBars")) assertTrue(carousel.contains("topInset: androidx.compose.ui.unit.Dp = 16.dp")) } + + @Test + fun browseCatalogAndAlphabetRailReserveMeasuredBottomChromeInset() { + assertTrue(libraries.contains("bottomContentInset = LocalBottomChromeInset.current")) + assertTrue(catalogGrid.contains("bottomContentInset: Dp = 0.dp")) + assertTrue(catalogGrid.contains("bottom = 8.dp + bottomContentInset")) + assertTrue(catalogGrid.contains(".padding(bottom = bottomContentInset)")) + } } From 1fbcda4835726fe8b96313a7288e158bc2b1a384 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 09:03:49 +0200 Subject: [PATCH 36/65] fix(shared): propagate cache write ownership --- .../repository/RoomCatalogCacheRepository.kt | 60 +++++++++++++--- .../RoomCatalogCacheRepositoryTest.kt | 24 +++++++ .../siloserver/silo/di/RepositoryModule.kt | 9 ++- .../silo/repository/CatalogRepository.kt | 13 ++-- .../silo/repository/PersonalDataRepository.kt | 10 ++- .../silo/repository/SectionRepository.kt | 4 +- .../silo/repository/port/CatalogCachePort.kt | 45 ++++++++++++ .../CatalogRepositoryDetailCacheTest.kt | 48 ++++++++++++- .../PersonalDataRepositoryCacheTest.kt | 68 +++++++++++++++++++ 9 files changed, 262 insertions(+), 19 deletions(-) create mode 100644 shared/src/commonTest/kotlin/org/siloserver/silo/repository/PersonalDataRepositoryCacheTest.kt diff --git a/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/repository/RoomCatalogCacheRepository.kt b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/repository/RoomCatalogCacheRepository.kt index 6a1a394dc3..1f75ad10ea 100644 --- a/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/repository/RoomCatalogCacheRepository.kt +++ b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/repository/RoomCatalogCacheRepository.kt @@ -12,6 +12,7 @@ import org.siloserver.silo.network.AuthScopeSnapshot import org.siloserver.silo.network.DefaultIdentityTransitionBarrier import org.siloserver.silo.network.IdentityTransitionBarrier import org.siloserver.silo.repository.port.CatalogCachePort +import org.siloserver.silo.repository.port.CatalogCacheWriteLease import kotlinx.serialization.json.Json /** @@ -31,46 +32,84 @@ class RoomCatalogCacheRepository( private val json = Json { ignoreUnknownKeys = true } override suspend fun cacheLibraries(libraries: List) = - put(KEY_LIBRARIES, json.encodeToString(libraries)) + cacheLibraries(libraries, currentWriteLease()) + + override suspend fun cacheLibraries(libraries: List, lease: CatalogCacheWriteLease) = + put(KEY_LIBRARIES, json.encodeToString(libraries), lease) override suspend fun getCachedLibraries(): List? = get(KEY_LIBRARIES)?.let { runCatching { json.decodeFromString>(it) }.getOrNull() } override suspend fun cacheDefaultLibraryPage(libraryId: Int, response: CatalogResponse) = - put(libraryKey(libraryId), json.encodeToString(response)) + cacheDefaultLibraryPage(libraryId, response, currentWriteLease()) + + override suspend fun cacheDefaultLibraryPage( + libraryId: Int, + response: CatalogResponse, + lease: CatalogCacheWriteLease, + ) = put(libraryKey(libraryId), json.encodeToString(response), lease) override suspend fun getCachedDefaultLibraryPage(libraryId: Int): CatalogResponse? = get(libraryKey(libraryId))?.let { runCatching { json.decodeFromString(it) }.getOrNull() } override suspend fun cacheLibrarySections(libraryId: Int, sections: List) = - put(librarySectionsKey(libraryId), json.encodeToString(sections)) + cacheLibrarySections(libraryId, sections, currentWriteLease()) + + override suspend fun cacheLibrarySections( + libraryId: Int, + sections: List, + lease: CatalogCacheWriteLease, + ) = put(librarySectionsKey(libraryId), json.encodeToString(sections), lease) override suspend fun getCachedLibrarySections(libraryId: Int): List? = get(librarySectionsKey(libraryId))?.let { runCatching { json.decodeFromString>(it) }.getOrNull() } override suspend fun cacheItemDetail(contentId: String, detail: ItemDetail) = - put(itemDetailKey(contentId), json.encodeToString(detail)) + cacheItemDetail(contentId, detail, currentWriteLease()) + + override suspend fun cacheItemDetail( + contentId: String, + detail: ItemDetail, + lease: CatalogCacheWriteLease, + ) = put(itemDetailKey(contentId), json.encodeToString(detail), lease) override suspend fun getCachedItemDetail(contentId: String): ItemDetail? = get(itemDetailKey(contentId))?.let { runCatching { json.decodeFromString(it) }.getOrNull() } override suspend fun cacheSeasons(seriesId: String, response: SeasonsResponse) = - put(seasonsKey(seriesId), json.encodeToString(response)) + cacheSeasons(seriesId, response, currentWriteLease()) + + override suspend fun cacheSeasons( + seriesId: String, + response: SeasonsResponse, + lease: CatalogCacheWriteLease, + ) = put(seasonsKey(seriesId), json.encodeToString(response), lease) override suspend fun getCachedSeasons(seriesId: String): SeasonsResponse? = get(seasonsKey(seriesId))?.let { runCatching { json.decodeFromString(it) }.getOrNull() } override suspend fun cacheEpisodes(seriesId: String, seasonNumber: Int, response: EpisodesResponse) = - put(episodesKey(seriesId, seasonNumber), json.encodeToString(response)) + cacheEpisodes(seriesId, seasonNumber, response, currentWriteLease()) + + override suspend fun cacheEpisodes( + seriesId: String, + seasonNumber: Int, + response: EpisodesResponse, + lease: CatalogCacheWriteLease, + ) = put(episodesKey(seriesId, seasonNumber), json.encodeToString(response), lease) override suspend fun getCachedEpisodes(seriesId: String, seasonNumber: Int): EpisodesResponse? = get(episodesKey(seriesId, seasonNumber))?.let { runCatching { json.decodeFromString(it) }.getOrNull() } - private suspend fun put(cacheKey: String, jsonStr: String) { - val requestIdentityGeneration = identityTransitions.generation.value + private suspend fun put( + cacheKey: String, + jsonStr: String, + lease: CatalogCacheWriteLease, + ) { + if (lease.identityGeneration != identityTransitions.generation.value) return val snapshot = snapshotProvider() ?: return val profileId = snapshot.profileId ?: return - if (requestIdentityGeneration != identityTransitions.generation.value) return + if (lease.identityGeneration != identityTransitions.generation.value) return // A Room row must fit SQLite's ~2MB CursorWindow or the *read* throws // SQLiteBlobTooBigException. Big library pages can exceed it, so don't // store an unreadable row — drop any prior row for this key and skip. @@ -89,6 +128,9 @@ class RoomCatalogCacheRepository( ) } + private fun currentWriteLease() = + CatalogCacheWriteLease(identityTransitions.generation.value) + private suspend fun get(cacheKey: String): String? { val snapshot = snapshotProvider() ?: return null val profileId = snapshot.profileId ?: return null diff --git a/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/data/repository/RoomCatalogCacheRepositoryTest.kt b/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/data/repository/RoomCatalogCacheRepositoryTest.kt index dde4cc1f4a..21b5c2857e 100644 --- a/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/data/repository/RoomCatalogCacheRepositoryTest.kt +++ b/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/data/repository/RoomCatalogCacheRepositoryTest.kt @@ -9,6 +9,7 @@ import org.siloserver.silo.model.personal.UserLibrary import org.siloserver.silo.network.AuthScopeSnapshot import org.siloserver.silo.network.DefaultIdentityTransitionBarrier import org.siloserver.silo.network.IdentityTransitionKind +import org.siloserver.silo.repository.port.CatalogCacheWriteLease import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.async import kotlinx.coroutines.test.runTest @@ -102,4 +103,27 @@ class RoomCatalogCacheRepositoryTest { assertNull(delayedRepo.getCachedLibraries()) } + + @Test + fun writeRequestedByOldProfileButInvokedAfterSwitchIsNotAttributedToNewProfile() = runTest { + val identityTransitions = DefaultIdentityTransitionBarrier() + val oldProfileGeneration = identityTransitions.generation.value + val guardedRepo = RoomCatalogCacheRepository( + db = db, + snapshotProvider = { scope }, + identityTransitions = identityTransitions, + now = { 1000L }, + ) + identityTransitions.changing(IdentityTransitionKind.PROFILE_SWITCH) { + scope = AuthScopeSnapshot("s1", "p2", "https://s1.example", null) + } + + guardedRepo.cacheLibraries( + listOf(UserLibrary(id = 1, name = "Profile A", type = "movie")), + CatalogCacheWriteLease(oldProfileGeneration), + ) + + assertEquals(0L, oldProfileGeneration) + assertNull(guardedRepo.getCachedLibraries()) + } } diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/di/RepositoryModule.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/di/RepositoryModule.kt index 1577bdcea4..a0eceadc19 100644 --- a/shared/src/commonMain/kotlin/org/siloserver/silo/di/RepositoryModule.kt +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/di/RepositoryModule.kt @@ -64,9 +64,12 @@ val repositoryModule = module { // back to the network-only no-op ports in commonMain tests / when unbound. single { PersonalDataRepository( - get(), - getOrNull() ?: org.siloserver.silo.repository.port.NoOpUserItemStatePort, - getOrNull() ?: org.siloserver.silo.repository.port.NoOpCatalogCachePort, + personalDataApi = get(), + userItemStatePort = getOrNull() + ?: org.siloserver.silo.repository.port.NoOpUserItemStatePort, + catalogCache = getOrNull() + ?: org.siloserver.silo.repository.port.NoOpCatalogCachePort, + identityTransitions = get(), ) } single { ProfileRepository(get(), get(), getOrNull(), get(), get(), get()) } diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/repository/CatalogRepository.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/repository/CatalogRepository.kt index ef2377ab0a..5208f948cf 100644 --- a/shared/src/commonMain/kotlin/org/siloserver/silo/repository/CatalogRepository.kt +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/repository/CatalogRepository.kt @@ -15,6 +15,7 @@ import org.siloserver.silo.network.DefaultIdentityTransitionBarrier import org.siloserver.silo.network.IdentityTransitionBarrier import org.siloserver.silo.network.api.CatalogApi import org.siloserver.silo.repository.port.CatalogCachePort +import org.siloserver.silo.repository.port.CatalogCacheWriteLease import org.siloserver.silo.repository.port.NoOpCatalogCachePort import org.siloserver.silo.repository.port.canServeCache @@ -44,6 +45,7 @@ class CatalogRepository( match: String? = null, ): ApiResult { val requestIdentityGeneration = identityTransitions.generation.value + val cacheWriteLease = CatalogCacheWriteLease(requestIdentityGeneration) val result = catalogApi.getCatalog( source = source, query = query, @@ -76,7 +78,7 @@ class CatalogRepository( if (result is ApiResult.Success) { if (requestIdentityGeneration == identityTransitions.generation.value) { - catalogCache.cacheDefaultLibraryPage(cacheableLibraryId, result.data) + catalogCache.cacheDefaultLibraryPage(cacheableLibraryId, result.data, cacheWriteLease) } return result } @@ -116,10 +118,11 @@ class CatalogRepository( /** Fetches full metadata for a single catalog item (offline: last cached detail). */ suspend fun getItemDetail(contentId: String): ApiResult { val requestIdentityGeneration = identityTransitions.generation.value + val cacheWriteLease = CatalogCacheWriteLease(requestIdentityGeneration) val result = catalogApi.getItemDetail(contentId) if (result is ApiResult.Success) { if (requestIdentityGeneration == identityTransitions.generation.value) { - catalogCache.cacheItemDetail(contentId, result.data) + catalogCache.cacheItemDetail(contentId, result.data, cacheWriteLease) } return result } @@ -149,10 +152,11 @@ class CatalogRepository( /** Lists seasons for a series (offline: last cached seasons). */ suspend fun getSeasons(seriesId: String): ApiResult { val requestIdentityGeneration = identityTransitions.generation.value + val cacheWriteLease = CatalogCacheWriteLease(requestIdentityGeneration) val result = catalogApi.getSeasons(seriesId) if (result is ApiResult.Success) { if (requestIdentityGeneration == identityTransitions.generation.value) { - catalogCache.cacheSeasons(seriesId, result.data) + catalogCache.cacheSeasons(seriesId, result.data, cacheWriteLease) } return result } @@ -165,10 +169,11 @@ class CatalogRepository( /** Lists episodes for a specific season of a series (offline: last cached episodes). */ suspend fun getEpisodes(seriesId: String, seasonNumber: Int): ApiResult { val requestIdentityGeneration = identityTransitions.generation.value + val cacheWriteLease = CatalogCacheWriteLease(requestIdentityGeneration) val result = catalogApi.getEpisodes(seriesId, seasonNumber) if (result is ApiResult.Success) { if (requestIdentityGeneration == identityTransitions.generation.value) { - catalogCache.cacheEpisodes(seriesId, seasonNumber, result.data) + catalogCache.cacheEpisodes(seriesId, seasonNumber, result.data, cacheWriteLease) } return result } diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/repository/PersonalDataRepository.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/repository/PersonalDataRepository.kt index 861e3d6fd8..43f3ac262f 100644 --- a/shared/src/commonMain/kotlin/org/siloserver/silo/repository/PersonalDataRepository.kt +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/repository/PersonalDataRepository.kt @@ -7,9 +7,12 @@ import org.siloserver.silo.model.personal.SyncProgressItem import org.siloserver.silo.model.personal.SyncProgressRequest import org.siloserver.silo.model.personal.UserLibrary import org.siloserver.silo.network.ApiResult +import org.siloserver.silo.network.DefaultIdentityTransitionBarrier +import org.siloserver.silo.network.IdentityTransitionBarrier import org.siloserver.silo.network.api.PersonalDataApi import org.siloserver.silo.network.map import org.siloserver.silo.repository.port.CatalogCachePort +import org.siloserver.silo.repository.port.CatalogCacheWriteLease import org.siloserver.silo.repository.port.NoOpCatalogCachePort import org.siloserver.silo.repository.port.NoOpUserItemStatePort import org.siloserver.silo.repository.port.UserItemStatePort @@ -27,14 +30,19 @@ open class PersonalDataRepository( private val userItemStatePort: UserItemStatePort = NoOpUserItemStatePort, /** Offline read cache for the library list (Track B). No-op by default. */ private val catalogCache: CatalogCachePort = NoOpCatalogCachePort, + private val identityTransitions: IdentityTransitionBarrier = DefaultIdentityTransitionBarrier(), ) { // -- Libraries -- /** Lists the libraries visible to the current user (offline: last cached list). */ suspend fun listUserLibraries(): ApiResult> { + val requestIdentityGeneration = identityTransitions.generation.value + val cacheWriteLease = CatalogCacheWriteLease(requestIdentityGeneration) val result = personalDataApi.listUserLibraries() if (result is ApiResult.Success) { - catalogCache.cacheLibraries(result.data) + if (requestIdentityGeneration == identityTransitions.generation.value) { + catalogCache.cacheLibraries(result.data, cacheWriteLease) + } return result } if (result.canServeCache()) { diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/repository/SectionRepository.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/repository/SectionRepository.kt index e0372e5804..309b417ebb 100644 --- a/shared/src/commonMain/kotlin/org/siloserver/silo/repository/SectionRepository.kt +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/repository/SectionRepository.kt @@ -12,6 +12,7 @@ import org.siloserver.silo.network.IdentityTransitionBarrier import org.siloserver.silo.network.api.SectionApi import org.siloserver.silo.network.map import org.siloserver.silo.repository.port.CatalogCachePort +import org.siloserver.silo.repository.port.CatalogCacheWriteLease import org.siloserver.silo.repository.port.NoOpCatalogCachePort import org.siloserver.silo.repository.port.canServeCache import kotlinx.coroutines.CoroutineScope @@ -93,10 +94,11 @@ class SectionRepository( /** Fetches a library's resolved sections (offline: last cached sections). */ suspend fun getLibrarySections(libraryId: Int): ApiResult { val requestIdentityGeneration = identityTransitions.generation.value + val cacheWriteLease = CatalogCacheWriteLease(requestIdentityGeneration) val result = sectionApi.getLibrarySections(libraryId) if (result is ApiResult.Success) { if (requestIdentityGeneration == identityTransitions.generation.value) { - catalogCache.cacheLibrarySections(libraryId, result.data.sections) + catalogCache.cacheLibrarySections(libraryId, result.data.sections, cacheWriteLease) } return result } diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/repository/port/CatalogCachePort.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/repository/port/CatalogCachePort.kt index 06dd8851d1..0ef74c8941 100644 --- a/shared/src/commonMain/kotlin/org/siloserver/silo/repository/port/CatalogCachePort.kt +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/repository/port/CatalogCachePort.kt @@ -8,6 +8,12 @@ import org.siloserver.silo.model.personal.UserLibrary import org.siloserver.silo.model.section.ResolvedSection import org.siloserver.silo.network.ApiResult +/** + * Ownership captured before a cacheable network request starts. Identity-scoped + * cache implementations must reject the write when this generation is stale. + */ +data class CatalogCacheWriteLease(val identityGeneration: Long) + /** * Offline read cache for catalog browse (Track B). Backs repository-level * cache-with-fallback in [org.siloserver.silo.repository.PersonalDataRepository] @@ -22,24 +28,63 @@ import org.siloserver.silo.network.ApiResult */ interface CatalogCachePort { suspend fun cacheLibraries(libraries: List) {} + suspend fun cacheLibraries(libraries: List, lease: CatalogCacheWriteLease) { + cacheLibraries(libraries) + } suspend fun getCachedLibraries(): List? = null /** Cache the default (unfiltered, first-page) browse for a library. */ suspend fun cacheDefaultLibraryPage(libraryId: Int, response: CatalogResponse) {} + suspend fun cacheDefaultLibraryPage( + libraryId: Int, + response: CatalogResponse, + lease: CatalogCacheWriteLease, + ) { + cacheDefaultLibraryPage(libraryId, response) + } suspend fun getCachedDefaultLibraryPage(libraryId: Int): CatalogResponse? = null /** Cache a library's resolved "Recommended" sections (for the offline landing tab). */ suspend fun cacheLibrarySections(libraryId: Int, sections: List) {} + suspend fun cacheLibrarySections( + libraryId: Int, + sections: List, + lease: CatalogCacheWriteLease, + ) { + cacheLibrarySections(libraryId, sections) + } suspend fun getCachedLibrarySections(libraryId: Int): List? = null /** Cache an item's detail page (tap-a-title-offline). */ suspend fun cacheItemDetail(contentId: String, detail: ItemDetail) {} + suspend fun cacheItemDetail( + contentId: String, + detail: ItemDetail, + lease: CatalogCacheWriteLease, + ) { + cacheItemDetail(contentId, detail) + } suspend fun getCachedItemDetail(contentId: String): ItemDetail? = null /** Cache a series' season list + a season's episode list (offline series detail). */ suspend fun cacheSeasons(seriesId: String, response: SeasonsResponse) {} + suspend fun cacheSeasons( + seriesId: String, + response: SeasonsResponse, + lease: CatalogCacheWriteLease, + ) { + cacheSeasons(seriesId, response) + } suspend fun getCachedSeasons(seriesId: String): SeasonsResponse? = null suspend fun cacheEpisodes(seriesId: String, seasonNumber: Int, response: EpisodesResponse) {} + suspend fun cacheEpisodes( + seriesId: String, + seasonNumber: Int, + response: EpisodesResponse, + lease: CatalogCacheWriteLease, + ) { + cacheEpisodes(seriesId, seasonNumber, response) + } suspend fun getCachedEpisodes(seriesId: String, seasonNumber: Int): EpisodesResponse? = null } diff --git a/shared/src/commonTest/kotlin/org/siloserver/silo/repository/CatalogRepositoryDetailCacheTest.kt b/shared/src/commonTest/kotlin/org/siloserver/silo/repository/CatalogRepositoryDetailCacheTest.kt index 75c3d94355..32db5b2e15 100644 --- a/shared/src/commonTest/kotlin/org/siloserver/silo/repository/CatalogRepositoryDetailCacheTest.kt +++ b/shared/src/commonTest/kotlin/org/siloserver/silo/repository/CatalogRepositoryDetailCacheTest.kt @@ -5,9 +5,11 @@ import org.siloserver.silo.model.catalog.SeasonsResponse import org.siloserver.silo.network.ApiResult import org.siloserver.silo.network.DefaultIdentityTransitionBarrier import org.siloserver.silo.network.IdentityTransitionKind +import org.siloserver.silo.network.IdentityTransitionBarrier import org.siloserver.silo.network.SiloJson import org.siloserver.silo.network.api.CatalogApi import org.siloserver.silo.repository.port.CatalogCachePort +import org.siloserver.silo.repository.port.CatalogCacheWriteLease import io.ktor.client.HttpClient import io.ktor.client.engine.mock.MockEngine import io.ktor.client.engine.mock.respond @@ -29,9 +31,23 @@ class CatalogRepositoryDetailCacheTest { private class FakeCache( val preset: ItemDetail? = null, val seasonsPreset: SeasonsResponse? = null, + val identityTransitions: IdentityTransitionBarrier? = null, + val beforeItemCache: suspend () -> Unit = {}, ) : CatalogCachePort { var cachedId: String? = null - override suspend fun cacheItemDetail(contentId: String, detail: ItemDetail) { cachedId = contentId } + override suspend fun cacheItemDetail( + contentId: String, + detail: ItemDetail, + lease: CatalogCacheWriteLease, + ) { + beforeItemCache() + if ( + identityTransitions == null || + lease.identityGeneration == identityTransitions.generation.value + ) { + cachedId = contentId + } + } override suspend fun getCachedItemDetail(contentId: String): ItemDetail? = preset override suspend fun getCachedSeasons(seriesId: String): SeasonsResponse? = seasonsPreset } @@ -141,4 +157,34 @@ class CatalogRepositoryDetailCacheTest { assertTrue(oldProfileRequest.await() is ApiResult.Success) assertEquals(null, cache.cachedId) } + + @Test + fun profileSwitchBetweenRepositoryGuardAndCacheWriteDoesNotCacheOldDetail() = runTest { + val identityTransitions = DefaultIdentityTransitionBarrier() + val cache = FakeCache( + identityTransitions = identityTransitions, + beforeItemCache = { + identityTransitions.changing(IdentityTransitionKind.PROFILE_SWITCH) { } + }, + ) + val client = HttpClient( + MockEngine { + respond( + """{"content_id":"c1","type":"movie","title":"Profile A"}""", + HttpStatusCode.OK, + headersOf(HttpHeaders.ContentType, "application/json"), + ) + }, + ) { + install(ContentNegotiation) { json(SiloJson) } + } + val repository = CatalogRepository( + catalogApi = CatalogApi(client), + catalogCache = cache, + identityTransitions = identityTransitions, + ) + + assertTrue(repository.getItemDetail("c1") is ApiResult.Success) + assertEquals(null, cache.cachedId) + } } diff --git a/shared/src/commonTest/kotlin/org/siloserver/silo/repository/PersonalDataRepositoryCacheTest.kt b/shared/src/commonTest/kotlin/org/siloserver/silo/repository/PersonalDataRepositoryCacheTest.kt new file mode 100644 index 0000000000..df8d74438d --- /dev/null +++ b/shared/src/commonTest/kotlin/org/siloserver/silo/repository/PersonalDataRepositoryCacheTest.kt @@ -0,0 +1,68 @@ +package org.siloserver.silo.repository + +import io.ktor.client.HttpClient +import io.ktor.client.engine.mock.MockEngine +import io.ktor.client.engine.mock.respond +import io.ktor.client.plugins.contentnegotiation.ContentNegotiation +import io.ktor.http.HttpHeaders +import io.ktor.http.HttpStatusCode +import io.ktor.http.headersOf +import io.ktor.serialization.kotlinx.json.json +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.async +import kotlinx.coroutines.test.runTest +import org.siloserver.silo.model.personal.UserLibrary +import org.siloserver.silo.network.ApiResult +import org.siloserver.silo.network.DefaultIdentityTransitionBarrier +import org.siloserver.silo.network.IdentityTransitionKind +import org.siloserver.silo.network.SiloJson +import org.siloserver.silo.network.api.PersonalDataApi +import org.siloserver.silo.repository.port.CatalogCachePort +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +class PersonalDataRepositoryCacheTest { + + private class FakeCache : CatalogCachePort { + var cachedLibraries: List? = null + + override suspend fun cacheLibraries(libraries: List) { + cachedLibraries = libraries + } + } + + @Test + fun librariesResponseStartedBeforeProfileSwitchIsNotCachedForNewProfile() = runTest { + val requestEntered = CompletableDeferred() + val releaseResponse = CompletableDeferred() + val client = HttpClient( + MockEngine { + requestEntered.complete(Unit) + releaseResponse.await() + respond( + """[{"id":1,"name":"Profile A","type":"movie"}]""", + HttpStatusCode.OK, + headersOf(HttpHeaders.ContentType, "application/json"), + ) + }, + ) { + install(ContentNegotiation) { json(SiloJson) } + } + val cache = FakeCache() + val identityTransitions = DefaultIdentityTransitionBarrier() + val repository = PersonalDataRepository( + personalDataApi = PersonalDataApi(client), + catalogCache = cache, + identityTransitions = identityTransitions, + ) + + val oldProfileRequest = async { repository.listUserLibraries() } + requestEntered.await() + identityTransitions.changing(IdentityTransitionKind.PROFILE_SWITCH) { } + releaseResponse.complete(Unit) + + assertTrue(oldProfileRequest.await() is ApiResult.Success) + assertEquals(null, cache.cachedLibraries) + } +} From 18fba487a9a6e53c88f53e471e12a9be771f75c6 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 09:06:30 +0200 Subject: [PATCH 37/65] fix(android): keep browse filters query scoped --- .../ui/screens/libraries/LibrariesScreen.kt | 18 ++- .../libraries/LibrariesViewModelTest.kt | 116 +++++++++++++++++- 2 files changed, 131 insertions(+), 3 deletions(-) diff --git a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibrariesScreen.kt b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibrariesScreen.kt index ce3f05ebbc..d198f3756e 100644 --- a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibrariesScreen.kt +++ b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibrariesScreen.kt @@ -196,6 +196,7 @@ class LibrariesViewModel( private var collectionsLoadedLibraryId: Int? = null private var recommendedRequestGeneration = 0L private var catalogRequestGeneration = 0L + private var catalogQueryGeneration = 0L private var collectionsRequestGeneration = 0L private val pageSize = 42 @@ -478,6 +479,8 @@ class LibrariesViewModel( filterState = requestState.filterState, ) val requestGeneration = ++catalogRequestGeneration + val queryGeneration = + if (reset) ++catalogQueryGeneration else catalogQueryGeneration val offset = if (reset) 0 else requestState.catalogItems.size viewModelScope.launch { if (!isCatalogRequestCurrent(requestGeneration, requestIdentity)) return@launch @@ -489,11 +492,11 @@ class LibrariesViewModel( // response so the filter sheet has every facet, not just genres. when (val filters = catalogRepository.getFilters(libraryId, includeTechnical = true)) { is ApiResult.Success -> { - if (!isCatalogRequestCurrent(requestGeneration, requestIdentity)) { + if (!isCatalogQueryCurrent(queryGeneration, requestIdentity)) { return@launch } _uiState.update { - if (isCatalogRequestCurrent(requestGeneration, requestIdentity, it)) { + if (isCatalogQueryCurrent(queryGeneration, requestIdentity, it)) { it.copy(availableFilters = filters.data) } else { it @@ -693,6 +696,17 @@ class LibrariesViewModel( state.selectedNamePrefix == identity.selectedNamePrefix && state.filterState == identity.filterState + private fun isCatalogQueryCurrent( + generation: Long, + identity: CatalogRequestIdentity, + state: LibrariesUiState = _uiState.value, + ): Boolean = + generation == catalogQueryGeneration && + state.selectedLibraryId == identity.libraryId && + state.browseSort == identity.browseSort && + state.selectedNamePrefix == identity.selectedNamePrefix && + state.filterState == identity.filterState + private fun isCollectionsRequestCurrent( generation: Long, libraryId: Int, diff --git a/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibrariesViewModelTest.kt b/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibrariesViewModelTest.kt index 28c8632d5f..734bffaa96 100644 --- a/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibrariesViewModelTest.kt +++ b/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibrariesViewModelTest.kt @@ -21,6 +21,8 @@ import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.runTest import kotlinx.coroutines.test.setMain +import org.siloserver.silo.catalog.filter.CatalogFacet +import org.siloserver.silo.catalog.filter.CatalogFilterState import org.siloserver.silo.network.SiloJson import org.siloserver.silo.network.api.CatalogApi import org.siloserver.silo.network.api.PersonalDataApi @@ -99,6 +101,93 @@ class LibrariesViewModelTest { } } + @Test + fun browseResponseFromPreviousFilterStateCannotReplaceCurrentQueryGrid() = runTest { + val fixture = DeferredLibrariesFixture( + deferredKeys = setOf( + "catalog:1:added_at:desc", + "catalog:1:added_at:desc:filtered", + ), + ) + Dispatchers.setMain(UnconfinedTestDispatcher(testScheduler)) + val viewModel = fixture.viewModel() + val store = ViewModelStore().also { it.put("libraries", viewModel) } + try { + fixture.awaitRequest("sections:1") + viewModel.uiState.first { !it.isLoadingSections } + viewModel.selectTab(LibrariesSubtab.Browse) + fixture.awaitRequest("catalog:1:added_at:desc") + val staleRequest = viewModel.onlyActiveRequest() + + val dramaOnly = CatalogFilterState( + selections = mapOf(CatalogFacet.Genre to setOf("Drama")), + ) + viewModel.applyFilterState(dramaOnly) + fixture.awaitRequest("catalog:1:added_at:desc:filtered") + fixture.complete( + "catalog:1:added_at:desc:filtered", + catalogBody("current-filter"), + ) + viewModel.uiState.first { + it.catalogItems.map { item -> item.contentId } == listOf("current-filter") + } + + fixture.complete("catalog:1:added_at:desc", catalogBody("stale-unfiltered")) + staleRequest.join() + + assertEquals(dramaOnly, viewModel.uiState.value.filterState) + assertEquals( + listOf("current-filter"), + viewModel.uiState.value.catalogItems.map { it.contentId }, + ) + } finally { + store.clear() + Dispatchers.resetMain() + fixture.close() + } + } + + @Test + fun delayedFilterVocabularyStillAppliesAfterLoadingNextPage() = runTest { + val firstPageKey = "catalog:1:added_at:desc:0" + val secondPageKey = "catalog:1:added_at:desc:1" + val fixture = DeferredLibrariesFixture( + deferredKeys = setOf("filters", firstPageKey, secondPageKey), + ) + Dispatchers.setMain(UnconfinedTestDispatcher(testScheduler)) + val viewModel = fixture.viewModel() + val store = ViewModelStore().also { it.put("libraries", viewModel) } + try { + fixture.awaitRequest("sections:1") + viewModel.uiState.first { !it.isLoadingSections } + viewModel.selectTab(LibrariesSubtab.Browse) + fixture.awaitRequest("filters") + fixture.awaitRequest(firstPageKey) + val filterRequest = viewModel.onlyActiveRequest() + fixture.complete(firstPageKey, catalogPageBody("page-1", hasMore = true)) + viewModel.uiState.first { + it.catalogItems.map { item -> item.contentId } == listOf("page-1") && + it.catalogHasMore + } + + viewModel.loadMoreCatalog() + fixture.awaitRequest(secondPageKey) + fixture.complete(secondPageKey, catalogPageBody("page-2", hasMore = false)) + viewModel.uiState.first { + it.catalogItems.map { item -> item.contentId } == listOf("page-1", "page-2") + } + + fixture.complete("filters", filtersBody("Drama")) + filterRequest.join() + + assertEquals(listOf("Drama"), viewModel.uiState.value.availableFilters?.genres) + } finally { + store.clear() + Dispatchers.resetMain() + fixture.close() + } + } + @Test fun collectionsResponseFromPreviousLibraryCannotReplaceCurrentLibraryCollections() = runTest { val fixture = DeferredLibrariesFixture( @@ -150,8 +239,22 @@ class LibrariesViewModelTest { "/api/v1/user/libraries" -> "libraries" "/api/v1/catalog/filters" -> "filters" "/api/v1/catalog" -> { - "catalog:${request.url.parameters["library_id"]}:" + + val baseKey = "catalog:${request.url.parameters["library_id"]}:" + "${request.url.parameters["sort"]}:${request.url.parameters["order"]}" + val filterSuffix = if ( + request.url.parameters.names().any { it.startsWith("groups[") } + ) { + ":filtered" + } else { + "" + } + val offsetSuffix = ":${request.url.parameters["offset"]}" + listOf( + baseKey + filterSuffix + offsetSuffix, + baseKey + filterSuffix, + baseKey + offsetSuffix, + baseKey, + ).firstOrNull(responses::containsKey) ?: (baseKey + filterSuffix) } else -> { val segments = request.url.encodedPath.split('/') @@ -229,6 +332,17 @@ class LibrariesViewModelTest { } """.trimIndent() + private fun catalogPageBody(id: String, hasMore: Boolean) = """ + { + "total":2, + "has_more":$hasMore, + "items":[{"content_id":"$id","type":"movie","title":"$id"}] + } + """.trimIndent() + + private fun filtersBody(genre: String) = + """{"genres":["$genre"],"studios":[],"networks":[],"countries":[],"content_ratings":[]}""" + private fun collectionsBody(id: String) = """{"collections":[{"id":"$id","name":"$id"}]}""" } From 1ae0e46a2206e64c8f6a903c3b4105f83ea9ece6 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 09:14:23 +0200 Subject: [PATCH 38/65] docs(android): extend cache ownership plan to home --- .../plans/2026-07-28-android-release-audit-fixes.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/docs/superpowers/plans/2026-07-28-android-release-audit-fixes.md b/docs/superpowers/plans/2026-07-28-android-release-audit-fixes.md index efbf80f826..bb39906d55 100644 --- a/docs/superpowers/plans/2026-07-28-android-release-audit-fixes.md +++ b/docs/superpowers/plans/2026-07-28-android-release-audit-fixes.md @@ -142,6 +142,15 @@ git commit -m "fix(shared): keep cache writes identity scoped" - Consumes: both reviewed fix commits. - Produces: one clean branch with green supply-chain, phone/TV unit, and phone/TV release gates. +- [ ] **Step 0: Preserve request-time ownership for Home cache writes** + +Add a Home-cache write lease using the shared identity generation, propagate it +from the section request through both `StartupWarmup` and `HomeViewModel`, and +make `RoomHomeCacheRepository` reject stale leases before and after resolving +the identity snapshot. First add a deterministic delayed A→B regression that +proves A's Home sections cannot be stored or read as B. Preserve existing +offline Home reads and successful same-identity warmup behavior. + - [ ] **Step 1: Review each task diff independently** Require explicit spec-compliance and code-quality approval; fix every Critical, Important, or Minor release finding before continuing. From e098749297cf6bdc9819cd2ca512f4adadd86bc1 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 09:18:31 +0200 Subject: [PATCH 39/65] fix(shared): keep home cache writes identity scoped --- .../repository/RoomHomeCacheRepository.kt | 16 +++ .../silo/common/startup/StartupWarmup.kt | 24 ++++- .../repository/RoomHomeCacheRepositoryTest.kt | 57 ++++++++++ .../siloserver/silo/android/MainActivity.kt | 3 + .../silo/android/di/AndroidModule.kt | 3 +- .../org/siloserver/silo/tv/MainTvActivity.kt | 3 + .../siloserver/silo/tv/di/AndroidTvModule.kt | 3 +- .../silo/repository/port/HomeCachePort.kt | 5 + .../silo/viewmodel/HomeViewModel.kt | 13 ++- .../HomeViewModelCacheIdentityTest.kt | 100 ++++++++++++++++++ 10 files changed, 220 insertions(+), 7 deletions(-) create mode 100644 shared/src/commonTest/kotlin/org/siloserver/silo/viewmodel/HomeViewModelCacheIdentityTest.kt diff --git a/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/repository/RoomHomeCacheRepository.kt b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/repository/RoomHomeCacheRepository.kt index d6cb172e89..1506d37268 100644 --- a/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/repository/RoomHomeCacheRepository.kt +++ b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/repository/RoomHomeCacheRepository.kt @@ -4,8 +4,11 @@ import org.siloserver.silo.common.data.db.SiloDatabase import org.siloserver.silo.common.data.db.entity.HomeCacheEntity import org.siloserver.silo.model.section.ResolvedSection import org.siloserver.silo.network.AuthScopeSnapshot +import org.siloserver.silo.network.DefaultIdentityTransitionBarrier +import org.siloserver.silo.network.IdentityTransitionBarrier import org.siloserver.silo.repository.port.HomeCachePort import org.siloserver.silo.repository.port.HomeCacheSnapshot +import org.siloserver.silo.repository.port.HomeCacheWriteLease import kotlinx.serialization.json.Json /** @@ -19,6 +22,7 @@ import kotlinx.serialization.json.Json class RoomHomeCacheRepository( db: SiloDatabase, private val snapshotProvider: suspend () -> AuthScopeSnapshot?, + private val identityTransitions: IdentityTransitionBarrier = DefaultIdentityTransitionBarrier(), private val now: () -> Long = { System.currentTimeMillis() }, ) : HomeCachePort { @@ -26,8 +30,20 @@ class RoomHomeCacheRepository( private val json = Json { ignoreUnknownKeys = true } override suspend fun cacheHome(sections: List) { + cacheHome( + sections = sections, + lease = HomeCacheWriteLease(identityTransitions.generation.value), + ) + } + + override suspend fun cacheHome( + sections: List, + lease: HomeCacheWriteLease, + ) { + if (lease.identityGeneration != identityTransitions.generation.value) return val snapshot = snapshotProvider() ?: return val profileId = snapshot.profileId ?: return + if (lease.identityGeneration != identityTransitions.generation.value) return val sectionsJson = json.encodeToString(sections) // A Room row must fit SQLite's ~2MB CursorWindow or the *read* throws // SQLiteBlobTooBigException. Large reorganized home layouts can exceed diff --git a/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/startup/StartupWarmup.kt b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/startup/StartupWarmup.kt index 21fdeda32f..fab17b620c 100644 --- a/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/startup/StartupWarmup.kt +++ b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/startup/StartupWarmup.kt @@ -7,11 +7,13 @@ import org.siloserver.silo.common.ui.components.resolveAvatarUrl import org.siloserver.silo.model.profile.Profile import org.siloserver.silo.model.section.ResolvedSection import org.siloserver.silo.network.ApiResult +import org.siloserver.silo.network.IdentityTransitionBarrier import org.siloserver.silo.repository.AuthRepository import org.siloserver.silo.repository.PersonalDataRepository import org.siloserver.silo.repository.ProfileRepository import org.siloserver.silo.repository.SectionRepository import org.siloserver.silo.repository.port.HomeCachePort +import org.siloserver.silo.repository.port.HomeCacheWriteLease import org.siloserver.silo.viewmodel.hydrateHomeSections import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.async @@ -83,6 +85,7 @@ suspend fun warmAuthenticatedStartup( personalDataRepository: PersonalDataRepository, sectionRepository: SectionRepository, homeCache: HomeCachePort, + identityTransitions: IdentityTransitionBarrier, serverUrl: String?, artworkPlan: StartupArtworkPlan, ) { @@ -106,7 +109,15 @@ suspend fun warmAuthenticatedStartup( Unit }, async { - runCatching { warmHome(context, sectionRepository, homeCache, artworkPlan) } + runCatching { + warmHome( + context, + sectionRepository, + homeCache, + identityTransitions, + artworkPlan, + ) + } Unit }, ).awaitAll() @@ -135,15 +146,22 @@ private suspend fun CoroutineScope.warmHome( context: Context, sectionRepository: SectionRepository, homeCache: HomeCachePort, + identityTransitions: IdentityTransitionBarrier, artworkPlan: StartupArtworkPlan, ) { + val requestIdentityGeneration = identityTransitions.generation.value + val cacheWriteLease = HomeCacheWriteLease(requestIdentityGeneration) when (val result = sectionRepository.getHomeSections()) { is ApiResult.Success -> { val hydration = hydrateHomeSections(result.data.sections) { sectionId -> sectionRepository.getHomeSectionItems(sectionId) } - if (hydration.fullyResolved && hydration.sections.isNotEmpty()) { - homeCache.cacheHome(hydration.sections) + if ( + hydration.fullyResolved && + hydration.sections.isNotEmpty() && + requestIdentityGeneration == identityTransitions.generation.value + ) { + homeCache.cacheHome(hydration.sections, cacheWriteLease) warmHomeArtwork(context, hydration.sections, artworkPlan) } } diff --git a/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/data/repository/RoomHomeCacheRepositoryTest.kt b/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/data/repository/RoomHomeCacheRepositoryTest.kt index d537fb1ede..3183758e43 100644 --- a/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/data/repository/RoomHomeCacheRepositoryTest.kt +++ b/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/data/repository/RoomHomeCacheRepositoryTest.kt @@ -6,6 +6,11 @@ import org.siloserver.silo.common.data.db.SiloDatabase import org.siloserver.silo.model.section.ResolvedSection import org.siloserver.silo.model.section.SectionItem import org.siloserver.silo.network.AuthScopeSnapshot +import org.siloserver.silo.network.DefaultIdentityTransitionBarrier +import org.siloserver.silo.network.IdentityTransitionKind +import org.siloserver.silo.repository.port.HomeCacheWriteLease +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.async import kotlinx.coroutines.test.runTest import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner @@ -86,4 +91,56 @@ class RoomHomeCacheRepositoryTest { scope = null assertNull(repo.getCachedHome()) } + + @Test + fun writeRequestedByOldProfileButInvokedAfterSwitchIsNotAttributedToNewProfile() = runTest { + val identityTransitions = DefaultIdentityTransitionBarrier() + val oldProfileGeneration = identityTransitions.generation.value + val guardedRepo = RoomHomeCacheRepository( + db = db, + snapshotProvider = { scope }, + identityTransitions = identityTransitions, + now = { 1000L }, + ) + identityTransitions.changing(IdentityTransitionKind.PROFILE_SWITCH) { + scope = AuthScopeSnapshot("s1", "p2", "https://s1.example", null) + } + + guardedRepo.cacheHome( + listOf(section("old", "c1")), + HomeCacheWriteLease(oldProfileGeneration), + ) + + assertEquals(0L, oldProfileGeneration) + assertNull(guardedRepo.getCachedHome()) + } + + @Test + fun profileSwitchDuringHomeScopeResolutionDoesNotAttributeOldWriteToNewProfile() = runTest { + val snapshotRequested = CompletableDeferred() + val releaseSnapshot = CompletableDeferred() + val identityTransitions = DefaultIdentityTransitionBarrier() + val guardedRepo = RoomHomeCacheRepository( + db = db, + snapshotProvider = { + snapshotRequested.complete(Unit) + releaseSnapshot.await() + scope + }, + identityTransitions = identityTransitions, + now = { 1000L }, + ) + + val oldProfileWrite = async { + guardedRepo.cacheHome(listOf(section("old", "c1"))) + } + snapshotRequested.await() + identityTransitions.changing(IdentityTransitionKind.PROFILE_SWITCH) { + scope = AuthScopeSnapshot("s1", "p2", "https://s1.example", null) + } + releaseSnapshot.complete(Unit) + oldProfileWrite.await() + + assertNull(guardedRepo.getCachedHome()) + } } diff --git a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/MainActivity.kt b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/MainActivity.kt index 170f8b5550..60ea4b76dd 100644 --- a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/MainActivity.kt +++ b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/MainActivity.kt @@ -311,6 +311,9 @@ class MainActivity : ComponentActivity() { personalDataRepository = get(PersonalDataRepository::class.java), sectionRepository = get(SectionRepository::class.java), homeCache = get(HomeCachePort::class.java), + identityTransitions = get( + org.siloserver.silo.network.IdentityTransitionBarrier::class.java, + ), serverUrl = get(ServerRegistry::class.java).activeEntry.value?.url, artworkPlan = StartupArtworkPlan.phone(), ) diff --git a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/di/AndroidModule.kt b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/di/AndroidModule.kt index 73a2b0dca2..f929e031f4 100644 --- a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/di/AndroidModule.kt +++ b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/di/AndroidModule.kt @@ -144,6 +144,7 @@ val androidModule = module { org.siloserver.silo.common.data.repository.RoomHomeCacheRepository( db = get(), snapshotProvider = { tokenManager.snapshotCurrentScope() }, + identityTransitions = get(), ) } single { @@ -337,7 +338,7 @@ val androidModule = module { castPlaybackPreparer = get(), ) } - viewModel { HomeViewModel(get(), get(), get(), get(), getOrNull()) } + viewModel { HomeViewModel(get(), get(), get(), get(), getOrNull(), get()) } viewModel { MainHeaderViewModel(get()) } viewModel { LibrariesViewModel( diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/MainTvActivity.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/MainTvActivity.kt index 712f6f073c..c8926e0dfe 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/MainTvActivity.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/MainTvActivity.kt @@ -325,6 +325,9 @@ class MainTvActivity : ComponentActivity() { personalDataRepository = get(PersonalDataRepository::class.java), sectionRepository = get(SectionRepository::class.java), homeCache = get(HomeCachePort::class.java), + identityTransitions = get( + org.siloserver.silo.network.IdentityTransitionBarrier::class.java, + ), serverUrl = get(ServerRegistry::class.java).activeEntry.value?.url, artworkPlan = StartupArtworkPlan.tv(), ) diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/di/AndroidTvModule.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/di/AndroidTvModule.kt index c4fc484c59..b468abebc7 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/di/AndroidTvModule.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/di/AndroidTvModule.kt @@ -112,6 +112,7 @@ val androidTvModule = module { org.siloserver.silo.common.data.repository.RoomHomeCacheRepository( db = get(), snapshotProvider = { tokenManager.snapshotCurrentScope() }, + identityTransitions = get(), ) } single { @@ -359,7 +360,7 @@ val androidTvModule = module { } // Content ViewModels - viewModel { HomeViewModel(get(), get(), get(), get(), getOrNull()) } + viewModel { HomeViewModel(get(), get(), get(), get(), getOrNull(), get()) } viewModel { org.siloserver.silo.tv.ui.screens.home.TvUpcomingViewModel(get()) } viewModel { RecommendationsViewModel(get()) } viewModel { RequestsViewModel(get()) } diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/repository/port/HomeCachePort.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/repository/port/HomeCachePort.kt index d35e8ef35e..6389a61976 100644 --- a/shared/src/commonMain/kotlin/org/siloserver/silo/repository/port/HomeCachePort.kt +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/repository/port/HomeCachePort.kt @@ -8,6 +8,8 @@ data class HomeCacheSnapshot( val cachedAtMs: Long, ) +data class HomeCacheWriteLease(val identityGeneration: Long) + /** * Offline read cache for the home screen (Track B). [HomeViewModel] serves the * cached layout instantly (stale-while-revalidate) so the app opens to content @@ -23,6 +25,9 @@ data class HomeCacheSnapshot( */ interface HomeCachePort { suspend fun cacheHome(sections: List) {} + suspend fun cacheHome(sections: List, lease: HomeCacheWriteLease) { + cacheHome(sections) + } suspend fun getCachedHome(): HomeCacheSnapshot? = null } diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeViewModel.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeViewModel.kt index 701ab3937d..fa6d4d45fa 100644 --- a/shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeViewModel.kt +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeViewModel.kt @@ -7,8 +7,11 @@ import org.siloserver.silo.model.catalog.MediaItemUserState import org.siloserver.silo.model.section.ResolvedSection import org.siloserver.silo.model.section.SectionItem import org.siloserver.silo.network.ApiResult +import org.siloserver.silo.network.DefaultIdentityTransitionBarrier +import org.siloserver.silo.network.IdentityTransitionBarrier import org.siloserver.silo.repository.SectionRepository import org.siloserver.silo.repository.port.HomeCachePort +import org.siloserver.silo.repository.port.HomeCacheWriteLease import org.siloserver.silo.repository.port.NoOpHomeCachePort import org.siloserver.silo.repository.port.NoOpUserItemStatePort import org.siloserver.silo.repository.port.UserItemStatePort @@ -43,6 +46,7 @@ class HomeViewModel( // Live-home accelerator (Apple realtime-updates spec). Null keeps // commonMain/tests network-only; the apps inject the shared coordinator. private val homeRealtime: org.siloserver.silo.repository.HomeRealtimeCoordinator? = null, + private val identityTransitions: IdentityTransitionBarrier = DefaultIdentityTransitionBarrier(), ) : ViewModel() { private val _uiState = MutableStateFlow(HomeUiState()) @@ -115,6 +119,8 @@ class HomeViewModel( } private suspend fun fetchSections() { + val requestIdentityGeneration = identityTransitions.generation.value + val cacheWriteLease = HomeCacheWriteLease(requestIdentityGeneration) // Whether we already have something to show (cached or prior fetch) — if a // refresh fails we keep it rather than replacing it with a blocking error. val hadSections = _uiState.value.sections.isNotEmpty() @@ -137,8 +143,11 @@ class HomeViewModel( // Cache the RAW server sections (snapshot), but display with the // local optimistic overlay applied. - if (fullyResolved) { - homeCache.cacheHome(resolved) + if ( + fullyResolved && + requestIdentityGeneration == identityTransitions.generation.value + ) { + homeCache.cacheHome(resolved, cacheWriteLease) } val overlaid = overlayLocalState(resolved) _uiState.update { diff --git a/shared/src/commonTest/kotlin/org/siloserver/silo/viewmodel/HomeViewModelCacheIdentityTest.kt b/shared/src/commonTest/kotlin/org/siloserver/silo/viewmodel/HomeViewModelCacheIdentityTest.kt new file mode 100644 index 0000000000..ee3150a35f --- /dev/null +++ b/shared/src/commonTest/kotlin/org/siloserver/silo/viewmodel/HomeViewModelCacheIdentityTest.kt @@ -0,0 +1,100 @@ +package org.siloserver.silo.viewmodel + +import io.ktor.client.HttpClient +import io.ktor.client.engine.mock.MockEngine +import io.ktor.client.engine.mock.respond +import io.ktor.client.plugins.contentnegotiation.ContentNegotiation +import io.ktor.http.HttpHeaders +import io.ktor.http.HttpStatusCode +import io.ktor.http.headersOf +import io.ktor.serialization.kotlinx.json.json +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.test.setMain +import org.siloserver.silo.domain.MediaActionsCoordinator +import org.siloserver.silo.model.section.ResolvedSection +import org.siloserver.silo.network.DefaultIdentityTransitionBarrier +import org.siloserver.silo.network.IdentityTransitionKind +import org.siloserver.silo.network.SiloJson +import org.siloserver.silo.network.api.PersonalDataApi +import org.siloserver.silo.network.api.SectionApi +import org.siloserver.silo.repository.PersonalDataRepository +import org.siloserver.silo.repository.SectionRepository +import org.siloserver.silo.repository.port.HomeCachePort +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertEquals + +@OptIn(ExperimentalCoroutinesApi::class) +class HomeViewModelCacheIdentityTest { + + private val dispatcher = UnconfinedTestDispatcher() + + @BeforeTest + fun setUp() { + Dispatchers.setMain(dispatcher) + } + + @AfterTest + fun tearDown() { + Dispatchers.resetMain() + } + + @Test + fun homeResponseStartedBeforeProfileSwitchIsNotCachedForNewProfile() = runTest(dispatcher) { + val requestEntered = CompletableDeferred() + val releaseResponse = CompletableDeferred() + val client = HttpClient( + MockEngine { + requestEntered.complete(Unit) + releaseResponse.await() + respond( + """{"sections":[{"id":"old","section_type":"row","title":"Profile A","items":[]}]}""", + HttpStatusCode.OK, + headersOf(HttpHeaders.ContentType, "application/json"), + ) + }, + ) { + install(ContentNegotiation) { json(SiloJson) } + } + val identityTransitions = DefaultIdentityTransitionBarrier() + val cache = RecordingHomeCache() + val viewModel = HomeViewModel( + sectionRepository = SectionRepository( + sectionApi = SectionApi(client), + identityTransitions = identityTransitions, + ), + mediaActions = mediaActions(), + homeCache = cache, + identityTransitions = identityTransitions, + ) + + requestEntered.await() + identityTransitions.changing(IdentityTransitionKind.PROFILE_SWITCH) { } + releaseResponse.complete(Unit) + viewModel.uiState.first { !it.isLoading } + + assertEquals(null, cache.sections) + } + + private class RecordingHomeCache : HomeCachePort { + var sections: List? = null + + override suspend fun cacheHome(sections: List) { + this.sections = sections + } + } + + private fun mediaActions(): MediaActionsCoordinator { + val client = HttpClient(MockEngine { error("Personal data network should not be used") }) { + install(ContentNegotiation) { json(SiloJson) } + } + return MediaActionsCoordinator(PersonalDataRepository(PersonalDataApi(client))) + } +} From e1b4b6e7f94a6590de2c6c43aeca8838c72bbf90 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 09:27:42 +0200 Subject: [PATCH 40/65] test(android): retain deferred library requests --- .../ui/screens/libraries/LibrariesViewModelTest.kt | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibrariesViewModelTest.kt b/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibrariesViewModelTest.kt index 734bffaa96..83ecd06af4 100644 --- a/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibrariesViewModelTest.kt +++ b/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibrariesViewModelTest.kt @@ -232,6 +232,7 @@ class LibrariesViewModelTest { private val deferredKeys: Set, ) { private val requests = Channel(Channel.UNLIMITED) + private val pendingRequests = mutableListOf() private val responses = deferredKeys.associateWith { CompletableDeferred() } private val client = HttpClient( MockEngine { request -> @@ -277,8 +278,15 @@ class LibrariesViewModelTest { ) suspend fun awaitRequest(expected: String) { - while (requests.receive() != expected) { - // Ignore setup requests and wait for the exact request under test. + val pendingIndex = pendingRequests.indexOf(expected) + if (pendingIndex >= 0) { + pendingRequests.removeAt(pendingIndex) + return + } + while (true) { + val actual = requests.receive() + if (actual == expected) return + pendingRequests += actual } } From 3717c9d99436fe055dd960ec931fe5048bffe69e Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 09:44:06 +0200 Subject: [PATCH 41/65] docs(android): plan final release ledger fixes --- .../2026-07-28-android-final-ledger-fixes.md | 221 ++++++++++++++++++ 1 file changed, 221 insertions(+) create mode 100644 docs/superpowers/plans/2026-07-28-android-final-ledger-fixes.md diff --git a/docs/superpowers/plans/2026-07-28-android-final-ledger-fixes.md b/docs/superpowers/plans/2026-07-28-android-final-ledger-fixes.md new file mode 100644 index 0000000000..5816f3231d --- /dev/null +++ b/docs/superpowers/plans/2026-07-28-android-final-ledger-fixes.md @@ -0,0 +1,221 @@ +# Android Final Ledger Fixes Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Fix every current defect validated from the independent 2026-07-28 Android end-to-end ledger before publishing release candidates. + +**Architecture:** Watch Together reconciliation remains centralized in its existing repository and lobby surfaces. Audiobook teardown reuses the application-owned playback lifecycle for asynchronous externally-owned session finalization. The three remaining isolated fixes stay at their current subtitle, authentication, and download ownership boundaries. + +**Tech Stack:** Kotlin, coroutines/Flow, Ktor, Jetpack Compose, Media3, Room, WorkManager, Kotlin test/coroutines-test, Gradle. + +## Global Constraints + +- Android phone and TV only; no server/API/schema/protocol changes. +- Preserve all already-reviewed Watch Together generation, lease, reconnect, and leave semantics. +- No `runBlocking` on UI/ViewModel teardown, arbitrary sleeps, timeout widening, or fire-and-forget global scopes. +- Every behavioral fix starts with a deterministic RED regression. +- Physical devices remain excluded. +- Delete only the verified-unused no-op auth stub; do not alter the installed real auth plugin. + +--- + +### Task 1: Reconcile Watch Together Suggestions and Surface Lobby Errors + +**Files:** +- Modify: `shared/src/commonMain/kotlin/org/siloserver/silo/watchtogether/WatchTogetherRepository.kt` +- Modify: phone and TV Watch Together lobby ViewModels/screens as required by their existing error-effect architecture. +- Test: `shared/src/commonTest/kotlin/org/siloserver/silo/watchtogether/WatchTogetherRepositoryTest.kt` +- Test: phone and TV lobby unit/source tests. + +**Interfaces:** +- Consumes: existing `Opened`, REST `listSuggestions`, repository `errors`, lobby message/snackbar effects. +- Produces: reconnect hydration, authoritative `votedIds`, and visible transient lobby failures on both clients. + +- [ ] **Step 1: Write reconnect hydration RED** + +Start a socket, publish suggestions, terminate transport, mutate the fake REST +suggestion list, connect the successor socket, emit `Opened`, and assert REST +is called again and the missed mutation is published. Verify a protocol +`Closed` remains terminal and does not refresh/reconnect. + +- [ ] **Step 2: Write authoritative unvote RED** + +Apply a REST list with `votedByMe=true`, then refresh with the same suggestion +set to false. Assert the repository's local vote set removes that ID while +preserving votes still reported true. + +- [ ] **Step 3: Implement repository reconciliation** + +On each healthy `Opened`, refresh suggestions through the existing REST API +without creating a second repository/socket architecture. Replace the +authoritative vote set from REST responses rather than only OR-ing true IDs; +retain optimistic mutation behavior between authoritative refreshes. + +- [ ] **Step 4: Write lobby error RED** + +Make vote/promote/suggest fail in each lobby ViewModel and assert one visible +message effect. Also assert repository transient socket errors are visible +while the lobby is active. + +- [ ] **Step 5: Implement phone/TV error parity** + +Collect the existing repository error flow in the existing lobby lifecycle, +and translate rejected operations through the same one-shot UI message path. +Do not add replay that can show stale errors after navigation. + +- [ ] **Step 6: Run focused GREEN and commit** + +Run repository and both lobby test suites, compile phone/TV, then commit: + +```bash +git commit -m "fix(watch-together): reconcile rooms and surface lobby errors" +``` + +### Task 2: Make Audiobook Teardown Non-Blocking + +**Files:** +- Modify: `android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/PlaybackSessionLifecycle.kt` +- Modify: `android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/AudiobookPlayerViewModel.kt` +- Modify: phone and TV DI factories for the shared audiobook ViewModel. +- Test: `android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/PlaybackSessionLifecycleTest.kt` +- Test: a source-contract test for audiobook teardown. + +**Interfaces:** +- Consumes: the lifecycle's existing application scope, `NonCancellable + Dispatchers.IO`, and `PlaybackSessionManager.reportProgress/stopSession`. +- Produces: `reportAndStopExternalSessionAsync(sessionId, positionSeconds, isPaused)` for an externally-owned audiobook session. + +- [ ] **Step 1: Write asynchronous finalization RED** + +Use a fake manager whose progress call suspends. Invoke the new external +finalizer, assert the caller returns before the fake is released, then assert +the exact session/position/pause report precedes stop. + +- [ ] **Step 2: Write audiobook source-contract RED** + +Assert `AudiobookPlayerViewModel.onCleared` contains no `runBlocking` and +submits a synchronously captured active session/position/pause snapshot to the +external finalizer. + +- [ ] **Step 3: Implement the smallest lifecycle reuse** + +Add a coalesced application-scope async operation for the explicit external +session ID. Do not adopt the audiobook session into the video lifecycle and do +not derive the target from lifecycle-owned state. Inject the lifecycle through +both clients' existing factories. + +- [ ] **Step 4: Run focused GREEN and commit** + +Run lifecycle/audiobook tests and phone/TV compilation, then commit: + +```bash +git commit -m "fix(android): finalize audiobook sessions asynchronously" +``` + +### Task 3: Correct TV Top Subtitle Title-Safe Compensation + +**Files:** +- Modify: `android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SubtitleManager.kt` +- Test: `android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/SubtitleManagerAppearanceTest.kt` + +**Interfaces:** +- Consumes: subtitle vertical preset and `titleSafeFraction`. +- Produces: unchanged Top base padding; compensated Bottom/LowerThird padding. + +- [ ] **Step 1: Write RED** + +With `titleSafeFraction = 0.05f`, assert Top remains its base `0.74f` padding +while Bottom and LowerThird retain their existing compensation. + +- [ ] **Step 2: Implement GREEN** + +Skip bottom-padding subtraction only for the Top preset; preserve every other +preset and the outer title-safe surface inset. + +- [ ] **Step 3: Verify and commit** + +Run the full subtitle appearance class and compile both clients: + +```bash +git commit -m "fix(tv): avoid double-shifting top subtitles" +``` + +### Task 4: Remove the Unused No-Op Auth Plugin + +**Files:** +- Delete: `shared/src/commonMain/kotlin/org/siloserver/silo/network/AuthInterceptor.kt` + +**Interfaces:** +- Consumes: repository-wide proof that only `SiloAuthPlugin` is installed. +- Produces: no public no-op authentication symbol that can be installed accidentally. + +- [ ] **Step 1: Prove non-use** + +Search production/tests/build publication metadata for `SiloAuth`; require the +declaration to be the only match and the real `SiloAuthPlugin` installation to +remain in `SiloHttpClientImpl`. + +- [ ] **Step 2: Delete and compile** + +Delete only the stub, compile shared/phone/TV, and commit: + +```bash +git commit -m "chore(shared): remove unused no-op auth plugin" +``` + +### Task 5: Clear Permanent Download Failure Progress + +**Files:** +- Modify: `android-shared/src/androidMain/kotlin/org/siloserver/silo/common/downloads/DownloadWorker.kt` +- Test: the existing DownloadWorker/sidecar status test suite. + +**Interfaces:** +- Consumes: existing live-record and sidecar status update helpers. +- Produces: nullable “preserve” byte arguments, with explicit zero clearing both stored representations on permanent failure. + +- [ ] **Step 1: Write RED** + +Seed a download and sidecar with nonzero bytes, invoke the permanent-failure +transition, and assert `Failed`, `bytesSent == 0`, and `fileSize == 0` in both. + +- [ ] **Step 2: Implement GREEN** + +Distinguish omitted/preserve values from explicit zero using nullable +arguments or an equally explicit update type. Preserve existing callers that +intend to retain progress. + +- [ ] **Step 3: Verify and commit** + +Run the focused worker/sidecar tests and compile phone/TV: + +```bash +git commit -m "fix(android): clear progress on permanent download failure" +``` + +### Task 6: Final Integrated Release Qualification + +**Files:** +- Verify only: `origin/main...HEAD`. + +**Interfaces:** +- Consumes: Tasks 1–5 with independent approval. +- Produces: clean reviewed branch, green supply-chain/unit/release gates, final universal APKs, and updated PR #126. + +- [ ] **Step 1: Independently review every task and fix every finding** + +- [ ] **Step 2: Run supply-chain and exact combined phone/TV unit/release gate** + +```bash +./scripts/test-check-build-supply-chain.sh +./scripts/check-build-supply-chain.sh +./gradlew \ + :androidApp:testDebugUnitTest \ + :androidTvApp:testDebugUnitTest \ + :androidApp:assembleRelease \ + :androidTvApp:assembleRelease \ + -PallowDebugReleaseSigning=true \ + --rerun-tasks --max-workers=2 --no-daemon +``` + +- [ ] **Step 3: Require a final whole-branch clean review** + +- [ ] **Step 4: Verify and copy final universal APKs, then push/update PR #126 without merging** From e4b086e691f0932b995ef39d2c6a4617eb11f62e Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 09:52:01 +0200 Subject: [PATCH 42/65] fix(watch-together): reconcile rooms and surface lobby errors --- .../watchtogether/WatchTogetherLobbyScreen.kt | 9 + .../WatchTogetherLobbyViewModel.kt | 31 ++- .../WatchTogetherLobbyErrorTest.kt | 177 ++++++++++++++++++ .../TvWatchTogetherLobbyScreen.kt | 11 ++ .../TvWatchTogetherLobbyViewModel.kt | 31 ++- .../TvWatchTogetherLobbyErrorTest.kt | 172 +++++++++++++++++ .../repository/WatchTogetherRepository.kt | 25 ++- .../repository/WatchTogetherRepositoryTest.kt | 78 ++++++++ 8 files changed, 517 insertions(+), 17 deletions(-) create mode 100644 androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/watchtogether/WatchTogetherLobbyErrorTest.kt create mode 100644 androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/watchtogether/TvWatchTogetherLobbyErrorTest.kt diff --git a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/watchtogether/WatchTogetherLobbyScreen.kt b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/watchtogether/WatchTogetherLobbyScreen.kt index 313c9f3a61..0f491479ed 100644 --- a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/watchtogether/WatchTogetherLobbyScreen.kt +++ b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/watchtogether/WatchTogetherLobbyScreen.kt @@ -1,6 +1,7 @@ package org.siloserver.silo.android.ui.screens.watchtogether import android.content.Intent +import android.widget.Toast import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row @@ -77,6 +78,14 @@ fun WatchTogetherLobbyScreen( if (closedReason != null) onBack() } + LaunchedEffect(viewModel) { + viewModel.errors.collect { message -> + if (message.isNotBlank()) { + Toast.makeText(context, message, Toast.LENGTH_SHORT).show() + } + } + } + // Role drives only the cosmetic header label; mutating controls gate on the // server's per-recipient management capability so a demoted/grace-period host // (selfRole still "host" but management revoked) doesn't see dead buttons. diff --git a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/watchtogether/WatchTogetherLobbyViewModel.kt b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/watchtogether/WatchTogetherLobbyViewModel.kt index 1346ff6600..b06485d8d0 100644 --- a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/watchtogether/WatchTogetherLobbyViewModel.kt +++ b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/watchtogether/WatchTogetherLobbyViewModel.kt @@ -8,6 +8,8 @@ import org.siloserver.silo.model.watchtogether.MemberRole import org.siloserver.silo.model.watchtogether.RoomPhase import org.siloserver.silo.model.watchtogether.RoomSnapshot import org.siloserver.silo.model.watchtogether.Suggestion +import org.siloserver.silo.network.ApiResult +import org.siloserver.silo.network.errorMessage import org.siloserver.silo.repository.WatchTogetherRepository import org.siloserver.silo.watchtogether.RoomSession import kotlinx.coroutines.flow.SharingStarted @@ -62,17 +64,36 @@ class WatchTogetherLobbyViewModel( .stateIn(viewModelScope, SharingStarted.Eagerly, repository.suggestions.value) val roomClosedReason: StateFlow = repository.roomClosedReason .stateIn(viewModelScope, SharingStarted.Eagerly, repository.roomClosedReason.value) + val errors = repository.errors + + fun vote(suggestionId: String) = + launchOperation("Could not vote") { repository.vote(suggestionId) } + + fun unvote(suggestionId: String) = + launchOperation("Could not remove vote") { repository.unvote(suggestionId) } - fun vote(suggestionId: String) = viewModelScope.launch { repository.vote(suggestionId) } - fun unvote(suggestionId: String) = viewModelScope.launch { repository.unvote(suggestionId) } fun removeSuggestion(suggestionId: String) = - viewModelScope.launch { repository.deleteSuggestion(suggestionId) } + launchOperation("Could not remove suggestion") { + repository.deleteSuggestion(suggestionId) + } /** Host: promote a suggestion to the room selection (moves everyone to the player). */ fun promote(suggestionId: String) = - viewModelScope.launch { repository.promoteSuggestion(PromoteSuggestionRequest(suggestionId = suggestionId)) } + launchOperation("Could not start suggestion") { + repository.promoteSuggestion(PromoteSuggestionRequest(suggestionId = suggestionId)) + } - fun closeRoom() = viewModelScope.launch { repository.closeRoom() } + fun closeRoom() = launchOperation("Could not close room") { repository.closeRoom() } + + private fun launchOperation( + fallback: String, + operation: suspend () -> ApiResult, + ) = viewModelScope.launch { + val result = operation() + if (result !is ApiResult.Success) { + repository.reportDeliveryFailure(result.errorMessage(fallback)) + } + } /** Guest/host leave: tear down the WS + clear room state. */ fun leave() { diff --git a/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/watchtogether/WatchTogetherLobbyErrorTest.kt b/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/watchtogether/WatchTogetherLobbyErrorTest.kt new file mode 100644 index 0000000000..b8a73d71c4 --- /dev/null +++ b/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/watchtogether/WatchTogetherLobbyErrorTest.kt @@ -0,0 +1,177 @@ +package org.siloserver.silo.android.ui.screens.watchtogether + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.toList +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.test.setMain +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import org.siloserver.silo.model.watchtogether.AddSuggestionRequest +import org.siloserver.silo.model.watchtogether.CreateRoomRequest +import org.siloserver.silo.model.watchtogether.JoinRoomRequest +import org.siloserver.silo.model.watchtogether.PromoteSuggestionRequest +import org.siloserver.silo.model.watchtogether.RoomResponse +import org.siloserver.silo.model.watchtogether.RoomSnapshot +import org.siloserver.silo.model.watchtogether.SetSelectionRequest +import org.siloserver.silo.model.watchtogether.SuggestionsResponse +import org.siloserver.silo.model.watchtogether.UpdatePolicyRequest +import org.siloserver.silo.network.ApiResult +import org.siloserver.silo.network.AuthScopeSnapshot +import org.siloserver.silo.network.DefaultIdentityTransitionBarrier +import org.siloserver.silo.network.api.WatchTogetherApi +import org.siloserver.silo.repository.WatchTogetherRepository +import org.siloserver.silo.watchtogether.RoomSession +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertEquals + +@OptIn(ExperimentalCoroutinesApi::class) +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34], application = android.app.Application::class) +class WatchTogetherLobbyErrorTest { + private val dispatcher = UnconfinedTestDispatcher() + + @BeforeTest + fun setUp() { + Dispatchers.setMain(dispatcher) + } + + @AfterTest + fun tearDown() { + Dispatchers.resetMain() + } + + @Test + fun `rejected lobby operations use the transient repository message path`() = runTest(dispatcher) { + val api = FailingLobbyApi() + val repository = WatchTogetherRepository( + api = api, + authScopeProvider = { AUTH_SCOPE }, + ) + repository.createRoom(CreateRoomRequest()) + val roomSession = RoomSession(repository, backgroundScope, DefaultIdentityTransitionBarrier()) + val viewModel = WatchTogetherLobbyViewModel("room-1", repository, roomSession) + val messages = mutableListOf() + val collector = backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { + viewModel.errors.toList(messages) + } + + viewModel.vote("suggestion-1") + viewModel.promote("suggestion-1") + repository.reportDeliveryFailure("Socket request rejected") + runCurrent() + + assertEquals( + listOf( + "Voting is disabled", + "Only the host can promote", + "Socket request rejected", + ), + messages, + ) + collector.cancel() + } + + @Test + fun `suggest rejection remains a visible one shot detail message`() = runTest(dispatcher) { + val repository = WatchTogetherRepository( + api = FailingLobbyApi(), + authScopeProvider = { AUTH_SCOPE }, + ) + repository.createRoom(CreateRoomRequest()) + val viewModel = SuggestToRoomViewModel(repository) + + viewModel.suggest("movie-1", "movie", "Movie One", null, null) + runCurrent() + + assertEquals("Suggestions are locked", viewModel.uiState.value.error) + viewModel.clearError() + assertEquals(null, viewModel.uiState.value.error) + } + + private class FailingLobbyApi : WatchTogetherApi { + private val roomResponse = + ApiResult.Success(RoomResponse(RoomSnapshot(roomId = "room-1"), "room-token")) + + override suspend fun createRoom(request: CreateRoomRequest, scope: AuthScopeSnapshot) = roomResponse + override suspend fun joinRoom(request: JoinRoomRequest, scope: AuthScopeSnapshot) = roomResponse + override suspend fun getRoom(roomId: String, roomToken: String, scope: AuthScopeSnapshot) = roomResponse + override suspend fun setSelection( + roomId: String, + roomToken: String, + request: SetSelectionRequest, + scope: AuthScopeSnapshot, + ) = roomResponse + + override suspend fun updatePolicy( + roomId: String, + roomToken: String, + request: UpdatePolicyRequest, + scope: AuthScopeSnapshot, + ) = roomResponse + + override suspend fun closeRoom(roomId: String, roomToken: String, scope: AuthScopeSnapshot) = + ApiResult.Success(Unit) + + override suspend fun listSuggestions( + roomId: String, + roomToken: String, + scope: AuthScopeSnapshot, + ) = ApiResult.Success(SuggestionsResponse()) + + override suspend fun addSuggestion( + roomId: String, + roomToken: String, + request: AddSuggestionRequest, + scope: AuthScopeSnapshot, + ): ApiResult = + ApiResult.Error(409, "suggestions_locked", "Suggestions are locked") + + override suspend fun deleteSuggestion( + roomId: String, + roomToken: String, + suggestionId: String, + scope: AuthScopeSnapshot, + ) = ApiResult.Success(SuggestionsResponse()) + + override suspend fun vote( + roomId: String, + roomToken: String, + suggestionId: String, + scope: AuthScopeSnapshot, + ): ApiResult = + ApiResult.Error(409, "voting_disabled", "Voting is disabled") + + override suspend fun unvote( + roomId: String, + roomToken: String, + suggestionId: String, + scope: AuthScopeSnapshot, + ) = ApiResult.Success(SuggestionsResponse()) + + override suspend fun promoteSuggestion( + roomId: String, + roomToken: String, + request: PromoteSuggestionRequest, + scope: AuthScopeSnapshot, + ): ApiResult = + ApiResult.Error(403, "host_required", "Only the host can promote") + } + + private companion object { + val AUTH_SCOPE = AuthScopeSnapshot( + serverId = "server-1", + profileId = "profile-1", + serverUrl = "https://example.test", + profileToken = "profile-token", + identityGeneration = 1L, + ) + } +} diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/watchtogether/TvWatchTogetherLobbyScreen.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/watchtogether/TvWatchTogetherLobbyScreen.kt index 8589ff4817..3530d0cb42 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/watchtogether/TvWatchTogetherLobbyScreen.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/watchtogether/TvWatchTogetherLobbyScreen.kt @@ -1,5 +1,6 @@ package org.siloserver.silo.tv.ui.screens.watchtogether +import android.widget.Toast import androidx.activity.compose.BackHandler import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.background @@ -32,6 +33,7 @@ import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow @@ -106,6 +108,7 @@ fun TvWatchTogetherLobbyScreen( val room by viewModel.room.collectAsState() val suggestions by viewModel.suggestions.collectAsState() val closedReason by viewModel.roomClosedReason.collectAsState() + val context = LocalContext.current // Role drives only the cosmetic header label; mutating controls gate on // the server's per-recipient management capability so a demoted/ @@ -145,6 +148,14 @@ fun TvWatchTogetherLobbyScreen( } } + LaunchedEffect(viewModel) { + viewModel.errors.collect { message -> + if (message.isNotBlank()) { + Toast.makeText(context, message, Toast.LENGTH_SHORT).show() + } + } + } + // Browsing away retains the process-scoped room connection. Leaving is an // explicit action below; hosts close the room for everyone via "Close room". BackHandler(enabled = true) { diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/watchtogether/TvWatchTogetherLobbyViewModel.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/watchtogether/TvWatchTogetherLobbyViewModel.kt index fdf2888306..a55b28c056 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/watchtogether/TvWatchTogetherLobbyViewModel.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/watchtogether/TvWatchTogetherLobbyViewModel.kt @@ -6,6 +6,8 @@ import org.siloserver.silo.model.watchtogether.PromoteSuggestionRequest import org.siloserver.silo.model.watchtogether.RoomSnapshot import org.siloserver.silo.model.watchtogether.Suggestion import org.siloserver.silo.model.watchtogether.UpdatePolicyRequest +import org.siloserver.silo.network.ApiResult +import org.siloserver.silo.network.errorMessage import org.siloserver.silo.repository.WatchTogetherRepository import org.siloserver.silo.watchtogether.RoomSession import kotlinx.coroutines.flow.SharingStarted @@ -40,26 +42,43 @@ class TvWatchTogetherLobbyViewModel( .stateIn(viewModelScope, SharingStarted.Eagerly, repository.suggestions.value) val roomClosedReason: StateFlow = repository.roomClosedReason .stateIn(viewModelScope, SharingStarted.Eagerly, repository.roomClosedReason.value) + val errors = repository.errors + + fun vote(suggestionId: String) = + launchOperation("Could not vote") { repository.vote(suggestionId) } + + fun unvote(suggestionId: String) = + launchOperation("Could not remove vote") { repository.unvote(suggestionId) } - fun vote(suggestionId: String) = viewModelScope.launch { repository.vote(suggestionId) } - fun unvote(suggestionId: String) = viewModelScope.launch { repository.unvote(suggestionId) } fun removeSuggestion(suggestionId: String) = - viewModelScope.launch { repository.deleteSuggestion(suggestionId) } + launchOperation("Could not remove suggestion") { + repository.deleteSuggestion(suggestionId) + } /** Host: promote a suggestion to the room selection (moves everyone to the player). */ fun promote(suggestionId: String) = - viewModelScope.launch { + launchOperation("Could not start suggestion") { repository.promoteSuggestion(PromoteSuggestionRequest(suggestionId = suggestionId)) } /** Host: change the guest-control policy. */ fun updatePolicy(guestControlPolicyWire: String) = - viewModelScope.launch { + launchOperation("Could not update room policy") { repository.updatePolicy(UpdatePolicyRequest(guestControlPolicy = guestControlPolicyWire)) } /** Host: close the room for everyone. */ - fun closeRoom() = viewModelScope.launch { repository.closeRoom() } + fun closeRoom() = launchOperation("Could not close room") { repository.closeRoom() } + + private fun launchOperation( + fallback: String, + operation: suspend () -> ApiResult, + ) = viewModelScope.launch { + val result = operation() + if (result !is ApiResult.Success) { + repository.reportDeliveryFailure(result.errorMessage(fallback)) + } + } /** * Leave the room: tear down our own WS and reset shared repo state. Matches diff --git a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/watchtogether/TvWatchTogetherLobbyErrorTest.kt b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/watchtogether/TvWatchTogetherLobbyErrorTest.kt new file mode 100644 index 0000000000..fe2c96acde --- /dev/null +++ b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/watchtogether/TvWatchTogetherLobbyErrorTest.kt @@ -0,0 +1,172 @@ +package org.siloserver.silo.tv.ui.screens.watchtogether + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.toList +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.test.setMain +import org.siloserver.silo.model.watchtogether.AddSuggestionRequest +import org.siloserver.silo.model.watchtogether.CreateRoomRequest +import org.siloserver.silo.model.watchtogether.JoinRoomRequest +import org.siloserver.silo.model.watchtogether.PromoteSuggestionRequest +import org.siloserver.silo.model.watchtogether.RoomResponse +import org.siloserver.silo.model.watchtogether.RoomSnapshot +import org.siloserver.silo.model.watchtogether.SetSelectionRequest +import org.siloserver.silo.model.watchtogether.SuggestionsResponse +import org.siloserver.silo.model.watchtogether.UpdatePolicyRequest +import org.siloserver.silo.network.ApiResult +import org.siloserver.silo.network.AuthScopeSnapshot +import org.siloserver.silo.network.DefaultIdentityTransitionBarrier +import org.siloserver.silo.network.api.WatchTogetherApi +import org.siloserver.silo.repository.WatchTogetherRepository +import org.siloserver.silo.watchtogether.RoomSession +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertEquals + +@OptIn(ExperimentalCoroutinesApi::class) +class TvWatchTogetherLobbyErrorTest { + private val dispatcher = UnconfinedTestDispatcher() + + @BeforeTest + fun setUp() { + Dispatchers.setMain(dispatcher) + } + + @AfterTest + fun tearDown() { + Dispatchers.resetMain() + } + + @Test + fun `rejected lobby operations use the transient repository message path`() = runTest(dispatcher) { + val api = FailingLobbyApi() + val repository = WatchTogetherRepository( + api = api, + authScopeProvider = { AUTH_SCOPE }, + ) + repository.createRoom(CreateRoomRequest()) + val roomSession = RoomSession(repository, backgroundScope, DefaultIdentityTransitionBarrier()) + val viewModel = TvWatchTogetherLobbyViewModel("room-1", repository, roomSession) + val messages = mutableListOf() + val collector = backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { + viewModel.errors.toList(messages) + } + + viewModel.vote("suggestion-1") + viewModel.promote("suggestion-1") + repository.reportDeliveryFailure("Socket request rejected") + runCurrent() + + assertEquals( + listOf( + "Voting is disabled", + "Only the host can promote", + "Socket request rejected", + ), + messages, + ) + collector.cancel() + } + + @Test + fun `suggest rejection remains a visible one shot detail message`() = runTest(dispatcher) { + val repository = WatchTogetherRepository( + api = FailingLobbyApi(), + authScopeProvider = { AUTH_SCOPE }, + ) + repository.createRoom(CreateRoomRequest()) + val viewModel = TvSuggestToRoomViewModel(repository) + + viewModel.suggest("movie-1", "movie", "Movie One", null, null) + runCurrent() + + assertEquals("Suggestions are locked", viewModel.uiState.value.error) + viewModel.clearError() + assertEquals(null, viewModel.uiState.value.error) + } + + private class FailingLobbyApi : WatchTogetherApi { + private val roomResponse = + ApiResult.Success(RoomResponse(RoomSnapshot(roomId = "room-1"), "room-token")) + + override suspend fun createRoom(request: CreateRoomRequest, scope: AuthScopeSnapshot) = roomResponse + override suspend fun joinRoom(request: JoinRoomRequest, scope: AuthScopeSnapshot) = roomResponse + override suspend fun getRoom(roomId: String, roomToken: String, scope: AuthScopeSnapshot) = roomResponse + override suspend fun setSelection( + roomId: String, + roomToken: String, + request: SetSelectionRequest, + scope: AuthScopeSnapshot, + ) = roomResponse + + override suspend fun updatePolicy( + roomId: String, + roomToken: String, + request: UpdatePolicyRequest, + scope: AuthScopeSnapshot, + ) = roomResponse + + override suspend fun closeRoom(roomId: String, roomToken: String, scope: AuthScopeSnapshot) = + ApiResult.Success(Unit) + + override suspend fun listSuggestions( + roomId: String, + roomToken: String, + scope: AuthScopeSnapshot, + ) = ApiResult.Success(SuggestionsResponse()) + + override suspend fun addSuggestion( + roomId: String, + roomToken: String, + request: AddSuggestionRequest, + scope: AuthScopeSnapshot, + ): ApiResult = + ApiResult.Error(409, "suggestions_locked", "Suggestions are locked") + + override suspend fun deleteSuggestion( + roomId: String, + roomToken: String, + suggestionId: String, + scope: AuthScopeSnapshot, + ) = ApiResult.Success(SuggestionsResponse()) + + override suspend fun vote( + roomId: String, + roomToken: String, + suggestionId: String, + scope: AuthScopeSnapshot, + ): ApiResult = + ApiResult.Error(409, "voting_disabled", "Voting is disabled") + + override suspend fun unvote( + roomId: String, + roomToken: String, + suggestionId: String, + scope: AuthScopeSnapshot, + ) = ApiResult.Success(SuggestionsResponse()) + + override suspend fun promoteSuggestion( + roomId: String, + roomToken: String, + request: PromoteSuggestionRequest, + scope: AuthScopeSnapshot, + ): ApiResult = + ApiResult.Error(403, "host_required", "Only the host can promote") + } + + private companion object { + val AUTH_SCOPE = AuthScopeSnapshot( + serverId = "server-1", + profileId = "profile-1", + serverUrl = "https://example.test", + profileToken = "profile-token", + identityGeneration = 1L, + ) + } +} diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/repository/WatchTogetherRepository.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/repository/WatchTogetherRepository.kt index c7449f4f9a..b91c96a485 100644 --- a/shared/src/commonMain/kotlin/org/siloserver/silo/repository/WatchTogetherRepository.kt +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/repository/WatchTogetherRepository.kt @@ -311,7 +311,7 @@ class WatchTogetherRepository( val published = stateMutex.withLock { if (!isCurrentLocked(lease)) return@withLock false votedIds.add(suggestionId) - applySuggestions(r.data.suggestions, fromBroadcast = false) + applySuggestions(r.data.suggestions, fromBroadcast = true) true } return if (published) r else obsoleteRoomRequest() @@ -324,7 +324,7 @@ class WatchTogetherRepository( val published = stateMutex.withLock { if (!isCurrentLocked(lease)) return@withLock false votedIds.remove(suggestionId) - applySuggestions(r.data.suggestions, fromBroadcast = false) + applySuggestions(r.data.suggestions, fromBroadcast = true) true } return if (published) r else obsoleteRoomRequest() @@ -385,12 +385,14 @@ class WatchTogetherRepository( lease: RoomBinding, result: ApiResult, expectedRoomRequest: Long? = null, + expectedConnectionOwner: Long? = null, ): ApiResult { if (result !is ApiResult.Success) return result val published = stateMutex.withLock { if ( !isCurrentLocked(lease) || - (expectedRoomRequest != null && latestRoomRequest != expectedRoomRequest) + (expectedRoomRequest != null && latestRoomRequest != expectedRoomRequest) || + (expectedConnectionOwner != null && activeConnectionOwner != expectedConnectionOwner) ) { return@withLock false } @@ -414,12 +416,14 @@ class WatchTogetherRepository( /** * Publish suggestions, re-merging `voted_by_me` from the local [votedIds] - * set. For REST results we also seed [votedIds] from authoritative - * voted_by_me; broadcasts force false, so we only OR the local set in. + * set. Authoritative REST lists replace [votedIds]; broadcasts and + * optimistic vote mutation responses preserve the local set because their + * per-recipient vote flags are not authoritative. */ private fun applySuggestions(list: List, fromBroadcast: Boolean) { if (!fromBroadcast) { - list.forEach { if (it.votedByMe) votedIds.add(it.id) } + votedIds.clear() + votedIds.addAll(list.filter { it.votedByMe }.map { it.id }) } _suggestions.value = list.map { s -> if (s.id in votedIds) s.copy(votedByMe = true) else s @@ -569,6 +573,15 @@ class WatchTogetherRepository( } else if (event is RoomRealtimeEvent.Opened) { openedAtMs = monotonicNowMs() markOpened(lease, owner, client.currentConnectionId()) + publishSuggestionsResponse( + lease = lease, + result = api.listSuggestions( + lease.roomId, + lease.roomToken, + lease.authScope, + ), + expectedConnectionOwner = owner, + ) } else if ( event is RoomRealtimeEvent.SnapshotEvent && event.room.roomId == lease.roomId diff --git a/shared/src/commonTest/kotlin/org/siloserver/silo/repository/WatchTogetherRepositoryTest.kt b/shared/src/commonTest/kotlin/org/siloserver/silo/repository/WatchTogetherRepositoryTest.kt index 98cd27d7f7..42bd8cdbfd 100644 --- a/shared/src/commonTest/kotlin/org/siloserver/silo/repository/WatchTogetherRepositoryTest.kt +++ b/shared/src/commonTest/kotlin/org/siloserver/silo/repository/WatchTogetherRepositoryTest.kt @@ -839,6 +839,84 @@ class WatchTogetherRepositoryTest { // ---- suggestions fold + voted_by_me re-merge ------------------------------ + @Test + fun `opened refreshes suggestions after reconnect without refreshing after room closed`() = runTest { + val api = FakeApi().apply { + listSuggestionsResponse = ApiResult.Success( + SuggestionsResponse(suggestions = listOf(suggestion("before-drop"))), + ) + } + val realtime = FakeRealtime() + val repository = repo(api = api, realtime = realtime) + repository.createRoom(CreateRoomRequest()) + val connection = launch { repository.connect("room-1") } + runCurrent() + + realtime.events.emit(RoomRealtimeEvent.Opened) + runCurrent() + assertEquals(1, api.listSuggestionsCalls) + assertEquals(listOf("before-drop"), repository.suggestions.value.map { it.id }) + + realtime.events.emit(RoomRealtimeEvent.TransportTerminated()) + runCurrent() + api.listSuggestionsResponse = ApiResult.Success( + SuggestionsResponse( + suggestions = listOf( + suggestion("before-drop"), + suggestion("missed-during-drop"), + ), + ), + ) + advanceTimeBy(WatchTogetherRepository.BACKOFF_MS.first()) + runCurrent() + assertEquals(2, realtime.connectCount) + + realtime.events.emit(RoomRealtimeEvent.Opened) + runCurrent() + assertEquals(2, api.listSuggestionsCalls) + assertEquals( + listOf("before-drop", "missed-during-drop"), + repository.suggestions.value.map { it.id }, + ) + + realtime.events.emit(RoomRealtimeEvent.Closed("host_left")) + advanceUntilIdle() + assertEquals(2, realtime.connectCount) + assertEquals(2, api.listSuggestionsCalls) + assertTrue(connection.isCompleted || connection.isCancelled) + } + + @Test + fun `rest refresh replaces authoritative local vote set`() = runTest { + val api = FakeApi().apply { + listSuggestionsResponse = ApiResult.Success( + SuggestionsResponse( + suggestions = listOf( + suggestion("removed-vote", votedByMe = true), + suggestion("preserved-vote", votedByMe = true), + ), + ), + ) + } + val repository = repo(api = api) + repository.createRoom(CreateRoomRequest()) + + repository.refreshSuggestions() + api.listSuggestionsResponse = ApiResult.Success( + SuggestionsResponse( + suggestions = listOf( + suggestion("removed-vote", votedByMe = false), + suggestion("preserved-vote", votedByMe = true), + ), + ), + ) + repository.refreshSuggestions() + + val byId = repository.suggestions.value.associateBy { it.id } + assertFalse(byId.getValue("removed-vote").votedByMe) + assertTrue(byId.getValue("preserved-vote").votedByMe) + } + @Test fun `suggestions event re-merges voted_by_me from local vote set`() = runTest { val api = FakeApi() From 14c06a6229a2c77a5ddd0a8ec5642ef868f5d440 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 09:54:37 +0200 Subject: [PATCH 43/65] fix(android): finalize audiobook sessions asynchronously --- .../common/player/AudiobookPlayerViewModel.kt | 23 +++-- .../common/player/PlaybackSessionLifecycle.kt | 43 +++++++++ .../AudiobookPlayerTeardownSourceTest.kt | 38 ++++++++ .../player/PlaybackSessionLifecycleTest.kt | 94 +++++++++++++++++++ .../silo/android/di/AndroidModule.kt | 1 + .../siloserver/silo/tv/di/AndroidTvModule.kt | 1 + 6 files changed, 188 insertions(+), 12 deletions(-) create mode 100644 android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/AudiobookPlayerTeardownSourceTest.kt diff --git a/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/AudiobookPlayerViewModel.kt b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/AudiobookPlayerViewModel.kt index bc61468488..4568851518 100644 --- a/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/AudiobookPlayerViewModel.kt +++ b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/AudiobookPlayerViewModel.kt @@ -34,7 +34,6 @@ import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch -import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import kotlin.math.abs import kotlin.random.Random @@ -81,6 +80,7 @@ data class AudiobookPlayerUiState( class AudiobookPlayerViewModel( private val catalogRepository: CatalogRepository, private val playbackSessionManager: PlaybackSessionManager, + private val playbackSessionLifecycle: PlaybackSessionLifecycle, private val capabilityDetector: PlaybackCapabilityDetector, private val bookmarksStore: AudiobookBookmarksStore, // Track B: durable position via the unified outbox (replaces AudiobookPositionStore @@ -1274,17 +1274,16 @@ class AudiobookPlayerViewModel( sleepTimerJob?.cancel() positionSaveJob?.cancel() val state = _uiState.value - state.sessionId?.let { sessionId -> - runCatching { - runBlocking(Dispatchers.IO) { - // SINK 1: report the retiring session in part-local space. - reportAndStopSession( - sessionId = sessionId, - positionSeconds = sessionLocalPosition(state), - isPaused = true, - ) - } - } + val sessionId = state.sessionId + if (sessionId != null) { + val positionSeconds = sessionLocalPosition(state) + val isPaused = true + // SINK 1: report the retiring session in part-local space. + playbackSessionLifecycle.reportAndStopExternalSessionAsync( + sessionId = sessionId, + positionSeconds = positionSeconds, + isPaused = isPaused, + ) } super.onCleared() } diff --git a/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/PlaybackSessionLifecycle.kt b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/PlaybackSessionLifecycle.kt index d4ffe442b7..17170bd33b 100644 --- a/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/PlaybackSessionLifecycle.kt +++ b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/PlaybackSessionLifecycle.kt @@ -96,6 +96,8 @@ class PlaybackSessionLifecycle( /** Session [pendingStopJob] is stopping; guarded by `pendingStopLock`. */ private var pendingStopSessionId: String? = null + private val externalFinalizationLock = Any() + private val pendingExternalFinalizations = mutableMapOf() private data class ActiveSessionSnapshot( val state: SessionState, @@ -683,6 +685,47 @@ class PlaybackSessionLifecycle( job.start() } + /** + * Reports and stops a session that remains externally owned. + * + * This does not adopt the session or mutate lifecycle-owned playback state. + * The application scope outlives the external owner, while [NonCancellable] + * and IO dispatch keep its final network writes off teardown callers. + */ + fun reportAndStopExternalSessionAsync( + sessionId: String, + positionSeconds: Double, + isPaused: Boolean, + ) { + val job = synchronized(externalFinalizationLock) { + pendingExternalFinalizations[sessionId] + ?.takeUnless { it.isCompleted } + ?: scope.launch( + context = NonCancellable + Dispatchers.IO, + start = CoroutineStart.LAZY, + ) { + runCatching { + sessionManager.reportProgress( + sessionId = sessionId, + position = positionSeconds, + isPaused = isPaused, + ) + } + runCatching { sessionManager.stopSession(sessionId) } + }.also { + pendingExternalFinalizations[sessionId] = it + } + } + job.invokeOnCompletion { + synchronized(externalFinalizationLock) { + if (pendingExternalFinalizations[sessionId] === job) { + pendingExternalFinalizations.remove(sessionId) + } + } + } + job.start() + } + private suspend fun awaitPendingStop() { val job = synchronized(pendingStopLock) { pendingStopJob } ?: return job.join() diff --git a/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/AudiobookPlayerTeardownSourceTest.kt b/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/AudiobookPlayerTeardownSourceTest.kt new file mode 100644 index 0000000000..c78685178d --- /dev/null +++ b/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/AudiobookPlayerTeardownSourceTest.kt @@ -0,0 +1,38 @@ +package org.siloserver.silo.common.player + +import java.io.File +import kotlin.test.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class AudiobookPlayerTeardownSourceTest { + private val viewModelSource = File( + requireNotNull(System.getProperty("user.dir")), + "src/androidMain/kotlin/org/siloserver/silo/common/player/AudiobookPlayerViewModel.kt", + ).readText() + + private val onClearedSource = viewModelSource + .substringAfter("override fun onCleared() {") + .substringBefore("\n companion object") + + @Test + fun `onCleared captures and submits external session finalization without blocking`() { + assertFalse(onClearedSource.contains("runBlocking")) + assertTrue(onClearedSource.contains("val state = _uiState.value")) + assertTrue(onClearedSource.contains("val sessionId = state.sessionId")) + assertTrue( + onClearedSource.contains( + "val positionSeconds = sessionLocalPosition(state)", + ), + ) + assertTrue(onClearedSource.contains("val isPaused = true")) + assertTrue( + onClearedSource.contains( + "playbackSessionLifecycle.reportAndStopExternalSessionAsync(", + ), + ) + assertTrue(onClearedSource.contains("sessionId = sessionId")) + assertTrue(onClearedSource.contains("positionSeconds = positionSeconds")) + assertTrue(onClearedSource.contains("isPaused = isPaused")) + } +} diff --git a/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/PlaybackSessionLifecycleTest.kt b/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/PlaybackSessionLifecycleTest.kt index a46d00570c..233bbf2227 100644 --- a/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/PlaybackSessionLifecycleTest.kt +++ b/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/PlaybackSessionLifecycleTest.kt @@ -352,6 +352,100 @@ class PlaybackSessionLifecycleTest { assertEquals(listOf("sess-old"), stopped) } + @Test + fun `external session finalization returns before reporting finishes and stops afterward`() = runTest { + val reportEntered = CompletableDeferred() + val releaseReport = CompletableDeferred() + val stopCompleted = CompletableDeferred() + val calls = mutableListOf() + val sessionMgr = object : FakeSessionManager() { + override suspend fun reportProgress( + sessionId: String, + position: Double, + isPaused: Boolean, + ): ApiResult { + calls += "report:$sessionId:$position:$isPaused" + reportEntered.complete(Unit) + releaseReport.await() + return ApiResult.Success(Unit) + } + + override suspend fun stopSession(sessionId: String): ApiResult { + calls += "stop:$sessionId" + stopCompleted.complete(Unit) + return ApiResult.Success(Unit) + } + } + val lifecycle = newLifecycle(sessionMgr, scope = backgroundScope) + + lifecycle.reportAndStopExternalSessionAsync( + sessionId = "audiobook-session", + positionSeconds = 42.25, + isPaused = true, + ) + + reportEntered.await() + assertEquals( + listOf("report:audiobook-session:42.25:true"), + calls, + "the non-blocking caller must return while progress reporting is suspended", + ) + + releaseReport.complete(Unit) + stopCompleted.await() + + assertEquals( + listOf( + "report:audiobook-session:42.25:true", + "stop:audiobook-session", + ), + calls, + ) + } + + @Test + fun `duplicate external session finalization is coalesced`() = runTest { + val reportEntered = CompletableDeferred() + val releaseReport = CompletableDeferred() + val stopCompleted = CompletableDeferred() + val sessionMgr = object : FakeSessionManager() { + override suspend fun reportProgress( + sessionId: String, + position: Double, + isPaused: Boolean, + ): ApiResult { + progressCallCount++ + reportEntered.complete(Unit) + releaseReport.await() + return ApiResult.Success(Unit) + } + + override suspend fun stopSession(sessionId: String): ApiResult { + val result = super.stopSession(sessionId) + stopCompleted.complete(Unit) + return result + } + } + val lifecycle = newLifecycle(sessionMgr, scope = backgroundScope) + + repeat(2) { + lifecycle.reportAndStopExternalSessionAsync( + sessionId = "audiobook-session", + positionSeconds = 42.25, + isPaused = true, + ) + } + + reportEntered.await() + assertEquals(1, sessionMgr.progressCallCount) + + releaseReport.complete(Unit) + stopCompleted.await() + + assertEquals(1, sessionMgr.progressCallCount) + assertEquals(1, sessionMgr.stopCallCount) + } + @Test fun `cancelled adoption closes the allocated server session`() = runTest { val oldStopEntered = CompletableDeferred() diff --git a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/di/AndroidModule.kt b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/di/AndroidModule.kt index f929e031f4..765d8fc0ee 100644 --- a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/di/AndroidModule.kt +++ b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/di/AndroidModule.kt @@ -445,6 +445,7 @@ val androidModule = module { org.siloserver.silo.common.player.AudiobookPlayerViewModel( catalogRepository = get(), playbackSessionManager = get(), + playbackSessionLifecycle = get(), capabilityDetector = get(), bookmarksStore = get(), userItemStatePort = get(), diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/di/AndroidTvModule.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/di/AndroidTvModule.kt index b468abebc7..2b2bde2bac 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/di/AndroidTvModule.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/di/AndroidTvModule.kt @@ -207,6 +207,7 @@ val androidTvModule = module { org.siloserver.silo.common.player.AudiobookPlayerViewModel( catalogRepository = get(), playbackSessionManager = get(), + playbackSessionLifecycle = get(), capabilityDetector = get(), bookmarksStore = get(), userItemStatePort = get(), From b02ea4f4659b6fd6542a45278681f66c451c9975 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 10:17:47 +0200 Subject: [PATCH 44/65] fix(tv): preserve subtitle title-safe positions --- .../silo/common/player/SubtitleManager.kt | 8 ++++- .../player/SubtitleManagerAppearanceTest.kt | 36 +++++++++++++++++-- 2 files changed, 41 insertions(+), 3 deletions(-) diff --git a/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SubtitleManager.kt b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SubtitleManager.kt index 75fa58bc8a..c47ac78bf7 100644 --- a/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SubtitleManager.kt +++ b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SubtitleManager.kt @@ -341,7 +341,13 @@ class SubtitleManager( SubtitlePositionPreset.LowerThird -> 0.18f SubtitlePositionPreset.Top -> 0.74f } - return (base - titleSafeFraction).coerceAtLeast(0.02f) + // The title-safe inset moves the subtitle surface in by f on both + // edges, leaving a height of (1 - 2f). Preserve the original physical + // preset by solving f + p(1 - 2f) = base for the new padding p. + val safeFraction = titleSafeFraction + val remainingScale = 1f - 2f * safeFraction + if (remainingScale <= 0f) return base + return ((base - safeFraction) / remainingScale).coerceAtLeast(0.02f) } private fun parseHexColor(hex: String, alpha: Int = 255): Int { diff --git a/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/SubtitleManagerAppearanceTest.kt b/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/SubtitleManagerAppearanceTest.kt index 7fdabff5c5..66c800d592 100644 --- a/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/SubtitleManagerAppearanceTest.kt +++ b/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/SubtitleManagerAppearanceTest.kt @@ -7,6 +7,7 @@ import androidx.media3.ui.CaptionStyleCompat import org.siloserver.silo.model.settings.SubtitleAppearance import org.siloserver.silo.model.settings.SubtitleBackgroundStylePreset import org.siloserver.silo.model.settings.SubtitleFontSizePreset +import org.siloserver.silo.model.settings.SubtitlePositionPreset import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import kotlin.test.Test @@ -46,7 +47,7 @@ class SubtitleManagerAppearanceTest { fun bottomSubtitlesUseTheReferenceSafeMargin() { val method = SubtitleManager::class.java.getDeclaredMethod( "bottomPaddingFor", - org.siloserver.silo.model.settings.SubtitlePositionPreset::class.java, + SubtitlePositionPreset::class.java, ) method.isAccessible = true @@ -54,11 +55,42 @@ class SubtitleManagerAppearanceTest { 0.09f, method.invoke( SubtitleManager(), - org.siloserver.silo.model.settings.SubtitlePositionPreset.Bottom, + SubtitlePositionPreset.Bottom, ) as Float, ) } + @Test + fun titleSafeCompensationDoesNotDoubleShiftTopSubtitles() { + val manager = SubtitleManager().apply { + titleSafeFraction = 0.05f + } + val method = SubtitleManager::class.java.getDeclaredMethod( + "bottomPaddingFor", + SubtitlePositionPreset::class.java, + ) + method.isAccessible = true + + // The padding fraction is evaluated inside a surface scaled to 90% of + // the original video height. Preserve the original physical presets: + // f + p(1 - 2f) = base, so p = (base - f) / (1 - 2f). + assertEquals( + expected = (0.74f - 0.05f) / 0.90f, + actual = method.invoke(manager, SubtitlePositionPreset.Top) as Float, + absoluteTolerance = 0.0001f, + ) + assertEquals( + expected = (0.09f - 0.05f) / 0.90f, + actual = method.invoke(manager, SubtitlePositionPreset.Bottom) as Float, + absoluteTolerance = 0.0001f, + ) + assertEquals( + expected = (0.18f - 0.05f) / 0.90f, + actual = method.invoke(manager, SubtitlePositionPreset.LowerThird) as Float, + absoluteTolerance = 0.0001f, + ) + } + @Test fun boxBackgroundStyleAppliesConfiguredBackgroundAlpha() { val style = captionStyleFor( From fc13dfe3f5beba62ba9be51a82967c49c01a9fff Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 10:17:58 +0200 Subject: [PATCH 45/65] chore(shared): remove unused no-op auth plugin --- .../org/siloserver/silo/network/AuthInterceptor.kt | 11 ----------- 1 file changed, 11 deletions(-) delete mode 100644 shared/src/commonMain/kotlin/org/siloserver/silo/network/AuthInterceptor.kt diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/network/AuthInterceptor.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/network/AuthInterceptor.kt deleted file mode 100644 index 56a194cb1f..0000000000 --- a/shared/src/commonMain/kotlin/org/siloserver/silo/network/AuthInterceptor.kt +++ /dev/null @@ -1,11 +0,0 @@ -package org.siloserver.silo.network - -import io.ktor.client.plugins.api.* - -/** - * Ktor plugin that attaches auth headers to every request. - * Full implementation provided by Agent 2 in AuthInterceptorImpl.kt. - */ -val SiloAuth = createClientPlugin("SiloAuth") { - // Stub - Agent 2 provides the real implementation -} From 576c2a6a91c9b7815eae8a06920004d3531dc917 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 10:19:39 +0200 Subject: [PATCH 46/65] fix(watch-together): wait for session attach echo --- .../ui/screens/player/RoomSyncController.kt | 21 ++++++++++++++++--- .../ui/screens/player/TvRoomSyncController.kt | 21 ++++++++++++++++--- .../silo/watchtogether/RoomDeliveryLatch.kt | 7 +++++++ .../watchtogether/RoomDeliveryLatchTest.kt | 15 +++++++++++++ 4 files changed, 58 insertions(+), 6 deletions(-) diff --git a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/RoomSyncController.kt b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/RoomSyncController.kt index a76005455c..f07d620215 100644 --- a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/RoomSyncController.kt +++ b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/RoomSyncController.kt @@ -148,8 +148,16 @@ class RoomSyncController( while (isActive) { val state = viewModel.uiState.value val sessionId = state.sessionId + val deliveryKey = deliveryLatch.keyOrNull( + repository.connectionState.value, + sessionId, + ) + val serverAttached = deliveryLatch.isServerAttached( + deliveryKey, + repository.roomSnapshot.value?.attachedSessionId, + ) val now = monotonicMs() - if (sessionId != null && + if (serverAttached && shouldEmitStateReport( now, lastReportMs, @@ -160,7 +168,7 @@ class RoomSyncController( ) { lastReportMs = now repository.stateReport( - sessionId = sessionId, + sessionId = deliveryKey!!.playbackSessionId, positionSeconds = state.position, isPaused = state.isPaused, ) @@ -186,7 +194,14 @@ class RoomSyncController( if (playbackState != RoomPlaybackState.Waiting || key == null) { return@collectLatest } - while (!deliveryLatch.isAttached(key)) delay(10) + while ( + !deliveryLatch.isServerAttached( + key, + repository.roomSnapshot.value?.attachedSessionId, + ) + ) { + delay(10) + } while (isActive && deliveryLatch.needsReadiness(key, buffering)) { val currentState = viewModel.uiState.value val delivered = if (buffering) { diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvRoomSyncController.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvRoomSyncController.kt index 6934983493..adf7c02761 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvRoomSyncController.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvRoomSyncController.kt @@ -205,8 +205,16 @@ class TvRoomSyncController( while (isActive) { val state = viewModel.uiState.value val sessionId = state.sessionId + val deliveryKey = deliveryLatch.keyOrNull( + repository.connectionState.value, + sessionId, + ) + val serverAttached = deliveryLatch.isServerAttached( + deliveryKey, + repository.roomSnapshot.value?.attachedSessionId, + ) val now = monotonicMs() - if (sessionId != null && + if (serverAttached && tvShouldEmitStateReport( now, lastReportMs, @@ -217,7 +225,7 @@ class TvRoomSyncController( ) { lastReportMs = now repository.stateReport( - sessionId = sessionId, + sessionId = deliveryKey!!.playbackSessionId, positionSeconds = state.position, isPaused = state.isPaused, ) @@ -243,7 +251,14 @@ class TvRoomSyncController( if (playbackState != RoomPlaybackState.Waiting || key == null) { return@collectLatest } - while (!deliveryLatch.isAttached(key)) delay(10) + while ( + !deliveryLatch.isServerAttached( + key, + repository.roomSnapshot.value?.attachedSessionId, + ) + ) { + delay(10) + } while (isActive && deliveryLatch.needsReadiness(key, buffering)) { val currentState = viewModel.uiState.value val delivered = if (buffering) { diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/watchtogether/RoomDeliveryLatch.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/watchtogether/RoomDeliveryLatch.kt index 5596f21bcd..1b08972465 100644 --- a/shared/src/commonMain/kotlin/org/siloserver/silo/watchtogether/RoomDeliveryLatch.kt +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/watchtogether/RoomDeliveryLatch.kt @@ -45,6 +45,13 @@ class RoomDeliveryLatch { fun isAttached(key: RoomDeliveryKey?): Boolean = key != null && attached == key + /** + * Session-scoped traffic is safe only after the attach frame was delivered + * and the server echoed that exact session in a room snapshot. + */ + fun isServerAttached(key: RoomDeliveryKey?, echoedSessionId: String?): Boolean = + isAttached(key) && echoedSessionId == key?.playbackSessionId + fun recordAttach(key: RoomDeliveryKey, delivered: Boolean) { if (delivered) attached = key } diff --git a/shared/src/commonTest/kotlin/org/siloserver/silo/watchtogether/RoomDeliveryLatchTest.kt b/shared/src/commonTest/kotlin/org/siloserver/silo/watchtogether/RoomDeliveryLatchTest.kt index e0ddf18704..e8bafb2b5a 100644 --- a/shared/src/commonTest/kotlin/org/siloserver/silo/watchtogether/RoomDeliveryLatchTest.kt +++ b/shared/src/commonTest/kotlin/org/siloserver/silo/watchtogether/RoomDeliveryLatchTest.kt @@ -77,6 +77,21 @@ class RoomDeliveryLatchTest { assertFalse(latch.isAttached(key)) } + @Test + fun `session traffic waits for both attach delivery and the server echo`() { + val latch = RoomDeliveryLatch() + val key = assertNotNull(latch.keyOrNull(open1, "session-a")) + + assertFalse(latch.isServerAttached(key, echoedSessionId = null)) + latch.recordAttach(key, delivered = true) + assertFalse(latch.isServerAttached(key, echoedSessionId = null)) + assertFalse(latch.isServerAttached(key, echoedSessionId = "session-b")) + assertTrue(latch.isServerAttached(key, echoedSessionId = "session-a")) + + val replacementEpoch = assertNotNull(latch.keyOrNull(open2, "session-a")) + assertFalse(latch.isServerAttached(replacementEpoch, echoedSessionId = "session-a")) + } + @Test fun `delayed command for session A cannot mutate replacement session B`() { val command = TransportCommand( From 632a3f08745d6a67247fb1a9ee2db3b5f5a74303 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 10:21:24 +0200 Subject: [PATCH 47/65] fix(android): clear failed download progress --- .../silo/common/downloads/DownloadWorker.kt | 31 ++++++++++---- .../downloads/DownloadWorkerProgressTest.kt | 42 +++++++++++++++++++ 2 files changed, 65 insertions(+), 8 deletions(-) create mode 100644 android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/downloads/DownloadWorkerProgressTest.kt diff --git a/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/downloads/DownloadWorker.kt b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/downloads/DownloadWorker.kt index 5f5fd2a40d..f7a5ab8019 100644 --- a/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/downloads/DownloadWorker.kt +++ b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/downloads/DownloadWorker.kt @@ -20,6 +20,7 @@ import androidx.work.OutOfQuotaPolicy import androidx.work.WorkManager import androidx.work.workDataOf import org.siloserver.silo.model.download.DownloadStatus +import org.siloserver.silo.model.download.DownloadRecord import org.siloserver.silo.repository.DownloadsRepository import io.ktor.client.HttpClient import io.ktor.client.plugins.HttpTimeoutConfig @@ -41,6 +42,16 @@ import java.io.IOException import java.net.URLDecoder import java.util.concurrent.TimeUnit +internal fun DownloadRecord.withWorkerStatus( + status: String, + bytesSent: Long? = null, + fileSize: Long? = null, +): DownloadRecord = copy( + status = status, + bytesSent = bytesSent ?: this.bytesSent, + fileSize = fileSize ?: this.fileSize, +) + /** * Streams `GET /api/v1/downloads/{id}/file` to the local * `/downloads////` @@ -338,7 +349,13 @@ class DownloadWorker( // Best-effort: publish failed state into the repo + sidecar. val record = if (uiPushAllowed(serverId, profileId)) repository.recordForFile(fileId) else null if (record != null) { - repository.upsertLocal(record.copy(status = DownloadStatus.Failed.wire)) + repository.upsertLocal( + record.withWorkerStatus( + status = DownloadStatus.Failed.wire, + bytesSent = 0, + fileSize = 0, + ), + ) } updateSidecarStatus( serverId, profileId, fileId, @@ -361,8 +378,8 @@ class DownloadWorker( profileId: String, fileId: Int, status: String, - bytesSent: Long, - fileSize: Long, + bytesSent: Long? = null, + fileSize: Long? = null, localUri: String? = null, fileName: String? = null, // null = keep existing; "" = clear (download finished/failed); else set. @@ -373,10 +390,10 @@ class DownloadWorker( metadataStore.writeSidecar( serverId, profileId, existing.copy( - record = existing.record.copy( + record = existing.record.withWorkerStatus( status = status, - bytesSent = if (bytesSent > 0) bytesSent else existing.record.bytesSent, - fileSize = if (fileSize > 0) fileSize else existing.record.fileSize, + bytesSent = bytesSent, + fileSize = fileSize, ), localUri = localUri ?: existing.localUri, fileName = fileName?.takeIf { it.isNotBlank() } ?: existing.fileName, @@ -406,8 +423,6 @@ class DownloadWorker( updateSidecarStatus( serverId, profileId, fileId, status = DownloadStatus.Downloading.wire, - bytesSent = 0, - fileSize = 0, localUri = localUri, resumeValidator = validator?.takeIf { it.isNotBlank() } ?: "", ) diff --git a/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/downloads/DownloadWorkerProgressTest.kt b/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/downloads/DownloadWorkerProgressTest.kt new file mode 100644 index 0000000000..ffedcc2c47 --- /dev/null +++ b/android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/downloads/DownloadWorkerProgressTest.kt @@ -0,0 +1,42 @@ +package org.siloserver.silo.common.downloads + +import org.siloserver.silo.model.download.DownloadRecord +import org.siloserver.silo.model.download.DownloadStatus +import kotlin.test.Test +import kotlin.test.assertEquals + +class DownloadWorkerProgressTest { + private val record = DownloadRecord( + id = "download-1", + contentId = "content-1", + mediaFileId = 7, + fileSize = 10_000, + bytesSent = 4_000, + kind = "download", + status = DownloadStatus.Downloading.wire, + createdAt = "2026-07-28T00:00:00Z", + ) + + @Test + fun `permanent failure explicitly clears stale progress`() { + val failed = record.withWorkerStatus( + status = DownloadStatus.Failed.wire, + bytesSent = 0, + fileSize = 0, + ) + + assertEquals(DownloadStatus.Failed.wire, failed.status) + assertEquals(0, failed.bytesSent) + assertEquals(0, failed.fileSize) + } + + @Test + fun `omitted progress preserves resume state`() { + val downloading = record.withWorkerStatus( + status = DownloadStatus.Downloading.wire, + ) + + assertEquals(4_000, downloading.bytesSent) + assertEquals(10_000, downloading.fileSize) + } +} From ff8b64863bf2fe92573003f1befcf60d3c9c7923 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 11:23:50 +0200 Subject: [PATCH 48/65] fix(watch-together): bind attach echoes to connection epoch --- .../ui/screens/player/RoomSyncController.kt | 4 +- .../ui/screens/player/TvRoomSyncController.kt | 4 +- .../repository/WatchTogetherRepository.kt | 18 ++++++++ .../silo/watchtogether/RoomDeliveryLatch.kt | 14 +++++- .../repository/WatchTogetherRepositoryTest.kt | 37 +++++++++++++++ .../watchtogether/RoomDeliveryLatchTest.kt | 45 ++++++++++++++++--- 6 files changed, 111 insertions(+), 11 deletions(-) diff --git a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/RoomSyncController.kt b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/RoomSyncController.kt index f07d620215..296394ffe1 100644 --- a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/RoomSyncController.kt +++ b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/RoomSyncController.kt @@ -154,7 +154,7 @@ class RoomSyncController( ) val serverAttached = deliveryLatch.isServerAttached( deliveryKey, - repository.roomSnapshot.value?.attachedSessionId, + repository.roomDeliveryEcho.value, ) val now = monotonicMs() if (serverAttached && @@ -197,7 +197,7 @@ class RoomSyncController( while ( !deliveryLatch.isServerAttached( key, - repository.roomSnapshot.value?.attachedSessionId, + repository.roomDeliveryEcho.value, ) ) { delay(10) diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvRoomSyncController.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvRoomSyncController.kt index adf7c02761..739f3f9c0b 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvRoomSyncController.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvRoomSyncController.kt @@ -211,7 +211,7 @@ class TvRoomSyncController( ) val serverAttached = deliveryLatch.isServerAttached( deliveryKey, - repository.roomSnapshot.value?.attachedSessionId, + repository.roomDeliveryEcho.value, ) val now = monotonicMs() if (serverAttached && @@ -254,7 +254,7 @@ class TvRoomSyncController( while ( !deliveryLatch.isServerAttached( key, - repository.roomSnapshot.value?.attachedSessionId, + repository.roomDeliveryEcho.value, ) ) { delay(10) diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/repository/WatchTogetherRepository.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/repository/WatchTogetherRepository.kt index b91c96a485..d9a7e22047 100644 --- a/shared/src/commonMain/kotlin/org/siloserver/silo/repository/WatchTogetherRepository.kt +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/repository/WatchTogetherRepository.kt @@ -18,6 +18,7 @@ import org.siloserver.silo.network.RoomRealtimeEvent import org.siloserver.silo.network.WatchTogetherRealtimeClient import org.siloserver.silo.network.api.WatchTogetherApi import org.siloserver.silo.util.parseRfc3339ToEpochMillis +import org.siloserver.silo.watchtogether.RoomDeliveryEcho import org.siloserver.silo.watchtogether.RoomDeliveryLatch import org.siloserver.silo.watchtogether.WatchTogetherEntryGateway import org.siloserver.silo.watchtogether.RoomSessionRepository @@ -120,9 +121,11 @@ class WatchTogetherRepository( private var activeConnectionOwner: Long? = null private val _roomSnapshot = MutableStateFlow(null) private val _suggestions = MutableStateFlow>(emptyList()) + private val _roomDeliveryEcho = MutableStateFlow(null) override val roomSnapshot: StateFlow = _roomSnapshot.asStateFlow() val suggestions: StateFlow> = _suggestions.asStateFlow() + val roomDeliveryEcho: StateFlow = _roomDeliveryEcho.asStateFlow() private val _connectionState = MutableStateFlow(WatchTogetherConnectionState()) val connectionState: StateFlow = _connectionState.asStateFlow() @kotlin.concurrent.Volatile @@ -257,6 +260,7 @@ class WatchTogetherRepository( _suggestions.value = emptyList() _roomClosedReason.value = null _roomSnapshot.value = data.room + _roomDeliveryEcho.value = null _connectionState.value = WatchTogetherConnectionState(generation = installed.generation) realtimeConnectionId = null refreshTransportAuthorizationLocked() @@ -375,6 +379,7 @@ class WatchTogetherRepository( val published = stateMutex.withLock { if (!isCurrentLocked(lease)) return@withLock false _roomSnapshot.value = result.data.room + _roomDeliveryEcho.value = null refreshTransportAuthorizationLocked() true } @@ -563,6 +568,7 @@ class WatchTogetherRepository( terminalGeneration = lease.generation _roomClosedReason.value = event.reason ?: "room_closed" _roomSnapshot.value = null + _roomDeliveryEcho.value = null refreshTransportAuthorizationLocked() } } @@ -621,6 +627,7 @@ class WatchTogetherRepository( terminalGeneration = lease.generation _roomClosedReason.value = "connection_lost" _roomSnapshot.value = null + _roomDeliveryEcho.value = null refreshTransportAuthorizationLocked() } } @@ -708,6 +715,16 @@ class WatchTogetherRepository( is RoomRealtimeEvent.SnapshotEvent -> if (event.room.roomId == lease.roomId) { _roomSnapshot.value = event.room + _roomDeliveryEcho.value = event.room.attachedSessionId + ?.takeIf { it.isNotBlank() } + ?.let { sessionId -> + val connection = _connectionState.value + RoomDeliveryEcho( + connectionGeneration = connection.generation, + connectionEpoch = connection.epoch, + playbackSessionId = sessionId, + ) + } refreshTransportAuthorizationLocked() } is RoomRealtimeEvent.SuggestionsEvent -> applySuggestions(event.suggestions, fromBroadcast = true) @@ -743,6 +760,7 @@ class WatchTogetherRepository( binding = null terminalGeneration = null _roomSnapshot.value = null + _roomDeliveryEcho.value = null _suggestions.value = emptyList() _roomClosedReason.value = null votedIds.clear() diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/watchtogether/RoomDeliveryLatch.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/watchtogether/RoomDeliveryLatch.kt index 1b08972465..43a227c90c 100644 --- a/shared/src/commonMain/kotlin/org/siloserver/silo/watchtogether/RoomDeliveryLatch.kt +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/watchtogether/RoomDeliveryLatch.kt @@ -16,6 +16,12 @@ data class RoomDeliveryKey( val playbackSessionId: String, ) +data class RoomDeliveryEcho( + val connectionGeneration: Long, + val connectionEpoch: Long, + val playbackSessionId: String, +) + /** * Successful-delivery latches for one player controller. * @@ -49,8 +55,12 @@ class RoomDeliveryLatch { * Session-scoped traffic is safe only after the attach frame was delivered * and the server echoed that exact session in a room snapshot. */ - fun isServerAttached(key: RoomDeliveryKey?, echoedSessionId: String?): Boolean = - isAttached(key) && echoedSessionId == key?.playbackSessionId + fun isServerAttached(key: RoomDeliveryKey?, echo: RoomDeliveryEcho?): Boolean = + isAttached(key) && + echo != null && + echo.connectionGeneration == key?.connectionGeneration && + echo.connectionEpoch == key.connectionEpoch && + echo.playbackSessionId == key.playbackSessionId fun recordAttach(key: RoomDeliveryKey, delivered: Boolean) { if (delivered) attached = key diff --git a/shared/src/commonTest/kotlin/org/siloserver/silo/repository/WatchTogetherRepositoryTest.kt b/shared/src/commonTest/kotlin/org/siloserver/silo/repository/WatchTogetherRepositoryTest.kt index 42bd8cdbfd..44a066cda1 100644 --- a/shared/src/commonTest/kotlin/org/siloserver/silo/repository/WatchTogetherRepositoryTest.kt +++ b/shared/src/commonTest/kotlin/org/siloserver/silo/repository/WatchTogetherRepositoryTest.kt @@ -1192,6 +1192,43 @@ class WatchTogetherRepositoryTest { job.cancel() } + @Test + fun `attach echo retains its observed epoch until the reconnect receives a fresh snapshot`() = runTest { + val attachedSnapshot = snapshot().copy(attachedSessionId = "playback-1") + val realtime = FakeRealtime().apply { + connectBehavior = { attempt -> + if (attempt == 1) { + flow { + emit(RoomRealtimeEvent.Opened) + emit(RoomRealtimeEvent.SnapshotEvent(attachedSnapshot)) + emit(RoomRealtimeEvent.TransportTerminated()) + } + } else { + events.asSharedFlow() + } + } + } + val repository = repo(realtime = realtime) + repository.createRoom(CreateRoomRequest()) + val job = launch { repository.connect("room-1") } + runCurrent() + + assertEquals(1L, repository.roomDeliveryEcho.value?.connectionEpoch) + advanceTimeBy(500) + runCurrent() + realtime.events.emit(RoomRealtimeEvent.Opened) + runCurrent() + + assertEquals(2L, repository.connectionState.value.epoch) + assertEquals(1L, repository.roomDeliveryEcho.value?.connectionEpoch) + + realtime.events.emit(RoomRealtimeEvent.SnapshotEvent(attachedSnapshot)) + runCurrent() + + assertEquals(2L, repository.roomDeliveryEcho.value?.connectionEpoch) + job.cancel() + } + @Test fun `send fails before the active connection reports writable`() = runTest { val realtime = FakeRealtime() diff --git a/shared/src/commonTest/kotlin/org/siloserver/silo/watchtogether/RoomDeliveryLatchTest.kt b/shared/src/commonTest/kotlin/org/siloserver/silo/watchtogether/RoomDeliveryLatchTest.kt index e8bafb2b5a..842ca21bdf 100644 --- a/shared/src/commonTest/kotlin/org/siloserver/silo/watchtogether/RoomDeliveryLatchTest.kt +++ b/shared/src/commonTest/kotlin/org/siloserver/silo/watchtogether/RoomDeliveryLatchTest.kt @@ -82,14 +82,49 @@ class RoomDeliveryLatchTest { val latch = RoomDeliveryLatch() val key = assertNotNull(latch.keyOrNull(open1, "session-a")) - assertFalse(latch.isServerAttached(key, echoedSessionId = null)) + assertFalse(latch.isServerAttached(key, echo = null)) latch.recordAttach(key, delivered = true) - assertFalse(latch.isServerAttached(key, echoedSessionId = null)) - assertFalse(latch.isServerAttached(key, echoedSessionId = "session-b")) - assertTrue(latch.isServerAttached(key, echoedSessionId = "session-a")) + assertFalse(latch.isServerAttached(key, echo = null)) + assertFalse( + latch.isServerAttached( + key, + RoomDeliveryEcho(7, 1, "session-b"), + ), + ) + assertTrue( + latch.isServerAttached( + key, + RoomDeliveryEcho(7, 1, "session-a"), + ), + ) val replacementEpoch = assertNotNull(latch.keyOrNull(open2, "session-a")) - assertFalse(latch.isServerAttached(replacementEpoch, echoedSessionId = "session-a")) + assertFalse( + latch.isServerAttached( + replacementEpoch, + RoomDeliveryEcho(7, 1, "session-a"), + ), + ) + } + + @Test + fun `stale prior epoch echo cannot authorize a newly delivered reconnect attach`() { + val latch = RoomDeliveryLatch() + val firstEpoch = assertNotNull(latch.keyOrNull(open1, "session-a")) + latch.recordAttach(firstEpoch, delivered = true) + val firstEcho = RoomDeliveryEcho(7, 1, "session-a") + assertTrue(latch.isServerAttached(firstEpoch, firstEcho)) + + val replacementEpoch = assertNotNull(latch.keyOrNull(open2, "session-a")) + latch.recordAttach(replacementEpoch, delivered = true) + + assertFalse(latch.isServerAttached(replacementEpoch, firstEcho)) + assertTrue( + latch.isServerAttached( + replacementEpoch, + RoomDeliveryEcho(7, 2, "session-a"), + ), + ) } @Test From f822d22c3e0c7702add38176e6bb60df87f76425 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Mon, 27 Jul 2026 23:54:07 +0200 Subject: [PATCH 49/65] test(tv): keep subtitle cleanup scheduler single-threaded --- .../SubtitleTransactionIntegrationTest.kt | 90 ++++++++++++++----- 1 file changed, 67 insertions(+), 23 deletions(-) diff --git a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/player/SubtitleTransactionIntegrationTest.kt b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/player/SubtitleTransactionIntegrationTest.kt index a54d48c112..3a728eac46 100644 --- a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/player/SubtitleTransactionIntegrationTest.kt +++ b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/player/SubtitleTransactionIntegrationTest.kt @@ -11,15 +11,18 @@ import io.ktor.http.HttpStatusCode import io.ktor.http.headersOf import io.ktor.serialization.kotlinx.json.json import java.util.Collections +import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicInteger import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.SharedFlow +import kotlinx.coroutines.launch import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.TestCoroutineScheduler import kotlinx.coroutines.test.TestScope @@ -27,6 +30,7 @@ import kotlinx.coroutines.test.runCurrent import kotlinx.coroutines.test.runTest import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeout +import kotlinx.coroutines.yield import kotlinx.serialization.encodeToString import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.int @@ -83,6 +87,30 @@ import kotlin.test.assertFalse import kotlin.test.assertIs import kotlin.test.assertNull import kotlin.test.assertTrue +import kotlin.time.Duration.Companion.milliseconds +import kotlin.time.TimeSource + +private suspend fun awaitHarnessCondition( + transactionScheduler: TestCoroutineScheduler, + cleanupScheduler: TestCoroutineScheduler, + timeoutMillis: Long, + condition: suspend () -> Boolean, +) { + val started = TimeSource.Monotonic.markNow() + while (!condition()) { + // runTest already owns and drives its transaction scheduler. Driving it + // again from another thread can execute nominally single-threaded test + // tasks concurrently. Only a genuinely separate manager-cleanup + // scheduler needs manual progress here. + if (cleanupScheduler !== transactionScheduler) { + cleanupScheduler.runCurrent() + } + if (started.elapsedNow() >= timeoutMillis.milliseconds) { + throw AssertionError("Timed out waiting for subtitle transaction cleanup") + } + yield() + } +} @OptIn(ExperimentalCoroutinesApi::class) @Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE") @@ -168,10 +196,36 @@ class SubtitleTransactionIntegrationTest { assertEquals(mapOf("s1" to 1), harness.stopCounts()) harness.assertNoOrphans() } finally { - cleanupJob.cancel() + cleanupJob.cancelAndJoin() } } + @Test + fun `cleanup wait never drives the shared transaction scheduler concurrently`() = runTest { + val firstTaskRunning = AtomicBoolean(false) + val overlapObserved = AtomicBoolean(false) + val completed = AtomicBoolean(false) + + backgroundScope.launch { + firstTaskRunning.set(true) + Thread.sleep(100) + firstTaskRunning.set(false) + } + backgroundScope.launch { + overlapObserved.set(firstTaskRunning.get()) + completed.set(true) + } + + awaitHarnessCondition( + transactionScheduler = testScheduler, + cleanupScheduler = testScheduler, + timeoutMillis = EVENT_TIMEOUT_MS, + condition = completed::get, + ) + + assertFalse(overlapObserved.get()) + } + @Test fun `off supersedes an in-flight sidecar and replans from the committed session`() = runTest { val firstEntered = CompletableDeferred() @@ -719,17 +773,12 @@ class SubtitleTransactionIntegrationTest { suspend fun awaitStopped(sessionId: String) { if (sessionId in stoppedSessions) return - withContext(Dispatchers.Default) { - withTimeout(EVENT_TIMEOUT_MS) { - while (sessionId !in stoppedSessions) { - transactionScheduler.runCurrent() - if (committedSessionCleanupScheduler !== transactionScheduler) { - committedSessionCleanupScheduler.runCurrent() - } - kotlinx.coroutines.yield() - } - } - } + awaitHarnessCondition( + transactionScheduler = transactionScheduler, + cleanupScheduler = committedSessionCleanupScheduler, + timeoutMillis = EVENT_TIMEOUT_MS, + condition = { sessionId in stoppedSessions }, + ) } suspend fun awaitReplans(count: Int) { @@ -768,17 +817,12 @@ class SubtitleTransactionIntegrationTest { } suspend fun assertNoOrphans() { - withContext(Dispatchers.Default) { - withTimeout(EVENT_TIMEOUT_MS) { - while (manager.orphanedSessionIdsForTest().isNotEmpty()) { - transactionScheduler.runCurrent() - if (committedSessionCleanupScheduler !== transactionScheduler) { - committedSessionCleanupScheduler.runCurrent() - } - kotlinx.coroutines.yield() - } - } - } + awaitHarnessCondition( + transactionScheduler = transactionScheduler, + cleanupScheduler = committedSessionCleanupScheduler, + timeoutMillis = EVENT_TIMEOUT_MS, + condition = { manager.orphanedSessionIdsForTest().isEmpty() }, + ) assertEquals(emptySet(), manager.orphanedSessionIdsForTest()) } From a49170aa47f18baa3ba669c6ba2bfcd17b7dabdc Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 12:00:32 +0200 Subject: [PATCH 50/65] docs: specify PR 126 review remediation --- ...28-pr-126-coderabbit-remediation-design.md | 73 +++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 docs/superpowers/specs/2026-07-28-pr-126-coderabbit-remediation-design.md diff --git a/docs/superpowers/specs/2026-07-28-pr-126-coderabbit-remediation-design.md b/docs/superpowers/specs/2026-07-28-pr-126-coderabbit-remediation-design.md new file mode 100644 index 0000000000..e3d00df422 --- /dev/null +++ b/docs/superpowers/specs/2026-07-28-pr-126-coderabbit-remediation-design.md @@ -0,0 +1,73 @@ +# PR #126 CodeRabbit Remediation Design + +## Goal + +Resolve every substantiated CodeRabbit finding on PR #126 without changing +deliberate request-sharing behavior or adding unrelated release scope. + +## Scope and approach + +The correction remains on `fix/tv-for-you-cold-navigation` and follows the +existing phone, TV, shared-repository, and Watch Together boundaries. Behavioral +changes are covered by focused regression tests before production changes. +Documentation and test-only cleanup remain separate from behavioral assertions +so failures identify the responsible correction. + +The implementation will: + +- Forward the shell Up fallback from the Alphabet library tab to its alphabet + rail, matching the Browse tab. +- Advance the For You entry request with a `null` selection whenever the + top-level For You destination is explicitly selected, so Watchlist or + Favorites state is not retained. +- Make the initial TV marquee seed sensitive to section identity while + preserving the rule that settled real focus always wins over a page-entry + seed. A refresh may update a stale page-entry identity, but must not replace + focused content. +- Accept IMDb ratings only when finite and within `(0, 10]` on both phone and + TV. Invalid rating and invalid duration cases will be tested independently. +- Make Watch Together delivery-key nullability explicit at the latch and player + reporting call sites without changing attach, cadence, or delivery semantics. +- Remove machine-specific paths from the committed SDD report and correct the + stale plan references and wording identified by CodeRabbit. +- Apply small behavior-preserving helper extractions only where they directly + address a review comment and reduce duplicated validation or test setup. +- Keep the existing shared in-flight recommendation request behavior. A + superseded caller may discard its result, but it must not cancel work shared + with another caller. + +## Finding disposition + +The Calendar fallback finding is already corrected on the current PR head and +will receive verification rather than another code change. The claimed +`RoomDeliveryLatch` compilation failure is disproven by both local compilation +and hosted Unit Tests; explicit null binding will nevertheless make the +invariant visible and remove the ambiguity that prompted the comment. + +Generic requests to split the PR or increase repository-wide docstring coverage +are not defects in the changed behavior and are outside this remediation. + +## Testing + +Focused tests will cover: + +- Alphabet and Browse fallback forwarding parity. +- Explicit For You root selection after Watchlist and Favorites entry. +- Marquee reseeding for a changed row identity, including protection of + real-focused content. +- Phone and TV rating upper bounds. +- Mixed valid-duration/invalid-rating and invalid-duration/valid-rating cases. +- Nullable and mismatched Watch Together delivery keys. + +After focused RED/GREEN cycles, the relevant phone, TV, shared, and +Android-shared unit suites will run, followed by the repository supply-chain +policy checks and phone/TV release compilation used by this branch. No APK will +be installed or deployed as part of this remediation. + +## Completion criteria + +The branch must be clean, all focused and full verification commands must pass, +an independent reviewer must report no unresolved critical or important issue, +and PR #126 must accurately reflect the added correction commit and current +check state. Proven false positives will be documented rather than addressed by +semantic changes. From 3b57abb47c902ef4d97a70a3c109c6980b6b5734 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 12:04:23 +0200 Subject: [PATCH 51/65] docs: plan PR 126 review remediation --- ...026-07-28-pr-126-coderabbit-remediation.md | 524 ++++++++++++++++++ 1 file changed, 524 insertions(+) create mode 100644 docs/superpowers/plans/2026-07-28-pr-126-coderabbit-remediation.md diff --git a/docs/superpowers/plans/2026-07-28-pr-126-coderabbit-remediation.md b/docs/superpowers/plans/2026-07-28-pr-126-coderabbit-remediation.md new file mode 100644 index 0000000000..8ea812e10e --- /dev/null +++ b/docs/superpowers/plans/2026-07-28-pr-126-coderabbit-remediation.md @@ -0,0 +1,524 @@ +# PR #126 CodeRabbit Remediation Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Resolve every substantiated CodeRabbit finding on PR #126 while preserving intentional shared-request and Watch Together delivery semantics. + +**Architecture:** Keep each correction at its current boundary: TV shell wiring owns destination/focus routing, the marquee state owns page-entry versus real-focus arbitration, phone/TV presentation helpers own metadata validation, and repositories own identity-safe cache writes. Add focused regressions before behavioral changes; use existing characterization tests for behavior-preserving refactors. + +**Tech Stack:** Kotlin 2.1, Jetpack Compose, Kotlin coroutines, Kotlin test/JUnit, Gradle, shell supply-chain policy scripts. + +## Global Constraints + +- Work only on `fix/tv-for-you-cold-navigation`; do not merge PR #126. +- Preserve shared in-flight recommendation requests; do not cancel repository work when one UI caller is superseded. +- Preserve Watch Together attach, cadence, and delivery semantics. +- Settled real TV card focus always wins over a page-entry marquee seed. +- IMDb ratings are valid only when finite and within `(0, 10]` on phone and TV. +- Do not install or deploy APKs. +- Address proven false positives with explicit invariants or documentation, not semantic changes. + +--- + +## File map + +- `androidTvApp/.../TvMainShell.kt`: root-destination selection and For You request reset. +- `androidTvApp/.../TvLibraryDetailScreen.kt`: Alphabet rail fallback forwarding. +- `androidTvApp/.../TvForYouEntryRequest.kt`: testable request transition. +- `androidTvApp/.../TvSkylineSectionFeed.kt`: initial marquee seed effect identity. +- `androidTvApp/.../TvFocusMarqueeModel.kt`: page-entry seed arbitration and TV metadata validation. +- `androidApp/.../FeaturedHeroMetadata.kt`: phone metadata validation. +- `shared/.../RoomDeliveryLatch.kt`: compiler-visible nullable-key invariant. +- Phone/TV room-sync controllers: non-null delivery-key binding at state-report call sites. +- `shared/.../SectionRepository.kt`: injectable home-request dispatcher. +- Phone library state logic and shared repositories: behavior-preserving helper extractions. +- Existing focused unit-test files plus small source-contract tests: regressions and wiring verification. +- Three review/plan/report documents: wording, stale references, and local-path hygiene. + +### Task 1: TV destination and focus wiring + +**Files:** +- Modify: `androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/library/TvLibraryDetailScreen.kt:158-167` +- Modify: `androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt:548-601` +- Modify: `androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvForYouEntryRequest.kt:8-14` +- Modify: `androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvForYouEntryRequestTest.kt` +- Create: `androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/library/TvLibraryReviewWiringSourceTest.kt` + +**Interfaces:** +- Consumes: `TvForYouEntryRequest.next(selection: SavedListSelection?)`. +- Produces: `TvForYouEntryRequest.nextForTopLevelForYou(): TvForYouEntryRequest`; Alphabet and Calendar both register their content-Up fallback with the shell. + +- [ ] **Step 1: Write the For You RED regression** + +Add to `TvForYouEntryRequestTest`: + +```kotlin +@Test +fun topLevelForYouRequestClearsSavedListSelection() { + val request = TvForYouEntryRequest( + sequence = 9, + selection = SavedListSelection.Watchlist, + ).nextForTopLevelForYou() + + assertEquals(10, request.sequence) + assertNull(request.selection) +} +``` + +- [ ] **Step 2: Write the Alphabet wiring RED regression** + +Create a source-contract test that loads +`TvLibraryDetailScreen.kt`, isolates the +`TvLibraryTab.Alphabet -> LibraryTab(...)` block, and asserts it contains: + +```kotlin +onContentUpFallbackChanged = onContentUpFallbackChanged +``` + +Also assert the existing `TvCalendarScreen(...)` call still contains +`onContentUpFallbackChanged = onContentUpFallback`. + +- [ ] **Step 3: Run RED** + +Run: + +```bash +./gradlew --no-daemon :androidTvApp:testDebugUnitTest \ + --tests '*TvForYouEntryRequestTest' \ + --tests '*TvLibraryReviewWiringSourceTest' \ + --max-workers=2 +``` + +Expected: failure because `nextForTopLevelForYou` is absent and the Alphabet +branch does not forward the fallback. + +- [ ] **Step 4: Implement the minimal GREEN changes** + +Add: + +```kotlin +fun nextForTopLevelForYou(): TvForYouEntryRequest = next(null) +``` + +At the start of `onSelectRoot`, update only the For You destination: + +```kotlin +if (dest == TvRootDestination.ForYou) { + forYouEntryRequest = forYouEntryRequest.nextForTopLevelForYou() +} +``` + +Forward `onContentUpFallbackChanged` in the Alphabet `LibraryTab` call exactly +as Browse already does. + +- [ ] **Step 5: Run GREEN and focused neighboring tests** + +Run: + +```bash +./gradlew --no-daemon :androidTvApp:testDebugUnitTest \ + --tests '*TvForYouEntryRequestTest' \ + --tests '*TvLibraryReviewWiringSourceTest' \ + --tests '*TvCalendarFocusRoutingTest' \ + --tests '*TvLibraryFocusRestoreTest' \ + --max-workers=2 +``` + +Expected: all selected tests pass. + +- [ ] **Step 6: Commit Task 1** + +```bash +git add androidTvApp/src/androidMain androidTvApp/src/androidUnitTest +git commit -m "fix(tv): close reviewed focus routing gaps" +``` + +### Task 2: Marquee identity and metadata bounds + +**Files:** +- Modify: `androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylineSectionFeed.kt:106-123` +- Modify: `androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeModel.kt:76-165,229-285` +- Modify: `androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeModelTest.kt` +- Modify: `androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeEnrichmentTest.kt` +- Modify: `androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/home/FeaturedHeroMetadata.kt:18-55` +- Modify: `androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/home/FeaturedHeroMetadataTest.kt` + +**Interfaces:** +- Consumes: `TvFocusMarqueeState.seedInitialPreview`, `TvMarqueeContent.from`, and `featuredHeroMetadata`. +- Produces: identity-aware page-entry reseeding that stops after real focus; consistent `(0, 10]` rating tokens on both clients. + +- [ ] **Step 1: Write page-entry identity RED tests** + +Add tests that: + +```kotlin +state.seedInitialPreview(item, "Row", rowIdentity = "row-old") +state.commit(state.candidate) +state.seedInitialPreview(item, "Row", rowIdentity = "row-new") +assertEquals("row-new#item-1", state.candidate?.id) +``` + +and: + +```kotlin +state.preview(focusedItem, "Focused", rowIdentity = "focused-row") +state.commit(state.candidate) +state.seedInitialPreview(seedItem, "Replacement", rowIdentity = "replacement-row") +assertEquals("focused-row#focused-item", state.content?.id) +assertNull(state.candidate) +``` + +- [ ] **Step 2: Write phone/TV rating and mixed-field RED tests** + +For both clients assert: + +```kotlin +ratingImdb = 11.0 +``` + +produces no rating token. Add two independent cases: + +```kotlin +ratingImdb = Double.NaN +durationSeconds = 7_200.0 +``` + +retains `"2h"`, while: + +```kotlin +ratingImdb = 8.4 +durationSeconds = Double.NaN +``` + +retains `"8.4"`. + +- [ ] **Step 3: Run RED** + +```bash +./gradlew --no-daemon \ + :androidApp:testDebugUnitTest \ + :androidTvApp:testDebugUnitTest \ + --tests '*FeaturedHeroMetadataTest' \ + --tests '*TvFocusMarqueeModelTest' \ + --tests '*TvFocusMarqueeEnrichmentTest' \ + --max-workers=2 +``` + +Expected: the row-identity and upper-bound assertions fail. + +- [ ] **Step 4: Implement minimal marquee arbitration** + +Keep `seedInitialPreview` as the boundary. Build `next` first, ignore seeds once +`focusedMarqueeId != null`, and otherwise replace a different page-entry +candidate/content identity: + +```kotlin +fun seedInitialPreview(item: SectionItem, rowTitle: String, rowIdentity: String = rowTitle) { + if (focusedMarqueeId != null) return + val next = TvMarqueeContent.from(item, rowTitle, rowIdentity) + if (candidate?.id == next.id || content?.id == next.id) return + candidate = next +} +``` + +Include `initialMarqueeSeed?.rowIdentity` in the `LaunchedEffect` key and call +`seedInitialPreview` without an outer `marquee.content == null` gate. + +- [ ] **Step 5: Implement bounded shared rating helpers** + +In each client boundary use a small private helper equivalent to: + +```kotlin +private fun validImdbRating(rating: Double?): Double? = + rating?.takeIf { it.isFinite() && it > 0.0 && it <= 10.0 } +``` + +Route both TV episode/non-episode branches through one TV `ratingToken` helper +to remove the duplicated filter. + +- [ ] **Step 6: Run GREEN** + +Repeat the Task 2 focused command. Expected: all selected tests pass. + +- [ ] **Step 7: Commit Task 2** + +```bash +git add androidApp/src/androidMain androidApp/src/androidUnitTest \ + androidTvApp/src/androidMain androidTvApp/src/androidUnitTest +git commit -m "fix(android): bound hero metadata and marquee identity" +``` + +### Task 3: Compiler-visible Watch Together delivery invariants + +**Files:** +- Modify: `shared/src/commonMain/kotlin/org/siloserver/silo/watchtogether/RoomDeliveryLatch.kt:58-64` +- Modify: `shared/src/commonTest/kotlin/org/siloserver/silo/watchtogether/RoomDeliveryLatchTest.kt` +- Modify: `androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/RoomSyncController.kt` +- Modify: `androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvRoomSyncController.kt:204-234` +- Create: `androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/player/TvRoomDeliveryKeySourceTest.kt` +- Create: `androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/player/RoomDeliveryKeySourceTest.kt` + +**Interfaces:** +- Consumes: `RoomDeliveryLatch.isServerAttached`. +- Produces: identical delivery decisions with no nullable-key dereference or force-unwrapped reporting key. + +- [ ] **Step 1: Strengthen nullable-key characterization** + +Add latch cases asserting `false` for: + +```kotlin +isServerAttached(key = null, echo = matchingEcho) +isServerAttached(key = validKey, echo = null) +isServerAttached(key = validKey, echo = wrongEpochEcho) +``` + +- [ ] **Step 2: Write source-contract RED tests** + +Assert each room-sync controller reporting block does not contain +`deliveryKey!!` and does contain an explicit `deliveryKey != null` guard before +`stateReport`. + +- [ ] **Step 3: Run RED** + +```bash +./gradlew --no-daemon \ + :shared:jvmTest \ + :androidApp:testDebugUnitTest \ + :androidTvApp:testDebugUnitTest \ + --tests '*RoomDeliveryLatchTest' \ + --tests '*RoomDeliveryKeySourceTest' \ + --tests '*TvRoomDeliveryKeySourceTest' \ + --max-workers=2 +``` + +Expected: latch behavior remains green; both source-contract tests fail on +`deliveryKey!!`. + +- [ ] **Step 4: Make nullability explicit without semantic changes** + +Use: + +```kotlin +key != null && + isAttached(key) && + echo != null && + echo.connectionGeneration == key.connectionGeneration +``` + +in the latch. In both controllers require a non-null local key before +`isServerAttached` and pass `key.playbackSessionId` to `stateReport`. + +- [ ] **Step 5: Run GREEN and neighboring room-sync tests** + +Run the Task 3 command plus `*RoomSyncStateReportGateTest`. Expected: all pass. + +- [ ] **Step 6: Commit Task 3** + +```bash +git add shared/src/commonMain shared/src/commonTest \ + androidApp/src/androidMain androidApp/src/androidUnitTest \ + androidTvApp/src/androidMain androidTvApp/src/androidUnitTest +git commit -m "refactor(watch-together): make delivery keys explicit" +``` + +### Task 4: Behavior-preserving review cleanups + +**Files:** +- Modify: `shared/src/commonMain/kotlin/org/siloserver/silo/repository/SectionRepository.kt:15-34` +- Modify: `shared/src/commonTest/kotlin/org/siloserver/silo/repository/SectionRepositoryCacheTest.kt:80-221` +- Modify: `androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibrariesScreen.kt:688-708` +- Modify: `shared/src/commonMain/kotlin/org/siloserver/silo/repository/CatalogRepository.kt:47-177` +- Modify: `shared/src/commonMain/kotlin/org/siloserver/silo/repository/PersonalDataRepository.kt:33-45` +- Verify: `shared/src/commonTest/kotlin/org/siloserver/silo/repository/CatalogRepositoryDetailCacheTest.kt` +- Verify: `shared/src/commonTest/kotlin/org/siloserver/silo/repository/PersonalDataRepositoryCacheTest.kt` + +**Interfaces:** +- Consumes: `CoroutineDispatcher`, identity transition generations, and `CatalogCacheWriteLease`. +- Produces: injectable home-request dispatcher and private helpers that preserve existing generation and cache-write decisions. + +- [ ] **Step 1: Establish the characterization-test baseline** + +```bash +./gradlew --no-daemon :shared:jvmTest \ + --tests '*SectionRepositoryCacheTest' \ + --tests '*CatalogRepositoryDetailCacheTest' \ + --tests '*PersonalDataRepositoryCacheTest' \ + --max-workers=2 +``` + +Expected: all selected tests pass before refactoring. + +- [ ] **Step 2: Inject the home request dispatcher** + +Add a constructor parameter with the existing runtime default: + +```kotlin +private val homeRequestDispatcher: CoroutineDispatcher = Dispatchers.Default +``` + +and use it in `homeRequestScope`. Update gated concurrency tests to pass a +`StandardTestDispatcher(testScheduler)` and extract one local helper that builds +the gated `MockEngine`/repository without changing assertions. + +- [ ] **Step 3: Extract the phone library identity comparison** + +Add: + +```kotlin +private fun CatalogRequestIdentity.matches(state: LibrariesUiState): Boolean = + state.selectedLibraryId == libraryId && + state.browseSort == browseSort && + state.selectedNamePrefix == selectedNamePrefix && + state.filterState == filterState +``` + +Keep request/query generation comparisons in their respective methods. +Do not retain or cancel a recommendation `Job`; shared repository work must +remain independent of one superseded UI caller. + +- [ ] **Step 4: Extract repository-local guarded-write helpers** + +In both repositories add the private pattern: + +```kotlin +private suspend fun writeIfIdentityUnchanged( + requestGeneration: Long, + write: suspend (CatalogCacheWriteLease) -> Unit, +) { + if (requestGeneration == identityTransitions.generation.value) { + write(CatalogCacheWriteLease(requestGeneration)) + } +} +``` + +Route existing cache write sites through it without moving network calls or +changing success/fallback behavior. + +- [ ] **Step 5: Re-run characterization tests** + +Repeat the Task 4 baseline command. Expected: all selected tests pass with the +same assertions. + +- [ ] **Step 6: Commit Task 4** + +```bash +git add shared/src/commonMain shared/src/commonTest androidApp/src/androidMain +git commit -m "refactor(android): clarify reviewed request guards" +``` + +### Task 5: Documentation and privacy corrections + +**Files:** +- Modify: `.superpowers/sdd/2026-07-28-android-tv-active-header-focus-editorial-hero/task-4-report.md` +- Modify: `docs/reviews/2026-07-27-android-tv-navigation-remediation-executive-summary.md:71` +- Modify: `docs/superpowers/plans/2026-07-28-android-tv-active-header-focus-editorial-hero.md:151,245` + +**Interfaces:** +- Consumes: current helper and focus-routing names. +- Produces: reproducible repository-relative evidence and implementation-accurate plan text. + +- [ ] **Step 1: Replace local paths** + +Replace the worktree with `fix/tv-for-you-cold-navigation worktree` and replace +Desktop artifact paths with the artifact filenames while retaining hashes and +signing notes. + +- [ ] **Step 2: Correct stale wording** + +Change `TV focused` to `TV-focused`, replace the stale +`FeaturedCarousel.metadataChips` reference with `featuredHeroMetadata`, and +update focus pseudocode to use `requestMenuFocusIfAvailable` plus the +`(focusRequest, focusRequestTarget)` handled identity. + +- [ ] **Step 3: Verify documentation** + +```bash +rg -n '/Users/jimcole' \ + .superpowers/sdd/2026-07-28-android-tv-active-header-focus-editorial-hero/task-4-report.md +rg -n 'FeaturedCarousel\\.metadataChips|TV focused|requestMenuFocus\\(selectedMenuFocusTarget\\)' \ + docs/reviews/2026-07-27-android-tv-navigation-remediation-executive-summary.md \ + docs/superpowers/plans/2026-07-28-android-tv-active-header-focus-editorial-hero.md +git diff --check +``` + +Expected: both `rg` commands return no matches and `git diff --check` passes. + +- [ ] **Step 4: Commit Task 5** + +```bash +git add .superpowers/sdd/2026-07-28-android-tv-active-header-focus-editorial-hero/task-4-report.md \ + docs/reviews/2026-07-27-android-tv-navigation-remediation-executive-summary.md \ + docs/superpowers/plans/2026-07-28-android-tv-active-header-focus-editorial-hero.md +git commit -m "docs: resolve PR 126 review findings" +``` + +### Task 6: Full verification, independent review, and PR update + +**Files:** +- Verify: all Task 1-5 files. +- Update remotely: PR #126 branch and description/check state only; do not merge. + +**Interfaces:** +- Consumes: all correction commits. +- Produces: reviewed branch with fresh focused, full, supply-chain, and release evidence. + +- [ ] **Step 1: Run complete unit gates** + +```bash +./gradlew --no-daemon \ + :shared:jvmTest \ + :android-shared:testDebugUnitTest \ + :androidApp:testDebugUnitTest \ + :androidTvApp:testDebugUnitTest \ + --max-workers=2 --rerun-tasks +``` + +Expected: exit 0 with no failed tests. + +- [ ] **Step 2: Run supply-chain policy** + +```bash +./scripts/test-check-build-supply-chain.sh +./scripts/check-build-supply-chain.sh +``` + +Expected: both exit 0. + +- [ ] **Step 3: Run phone and TV release compilation** + +```bash +./gradlew --no-daemon \ + :androidApp:assembleRelease \ + :androidTvApp:assembleRelease \ + -PallowDebugReleaseSigning=true \ + --max-workers=2 +``` + +Expected: `BUILD SUCCESSFUL`; these artifacts are verification-only and are not +installed or deployed. + +- [ ] **Step 4: Perform diff and scope checks** + +```bash +git diff --check origin/main...HEAD +git status --short +git log --oneline origin/main..HEAD +``` + +Expected: no whitespace errors, no uncommitted changes, and only the documented +PR #126 plus review-remediation commits. + +- [ ] **Step 5: Obtain independent focused review** + +Request review of `f822d22c..HEAD` against this plan and the design spec. Require +explicit assessment of the marquee real-focus invariant, For You reset, +Alphabet fallback, request-sharing non-cancellation, Watch Together delivery +semantics, and test adequacy. Fix any critical or important finding with a new +focused RED/GREEN cycle. + +- [ ] **Step 6: Push and update PR #126** + +Push `fix/tv-for-you-cold-navigation`, update the PR verification summary with +fresh commands, and leave the PR open and unmerged. Record which CodeRabbit +suggestion was intentionally rejected because cancelling a UI caller must not +cancel shared repository work. From 7f87291f96e49a56d5f175c4b5e4004bfbe6d196 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 12:05:39 +0200 Subject: [PATCH 52/65] docs: correct marquee review assertion --- .../plans/2026-07-28-pr-126-coderabbit-remediation.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/superpowers/plans/2026-07-28-pr-126-coderabbit-remediation.md b/docs/superpowers/plans/2026-07-28-pr-126-coderabbit-remediation.md index 8ea812e10e..11f031a27b 100644 --- a/docs/superpowers/plans/2026-07-28-pr-126-coderabbit-remediation.md +++ b/docs/superpowers/plans/2026-07-28-pr-126-coderabbit-remediation.md @@ -165,7 +165,7 @@ state.preview(focusedItem, "Focused", rowIdentity = "focused-row") state.commit(state.candidate) state.seedInitialPreview(seedItem, "Replacement", rowIdentity = "replacement-row") assertEquals("focused-row#focused-item", state.content?.id) -assertNull(state.candidate) +assertEquals("focused-row#focused-item", state.candidate?.id) ``` - [ ] **Step 2: Write phone/TV rating and mixed-field RED tests** From fac001c64b3cbaf71f10ebd42b35f1db27c6eaf4 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 12:06:02 +0200 Subject: [PATCH 53/65] docs: use available shared test task --- .../plans/2026-07-28-pr-126-coderabbit-remediation.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/superpowers/plans/2026-07-28-pr-126-coderabbit-remediation.md b/docs/superpowers/plans/2026-07-28-pr-126-coderabbit-remediation.md index 11f031a27b..9ebaa3f0cb 100644 --- a/docs/superpowers/plans/2026-07-28-pr-126-coderabbit-remediation.md +++ b/docs/superpowers/plans/2026-07-28-pr-126-coderabbit-remediation.md @@ -282,7 +282,7 @@ Assert each room-sync controller reporting block does not contain ```bash ./gradlew --no-daemon \ - :shared:jvmTest \ + :shared:test \ :androidApp:testDebugUnitTest \ :androidTvApp:testDebugUnitTest \ --tests '*RoomDeliveryLatchTest' \ @@ -339,7 +339,7 @@ git commit -m "refactor(watch-together): make delivery keys explicit" - [ ] **Step 1: Establish the characterization-test baseline** ```bash -./gradlew --no-daemon :shared:jvmTest \ +./gradlew --no-daemon :shared:test \ --tests '*SectionRepositoryCacheTest' \ --tests '*CatalogRepositoryDetailCacheTest' \ --tests '*PersonalDataRepositoryCacheTest' \ @@ -466,7 +466,7 @@ git commit -m "docs: resolve PR 126 review findings" ```bash ./gradlew --no-daemon \ - :shared:jvmTest \ + :shared:test \ :android-shared:testDebugUnitTest \ :androidApp:testDebugUnitTest \ :androidTvApp:testDebugUnitTest \ From cd43af9c11a8cf1e224401e6d5f9d33f4cea9392 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 12:08:42 +0200 Subject: [PATCH 54/65] fix(tv): close reviewed focus routing gaps --- .../screens/library/TvLibraryDetailScreen.kt | 1 + .../recommendations/TvForYouEntryRequest.kt | 2 ++ .../silo/tv/ui/shell/TvMainShell.kt | 3 +++ .../TvLibraryReviewWiringSourceTest.kt | 27 +++++++++++++++++++ .../TvForYouEntryRequestTest.kt | 11 ++++++++ 5 files changed, 44 insertions(+) create mode 100644 androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/library/TvLibraryReviewWiringSourceTest.kt diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/library/TvLibraryDetailScreen.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/library/TvLibraryDetailScreen.kt index 83b2b3e118..3a9cf8740e 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/library/TvLibraryDetailScreen.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/library/TvLibraryDetailScreen.kt @@ -164,6 +164,7 @@ fun TvLibraryDetailScreen( onRetry = viewModel::retryBrowse, onInitialContentFocus = onInitialContentFocus, showAlphabetRail = true, + onContentUpFallbackChanged = onContentUpFallbackChanged, ) TvLibraryTab.RecentlyAdded -> LibraryTab( state = state, diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvForYouEntryRequest.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvForYouEntryRequest.kt index 82f08b8363..53989f338a 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvForYouEntryRequest.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvForYouEntryRequest.kt @@ -11,6 +11,8 @@ data class TvForYouEntryRequest( ) { fun next(selection: SavedListSelection?): TvForYouEntryRequest = TvForYouEntryRequest(sequence = sequence + 1, selection = selection) + + fun nextForTopLevelForYou(): TvForYouEntryRequest = next(null) } internal data class AppliedForYouSelection( diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt index fcd59b2208..9449f98615 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt @@ -547,6 +547,9 @@ fun TvMainShell( val onSelectRoot: (TvRootDestination) -> Unit = { dest -> val route = dest.toRoute() + if (dest == TvRootDestination.ForYou) { + forYouEntryRequest = forYouEntryRequest.nextForTopLevelForYou() + } if (dest == TvRootDestination.Home) { // Detail return deliberately preserves the card that opened the // detail page, but that protection must end when the user diff --git a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/library/TvLibraryReviewWiringSourceTest.kt b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/library/TvLibraryReviewWiringSourceTest.kt new file mode 100644 index 0000000000..09a35cf509 --- /dev/null +++ b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/library/TvLibraryReviewWiringSourceTest.kt @@ -0,0 +1,27 @@ +package org.siloserver.silo.tv.ui.screens.library + +import java.io.File +import kotlin.test.Test +import kotlin.test.assertTrue + +class TvLibraryReviewWiringSourceTest { + private val detailScreen = File( + "src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/library/TvLibraryDetailScreen.kt", + ).readText() + private val mainShell = File( + "src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt", + ).readText() + + @Test + fun alphabetAndCalendarForwardContentUpFallbackToTheShell() { + val alphabetTab = detailScreen + .substringAfter("TvLibraryTab.Alphabet -> LibraryTab(") + .substringBefore("TvLibraryTab.RecentlyAdded ->") + val calendarScreen = mainShell + .substringAfter("TvCalendarScreen(") + .substringBefore("composable(TvMainRoute.Search.route)") + + assertTrue(alphabetTab.contains("onContentUpFallbackChanged = onContentUpFallbackChanged")) + assertTrue(calendarScreen.contains("onContentUpFallbackChanged = onContentUpFallback")) + } +} diff --git a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvForYouEntryRequestTest.kt b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvForYouEntryRequestTest.kt index 31ab1e9a76..1d719b849d 100644 --- a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvForYouEntryRequestTest.kt +++ b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvForYouEntryRequestTest.kt @@ -30,6 +30,17 @@ class TvForYouEntryRequestTest { assertNull(request.selection) } + @Test + fun topLevelForYouRequestClearsSavedListSelection() { + val request = TvForYouEntryRequest( + sequence = 9, + selection = SavedListSelection.Watchlist, + ).nextForTopLevelForYou() + + assertEquals(10, request.sequence) + assertNull(request.selection) + } + @Test fun unrelatedRecompositionDoesNotOverrideInPageSelection() { val applied = applyForYouEntryRequest( From 5d0d44b565f9fef123de39482d13fba4bd839ebe Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 12:11:57 +0200 Subject: [PATCH 55/65] test(tv): make focus wiring anchors fail closed --- .../TvLibraryReviewWiringSourceTest.kt | 27 ++++++++++++++----- 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/library/TvLibraryReviewWiringSourceTest.kt b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/library/TvLibraryReviewWiringSourceTest.kt index 09a35cf509..49ebe8b960 100644 --- a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/library/TvLibraryReviewWiringSourceTest.kt +++ b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/library/TvLibraryReviewWiringSourceTest.kt @@ -14,14 +14,29 @@ class TvLibraryReviewWiringSourceTest { @Test fun alphabetAndCalendarForwardContentUpFallbackToTheShell() { - val alphabetTab = detailScreen - .substringAfter("TvLibraryTab.Alphabet -> LibraryTab(") - .substringBefore("TvLibraryTab.RecentlyAdded ->") - val calendarScreen = mainShell - .substringAfter("TvCalendarScreen(") - .substringBefore("composable(TvMainRoute.Search.route)") + val alphabetTab = extractBetween( + source = detailScreen, + startAnchor = "TvLibraryTab.Alphabet -> LibraryTab(", + endAnchor = "TvLibraryTab.RecentlyAdded ->", + ) + val calendarScreen = extractBetween( + source = mainShell, + startAnchor = "TvCalendarScreen(", + endAnchor = "composable(TvMainRoute.Browse.route)", + ) assertTrue(alphabetTab.contains("onContentUpFallbackChanged = onContentUpFallbackChanged")) assertTrue(calendarScreen.contains("onContentUpFallbackChanged = onContentUpFallback")) } + + private fun extractBetween(source: String, startAnchor: String, endAnchor: String): String { + val start = source.indexOf(startAnchor) + assertTrue(start >= 0, "Missing start anchor: $startAnchor") + + val contentStart = start + startAnchor.length + val end = source.indexOf(endAnchor, contentStart) + assertTrue(end >= 0, "Missing end anchor: $endAnchor") + + return source.substring(contentStart, end) + } } From 5a93c22599c0c831b676eacd33bdd5972d117c8d Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 12:17:18 +0200 Subject: [PATCH 56/65] fix(android): bound hero metadata and marquee identity --- .../ui/screens/home/FeaturedHeroMetadata.kt | 6 +- .../screens/home/FeaturedHeroMetadataTest.kt | 31 +++++++++ .../tv/ui/components/TvFocusMarqueeModel.kt | 20 +++--- .../tv/ui/components/TvSkylineSectionFeed.kt | 10 +-- .../TvFocusMarqueeEnrichmentTest.kt | 65 ++++++++++++++----- .../ui/components/TvFocusMarqueeModelTest.kt | 33 ++++++++++ 6 files changed, 134 insertions(+), 31 deletions(-) diff --git a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/home/FeaturedHeroMetadata.kt b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/home/FeaturedHeroMetadata.kt index 59a5eade95..48f0c829cc 100644 --- a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/home/FeaturedHeroMetadata.kt +++ b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/home/FeaturedHeroMetadata.kt @@ -30,8 +30,7 @@ internal fun featuredHeroMetadata(item: SectionItem): List 0.0 } + validImdbRating(item.ratingImdb) ?.let { result += FeaturedHeroMetadataChip( label = String.format(Locale.US, "%.1f", it), @@ -55,6 +54,9 @@ internal fun featuredHeroMetadata(item: SectionItem): List 0.0 && it <= 10.0 } + private fun episodeToken(season: Int?, episode: Int?): String? = when { season != null && episode != null -> "S$season E$episode" season != null -> "Season $season" diff --git a/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/home/FeaturedHeroMetadataTest.kt b/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/home/FeaturedHeroMetadataTest.kt index f4f67bdb35..e5be2da9ec 100644 --- a/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/home/FeaturedHeroMetadataTest.kt +++ b/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/home/FeaturedHeroMetadataTest.kt @@ -72,6 +72,7 @@ class FeaturedHeroMetadataTest { Double.NEGATIVE_INFINITY, 0.0, -1.0, + 11.0, ).forEachIndexed { index, invalid -> val chips = featuredHeroMetadata( SectionItem( @@ -86,4 +87,34 @@ class FeaturedHeroMetadataTest { assertEquals(emptyList(), chips) } } + + @Test + fun invalidRatingDoesNotHideValidPhoneRuntime() { + val chips = featuredHeroMetadata( + SectionItem( + contentId = "runtime-with-invalid-rating", + type = "movie", + title = "Movie", + ratingImdb = Double.NaN, + durationSeconds = 7_200.0, + ), + ) + + assertEquals(listOf("2h"), chips.map { it.label }) + } + + @Test + fun validRatingDoesNotHideInvalidPhoneRuntime() { + val chips = featuredHeroMetadata( + SectionItem( + contentId = "rating-with-invalid-runtime", + type = "movie", + title = "Movie", + ratingImdb = 8.4, + durationSeconds = Double.NaN, + ), + ) + + assertEquals(listOf("8.4"), chips.map { it.label }) + } } diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeModel.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeModel.kt index fe8a3e6eb4..c140a4bdd4 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeModel.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeModel.kt @@ -86,15 +86,11 @@ data class TvMarqueeContent( episodeToken(item.seasonNumber, item.episodeNumber)?.let(meta::add) if (item.title.isNotBlank()) meta.add(item.title) lengthText(item.durationSeconds)?.let(meta::add) - item.ratingImdb - ?.takeIf { it.isFinite() && it > 0.0 } - ?.let { meta.add(formatRating(it)) } + ratingToken(item.ratingImdb)?.let(meta::add) } else { if (item.year > 0) meta.add(item.year.toString()) lengthText(item.durationSeconds)?.let(meta::add) - item.ratingImdb - ?.takeIf { it.isFinite() && it > 0.0 } - ?.let { meta.add(formatRating(it)) } + ratingToken(item.ratingImdb)?.let(meta::add) item.genres.firstOrNull { it.isNotBlank() }?.let(meta::add) } @@ -158,6 +154,12 @@ data class TvMarqueeContent( } } + private fun ratingToken(rating: Double?): String? = + validImdbRating(rating)?.let(::formatRating) + + private fun validImdbRating(rating: Double?): Double? = + rating?.takeIf { it.isFinite() && it > 0.0 && it <= 10.0 } + private fun formatRating(rating: Double): String { val rounded = (rating * 10).roundToInt() / 10.0 return rounded.toString() @@ -273,8 +275,10 @@ class TvFocusMarqueeState internal constructor() { * content, the seed is ignored so it never fights real navigation. */ fun seedInitialPreview(item: SectionItem, rowTitle: String, rowIdentity: String = rowTitle) { - if (content != null || candidate != null) return - candidate = TvMarqueeContent.from(item, rowTitle, rowIdentity) + if (focusedMarqueeId != null) return + val next = TvMarqueeContent.from(item, rowTitle, rowIdentity) + if (candidate?.id == next.id || content?.id == next.id) return + candidate = next } internal fun commit(value: TvMarqueeContent?) { diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylineSectionFeed.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylineSectionFeed.kt index 250679292d..befc6a02bd 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylineSectionFeed.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylineSectionFeed.kt @@ -115,11 +115,13 @@ fun TvSkylineSectionFeed( } } - LaunchedEffect(initialMarqueeSeed?.item?.contentId, initialMarqueeSeed?.rowTitle) { + LaunchedEffect( + initialMarqueeSeed?.item?.contentId, + initialMarqueeSeed?.rowTitle, + initialMarqueeSeed?.rowIdentity, + ) { val seed = initialMarqueeSeed ?: return@LaunchedEffect - if (marquee.content == null) { - marquee.seedInitialPreview(seed.item, seed.rowTitle, seed.rowIdentity) - } + marquee.seedInitialPreview(seed.item, seed.rowTitle, seed.rowIdentity) } val rowBandState = rememberLazyListState() diff --git a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeEnrichmentTest.kt b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeEnrichmentTest.kt index 9b854e28e8..aea52fd560 100644 --- a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeEnrichmentTest.kt +++ b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeEnrichmentTest.kt @@ -138,34 +138,65 @@ class TvFocusMarqueeEnrichmentTest { } @Test - fun `initial seed joins the coordinated candidate and does not replace it`() { + fun `page entry reseeds a stale candidate when its row identity changes`() { val state = TvFocusMarqueeState() - val first = SectionItem( - contentId = "first", + val item = SectionItem(contentId = "item-1", type = "movie", title = "Item") + + state.seedInitialPreview(item, "Row", rowIdentity = "row-old") + state.commit(state.candidate) + state.seedInitialPreview(item, "Row", rowIdentity = "row-new") + + assertEquals("row-new#item-1", state.candidate?.id) + } + + @Test + fun `page entry seed never replaces settled real focus`() { + val state = TvFocusMarqueeState() + val focusedItem = SectionItem( + contentId = "focused-item", type = "movie", - title = "First Movie", - backdropUrl = "https://art/first.jpg", + title = "Focused", ) - val second = SectionItem( - contentId = "second", + val seedItem = SectionItem( + contentId = "seed-item", type = "movie", - title = "Second Movie", - backdropUrl = "https://art/second.jpg", + title = "Replacement", ) - state.seedInitialPreview(first, "Continue Watching") - - assertNull(state.content) - assertEquals("First Movie", state.candidate?.title) + state.preview(focusedItem, "Focused", rowIdentity = "focused-row") + state.commit(state.candidate) + state.seedInitialPreview(seedItem, "Replacement", rowIdentity = "replacement-row") - state.seedInitialPreview(second, "Next Row") + assertEquals("focused-row#focused-item", state.content?.id) + assertEquals("focused-row#focused-item", state.candidate?.id) + } - assertEquals("First Movie", state.candidate?.title) + @Test + fun `page entry seed never replaces pending real focus`() { + val state = TvFocusMarqueeState() + val initialItem = SectionItem( + contentId = "initial-item", + type = "movie", + title = "Initial", + ) + val focusedItem = SectionItem( + contentId = "focused-item", + type = "movie", + title = "Focused", + ) + val seedItem = SectionItem( + contentId = "seed-item", + type = "movie", + title = "Replacement", + ) + state.seedInitialPreview(initialItem, "Initial", rowIdentity = "initial-row") state.commit(state.candidate) + state.preview(focusedItem, "Focused", rowIdentity = "focused-row") + state.seedInitialPreview(seedItem, "Replacement", rowIdentity = "replacement-row") - assertEquals("First Movie", state.content?.title) - assertEquals("https://art/first.jpg", state.content?.heroBackdropUrl) + assertEquals("initial-row#initial-item", state.content?.id) + assertEquals("focused-row#focused-item", state.candidate?.id) } @Test diff --git a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeModelTest.kt b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeModelTest.kt index 9813e9c2f0..38de92ea22 100644 --- a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeModelTest.kt +++ b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvFocusMarqueeModelTest.kt @@ -91,6 +91,7 @@ class TvFocusMarqueeModelTest { Double.NEGATIVE_INFINITY, 0.0, -1.0, + 11.0, ).forEachIndexed { index, invalid -> val content = TvMarqueeContent.from( item = SectionItem( @@ -106,4 +107,36 @@ class TvFocusMarqueeModelTest { assertEquals(emptyList(), content.metaParts) } } + + @Test + fun invalidRatingDoesNotHideValidTvRuntime() { + val content = TvMarqueeContent.from( + item = SectionItem( + contentId = "runtime-with-invalid-rating", + type = "movie", + title = "Movie", + ratingImdb = Double.NaN, + durationSeconds = 7_200.0, + ), + rowTitle = "Row", + ) + + assertEquals(listOf("2h"), content.metaParts) + } + + @Test + fun validRatingDoesNotHideInvalidTvRuntime() { + val content = TvMarqueeContent.from( + item = SectionItem( + contentId = "rating-with-invalid-runtime", + type = "movie", + title = "Movie", + ratingImdb = 8.4, + durationSeconds = Double.NaN, + ), + rowTitle = "Row", + ) + + assertEquals(listOf("8.4"), content.metaParts) + } } From 3b757fd3005281a86b3b9bd177055a0cce65a059 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 12:26:37 +0200 Subject: [PATCH 57/65] refactor(watch-together): make delivery keys explicit --- .../ui/screens/player/RoomSyncController.kt | 12 ++++----- .../player/RoomDeliveryKeySourceTest.kt | 26 +++++++++++++++++++ .../ui/screens/player/TvRoomSyncController.kt | 12 ++++----- .../player/TvRoomDeliveryKeySourceTest.kt | 26 +++++++++++++++++++ .../silo/watchtogether/RoomDeliveryLatch.kt | 5 ++-- .../watchtogether/RoomDeliveryLatchTest.kt | 17 ++++++++++++ 6 files changed, 84 insertions(+), 14 deletions(-) create mode 100644 androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/player/RoomDeliveryKeySourceTest.kt create mode 100644 androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/player/TvRoomDeliveryKeySourceTest.kt diff --git a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/RoomSyncController.kt b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/RoomSyncController.kt index 296394ffe1..f995e97ae0 100644 --- a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/RoomSyncController.kt +++ b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/RoomSyncController.kt @@ -152,12 +152,12 @@ class RoomSyncController( repository.connectionState.value, sessionId, ) - val serverAttached = deliveryLatch.isServerAttached( - deliveryKey, - repository.roomDeliveryEcho.value, - ) val now = monotonicMs() - if (serverAttached && + if (deliveryKey != null && + deliveryLatch.isServerAttached( + deliveryKey, + repository.roomDeliveryEcho.value, + ) && shouldEmitStateReport( now, lastReportMs, @@ -168,7 +168,7 @@ class RoomSyncController( ) { lastReportMs = now repository.stateReport( - sessionId = deliveryKey!!.playbackSessionId, + sessionId = deliveryKey.playbackSessionId, positionSeconds = state.position, isPaused = state.isPaused, ) diff --git a/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/player/RoomDeliveryKeySourceTest.kt b/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/player/RoomDeliveryKeySourceTest.kt new file mode 100644 index 0000000000..2d486bc06a --- /dev/null +++ b/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/player/RoomDeliveryKeySourceTest.kt @@ -0,0 +1,26 @@ +package org.siloserver.silo.android.ui.screens.player + +import java.io.File +import kotlin.test.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class RoomDeliveryKeySourceTest { + private val controllerSource = File( + "src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/RoomSyncController.kt", + ).readText() + + @Test + fun stateReportRequiresAnExplicitNonNullDeliveryKey() { + val reportingBlock = controllerSource + .substringAfter("// Drift reporting loop") + .substringBefore("// ready / buffering during the waiting barrier.") + + assertFalse(reportingBlock.contains("deliveryKey!!")) + assertTrue(reportingBlock.contains("deliveryKey != null")) + assertTrue( + reportingBlock.indexOf("deliveryKey != null") < + reportingBlock.indexOf("repository.stateReport("), + ) + } +} diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvRoomSyncController.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvRoomSyncController.kt index 739f3f9c0b..b48e2ede83 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvRoomSyncController.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvRoomSyncController.kt @@ -209,12 +209,12 @@ class TvRoomSyncController( repository.connectionState.value, sessionId, ) - val serverAttached = deliveryLatch.isServerAttached( - deliveryKey, - repository.roomDeliveryEcho.value, - ) val now = monotonicMs() - if (serverAttached && + if (deliveryKey != null && + deliveryLatch.isServerAttached( + deliveryKey, + repository.roomDeliveryEcho.value, + ) && tvShouldEmitStateReport( now, lastReportMs, @@ -225,7 +225,7 @@ class TvRoomSyncController( ) { lastReportMs = now repository.stateReport( - sessionId = deliveryKey!!.playbackSessionId, + sessionId = deliveryKey.playbackSessionId, positionSeconds = state.position, isPaused = state.isPaused, ) diff --git a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/player/TvRoomDeliveryKeySourceTest.kt b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/player/TvRoomDeliveryKeySourceTest.kt new file mode 100644 index 0000000000..ef5050eb00 --- /dev/null +++ b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/player/TvRoomDeliveryKeySourceTest.kt @@ -0,0 +1,26 @@ +package org.siloserver.silo.tv.ui.screens.player + +import java.io.File +import kotlin.test.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class TvRoomDeliveryKeySourceTest { + private val controllerSource = File( + "src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvRoomSyncController.kt", + ).readText() + + @Test + fun stateReportRequiresAnExplicitNonNullDeliveryKey() { + val reportingBlock = controllerSource + .substringAfter("// Drift reporting loop") + .substringBefore("// ready / buffering during the waiting barrier.") + + assertFalse(reportingBlock.contains("deliveryKey!!")) + assertTrue(reportingBlock.contains("deliveryKey != null")) + assertTrue( + reportingBlock.indexOf("deliveryKey != null") < + reportingBlock.indexOf("repository.stateReport("), + ) + } +} diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/watchtogether/RoomDeliveryLatch.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/watchtogether/RoomDeliveryLatch.kt index 43a227c90c..b2326d8d60 100644 --- a/shared/src/commonMain/kotlin/org/siloserver/silo/watchtogether/RoomDeliveryLatch.kt +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/watchtogether/RoomDeliveryLatch.kt @@ -56,9 +56,10 @@ class RoomDeliveryLatch { * and the server echoed that exact session in a room snapshot. */ fun isServerAttached(key: RoomDeliveryKey?, echo: RoomDeliveryEcho?): Boolean = - isAttached(key) && + key != null && + isAttached(key) && echo != null && - echo.connectionGeneration == key?.connectionGeneration && + echo.connectionGeneration == key.connectionGeneration && echo.connectionEpoch == key.connectionEpoch && echo.playbackSessionId == key.playbackSessionId diff --git a/shared/src/commonTest/kotlin/org/siloserver/silo/watchtogether/RoomDeliveryLatchTest.kt b/shared/src/commonTest/kotlin/org/siloserver/silo/watchtogether/RoomDeliveryLatchTest.kt index 842ca21bdf..19d3a9f6d8 100644 --- a/shared/src/commonTest/kotlin/org/siloserver/silo/watchtogether/RoomDeliveryLatchTest.kt +++ b/shared/src/commonTest/kotlin/org/siloserver/silo/watchtogether/RoomDeliveryLatchTest.kt @@ -107,6 +107,23 @@ class RoomDeliveryLatchTest { ) } + @Test + fun `server attach rejects nullable keys and stale echoes`() { + val latch = RoomDeliveryLatch() + val key = assertNotNull(latch.keyOrNull(open1, "session-a")) + val matchingEcho = RoomDeliveryEcho(7, 1, "session-a") + latch.recordAttach(key, delivered = true) + + assertFalse(latch.isServerAttached(key = null, echo = matchingEcho)) + assertFalse(latch.isServerAttached(key = key, echo = null)) + assertFalse( + latch.isServerAttached( + key = key, + echo = RoomDeliveryEcho(7, 2, "session-a"), + ), + ) + } + @Test fun `stale prior epoch echo cannot authorize a newly delivered reconnect attach`() { val latch = RoomDeliveryLatch() From d91623849bdbd844e397231f6fb7f992d8f12460 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 12:33:04 +0200 Subject: [PATCH 58/65] refactor(android): clarify reviewed request guards --- .../ui/screens/libraries/LibrariesScreen.kt | 16 +-- .../silo/repository/CatalogRepository.kt | 21 +-- .../silo/repository/PersonalDataRepository.kt | 12 +- .../silo/repository/SectionRepository.kt | 4 +- .../repository/SectionRepositoryCacheTest.kt | 124 +++++++++--------- 5 files changed, 96 insertions(+), 81 deletions(-) diff --git a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibrariesScreen.kt b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibrariesScreen.kt index d198f3756e..f34f03008b 100644 --- a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibrariesScreen.kt +++ b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibrariesScreen.kt @@ -691,10 +691,7 @@ class LibrariesViewModel( state: LibrariesUiState = _uiState.value, ): Boolean = generation == catalogRequestGeneration && - state.selectedLibraryId == identity.libraryId && - state.browseSort == identity.browseSort && - state.selectedNamePrefix == identity.selectedNamePrefix && - state.filterState == identity.filterState + identity.matches(state) private fun isCatalogQueryCurrent( generation: Long, @@ -702,10 +699,13 @@ class LibrariesViewModel( state: LibrariesUiState = _uiState.value, ): Boolean = generation == catalogQueryGeneration && - state.selectedLibraryId == identity.libraryId && - state.browseSort == identity.browseSort && - state.selectedNamePrefix == identity.selectedNamePrefix && - state.filterState == identity.filterState + identity.matches(state) + + private fun CatalogRequestIdentity.matches(state: LibrariesUiState): Boolean = + state.selectedLibraryId == libraryId && + state.browseSort == browseSort && + state.selectedNamePrefix == selectedNamePrefix && + state.filterState == filterState private fun isCollectionsRequestCurrent( generation: Long, diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/repository/CatalogRepository.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/repository/CatalogRepository.kt index 5208f948cf..667b875389 100644 --- a/shared/src/commonMain/kotlin/org/siloserver/silo/repository/CatalogRepository.kt +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/repository/CatalogRepository.kt @@ -45,7 +45,6 @@ class CatalogRepository( match: String? = null, ): ApiResult { val requestIdentityGeneration = identityTransitions.generation.value - val cacheWriteLease = CatalogCacheWriteLease(requestIdentityGeneration) val result = catalogApi.getCatalog( source = source, query = query, @@ -77,7 +76,7 @@ class CatalogRepository( } ?: return result if (result is ApiResult.Success) { - if (requestIdentityGeneration == identityTransitions.generation.value) { + writeIfIdentityUnchanged(requestIdentityGeneration) { cacheWriteLease -> catalogCache.cacheDefaultLibraryPage(cacheableLibraryId, result.data, cacheWriteLease) } return result @@ -118,10 +117,9 @@ class CatalogRepository( /** Fetches full metadata for a single catalog item (offline: last cached detail). */ suspend fun getItemDetail(contentId: String): ApiResult { val requestIdentityGeneration = identityTransitions.generation.value - val cacheWriteLease = CatalogCacheWriteLease(requestIdentityGeneration) val result = catalogApi.getItemDetail(contentId) if (result is ApiResult.Success) { - if (requestIdentityGeneration == identityTransitions.generation.value) { + writeIfIdentityUnchanged(requestIdentityGeneration) { cacheWriteLease -> catalogCache.cacheItemDetail(contentId, result.data, cacheWriteLease) } return result @@ -152,10 +150,9 @@ class CatalogRepository( /** Lists seasons for a series (offline: last cached seasons). */ suspend fun getSeasons(seriesId: String): ApiResult { val requestIdentityGeneration = identityTransitions.generation.value - val cacheWriteLease = CatalogCacheWriteLease(requestIdentityGeneration) val result = catalogApi.getSeasons(seriesId) if (result is ApiResult.Success) { - if (requestIdentityGeneration == identityTransitions.generation.value) { + writeIfIdentityUnchanged(requestIdentityGeneration) { cacheWriteLease -> catalogCache.cacheSeasons(seriesId, result.data, cacheWriteLease) } return result @@ -169,10 +166,9 @@ class CatalogRepository( /** Lists episodes for a specific season of a series (offline: last cached episodes). */ suspend fun getEpisodes(seriesId: String, seasonNumber: Int): ApiResult { val requestIdentityGeneration = identityTransitions.generation.value - val cacheWriteLease = CatalogCacheWriteLease(requestIdentityGeneration) val result = catalogApi.getEpisodes(seriesId, seasonNumber) if (result is ApiResult.Success) { - if (requestIdentityGeneration == identityTransitions.generation.value) { + writeIfIdentityUnchanged(requestIdentityGeneration) { cacheWriteLease -> catalogCache.cacheEpisodes(seriesId, seasonNumber, result.data, cacheWriteLease) } return result @@ -218,4 +214,13 @@ class CatalogRepository( limit = limit, snapshotAt = snapshotAt, ) + + private suspend fun writeIfIdentityUnchanged( + requestGeneration: Long, + write: suspend (CatalogCacheWriteLease) -> Unit, + ) { + if (requestGeneration == identityTransitions.generation.value) { + write(CatalogCacheWriteLease(requestGeneration)) + } + } } diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/repository/PersonalDataRepository.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/repository/PersonalDataRepository.kt index 43f3ac262f..92c8e42b3b 100644 --- a/shared/src/commonMain/kotlin/org/siloserver/silo/repository/PersonalDataRepository.kt +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/repository/PersonalDataRepository.kt @@ -37,10 +37,9 @@ open class PersonalDataRepository( /** Lists the libraries visible to the current user (offline: last cached list). */ suspend fun listUserLibraries(): ApiResult> { val requestIdentityGeneration = identityTransitions.generation.value - val cacheWriteLease = CatalogCacheWriteLease(requestIdentityGeneration) val result = personalDataApi.listUserLibraries() if (result is ApiResult.Success) { - if (requestIdentityGeneration == identityTransitions.generation.value) { + writeIfIdentityUnchanged(requestIdentityGeneration) { cacheWriteLease -> catalogCache.cacheLibraries(result.data, cacheWriteLease) } return result @@ -172,4 +171,13 @@ open class PersonalDataRepository( open suspend fun dismissNextUp(itemId: String, seriesId: String): ApiResult = personalDataApi.dismissNextUp(itemId, seriesId) + + private suspend fun writeIfIdentityUnchanged( + requestGeneration: Long, + write: suspend (CatalogCacheWriteLease) -> Unit, + ) { + if (requestGeneration == identityTransitions.generation.value) { + write(CatalogCacheWriteLease(requestGeneration)) + } + } } diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/repository/SectionRepository.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/repository/SectionRepository.kt index 309b417ebb..9385b62063 100644 --- a/shared/src/commonMain/kotlin/org/siloserver/silo/repository/SectionRepository.kt +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/repository/SectionRepository.kt @@ -15,6 +15,7 @@ import org.siloserver.silo.repository.port.CatalogCachePort import org.siloserver.silo.repository.port.CatalogCacheWriteLease import org.siloserver.silo.repository.port.NoOpCatalogCachePort import org.siloserver.silo.repository.port.canServeCache +import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Deferred @@ -29,8 +30,9 @@ class SectionRepository( /** Offline read cache for a library's Recommended sections (Track B). No-op by default. */ private val catalogCache: CatalogCachePort = NoOpCatalogCachePort, private val identityTransitions: IdentityTransitionBarrier = DefaultIdentityTransitionBarrier(), + private val homeRequestDispatcher: CoroutineDispatcher = Dispatchers.Default, ) { - private val homeRequestScope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + private val homeRequestScope = CoroutineScope(SupervisorJob() + homeRequestDispatcher) private val homeRequestMutex = Mutex() private val homeSectionsInFlight = mutableMapOf>>() diff --git a/shared/src/commonTest/kotlin/org/siloserver/silo/repository/SectionRepositoryCacheTest.kt b/shared/src/commonTest/kotlin/org/siloserver/silo/repository/SectionRepositoryCacheTest.kt index efa2965ed4..f721e0b9a9 100644 --- a/shared/src/commonTest/kotlin/org/siloserver/silo/repository/SectionRepositoryCacheTest.kt +++ b/shared/src/commonTest/kotlin/org/siloserver/silo/repository/SectionRepositoryCacheTest.kt @@ -3,6 +3,7 @@ package org.siloserver.silo.repository import org.siloserver.silo.model.section.ResolvedSection import org.siloserver.silo.network.ApiResult import org.siloserver.silo.network.DefaultIdentityTransitionBarrier +import org.siloserver.silo.network.IdentityTransitionBarrier import org.siloserver.silo.network.IdentityTransitionKind import org.siloserver.silo.network.SiloJson import org.siloserver.silo.network.api.SectionApi @@ -15,11 +16,13 @@ import io.ktor.http.HttpHeaders import io.ktor.http.HttpStatusCode import io.ktor.http.headersOf import io.ktor.serialization.kotlinx.json.json +import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.launch +import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.runTest import kotlinx.coroutines.yield import kotlin.test.Test @@ -50,6 +53,36 @@ class SectionRepositoryCacheTest { return SectionRepository(SectionApi(client), cache) } + private fun gatedRepository( + homeRequestDispatcher: CoroutineDispatcher, + requestEntered: CompletableDeferred, + releaseResponse: CompletableDeferred, + body: () -> String, + onRequest: () -> Unit = {}, + identityTransitions: IdentityTransitionBarrier = DefaultIdentityTransitionBarrier(), + ): SectionRepository { + val client = HttpClient( + MockEngine { + onRequest() + requestEntered.complete(Unit) + val responseBody = body() + releaseResponse.await() + respond( + responseBody, + HttpStatusCode.OK, + headersOf(HttpHeaders.ContentType, "application/json"), + ) + }, + ) { + install(ContentNegotiation) { json(SiloJson) } + } + return SectionRepository( + sectionApi = SectionApi(client), + identityTransitions = identityTransitions, + homeRequestDispatcher = homeRequestDispatcher, + ) + } + private fun section(id: String) = ResolvedSection(id = id, sectionType = id, title = id) @Test @@ -82,21 +115,13 @@ class SectionRepositoryCacheTest { var calls = 0 val entered = CompletableDeferred() val release = CompletableDeferred() - val client = HttpClient( - MockEngine { - calls += 1 - entered.complete(Unit) - release.await() - respond( - """{"sections":[]}""", - HttpStatusCode.OK, - headersOf(HttpHeaders.ContentType, "application/json"), - ) - }, - ) { - install(ContentNegotiation) { json(SiloJson) } - } - val repository = SectionRepository(SectionApi(client)) + val repository = gatedRepository( + homeRequestDispatcher = StandardTestDispatcher(testScheduler), + requestEntered = entered, + releaseResponse = release, + body = { """{"sections":[]}""" }, + onRequest = { calls += 1 }, + ) val requests = listOf( async { repository.getHomeSections() }, @@ -115,21 +140,13 @@ class SectionRepositoryCacheTest { var calls = 0 val entered = CompletableDeferred() val release = CompletableDeferred() - val client = HttpClient( - MockEngine { - calls += 1 - entered.complete(Unit) - release.await() - respond( - """{"items":[],"total":0}""", - HttpStatusCode.OK, - headersOf(HttpHeaders.ContentType, "application/json"), - ) - }, - ) { - install(ContentNegotiation) { json(SiloJson) } - } - val repository = SectionRepository(SectionApi(client)) + val repository = gatedRepository( + homeRequestDispatcher = StandardTestDispatcher(testScheduler), + requestEntered = entered, + releaseResponse = release, + body = { """{"items":[],"total":0}""" }, + onRequest = { calls += 1 }, + ) val requests = listOf( async { repository.getHomeSectionItems("same") }, @@ -148,21 +165,13 @@ class SectionRepositoryCacheTest { var calls = 0 val entered = CompletableDeferred() val release = CompletableDeferred() - val client = HttpClient( - MockEngine { - calls += 1 - entered.complete(Unit) - release.await() - respond( - """{"sections":[]}""", - HttpStatusCode.OK, - headersOf(HttpHeaders.ContentType, "application/json"), - ) - }, - ) { - install(ContentNegotiation) { json(SiloJson) } - } - val repository = SectionRepository(SectionApi(client)) + val repository = gatedRepository( + homeRequestDispatcher = StandardTestDispatcher(testScheduler), + requestEntered = entered, + releaseResponse = release, + body = { """{"sections":[]}""" }, + onRequest = { calls += 1 }, + ) val firstCaller = launch { repository.getHomeSections() } entered.await() @@ -181,28 +190,19 @@ class SectionRepositoryCacheTest { var calls = 0 val oldRequestEntered = CompletableDeferred() val releaseOldRequest = CompletableDeferred() - val client = HttpClient( - MockEngine { - calls += 1 - val body = if (calls == 1) { - oldRequestEntered.complete(Unit) - releaseOldRequest.await() + val identityTransitions = DefaultIdentityTransitionBarrier() + val repository = gatedRepository( + homeRequestDispatcher = StandardTestDispatcher(testScheduler), + requestEntered = oldRequestEntered, + releaseResponse = releaseOldRequest, + body = { + if (calls == 1) { """{"sections":[{"id":"old","section_type":"old","title":"Old"}]}""" } else { """{"sections":[{"id":"new","section_type":"new","title":"New"}]}""" } - respond( - body, - HttpStatusCode.OK, - headersOf(HttpHeaders.ContentType, "application/json"), - ) }, - ) { - install(ContentNegotiation) { json(SiloJson) } - } - val identityTransitions = DefaultIdentityTransitionBarrier() - val repository = SectionRepository( - sectionApi = SectionApi(client), + onRequest = { calls += 1 }, identityTransitions = identityTransitions, ) From 98e5b7bb3c506ad01d56eb8bd2bcf70243853fb4 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 12:39:01 +0200 Subject: [PATCH 59/65] docs: resolve PR 126 review findings --- .../task-4-report.md | 6 ++-- ...avigation-remediation-executive-summary.md | 2 +- ...d-tv-active-header-focus-editorial-hero.md | 35 ++++++++++++------- 3 files changed, 26 insertions(+), 17 deletions(-) diff --git a/.superpowers/sdd/2026-07-28-android-tv-active-header-focus-editorial-hero/task-4-report.md b/.superpowers/sdd/2026-07-28-android-tv-active-header-focus-editorial-hero/task-4-report.md index 3c25dda643..a0733193df 100644 --- a/.superpowers/sdd/2026-07-28-android-tv-active-header-focus-editorial-hero/task-4-report.md +++ b/.superpowers/sdd/2026-07-28-android-tv-active-header-focus-editorial-hero/task-4-report.md @@ -1,7 +1,7 @@ # Task 4 Report: Android TV Focus and Phone/TV Hero Verification Date: 2026-07-28 -Worktree: `/Users/jimcole/projects/silo/silo-android/.worktrees/tv-for-you-cold-navigation` +Worktree: `fix/tv-for-you-cold-navigation worktree` Final local HEAD: `9c251293dc321385ea9be205a0732cc7b14b1251` ## Summary @@ -140,8 +140,8 @@ Signing caveat: these are debug-signed release builds. They only upgrade install Copied artifacts: -- `/Users/jimcole/Desktop/Silo Releases/Silo-Phone-Universal-0.3.11-FocusHeroFix-9c251293.apk` -- `/Users/jimcole/Desktop/Silo Releases/Silo-TV-Universal-0.3.11-TVFocusHeroFix-9c251293.apk` +- `Silo-Phone-Universal-0.3.11-FocusHeroFix-9c251293.apk` +- `Silo-TV-Universal-0.3.11-TVFocusHeroFix-9c251293.apk` SHA-256: diff --git a/docs/reviews/2026-07-27-android-tv-navigation-remediation-executive-summary.md b/docs/reviews/2026-07-27-android-tv-navigation-remediation-executive-summary.md index 772e20017d..21b2f07616 100644 --- a/docs/reviews/2026-07-27-android-tv-navigation-remediation-executive-summary.md +++ b/docs/reviews/2026-07-27-android-tv-navigation-remediation-executive-summary.md @@ -68,7 +68,7 @@ After the change, a combined cold-navigation run recorded 769 frames, 114 janky frames (14.82%), p50 10 ms, p90 24 ms, p95 46 ms, and p99 300 ms. The captured run contained only five combined HTTP-completion/GC log matches. -Supply-chain policy checks, shared and TV focused unit tests, Android shared +Supply-chain policy checks, shared and TV-focused unit tests, Android shared tests, and the minified TV release assembly passed. A final independent review approved the branch after two correction rounds. diff --git a/docs/superpowers/plans/2026-07-28-android-tv-active-header-focus-editorial-hero.md b/docs/superpowers/plans/2026-07-28-android-tv-active-header-focus-editorial-hero.md index b69b3de169..11c817d7f9 100644 --- a/docs/superpowers/plans/2026-07-28-android-tv-active-header-focus-editorial-hero.md +++ b/docs/superpowers/plans/2026-07-28-android-tv-active-header-focus-editorial-hero.md @@ -4,7 +4,7 @@ **Goal:** Make content-to-header navigation land on the active TV section and present ordered editorial browsing metadata on Android phone and TV. -**Architecture:** Keep `TvMainShell` as the route-aware focus coordinator, pass its active root explicitly through `TvShellFocusState`, and let `TvTopMenuBar` apply the existing requester after composition. Keep TV hero transformation inside `TvMarqueeContent.from` and phone hero transformation in a small pure `FeaturedCarousel` metadata helper, using only existing `SectionItem` data and leaving player/detail surfaces unchanged. +**Architecture:** Keep `TvMainShell` as the route-aware focus coordinator, pass its active root explicitly through `TvShellFocusState`, and let `TvTopMenuBar` apply the existing requester after composition. Keep TV hero transformation inside `TvMarqueeContent.from` and phone hero transformation in the small pure `featuredHeroMetadata` mapper, using only existing `SectionItem` data and leaving player/detail surfaces unchanged. **Tech Stack:** Kotlin 2.1, Jetpack Compose/Compose for TV, Compose focus and `FlowRow` layout APIs, Kotlin coroutines, Kotlin test/JUnit, Gradle. @@ -70,7 +70,7 @@ - Modify: `androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/shell/TvShellFocusStateTest.kt:90-125,245-280` **Interfaces:** -- Consumes: `TvTopMenuPanel.Root(TvRootDestination)`, `TvShellFocusState.requestMenuFocus(TvTopMenuPanel?)`, and each existing top-menu `FocusRequester`. +- Consumes: `TvTopMenuPanel.Root(TvRootDestination)`, `TvShellFocusState.requestMenuFocusIfAvailable(TvTopMenuPanel?, Boolean)`, and each existing top-menu `FocusRequester`. - Produces: `internal suspend fun requestTopMenuFocusUntilApplied(awaitFrame: suspend () -> Unit, requestFocus: () -> Boolean)`. - Produces: `TvShellFocusState.onBack(onTabRoot: Boolean, menuFocusTarget: TvTopMenuPanel? = null): TvShellBackAction`. - Produces: one `selectedMenuFocusTarget: TvTopMenuPanel?` in `TvMainShell`, reused by content Up and Back. @@ -218,32 +218,41 @@ focusState.onBack( Use it at both first-row Up handoffs: ```kotlin -focusState.requestMenuFocus(selectedMenuFocusTarget) +focusState.requestMenuFocusIfAvailable( + selectedMenuFocusTarget, + allowNullTarget = currentRoute == TvMainRoute.Search.route, +) ``` Leave `selectedMenuFocusTarget` null on Search. `TvTopMenuBar` must continue using `isSearchActive` to select Search for that route; other secondary routes must not silently select Home. -- [ ] **Step 7: Apply the requester after composition and only acknowledge success** +- [ ] **Step 7: Apply the requester after composition and record the handled identity** -In `TvTopMenuBar`, replace the immediate focus call inside the -`LaunchedEffect(focusRequest, isFocusSuppressed)` with: +In `TvTopMenuBar`, track `focusRequestIdentity` as +`focusRequest to focusRequestTarget`, then replace the immediate focus call +inside the `LaunchedEffect(focusRequest, focusRequestTarget, isFocusSuppressed)` +with: ```kotlin requestTopMenuFocusUntilApplied( awaitFrame = { androidx.compose.runtime.withFrameNanos { } }, + isTargetCurrent = { + currentFocusRequestTarget == focusRequestTarget && + isTopMenuFocusTargetAvailable(focusRequestTarget, currentDestinations) + }, requestFocus = { runCatching { requester.requestFocus() }.getOrDefault(false) }, ) -lastHandledFocusRequest = focusRequest +lastHandledFocusRequest = focusRequestIdentity ``` -Move the existing `lastHandledFocusRequest = focusRequest` assignment out of -the pre-request path. The frame loop suspends rather than spins and is cancelled -automatically if the `LaunchedEffect` keys change. Keep the explicit-target -resolution and `dwellSuppressedButton` behavior unchanged. +Move the existing `lastHandledFocusRequest = focusRequestIdentity` assignment +out of the pre-request path. The frame loop suspends rather than spins and is +cancelled automatically if the `LaunchedEffect` keys change. Keep the +explicit-target resolution and `dwellSuppressedButton` behavior unchanged. - [ ] **Step 8: Run focused tests and verify GREEN** @@ -700,8 +709,8 @@ In `FeaturedCarousel.kt`: - import `ExperimentalLayoutApi` and `FlowRow` from `androidx.compose.foundation.layout`; - annotate `FeaturedCardContent` with `@OptIn(ExperimentalLayoutApi::class)`; -- replace `remember(item) { metadataChips(item) }` with - `remember(item) { featuredHeroMetadata(item) }`; +- use `remember(item) { featuredHeroMetadata(item) }` for the phone hero + metadata; - replace the single `Row` with: ```kotlin From 4d18591d1753a813d27f0d8325bb5cce2bbf15c5 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 12:41:15 +0200 Subject: [PATCH 60/65] docs: remove remaining local paths --- .../task-4-report.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.superpowers/sdd/2026-07-28-android-tv-active-header-focus-editorial-hero/task-4-report.md b/.superpowers/sdd/2026-07-28-android-tv-active-header-focus-editorial-hero/task-4-report.md index a0733193df..27b5e104a9 100644 --- a/.superpowers/sdd/2026-07-28-android-tv-active-header-focus-editorial-hero/task-4-report.md +++ b/.superpowers/sdd/2026-07-28-android-tv-active-header-focus-editorial-hero/task-4-report.md @@ -113,7 +113,7 @@ Physical device safety: TV smoke on final TV APK: -- Installed `/androidTvApp/build/outputs/apk/release/androidTvApp-universal-release.apk` on `Silo_TV`. +- Installed `androidTvApp/build/outputs/apk/release/androidTvApp-universal-release.apk` on `Silo_TV`. - Home: from content card, fresh Up focused the Home top pill. Pass. - Movies library: from first content card, first Up left focus on the content card; second Up focused the Movies pill. Not a clean pass. - For You: from content, fresh Up focused the For You control. Pass. @@ -124,7 +124,7 @@ TV smoke on final TV APK: Phone smoke on final phone APK: -- Installed `/androidApp/build/outputs/apk/release/androidApp-universal-release.apk` on `Silo_Phone`. +- Installed `androidApp/build/outputs/apk/release/androidApp-universal-release.apk` on `Silo_Phone`. - Opened Libraries > Movies. The Movies library Recommended hero displayed editorial chips `2004`, `7.3`, `War`, `R`, with no generic `Movie` chip, and Play / More Info visible. - The selected movie did not show a runtime chip in the UIAutomator dump, so the requested movie smoke is partial rather than a full pass. - Episode carousel page smoke was not completed. @@ -155,7 +155,7 @@ SHA-256: `apkanalyzer` status: -- `/opt/homebrew/bin/apkanalyzer` failed with `IllegalStateException: Cannot locate latest build tools`, even with `ANDROID_HOME` and `ANDROID_SDK_ROOT` set. +- `apkanalyzer` failed with `IllegalStateException: Cannot locate latest build tools`, even with `ANDROID_HOME` and `ANDROID_SDK_ROOT` set. - Used SDK `aapt` as fallback for package/version/ABI metadata. `aapt dump badging` metadata: From f2bba1c46203260b41d78cafcdb868c5bad32cf3 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 12:43:57 +0200 Subject: [PATCH 61/65] docs: generalize tester artifact destinations --- ...026-07-28-android-tv-active-header-focus-editorial-hero.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/superpowers/plans/2026-07-28-android-tv-active-header-focus-editorial-hero.md b/docs/superpowers/plans/2026-07-28-android-tv-active-header-focus-editorial-hero.md index 11c817d7f9..71f40a429d 100644 --- a/docs/superpowers/plans/2026-07-28-android-tv-active-header-focus-editorial-hero.md +++ b/docs/superpowers/plans/2026-07-28-android-tv-active-header-focus-editorial-hero.md @@ -912,9 +912,9 @@ artifacts: ```bash cp androidApp/build/outputs/apk/release/androidApp-universal-release.apk \ - "/Users/jimcole/Desktop/Silo Releases/Silo-Phone-Universal-0.3.11-FocusHeroFix-$(git rev-parse --short HEAD).apk" + "Silo-Phone-Universal-0.3.11-FocusHeroFix-$(git rev-parse --short HEAD).apk" cp androidTvApp/build/outputs/apk/release/androidTvApp-universal-release.apk \ - "/Users/jimcole/Desktop/Silo Releases/Silo-TV-Universal-0.3.11-TVFocusHeroFix-$(git rev-parse --short HEAD).apk" + "Silo-TV-Universal-0.3.11-TVFocusHeroFix-$(git rev-parse --short HEAD).apk" ``` If a generated filename differs, select its universal artifact explicitly; From 77c87114967f2702775f7627a4794c78db35f6c4 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 13:10:18 +0200 Subject: [PATCH 62/65] fix(tv): close final PR 126 review findings --- .../task-4-report.md | 12 +++--- .../silo/tv/ui/shell/TvTopMenuBar.kt | 40 ++++++++++++------- .../silo/tv/ui/shell/TvTopMenuFocusRequest.kt | 22 ++++++++-- .../tv/ui/shell/TvTopMenuFocusRequestTest.kt | 33 +++++++++++++++ ...07-27-android-tv-navigation-remediation.md | 6 ++- ...7-28-android-phone-library-chrome-inset.md | 9 +++-- ...026-07-28-pr-126-coderabbit-remediation.md | 2 +- 7 files changed, 94 insertions(+), 30 deletions(-) diff --git a/.superpowers/sdd/2026-07-28-android-tv-active-header-focus-editorial-hero/task-4-report.md b/.superpowers/sdd/2026-07-28-android-tv-active-header-focus-editorial-hero/task-4-report.md index 27b5e104a9..d41e963b60 100644 --- a/.superpowers/sdd/2026-07-28-android-tv-active-header-focus-editorial-hero/task-4-report.md +++ b/.superpowers/sdd/2026-07-28-android-tv-active-header-focus-editorial-hero/task-4-report.md @@ -107,13 +107,14 @@ Repeat review result: Physical device safety: -- ADB showed physical Shield `192.168.1.128:5555`; I did not target it. -- TV smoke used AVD `Silo_TV`, serial `emulator-5554`. -- Phone smoke used AVD `Silo_Phone`, serial `emulator-5556`. +- ADB showed an unapproved physical TV device; I did not target it. +- TV smoke used the dedicated TV emulator. +- Phone smoke used the dedicated phone emulator. TV smoke on final TV APK: -- Installed `androidTvApp/build/outputs/apk/release/androidTvApp-universal-release.apk` on `Silo_TV`. +- Installed `androidTvApp/build/outputs/apk/release/androidTvApp-universal-release.apk` + on the dedicated TV emulator. - Home: from content card, fresh Up focused the Home top pill. Pass. - Movies library: from first content card, first Up left focus on the content card; second Up focused the Movies pill. Not a clean pass. - For You: from content, fresh Up focused the For You control. Pass. @@ -124,7 +125,8 @@ TV smoke on final TV APK: Phone smoke on final phone APK: -- Installed `androidApp/build/outputs/apk/release/androidApp-universal-release.apk` on `Silo_Phone`. +- Installed `androidApp/build/outputs/apk/release/androidApp-universal-release.apk` + on the dedicated phone emulator. - Opened Libraries > Movies. The Movies library Recommended hero displayed editorial chips `2004`, `7.3`, `War`, `R`, with no generic `Movie` chip, and Play / More Info visible. - The selected movie did not show a runtime chip in the UIAutomator dump, so the requested movie smoke is partial rather than a full pass. - Episode carousel page smoke was not completed. diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuBar.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuBar.kt index b9bd48a9a3..e95b99c5ba 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuBar.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuBar.kt @@ -234,23 +234,35 @@ fun TvTopMenuBar( val currentDestinations by rememberUpdatedState(destinations) var lastHandledFocusRequest by remember { mutableStateOf>(0 to null) } val focusRequestIdentity = focusRequest to focusRequestTarget - LaunchedEffect(focusRequest, focusRequestTarget, isFocusSuppressed) { - if (isFocusSuppressed) return@LaunchedEffect - if (focusRequestIdentity == lastHandledFocusRequest) return@LaunchedEffect - val explicitFocus = focusRequestTarget?.let(::focusForPanel) - dwellSuppressedButton = explicitFocus - val requester = explicitFocus?.let(::requesterForFocus) ?: selectedEntryRequester() - requestTopMenuFocusUntilApplied( - awaitFrame = { androidx.compose.runtime.withFrameNanos { } }, - isTargetCurrent = { - currentFocusRequestTarget == focusRequestTarget && - isTopMenuFocusTargetAvailable(focusRequestTarget, currentDestinations) - }, + val focusRequestTargetAvailable = + isTopMenuFocusTargetAvailable(focusRequestTarget, destinations) + LaunchedEffect( + focusRequest, + focusRequestTarget, + isFocusSuppressed, + focusRequestTargetAvailable, + ) { + lastHandledFocusRequest = handleTopMenuFocusRequestIfAvailable( + requestIdentity = focusRequestIdentity, + lastHandledRequest = lastHandledFocusRequest, + isFocusSuppressed = isFocusSuppressed, + isTargetAvailable = focusRequestTargetAvailable, requestFocus = { - runCatching { requester.requestFocus() }.getOrDefault(false) + val explicitFocus = focusRequestTarget?.let(::focusForPanel) + dwellSuppressedButton = explicitFocus + val requester = explicitFocus?.let(::requesterForFocus) ?: selectedEntryRequester() + requestTopMenuFocusUntilApplied( + awaitFrame = { androidx.compose.runtime.withFrameNanos { } }, + isTargetCurrent = { + currentFocusRequestTarget == focusRequestTarget && + isTopMenuFocusTargetAvailable(focusRequestTarget, currentDestinations) + }, + requestFocus = { + runCatching { requester.requestFocus() }.getOrDefault(false) + }, + ) }, ) - lastHandledFocusRequest = focusRequestIdentity } LaunchedEffect(focusedButton) { diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuFocusRequest.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuFocusRequest.kt index bc3dc2d51d..678e6d46be 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuFocusRequest.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuFocusRequest.kt @@ -10,15 +10,29 @@ internal fun isTopMenuFocusTargetAvailable( TvTopMenuPanel.Profile, null -> true } +internal suspend fun handleTopMenuFocusRequestIfAvailable( + requestIdentity: Pair, + lastHandledRequest: Pair, + isFocusSuppressed: Boolean, + isTargetAvailable: Boolean, + requestFocus: suspend () -> Boolean, +): Pair { + if (isFocusSuppressed || !isTargetAvailable || requestIdentity == lastHandledRequest) { + return lastHandledRequest + } + return if (requestFocus()) requestIdentity else lastHandledRequest +} + internal suspend fun requestTopMenuFocusUntilApplied( awaitFrame: suspend () -> Unit, isTargetCurrent: () -> Boolean = { true }, requestFocus: () -> Boolean, -) { +): Boolean { repeat(TopMenuFocusMaxAttempts) { - if (!isTargetCurrent()) return + if (!isTargetCurrent()) return false awaitFrame() - if (!isTargetCurrent()) return - if (requestFocus()) return + if (!isTargetCurrent()) return false + if (requestFocus()) return true } + return false } diff --git a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuFocusRequestTest.kt b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuFocusRequestTest.kt index 1772d7d9c3..88adb05527 100644 --- a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuFocusRequestTest.kt +++ b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuFocusRequestTest.kt @@ -81,4 +81,37 @@ class TvTopMenuFocusRequestTest { ), ) } + + @Test + fun focusRequestRemainsPendingUntilItsLibraryDestinationAppears() = runTest { + val movies = TvRootDestination.LibraryType(TvLibraryTabType.Movies) + val identity = 1 to TvTopMenuPanel.Root(movies) + val initialHandled = 0 to null + var focusAttempts = 0 + + val handledWhileAbsent = handleTopMenuFocusRequestIfAvailable( + requestIdentity = identity, + lastHandledRequest = initialHandled, + isFocusSuppressed = false, + isTargetAvailable = false, + requestFocus = { + focusAttempts += 1 + true + }, + ) + val handledAfterAppearing = handleTopMenuFocusRequestIfAvailable( + requestIdentity = identity, + lastHandledRequest = handledWhileAbsent, + isFocusSuppressed = false, + isTargetAvailable = true, + requestFocus = { + focusAttempts += 1 + true + }, + ) + + assertEquals(initialHandled, handledWhileAbsent) + assertEquals(identity, handledAfterAppearing) + assertEquals(1, focusAttempts) + } } diff --git a/docs/superpowers/plans/2026-07-27-android-tv-navigation-remediation.md b/docs/superpowers/plans/2026-07-27-android-tv-navigation-remediation.md index bf7c4acd67..0ac4fdae16 100644 --- a/docs/superpowers/plans/2026-07-27-android-tv-navigation-remediation.md +++ b/docs/superpowers/plans/2026-07-27-android-tv-navigation-remediation.md @@ -857,7 +857,8 @@ git commit -m "fix(tv): unify for-you saved-list routes" - Modify only if verification exposes a feature regression: files already listed in Tasks 1-4. **Interfaces:** -- Consumes: all prior task commits and the authenticated local Shield at `192.168.1.128:5555`. +- Consumes: all prior task commits and an explicitly approved authenticated TV + test target. - Produces: a concise executive summary containing impact, causes, remedy, quantified before/after evidence, rollout risk, and rollback boundary. - [ ] **Step 1: Run supply-chain and complete relevant unit gates** @@ -894,7 +895,8 @@ Expected: both tasks exit zero. Install only on the explicitly selected Shield if the candidate signer is compatible with the installed package; otherwise use the dedicated TV emulator. Preserve app data with: ```bash -adb -s 192.168.1.128:5555 install -r \ +TV_TEST_SERIAL="" +adb -s "$TV_TEST_SERIAL" install -r \ androidTvApp/build/outputs/apk/release/androidTvApp-universal-release.apk ``` diff --git a/docs/superpowers/plans/2026-07-28-android-phone-library-chrome-inset.md b/docs/superpowers/plans/2026-07-28-android-phone-library-chrome-inset.md index 0f8aabdc10..f71111ce6e 100644 --- a/docs/superpowers/plans/2026-07-28-android-phone-library-chrome-inset.md +++ b/docs/superpowers/plans/2026-07-28-android-phone-library-chrome-inset.md @@ -310,7 +310,8 @@ Expected: BUILD SUCCESSFUL; no unit-test failures; both universal release APKs e - [ ] **Step 3: Perform emulator-only visual validation when available** -Use only `emulator-5556`. Install the debug build serial-specifically, launch the +Use only a dedicated phone emulator selected explicitly through the local test +harness. Install the debug build serial-specifically, launch the phone app, and verify Recommended, Browse, and Collections content stops at the fixed chrome boundary before and after scrolling. Open/close the profile menu and verify the list position does not change. If the dedicated emulator is not @@ -331,9 +332,9 @@ androidApp/build/outputs/apk/release/androidApp-universal-release.apk androidTvApp/build/outputs/apk/release/androidTvApp-universal-release.apk ``` -Copy them without overwriting existing files into -`/Users/jimcole/Desktop/Silo Releases` using filenames containing `0.3.11`, -`FocusHeroLibraryInset`, and the final short commit. +Copy them without overwriting existing files into the tester-selected release +artifact destination outside the repository, using filenames containing +`0.3.11`, `FocusHeroLibraryInset`, and the final short commit. - [ ] **Step 6: Final hygiene and PR update** diff --git a/docs/superpowers/plans/2026-07-28-pr-126-coderabbit-remediation.md b/docs/superpowers/plans/2026-07-28-pr-126-coderabbit-remediation.md index 9ebaa3f0cb..70497b39a5 100644 --- a/docs/superpowers/plans/2026-07-28-pr-126-coderabbit-remediation.md +++ b/docs/superpowers/plans/2026-07-28-pr-126-coderabbit-remediation.md @@ -433,7 +433,7 @@ update focus pseudocode to use `requestMenuFocusIfAvailable` plus the - [ ] **Step 3: Verify documentation** ```bash -rg -n '/Users/jimcole' \ +rg -n --pcre2 '/(Users|home)/[^/[:space:]]+' \ .superpowers/sdd/2026-07-28-android-tv-active-header-focus-editorial-hero/task-4-report.md rg -n 'FeaturedCarousel\\.metadataChips|TV focused|requestMenuFocus\\(selectedMenuFocusTarget\\)' \ docs/reviews/2026-07-27-android-tv-navigation-remediation-executive-summary.md \ From 615ff876fac7a0b00c15231d4db1553337cac604 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 13:28:14 +0200 Subject: [PATCH 63/65] test(android): fail closed room source anchors --- .../player/RoomDeliveryKeySourceTest.kt | 37 +++++++-- .../player/TvRoomDeliveryKeySourceTest.kt | 37 +++++++-- ...026-07-28-pr-126-coderabbit-remediation.md | 79 ++++++++++--------- 3 files changed, 99 insertions(+), 54 deletions(-) diff --git a/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/player/RoomDeliveryKeySourceTest.kt b/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/player/RoomDeliveryKeySourceTest.kt index 2d486bc06a..d6d4784a02 100644 --- a/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/player/RoomDeliveryKeySourceTest.kt +++ b/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/player/RoomDeliveryKeySourceTest.kt @@ -3,24 +3,45 @@ package org.siloserver.silo.android.ui.screens.player import java.io.File import kotlin.test.Test import kotlin.test.assertFalse +import kotlin.test.assertFailsWith import kotlin.test.assertTrue class RoomDeliveryKeySourceTest { + private val reportingStartAnchor = "// Drift reporting loop" + private val reportingEndAnchor = "// ready / buffering during the waiting barrier." + private val controllerSource = File( "src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/RoomSyncController.kt", ).readText() @Test fun stateReportRequiresAnExplicitNonNullDeliveryKey() { - val reportingBlock = controllerSource - .substringAfter("// Drift reporting loop") - .substringBefore("// ready / buffering during the waiting barrier.") + val reportingBlock = reportingBlock(controllerSource) + val guardIndex = reportingBlock.indexOf("deliveryKey != null") + val stateReportIndex = reportingBlock.indexOf("repository.stateReport(") assertFalse(reportingBlock.contains("deliveryKey!!")) - assertTrue(reportingBlock.contains("deliveryKey != null")) - assertTrue( - reportingBlock.indexOf("deliveryKey != null") < - reportingBlock.indexOf("repository.stateReport("), - ) + assertTrue(guardIndex >= 0, "Drift reporting block must guard deliveryKey explicitly.") + assertTrue(stateReportIndex >= 0, "Drift reporting block must report state.") + assertTrue(guardIndex < stateReportIndex) + } + + @Test + fun reportingBlockFailsClosedWhenEitherAnchorIsMissing() { + assertFailsWith { + reportingBlock(controllerSource.replace(reportingStartAnchor, "")) + } + assertFailsWith { + reportingBlock(controllerSource.replace(reportingEndAnchor, "")) + } + } + + private fun reportingBlock(source: String): String { + val startAnchorIndex = source.indexOf(reportingStartAnchor) + assertTrue(startAnchorIndex >= 0, "Missing drift-reporting start anchor.") + val blockStart = startAnchorIndex + reportingStartAnchor.length + val endAnchorIndex = source.indexOf(reportingEndAnchor, startIndex = blockStart) + assertTrue(endAnchorIndex >= blockStart, "Missing drift-reporting end anchor.") + return source.substring(blockStart, endAnchorIndex) } } diff --git a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/player/TvRoomDeliveryKeySourceTest.kt b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/player/TvRoomDeliveryKeySourceTest.kt index ef5050eb00..e350c30bb0 100644 --- a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/player/TvRoomDeliveryKeySourceTest.kt +++ b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/player/TvRoomDeliveryKeySourceTest.kt @@ -3,24 +3,45 @@ package org.siloserver.silo.tv.ui.screens.player import java.io.File import kotlin.test.Test import kotlin.test.assertFalse +import kotlin.test.assertFailsWith import kotlin.test.assertTrue class TvRoomDeliveryKeySourceTest { + private val reportingStartAnchor = "// Drift reporting loop" + private val reportingEndAnchor = "// ready / buffering during the waiting barrier." + private val controllerSource = File( "src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvRoomSyncController.kt", ).readText() @Test fun stateReportRequiresAnExplicitNonNullDeliveryKey() { - val reportingBlock = controllerSource - .substringAfter("// Drift reporting loop") - .substringBefore("// ready / buffering during the waiting barrier.") + val reportingBlock = reportingBlock(controllerSource) + val guardIndex = reportingBlock.indexOf("deliveryKey != null") + val stateReportIndex = reportingBlock.indexOf("repository.stateReport(") assertFalse(reportingBlock.contains("deliveryKey!!")) - assertTrue(reportingBlock.contains("deliveryKey != null")) - assertTrue( - reportingBlock.indexOf("deliveryKey != null") < - reportingBlock.indexOf("repository.stateReport("), - ) + assertTrue(guardIndex >= 0, "Drift reporting block must guard deliveryKey explicitly.") + assertTrue(stateReportIndex >= 0, "Drift reporting block must report state.") + assertTrue(guardIndex < stateReportIndex) + } + + @Test + fun reportingBlockFailsClosedWhenEitherAnchorIsMissing() { + assertFailsWith { + reportingBlock(controllerSource.replace(reportingStartAnchor, "")) + } + assertFailsWith { + reportingBlock(controllerSource.replace(reportingEndAnchor, "")) + } + } + + private fun reportingBlock(source: String): String { + val startAnchorIndex = source.indexOf(reportingStartAnchor) + assertTrue(startAnchorIndex >= 0, "Missing drift-reporting start anchor.") + val blockStart = startAnchorIndex + reportingStartAnchor.length + val endAnchorIndex = source.indexOf(reportingEndAnchor, startIndex = blockStart) + assertTrue(endAnchorIndex >= blockStart, "Missing drift-reporting end anchor.") + return source.substring(blockStart, endAnchorIndex) } } diff --git a/docs/superpowers/plans/2026-07-28-pr-126-coderabbit-remediation.md b/docs/superpowers/plans/2026-07-28-pr-126-coderabbit-remediation.md index 70497b39a5..d35dae649c 100644 --- a/docs/superpowers/plans/2026-07-28-pr-126-coderabbit-remediation.md +++ b/docs/superpowers/plans/2026-07-28-pr-126-coderabbit-remediation.md @@ -1,6 +1,8 @@ # PR #126 CodeRabbit Remediation Implementation Plan -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. +> **Status:** Completed 2026-07-28. All remediation tasks and their recorded verification/review steps were completed on `fix/tv-for-you-cold-navigation`. + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkboxes for tracking. **Goal:** Resolve every substantiated CodeRabbit finding on PR #126 while preserving intentional shared-request and Watch Together delivery semantics. @@ -48,7 +50,7 @@ - Consumes: `TvForYouEntryRequest.next(selection: SavedListSelection?)`. - Produces: `TvForYouEntryRequest.nextForTopLevelForYou(): TvForYouEntryRequest`; Alphabet and Calendar both register their content-Up fallback with the shell. -- [ ] **Step 1: Write the For You RED regression** +- [x] **Step 1: Write the For You RED regression** Add to `TvForYouEntryRequestTest`: @@ -65,7 +67,7 @@ fun topLevelForYouRequestClearsSavedListSelection() { } ``` -- [ ] **Step 2: Write the Alphabet wiring RED regression** +- [x] **Step 2: Write the Alphabet wiring RED regression** Create a source-contract test that loads `TvLibraryDetailScreen.kt`, isolates the @@ -78,7 +80,7 @@ onContentUpFallbackChanged = onContentUpFallbackChanged Also assert the existing `TvCalendarScreen(...)` call still contains `onContentUpFallbackChanged = onContentUpFallback`. -- [ ] **Step 3: Run RED** +- [x] **Step 3: Run RED** Run: @@ -92,7 +94,7 @@ Run: Expected: failure because `nextForTopLevelForYou` is absent and the Alphabet branch does not forward the fallback. -- [ ] **Step 4: Implement the minimal GREEN changes** +- [x] **Step 4: Implement the minimal GREEN changes** Add: @@ -111,7 +113,7 @@ if (dest == TvRootDestination.ForYou) { Forward `onContentUpFallbackChanged` in the Alphabet `LibraryTab` call exactly as Browse already does. -- [ ] **Step 5: Run GREEN and focused neighboring tests** +- [x] **Step 5: Run GREEN and focused neighboring tests** Run: @@ -126,7 +128,7 @@ Run: Expected: all selected tests pass. -- [ ] **Step 6: Commit Task 1** +- [x] **Step 6: Commit Task 1** ```bash git add androidTvApp/src/androidMain androidTvApp/src/androidUnitTest @@ -147,7 +149,7 @@ git commit -m "fix(tv): close reviewed focus routing gaps" - Consumes: `TvFocusMarqueeState.seedInitialPreview`, `TvMarqueeContent.from`, and `featuredHeroMetadata`. - Produces: identity-aware page-entry reseeding that stops after real focus; consistent `(0, 10]` rating tokens on both clients. -- [ ] **Step 1: Write page-entry identity RED tests** +- [x] **Step 1: Write page-entry identity RED tests** Add tests that: @@ -168,7 +170,7 @@ assertEquals("focused-row#focused-item", state.content?.id) assertEquals("focused-row#focused-item", state.candidate?.id) ``` -- [ ] **Step 2: Write phone/TV rating and mixed-field RED tests** +- [x] **Step 2: Write phone/TV rating and mixed-field RED tests** For both clients assert: @@ -192,7 +194,7 @@ durationSeconds = Double.NaN retains `"8.4"`. -- [ ] **Step 3: Run RED** +- [x] **Step 3: Run RED** ```bash ./gradlew --no-daemon \ @@ -206,7 +208,7 @@ retains `"8.4"`. Expected: the row-identity and upper-bound assertions fail. -- [ ] **Step 4: Implement minimal marquee arbitration** +- [x] **Step 4: Implement minimal marquee arbitration** Keep `seedInitialPreview` as the boundary. Build `next` first, ignore seeds once `focusedMarqueeId != null`, and otherwise replace a different page-entry @@ -224,7 +226,7 @@ fun seedInitialPreview(item: SectionItem, rowTitle: String, rowIdentity: String Include `initialMarqueeSeed?.rowIdentity` in the `LaunchedEffect` key and call `seedInitialPreview` without an outer `marquee.content == null` gate. -- [ ] **Step 5: Implement bounded shared rating helpers** +- [x] **Step 5: Implement bounded shared rating helpers** In each client boundary use a small private helper equivalent to: @@ -236,11 +238,11 @@ private fun validImdbRating(rating: Double?): Double? = Route both TV episode/non-episode branches through one TV `ratingToken` helper to remove the duplicated filter. -- [ ] **Step 6: Run GREEN** +- [x] **Step 6: Run GREEN** Repeat the Task 2 focused command. Expected: all selected tests pass. -- [ ] **Step 7: Commit Task 2** +- [x] **Step 7: Commit Task 2** ```bash git add androidApp/src/androidMain androidApp/src/androidUnitTest \ @@ -262,7 +264,7 @@ git commit -m "fix(android): bound hero metadata and marquee identity" - Consumes: `RoomDeliveryLatch.isServerAttached`. - Produces: identical delivery decisions with no nullable-key dereference or force-unwrapped reporting key. -- [ ] **Step 1: Strengthen nullable-key characterization** +- [x] **Step 1: Strengthen nullable-key characterization** Add latch cases asserting `false` for: @@ -272,13 +274,13 @@ isServerAttached(key = validKey, echo = null) isServerAttached(key = validKey, echo = wrongEpochEcho) ``` -- [ ] **Step 2: Write source-contract RED tests** +- [x] **Step 2: Write source-contract RED tests** Assert each room-sync controller reporting block does not contain `deliveryKey!!` and does contain an explicit `deliveryKey != null` guard before `stateReport`. -- [ ] **Step 3: Run RED** +- [x] **Step 3: Run RED** ```bash ./gradlew --no-daemon \ @@ -291,10 +293,11 @@ Assert each room-sync controller reporting block does not contain --max-workers=2 ``` -Expected: latch behavior remains green; both source-contract tests fail on -`deliveryKey!!`. +Historical pre-fix result: latch behavior remained green while both +source-contract tests failed because their reporting blocks used +`deliveryKey!!`. The current tree binds a non-null key before state reporting. -- [ ] **Step 4: Make nullability explicit without semantic changes** +- [x] **Step 4: Make nullability explicit without semantic changes** Use: @@ -308,11 +311,11 @@ key != null && in the latch. In both controllers require a non-null local key before `isServerAttached` and pass `key.playbackSessionId` to `stateReport`. -- [ ] **Step 5: Run GREEN and neighboring room-sync tests** +- [x] **Step 5: Run GREEN and neighboring room-sync tests** Run the Task 3 command plus `*RoomSyncStateReportGateTest`. Expected: all pass. -- [ ] **Step 6: Commit Task 3** +- [x] **Step 6: Commit Task 3** ```bash git add shared/src/commonMain shared/src/commonTest \ @@ -336,7 +339,7 @@ git commit -m "refactor(watch-together): make delivery keys explicit" - Consumes: `CoroutineDispatcher`, identity transition generations, and `CatalogCacheWriteLease`. - Produces: injectable home-request dispatcher and private helpers that preserve existing generation and cache-write decisions. -- [ ] **Step 1: Establish the characterization-test baseline** +- [x] **Step 1: Establish the characterization-test baseline** ```bash ./gradlew --no-daemon :shared:test \ @@ -348,7 +351,7 @@ git commit -m "refactor(watch-together): make delivery keys explicit" Expected: all selected tests pass before refactoring. -- [ ] **Step 2: Inject the home request dispatcher** +- [x] **Step 2: Inject the home request dispatcher** Add a constructor parameter with the existing runtime default: @@ -360,7 +363,7 @@ and use it in `homeRequestScope`. Update gated concurrency tests to pass a `StandardTestDispatcher(testScheduler)` and extract one local helper that builds the gated `MockEngine`/repository without changing assertions. -- [ ] **Step 3: Extract the phone library identity comparison** +- [x] **Step 3: Extract the phone library identity comparison** Add: @@ -376,7 +379,7 @@ Keep request/query generation comparisons in their respective methods. Do not retain or cancel a recommendation `Job`; shared repository work must remain independent of one superseded UI caller. -- [ ] **Step 4: Extract repository-local guarded-write helpers** +- [x] **Step 4: Extract repository-local guarded-write helpers** In both repositories add the private pattern: @@ -394,12 +397,12 @@ private suspend fun writeIfIdentityUnchanged( Route existing cache write sites through it without moving network calls or changing success/fallback behavior. -- [ ] **Step 5: Re-run characterization tests** +- [x] **Step 5: Re-run characterization tests** Repeat the Task 4 baseline command. Expected: all selected tests pass with the same assertions. -- [ ] **Step 6: Commit Task 4** +- [x] **Step 6: Commit Task 4** ```bash git add shared/src/commonMain shared/src/commonTest androidApp/src/androidMain @@ -417,20 +420,20 @@ git commit -m "refactor(android): clarify reviewed request guards" - Consumes: current helper and focus-routing names. - Produces: reproducible repository-relative evidence and implementation-accurate plan text. -- [ ] **Step 1: Replace local paths** +- [x] **Step 1: Replace local paths** Replace the worktree with `fix/tv-for-you-cold-navigation worktree` and replace Desktop artifact paths with the artifact filenames while retaining hashes and signing notes. -- [ ] **Step 2: Correct stale wording** +- [x] **Step 2: Correct stale wording** Change `TV focused` to `TV-focused`, replace the stale `FeaturedCarousel.metadataChips` reference with `featuredHeroMetadata`, and update focus pseudocode to use `requestMenuFocusIfAvailable` plus the `(focusRequest, focusRequestTarget)` handled identity. -- [ ] **Step 3: Verify documentation** +- [x] **Step 3: Verify documentation** ```bash rg -n --pcre2 '/(Users|home)/[^/[:space:]]+' \ @@ -443,7 +446,7 @@ git diff --check Expected: both `rg` commands return no matches and `git diff --check` passes. -- [ ] **Step 4: Commit Task 5** +- [x] **Step 4: Commit Task 5** ```bash git add .superpowers/sdd/2026-07-28-android-tv-active-header-focus-editorial-hero/task-4-report.md \ @@ -462,7 +465,7 @@ git commit -m "docs: resolve PR 126 review findings" - Consumes: all correction commits. - Produces: reviewed branch with fresh focused, full, supply-chain, and release evidence. -- [ ] **Step 1: Run complete unit gates** +- [x] **Step 1: Run complete unit gates** ```bash ./gradlew --no-daemon \ @@ -475,7 +478,7 @@ git commit -m "docs: resolve PR 126 review findings" Expected: exit 0 with no failed tests. -- [ ] **Step 2: Run supply-chain policy** +- [x] **Step 2: Run supply-chain policy** ```bash ./scripts/test-check-build-supply-chain.sh @@ -484,7 +487,7 @@ Expected: exit 0 with no failed tests. Expected: both exit 0. -- [ ] **Step 3: Run phone and TV release compilation** +- [x] **Step 3: Run phone and TV release compilation** ```bash ./gradlew --no-daemon \ @@ -497,7 +500,7 @@ Expected: both exit 0. Expected: `BUILD SUCCESSFUL`; these artifacts are verification-only and are not installed or deployed. -- [ ] **Step 4: Perform diff and scope checks** +- [x] **Step 4: Perform diff and scope checks** ```bash git diff --check origin/main...HEAD @@ -508,7 +511,7 @@ git log --oneline origin/main..HEAD Expected: no whitespace errors, no uncommitted changes, and only the documented PR #126 plus review-remediation commits. -- [ ] **Step 5: Obtain independent focused review** +- [x] **Step 5: Obtain independent focused review** Request review of `f822d22c..HEAD` against this plan and the design spec. Require explicit assessment of the marquee real-focus invariant, For You reset, @@ -516,7 +519,7 @@ Alphabet fallback, request-sharing non-cancellation, Watch Together delivery semantics, and test adequacy. Fix any critical or important finding with a new focused RED/GREEN cycle. -- [ ] **Step 6: Push and update PR #126** +- [x] **Step 6: Push and update PR #126** Push `fix/tv-for-you-cold-navigation`, update the PR verification summary with fresh commands, and leave the PR open and unmerged. Record which CodeRabbit From 21ab78b2dec6f4a4dc8bf50c2a50bac869f94485 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 13:54:05 +0200 Subject: [PATCH 64/65] test(tv): keep subtitle adoption on test scheduler --- .../SubtitleTransactionIntegrationTest.kt | 23 +++++++++++-------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/player/SubtitleTransactionIntegrationTest.kt b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/player/SubtitleTransactionIntegrationTest.kt index 3a728eac46..53b31ef4fc 100644 --- a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/player/SubtitleTransactionIntegrationTest.kt +++ b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/player/SubtitleTransactionIntegrationTest.kt @@ -251,6 +251,10 @@ class SubtitleTransactionIntegrationTest { harness.awaitReplans(2) harness.awaitStopped("s2") harness.awaitAdopted("s3") + assertTrue( + testScheduler.currentTime < EVENT_TIMEOUT_MS, + "Adoption reached the pending Media3 mount deadline before the test could mount it.", + ) runCurrent() assertEquals(listOf("s1", "s1"), harness.replanBaseSessions) @@ -472,7 +476,6 @@ class SubtitleTransactionIntegrationTest { val media3Selections = mutableListOf() private val replanEvents = Channel(Channel.UNLIMITED) - private val adoptedEvents = Channel(Channel.UNLIMITED) private val persistenceEvents = Channel(Channel.UNLIMITED) private val startIndex = AtomicInteger() private val replanIndex = AtomicInteger() @@ -616,7 +619,6 @@ class SubtitleTransactionIntegrationTest { if (adopted && adoption.isCurrent()) { adoptedPlaybackRows[candidate.session.sessionId] = adoption.playback.subtitleTracks - adoptedEvents.send(candidate.session.sessionId) TvSubtitleAdoptionResult.Adopted } else { TvSubtitleAdoptionResult.Superseded @@ -790,14 +792,15 @@ class SubtitleTransactionIntegrationTest { } suspend fun awaitAdopted(sessionId: String) { - if (lifecycle.activeSessionId() == sessionId) return - withContext(Dispatchers.Default) { - withTimeout(5_000) { - while (adoptedEvents.receive() != sessionId) { - // Drain unrelated adoption completions. - } - } - } + awaitHarnessCondition( + transactionScheduler = transactionScheduler, + cleanupScheduler = transactionScheduler, + timeoutMillis = EVENT_TIMEOUT_MS, + condition = { + manager.activeSessionIdForTest() == sessionId && + lifecycle.activeSessionId() == sessionId + }, + ) } suspend fun awaitPersistence(count: Int) { From 58a248597a9f95aa08af7e0cfaf6b20ae2c9ce60 Mon Sep 17 00:00:00 2001 From: rxwatcher Date: Tue, 28 Jul 2026 14:12:49 +0200 Subject: [PATCH 65/65] test(android): await transient library request siblings --- .../libraries/LibrariesViewModelTest.kt | 24 +++++++++++++++---- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibrariesViewModelTest.kt b/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibrariesViewModelTest.kt index 83ecd06af4..4d4f762087 100644 --- a/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibrariesViewModelTest.kt +++ b/androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/libraries/LibrariesViewModelTest.kt @@ -16,11 +16,14 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.Job import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.delay import kotlinx.coroutines.flow.first +import kotlinx.coroutines.launch import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.runTest import kotlinx.coroutines.test.setMain +import kotlinx.coroutines.withTimeout import org.siloserver.silo.catalog.filter.CatalogFacet import org.siloserver.silo.catalog.filter.CatalogFilterState import org.siloserver.silo.network.SiloJson @@ -113,6 +116,7 @@ class LibrariesViewModelTest { val viewModel = fixture.viewModel() val store = ViewModelStore().also { it.put("libraries", viewModel) } try { + viewModel.viewModelScope.launch { delay(1) } fixture.awaitRequest("sections:1") viewModel.uiState.first { !it.isLoadingSections } viewModel.selectTab(LibrariesSubtab.Browse) @@ -222,11 +226,21 @@ class LibrariesViewModelTest { } } - private fun LibrariesViewModel.onlyActiveRequest(): Job = - viewModelScope.coroutineContext[Job] - ?.children - ?.single { it.isActive } - ?: error("Expected exactly one active Libraries request") + private suspend fun LibrariesViewModel.onlyActiveRequest(): Job = withTimeout(5_000) { + while (true) { + val activeRequests = viewModelScope.coroutineContext[Job] + ?.children + ?.filter { it.isActive } + ?.toList() + .orEmpty() + when (activeRequests.size) { + 0 -> error("Expected an active Libraries request") + 1 -> return@withTimeout activeRequests.single() + else -> delay(1) + } + } + error("Unreachable") + } private class DeferredLibrariesFixture( private val deferredKeys: Set,