Repository navigation
Conversation
📝 WalkthroughWalkthroughThe PR adds scoped Home request coalescing, bounded section hydration, durable final playback-position persistence, lifecycle-safe playback teardown, and route-aware Android mobile/TV detail and player updates. It also adds extensive unit and source-structure tests plus implementation plans and design specifications. ChangesAndroid performance and request-flow remediation
Estimated code review effort: 5 (Critical) | ~120 minutes Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 7
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
shared/src/androidMain/kotlin/org/siloserver/silo/network/EncryptedTokenManagerImpl.kt (1)
300-325: 🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy liftMake scope capture atomic with identity generation.
Lines 308 and 324 can observe a new generation after
changing()begins but before the transition updates state undermutex. That produces an old scope labeled with the new generation; if identifiers are reused, the request/cache validation can accept pre-transition data. Capture the generation and scope state in one transition-protected transaction.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@shared/src/androidMain/kotlin/org/siloserver/silo/network/EncryptedTokenManagerImpl.kt` around lines 300 - 325, Update snapshotCurrentScope so identity generation and all scope fields are captured atomically under the same transition protection as changing(). Ensure both the temporaryScope and active-scope branches read and label their snapshot from the same captured generation/state transaction, preventing an old scope from being paired with a newer identity generation.
🧹 Nitpick comments (2)
android-shared/src/androidMain/kotlin/org/siloserver/silo/common/startup/StartupWarmup.kt (1)
75-103: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winHydration/fallback algorithm duplicated with
HomeViewModel.fetchSections.This function reimplements the same unresolved-section filter → bounded-concurrency fetch →
resolveHomeSectionItems→ fully-resolved-tracking algorithm found inHomeViewModel.fetchSections(shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeViewModel.kt lines ~137-159). This function's shape (a named data class + suspend function taking afetchItemscallback) is actually the cleaner candidate to promote intocommonMainand reuse from both call sites.
See consolidated comment for the proposed extraction.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@android-shared/src/androidMain/kotlin/org/siloserver/silo/common/startup/StartupWarmup.kt` around lines 75 - 103, The hydration algorithm in hydrateStartupHomeSections duplicates HomeViewModel.fetchSections. Promote StartupHomeResolution and hydrateStartupHomeSections into commonMain, preserving the unresolved filtering, bounded-concurrency fetches, resolveHomeSectionItems usage, and fullyResolved behavior, then update both call sites to reuse the shared implementation and remove the duplicate logic.shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeViewModel.kt (1)
137-159: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winHydration fallback algorithm duplicated with
StartupWarmup.hydrateStartupHomeSections.This block reimplements the same unresolved-section filter → bounded-concurrency fetch →
resolveHomeSectionItems→ fully-resolved-tracking algorithm ashydrateStartupHomeSectionsinStartupWarmup.kt, just with aPair<ResolvedSection, Boolean>shape instead of a named result type. Behavior is equivalent today but the duplication risks silent drift between the ViewModel and startup-warmup paths on future changes.
See consolidated comment for the proposed shared-function extraction.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeViewModel.kt` around lines 137 - 159, Extract the duplicated section-hydration workflow from the HomeViewModel loading path into a shared function, then have both this flow and StartupWarmup.hydrateStartupHomeSections use it. Preserve the existing filtering, bounded concurrency, resolveHomeSectionItems fallback, and fully-resolved status while replacing the local Pair<ResolvedSection, Boolean> implementation with the shared result type.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In
`@android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/repository/RoomUserItemStateRepository.kt`:
- Around line 106-120: Make the scope check and final write in the repository
method containing snapshotProvider and recordPositionOwned execute under the
same generation gate or lock used by profile/credential transitions. Move or
coordinate validation with the Room transaction so an identity change cannot
occur between validation and commit; return false for stale scope, otherwise
complete the write before allowing the transition.
In
`@android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/FinalPlaybackPositionWriter.kt`:
- Around line 36-49: Update the worker loop in FinalPlaybackPositionWriter’s
init coroutine so failed write(snapshot) operations are retained instead of
being discarded after pending.clear(). Reinsert or otherwise preserve the latest
failed snapshots, retry them with bounded backoff, and keep the coroutine alive
while continuing to process wakeUp triggers and successful writes.
In
`@android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/data/repository/RoomUserItemStateRepositoryTest.kt`:
- Around line 245-265: Extend the repository tests around recordPosition to
cover a credential-generation mismatch for the same server and profile, varying
captured versus current credentialGenerationId while keeping identity otherwise
matching. Assert recordPosition rejects the stale write, both projection rows
remain absent as appropriate, and the outbox contains no SET_POSITION entry; use
the existing DAO/query helpers and test symbols.
In
`@android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/PlaybackSessionLifecycleLoggingTest.kt`:
- Around line 22-38: The current test only inspects source text instead of
validating lifecycle ordering. In PlaybackSessionLifecycleLoggingTest, add a
coroutine-based race test that blocks stopSession or its final flush, invokes
stopAsync(), verifies start() or adoptActiveSession() stays suspended, then
releases teardown and confirms the new session remains active. Replace or
supplement the substring assertions with this focused behavioral coverage.
In
`@androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerViewModel.kt`:
- Around line 3141-3180: Update onExit() to explicitly cancel upNextCountdownJob
and resolveNextEpisodeJob, and clear showUpNext before exiting. Ensure
startUpNextCountdown() cannot continue or invoke advanceToNextEpisode() after
exit, while preserving the existing exit guard and cleanup behavior.
In
`@androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt`:
- Around line 479-485: Update the collection probe loop around runCatching in
the library identity-probe flow to rethrow CancellationException instead of
converting cancellation into a null result. Ensure the snapshot assignments to
librariesWithCollectionsSnapshot, probedCollectionsIdentityKey, and
probedCollectionLibraryIds occur only after a non-cancelled probe completes.
In
`@shared/src/commonTest/kotlin/org/siloserver/silo/model/section/HomeSectionHydrationTest.kt`:
- Around line 8-20: Update
topLevelItemsHydrateSectionMetadataWithDefaultZeroCount to assert that
resolved?.totalCount equals 0, verifying that resolveHomeSectionItems uses the
response metadata count instead of preserving original.totalCount.
---
Outside diff comments:
In
`@shared/src/androidMain/kotlin/org/siloserver/silo/network/EncryptedTokenManagerImpl.kt`:
- Around line 300-325: Update snapshotCurrentScope so identity generation and
all scope fields are captured atomically under the same transition protection as
changing(). Ensure both the temporaryScope and active-scope branches read and
label their snapshot from the same captured generation/state transaction,
preventing an old scope from being paired with a newer identity generation.
---
Nitpick comments:
In
`@android-shared/src/androidMain/kotlin/org/siloserver/silo/common/startup/StartupWarmup.kt`:
- Around line 75-103: The hydration algorithm in hydrateStartupHomeSections
duplicates HomeViewModel.fetchSections. Promote StartupHomeResolution and
hydrateStartupHomeSections into commonMain, preserving the unresolved filtering,
bounded-concurrency fetches, resolveHomeSectionItems usage, and fullyResolved
behavior, then update both call sites to reuse the shared implementation and
remove the duplicate logic.
In `@shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeViewModel.kt`:
- Around line 137-159: Extract the duplicated section-hydration workflow from
the HomeViewModel loading path into a shared function, then have both this flow
and StartupWarmup.hydrateStartupHomeSections use it. Preserve the existing
filtering, bounded concurrency, resolveHomeSectionItems fallback, and
fully-resolved status while replacing the local Pair<ResolvedSection, Boolean>
implementation with the shared result type.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: d6f939d2-f26c-42f7-94a6-5d55dce87cbb
📒 Files selected for processing (64)
android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/repository/RoomUserItemStateRepository.ktandroid-shared/src/androidMain/kotlin/org/siloserver/silo/common/di/PlayerInfraModule.ktandroid-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/FinalPlaybackPositionWriter.ktandroid-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/PlaybackSessionLifecycle.ktandroid-shared/src/androidMain/kotlin/org/siloserver/silo/common/startup/StartupWarmup.ktandroid-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/data/repository/RoomUserItemStateRepositoryTest.ktandroid-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/FinalPlaybackPositionWriterTest.ktandroid-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/PlaybackSessionLifecycleLoggingTest.ktandroid-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/startup/StartupHomeHydrationTest.ktandroid-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/startup/StartupWarmupSourceTest.ktandroidApp/src/androidMain/kotlin/org/siloserver/silo/android/di/AndroidModule.ktandroidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/detail/ItemDetailScreen.ktandroidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/detail/ItemDetailViewModel.ktandroidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/detail/SimilarRail.ktandroidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerScreen.ktandroidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerViewModel.ktandroidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/SharedStartupWarmupSourceTest.ktandroidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/performance/MobileDetailOpenPerformanceSourceTest.ktandroidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/performance/MobilePlayerLifecyclePerformanceSourceTest.ktandroidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/detail/EpisodeRollupAccumulatorTest.ktandroidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/player/MobilePlayerPresentationStateTest.ktandroidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerScreenStartPositionTest.ktandroidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/di/AndroidTvModule.ktandroidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylineSectionFeed.ktandroidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/detail/TvItemDetailScreen.ktandroidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/detail/TvItemDetailViewModel.ktandroidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/home/HomeResumeRefreshPolicy.ktandroidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/home/TvHomeScreen.ktandroidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvPlayerScreen.ktandroidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvPlayerViewModel.ktandroidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.ktandroidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/SharedStartupWarmupSourceTest.ktandroidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/components/TvSkylineSectionFeedSourceTest.ktandroidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/performance/TvDetailOpenPerformanceSourceTest.ktandroidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/home/HomeResumeRefreshPolicyTest.ktandroidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/home/TvHomeScreenSourceTest.ktandroidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/player/TvPlayerPresentationStateTest.ktandroidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/player/TvPlayerScreenStartPositionTest.ktandroidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/player/TvPlayerViewModelPlaybackPositionTest.ktandroidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/shell/TvCollectionsPresenceCacheTest.ktdocs/superpowers/plans/2026-07-22-android-home-request-coalescing.mddocs/superpowers/plans/2026-07-22-android-mobile-performance-remediation.mddocs/superpowers/plans/2026-07-22-android-startup-home-fanout-remediation.mddocs/superpowers/plans/2026-07-22-android-tv-performance-remediation.mddocs/superpowers/specs/2026-07-22-android-home-request-coalescing-design.mddocs/superpowers/specs/2026-07-22-android-mobile-performance-remediation-design.mddocs/superpowers/specs/2026-07-22-android-startup-home-fanout-remediation-design.mddocs/superpowers/specs/2026-07-22-android-tv-performance-remediation-design.mdshared/src/androidMain/kotlin/org/siloserver/silo/network/EncryptedTokenManagerImpl.ktshared/src/commonMain/kotlin/org/siloserver/silo/di/RepositoryModule.ktshared/src/commonMain/kotlin/org/siloserver/silo/model/section/HomeSectionHydration.ktshared/src/commonMain/kotlin/org/siloserver/silo/network/AuthScopeSnapshot.ktshared/src/commonMain/kotlin/org/siloserver/silo/network/api/SectionApi.ktshared/src/commonMain/kotlin/org/siloserver/silo/repository/HomeSectionsRequestGate.ktshared/src/commonMain/kotlin/org/siloserver/silo/repository/SectionRepository.ktshared/src/commonMain/kotlin/org/siloserver/silo/repository/port/UserItemStatePort.ktshared/src/commonMain/kotlin/org/siloserver/silo/util/BoundedConcurrency.ktshared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeViewModel.ktshared/src/commonTest/kotlin/org/siloserver/silo/model/section/HomeSectionHydrationTest.ktshared/src/commonTest/kotlin/org/siloserver/silo/network/SiloAuthPluginPinTest.ktshared/src/commonTest/kotlin/org/siloserver/silo/repository/HomeSectionsRequestGateTest.ktshared/src/commonTest/kotlin/org/siloserver/silo/util/BoundedConcurrencyTest.ktshared/src/commonTest/kotlin/org/siloserver/silo/viewmodel/HomeViewModelPerformanceSourceTest.ktshared/src/commonTest/kotlin/org/siloserver/silo/viewmodel/HomeViewModelRefreshPolicySourceTest.kt
💤 Files with no reviewable changes (1)
- androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylineSectionFeed.kt
| val current = snapshotProvider() ?: return false | ||
| if (current.serverId != scope.serverId || | ||
| current.profileId != scope.profileId || | ||
| current.credentialGenerationId != scope.credentialGenerationId || | ||
| current.identityGeneration != scope.identityGeneration | ||
| ) return false | ||
|
|
||
| return recordPositionOwned( | ||
| serverId = scope.serverId, | ||
| profileId = scope.profileId, | ||
| contentId = contentId, | ||
| fileId = fileId, | ||
| positionSeconds = positionSeconds, | ||
| durationSeconds = durationSeconds, | ||
| ) |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
Make scope validation atomic with the final write.
Lines 106-111 validate identity before the Room transaction starts at Line 144. A profile/credential transition in that gap still allows this write to commit and return true after its captured identity is no longer current. Coordinate auth-scope transitions and this write through the same generation gate/lock so the write is either rejected or completes before the identity changes.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In
`@android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/repository/RoomUserItemStateRepository.kt`
around lines 106 - 120, Make the scope check and final write in the repository
method containing snapshotProvider and recordPositionOwned execute under the
same generation gate or lock used by profile/credential transitions. Move or
coordinate validation with the Room transaction so an identity change cannot
occur between validation and commit; return false for stale scope, otherwise
complete the write before allowing the transition.
| init { | ||
| scope.launch { | ||
| for (ignored in wakeUp) { | ||
| while (true) { | ||
| val batch = synchronized(lock) { | ||
| if (pending.isEmpty()) { | ||
| emptyList() | ||
| } else { | ||
| pending.values.toList().also { pending.clear() } | ||
| } | ||
| } | ||
| if (batch.isEmpty()) break | ||
| batch.forEach { snapshot -> runCatching { write(snapshot) } } | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Do not discard failed final-position writes.
Line 48 swallows failures after Lines 40-45 clear pending, so a transient Room failure silently loses the final resume position and no later trigger retries it. Preserve the latest failed snapshot and retry with bounded backoff while keeping the worker alive.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In
`@android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/FinalPlaybackPositionWriter.kt`
around lines 36 - 49, Update the worker loop in FinalPlaybackPositionWriter’s
init coroutine so failed write(snapshot) operations are retained instead of
being discarded after pending.clear(). Reinsert or otherwise preserve the latest
failed snapshots, retry them with bounded backoff, and keep the coroutine alive
while continuing to process wakeUp triggers and successful writes.
| @Test | ||
| fun scopedPositionRejectsProfileThatIsNoLongerCurrent() = runTest { | ||
| val captured = PlaybackWriteScope("server", "profile-a", null, 4L) | ||
| currentSnapshot = authScope("server", "profile-b", generation = 5L) | ||
|
|
||
| assertFalse(repo.recordPosition(captured, "movie", 7, 42.0, 100.0)) | ||
| assertNull(db.userItemStateDao().get("server", "profile-a", "movie", 7)) | ||
| assertNull(db.userItemStateDao().get("server", "profile-b", "movie", 7)) | ||
| } | ||
|
|
||
| @Test | ||
| fun scopedPositionWritesOnlyToMatchingCapturedIdentity() = runTest { | ||
| val captured = PlaybackWriteScope("server", "profile-a", null, 4L) | ||
| currentSnapshot = authScope("server", "profile-a", generation = 4L) | ||
|
|
||
| assertTrue(repo.recordPosition(captured, "movie", 7, 42.0, 100.0)) | ||
| assertEquals( | ||
| 42.0, | ||
| db.userItemStateDao().get("server", "profile-a", "movie", 7)?.positionSeconds, | ||
| ) | ||
| } |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Cover credential rotation and outbox suppression.
These cases never vary credentialGenerationId and only assert projection rows. Add a same-server/profile credential-generation mismatch case and assert no SET_POSITION outbox row is queued; otherwise a stale final-position write can still be synchronized after an identity change.
As per coding guidelines, “add focused tests for shared-logic changes only when behavior is critical or high-risk.”
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In
`@android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/data/repository/RoomUserItemStateRepositoryTest.kt`
around lines 245 - 265, Extend the repository tests around recordPosition to
cover a credential-generation mismatch for the same server and profile, varying
captured versus current credentialGenerationId while keeping identity otherwise
matching. Assert recordPosition rejects the stale write, both projection rows
remain absent as appropriate, and the outbox contains no SET_POSITION entry; use
the existing DAO/query helpers and test symbols.
Source: Coding guidelines
| @Test | ||
| fun aNewStartWaitsForAnAsynchronousStopToFinish() { | ||
| val text = source.joinToString("\n") | ||
|
|
||
| assertTrue(text.contains("private var pendingStopJob: Job?")) | ||
| assertTrue(text.contains("private suspend fun awaitPendingStop()")) | ||
| assertTrue( | ||
| text.substringAfter("suspend fun start(params: StartParams)") | ||
| .substringBefore("suspend fun adoptActiveSession(") | ||
| .contains("awaitPendingStop()"), | ||
| ) | ||
| assertTrue( | ||
| text.substringAfter("suspend fun adoptActiveSession(") | ||
| .substringBefore("private suspend fun startInternal(") | ||
| .contains("awaitPendingStop()"), | ||
| ) | ||
| } |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟠 Major | 🏗️ Heavy lift
Test the lifecycle race behavior directly.
This only proves substrings exist. Add a coroutine test that holds stopSession/final flush, calls stopAsync(), verifies start() or adoptActiveSession() remains suspended, then releases teardown and verifies the new session survives. That validates the ordering this change is intended to guarantee.
As per coding guidelines, “add focused tests for shared-logic changes only when behavior is critical or high-risk.”
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In
`@android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/PlaybackSessionLifecycleLoggingTest.kt`
around lines 22 - 38, The current test only inspects source text instead of
validating lifecycle ordering. In PlaybackSessionLifecycleLoggingTest, add a
coroutine-based race test that blocks stopSession or its final flush, invokes
stopAsync(), verifies start() or adoptActiveSession() stays suspended, then
releases teardown and confirms the new session remains active. Replace or
supplement the substring assertions with this focused behavioral coverage.
Source: Coding guidelines
| /** Called when the user exits the player. */ | ||
| fun onExit() { | ||
| if (!exitPrepared.compareAndSet(false, true)) return | ||
| resetPlaybackRecoveryState() | ||
| viewModelScope.launch { | ||
| // Track B: durably record the final position for both paths, then ask | ||
| // the outbox to drain promptly (covers the online offline-download case | ||
| // where there's no live session and no connectivity change to trigger it). | ||
| val cid = _uiState.value.contentId.takeIf { it.isNotBlank() } | ||
| val fid = currentFileId() | ||
| if (cid != null && fid != null) { | ||
| userItemStatePort.recordPosition( | ||
| cid, | ||
| fid, | ||
| _uiState.value.position, | ||
| _uiState.value.duration.takeIf { it > 0.0 }, | ||
| ) | ||
| outboxSyncScheduler.requestSync() | ||
| } | ||
| // Lifecycle.stop() handles: final progress report, snapshot via PersonalData, | ||
| // session stop, and reporter cancellation. The single call replaces the | ||
| // duplicated reportProgress/stopSession + syncProgressSnapshot flow. | ||
| sessionLifecycle.stop() | ||
| controlsHideJob?.cancel() | ||
| introObserverJob?.cancel() | ||
| searchJob?.cancel() | ||
| aiJobHandle?.cancel() | ||
| introAutoSkipController.reset() | ||
| _uiState.update { | ||
| it.copy( | ||
| isLoading = false, | ||
| sessionId = null, | ||
| playMethod = null, | ||
| playbackPlan = null, | ||
| delivery = null, | ||
| streamUrl = null, | ||
| container = null, | ||
| subtitleTracks = emptyList(), | ||
| isPaused = true, | ||
| isPlaying = false, | ||
| val state = _uiState.value | ||
| val cid = state.contentId.takeIf { it.isNotBlank() } | ||
| val fid = currentFileId() | ||
| val scope = finalPositionScope | ||
| if (scope != null && cid != null && fid != null) { | ||
| finalPlaybackPositionWriter.submit( | ||
| FinalPlaybackPosition( | ||
| scope = scope, | ||
| contentId = cid, | ||
| fileId = fid, | ||
| positionSeconds = state.position, | ||
| durationSeconds = state.duration.takeIf { it > 0.0 }, | ||
| ) | ||
| } | ||
| ) | ||
| } | ||
| sessionLifecycle.stopAsync() | ||
| controlsHideJob?.cancel() | ||
| introObserverJob?.cancel() | ||
| searchJob?.cancel() | ||
| aiJobHandle?.cancel() | ||
| introAutoSkipController.reset() | ||
| _uiState.update { | ||
| it.copy( | ||
| isLoading = false, | ||
| sessionId = null, | ||
| playMethod = null, | ||
| playbackPlan = null, | ||
| delivery = null, | ||
| streamUrl = null, | ||
| container = null, | ||
| subtitleTracks = emptyList(), | ||
| isPaused = true, | ||
| isPlaying = false, | ||
| ) | ||
| } | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
onExit() doesn't stop the Up Next auto-advance, so a countdown can start a session that outlives the exit guard.
onExit()'s resetPlaybackRecoveryState() cancels recovery/seek jobs but not upNextCountdownJob or resolveNextEpisodeJob, and it never clears showUpNext. startUpNextCountdown()'s loop only bails on !state.showUpNext, which stays true after exit. If a user backs out while the (non-modal) Up Next countdown is running, the countdown can still fire advanceToNextEpisode() → loadContent() after onExit() already ran. Since exitPrepared is a one-shot latch with no reset, that newly-started session's final-position submit and sessionLifecycle.stopAsync() are permanently skipped on any later onExit()/onCleared() call — an orphaned session. Notably, loadContent() itself already treats upNextCountdownJob/resolveNextEpisodeJob as needing explicit cancellation on transitions; onExit() should do the same.
🔧 Proposed fix
fun onExit() {
if (!exitPrepared.compareAndSet(false, true)) return
+ upNextCountdownJob?.cancel()
+ upNextCountdownJob = null
+ resolveNextEpisodeJob?.cancel()
resetPlaybackRecoveryState()
val state = _uiState.value
val cid = state.contentId.takeIf { it.isNotBlank() }
val fid = currentFileId()
val scope = finalPositionScope
if (scope != null && cid != null && fid != null) {
finalPlaybackPositionWriter.submit(
FinalPlaybackPosition(
scope = scope,
contentId = cid,
fileId = fid,
positionSeconds = state.position,
durationSeconds = state.duration.takeIf { it > 0.0 },
)
)
}
sessionLifecycle.stopAsync()
controlsHideJob?.cancel()
introObserverJob?.cancel()
searchJob?.cancel()
aiJobHandle?.cancel()
introAutoSkipController.reset()
_uiState.update {
it.copy(
isLoading = false,
sessionId = null,
playMethod = null,
playbackPlan = null,
delivery = null,
streamUrl = null,
container = null,
subtitleTracks = emptyList(),
isPaused = true,
isPlaying = false,
+ showUpNext = false,
+ upNextCountdownSeconds = null,
)
}
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| /** Called when the user exits the player. */ | |
| fun onExit() { | |
| if (!exitPrepared.compareAndSet(false, true)) return | |
| resetPlaybackRecoveryState() | |
| viewModelScope.launch { | |
| // Track B: durably record the final position for both paths, then ask | |
| // the outbox to drain promptly (covers the online offline-download case | |
| // where there's no live session and no connectivity change to trigger it). | |
| val cid = _uiState.value.contentId.takeIf { it.isNotBlank() } | |
| val fid = currentFileId() | |
| if (cid != null && fid != null) { | |
| userItemStatePort.recordPosition( | |
| cid, | |
| fid, | |
| _uiState.value.position, | |
| _uiState.value.duration.takeIf { it > 0.0 }, | |
| ) | |
| outboxSyncScheduler.requestSync() | |
| } | |
| // Lifecycle.stop() handles: final progress report, snapshot via PersonalData, | |
| // session stop, and reporter cancellation. The single call replaces the | |
| // duplicated reportProgress/stopSession + syncProgressSnapshot flow. | |
| sessionLifecycle.stop() | |
| controlsHideJob?.cancel() | |
| introObserverJob?.cancel() | |
| searchJob?.cancel() | |
| aiJobHandle?.cancel() | |
| introAutoSkipController.reset() | |
| _uiState.update { | |
| it.copy( | |
| isLoading = false, | |
| sessionId = null, | |
| playMethod = null, | |
| playbackPlan = null, | |
| delivery = null, | |
| streamUrl = null, | |
| container = null, | |
| subtitleTracks = emptyList(), | |
| isPaused = true, | |
| isPlaying = false, | |
| val state = _uiState.value | |
| val cid = state.contentId.takeIf { it.isNotBlank() } | |
| val fid = currentFileId() | |
| val scope = finalPositionScope | |
| if (scope != null && cid != null && fid != null) { | |
| finalPlaybackPositionWriter.submit( | |
| FinalPlaybackPosition( | |
| scope = scope, | |
| contentId = cid, | |
| fileId = fid, | |
| positionSeconds = state.position, | |
| durationSeconds = state.duration.takeIf { it > 0.0 }, | |
| ) | |
| } | |
| ) | |
| } | |
| sessionLifecycle.stopAsync() | |
| controlsHideJob?.cancel() | |
| introObserverJob?.cancel() | |
| searchJob?.cancel() | |
| aiJobHandle?.cancel() | |
| introAutoSkipController.reset() | |
| _uiState.update { | |
| it.copy( | |
| isLoading = false, | |
| sessionId = null, | |
| playMethod = null, | |
| playbackPlan = null, | |
| delivery = null, | |
| streamUrl = null, | |
| container = null, | |
| subtitleTracks = emptyList(), | |
| isPaused = true, | |
| isPlaying = false, | |
| ) | |
| } | |
| } | |
| /** Called when the user exits the player. */ | |
| fun onExit() { | |
| if (!exitPrepared.compareAndSet(false, true)) return | |
| upNextCountdownJob?.cancel() | |
| upNextCountdownJob = null | |
| resolveNextEpisodeJob?.cancel() | |
| resetPlaybackRecoveryState() | |
| val state = _uiState.value | |
| val cid = state.contentId.takeIf { it.isNotBlank() } | |
| val fid = currentFileId() | |
| val scope = finalPositionScope | |
| if (scope != null && cid != null && fid != null) { | |
| finalPlaybackPositionWriter.submit( | |
| FinalPlaybackPosition( | |
| scope = scope, | |
| contentId = cid, | |
| fileId = fid, | |
| positionSeconds = state.position, | |
| durationSeconds = state.duration.takeIf { it > 0.0 }, | |
| ) | |
| ) | |
| } | |
| sessionLifecycle.stopAsync() | |
| controlsHideJob?.cancel() | |
| introObserverJob?.cancel() | |
| searchJob?.cancel() | |
| aiJobHandle?.cancel() | |
| introAutoSkipController.reset() | |
| _uiState.update { | |
| it.copy( | |
| isLoading = false, | |
| sessionId = null, | |
| playMethod = null, | |
| playbackPlan = null, | |
| delivery = null, | |
| streamUrl = null, | |
| container = null, | |
| subtitleTracks = emptyList(), | |
| isPaused = true, | |
| isPlaying = false, | |
| showUpNext = false, | |
| upNextCountdownSeconds = null, | |
| ) | |
| } | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In
`@androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerViewModel.kt`
around lines 3141 - 3180, Update onExit() to explicitly cancel
upNextCountdownJob and resolveNextEpisodeJob, and clear showUpNext before
exiting. Ensure startUpNextCountdown() cannot continue or invoke
advanceToNextEpisode() after exit, while preserving the existing exit guard and
cleanup behavior.
| libraries.forEach { lib -> | ||
| val result = runCatching { sectionRepository.getLibraryCollections(lib.id) }.getOrNull() | ||
| if (result is ApiResult.Success && result.data.isNotEmpty()) ids += lib.id | ||
| } | ||
| librariesWithCollections = ids | ||
| librariesWithCollectionsSnapshot = ids.toIntArray() | ||
| probedCollectionsIdentityKey = collectionsIdentityKey | ||
| probedCollectionLibraryIds = currentLibraryIds |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Do not swallow cancellation from collection probes.
runCatching captures CancellationException. A cancelled prior identity probe can continue and overwrite the newer cache, leaving librariesWithCollections unknown or stale until the library list changes. Rethrow cancellation before committing the snapshot.
Proposed fix
- val result = runCatching { sectionRepository.getLibraryCollections(lib.id) }.getOrNull()
+ val result = try {
+ sectionRepository.getLibraryCollections(lib.id)
+ } catch (error: CancellationException) {
+ throw error
+ } catch (_: Throwable) {
+ null
+ }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| libraries.forEach { lib -> | |
| val result = runCatching { sectionRepository.getLibraryCollections(lib.id) }.getOrNull() | |
| if (result is ApiResult.Success && result.data.isNotEmpty()) ids += lib.id | |
| } | |
| librariesWithCollections = ids | |
| librariesWithCollectionsSnapshot = ids.toIntArray() | |
| probedCollectionsIdentityKey = collectionsIdentityKey | |
| probedCollectionLibraryIds = currentLibraryIds | |
| libraries.forEach { lib -> | |
| val result = try { | |
| sectionRepository.getLibraryCollections(lib.id) | |
| } catch (error: CancellationException) { | |
| throw error | |
| } catch (_: Throwable) { | |
| null | |
| } | |
| if (result is ApiResult.Success && result.data.isNotEmpty()) ids += lib.id | |
| } | |
| librariesWithCollectionsSnapshot = ids.toIntArray() | |
| probedCollectionsIdentityKey = collectionsIdentityKey | |
| probedCollectionLibraryIds = currentLibraryIds |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In
`@androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt`
around lines 479 - 485, Update the collection probe loop around runCatching in
the library identity-probe flow to rethrow CancellationException instead of
converting cancellation into a null result. Ensure the snapshot assignments to
librariesWithCollectionsSnapshot, probedCollectionsIdentityKey, and
probedCollectionLibraryIds occur only after a non-cancelled probe completes.
| fun topLevelItemsHydrateSectionMetadataWithDefaultZeroCount() { | ||
| val original = section("original", totalCount = 1) | ||
| val metadata = section("server", totalCount = 0) | ||
| val item = SectionItem(contentId = "movie-1", type = "movie", title = "Movie") | ||
|
|
||
| val resolved = resolveHomeSectionItems( | ||
| originalSection = original, | ||
| response = HomeSectionItemsResponse(section = metadata, items = listOf(item)), | ||
| ) | ||
|
|
||
| assertEquals("server", resolved?.id) | ||
| assertEquals(listOf("movie-1"), resolved?.items?.map { it.contentId }) | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Assert the zero-count metadata contract.
This test passes if resolveHomeSectionItems keeps original.totalCount == 1, despite its stated purpose. Assert the resolved count is 0.
Proposed fix
assertEquals("server", resolved?.id)
+ assertEquals(0, resolved?.totalCount)
assertEquals(listOf("movie-1"), resolved?.items?.map { it.contentId })📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| fun topLevelItemsHydrateSectionMetadataWithDefaultZeroCount() { | |
| val original = section("original", totalCount = 1) | |
| val metadata = section("server", totalCount = 0) | |
| val item = SectionItem(contentId = "movie-1", type = "movie", title = "Movie") | |
| val resolved = resolveHomeSectionItems( | |
| originalSection = original, | |
| response = HomeSectionItemsResponse(section = metadata, items = listOf(item)), | |
| ) | |
| assertEquals("server", resolved?.id) | |
| assertEquals(listOf("movie-1"), resolved?.items?.map { it.contentId }) | |
| } | |
| fun topLevelItemsHydrateSectionMetadataWithDefaultZeroCount() { | |
| val original = section("original", totalCount = 1) | |
| val metadata = section("server", totalCount = 0) | |
| val item = SectionItem(contentId = "movie-1", type = "movie", title = "Movie") | |
| val resolved = resolveHomeSectionItems( | |
| originalSection = original, | |
| response = HomeSectionItemsResponse(section = metadata, items = listOf(item)), | |
| ) | |
| assertEquals("server", resolved?.id) | |
| assertEquals(0, resolved?.totalCount) | |
| assertEquals(listOf("movie-1"), resolved?.items?.map { it.contentId }) | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In
`@shared/src/commonTest/kotlin/org/siloserver/silo/model/section/HomeSectionHydrationTest.kt`
around lines 8 - 20, Update
topLevelItemsHydrateSectionMetadataWithDefaultZeroCount to assert that
resolved?.totalCount equals 0, verifying that resolveHomeSectionItems uses the
response metadata count instead of preserving original.totalCount.
Summary
Verification
CI
Summary by CodeRabbit