Skip to content

fix: Android QA sweep + full review (phone + TV) + multi-part audiobooks (2026-07-09) - #50

Merged
RXWatcher merged 76 commits into
Silo-Server:mainfrom
RXWatcher:fix/android-qa-review-2026-07-09
Jul 9, 2026
Merged

RXWatcher merged 76 commits into
Silo-Server:mainfrom
RXWatcher:fix/android-qa-review-2026-07-09

Conversation

@RXWatcher

@RXWatcher RXWatcher commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

Supersedes #49 (closed). This rolls the phone QA sweep together with an exhaustive follow-up review of the whole Android codebase and a new multi-part audiobook feature, all on one stacked branch. 76 commits (29 original QA sweep + 47 review-fix commits, incl. a post-review deep-dive wave of 38 verified fixes); every wave was gated on :androidApp:assembleDebug + :androidTvApp:assembleDebug + ./gradlew test (all green).

⚠️ Not yet device-verified. It compiles and the unit/source-test suite passes, but the player/focus/audio behavior needs an on-device pass. Highest-priority things to eyeball: the first-frame black-screen watchdog window vs real remux cold-start, the multi-part audiobook flows (needs an actual multi-part book), the Box subtitle background across formats, and the touch-slop feel.

Phone (QA sweep + review fixes)

  • Player: failed subtitle picks / version switches no longer strand playback; orientation no longer snaps rotate-freely users to landscape and back; quality sheet opens fully expanded; tracks submenus have a back path; honest gesture feedback for gated Watch Together guests; a first-frame black-screen watchdog recovers silent DV-remux black screens.
  • Home/detail: audiobook continue-watching glyph routes to the audiobook player; released hero-transition claims re-offer to surviving duplicates; empty For You recovers; empty/failed season keeps the chips reachable; the Auto version/subtitle previews resolve through the real selection logic; backdrop info block scales with font size.
  • iOS-match items: small horizontal flicks no longer open cards (decoupled tap slop from row scroll slop); bare "Auto" subtitle preview (iOS phone parity); unified Dolby Vision detection behind one shared predicate.
  • Cleanup: Downloads double status-bar inset, shared card-date formatter, dead imports/wrappers.

TV (exhaustive review — T1 security/data, T2 player, T3 screens/UX)

  • Security/data: Sign Out now fully logs out (was leaving tokens/session live); Watch Next no longer leaks across profiles or mis-ranks/mis-types tiles; profile PINs are settable/changeable/removable; player session is actually stopped on teardown; version switches are single-flighted; request submissions survive navigation; removing the active server is handled instead of stranding the shell.
  • Player: black-screen watchdog re-arms per engine; scrubber hold-seek reads live state and Back/auto-hide no longer strand a scrub; credits don't fire on seeks; engine-switch timeout; full subtitle resolution/persistence repair; Watch Together transport gating holes closed (chapter seek, intro auto-skip, cast adapter); unsupported cast Launch returns an error frame instead of hanging.
  • Screens/UX: infinite load-more retry loop, search query mixing, personal-list/For You/calendar staleness, a large batch of focus/nav fixes, plus assorted small ones (inbox focus, admin feedback, settings retry, cast lifecycle, library-selection server scoping, locale decimals, PiP gates, audio-becoming-noisy gated off TV).

Multi-part audiobooks (new, matches Apple)

Android had no part model, so multi-file audiobooks broke resume/progress/sleep/sync. Ports Apple's client-side whole-book timeline:

  • Pure AudiobookTimeline (stitch parts by index, cumulative-sum durations, stitch chapters, map whole-book ↔ part-local) with unit tests.
  • Part-aware AudiobookPlayerViewModel: resume lands in the right part, Part 2+ reachable, seek/advance across parts, one whole-book position/duration to the UI. The corruption fix is a two-sink sync — the per-part session gets the part-local position while /sync/progress gets the whole-book global position — with a new disable_progress_persistence flag so a part-local position is never persisted as the book's.
  • Detail Parts list + stitched chapters + book-global Resume; sleep timer trimmed to Apple's Off/15/30/60. Single-part books collapse to today's behavior.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added whole-book audiobook playback with chapter/part navigation and resume from a specific position.
    • Added clearer player controls for quality, subtitles, chapters, and AI translate/navigation.
    • Improved shared-element transitions and item card interactions across home and detail screens.
  • Bug Fixes

    • Fixed subtitle rendering, auto-selection, and playback track selection behavior.
    • Improved playback stability for PiP, Dolby Vision, sleep timers, and resume handling.
    • Refined TV navigation, refresh behavior, and bottom-sheet scrolling to reduce accidental dismissals.

RXWatcher and others added 30 commits July 9, 2026 07:15
…rect-resume CW

From the 2026-07-09 phone QA pass:

Onboarding:
- Profile selection respects the status bar inset instead of bleeding
  into the phone's camera/menu chrome.
- Login focuses the username field on entry so the keyboard carries
  over from server setup.

Home:
- Poster flicker: the same item in two rows registered duplicate
  shared-element keys, and the transition machinery morphed between the
  two live cards, drawing into the overlay above everything (also
  hiding the header logo). A per-screen HeroClaimRegistry now lets only
  one visible card own a hero key; duplicates render plain and still
  navigate.
- "See All" removed from home rows (iOS has none; the landing screen
  shipped broken): screen, route, DI, and row affordance deleted.
- Continue Watching's center play glyph is now a direct-resume action
  (navigates to the player at position_seconds); poster tap still opens
  the item page. Book items keep the decorative glyph.
- Backdrop cards reserve a constant info-block height so mixed
  episode/movie rows no longer change height mid-scroll and bounce the
  rows below.
- Touch slop is inflated 1.75x inside horizontal rows only, so a
  mostly-vertical drag with sideways wobble no longer locks to the row.

Co-Authored-By: Claude Fable 5 <[email protected]>
- Person page: provider ids (TMDB/IMDb/TVDB/Plex) are internal
  bookkeeping no other client surfaces — removed; homepage stays.
  Added pull-to-refresh.
- For You: when the server has no recommendation sections, the
  Watchlist/Favorites pills become an inline selector (Watchlist by
  default) over the saved-list grid — the iOS savedListsFallback —
  instead of an empty promise that navigates away.

Co-Authored-By: Claude Fable 5 <[email protected]>
End clients don't get the Media Info dump on any other platform; drop
the overflow entry and the phone-only sheet behind it.

Co-Authored-By: Claude Fable 5 <[email protected]>
No other platform shows Tags/Genres as a detail section (genres stay in
the hero facts line), and iOS renders Cast & Crew / Details as plain
single-line headers. Make the eyebrow label optional and ellipsize
headers to one line.

Co-Authored-By: Claude Fable 5 <[email protected]>
Servers without media embeddings return an empty similar list; the
section header now lives inside SimilarRail and only renders once the
request resolves with items, matching the TV client's gating.

Co-Authored-By: Claude Fable 5 <[email protected]>
Calendar:
- Embedded in the tab shell, Scaffold no longer stacks its own
  status-bar inset on top of the shared header runway (the doubled top
  padding in portrait).
- The month label can no longer wrap into a one-character-per-line
  vertical stack when the Today pill squeezes the week strip.

Library browse:
- Sorting by Date Added / Release Date shows that date under each card
  (replaces the year caption).
- Comfortable/Normal/Compact view-density chips moved out of the
  control bar (where they read as sort options) into the filter sheet
  under a "View" heading.
- Genre filtering already exists as a facet in the filter sheet.

Co-Authored-By: Claude Fable 5 <[email protected]>
Product decision: pulled pending a cross-platform design. Drops the
episode-still blur/veil, the header eye toggle, and the source test
that pinned the feature.

Co-Authored-By: Claude Fable 5 <[email protected]>
Entering the phone player now locks to SENSOR_LANDSCAPE by default (iOS
PlayerOrientationCoordinator parity: landscapeLocked is the default on
new clients) and releases the lock on exit via the existing
originalOrientation restore. The HUD lock toggle now persists through
the orientation-mode player setting (raw values landscapeLocked /
rotateFreely, matching iOS) instead of flipping a transient local bool,
so an existing stored preference is respected on the next entry;
rotateFreely falls back to SCREEN_ORIENTATION_USER so the system
rotation preference stays in charge.

Co-Authored-By: Claude Fable 5 <[email protected]>
Replace the version pill + overflow-buried audio/subtitle entries with
a box-style list of all three track groups under the hero actions,
matching the TV/Apple detail treatment. Auto rows in every picker, and
selector values preview what Auto resolves to ("Auto - 1080p · HEVC"),
mirroring TvPlaybackFormatting.

Co-Authored-By: Claude Fable 5 <[email protected]>
Double-tap now uses iOS MobilePlayerGestureLayer's 35% side zones (the
middle band keeps the controls toggle) and shows clear visual feedback:
a 74dp circular badge with the Forward10/Replay10 glyph and a
"+10s"/"−10s" caption, vertically centered in the tapped half, held
700ms then faded out over 200ms — matching the iOS skipFlash timing.
Rapid re-taps restart the hold timer so repeated skips keep the badge
alive.

Co-Authored-By: Claude Fable 5 <[email protected]>
The pinch gesture previously cycled Fit -> Fill -> Stretch -> Fit
regardless of direction, evaluated mid-gesture. It now matches iOS
MobilePlayerGestureLayer: the scale accumulates over the whole gesture
and is evaluated once on release — pinch-out (>1.08) steps toward
fill/stretch, pinch-in (<1/1.08) steps back toward fit, clamped at
both ends with a dead zone in between. Two-finger events are consumed
for the whole pinch so they no longer leak into the seek/brightness
drag detectors. Clamped (no-op) steps skip the toast.

Co-Authored-By: Claude Fable 5 <[email protected]>
Episode pages now load the parent series' seasons and this season's
siblings (iOS episode-detail parity): season chips + the episode list
render as the first below-fold section with the open episode marked
Now Viewing; tapping a sibling opens its detail. Sibling downloads
group under the parent series.

Co-Authored-By: Claude Fable 5 <[email protected]>
All HUD chrome — the transport controls column and the overlay's
transient chips (notice, remote message, Watch Together badge, 2x pill,
sleep-timer chip, intro-skip / Up Next slot) — now applies
WindowInsets.safeDrawing before its edge padding. In portrait this
pushes the top-right cluster (gear included) below the camera cutout
instead of under it, and in landscape it clears cutout ears; the
existing 16dp edge padding rides on top of the insets as the extra
touch margin (iOS safe-area + 16pt parity).

Co-Authored-By: Claude Fable 5 <[email protected]>
Pair the hero download button's filled state with an explicit green
Downloaded row (iOS parity), and require a Discard/Keep confirmation
before a tap cancels an in-progress download.

Co-Authored-By: Claude Fable 5 <[email protected]>
Product decision: the HUD owns chapters + audio/subtitles + quality.
Adds a HighQuality HUD button (shown only when the item has multiple
file versions) that opens the existing QualitySelector sheet, and
removes the Quality row and the Navigation/Chapters row (and their
plumbing) from the gear settings sheet.

Co-Authored-By: Claude Fable 5 <[email protected]>
The detail perf source test asserted content types for the Tags/Genres
section and the similar-rail skeleton, both intentionally removed in
this QA sweep.

Co-Authored-By: Claude Fable 5 <[email protected]>
Track selectors in box style with Auto labels, Media Info hidden,
single-line headers, Tags/Genres sections dropped, similar rail gated
on results, episode-page season/episode selector, hide-spoilers
removed, downloaded indicator + cancel confirmation.

Co-Authored-By: Claude Fable 5 <[email protected]>
… back

Three related bottom-sheet QA issues, fixed via a shared
PlayerSheetSupport:

- Handle too close to the top edge: the player runs immersive, so tall
  sheets grew flush with the display edge and dragging the handle down
  opened the system notification shade. Sheet content is now capped at
  80% of the screen height (playerSheetMaxHeight) so the handle always
  sits well below the edge.
- Scrolling up inside sheets often dismissed them: Material 3 forwards
  the fling velocity left over after content scrolling into the sheet's
  settle, so a downward fling that ran into the top of the content
  hurled the sheet to Hidden. PlayerSheetFlingGuard (a nested-scroll
  connection between the content and the sheet) consumes post-fling
  velocity; drags pass through untouched, so the sheet still dismisses
  from the handle or when the content is already at the top. Applied to
  the settings, tracks, chapters, subtitle-style, stats, subtitle-search
  and quality sheets.
- Gear submenus had no way back to the parent menu: Subtitle Style,
  Sleep Timer and Playback Stats now take an optional onBack and render
  a leading back chevron in their headers that reopens the settings
  sheet.

Co-Authored-By: Claude Fable 5 <[email protected]>
QA: HDR content on the compatibility (Media3/ExoPlayer) pipeline played
audio+subtitles with a permanently black video surface.

Investigation findings:
- The phone track-selection path (buildPhoneParameters) has no HDR
  video-MIME handling at all (unlike the TV path), and Media3 has no
  phone-side tone-mapping fallback wired up (no setVideoEffects /
  TONEMAP anywhere in the pipeline).
- Nothing catches the failure: preflight only inspects Dolby Vision
  codec strings (HDR10/HLG never trigger onUnsupportedPlayback), the
  startup-stall detector marks the session started as soon as AUDIO
  progresses (isPlaying short-circuits it), and a video renderer that
  silently produces no frames raises no fatal PlaybackException — so
  the black screen persisted with no recovery.

A real Media3 HDR fix (tone-mapped decoder config / first-frame
watchdog) is deep; per the QA decision, HDR sources now prefer the
primary engine instead: VideoPlaybackBackendRequest gains hasHdrVideo
(from the active FileVersion.hdr) and the Auto selector routes it to
MPV, whose gpu-next renderer tone-maps HDR correctly. Route intent
(Cast/DRM/HLS/transcode) and the MPV device floor still win first, and
the engine decision log now reports hasHdrVideo (plus the previously
missing hasSoftwareOnlyVideoCodec) as the selection reason.

Co-Authored-By: Claude Fable 5 <[email protected]>
Subtitle overrides chosen in the phone player were persisted (commit
63b0e7a's mechanism fired correctly on write) but never restored:
selections are recorded as fingerprints of the MOUNTED subtitle list
(PlayerSubtitleInfo — uiState.subtitleTracks), while restore resolved
them against the catalog FileVersion.subtitleTracks (SubtitleTrack),
whose index space is the demux stream index. The two fingerprint
overloads therefore never matched and the saved choice was silently
dropped (audio persisted fine because it uses the catalog type on both
sides).

Adds resolveMountedSubtitleOrdinal (a PlayerSubtitleInfo resolver — a
List overload would erase to the same JVM signature) and restores the
saved fingerprint against playbackState.subtitleUrls, the same list the
write path fingerprints.

Co-Authored-By: Claude Fable 5 <[email protected]>
Selecting subtitles on the item page before playback never enabled
them: the detail screen's pick is an ordinal into the catalog
FileVersion.subtitleTracks list, but the phone player validated it
directly against the mounted playbackState.subtitleUrls list (a
different index space and ordering) — so it either fell out of range
and dropped to auto/-1, or selected the wrong track.

Adds resolveInitialMobileSubtitleOrdinal (TV
resolveInitialSubtitleTrackIndex parity): the catalog pick is matched
onto the mounted list by label first, then language + forced flag +
codec; unmatched picks fall back to the raw ordinal when mountable
(previous behavior), else defer to persisted/auto selection.

Co-Authored-By: Claude Fable 5 <[email protected]>
The Box background style previously used CaptionStyleCompat's
backgroundColor, which Media3 renders as a per-line BackgroundColorSpan
hugging the glyphs with no breathing room. Box now paints through
windowColor instead: SubtitlePainter draws the window as a single block
behind the whole cue with INNER_PADDING_RATIO (12.5% of the text size)
of padding, giving the box visible margin around the text. Shadow /
Outline / None keep a fully transparent window as before. The MPV
route already pads its box via MpvSubtitleStyle's sub-border-size
floor (same QA sweep).

Co-Authored-By: Claude Fable 5 <[email protected]>
- MediaRow read LocalViewConfiguration inside remember's calculation
  lambda (non-composable context); capture it first.
- Restore HomeSectionRow's optional onSeeAllClick pass-through:
  Libraries and the Reading hub legitimately route it to their browse
  surfaces — only Home drops the affordance (iOS parity).
- PersonDetailScreen needed the ExperimentalMaterial3Api opt-in for
  PullToRefreshBox.

Earlier "compile checks" during the sweep invoked a nonexistent Gradle
task and filtered for a string Kotlin errors don't emit — worthless on
both counts. Real verification below.

Co-Authored-By: Claude Fable 5 <[email protected]>
Landscape lock with persisted preference, double-tap ±10s zones,
safe-inset HUD padding, quality HUD button (chapters/quality out of the
gear), sheet fling guard + submenu back navigation, pinch
fit/fill/stretch, HDR-to-MPV routing, subtitle persistence fingerprint
fix, pre-playback subtitle carry-over, boxed-subtitle padding.

Co-Authored-By: Claude Fable 5 <[email protected]>
…stly

Follow-ups from the first hands-on pass of the QA build:

- The top-bar title had no width constraint, so in portrait with every
  button visible (rotate, chapters, tracks, quality, gear) the trailing
  buttons were pushed off-screen — the gear "disappeared" exactly when
  a second file version made the quality button appear, and the
  remaining buttons crowded oddly. The title now owns a weighted,
  shrink-first middle slot and ellipsizes; the cluster always fits.
- Orientation toggle uses screen-rotation glyphs instead of a padlock —
  it changes rotation behavior, it doesn't lock anything.
- Tracks button swaps "CC" for the speech-bubble glyph (iOS
  captions.bubble): the sheet selects audio as well as subtitles.
- Control glyphs normalized to a uniform 22dp.

Co-Authored-By: Claude Fable 5 <[email protected]>
…forced flag

Codex review findings on PR #49, both verified:

- The HDR-to-MPV clause sat below the planned-engine checks, so a v2
  plan naming MEDIA3_DIRECT — the normal direct-play case — kept HDR on
  the black-screen Media3 path. HDR now outranks planned Media3 engines
  (transcoded output exempt: the server already resolved HDR), with a
  regression test pinning the planned-MEDIA3_DIRECT case.
- Catalog-to-mounted subtitle matching returned on a bare label match;
  duplicate titles ("English" full + forced) could map to the wrong
  variant when mounted order differs. A label match now also requires
  the forced flag to agree.

Co-Authored-By: Claude Fable 5 <[email protected]>
- A stale explicit subtitle index no longer displays as "Auto - None":
  the formatter falls back to the default track's label, mirroring the
  audio formatter's honest handling.
- The "Details" header renders inside DetailFactsList, gated on having
  facts — sparse items no longer show a lone header (movie + series).
- PlaybackStatsSheet adopts the shared PlayerSheetHeader like the other
  sheets instead of hand-rolling a diverging header.

Co-Authored-By: Claude Fable 5 <[email protected]>
Device A/B on a Pixel 10 Pro (2026-07-09): the same HDR10+ 4K HEVC file
plays perfectly on Media3 (official v0.3.4) but hiccups on the QA
build, which routed it to MPV under the new blanket hasHdrVideo clause.
MPV's slurp-then-idle streaming pattern leaves the connection idle long
enough to be reset mid-file (observed: "Stream ends prematurely" +
reconnect at 1.2GB of 5.2GB), each reset a visible stutter.

The Media3 black-screen class is Dolby Vision, not HDR at large. The
routing clause and request field become hasDolbyVisionVideo, detected
from the playback plan's source metadata (dolby_vision_profile /
hdr_format); HDR10/HDR10+/HLG stays on Media3. Plan-less legacy
sessions fall back to Media3 with the failure detectors as backstop.

Co-Authored-By: Claude Fable 5 <[email protected]>
… pill

Selecting a version/quality that the server can't honor (e.g. "No lower
resolution version available for transcoding") dropped the viewer to a
bare black full-screen error, because onSelectVersion stops the current
session before attempting the new one — so any failure left nothing
playing.

Failures are now non-fatal: a dismissable, auto-expiring pill surfaces
a humanized message ("That quality isn't available for this title.")
over the still-playing video, and the previously-working version is
restarted. A recursion guard covers the unlikely case where the
restore itself fails.

Co-Authored-By: Claude Fable 5 <[email protected]>
…anding playback

Three verified fixes from the PR #49 review:

- Subtitle silent-Off: the initial-selection chain suppressed the persisted
  and auto fallbacks (and armed persistence) on the mere presence of an
  explicit detail-page pick. An unmatchable pick then resolved to -1 (Off)
  AND persisted that Off for every future playback of the file. Resolve the
  pick first and gate suppression/persistence on it actually resolving, so a
  failed pick falls through to persisted -> auto and never persists Off. A
  deliberate -1 (Off) from the detail page still resolves and persists.

- Version-switch failure: removed the dead versionSwitchRecovering guard and
  the selectedVersionIndex=-1 sentinel. Extracted startVersionPlayback(index,
  isRecovery) that bypasses the dedupe on recovery without writing an invalid
  index; a recovery restart that also fails now raises a persistent error
  screen instead of leaving a session-less black player behind a 4s pill. The
  auto-dismiss timer is a single cancellable job, so repeated identical
  failures no longer dismiss the fresh pill early.

- Orientation snap: orientationLocked's eager 'true' meant the factory-scoped
  VM's first frame always reported locked, snapping rotateFreely users to
  landscape then back on every entry. Added orientationLockedResolved (nullable,
  null until the persisted value arrives); PlayerScreen applies orientation only
  once resolved. The non-null display flow is unchanged for the HUD toggle.

Co-Authored-By: Claude Fable 5 <[email protected]>
RXWatcher and others added 7 commits July 9, 2026 17:10
…bility floor

- TV never set hasDolbyVisionVideo on its playback-backend requests, so the
  selector's DV->MPV arm never fired and a DV file rode Media3 until the
  first-frame watchdog recovered it (~8s of black). Set it at all three request
  sites via the shared isDolbyVision predicate, so DV routes to MPV proactively
  with the watchdog as the reactive backstop.
- PiP auto-enter was armed for any API 31+ surface while the explicit enter path
  is gated at API 34 for TV, so Android 12/13 TVs could auto-enter a PiP mode the
  app deems unsupported. Gate auto-enter through the same eligibility check, and
  guard setPictureInPictureParams behind FEATURE_PICTURE_IN_PICTURE so it can't
  throw on hardware without PiP.

Co-Authored-By: Claude Fable 5 <[email protected]>
…ange

setHandleAudioBecomingNoisy and setSuppressPlaybackOnUnsuitableOutput were on
unconditionally in the shared ExoPlayer factory, so on Android TV an HDMI/eARC
renegotiation (e.g. a soundbar power-cycle) could pause or suppress playback with
no user action — a phone default on the wrong form factor, and inconsistent with
the MPV engine. Gate both behind !isTv; phone/tablet behavior is unchanged.

Co-Authored-By: Claude Fable 5 <[email protected]>
…es (match tvOS)

The detail Subtitles row previewed 'Auto - <isDefault track>' while the player's
auto path uses preferred-language/mode/forced/SDH rules and can resolve to Off, so
the preview contradicted playback. Apple tvOS shows a resolved 'Auto - X' computed
by mirroring the real resolver (unlike the iOS phone, which shows a bare 'Auto').
Match tvOS: compute the preview via the same auto-selection logic the TV player
uses (dropping isDefault), showing 'Auto - None' when auto resolves to disabled.
The prefs (preferred language, subtitle mode, show-forced) come from the active
profile, threaded through the detail VM and selector row; audio language is
derived from the selected version. Tests updated to the resolved labels.

Co-Authored-By: Claude Fable 5 <[email protected]>
…the video

Box style routes the background through CaptionStyleCompat.windowColor, and
media3's SubtitlePainter expands the window rect to the full cue-region width
whenever a cue carries a size. Every WebVTT cue defaults to full-width size, and
the server delivers all sidecar text subtitles (including converted SRT) as .vtt,
so the box rendered as a full-video-width band on both phone and TV. Neutralize
the WebVTT full-width default size (size==1) on text cues before they reach the
SubtitleView, via the existing SubtitleVideoRectSync listener (one shared hook),
so the box hugs the text. Bitmap cues and intentionally-narrower positioned cues
are left untouched. NEEDS ON-DEVICE VERIFICATION across SRT-as-VTT, native SRT,
positioned WebVTT, and PGS.

Co-Authored-By: Claude Fable 5 <[email protected]>
…t books

The server sends audiobooks as separate per-file versions tagged
presentation_kind=audiobook_part with presentation_part_index, but Android never
deserialized those fields, so it treated every audiobook as a single file. Add
the fields to FileVersion (defaulted, single-file items unchanged) and a pure
AudiobookTimeline that stitches the parts into one whole-book timeline the way
Apple's AudiobookPlaybackContext does: order by part index, cumulative-sum each
part's duration for its global start offset, stitch and globally sort chapters,
and map whole-book <-> (part, part-local) positions. Foundation only; the player
VM and UI consume it next. commonTest covers offsets, boundaries, round-trips,
chapter stitching, and single/zero-part cases.

Co-Authored-By: Claude Fable 5 <[email protected]>
…h correct sync

Rework the shared AudiobookPlayerViewModel to be part-aware, mirroring Apple's
AudioPlayerViewModel. It builds the whole-book timeline once, drives playback one
part at a time, and presents a single whole-book position/duration to the UI:
resume maps the stored book-global position to the right part + in-part offset
(fixing the 'seeks past end of Part 1 and ends instantly' bug), seeking and part
advance load the target part, and Part 2+ is reachable. Single-part books collapse
to today's behavior.

The corruption fix is the two-sink model: the per-part playback session gets the
part-local position, while durable resume (/sync/progress) gets the whole-book
global position and total. Every audiobook session is now started with
disable_progress_persistence=true (added to StartPlaybackRequest / the repository /
PlaybackSessionManager; verified against the server field and the Apple/web
clients), so a part-local position can never be persisted as the book's position.
Playback speed carries across part loads; load/start generation guards prevent a
stale load or an older book from clobbering a newer one. Video playback is
unaffected (the new flag defaults false).

Co-Authored-By: Claude Fable 5 <[email protected]>
…ute-only sleep timer

With the timeline and part-aware VM in place, wire the UI on both platforms:
- Detail Play/Resume launches with the whole-book resume position (fileId=null)
  and lets the VM resolve the part, instead of pinning Part 1 — so Resume no
  longer seeks past the end of the first part. Apple's gating: resume >30s ->
  Resume, finished -> Play Again from 0, else Play.
- A Parts list appears only for multi-part books (row = file name or 'Part N',
  tapping plays from that part's whole-book offset); tapping a part or chapter no
  longer wrongly resolves to Part 1.
- Chapters use the stitched whole-book list (global offsets) for multi-part books;
  single-part books keep the file's own chapters. The scrubber already reads the
  whole-book position/duration from the VM, so it needed no change.
- Sleep timer trimmed to Apple's Off/15/30/60 minutes on both platforms:
  EndOfChapter/EndOfBook removed from SleepTimerChoice, the VM boundary logic, and
  both sleep panels (Apple has no such options). Single-part audiobooks are
  unchanged throughout.

Co-Authored-By: Claude Fable 5 <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 9, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

This PR introduces a stitched whole-book audiobook timeline model shared across platforms, Dolby Vision detection and backend routing, and a broad set of player, detail-screen, navigation, and TV app improvements. Changes span shared Kotlin models, android-shared player core (PiP, session management, subtitle rendering), phone app UI (navigation, home/browse/detail screens, player sheets/gestures/HUD, recommendations), and TV app UI (navigation, detail/player screens, requests, profiles, Watch Next).

Changes

Shared module

Layer / File(s) Summary
Audiobook timeline model
shared/.../audiobook/AudiobookTimeline.kt, shared/.../model/catalog/CatalogModels.kt, shared/src/commonTest/.../AudiobookTimelineTest.kt
Adds a stitched whole-book timeline (tracks/chapters/offsets), a builder from FileVersion parts, and catalog fields for presentation kind/part index/total, with extensive tests.
Dolby Vision detection
shared/.../player/DolbyVisionDetection.kt, shared/src/commonTest/.../DolbyVisionDetectionTest.kt
Adds a singleton detecting Dolby Vision from profile, HDR format string, or codec token.
Playback flags and subtitle fingerprint
shared/.../model/playback/PlaybackModels.kt, shared/.../repository/PlaybackRepository.kt, shared/.../playback/TrackSelectionFingerprint.kt, shared/src/commonTest/...
Adds disableProgressPersistence to start-playback request/repository and resolveMountedSubtitleOrdinal for fingerprint-to-index mapping.
CalendarViewModel
shared/.../viewmodel/CalendarViewModel.kt
Recomputes "today" on every load/refresh call.

Estimated code review effort: 5 (Critical) | ~150 minutes

android-shared

Layer / File(s) Summary
PiP eligibility
.../pip/SiloPictureInPictureCoordinator.kt
Adds device feature checks alongside API-level checks for PiP entry/exit/auto-enter.
Multi-part audiobook playback engine
.../player/AudiobookPlayerViewModel.kt, .../player/SleepTimerChoice.kt
Reworks the ViewModel around a stitched timeline (cross-part load/seek/retire, global/local time mapping) and trims sleep timer to Off/Minutes only.
Session progress-persistence toggle
.../player/PlaybackSessionManager.kt, tests
Adds disableProgressPersistence parameter forwarded to the repository.
TV audio-route guard
.../player/SiloPlayerFactory.kt
Scopes noisy-audio/unsuitable-output guards to non-TV form factors.
Subtitle cue neutralization
.../player/SubtitleManager.kt, tests
Neutralizes full-width cue sizing and fixes caption background color ordering.
Dolby Vision backend routing
.../player/backend/*, .../player/video/OriginalPlaybackRequestPolicy.kt, tests
Adds hasDolbyVisionVideo to backend requests, routes Dolby Vision direct-play to MPV, and centralizes codec detection.

androidApp

Layer / File(s) Summary
Navigation/DI cleanup
ui/navigation/*, di/AndroidModule.kt, ui/screens/MainScreen.kt
Removes HomeSectionItems route/screen wiring and adds startPosition to audiobook player navigation.
Hero shared-element registry
ui/navigation/SharedElementTransition.kt
Adds ownership-based hero claim registry for duplicate shared-element cards.
Home screen and cards
ui/screens/home/*, ui/components/MediaCard.kt, MediaRow.kt, BackdropCard.kt
Wires hero claims, audiobook-aware item-play routing, overlay play affordance, and gesture-slop scoping.
Browse/catalog and detail screens
ui/screens/browse/*, ui/screens/detail/*, ui/screens/audiobook/*, ui/util/Formatters.kt
Adds per-card date subtitle, timeline-based audiobook detail rendering, auto version/audio/subtitle selection, episode "now viewing" badge, and simplified similar rail.
Player sheets and controls
ui/screens/player/*
Adds a shared sheet-support module, capped height/fling guard/back navigation across all bottom sheets, quality HUD button, iOS-style skip gestures, directional pinch gravity, and player screen/view model Dolby Vision routing, watchdog, and version-switch messaging.
Recommendations fallback
ui/screens/recommendations/RecommendationsScreen.kt
Adds resume refresh and an inline watchlist/favorites fallback when the feed is empty.

androidTvApp

Layer / File(s) Summary
TV navigation and shell
ui/navigation/TvAppNavigation.kt, ui/shell/TvMainShell.kt, MainTvActivity.kt, cast/TvSiloCastReceiver.kt
Gates deep links pre-auth, adds full sign-out/profile-switch teardown, and reworks content-up fallback ownership.
TV lists/pagination
ui/components/TvCatalogGrid.kt, ui/components/TvSkylineSectionFeed.kt, ui/screens/library/TvLibraryDetailViewModel.kt, ui/screens/notifications/TvInboxScreen.kt, ui/screens/people/TvPersonDetailViewModel.kt, ui/screens/search/TvSearchViewModel.kt
Adds stall detection/retry, dedup pagination, and generation-guarded search results.
TV audiobook/detail/player
ui/screens/audiobook/*, ui/screens/detail/Tv*, ui/screens/player/Tv*, data/preferences/TvLibrarySelectionStore.kt
Adopts the stitched timeline for parts/chapters/playback, adds Dolby Vision routing, engine-switch timeout/watchdog, subtitle auto-resolution, and per-server library selection partitioning.
TV requests, profiles, servers, settings
ui/screens/requests/*, ui/screens/profiles/*, ui/screens/servers/*, ui/screens/settings/TvSettingsViewModel.kt
Adds a dedicated requests action view model, PIN clear/keep semantics, active-server removal handling, and bounded user-load retry.
Watch Next
watchnext/*
Adds audiobook program typing, nullable engagement time, coroutine-safe diff/clear, and cancellation checks in sync worker.

Repository housekeeping

Layer / File(s) Summary
Gitignore
.gitignore
Adds docs/reviews/ to ignored paths.

Sequence Diagram(s)

sequenceDiagram
  participant UI as AudiobookDetailContent/TvItemDetailScreen
  participant Timeline as buildAudiobookTimeline
  participant VM as AudiobookPlayerViewModel/TvPlayerViewModel
  participant Session as PlaybackSessionManager
  participant Repo as PlaybackRepository

  UI->>Timeline: build stitched timeline from FileVersions
  Timeline-->>UI: AudiobookTimeline(tracks, chapters, totalSeconds)
  UI->>VM: onPlayFromPositionClick(startPositionSeconds)
  VM->>VM: clampGlobal / loadTrack(trackIndex, localStart)
  VM->>Session: startSession(disableProgressPersistence=true)
  Session->>Repo: startPlayback(disableProgressPersistence)
  Repo-->>Session: PlaybackSessionResponse
  Session-->>VM: session started
  VM->>VM: applyStartedSession(localSeek, globalPosition)
  VM-->>UI: uiState.positionSeconds (whole-book)
Loading
sequenceDiagram
  participant Screen as PlayerScreen/TvPlayerScreen
  participant Selector as VideoPlaybackBackendSelector
  participant Detection as DolbyVisionDetection
  participant Engine as PlaybackEngine (MPV/Media3)

  Screen->>Detection: isDolbyVision(profile, hdrFormat, videoCodec)
  Detection-->>Screen: true/false
  Screen->>Selector: select(VideoPlaybackBackendRequest{hasDolbyVisionVideo})
  Selector->>Selector: check hasDolbyVisionVideo && playMethod != TRANSCODE
  Selector-->>Screen: VideoPlaybackBackendKind.Mpv or Media3
  Screen->>Engine: awaitEngineSwitch(withTimeout)
  Engine-->>Screen: EngineSwitchResult(success/swapped)
Loading

Estimated code review effort: 5 (Critical) | ~180 minutes

Possibly related issues

Possibly related PRs

  • Silo-Server/silo-android#38: Both PRs modify VideoPlaybackBackendSelector.select(...) to add new backend-precedence rules (Dolby Vision vs software-only codec), so the changes are code-level related.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 32.31% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately reflects the stacked QA fixes across phone/TV plus the new multi-part audiobook work.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@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: 246803d937

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

}
// Cross-process ContentResolver deletes are binder I/O: run them off
// the caller's (main) thread so clear() stays cheap for call sites.
scope.launch { repository.clearAll() }

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 Await Watch Next clears before reseeding

When switching to an already-authenticated server, the navigation path still calls watchNextSeeder.clear(); watchNextSeeder.seedNow(); watchNextSeeder.enqueuePeriodic() in sequence. This change makes clear() return immediately while clearAll() runs on a background scope, so the delete can race after the new one-shot sync writes rows for the new server/profile and wipe the freshly seeded Watch Next channel until the next periodic sync. Keep the wipe awaited off the main thread, or sequence reseeding after it completes.

Useful? React with 👍 / 👎.

Comment on lines 612 to 613
it.copy(
streamUrl = resolvePlaybackStreamUrl(serverUrl, r.data.streamUrl),

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 Guard stale audiobook transcode starts

For multi-part audiobooks whose part session resolves to REMUX/TRANSCODE, startTranscodeFallback is another suspend call after the loadGeneration check in loadTrack. If the user seeks or auto-advances to a different part while /transcode/start is in flight, this success branch still writes the old streamUrl/sessionId because it never rechecks generation/isClosing after the call returns, so a stale part can replace the current one and leave the newer session inconsistent. Recheck the generation before applying r.data.

Useful? React with 👍 / 👎.

@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: 17

Caution

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

⚠️ Outside diff range comments (2)
androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvPlayerViewModel.kt (1)

878-882: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Reset the auto-subtitle latch on each fresh load.

autoTextSubtitleSelectionAttempted is session-scoped but survives loadContent() calls for retry/version-switch/fallback restarts. Once it is set, a later fresh mount with new tracks will skip auto subtitle resolution entirely.

Proposed fix
         introAutoSkipController.reset()
         manualSubtitleSelectionApplied = false
+        autoTextSubtitleSelectionAttempted = false
         // Fresh content: forget engines attempted for the previous item.

Also applies to: 1694-1700

🤖 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/player/TvPlayerViewModel.kt`
around lines 878 - 882, The fresh-load reset in TvPlayerViewModel.loadContent
should also clear the session-scoped auto-subtitle latch, since
autoTextSubtitleSelectionAttempted can incorrectly persist across
retry/version-switch/fallback restarts and block auto subtitle resolution on new
tracks. Update the existing reset block alongside
introAutoSkipController.reset(), manualSubtitleSelectionApplied,
attemptedEngines, and engineSwitchFailureEngines so
autoTextSubtitleSelectionAttempted is reset for each fresh content mount; apply
the same change in the other load/restart path referenced by the duplicate
block.
android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/AudiobookPlayerViewModel.kt (1)

291-318: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Keep the offline fallback in file-local time.

Line 317 uses wholeBookDuration even when offlineMedia != null, but Line 325 returns before timeline is assigned. That leaves onPositionChanged() treating part-local engine time as whole-book time while the UI/save sink uses a whole-book duration, so downloaded multi-part playback can persist a part-local position as the book position.

Proposed fix
                     val wholeBookDuration = builtTimeline?.totalSeconds
                         ?: d.audiobook?.totalDurationSeconds?.toDouble()
                         ?: selectedVersion.duration
+                    val playbackDuration = if (offlineMedia != null) {
+                        offlineMedia.sidecar.durationSeconds ?: selectedVersion.duration
+                    } else {
+                        wholeBookDuration
+                    }
...
-                            durationSeconds = wholeBookDuration,
+                            durationSeconds = playbackDuration,
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/AudiobookPlayerViewModel.kt`
around lines 291 - 318, The offline fallback is mixing file-local playback with
whole-book duration/position handling in AudiobookPlayerViewModel. In the state
update around wholeBookDuration/displayChapters, keep offlineMedia-null/nonnull
paths consistent by using the selected file’s local duration and chapter space
when offlineMedia is present, and only use builtTimeline.toWholeBookChapters()
plus whole-book duration for online playback. Also make sure the
onPositionChanged/timeline setup uses the same mode so downloaded multi-part
playback does not save a part-local position as the book position.
🧹 Nitpick comments (5)
android-shared/src/androidMain/kotlin/org/siloserver/silo/common/pip/SiloPictureInPictureCoordinator.kt (1)

126-128: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider using Activity parameter in buildParams to reuse supportsPictureInPicture() extension

buildParams is always called with an Activity but typed as Context, forcing an inline context.packageManager.hasSystemFeature(...) duplicate of the supportsPictureInPicture() extension at lines 123-124. Changing the parameter to Activity would eliminate the duplication.

♻️ Proposed refactor
 private fun buildParams(
-    context: Context,
+    activity: Activity,
     surface: SiloPictureInPictureSurface,
     state: SiloPictureInPicturePlaybackState,
 ): PictureInPictureParams {
     val builder = PictureInPictureParams.Builder()
         .setAspectRatio(aspectRatioFor(state))
-        .setActions(remoteActions(context, state.isPlaying))
+        .setActions(remoteActions(activity, state.isPlaying))
     val rect = state.sourceRectHint
     if (rect != null && !rect.isEmpty) {
         builder.setSourceRectHint(rect)
     }
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
         builder.setAutoEnterEnabled(
             siloCanEnterPictureInPicture(
                 surface = surface,
                 sdkInt = Build.VERSION.SDK_INT,
-                deviceSupportsPictureInPicture = context.packageManager
-                    .hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE),
+                deviceSupportsPictureInPicture = activity.supportsPictureInPicture(),
                 enabled = state.enabled,
                 videoActive = state.videoActive,
                 isPlaying = state.isPlaying,
             ),
         )
         builder.setSeamlessResizeEnabled(true)
     }
     return builder.build()
 }

Also applies to: 146-147

🤖 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/pip/SiloPictureInPictureCoordinator.kt`
around lines 126 - 128, The buildParams function is typed too broadly as Context
even though it is only called with an Activity, which causes a duplicated
picture-in-picture capability check instead of reusing
supportsPictureInPicture(). Update buildParams in
SiloPictureInPictureCoordinator to accept an Activity and call the existing
supportsPictureInPicture() extension from that type, then adjust the related
call sites so the parameter type matches and the duplicate packageManager
feature check can be removed.
androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvSubtitleSearchDialog.kt (1)

240-240: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

The provider-scoped download spinner logic is correct.

The two-condition isDownloading check properly scopes the spinner to the exact provider:id row the user clicked, and enabled = state.downloadingResultId == null prevents concurrent downloads. The LaunchedEffect clearing at line 130-132 correctly resets downloadingKey when the VM settles.

One optional nit: the key string "${result.provider}:${result.id}" is now constructed in three places (lines 240, 245, 248). A small local helper would prevent format drift.

♻️ Optional: extract key helper
@@ items(
     state.results,
     key = { "${it.provider}:${it.id}" },
 ) { result ->
+    val rowKey = "${result.provider}:${result.id}"
     TvSubtitleResultRow(
         result = result,
-        isDownloading = state.downloadingResultId != null &&
-            downloadingKey == "${result.provider}:${result.id}",
+        isDownloading = state.downloadingResultId != null &&
+            downloadingKey == rowKey,
         enabled = state.downloadingResultId == null,
         onClick = {
-            downloadingKey = "${result.provider}:${result.id}"
+            downloadingKey = rowKey
             onDownload(result)
         },
     )
 }

Also applies to: 244-250

🤖 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/player/TvSubtitleSearchDialog.kt`
at line 240, The provider:id key formatting is duplicated in
TvSubtitleSearchDialog across the item key and download-state checks, so extract
a small local helper or shared function for building that key. Update the
LazyColumn row key and the isDownloading/downloadingKey comparisons to use the
same helper so the provider-scoped spinner logic stays consistent and format
drift is avoided.
androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/ChaptersSheet.kt (1)

99-105: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Use PlayerSheetHeader for header consistency across player sheets.

Other sheets in this PR adopted PlayerSheetHeader. With onBack = null, it produces identical padding and text styling to this manual Text, so it's a drop-in replacement.

♻️ Proposed refactor
-            Text(
-                text = "Chapters",
-                color = Color.White,
-                fontSize = 18.sp,
-                fontWeight = FontWeight.Medium,
-                modifier = Modifier.padding(start = 20.dp, end = 20.dp, top = 20.dp, bottom = 8.dp),
-            )
+            PlayerSheetHeader(title = "Chapters")
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/ChaptersSheet.kt`
around lines 99 - 105, The chapter sheet header is still built with a manual
Text block instead of the shared PlayerSheetHeader used elsewhere in the player
sheets. Update ChaptersSheet to replace the inline header with
PlayerSheetHeader, using onBack = null so it preserves the same padding and text
styling while keeping header behavior consistent with the other sheet
components.
shared/src/commonMain/kotlin/org/siloserver/silo/audiobook/AudiobookTimeline.kt (1)

80-89: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

Consider removing redundant sort in trackIndexAt.

tracks.sortedBy { it.index } runs on every call, but buildAudiobookTimeline already produces tracks in index order. During playback this may be called frequently (per position update). For typical audiobook part counts the overhead is negligible, but the sort adds avoidable allocation and cognitive noise. If defensive sorting is desired, consider pre-sorting once in an init block or storing a sorted copy.

♻️ Optional: pre-sort once instead of per-call
 data class AudiobookTimeline(
     val tracks: List<AudioPlaybackTrack>,
     val chapters: List<AudioPlaybackChapter>,
     val totalSeconds: Double,
 ) {
+    private val sortedTracks: List<AudioPlaybackTrack> = tracks.sortedBy { it.index }
+
     /** True when the book is a single part (offset math is trivial). */
     val isSingle: Boolean get() = tracks.size <= 1
 
     fun trackIndexAt(globalTime: Double): Int {
-        if (tracks.isEmpty()) return 0
+        if (sortedTracks.isEmpty()) return 0
         val clamped = maxOf(0.0, globalTime)
-        for (track in tracks.sortedBy { it.index }) {
+        for (track in sortedTracks) {
             val start = track.startOffsetSeconds
             val end = start + maxOf(0.0, track.durationSeconds)
             if (clamped >= start && clamped < end) return track.index
         }
-        return tracks.last().index
+        return sortedTracks.last().index
     }
🤖 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/audiobook/AudiobookTimeline.kt`
around lines 80 - 89, trackIndexAt is doing a redundant per-call sort by using
tracks.sortedBy { it.index }, even though buildAudiobookTimeline already creates
tracks in index order. Remove the repeated sort and iterate tracks directly in
trackIndexAt, or if you want a defensive order guarantee, precompute a sorted
copy once in AudiobookTimeline instead of allocating on every playback update.
shared/src/commonTest/kotlin/org/siloserver/silo/player/DolbyVisionDetectionTest.kt (1)

12-16: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider adding a test for dolbyVisionProfile = 0.

Profile 0 is a valid Dolby Vision profile and the implementation correctly treats it as DV (!= null → true), but no test confirms this edge case. A one-line addition would prevent a future regression if someone changes the null check to > 0.

🧪 Suggested test addition
     assertTrue(DolbyVisionDetection.isDolbyVision(dolbyVisionProfile = 5))
     assertTrue(DolbyVisionDetection.isDolbyVision(dolbyVisionProfile = 8))
+    assertTrue(DolbyVisionDetection.isDolbyVision(dolbyVisionProfile = 0))
     assertFalse(DolbyVisionDetection.isDolbyVision(dolbyVisionProfile = 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
`@shared/src/commonTest/kotlin/org/siloserver/silo/player/DolbyVisionDetectionTest.kt`
around lines 12 - 16, Add coverage in DolbyVisionDetectionTest’s
structuredProfileIsAuthoritative test for the edge case where dolbyVisionProfile
is 0, since DolbyVisionDetection.isDolbyVision currently treats any non-null
profile as Dolby Vision. Extend the existing assertions in that test to include
profile 0 so the behavior is locked down and won’t regress if the null-based
check in DolbyVisionDetection changes to a numeric comparison.
🤖 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/player/AudiobookPlayerViewModel.kt`:
- Around line 664-670: The automatic transition in advanceAfterTrackEnd should
detect the next segment using TRACK_END_EPSILON, but loadTrack must start the
next part at its exact boundary instead of the offset. Update
advanceAfterTrackEnd (and the related flow at the other referenced site) so the
epsilon is only used in the track-end check, then pass the next track’s true
start time into loadTrack(atGlobalTime = ..., autoplay = true) when advancing
from AudioPlaybackTrack.
- Around line 414-436: The settle guard currently relies only on
pendingTrackLoadLocalStart, so a cross-part transition can be cleared by the old
stream before the new track is active. Update the guard in
AudiobookPlayerViewModel around the seek/load flow (the viewModelScope launch
that calls startPartSession and applies the session) to also record the target
track identity, such as fileId or a session/track token, and only settle when
both the time and the target track match. Make the same adjustment anywhere the
settle logic is duplicated so older parts cannot remap their time into the new
global position.
- Around line 605-644: loadTrack() still applies startTranscodeFallback()
results after suspension, so a newer seek/stop can let a stale session overwrite
streamUrl/sessionId and the failure branches can leave the newly started session
running. Re-check loadGeneration immediately after startTranscodeFallback()
returns and before updating _uiState or applying any started session data, and
if the generation changed then discard the result and stop/cancel that session.
Make the same guard cover the ApiResult.Success, ApiResult.Error, and
ApiResult.NetworkError paths in AudiobookPlayerViewModel.

In
`@androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/browse/BrowseScreen.kt`:
- Around line 252-257: The card subtitle logic in BrowseScreen’s cardSubtitle
when-block is checking the wrong sort key, so the Release Year branch never
runs. Update the sort-field comparison to match the value used by
browseSortOptions for Release Year (the "year" option) and keep the added_at
branch unchanged so the correct subtitle formatter is selected for each sort.

In
`@androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/detail/ItemDetailScreen.kt`:
- Around line 595-616: The auto-preview path in ItemDetailScreen is resolving
the display version with selectPlaybackVersion(), but the forced playback/cast
file still comes from playbackFileId based on the earlier selection, which can
desync track overrides. Update the track-override flow to derive the forced
fileId from the same resolved auto version (or a single shared resolved
version/file helper) so playback, cast, and the audio/subtitle selection all use
the same file. Apply this consistently in the logic around selectedVersion,
playbackFileId, and the related track override branches in ItemDetailScreen.

In
`@androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/AiTranslateSheet.kt`:
- Around line 120-123: `AiTranslateSheet` is passing `onBack` straight into
`PlayerSheetHeader`, which skips the sheet hide animation on dismiss. Update the
`PlayerSheetHeader` callback in `AiTranslateSheet` to first call
`sheetState.hide()` and then invoke `onBack`, matching the pattern used by
`PlaybackStatsSheet` so the back chevron triggers a consistent animated
dismissal.

In
`@androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/SubtitleSearchSheet.kt`:
- Around line 81-92: SubtitleSearchSheet is calling onBack/onDismiss directly
without hiding the bottom sheet first, so it skips the same exit animation used
by sibling sheets. In SubtitleSearchSheet, extract the sheetState and scope like
SleepTimerSheet and SubtitleStyleSheet, then wrap the PlayerSheetHeader back
action and the LaunchedEffect(tools.downloadCompleted) completion path so they
call sheetState.hide() before invoking onBack or onDismiss. Use the existing
SubtitleSearchSheet, PlayerSheetHeader, and
LaunchedEffect(tools.downloadCompleted) symbols to update both back-navigation
paths consistently.

In
`@androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/profiles/ProfileSelectionScreen.kt`:
- Line 160: The modifier chain in ProfileSelectionScreen is applying
statusBarsPadding() to the scrollable content, so the top inset scrolls away
with the list. Update the composable chain around the main container so
statusBarsPadding() is applied before verticalScroll() (or otherwise outside the
scroll viewport) in the ProfileSelectionScreen UI, keeping the status-bar inset
pinned while the profile list scrolls.

In
`@androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/data/preferences/TvLibrarySelectionStore.kt`:
- Around line 107-113: The new per-server selected library key in
TvLibrarySelectionStore is orphaning values previously saved under the old fixed
key, so add a one-time migration path in getSelectedLibraryId: first check the
new selectedLibraryKey(serverId), and if it is absent, read the legacy
intPreferencesKey("selected_library") and persist that value into the
appropriate current key (such as selected_library_default) before returning it.
Add a legacy key constant in the companion object alongside DEFAULT_SERVER_ID,
and keep the fallback logic localized to the existing selected library
read/write flow so existing users retain their remembered tab selection.

In
`@androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/navigation/TvAppNavigation.kt`:
- Around line 387-405: The TV sign-out flows are inconsistent: this callback
performs the full teardown, but the ProfileSelection sign-out path still only
does authRepository.logout() and watchNextSeeder.clear(). Extract the shared
logout teardown from TvAppNavigation into a reusable helper and invoke it from
both sign-out entry points so credentials, profile state, prefs, and Watch Next
are always cleared before navigating to TvRoute.ServerSetup.
- Around line 60-69: The pre-auth route set is missing the pairing screen route,
so content deep links are being treated as stale while PairDevice is active.
Update preMainAuthRoutes in TvAppNavigation to include TvRoute.PairDevice.ROUTE,
so the deep-link handling logic in the navigation flow preserves and replays
queued content after pairing instead of clearing it.

In
`@androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/detail/TvAudiobookDetailHero.kt`:
- Around line 60-61: The hero detail state in TvAudiobookDetailHero is letting a
stale resumePosition override a finished book, so a title marked played can
still surface “Resume” and start mid-book. Update the logic around
audiobookResumePositionSeconds, audiobookIsFinished, and the UI/action selection
so that isFinished takes precedence and suppresses any resume position whenever
the book is finished or marked played; apply the same precedence in the other
duplicated spots mentioned in this component.

In
`@androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/detail/TvPlaybackFormatting.kt`:
- Around line 373-376: The bitmap subtitle detector in isBitmapSubtitle should
actually cover the VobSub and DVB variants it claims to mirror. Update the token
checks in TvPlaybackFormatting so that common strings like vobsub, dvb_subtitle,
and dvb-subtitle are recognized in addition to the existing pgs/hdmv/dvd/dvbsubs
cases, using the same normalization logic already applied in this helper.

In
`@androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvPlayerViewModel.kt`:
- Around line 1248-1258: The selectedSubtitleTrackIndex function is treating an
unloaded or empty subtitle track list as “Off” by returning -1 too early. Update
the logic in selectedSubtitleTrackIndex so that it only returns -1 when subtitle
tracks are known and none is selected, and returns null/keeps current when
state.subtitleTracks is not yet populated. Keep the existing match against
state.subtitleUrls for selected mounted subtitles, but avoid sending an explicit
Off value before the tracks have loaded.

In
`@androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/search/TvSearchViewModel.kt`:
- Around line 217-220: Clear the stale paging state in TvSearchViewModel when a
reset search fails, not only on ApiResult.Success. Update the search result
handling around the result when/reset path so a failed reset also invalidates
the prior generation and clears or reinitializes items, hasMore, and
rawResultCount for the new query; this ensures loadMore() does not see stale
state and immediately drop the request. Use the existing resultsGeneration,
loadMore(), and the result-handling branch in the search flow to locate the fix.

In
`@androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt`:
- Around line 217-225: The async reread in TvMainShell’s LaunchedEffect updates
showAudiobooksTab but never clears showAudiobooksTabResolved first, so later
route changes can bypass the redirect gate. Reset showAudiobooksTabResolved to
false before starting each getShowAudiobooksTab() read, then set it back to true
after the value is loaded so the main/audiobooks redirect only runs once the
latest store value has arrived.

In
`@androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/detail/TvPlaybackFormattingTest.kt`:
- Around line 106-224: The added test function names in TvPlaybackFormattingTest
use underscores instead of Kotlin camelCase. Rename each new `@Test` method to
camelCase, such as subtitleValueLabelAutoWithoutContextIsBare and the other
subtitleValueLabel/resolvedAudioLanguage tests, keeping the same test behavior
while aligning with the function naming guideline.

---

Outside diff comments:
In
`@android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/AudiobookPlayerViewModel.kt`:
- Around line 291-318: The offline fallback is mixing file-local playback with
whole-book duration/position handling in AudiobookPlayerViewModel. In the state
update around wholeBookDuration/displayChapters, keep offlineMedia-null/nonnull
paths consistent by using the selected file’s local duration and chapter space
when offlineMedia is present, and only use builtTimeline.toWholeBookChapters()
plus whole-book duration for online playback. Also make sure the
onPositionChanged/timeline setup uses the same mode so downloaded multi-part
playback does not save a part-local position as the book position.

In
`@androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvPlayerViewModel.kt`:
- Around line 878-882: The fresh-load reset in TvPlayerViewModel.loadContent
should also clear the session-scoped auto-subtitle latch, since
autoTextSubtitleSelectionAttempted can incorrectly persist across
retry/version-switch/fallback restarts and block auto subtitle resolution on new
tracks. Update the existing reset block alongside
introAutoSkipController.reset(), manualSubtitleSelectionApplied,
attemptedEngines, and engineSwitchFailureEngines so
autoTextSubtitleSelectionAttempted is reset for each fresh content mount; apply
the same change in the other load/restart path referenced by the duplicate
block.

---

Nitpick comments:
In
`@android-shared/src/androidMain/kotlin/org/siloserver/silo/common/pip/SiloPictureInPictureCoordinator.kt`:
- Around line 126-128: The buildParams function is typed too broadly as Context
even though it is only called with an Activity, which causes a duplicated
picture-in-picture capability check instead of reusing
supportsPictureInPicture(). Update buildParams in
SiloPictureInPictureCoordinator to accept an Activity and call the existing
supportsPictureInPicture() extension from that type, then adjust the related
call sites so the parameter type matches and the duplicate packageManager
feature check can be removed.

In
`@androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/ChaptersSheet.kt`:
- Around line 99-105: The chapter sheet header is still built with a manual Text
block instead of the shared PlayerSheetHeader used elsewhere in the player
sheets. Update ChaptersSheet to replace the inline header with
PlayerSheetHeader, using onBack = null so it preserves the same padding and text
styling while keeping header behavior consistent with the other sheet
components.

In
`@androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvSubtitleSearchDialog.kt`:
- Line 240: The provider:id key formatting is duplicated in
TvSubtitleSearchDialog across the item key and download-state checks, so extract
a small local helper or shared function for building that key. Update the
LazyColumn row key and the isDownloading/downloadingKey comparisons to use the
same helper so the provider-scoped spinner logic stays consistent and format
drift is avoided.

In
`@shared/src/commonMain/kotlin/org/siloserver/silo/audiobook/AudiobookTimeline.kt`:
- Around line 80-89: trackIndexAt is doing a redundant per-call sort by using
tracks.sortedBy { it.index }, even though buildAudiobookTimeline already creates
tracks in index order. Remove the repeated sort and iterate tracks directly in
trackIndexAt, or if you want a defensive order guarantee, precompute a sorted
copy once in AudiobookTimeline instead of allocating on every playback update.

In
`@shared/src/commonTest/kotlin/org/siloserver/silo/player/DolbyVisionDetectionTest.kt`:
- Around line 12-16: Add coverage in DolbyVisionDetectionTest’s
structuredProfileIsAuthoritative test for the edge case where dolbyVisionProfile
is 0, since DolbyVisionDetection.isDolbyVision currently treats any non-null
profile as Dolby Vision. Extend the existing assertions in that test to include
profile 0 so the behavior is locked down and won’t regress if the null-based
check in DolbyVisionDetection changes to a numeric comparison.
🪄 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: de897478-7786-4558-ae2e-d08f16b899b3

📥 Commits

Reviewing files that changed from the base of the PR and between 3fecf74 and 246803d.

📒 Files selected for processing (124)
  • .gitignore
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/pip/SiloPictureInPictureCoordinator.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/AudiobookPlayerViewModel.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/PlaybackSessionManager.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SiloPlayerFactory.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SleepTimerChoice.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/SubtitleManager.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/backend/PlaybackEngineDecision.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/backend/VideoPlaybackBackendRequest.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/backend/VideoPlaybackBackendSelector.kt
  • android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/video/OriginalPlaybackRequestPolicy.kt
  • android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/AudiobookPlayerSleepWatcherTest.kt
  • android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/PlaybackSessionLifecycleTest.kt
  • android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/SubtitleManagerAppearanceTest.kt
  • android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/backend/PlaybackEngineDecisionTest.kt
  • android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/backend/VideoPlaybackBackendSelectorTest.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/di/AndroidModule.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/components/BackdropCard.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/components/MediaCard.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/components/MediaRow.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/navigation/AppNavigation.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/navigation/Routes.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/navigation/SharedElementTransition.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/MainScreen.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/audiobook/AudiobookDetailContent.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/audiobook/AudiobookSleepTimerSheet.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/auth/LoginScreen.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/browse/BrowseScreen.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/browse/CatalogGrid.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/browse/FilterSheet.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/calendar/CalendarScreen.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/detail/DetailSharedComponents.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/detail/EpisodeList.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/detail/ItemDetailScreen.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/detail/ItemDetailViewModel.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/detail/MediaInfoSheet.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/detail/MediaSelectors.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/detail/MovieDetailContent.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/detail/SeriesDetailContent.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/detail/SimilarRail.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/home/HomeSectionItemsScreen.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/home/HomeSectionRow.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/people/PersonDetailScreen.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/AiTranslateSheet.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/ChaptersSheet.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/MobileSubtitleAutoSelection.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/PlaybackStatsSheet.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerControls.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerGestureHandler.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerOverlay.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerScreen.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerSettingsSheet.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerSheetSupport.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerViewModel.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/QualitySelector.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/SleepTimerSheet.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/SubtitleSearchSheet.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/SubtitleStyleSheet.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/player/TracksSheet.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/profiles/ProfileSelectionScreen.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/recommendations/RecommendationsScreen.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/util/Formatters.kt
  • androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/performance/MobileDetailOpenPerformanceSourceTest.kt
  • androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/detail/EpisodeSpoilerBlurSourceTest.kt
  • androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/detail/MobileReadingAudioDetailParitySourceTest.kt
  • androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/player/MobileSubtitleAutoSelectionTest.kt
  • androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/player/PlayerPinchGravitySourceTest.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/MainTvActivity.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/cast/TvSiloCastReceiver.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/data/preferences/TvLibrarySelectionStore.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/di/AndroidTvModule.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/components/TvCatalogGrid.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/admin/TvAdminSessionsScreen.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/audiobook/TvAudiobookPlayerScreen.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/audiobook/TvAudiobookSleepPanel.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/calendar/TvCalendarScreen.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/detail/TvAudiobookDetailHero.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/detail/TvPlaybackFormatting.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/detail/TvPlaybackSelectorRow.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/library/TvLibraryDetailViewModel.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/notifications/TvInboxScreen.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/people/TvPersonDetailViewModel.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/personal/TvPersonalScreens.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvPlayerHud.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvPlayerScreen.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvPlayerScrubber.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvPlayerViewModel.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/player/TvSubtitleSearchDialog.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/profiles/TvCreateProfileViewModel.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/profiles/TvEditProfileViewModel.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/profiles/TvProfileForm.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/requests/TvRequestsScreen.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/requests/TvRequestsViewModel.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/search/TvSearchViewModel.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/servers/TvServerListScreen.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/servers/TvServerListViewModel.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/settings/TvSettingsViewModel.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/watchnext/WatchNextProgramMapper.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/watchnext/WatchNextRepository.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/watchnext/WatchNextSeeder.kt
  • androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/watchnext/WatchNextSyncWorker.kt
  • androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/audiobook/TvAudiobookSleepPanelSourceTest.kt
  • androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/detail/TvAudiobookDetailHeroParitySourceTest.kt
  • androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/detail/TvPlaybackFormattingTest.kt
  • androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/watchnext/WatchNextProgramMapperTest.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/audiobook/AudiobookTimeline.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/model/catalog/CatalogModels.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/model/playback/PlaybackModels.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/playback/TrackSelectionFingerprint.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/player/DolbyVisionDetection.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/repository/PlaybackRepository.kt
  • shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/CalendarViewModel.kt
  • shared/src/commonTest/kotlin/org/siloserver/silo/audiobook/AudiobookTimelineTest.kt
  • shared/src/commonTest/kotlin/org/siloserver/silo/playback/TrackSelectionFingerprintTest.kt
  • shared/src/commonTest/kotlin/org/siloserver/silo/player/DolbyVisionDetectionTest.kt
💤 Files with no reviewable changes (6)
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/home/HomeSectionItemsScreen.kt
  • androidApp/src/androidUnitTest/kotlin/org/siloserver/silo/android/ui/screens/detail/EpisodeSpoilerBlurSourceTest.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/MainScreen.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/detail/MediaInfoSheet.kt
  • android-shared/src/androidUnitTest/kotlin/org/siloserver/silo/common/player/AudiobookPlayerSleepWatcherTest.kt
  • androidApp/src/androidMain/kotlin/org/siloserver/silo/android/di/AndroidModule.kt

Comment on lines +414 to +436
pendingTrackLoadLocalStart = localTime
_uiState.update { it.copy(positionSeconds = clamped) }
if (autoplay) _uiState.update { it.copy(isPaused = false) }

val generation = ++loadGeneration
viewModelScope.launch {
val profileId = profileRepository.getActiveProfileId()
if (profileId == null) {
_uiState.update { it.copy(error = "No active profile") }
return@launch
}
retireActiveSession()
when (val playback = startPartSession(track.fileId, profileId, localTime)) {
is ApiResult.Success -> {
if (generation != loadGeneration || isClosing) {
// Superseded by a newer seek/advance or a close while the
// request was in flight — release the session we no
// longer need (Apple parity).
runCatching { playbackSessionManager.stopSession(playback.data.sessionId) }
return@launch
}
applyStartedSession(
session = playback.data,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Tie the settle guard to the target track.

pendingTrackLoadLocalStart only stores a local timestamp. During a cross-part load, the outgoing stream can report a time within the 3s tolerance of the target local time and clear the guard before the new track is active, allowing old part time to be remapped as the new global position.

Proposed fix
-    private var pendingTrackLoadLocalStart: Double? = null
+    private data class PendingTrackLoad(val trackIndex: Int, val localStart: Double)
+    private var pendingTrackLoad: PendingTrackLoad? = null
...
-        pendingTrackLoadLocalStart = localTime
+        pendingTrackLoad = PendingTrackLoad(index, localTime)
...
-        val awaiting = pendingTrackLoadLocalStart
+        val awaiting = pendingTrackLoad
         if (awaiting != null) {
-            if (abs(seconds - awaiting) <= TRACK_LOAD_SETTLE_TOLERANCE) {
-                pendingTrackLoadLocalStart = null
+            if (
+                activeTrackIndex == awaiting.trackIndex &&
+                abs(seconds - awaiting.localStart) <= TRACK_LOAD_SETTLE_TOLERANCE
+            ) {
+                pendingTrackLoad = null
             } else {
                 return
             }
         }

Also applies to: 730-736

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/AudiobookPlayerViewModel.kt`
around lines 414 - 436, The settle guard currently relies only on
pendingTrackLoadLocalStart, so a cross-part transition can be cleared by the old
stream before the new track is active. Update the guard in
AudiobookPlayerViewModel around the seek/load flow (the viewModelScope launch
that calls startPartSession and applies the session) to also record the target
track identity, such as fileId or a session/track token, and only settle when
both the time and the target track match. Make the same adjustment anywhere the
settle logic is duplicated so older parts cannot remap their time into the new
global position.

Comment on lines +664 to +670
private fun advanceAfterTrackEnd(active: AudioPlaybackTrack) {
val tl = timeline ?: return
val nextStart = active.startOffsetSeconds + active.durationSeconds + TRACK_END_EPSILON
val total = _uiState.value.durationSeconds
if (tl.trackIndexAt(nextStart) != active.index && nextStart < total) {
loadTrack(atGlobalTime = nextStart, autoplay = true)
} else {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Start the next part at its boundary.

Line 666 adds TRACK_END_EPSILON to the value passed into loadTrack(), so automatic transitions seek about 250ms into each next part. Use the epsilon only for detection/probing, then load the next track’s exact start.

Proposed fix direction
-        val nextStart = active.startOffsetSeconds + active.durationSeconds + TRACK_END_EPSILON
+        val currentEnd = active.startOffsetSeconds + active.durationSeconds
+        val nextTrack = tl.tracks.firstOrNull { it.index == active.index + 1 }
         val total = _uiState.value.durationSeconds
-        if (tl.trackIndexAt(nextStart) != active.index && nextStart < total) {
-            loadTrack(atGlobalTime = nextStart, autoplay = true)
+        if (nextTrack != null && nextTrack.startOffsetSeconds < total) {
+            loadTrack(atGlobalTime = nextTrack.startOffsetSeconds, autoplay = true)

Also applies to: 1178-1186

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@android-shared/src/androidMain/kotlin/org/siloserver/silo/common/player/AudiobookPlayerViewModel.kt`
around lines 664 - 670, The automatic transition in advanceAfterTrackEnd should
detect the next segment using TRACK_END_EPSILON, but loadTrack must start the
next part at its exact boundary instead of the offset. Update
advanceAfterTrackEnd (and the related flow at the other referenced site) so the
epsilon is only used in the track-end check, then pass the next track’s true
start time into loadTrack(atGlobalTime = ..., autoplay = true) when advancing
from AudioPlaybackTrack.

Comment on lines +252 to +257
// Date sorts surface the sorted-by date under each card.
cardSubtitle = when (state.filterState.sort) {
"added_at" -> { item -> formatCardDate(item.addedAt) }
"release_date" -> { item -> formatCardDate(item.releaseDate) }
else -> null
},

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Sort field mismatch: "release_date" doesn't match any available sort option.

browseSortOptions (line 292) defines the Release Year sort field as "year", not "release_date". The cardSubtitle when-block checks for "release_date", which never matches, so the release date subtitle won't appear when sorting by Release Year. The "release_date" branch is dead code.

🐛 Proposed fix: align sort field name
                     cardSubtitle = when (state.filterState.sort) {
                         "added_at" -> { item -> formatCardDate(item.addedAt) }
-                        "release_date" -> { item -> formatCardDate(item.releaseDate) }
+                        "year" -> { item -> formatCardDate(item.releaseDate) }
                         else -> null
                     },
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Date sorts surface the sorted-by date under each card.
cardSubtitle = when (state.filterState.sort) {
"added_at" -> { item -> formatCardDate(item.addedAt) }
"release_date" -> { item -> formatCardDate(item.releaseDate) }
else -> null
},
// Date sorts surface the sorted-by date under each card.
cardSubtitle = when (state.filterState.sort) {
"added_at" -> { item -> formatCardDate(item.addedAt) }
"year" -> { item -> formatCardDate(item.releaseDate) }
else -> null
},
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/browse/BrowseScreen.kt`
around lines 252 - 257, The card subtitle logic in BrowseScreen’s cardSubtitle
when-block is checking the wrong sort key, so the Release Year branch never
runs. Update the sort-field comparison to match the value used by
browseSortOptions for Release Year (the "year" option) and keep the added_at
branch unchanged so the correct subtitle formatter is selected for each sort.

Comment on lines +595 to +616
// Auto preview must resolve through the SAME shared
// selector as playback (lastFileId → preferred-quality
// rank → bestAvailable), not just lastFileId-else-[0] —
// otherwise the previewed version (and the audio/subtitle
// lists derived from it) can describe a file playback
// won't use. An explicit user pick still wins. TV parity:
// selectTvDetailDisplayVersion does the same.
val videoDisplayVersionIndex = if (
state.hasExplicitVersionSelection || detail.versions.isEmpty()
) {
effectiveSelectedVersionIndex
} else {
val resolvedFileId = selectPlaybackVersion(
detail.versions,
detail.userData?.lastFileId,
preferredQuality,
).fileId
detail.versions.indexOfFirst { it.fileId == resolvedFileId }
.takeIf { it >= 0 }
?: effectiveSelectedVersionIndex
}
val selectedVersion = detail.versions.getOrNull(videoDisplayVersionIndex)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Use the resolved auto version when forcing a file for track overrides.

Line 607 previews Auto through selectPlaybackVersion(...), but playback/cast still use playbackFileId, derived earlier from effectiveSelectedVersionIndex. In Auto + explicit audio/subtitle mode, the UI can select tracks from one file while playback forces a different fileId.

Proposed fix
                         val selectedVersion = detail.versions.getOrNull(videoDisplayVersionIndex)
+                        val videoPlaybackFileId = explicitFileId ?: selectedVersion
+                            ?.fileId
+                            ?.takeIf { state.hasExplicitAudioSelection || state.hasExplicitSubtitleSelection }
                         val selectedLocalDownload = selectedVersion?.let { version ->
                             localDownloadFor(version.fileId)
                         }
@@
                                     detail.contentId,
-                                    playbackFileId,
+                                    videoPlaybackFileId,
                                     explicitAudioIndex,
                                     explicitSubtitleIndex,
                                     playbackResumePosition(detail.userData),
@@
                                     contentId = detail.contentId,
                                     title = detail.title,
-                                    fileId = playbackFileId,
+                                    fileId = videoPlaybackFileId,
                                     audioTrackIndex = explicitAudioIndex,
                                     subtitleTrackIndex = explicitSubtitleIndex,

Also applies to: 631-642, 726-733

🤖 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/detail/ItemDetailScreen.kt`
around lines 595 - 616, The auto-preview path in ItemDetailScreen is resolving
the display version with selectPlaybackVersion(), but the forced playback/cast
file still comes from playbackFileId based on the earlier selection, which can
desync track overrides. Update the track-override flow to derive the forced
fileId from the same resolved auto version (or a single shared resolved
version/file helper) so playback, cast, and the audio/subtitle selection all use
the same file. Apply this consistently in the logic around selectedVersion,
playbackFileId, and the related track override branches in ItemDetailScreen.

Comment on lines 217 to +220
when (result) {
is ApiResult.Success -> {
// The results now belong to this generation; load-more may page.
if (reset) resultsGeneration = generation

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Clear stale paging state when a reset search fails.

resultsGeneration is stamped only on reset success, so a failed reset can leave prior items/hasMore/rawResultCount under the new query. Then loadMore() passes hasMore but immediately drops as stale, leaving a no-op pager.

Proposed fix
+        fun UiState.withSearchFailure(message: String): UiState =
+            if (reset) {
+                copy(
+                    isLoading = false,
+                    isLoadingMore = false,
+                    items = emptyList(),
+                    total = 0,
+                    hasMore = false,
+                    rawResultCount = 0,
+                    error = message,
+                )
+            } else {
+                copy(
+                    isLoading = false,
+                    isLoadingMore = false,
+                    error = message,
+                )
+            }
+
         when (result) {
             is ApiResult.Success -> {
                 // The results now belong to this generation; load-more may page.
                 if (reset) resultsGeneration = generation
@@
-            is ApiResult.Error -> _uiState.update {
-                it.copy(
-                    isLoading = false,
-                    isLoadingMore = false,
-                    error = result.message.ifBlank { "Search failed" },
-                )
-            }
-            is ApiResult.NetworkError -> _uiState.update {
-                it.copy(
-                    isLoading = false,
-                    isLoadingMore = false,
-                    error = "Network error: ${result.exception.message ?: "unknown"}",
-                )
-            }
+            is ApiResult.Error -> _uiState.update {
+                it.withSearchFailure(result.message.ifBlank { "Search failed" })
+            }
+            is ApiResult.NetworkError -> _uiState.update {
+                it.withSearchFailure("Network error: ${result.exception.message ?: "unknown"}")
+            }
         }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
when (result) {
is ApiResult.Success -> {
// The results now belong to this generation; load-more may page.
if (reset) resultsGeneration = generation
fun UiState.withSearchFailure(message: String): UiState =
if (reset) {
copy(
isLoading = false,
isLoadingMore = false,
items = emptyList(),
total = 0,
hasMore = false,
rawResultCount = 0,
error = message,
)
} else {
copy(
isLoading = false,
isLoadingMore = false,
error = message,
)
}
when (result) {
is ApiResult.Success -> {
// The results now belong to this generation; load-more may page.
if (reset) resultsGeneration = generation
is ApiResult.Error -> _uiState.update {
it.withSearchFailure(result.message.ifBlank { "Search failed" })
}
is ApiResult.NetworkError -> _uiState.update {
it.withSearchFailure("Network error: ${result.exception.message ?: "unknown"}")
}
}
🤖 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 217 - 220, Clear the stale paging state in TvSearchViewModel when a
reset search fails, not only on ApiResult.Success. Update the search result
handling around the result when/reset path so a failed reset also invalidates
the prior generation and clears or reinitializes items, hasMore, and
rawResultCount for the new query; this ensures loadMore() does not see stale
state and immediately drop the request. Use the existing resultsGeneration,
loadMore(), and the result-handling branch in the search flow to locate the fix.

Comment on lines +217 to +225
var showAudiobooksTabResolved by remember { mutableStateOf(false) }
// The store exposes no Flow and Settings is an in-shell NavHost route (so no
// ON_RESUME fires when the user backs out of it), which is why a one-shot
// read left the tab bar stale after toggling the setting. Re-read on every
// shell route change — a cheap DataStore lookup — so toggling Settings >
// "Show Audiobooks tab" takes effect on return, without recreating the shell.
LaunchedEffect(libraries, currentEntry?.destination?.route) {
showAudiobooksTab = runCatching { tvLibraryScopeStore.getShowAudiobooksTab() }.getOrDefault(false)
showAudiobooksTabResolved = true

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Reset showAudiobooksTabResolved before each async reread.

After the first read, this flag remains true, so later route-change rereads no longer gate the redirect at Lines 526-533. A stale showAudiobooksTab=false can still eject main/audiobooks before the new DataStore value lands.

Proposed fix
 LaunchedEffect(libraries, currentEntry?.destination?.route) {
+    showAudiobooksTabResolved = false
     showAudiobooksTab = runCatching { tvLibraryScopeStore.getShowAudiobooksTab() }.getOrDefault(false)
     showAudiobooksTabResolved = true
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
var showAudiobooksTabResolved by remember { mutableStateOf(false) }
// The store exposes no Flow and Settings is an in-shell NavHost route (so no
// ON_RESUME fires when the user backs out of it), which is why a one-shot
// read left the tab bar stale after toggling the setting. Re-read on every
// shell route change — a cheap DataStore lookup — so toggling Settings >
// "Show Audiobooks tab" takes effect on return, without recreating the shell.
LaunchedEffect(libraries, currentEntry?.destination?.route) {
showAudiobooksTab = runCatching { tvLibraryScopeStore.getShowAudiobooksTab() }.getOrDefault(false)
showAudiobooksTabResolved = true
var showAudiobooksTabResolved by remember { mutableStateOf(false) }
// The store exposes no Flow and Settings is an in-shell NavHost route (so no
// ON_RESUME fires when the user backs out of it), which is why a one-shot
// read left the tab bar stale after toggling the setting. Re-read on every
// shell route change — a cheap DataStore lookup — so toggling Settings >
// "Show Audiobooks tab" takes effect on return, without recreating the shell.
LaunchedEffect(libraries, currentEntry?.destination?.route) {
showAudiobooksTabResolved = false
showAudiobooksTab = runCatching { tvLibraryScopeStore.getShowAudiobooksTab() }.getOrDefault(false)
showAudiobooksTabResolved = true
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt`
around lines 217 - 225, The async reread in TvMainShell’s LaunchedEffect updates
showAudiobooksTab but never clears showAudiobooksTabResolved first, so later
route changes can bypass the redirect gate. Reset showAudiobooksTabResolved to
false before starting each getShowAudiobooksTab() read, then set it back to true
after the value is loaded so the main/audiobooks redirect only runs once the
latest store value has arrived.

Comment on lines +106 to +224
@Test fun subtitleValueLabel_autoWithoutContextIsBare() {
// No resolution inputs (no autoContext): we can't preview the pick, so
// show a bare "Auto" rather than guessing from isDefault (which the
// player's resolver never consults) — QA 2026-07-09 / tvOS parity.
val v = fileVersion(subtitles = listOf(subtitleTrack(lang = "eng"), subtitleTrack(lang = "fre")))
assertEquals("Auto", TvPlaybackFormatting.subtitleValueLabel(v, selectedSubtitleTrackIndex = null))
}

@Test fun subtitleValueLabel_autoWithoutContextSingleTrackShowsTrack() {
val v = fileVersion(subtitles = listOf(subtitleTrack(lang = "eng")))
assertEquals("English", TvPlaybackFormatting.subtitleValueLabel(v, selectedSubtitleTrackIndex = null))
}

// --- Auto preview resolved through the REAL selection rules (tvOS parity) ---

@Test fun subtitleValueLabel_autoResolvesPreferredLanguage() {
// preferred=fr, audio=en → readable French subs auto-selected.
val v = fileVersion(
subtitles = listOf(
subtitleTrack(lang = "eng"),
subtitleTrack(lang = "fre"),
),
)
val ctx = TvPlaybackFormatting.SubtitleAutoContext(
preferredLanguage = "fr",
mode = "auto",
audioLanguage = "eng",
)
assertEquals("Auto - French", TvPlaybackFormatting.subtitleValueLabel(v, null, ctx))
}

@Test fun subtitleValueLabel_autoNoneWhenAudioMatchesPreferred() {
// auto mode hides subs when audio is already in the preferred language.
val v = fileVersion(subtitles = listOf(subtitleTrack(lang = "eng")))
val ctx = TvPlaybackFormatting.SubtitleAutoContext(
preferredLanguage = "en",
mode = "auto",
audioLanguage = "eng",
)
assertEquals("Auto - None", TvPlaybackFormatting.subtitleValueLabel(v, null, ctx))
}

@Test fun subtitleValueLabel_autoForcedWhenAudioMatchesAndShowForced() {
// audio matches preferred + showForced → the language-matching forced
// (signs-only) track is exactly what plays.
val v = fileVersion(
subtitles = listOf(
subtitleTrack(lang = "eng"),
subtitleTrack(lang = "eng", forced = true),
),
)
val ctx = TvPlaybackFormatting.SubtitleAutoContext(
preferredLanguage = "en",
mode = "auto",
showForced = true,
audioLanguage = "eng",
)
assertEquals("Auto - Forced - English", TvPlaybackFormatting.subtitleValueLabel(v, null, ctx))
}

@Test fun subtitleValueLabel_autoNoneWhenModeOff() {
val v = fileVersion(subtitles = listOf(subtitleTrack(lang = "eng")))
val ctx = TvPlaybackFormatting.SubtitleAutoContext(preferredLanguage = "en", mode = "off")
assertEquals("Auto - None", TvPlaybackFormatting.subtitleValueLabel(v, null, ctx))
}

@Test fun subtitleValueLabel_autoNoneWhenPreferenceIsNoSubs() {
// Empty (not null) preferred language means "no subs" at this level.
val v = fileVersion(subtitles = listOf(subtitleTrack(lang = "eng")))
val ctx = TvPlaybackFormatting.SubtitleAutoContext(preferredLanguage = "", mode = "auto")
assertEquals("Auto - None", TvPlaybackFormatting.subtitleValueLabel(v, null, ctx))
}

@Test fun subtitleValueLabel_autoNoneWhenNoPreferenceAndModeAuto() {
// No language preference + plain auto → resolver leaves subs off.
val v = fileVersion(subtitles = listOf(subtitleTrack(lang = "eng")))
val ctx = TvPlaybackFormatting.SubtitleAutoContext(preferredLanguage = null, mode = "auto")
assertEquals("Auto - None", TvPlaybackFormatting.subtitleValueLabel(v, null, ctx))
}

@Test fun subtitleValueLabel_autoAlwaysPicksFullDialogueWithNoPreference() {
// mode=always with no language pref falls back to the best track,
// preferring full-dialogue (non-forced, non-SDH) over the forced one.
val v = fileVersion(
subtitles = listOf(
subtitleTrack(lang = "fre", forced = true),
subtitleTrack(lang = "fre"),
),
)
val ctx = TvPlaybackFormatting.SubtitleAutoContext(preferredLanguage = null, mode = "always")
assertEquals("Auto - French", TvPlaybackFormatting.subtitleValueLabel(v, null, ctx))
}

@Test fun subtitleValueLabel_autoPrefersFullDialogueOverSdh() {
// With a language match, SDH is skipped in favour of the readable track.
val v = fileVersion(
subtitles = listOf(
subtitleTrack(lang = "eng", title = "English SDH"),
subtitleTrack(lang = "eng"),
),
)
val ctx = TvPlaybackFormatting.SubtitleAutoContext(
preferredLanguage = "en",
mode = "auto",
audioLanguage = "jpn",
)
assertEquals("Auto - English", TvPlaybackFormatting.subtitleValueLabel(v, null, ctx))
}

@Test fun resolvedAudioLanguage_returnsAutoTrackLanguage() {
val v = fileVersion(
audio = listOf(
audioTrack(codec = "aac", lang = "jpn"),
audioTrack(codec = "eac3", lang = "eng", default = true),
),
)
// Auto resolves to the default track → its language.
assertEquals("eng", TvPlaybackFormatting.resolvedAudioLanguage(v, selectedAudioTrackIndex = null))
assertEquals("jpn", TvPlaybackFormatting.resolvedAudioLanguage(v, selectedAudioTrackIndex = 0))

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

Rename the new test functions to camelCase.

The added test names use underscores; please rename them to camelCase, e.g. subtitleValueLabelAutoWithoutContextIsBare. As per coding guidelines, “Kotlin classes and composables must use PascalCase; functions and properties must use camelCase.” <coding_guidelines>

🤖 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/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/detail/TvPlaybackFormattingTest.kt`
around lines 106 - 224, The added test function names in
TvPlaybackFormattingTest use underscores instead of Kotlin camelCase. Rename
each new `@Test` method to camelCase, such as
subtitleValueLabelAutoWithoutContextIsBare and the other
subtitleValueLabel/resolvedAudioLanguage tests, keeping the same test behavior
while aligning with the function naming guideline.

Source: Coding guidelines

RXWatcher and others added 6 commits July 9, 2026 20:53
…y loops

Review follow-up on the TV player fixes:
- onCleared blocked the main thread in runBlocking around two network calls
  (30-60s timeouts) — a hard ANR on slow-network teardown. The session stop now
  runs fire-and-forget on the lifecycle singleton's own scope (stopAsync).
- The version-switch single-flight was defeated three ways (safeApiCall eats the
  cancellation, loadContent's pipeline is a sibling launch, the job completes
  instantly): ensureActive after the stop plus a content-load generation checked
  before results apply make superseded pipelines inert.
- A null playback plan (older servers) bypassed the per-engine escalation dedupe,
  looping watchdog->transcode recovery every ~8s unbounded; null is now its own
  one-shot sentinel key.
- Back-cancelling a scrub desynced the scrubber's local state (next OK committed
  a ghost seek to 0:00); the scrubber now resyncs whenever the VM stops scrubbing.
- Gating the intro auto-skip observer per room killed the manual Skip Intro
  prompt too; the observer now runs with auto-fire disabled in rooms so the
  gated manual path works again.
- A fresh recovery session with subtitleTrackIndex=null meant 'server decides',
  not 'keep' — explicit -1 restores deterministic behavior; an explicit detail
  pick is no longer consumed before MPV's async sidecars mount (bounded retry);
  the credits-crossing check can no longer be re-armed by a stale poll tick
  racing a local seek; DV detection now also considers the codec FourCC; and
  the launch-time subtitle auto path explicitly disables text on no-preference,
  so playback matches the detail preview's 'Auto - None' (idempotent re-selects
  keep correctly-chosen tracks).

Co-Authored-By: Claude Fable 5 <[email protected]>
- Offline playback of a multi-part book fed the whole-book position into a single
  downloaded part and then persisted part-local positions against the book —
  reintroducing the sync corruption through the offline path. Offline multi-part
  playback is now part-local (own duration/chapters, resume mapped through the
  timeline or 0) and never writes whole-book progress.
- The transcode part-start path applied its result without rechecking the load
  generation, letting a stale part clobber a newer session and leak it; it now
  bails and stops the stale session.
- The part-load settle heuristic compared positions, so the outgoing stream could
  false-clear it and churn server sessions at the poll rate on short parts; it is
  now tied to stream identity.
- Zero-duration parts (unprobed, no chapters) made a book insta-finish (last
  part) or be unreachable (middle); they are excluded from the timeline and
  end-detection is floor-guarded. Apple carries the same parts but advances on an
  end event, not a poll, so the guard is Android-mechanics.
- The outgoing session's final progress report is captured before the cross-part
  position pre-write, so skipped parts no longer report as fully played.
- Timeline tests cover the zero-duration configurations; download sidecars record
  the file's own duration.

Co-Authored-By: Claude Fable 5 <[email protected]>
…l races

- The first-frame watchdog could never re-arm (job never nulled on completion,
  no reset on recovery swaps), so the fallback mount was never watched and a
  rebuffed first window disarmed detection for the session; it now re-arms on
  every engine/route swap like TV.
- A watchdog false-fire consumed the single escalation one-shot, downgrading a
  later real engine failure to a fatal error; escalation is now per-engine (with
  the null-plan sentinel) like TV.
- The season revert on a failed load used the previous optimistic selection, so
  rapid taps could land on a never-loaded season; it reverts to the last LOADED
  season like TV.
- The Auto version preview resolved with a null quality preference on the first
  frame (flashing the wrong version); it now holds until the preference resolves,
  showing the lastFileId-based value immediately when one exists.
- The subtitle-refresh nonce is reset on a fresh mount (TV's T11 fix, previously
  phone-missing), and DV detection also considers the codec FourCC.

Co-Authored-By: Claude Fable 5 <[email protected]>
…e small races

- The stale-deep-link drop also discarded fresh warm-launch Watch Next clicks
  (any link arriving off the Main route); links are now consumed from any
  authenticated route — which also makes staleness impossible — and
  MainTvActivity is singleTask so warm clicks arrive via onNewIntent instead of
  stacking a second activity.
- The Watch Next wipe was fire-and-forget, racing the reseed on server switch;
  seedNow now joins any pending wipe first.
- The Settings sign-out path ran logout twice (the nav callback repeats the
  teardown); the network logout is skipped when tokens are already cleared.
- The requests success effect re-fired its refresh and resurfaced the stale
  'Request submitted.' banner on every re-entry; a consumed-generation guard
  fires it once per new success and clears the stale banner.
- The cast warmup's lifecycle check-then-act could still start the receiver
  after onStop; both sites now stop it post-start if no longer STARTED.

Co-Authored-By: Claude Fable 5 <[email protected]>
- The load-more latch survived a refresh that shrank a paged list back to one
  page (false 'Couldn't load more' + dead paging); the reset now also keys on the
  item count.
- The personal-list resume refresh never fired on return-from-detail (the
  composition-scoped guard ate the replayed ON_RESUME — the exact case it was
  added for); the gate is now VM-side (hasLoadedOnce + not-loading).
- A failed person filmography load was unrecoverable (empty grid never triggers
  load-more, same-filter re-tap early-returned); same-filter retries are allowed
  on error and a focusable Retry renders on an empty failed grid.
- The inbox refocus fired on any unread-to-zero transition (reading the last
  unread yanked focus); it now only fires for an actual Mark-all click.
- A search submit didn't bump the generation, letting a cancelled load-more paint
  a false error over the in-flight reset; submit bumps it and swallowed
  cancellations are rethrown before state writes.
- The For You empty branch grabbed focus every time it composed; it now uses the
  screen's one-shot flag.
- The admin action toast timer was keyed on the message string, so identical
  consecutive messages were dismissed early; keyed on a nonce now.

Co-Authored-By: Claude Fable 5 <[email protected]>
…eep code

- Bitmap subtitle classification only matched Media3's mime token, so ffprobe
  names (dvb_subtitle, vobsub) were treated as text and the preview disagreed
  with the player; both classifiers now use Apple's ffprobe token set under
  alphanumeric normalization, with regression tests.
- The audio Auto preview lacked Apple's middle resolution rung: the server's
  effective_audio_track_index (which Apple parses and uses) is now deserialized
  on FileVersion and consulted between the explicit selection and the default
  flag, on both platforms.
- The card date formatter cached the process-start locale forever; it now
  rebuilds when the system locale changes.
- The sleep-boundary chapter helpers (and their test) had zero callers since the
  timer was trimmed to Apple's minutes-only; deleted.

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.

1 participant