Skip to content

Polish cast pairing and TV navigation UI across Android clients - #63

Merged
Quick104 merged 85 commits into
mainfrom
codex/polish-shield-ui-ux
Jul 14, 2026
Merged

Quick104 merged 85 commits into
mainfrom
codex/polish-shield-ui-ux

Conversation

@Quick104

@Quick104 Quick104 commented Jul 11, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Tighten the cast pairing flow and transport handling across shared Android code.
  • Refine Android phone and TV navigation, shell, and detail screens for cleaner focus, spacing, and playback presentation.
  • Update shared token, catalog, and device login models plus supporting tests for the new behavior.
  • Add UI validation assets and ignore generated/local artifacts as needed.

Testing

  • Android unit tests updated for cast, pairing, token, catalog, and TV shell/detail behavior.
  • UI validation performed on the updated phone and TV surfaces where applicable.
  • Not all platform builds were run in this pass.

Summary by CodeRabbit

  • New Features
    • Added full remote playback and control across Android phone and TV, including target selection, handoff flow, reconnect/auto-resume, and expanded UI controls (volume/mute, subtitles, HDR, and more).
    • Added server selection during companion pairing.
    • Improved startup warmup with configurable artwork planning and enhanced splash timing; added subtitle custom appearance handling.
  • Bug Fixes
    • Watched toggles now clear resume progress while preserving other reading preferences.
    • Improved local air-time formatting and pairing discovery/resolution reliability.
  • Style
    • Refreshed Android TV typography and navigation chrome, plus updated focus and card/overlay visuals.

@Quick104
Quick104 marked this pull request as ready for review July 13, 2026 23:10

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note

Due to the large number of review comments, Critical severity comments were prioritized as inline comments.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (4)
androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/MainScreen.kt (1)

357-365: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Cast redirect can break the offline-first Downloads flow.

playVideo now runs launchOnConnectedTarget before falling back to local playback. If the user has an active cast session, tapping a downloaded row will redirect to the remote target instead of local playback — even though the comment directly above (lines 351-356) states this path exists specifically so playback "works offline" without depending on the server. A downloaded item played via cast would depend on network/server reachability again, defeating the purpose of downloads.

💡 Suggested fix: bypass cast redirect for downloaded content
                             onItemClick = { item ->
                                 if (item.mediaType == org.siloserver.silo.model.download.DownloadMediaType.Audiobook) {
                                     navController.navigate(
                                         Route.AudiobookPlayer(item.contentId, item.fileId).route,
                                     )
                                 } else {
-                                    playVideo(item.contentId, fileId = item.fileId)
+                                    navController.navigate(
+                                        Route.Player(
+                                            contentId = item.contentId,
+                                            fileId = item.fileId,
+                                        ).route,
+                                    )
                                 }
                             },
🤖 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/MainScreen.kt`
around lines 357 - 365, Update the downloaded-item handling in MainScreen’s
onItemClick callback to bypass playVideo’s cast-aware redirect and start local
playback directly for non-audiobook downloads. Preserve the existing
AudiobookPlayer navigation, and ensure downloaded video playback remains
offline-first even when an active cast session exists.
androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/profiles/TvProfileSelectionScreen.kt (1)

146-173: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Restore a way to enter manage mode — the removed top-row action was the only visible trigger, and state.isManageMode is still used to switch profile taps into edit/delete behavior. With no remaining caller for toggleManageMode(), profile management becomes unreachable on TV unless another entry point replaces it.

🤖 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/screens/profiles/TvProfileSelectionScreen.kt`
around lines 146 - 173, Restore a visible TV action in the top utility Row that
invokes toggleManageMode(), allowing users to enter manage mode and preserving
the existing state.isManageMode behavior for profile interactions. Keep the
Change Server and Sign Out actions intact, and match the surrounding
TvHeroActionPill styling and layout.
androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/navigation/BottomNavBar.kt (1)

76-111: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Stale comment: says "72dp content area" but height is now 60.dp.

The unchanged rationale comment above still references a 72dp content area, but this diff sets NavigationBar's height to 60.dp. Update the comment to match the new value so it doesn't mislead future edits.

🤖 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/navigation/BottomNavBar.kt`
around lines 76 - 111, Update the rationale comment above the outer Box and
NavigationBar to refer to the 60dp content area instead of 72dp, leaving the
surrounding inset and glass-background guidance unchanged.
androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/cast/TvSiloCastReceiver.kt (1)

139-155: 🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift

End the temporary remote identity during receiver shutdown.

stop() cancels the identity-end job but never calls identityManager.end() or clears pendingPlayerIdentityGeneration. The next start() can therefore advertise and authorize against a stale remote server/profile. Perform non-cancellable identity teardown before cancelling the owner scope.

🤖 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/cast/TvSiloCastReceiver.kt`
around lines 139 - 155, Update TvSiloCastReceiver.stop() to perform
non-cancellable identity teardown before cancelling scope: end the temporary
remote identity through identityManager.end() and clear
pendingPlayerIdentityGeneration. Keep this cleanup ahead of scope?.cancel() so
the next start() cannot reuse stale server or profile identity.
🟠 Major comments (22)
androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/downloads/DownloadsScreen.kt-162-162 (1)

162-162: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Inset the floating bulk-delete action as well as the list.

The list now avoids bottom chrome, but the BottomCenter button at Line 255 still has only 16.dp padding and can be obscured or intercept-conflicted. Add LocalBottomChromeInset.current to that button’s bottom padding.

🤖 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/downloads/DownloadsScreen.kt`
at line 162, Update the BottomCenter bulk-delete action’s padding in the
downloads screen to include LocalBottomChromeInset.current in its bottom
padding, matching the list’s contentPadding while preserving the existing 16.dp
spacing.
android-shared/src/androidMain/kotlin/org/siloserver/silo/common/cast/SiloCastNsdBrowser.kt-90-92 (1)

90-92: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Reject stale resolution callbacks before publishing targets.

A resolution completing after stop() can repopulate _targets, because liveness is checked only by finishResolution after the update. Queued services lost before resolution can also be published permanently. Track the discovery generation/service presence and validate it under the same synchronization used by stop() before updating _targets; remove lost services from the pending queue.

Also applies to: 100-110, 125-132, 142-148

🤖 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/cast/SiloCastNsdBrowser.kt`
around lines 90 - 92, Update the resolution lifecycle around finishResolution,
stop(), and pending service processing to track the current discovery generation
and whether each service is still present. Under the same synchronization used
by stop(), reject callbacks from older generations or services no longer
discovered before publishing _targets, and remove lost services from
pendingResolutions so they cannot be published later.
androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvRecommendationsScreen.kt-74-77 (1)

74-77: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Provide a path back to recommendations.

Once Watchlist is selected automatically or manually, the saved-list branch wins permanently—even if a refresh later returns recommendations. Add a Recommendations option or let the active saved-list pill toggle back to null; also clear only the automatic fallback when recommendations become available.

Also applies to: 114-121, 237-258

🤖 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/screens/recommendations/TvRecommendationsScreen.kt`
around lines 74 - 77, The recommendations screen’s saved-list selection can
become permanently active after the automatic Watchlist fallback, preventing
refreshed recommendations from displaying. Update the LaunchedEffect and
saved-list selection UI around savedListSelection and the saved-list branch so
users can return to recommendations, either by adding a Recommendations option
or toggling the active saved-list pill to null; clear only the automatic
Watchlist fallback when visibleSections becomes non-empty, while preserving
explicit user selections.
androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/cast/RemotePlaybackIdentityManager.kt-151-165 (1)

151-165: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Local cleanup is skipped if the server-side "end remote playback" call fails.

endLocked() calls deviceLoginApi.endRemotePlayback(...) before clearing tokenManager's temporary scope and activeIdentity. A transient network failure on that call throws before local state is cleaned up — and since endLocked() is also called from prepare() (Line 67) to clear a stale identity before starting a new handoff, a brand-new valid handoff request fails entirely just because releasing the previous session hit a transient error, leaving local state stale.

🔧 Proposed fix
     private suspend fun endLocked() {
         val active = activeIdentity
         if (active != null && tokenManager.hasTemporaryScope()) {
-            deviceLoginApi.endRemotePlayback(
-                AuthScopeSnapshot(
-                    serverId = active.serverId,
-                    serverUrl = active.serverUrl,
-                    profileId = active.profileId,
-                    profileToken = null,
-                ),
-            )
+            runCatching {
+                deviceLoginApi.endRemotePlayback(
+                    AuthScopeSnapshot(
+                        serverId = active.serverId,
+                        serverUrl = active.serverUrl,
+                        profileId = active.profileId,
+                        profileToken = null,
+                    ),
+                )
+            }
         }
         tokenManager.endTemporaryScope()
         activeIdentity = 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
`@androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/cast/RemotePlaybackIdentityManager.kt`
around lines 151 - 165, Update endLocked in RemotePlaybackIdentityManager so
tokenManager.endTemporaryScope() and activeIdentity cleanup always execute even
when deviceLoginApi.endRemotePlayback fails. Preserve the server-side end
attempt, but isolate or defer its exception so prepare() can clear stale local
state and proceed with a new handoff.
androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/detail/TvItemDetailViewModel.kt-622-638 (1)

622-638: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Preserve known favorite states when individual lookups fail.

Every non-success response becomes false, so a transient failure during a quiet episode reload can overwrite an already-known favorite. Collect successful results only and merge them into the existing map for the current episode IDs.

🤖 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/screens/detail/TvItemDetailViewModel.kt`
around lines 622 - 638, Update refreshEpisodeFavoriteStates so failed or
non-successful isFavorite lookups do not become false. Collect only
ApiResult.Success values, then merge those successful states with the existing
episodeFavoriteStates for the current episode IDs before updating the UI state,
preserving previously known values when lookups fail.
androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/detail/TvItemDetailViewModel.kt-641-691 (1)

641-691: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Serialize per-episode watched and favorite mutations.

These actions launch independently with no operation generation or in-flight guard. Out-of-order completions can overwrite the latest choice, while watched rollback restores the entire stale previousEpisodes snapshot and can discard newer updates. Track the latest operation per episode and only commit or roll back that operation.

🤖 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/screens/detail/TvItemDetailViewModel.kt`
around lines 641 - 691, Serialize watched and favorite mutations per episode in
onSetEpisodeWatched and onSetEpisodeFavorite by tracking the latest operation or
in-flight request for each episodeContentId. Ensure older completions cannot
commit or roll back after a newer mutation, and replace the watched rollback of
the entire previousEpisodes snapshot with a targeted update that restores only
the affected episode when its operation is still current.
androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylineSectionFeed.kt-440-445 (1)

440-445: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Keep the return target pending until the intended card has focus

In the two restore loops here, detailReturnPending is cleared even when requestFocus() only reports success transiently. Leave it set until focusedRowIndex/focusedItemIndex match the restore target, or retry on the next pass. (Lines 426-445 and 529-535)

🤖 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/components/TvSkylineSectionFeed.kt`
around lines 440 - 445, Update both restore loops around
detailReturnItemFocusRequester.requestFocus() so detailReturnPending is cleared
only after focusedRowIndex and focusedItemIndex match the intended rowIndex and
itemIndex. Preserve the pending state when all retries fail to establish the
target focus, allowing the next restore pass to retry.

Source: Coding guidelines

androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/pairing/CompanionPairingViewModel.kt-46-82 (1)

46-82: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Race: cancelled job's finally can null out a newer pairingJob.

dismissPairing() synchronously does pairingJob?.cancel(); pairingJob = null, but cancellation is cooperative — the cancelled coroutine keeps running until its next suspension point and only then runs its own finally { pairingJob = null } (line 79). If pair() is invoked again immediately after dismissPairing(), the new call's job is stored in pairingJob; when the old cancelled coroutine's finally later executes, it unconditionally clears pairingJob, wiping the reference to the new job. This defeats the pairingJob?.isActive == true re-entrancy guard for the new pairing attempt, allowing a subsequent pair() call to run concurrently with it.

Guard the clear with an identity check against the coroutine's own job.

🔧 Proposed fix
     fun pair(target: CompanionPairingTarget) {
         if (pairingJob?.isActive == true) return
-        pairingJob = viewModelScope.launch {
+        var job: Job? = null
+        job = viewModelScope.launch {
             try {
                 val result = coordinator.pair(
                     target = target,
                     chooseServers = { choices -> ... },
                     confirmFirstMatch = { approval -> ... },
                 )
                 if (result is CompanionPairingResult.Completed) {
                     browser.stop()
                 }
             } finally {
-                pairingJob = null
+                if (pairingJob === job) pairingJob = null
             }
         }
+        pairingJob = job
     }

Also applies to: 100-110

🤖 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/pairing/CompanionPairingViewModel.kt`
around lines 46 - 82, Update the finally block in pair so it clears pairingJob
only when the currently stored job is the same coroutine job that is finishing.
Capture or otherwise reference the launched coroutine’s Job for this identity
check, preventing a cancelled older pairing from clearing a newer pairing job.
android-shared/src/androidMain/kotlin/org/siloserver/silo/common/pairing/PairingAuthPort.kt-31-49 (1)

31-49: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Make the approved-session commit atomic.

persistApprovedSession updates the registry and token store in separate steps with no rollback. If the coroutine is cancelled after the server switch but before saveTokens, the new server stays selected with cleared profile/token state and no credentials saved. Wrap these writes in one coordinated commit or add rollback on failure so pairing can’t end half-finished.

🤖 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/pairing/PairingAuthPort.kt`
around lines 31 - 49, Make persistApprovedSession’s registry and token updates
atomic by using an existing coordinated transaction/commit mechanism if
available, or by capturing prior state and restoring it whenever any step fails
or the coroutine is cancelled. Ensure server selection, profile clearing, and
token persistence either all complete or leave the previous server and
credentials unchanged.
shared/src/commonMain/kotlin/org/siloserver/silo/network/api/DeviceLoginApi.kt-50-60 (1)

50-60: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Do not silently discard candidate-server and authentication scopes.

These defaults route candidate/scoped operations through the active server, perform normal login for remote handoff, or return a false-success logout. Any implementation inheriting them can send credentials to the wrong scope or leak a temporary session. Make these methods abstract, or return an explicit unsupported error.

Proposed contract fix
 suspend fun startDeviceLoginAt(
     serverUrl: String,
     deviceName: String?,
     devicePlatform: String?,
-): ApiResult<DeviceLoginStartResponse> = startDeviceLogin(deviceName, devicePlatform)
+): ApiResult<DeviceLoginStartResponse>

 suspend fun pollDeviceLoginAt(
     serverUrl: String,
     deviceCode: String,
-): ApiResult<DeviceLoginPollResponse> = pollDeviceLogin(deviceCode)
+): ApiResult<DeviceLoginPollResponse>

 suspend fun startRemotePlaybackAt(
     serverUrl: String,
     deviceName: String?,
     devicePlatform: String?,
-): ApiResult<DeviceLoginStartResponse> = startDeviceLoginAt(serverUrl, deviceName, devicePlatform)
+): ApiResult<DeviceLoginStartResponse>

-suspend fun endRemotePlayback(scope: AuthScopeSnapshot): ApiResult<Unit> =
-    ApiResult.Success(Unit)
+suspend fun endRemotePlayback(scope: AuthScopeSnapshot): ApiResult<Unit>

Apply the same abstract-contract treatment to the scope-based lookup, approve, and deny methods.

Also applies to: 70-74, 92-112

🤖 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/network/api/DeviceLoginApi.kt`
around lines 50 - 60, Update the candidate-server methods in DeviceLoginApi,
including startDeviceLoginAt, pollDeviceLoginAt, and the scope-based lookup,
approve, and deny methods, so they no longer delegate to active-scope
operations. Make these methods abstract or return an explicit unsupported error,
preserving serverUrl and authentication scope instead of silently discarding
them.
androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/home/HomeScreen.kt-121-137 (1)

121-137: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Stale presentedPairingTarget never clears when the target disappears.

When presented != null, the effect only updates presentedPairingTarget on a match by deviceId; if the device is no longer in companionTargets (advertisement expired, phone closed, etc.), nothing clears it. The pairing overlay keeps showing a dead target until the user manually dismisses it.

🐛 Proposed fix
             } else {
                 // Android NSD can resolve the same TV again with a new listener port after
                 // its setup screen restarts. Keep the visible card, but always pair with the
                 // freshest endpoint instead of the target object originally latched by UI.
-                companionTargets.firstOrNull { it.deviceId == presented.deviceId }?.let {
-                    presentedPairingTarget = it
-                }
+                presentedPairingTarget = companionTargets.firstOrNull { it.deviceId == presented.deviceId }
             }
🤖 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/home/HomeScreen.kt`
around lines 121 - 137, Update the presentedPairingTarget handling in the
LaunchedEffect so that when a non-null presented target has no matching deviceId
in companionTargets, it is cleared; continue replacing it with the freshest
matching target when available and preserve the existing selection behavior for
a null presented target.
androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/search/TvSearchViewModel.kt-39-52 (1)

39-52: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Re-run active searches when audiobook visibility becomes known.

showAudiobooks starts false, but changing it to true only reruns when mediaType also changes. An All search completed during initialization therefore remains missing audiobooks until another query/filter edit. Additionally, a library-fetch failure returns before reading the persisted preference.

Read the preference independently and treat a visibility change as a new search generation when a query is active.

Also applies to: 73-98

🤖 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/screens/search/TvSearchViewModel.kt`
around lines 39 - 52, The audiobook visibility initialization must read the
persisted preference even when library retrieval fails, rather than returning
before that read. In the ViewModel initialization/update flow around the state
containing showAudiobooks and the active search generation, detect changes to
audiobook visibility independently of mediaType and rerun the search whenever a
non-empty query is active, including an existing All search.
android-shared/src/androidMain/kotlin/org/siloserver/silo/common/settings/AndroidPlayerSettingsStore.kt-361-368 (1)

361-368: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Backfill the saved-custom key before clearing a legacy override.

Upgraded users can have SubtitleUsesDeviceOverride=true with their custom JSON only in the old SubtitleAppearance key. Disabling immediately refreshes and overwrites that value with the server fallback, permanently losing the custom appearance.

When disabling, copy the current appearance into the new key if it is absent, then clear the override. Add a test that seeds this legacy preference layout.

Proposed fix
             } else {
                 store.edit {
+                    val savedCustomKey =
+                        stringPreferencesKey(scope.keyPrefix + SAVED_CUSTOM_SUBTITLE_APPEARANCE)
+                    if (it[savedCustomKey] == null) {
+                        it[savedCustomKey] =
+                            snapshot.stringFor(
+                                scope,
+                                PlaybackSettingsKeys.SubtitleAppearance,
+                                SubtitleAppearance.DEFAULT.toJsonString(),
+                            )
+                    }
                     it[booleanPreferencesKey(scope.keyPrefix + PlaybackSettingsKeys.SubtitleUsesDeviceOverride)] = false
                 }

Also applies to: 424-427, 528-528

🤖 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/settings/AndroidPlayerSettingsStore.kt`
around lines 361 - 368, Update the subtitle override-disabling flows around the
shown appearance migration logic and the corresponding occurrences to preserve
legacy custom JSON: when the new SAVED_CUSTOM_SUBTITLE_APPEARANCE key is absent,
copy the current SubtitleAppearance value into it before clearing
SubtitleUsesDeviceOverride and allowing the server fallback to overwrite the old
key. Add a test covering preferences seeded with the legacy layout and verify
the custom appearance remains available after disabling.
androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/cast/SiloCastPhoneSourceTest.kt-38-54 (1)

38-54: 📐 Maintainability & Code Quality | 🟠 Major | 🏗️ Heavy lift

Replace lifecycle token checks with behavioral tests.

These assertions pass even if heartbeat resets, backoff, auto-resume gating, or handoff racing are implemented incorrectly or remain in dead code. Exercise the controller with fake transport/time dependencies and coroutine tests; retain source checks only as smoke coverage.

🤖 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/androidUnitTest/kotlin/org/siloserver/silo/android/cast/SiloCastPhoneSourceTest.kt`
around lines 38 - 54, Replace the source-string assertions in
SiloCastPhoneSourceTest with coroutine-based behavioral tests that exercise the
controller using fake transport and controllable time dependencies. Verify
heartbeat miss-counter resets only on pong, reconnect backoff and attempt limits
after unexpected transport drops, playing-gated auto-resume using the persisted
target, and racing handoff challenge/ready responses during reused-identity
switching. Retain only minimal source checks as smoke coverage.
androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/cast/SiloCastRemoteScreen.kt-765-773 (1)

765-773: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Use the v2 "standard" identifier for the Bottom position.

The v2 playback fixture reports "standard", so the current menu never marks Bottom selected and sends a different value back to the receiver.

Proposed fix
-        listOf("bottom" to "Bottom", "lower-third" to "Lower Third", "top" to "Top").forEach { (id, label) ->
+        listOf("standard" to "Bottom", "lower-third" to "Lower Third", "top" to "Top").forEach { (id, label) ->
🤖 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/cast/SiloCastRemoteScreen.kt`
around lines 765 - 773, Update the subtitle-position options in the playback
menu to use the v2 identifier "standard" for the Bottom entry instead of
"bottom", while keeping its displayed label and selection/click behavior
unchanged. Apply the change within the supportsSubtitlePosition block of
SiloCastRemoteScreen.
shared/src/commonMain/kotlin/org/siloserver/silo/network/TokenManager.kt-5-13 (1)

5-13: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Redact tokens from TemporaryAuthScope.toString()
TemporaryAuthScope is a data class, so any accidental logging will include accessToken, refreshToken, and profileToken in plain text. Override toString() to mask those fields, or avoid a data class here if the object may be logged.

🤖 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/network/TokenManager.kt`
around lines 5 - 13, Redact sensitive values from TemporaryAuthScope.toString()
by overriding the data class’s generated representation and masking accessToken,
refreshToken, and profileToken while retaining non-sensitive fields such as
serverId, serverUrl, profileId, and expiresAtEpochMs.
androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/detail/TvDetailFactsTable.kt-113-119 (1)

113-119: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Use the same episode date formatter in the facts table. formattedDate(airDate ?: releaseDate) parses the raw string differently from TvDetailMetadata.abbreviatedDate(...), so the hero and the “Aired” row can show different calendar days for the same episode. Reuse TvDetailMetadata.abbreviatedDate(airDate ?: releaseDate) here.

🤖 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/screens/detail/TvDetailFactsTable.kt`
around lines 113 - 119, Update the episode branch in the facts-table date logic
to use TvDetailMetadata.abbreviatedDate(airDate ?: releaseDate) instead of
formattedDate, while leaving the non-episode release and airing rows unchanged.
shared/src/androidMain/kotlin/org/siloserver/silo/network/EncryptedTokenManagerImpl.kt-154-170 (1)

154-170: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Keep invalidateSession() atomic

invalidateSession() releases mutex before clearTokens(), so another coroutine can start a new temporary scope in between. That makes clearTokens() skip the persistent wipe while _sessionExpired still fires. Hold the whole invalidation path under one lock or split out a non-locking clear helper.

🤖 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 154 - 170, Update invalidateSession() to keep temporary-scope
invalidation, persistent token clearing, and _sessionExpired emission
coordinated under the same mutex. Prevent another coroutine from creating a new
temporary scope between the existing mutex.withLock block and clearTokens(); use
a non-locking token-clear helper if needed while preserving the early return
behavior for temporary-session invalidation.
android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/repository/RoomUserItemStateRepository.kt-55-62 (1)

55-62: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Restore playback progress when SET_WATCHED is rejected.
record() clears user_item_state.positionSeconds as part of the watched mutation, but the TERMINAL path only reverts ContentItemStateEntity. If the server rejects the op, the watch flag rolls back and the resume point is lost permanently. Snapshot the prior progress before clearing it, or delay the clear until the op is accepted.

🤖 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 55 - 62, Update the SET_WATCHED flow in RoomUserItemStateRepository
so rejection restores both the previous watched value and the prior playback
position. Snapshot the existing progress before record() clears it, then ensure
the TERMINAL/rejection rollback restores that snapshot while preserving the
current accepted-mutation behavior.
android-shared/src/androidMain/kotlin/org/siloserver/silo/common/pairing/CompanionPairingCoordinator.kt-215-242 (1)

215-242: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Close the pairing transport exactly once.

The inner cleanup closes connected, then the outer finally closes the same object again without runCatching. A second-close failure can turn a completed pairing into an exception or mask the original error. Clear transport after inner cleanup and retain the outer close only as the pre-session fallback.

🤖 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/pairing/CompanionPairingCoordinator.kt`
around lines 215 - 242, Update the pairing cleanup around the inner finally and
the outer transport finally so the connected transport is closed exactly once.
After closing connected in the inner cleanup, clear the transport reference;
keep the outer transport close only for the pre-session fallback and guard it
with the existing safe-close pattern so a second close cannot alter pairing
results or mask errors.
androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/detail/TvItemDetailScreen.kt-241-258 (1)

241-258: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Use the Boolean from requestFocus()

  • runCatching { …requestFocus() }.isSuccess treats false as success at both focus-restoration sites, so the cast/hero fallback paths can be skipped when focus was never granted. Check the boolean result directly.
🤖 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/screens/detail/TvItemDetailScreen.kt`
around lines 241 - 258, The focus-restoration loop in the detail screen
incorrectly treats a completed requestFocus() call as success regardless of its
Boolean result. Update the cast restoration logic around
castReturnFocus.requestFocus() to use the returned Boolean, while preserving the
existing restored state and retry behavior so fallback paths execute when focus
is not granted.
androidApp/src/androidMain/kotlin/org/siloserver/silo/android/cast/SiloCastController.kt-177-188 (1)

177-188: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Clear isLaunching on transport teardown. teardownTransportLocked() cancels the handoff deferreds, and the reconnect path calls it without resetting launch state, so a mid-handoff drop can leave the spinner stuck after the resulting CancellationException is ignored. Either clear isLaunching there or complete the deferreds exceptionally with a transport error.

🤖 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/cast/SiloCastController.kt`
around lines 177 - 188, Update teardownTransportLocked() to clear the launch
state when transport teardown cancels an in-progress handoff, ensuring
isLaunching becomes false before the resulting CancellationException is ignored.
Preserve the existing reconnect and cancellation behavior while preventing the
launch spinner from remaining active after a mid-handoff disconnect.

Source: Linters/SAST tools

🟡 Minor comments (7)
androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/cast/TvSiloCastStandbyView.kt-35-36 (1)

35-36: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Remember the FocusRequester

TvSiloCastStandbyView is driven by a StateFlow, so recompositions are expected. Keep disconnectFocus stable with remember { FocusRequester() }; otherwise the button can detach from the requester while LaunchedEffect(Unit) still targets the original instance.

🤖 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/screens/cast/TvSiloCastStandbyView.kt`
around lines 35 - 36, Update the disconnectFocus declaration in
TvSiloCastStandbyView to retain the FocusRequester across recompositions using
Compose remember, so LaunchedEffect(Unit) continues targeting the requester
attached to the button.
androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuBar.kt-378-386 (1)

378-386: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Use the shared safe-area inset here — Spacing.safeArea is 40.dp while the trailing cluster still uses TvSkyline.safeAreaX at 44.dp, so the top bar ends up asymmetrically inset. Switch this leading padding to TvSkyline.safeAreaX for consistency.

🤖 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/TvTopMenuBar.kt`
around lines 378 - 386, Update the leading padding in the Box containing
TvSiloWordmark to use TvSkyline.safeAreaX instead of Spacing.safeArea, matching
the trailing cluster’s shared horizontal safe-area inset.
shared/src/commonMain/kotlin/org/siloserver/silo/repository/AuthRepository.kt-189-195 (1)

189-195: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Revalidate the active server before storing the fetched name.

A server switch during checkHealth() can make this response belong to a different active server while it is still written under activeId. Check that the active ID is unchanged—or bind the health request to a specific server—before calling setFetchedName.

🤖 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/repository/AuthRepository.kt`
around lines 189 - 195, Update the health-result handling around checkHealth and
registry.setFetchedName to verify that registry.activeServerId.value still
equals activeId immediately before storing the fetched name. Only call
setFetchedName when the active server remains unchanged, while preserving the
existing successful, nonblank serverName filtering.
androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/library/TvLibraryDetailViewModel.kt-246-248 (1)

246-248: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

onFacetSelectionApplied doesn't reset namePrefix like sibling filter-dimension setters.

onGenreChanged/onYearRangeChanged clear namePrefix when a "high-level filter dimension" changes (per the comment on onYearRangeChanged). Facet selection is the same kind of dimension change but leaves any active alphabet jump in place, silently combining it with the new facets.

♻️ Proposed fix
     fun onFacetSelectionApplied(selection: TvCatalogFacetSelection) {
-        updateBrowseFilter(_uiState.value.browseFilter.copy(facetSelection = selection))
+        updateBrowseFilter(
+            _uiState.value.browseFilter.copy(facetSelection = selection, namePrefix = 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
`@androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/library/TvLibraryDetailViewModel.kt`
around lines 246 - 248, Update onFacetSelectionApplied to clear namePrefix when
applying a new facet selection, matching the behavior of onGenreChanged and
onYearRangeChanged while preserving the existing facetSelection update.
androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/cast/SiloCastMiniBar.kt-110-116 (1)

110-116: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Drive the icon from collected playback state. controller.isPlaying() comes from a private clock, so this composable only refreshes when some other controller.state change happens; a local play/pause tap can leave the icon stale until the next playback-state message arrives.

🤖 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/cast/SiloCastMiniBar.kt`
around lines 110 - 116, Update the play/pause Icon in the SiloCastMiniBar
composable to derive its displayed icon and contentDescription from collected
controller playback state rather than directly calling controller.isPlaying().
Ensure local play/pause state changes trigger recomposition immediately while
preserving the existing Pause/Play behavior.
androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/cast/SiloCastArtwork.kt-34-45 (1)

34-45: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Stale artwork shown while new content resolves.

artwork isn't cleared when contentId changes; the previous item's poster/backdrop stays visible until the new LaunchedEffect finishes its (cache/network) lookup, which can briefly show the wrong artwork for the newly cast item.

🛠️ Proposed fix: reset state immediately on key change
     var artwork by remember { mutableStateOf(SiloCastArtwork()) }
     LaunchedEffect(contentId) {
+        artwork = SiloCastArtwork()
         artwork = if (contentId.isNullOrBlank()) {
             SiloCastArtwork()
         } else {
             resolveCastArtwork(repository, 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
`@androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/cast/SiloCastArtwork.kt`
around lines 34 - 45, Update rememberSiloCastArtwork so artwork resets to an
empty SiloCastArtwork immediately when contentId changes, before
resolveCastArtwork runs for the new ID. Keep the existing blank-ID handling and
asynchronous resolution behavior unchanged.
androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/calendar/TvCalendarScreen.kt-151-184 (1)

151-184: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Guard the consumed focus token before state.isLoading.
Because this effect is keyed on loading, any later load() transition can re-enter it and request filter focus again for the same focusRequest, stealing focus from the current shelf. Skip the effect as soon as the token has already been applied, regardless of loading state.

🤖 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/screens/calendar/TvCalendarScreen.kt`
around lines 151 - 184, Update the early-return guard in the LaunchedEffect
keyed by focusRequest and state.isLoading so it returns whenever focusRequest
equals lastAppliedFocusRequest, without requiring !state.isLoading. Keep the
existing focus-request and loading behavior unchanged for new, unapplied tokens.
🧹 Nitpick comments (5)
androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/di/AndroidTvModule.kt (1)

261-318: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Extract the shared TV device-name fallback
android.os.Build.MODEL?.trim()?.ifBlank { null } ?: "Android TV" is repeated in the pairing receiver, RemotePlaybackIdentityManager, and TvSiloCastReceiver. A small private helper would keep the three bindings in sync.

🤖 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/di/AndroidTvModule.kt`
around lines 261 - 318, Extract the repeated android.os.Build.MODEL fallback
into a private helper in AndroidTvModule, then reuse that helper for the name
provider in PairingReceiver, RemotePlaybackIdentityManager, and
TvSiloCastReceiver. Preserve the existing trimming and "Android TV" fallback
behavior.
androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvPinEntryDialog.kt (1)

73-75: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Move the PIN reset out of composition.

Writing pin directly while composing introduces an uncontrolled side effect. Use LaunchedEffect(isVerifying, errorMessage) so repeated identical errors are also handled after verification transitions. Compose guidance recommends keeping composables side-effect free and performing mutations through effect APIs. (developer.android.com)

Proposed fix
     var pin by remember { mutableStateOf("") }
     val latestError = remember(errorMessage) { errorMessage }
-    if (latestError != null && pin.length == PIN_LENGTH) pin = ""
+    LaunchedEffect(isVerifying, latestError) {
+        if (!isVerifying && latestError != null && pin.length == PIN_LENGTH) {
+            pin = ""
+        }
+    }

As per coding guidelines, “Use Kotlin 2.1, Java 21 targets, and Compose idioms.”

🤖 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/components/TvPinEntryDialog.kt`
around lines 73 - 75, Move the PIN-clearing mutation out of the composable body
in TvPinEntryDialog and into a LaunchedEffect keyed by isVerifying and
errorMessage. Preserve the condition that clears pin only when an error exists
and the PIN has reached PIN_LENGTH, including repeated identical errors after
verification transitions.

Source: Coding guidelines

shared/src/commonMain/kotlin/org/siloserver/silo/model/auth/DeviceLoginModels.kt (1)

75-79: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Consider defaults for DeviceLoginCapabilityResponse fields.

Unlike the other DTOs updated in this diff (which use nullable/default fields for new additions), remotePlaybackHandoff and protocolVersions have no defaults. A response missing either field (older server, partial payload) will throw MissingFieldException during deserialization instead of degrading gracefully.

♻️ Suggested defaults
 `@Serializable`
 data class DeviceLoginCapabilityResponse(
-    `@SerialName`("remote_playback_handoff") val remotePlaybackHandoff: Boolean,
-    `@SerialName`("protocol_versions") val protocolVersions: List<Int>,
+    `@SerialName`("remote_playback_handoff") val remotePlaybackHandoff: Boolean = false,
+    `@SerialName`("protocol_versions") val protocolVersions: List<Int> = emptyList(),
 )
🤖 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/model/auth/DeviceLoginModels.kt`
around lines 75 - 79, Update the DeviceLoginCapabilityResponse constructor
fields remotePlaybackHandoff and protocolVersions to provide nullable or
otherwise established safe defaults consistent with the other DTOs, so payloads
missing either field deserialize without MissingFieldException while preserving
normal values when present.
android-shared/src/androidMain/kotlin/org/siloserver/silo/common/startup/StartupWarmup.kt (1)

266-269: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Constant names should use camelCase, not PascalCase.

MaxProfileArtworkUrls and ProfileAvatarWarmSizePx are properties, not classes/composables. As per coding guidelines, **/*.kt functions and properties should use camelCase (e.g., maxProfileArtworkUrls, profileAvatarWarmSizePx).

✏️ Proposed rename
-private const val MaxProfileArtworkUrls = 8
+private const val maxProfileArtworkUrls = 8

 /** DiceBear presets already resolve at 256px; server avatars decode fine at it too. */
-private const val ProfileAvatarWarmSizePx = 256
+private const val profileAvatarWarmSizePx = 256
🤖 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 266 - 269, Rename the top-level constants MaxProfileArtworkUrls and
ProfileAvatarWarmSizePx to maxProfileArtworkUrls and profileAvatarWarmSizePx,
and update all references to use the camelCase names while preserving their
values and behavior.

Source: Coding guidelines

androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvAlphabetRail.kt (1)

121-121: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

FocusProperties.enter is deprecated; prefer onEnter.

FocusProperties.enter and FocusProperties.exit have been replaced with onEnter and onExit, using a receiver scope instead of FocusDirection parameter, and Multiple Focus APIs are now stable, including Modifier.focusRestorer() and onEnter and onExit FocusProperties since Compose UI 1.8.0. Consider migrating enter = { allFocusRequester } to onEnter = { allFocusRequester.requestFocus() } (or similar onEnter/FocusEnterExitScope usage) to move off the deprecated, experimental surface.

🤖 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/components/TvAlphabetRail.kt`
at line 121, Replace the deprecated enter assignment in the focusProperties
modifier with the stable onEnter callback, invoking
allFocusRequester.requestFocus() through the FocusEnterExitScope. Preserve the
existing behavior of moving focus to allFocusRequester when focus enters the
rail.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

latestSiloCastMediaController?.volume = if (muted) 0f else 1f

P2 Badge Restore the prior volume when unmuting remotely

When the phone remote mutes after the user has set TV playback below 100%, unmuting sends setMuted(false) and this receiver forces the MediaController volume to 1f instead of restoring the prior level. Because the cast state derives isMuted from volume being zero, the remote mute toggle can unexpectedly jump playback to full volume rather than returning to the user's chosen volume.

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +260 to +261
dismissHomeProgressItem(itemId) {
mediaActions.dismissNextUp(itemId, seriesId)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Remove dismissed Next Up items from next_up sections

When a TV Home progress row is a next_up/up_next section, the new action calls dismissNextUp, but dismissHomeProgressItem only removes items from continue_watching and in_progress sections. The API may succeed, yet the card stays visible until a full refresh, making the Remove action look like it did nothing for Next Up rows.

Useful? React with 👍 / 👎.

isConnectingToThis: Boolean,
onSelect: () -> Unit,
) {
val needsUpdate = launchRequest != null && target.version < SiloCastProtocol.version

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Disable unsupported TVs in remote-only picker

When the sheet is opened from Remote Control (launchRequest == null), this condition leaves v1 TVs enabled even though the controller and receiver negotiate only SiloCastProtocol.version 2. Selecting one proceeds to controller.connect and then fails after the hello/version check instead of showing the update-required disabled row, so users with an older TV client see a broken remote-control target.

Useful? React with 👍 / 👎.

Comment on lines +455 to +456
// Admin dashboard entry hidden for now (product call 2026-07-12);
// route + screen stay compiled for an easy re-enable.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep the acting-admin Settings entry live

AGENTS.md for this repo says the Admin STATS dashboard is live for acting admins with a Settings entry on both platforms. This change removes the only role-gated Settings rail action that invoked onNavigateToAdmin, so acting admins on Android TV can no longer reach the live stats dashboard even though the route remains compiled in TvMainShell.

Useful? React with 👍 / 👎.

Comment on lines 582 to 584
onSeasonSelected = { season ->
if (detail.type == "series") {
viewModel.onSeasonSelected(season.seasonNumber)
} else if (season.contentId != detail.contentId) {
// Switching seasons REPLACES the nav entry
// (QA 2026-07-08): flipping through seasons
// must not stack pages — one Back returns
// to wherever the user came from.
onItemDetailReplace(season.contentId)
}
viewModel.onSeasonSelected(season.seasonNumber)
},

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve season navigation on non-series detail pages

When the current detail page is a season or episode, selecting another season chip now only reloads the episode rail via onSeasonSelected, leaving the hero/title/metadata and back stack on the original season/episode. The previous non-series branch navigated to the selected season's content, so keep the in-place reload for series detail pages but navigate for season/episode pages to avoid showing a mismatched season rail under the wrong detail header.

Useful? React with 👍 / 👎.

Comment on lines +406 to +408
lastTargetStore.save(
SiloCastPersistedTarget(deviceId = target.deviceId, name = target.name, serverId = target.serverId),
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Persist the active server for cross-server casts

For a handoff launch to a TV that was advertising a different server, target.serverId is the TV's old advertised server, while the actual remote session is for the phone's active request.serverId. Saving the old target server here makes attemptAutoResumeIfIdle() reject the session on the next foreground because the persisted server no longer matches the active server, so cross-server remote playback cannot silently reattach while it is still playing.

Useful? React with 👍 / 👎.

@@ -979,19 +1115,29 @@ fun TvMainShell(
}
},
onSearchClick = onSearchPressed,
onProfileClick = { focusState.toggleProfileMenu() },
onProfileClick = {},

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Open the profile menu on avatar select

With the profile avatar focused, pressing Center/Enter still invokes the button's onClick, but this handler is now a no-op; the only remaining path into the profile menu is D-pad Down after focus/dwell. On a TV remote the primary select action should open the profile/actions menu, so users can focus the avatar and press OK yet nothing happens.

Useful? React with 👍 / 👎.

Comment on lines +245 to +247
val visibleItems = response.items
.visibleOnTv()
.filter { _uiState.value.showAudiobooks || !isAudiobookItemType(it.type) }

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Drain hidden audiobook pages in TV search

When the Audiobooks tab is hidden (the default), an All search can receive a page of audiobook results first and filter every item out here while still keeping hasMore from the raw response. TvCatalogGrid does not request another page when the rendered items list is empty, so later movie/series matches become unreachable and the screen can show “No matches” even though visible results exist on subsequent pages.

Useful? React with 👍 / 👎.

@Quick104
Quick104 merged commit f8003f2 into main Jul 14, 2026
3 of 4 checks passed
@Quick104
Quick104 deleted the codex/polish-shield-ui-ux branch July 14, 2026 00:28

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
shared/src/androidMain/kotlin/org/siloserver/silo/network/EncryptedTokenManagerImpl.kt (2)

130-149: 🔒 Security & Privacy | 🔴 Critical | ⚡ Quick win

Sign-out can silently no-op while a temporary scope is active.

clearTokens()/invalidateSession() now only clear temporaryScope and return early when it is non-null, never reaching clearPersistentTokensLocked(). signOutCurrentServer() (line 244-246) delegates straight to clearTokens(), so if a temporary scope happens to be active (e.g. a remote-cast pairing in progress) when the user signs out of their real account, the persistent access/refresh/profile tokens for the active server are never cleared — the user believes they are signed out, but the persistent session remains valid on disk.

🔒 Proposed fix — make sign-out unconditional on the persistent scope
     override suspend fun signOutCurrentServer() {
-        clearTokens()
+        mutex.withLock {
+            temporaryScope = null
+            clearPersistentTokensLocked()
+        }
     }

Also applies to: 244-246

🤖 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 130 - 149, Update clearTokens() and invalidateSession() so clearing
temporaryScope does not return before clearPersistentTokensLocked(); sign-out
must always clear persistent access, refresh, and profile tokens while still
removing any active temporary scope. Preserve session-expiration emission
behavior in invalidateSession(), and ensure signOutCurrentServer() continues to
inherit this unconditional persistent cleanup through clearTokens().

232-234: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

getCurrentServerId() doesn't guard against the documented registry-switch race.

Every other ambient getter (getAccessToken, getRefreshToken, getProfileId, getProfileToken) calls ensureCacheMatchesRegistryLocked() before reading cached state, specifically to avoid the race this file documents at lines 90-98 (ServerRegistry.switchTo() racing the async collector). getCurrentServerId() reads the raw cached activeServerId without that guard, so during that window it can report the OLD server id while getServerUrl() (which reads the live registry) already reports the NEW one — the exact server/credential mismatch the surrounding comments warn about.

🐛 Proposed fix
     override suspend fun getCurrentServerId(): String? = mutex.withLock {
+        ensureCacheMatchesRegistryLocked()
         temporaryScope?.serverId ?: activeServerId
     }
🤖 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 232 - 234, Update getCurrentServerId() to call
ensureCacheMatchesRegistryLocked() inside mutex.withLock before reading
temporaryScope?.serverId or activeServerId, matching the guard used by
getAccessToken, getRefreshToken, getProfileId, and getProfileToken.
androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/detail/TvItemDetailScreen.kt (1)

319-344: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Use the boolean result from requestFocus() here.

runCatching { ... }.isSuccess only means the call didn’t throw, so focusedImmediately can become true even when focus wasn’t granted. That skips the retry after the scroll and breaks the off-screen hero fallback; use getOrDefault(false) like the cast-restoration path above, and apply the same fix to the later retry guard.

🤖 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/screens/detail/TvItemDetailScreen.kt`
around lines 319 - 344, The returnToHero focus flow must use requestFocus()’s
boolean result rather than exception-free execution. Replace the isSuccess
checks around selectorFocus and playFocus with
runCatching(...).getOrDefault(false), and update the later selector retry guard
to test that boolean result similarly so failed focus requests still fall back
to playFocus after scrolling.
🧹 Nitpick comments (4)
shared/src/androidMain/kotlin/org/siloserver/silo/network/EncryptedTokenManagerImpl.kt (1)

288-297: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicate persistent-token lookup logic.

getAccessTokenForScope(serverId: String)/getRefreshTokenForScope(serverId: String) re-implement the exact same body as the new private persistentAccessToken/persistentRefreshToken helpers a few lines below. Delegating avoids the two copies drifting apart later.

♻️ Proposed refactor
     override suspend fun getAccessTokenForScope(serverId: String): String? = mutex.withLock {
-        if (serverId == activeServerId) accessToken
-        else prefs.getString(serverScopedKey(serverId, KEY_ACCESS_TOKEN), null)
+        persistentAccessToken(serverId)
     }

     override suspend fun getRefreshTokenForScope(serverId: String): String? = mutex.withLock {
-        if (serverId == activeServerId) refreshToken
-        else prefs.getString(serverScopedKey(serverId, KEY_REFRESH_TOKEN), null)
+        persistentRefreshToken(serverId)
     }

Also applies to: 356-363

🤖 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 288 - 297, Update getAccessTokenForScope and
getRefreshTokenForScope to delegate their non-active-server lookups to the
existing persistentAccessToken and persistentRefreshToken helpers, respectively,
while preserving the active-server accessToken and refreshToken behavior and
mutex protection.
android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/sync/OutboxOperation.kt (1)

93-105: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicate parse-and-branch logic between decodeBooleanPayload and decodeWatchedPayload.

Both functions perform the identical JsonPrimitive vs decodeFromJsonElement branching. decodeBooleanPayload can simply delegate to decodeWatchedPayload.

♻️ Proposed refactor
-        fun decodeBooleanPayload(payloadJson: String): Boolean {
-            val element = json.parseToJsonElement(payloadJson)
-            return if (element is JsonPrimitive) element.boolean
-            else json.decodeFromJsonElement<WatchedPayload>(element).watched
-        }
+        fun decodeBooleanPayload(payloadJson: String): Boolean =
+            decodeWatchedPayload(payloadJson).watched
🤖 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/sync/OutboxOperation.kt`
around lines 93 - 105, Refactor decodeBooleanPayload to delegate to
decodeWatchedPayload for parsing and primitive/object handling, returning that
result’s watched value. Remove its duplicated parse-and-branch logic while
preserving the existing behavior of decodeWatchedPayload.
android-shared/src/androidMain/kotlin/org/siloserver/silo/common/settings/AndroidPlayerSettingsStore.kt (1)

223-229: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

SAVED_CUSTOM_SUBTITLE_APPEARANCE reads bypass the unscoped-legacy fallback used by every other setting.

Both read sites for this new key go straight to p[stringPreferencesKey(scope.keyPrefix + SAVED_CUSTOM_SUBTITLE_APPEARANCE)] and fall back to the current SubtitleAppearance value rather than the unscoped legacy key. Every other flow in this file (boolFor/intFor/stringFor → scopedRead) falls back scoped → unscoped-legacy → default specifically to survive the transition from keyPrefix == "" to a non-empty scoped prefix (once serverUrl/deviceId become available). Skipping that fallback here means a user's actual saved-custom appearance written while unscoped can silently disappear and get replaced by whatever the live SubtitleAppearance happens to be at that moment.

  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/settings/AndroidPlayerSettingsStore.kt#L223-L229: read via a stringFor-style helper (scoped → unscoped-legacy → current-appearance default) instead of the direct p[...] lookup.
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/settings/AndroidPlayerSettingsStore.kt#L359-L363: same — read SAVED_CUSTOM_SUBTITLE_APPEARANCE through the scoped/legacy-fallback helper before falling back to the current SubtitleAppearance.
🤖 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/settings/AndroidPlayerSettingsStore.kt`
around lines 223 - 229, Update AndroidPlayerSettingsStore.kt lines 223-229 and
359-363 to read SAVED_CUSTOM_SUBTITLE_APPEARANCE through the existing
stringFor/scopedRead-style helper, preserving scoped → unscoped-legacy lookup
and using the current SubtitleAppearance value only as the final default.
shared/src/commonMain/kotlin/org/siloserver/silo/network/AuthInterceptorImpl.kt (1)

151-180: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low value

Swallowed exception in pinned refresh path.

catch (e: Throwable) { false } discards the failure reason (detekt: SwallowedException). This mirrors the existing pattern in the non-pinned refresh path below, but since pinned refresh failures currently just surface as a silent 401 pass-through, a log line would help diagnose recurring pinned-refresh failures.

🩹 Optional: log the swallowed exception
-                } catch (e: Throwable) {
-                    false
-                }
+                } catch (e: Throwable) {
+                    Log.w(TAG, "Pinned refresh failed for scope ${pinnedScope.serverId}", e)
+                    false
+                }
🤖 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/network/AuthInterceptorImpl.kt`
around lines 151 - 180, Update the catch block in the pinned refresh path within
the interceptor to log the caught failure, including its exception details,
before returning false. Reuse the existing logging facility and preserve the
current behavior of allowing the refresh attempt to fail without throwing.

Source: Linters/SAST tools

🤖 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 275-280: Update the requiresReplay branch in the
operation-resolution flow around OutboxOperation.decodeWatchedPayload so it
persists the replay flag as consumed/false before calling
syncScheduler.requestSync(). Keep the existing deletion path for non-replay
operations, and add a focused test that resolves two consecutive SYNCED
acknowledgements and verifies the operation is deleted after the replay ACK.

In
`@android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/sync/SyncEngine.kt`:
- Around line 108-118: The TERMINAL branch in SyncEngine must make the
newer-pending check, conditional rollback, and op deletion atomic. Wrap the flow
around countNewerPending, revertForTerminalOp,
restorePlaybackProgressForTerminalOp, and deleteById in the database transaction
mechanism used by RoomUserItemStateRepository.resolve(), or move it into an
equivalent transactional helper while preserving the existing stale-op guard and
dropped count behavior.

In
`@androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/profiles/TvProfileSelectionScreen.kt`:
- Line 95: Rename the property ProfileUtilityManageWidth to
profileUtilityManageWidth and update every reference to it, preserving its
existing value and behavior.

---

Outside diff comments:
In
`@androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/detail/TvItemDetailScreen.kt`:
- Around line 319-344: The returnToHero focus flow must use requestFocus()’s
boolean result rather than exception-free execution. Replace the isSuccess
checks around selectorFocus and playFocus with
runCatching(...).getOrDefault(false), and update the later selector retry guard
to test that boolean result similarly so failed focus requests still fall back
to playFocus after scrolling.

In
`@shared/src/androidMain/kotlin/org/siloserver/silo/network/EncryptedTokenManagerImpl.kt`:
- Around line 130-149: Update clearTokens() and invalidateSession() so clearing
temporaryScope does not return before clearPersistentTokensLocked(); sign-out
must always clear persistent access, refresh, and profile tokens while still
removing any active temporary scope. Preserve session-expiration emission
behavior in invalidateSession(), and ensure signOutCurrentServer() continues to
inherit this unconditional persistent cleanup through clearTokens().
- Around line 232-234: Update getCurrentServerId() to call
ensureCacheMatchesRegistryLocked() inside mutex.withLock before reading
temporaryScope?.serverId or activeServerId, matching the guard used by
getAccessToken, getRefreshToken, getProfileId, and getProfileToken.

---

Nitpick comments:
In
`@android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/sync/OutboxOperation.kt`:
- Around line 93-105: Refactor decodeBooleanPayload to delegate to
decodeWatchedPayload for parsing and primitive/object handling, returning that
result’s watched value. Remove its duplicated parse-and-branch logic while
preserving the existing behavior of decodeWatchedPayload.

In
`@android-shared/src/androidMain/kotlin/org/siloserver/silo/common/settings/AndroidPlayerSettingsStore.kt`:
- Around line 223-229: Update AndroidPlayerSettingsStore.kt lines 223-229 and
359-363 to read SAVED_CUSTOM_SUBTITLE_APPEARANCE through the existing
stringFor/scopedRead-style helper, preserving scoped → unscoped-legacy lookup
and using the current SubtitleAppearance value only as the final default.

In
`@shared/src/androidMain/kotlin/org/siloserver/silo/network/EncryptedTokenManagerImpl.kt`:
- Around line 288-297: Update getAccessTokenForScope and getRefreshTokenForScope
to delegate their non-active-server lookups to the existing
persistentAccessToken and persistentRefreshToken helpers, respectively, while
preserving the active-server accessToken and refreshToken behavior and mutex
protection.

In
`@shared/src/commonMain/kotlin/org/siloserver/silo/network/AuthInterceptorImpl.kt`:
- Around line 151-180: Update the catch block in the pinned refresh path within
the interceptor to log the caught failure, including its exception details,
before returning false. Reuse the existing logging facility and preserve the
current behavior of allowing the refresh attempt to fail without throwing.
🪄 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: bd99c5af-9c8a-4890-8924-4a512235de78

📥 Commits

Reviewing files that changed from the base of the PR and between 0ed7848 and 5fcbd17.

📒 Files selected for processing (51)
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/cast/SiloCastNsdBrowser.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/db/dao/DirtyOperationDao.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/db/dao/UserItemStateDao.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/repository/RoomUserItemStateRepository.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/sync/ContentProjectionRevert.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/sync/OutboxOperation.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/sync/SyncEngine.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/pairing/CompanionPairingCoordinator.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/pairing/PairingAuthPort.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/settings/AndroidPlayerSettingsStore.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/startup/StartupWarmup.kt
  • android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/data/repository/RoomUserItemStateRepositoryTest.kt
  • android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/network/EncryptedTokenManagerScopeIsolationTest.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/cast/SiloCastController.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/navigation/BottomNavBar.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/MainScreen.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/cast/SiloCastArtwork.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/cast/SiloCastMiniBar.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/cast/SiloCastRemoteScreen.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/cast/SiloCastTargetPickerSheet.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/downloads/DownloadsScreen.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/home/HomeScreen.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/pairing/CompanionPairingViewModel.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/cast/RemotePlaybackIdentityManager.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/cast/TvSiloCastReceiver.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/di/AndroidTvModule.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvAlphabetRail.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvPinEntryDialog.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylineSectionFeed.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/navigation/TvAppNavigation.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/calendar/TvCalendarScreen.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/cast/TvSiloCastStandbyView.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/detail/TvDetailFactsTable.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/detail/TvItemDetailScreen.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/detail/TvItemDetailViewModel.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/library/TvLibraryDetailViewModel.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvPlayerScreen.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/profiles/TvProfileSelectionScreen.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvRecommendationsScreen.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/search/TvSearchViewModel.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/settings/TvSettingsScreen.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuBar.kt
  • shared/src/androidMain/kotlin/org/siloserver/silo/network/EncryptedTokenManagerImpl.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/model/auth/DeviceLoginModels.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/network/AuthInterceptorImpl.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/network/AuthScopeSnapshot.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/network/TokenManager.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/network/api/DeviceLoginApi.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/repository/AuthRepository.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeViewModel.kt
🚧 Files skipped from review as they are similar to previous changes (34)
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/downloads/DownloadsScreen.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/cast/SiloCastArtwork.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/detail/TvDetailFactsTable.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/db/dao/UserItemStateDao.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvAlphabetRail.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/pairing/PairingAuthPort.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/cast/TvSiloCastStandbyView.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/cast/SiloCastNsdBrowser.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/pairing/CompanionPairingViewModel.kt
  • android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/data/repository/RoomUserItemStateRepositoryTest.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/cast/RemotePlaybackIdentityManager.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/cast/SiloCastMiniBar.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/model/auth/DeviceLoginModels.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/navigation/BottomNavBar.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/di/AndroidTvModule.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/cast/SiloCastTargetPickerSheet.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/repository/AuthRepository.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/search/TvSearchViewModel.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/startup/StartupWarmup.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvPinEntryDialog.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/recommendations/TvRecommendationsScreen.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/navigation/TvAppNavigation.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/detail/TvItemDetailViewModel.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvPlayerScreen.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/pairing/CompanionPairingCoordinator.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/home/HomeScreen.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/library/TvLibraryDetailViewModel.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvTopMenuBar.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvSkylineSectionFeed.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/calendar/TvCalendarScreen.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/cast/SiloCastController.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/cast/TvSiloCastReceiver.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/settings/TvSettingsScreen.kt

Comment on lines +275 to +280
val op = outboxDao.getById(handle.opId)
val requiresReplay = op?.takeIf { it.opKind == OutboxOperation.SET_WATCHED }
?.let { runCatching { OutboxOperation.decodeWatchedPayload(it.payloadJson).requiresReplay }.getOrDefault(false) }
?: false
if (requiresReplay) syncScheduler.requestSync()
else outboxDao.deleteById(handle.opId)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Consume requiresReplay before scheduling the final replay.

The operation remains queued with requiresReplay=true; its replay ACK follows this same branch and schedules another replay indefinitely. Persist a consumed/false replay flag before requesting sync, so the next ACK deletes the operation. Add a focused test covering two consecutive SYNCED resolutions.

As per coding guidelines, “For shared logic changes, add focused tests only for critical or high-risk behavior.”

🤖 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 275 - 280, Update the requiresReplay branch in the
operation-resolution flow around OutboxOperation.decodeWatchedPayload so it
persists the replay flag as consumed/false before calling
syncScheduler.requestSync(). Keep the existing deletion path for non-replay
operations, and add a focused test that resolves two consecutive SYNCED
acknowledgements and verifies the operation is deleted after the replay ACK.

Source: Coding guidelines

Comment on lines 108 to 118
WriteOutcome.TERMINAL -> {
// Server rejected this op for good — drop it AND revert the
// optimistic content projection so the card overlay defers to
// server state (no fake local state after cold start).
contentDao.revertForTerminalOp(op)
// A stale in-flight op must not roll back a newer pending
// intent with the same key. Otherwise revert both its
// optimistic content field and any resume rows it cleared.
if (dao.countNewerPending(op.coalesceKey, op.id) == 0) {
contentDao.revertForTerminalOp(op)
userStateDao.restorePlaybackProgressForTerminalOp(op)
}
dao.deleteById(op.id)
dropped++
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Map the target file and nearby symbols
ast-grep outline android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/sync/SyncEngine.kt --view expanded || true

# Find the related DAO and repository methods
rg -n "countNewerPending|revertForTerminalOp|restorePlaybackProgressForTerminalOp|supersedeOrRecordFailure|`@Transaction`" android-shared/src/androidMain/kotlin/org/siloserver/silo -S

# Show the relevant slice of SyncEngine.kt with line numbers
sed -n '80,150p' android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/sync/SyncEngine.kt

# Show the surrounding DAO definitions
fd -a "DirtyOperationDao.kt|.*Content.*Dao.*kt|.*User.*State.*Repository.*kt|.*Playback.*Progress.*kt" android-shared/src/androidMain/kotlin/org/siloserver/silo -t f

Repository: Silo-Server/silo-android

Length of output: 7299


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the DAO and repository implementations once located
for f in \
  android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/sync/DirtyOperationDao.kt \
  android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/content/ContentProjectionRevert.kt \
  android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/userstate/UserItemStateRepository.kt
do
  if [ -f "$f" ]; then
    echo "### FILE: $f"
    sed -n '1,240p' "$f"
    echo
  fi
done

Repository: Silo-Server/silo-android

Length of output: 162


🏁 Script executed:

#!/bin/bash
set -euo pipefail

sed -n '1,220p' android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/db/dao/DirtyOperationDao.kt
printf '\n### ContentProjectionRevert.kt\n'
sed -n '1,220p' android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/sync/ContentProjectionRevert.kt
printf '\n### RoomUserItemStateRepository.kt (260-320)\n'
sed -n '260,320p' android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/repository/RoomUserItemStateRepository.kt

Repository: Silo-Server/silo-android

Length of output: 12521


Make the terminal revert atomic
SyncEngine’s TERMINAL path does countNewerPending() and the revert/delete steps separately, so a new coalescing op can slip in between the guard and the rollback. The same flow in RoomUserItemStateRepository.resolve() is already wrapped in db.withTransaction; mirror that here or move the whole check-and-revert into a transactional helper.

🤖 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/sync/SyncEngine.kt`
around lines 108 - 118, The TERMINAL branch in SyncEngine must make the
newer-pending check, conditional rollback, and op deletion atomic. Wrap the flow
around countNewerPending, revertForTerminalOp,
restorePlaybackProgressForTerminalOp, and deleteById in the database transaction
mechanism used by RoomUserItemStateRepository.resolve(), or move it into an
equivalent transactional helper while preserving the existing stale-op guard and
dropped count behavior.

private val ProfileUtilityChromeTop = 40.dp
private val ProfileUtilityChromeEnd = 64.dp
private val ProfileUtilityChangeServerWidth = 164.dp
private val ProfileUtilityManageWidth = 104.dp

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Use camelCase for the new property.

Rename ProfileUtilityManageWidth to profileUtilityManageWidth and update its use.

As per coding guidelines, “Kotlin classes and composables use PascalCase; functions and properties use camelCase.”

🤖 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/screens/profiles/TvProfileSelectionScreen.kt`
at line 95, Rename the property ProfileUtilityManageWidth to
profileUtilityManageWidth and update every reference to it, preserving its
existing value and behavior.

Source: Coding guidelines

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5fcbd17398

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +142 to +144
if (temporaryScope != null) {
temporaryScope = null
return

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge End the remote identity when temporary auth expires

When a remote-playback temporary session gets a 401 and refresh cannot recover, SiloAuthPlugin calls invalidateSession(), but this branch only nulls temporaryScope. The TV receiver/player still have RemotePlaybackIdentityManager.activeIdentity registered, so subsequent relative API calls fall back to the saved TV server/profile via getServerUrl()/getAccessToken() instead of stopping the remote session, which can fetch or sync progress under the wrong account after the temporary credentials expire or are revoked.

Useful? React with 👍 / 👎.

Comment thread .gitignore

# Local review notes (not for publishing)
docs/reviews/
ui-validation/ No newline at end of file

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Remove tracked UI validation artifacts

Adding ui-validation/ to .gitignore does not untrack the many ui-validation/*.png and *.mp4 blobs added in this same commit, so they remain part of the repository and bloat every clone despite the ignore rule. The repo instructions say not to commit generated output or media fixtures; remove these validation captures from the index or publish them as external artifacts instead.

Useful? React with 👍 / 👎.

val requiresReplay = op?.takeIf { it.opKind == OutboxOperation.SET_WATCHED }
?.let { runCatching { OutboxOperation.decodeWatchedPayload(it.payloadJson).requiresReplay }.getOrDefault(false) }
?: false
if (requiresReplay) syncScheduler.requestSync()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Defer watched replay until progress settles

When a watched mutation is recorded while a SET_POSITION request is already in flight, this immediately schedules the replay as soon as the inline watched call succeeds, but the original progress request can still complete or be retried after that replay. In that race the later position sync can resurrect Continue Watching even though the user just marked the item watched; keep the replay queued until no matching in-flight progress remains, or supersede that progress op instead of letting it land later.

Useful? React with 👍 / 👎.

val next = if (filter.sort == sort.wireValue) {
filter.copy(order = if (filter.order == "asc") "desc" else "asc")
} else {
filter.copy(sort = sort.wireValue, order = sort.defaultOrder)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Clear the hidden A–Z prefix on non-title sorts

If the user has selected an A–Z prefix and then picks a non-title sort in the new Browse sort panel, this preserves namePrefix while changing the sort. The Browse screen hides the alphabet rail whenever the sort is not Title, so the grid silently remains limited to that letter with no visible filter or direct way to clear it; clear namePrefix when switching away from Title, or keep the prefix control visible.

Useful? React with 👍 / 👎.

val visibleItems = result.data.items.visibleOnTv()
val visibleItems = result.data.items
.visibleOnTv()
.filter { allowAudiobooks || !isAudiobookItemType(it.type) }

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Drain hidden audiobook pages in person filmography

When Audiobooks are hidden, an All filmography request can still receive a raw page whose items are all audiobooks, and this new filter drops every rendered item while keeping result.data.hasMore. TvCatalogGrid does not request another page when the rendered list is empty, so visible movie/series works on later pages are unreachable and the person page can show “No titles found.” even though more visible results exist; drain hidden-only pages before publishing the empty state.

Useful? React with 👍 / 👎.

@coderabbitai coderabbitai Bot mentioned this pull request Aug 4, 2026
3 tasks done
Quick104 added a commit that referenced this pull request Aug 17, 2026
TvCardOverlaySettingsScreen lost its Settings entry in #63 and has been
dead code since; overlay prefs are edited on the web app (profile-scoped
server setting) and the TV keeps rendering them. Remove the file and its
references in TvControlWiringCallSiteTest.

Co-Authored-By: Claude Fable 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants