Android Auto should restore the latest played book into an idle Media3 session #88

Open
opened 2026-09-24 06:01:59 +02:00 by alexander · 6 comments
Owner

Problem

When BookWave is connected to Android Auto while nothing is actively playing, the Android Auto playback surface can have no default/current book. The desired behavior is:

  1. If the live Media3 player/session is already holding a book, keep and display that book even while paused/not playing.
  2. If the playback service/session has been recreated and the player is empty, restore the active profile's latest resumable book.
  3. On a genuinely fresh BookWave state where no device-local remembered book exists, derive the latest played book from the server and use it as the fallback resume/default item.
  4. None of this should start audio merely because Android Auto connected.

This issue is the staging area for the investigation and eventual repair.

Investigation baseline: main = ca080a875f95e7e50a3944e1810cf9c76194c167 on 2026-09-24.

Not a duplicate of #65

#65 owns the Android Auto browse information architecture (Continue → Series → Authors → Profiles), artwork, and profile switching.

This defect is below that browse tree: it is about what the actual Media3 playback session exposes as its current/default resumable book when playback is idle or the service has been recreated.

Current logic

1. A newly created PlaybackService starts with an empty player

PlaybackService.onCreate() builds the ExoPlayer and MediaLibrarySession, but does not install a media item.

Relevant code:

  • playback/.../PlaybackService.kt around 300–374
  • MediaLibrarySession.Builder(this, sessionPlayer, LibraryCallback())

So a fresh service has no currentMediaItem until some later path loads one.

2. A live held book is already preserved

LibraryCallback.onPostConnect() exits immediately when current.mediaItemCount > 0.

That is good: Android Auto does not replace a book that the current Media3 player is already holding.

The problem begins when the service/player has been destroyed and recreated.

3. BookWave intentionally destroys paused/empty playback sessions

PlaybackService.onTaskRemoved() delegates the lifecycle decision to Media3. The code comment explicitly records that Media3 stops paused/empty sessions and onDestroy() releases both the session and player so a stale in-memory item cannot later be resumed accidentally.

Relevant code:

  • PlaybackService.kt around 473–517

This is correct lifecycle hygiene and should not be reversed by keeping the service alive indefinitely.

It does mean, however, that the next Android Auto connection starts from an empty Media3 player and needs a deterministic restoration path.

4. Android Auto restoration is currently coupled to the car device policy

The only current car-connect path that repopulates an empty player is:

PlaybackService.LibraryCallback.onPostConnect()
→ CarConnection.decide(...)
→ startLastBook(current, play = ...)

Current actions:

  • AutoPlay → open last book and play
  • ArmOnly / Ask → open last book and prepare it paused
  • Never → do nothing
  • locked profile → suppress

startLastBook() then calls:
auto.lastPlayed()
→ openQueue()
→ setMediaItem()
→ prepare()

This means “what Android Auto can show as the current book” is accidentally coupled to “what a newly connected car is allowed to do to playback”.

The two concepts should be separated:

  • resume/default presentation state
  • device auto-start policy

The existing lock/privacy suppression remains important and must not be weakened.

5. Media3 playback resumption exists, but it is callback-driven

BookWave already implements both halves of Media3 1.11 playback resumption:

onPlaybackResumption(isForPlayback = true)

  • calls auto.lastPlayed()
  • opens a fresh server playback session
  • returns a playable queue
  • Media3 installs/prepares/plays it

onPlaybackResumption(isForPlayback = false)

  • calls auto.resumeItem()
  • returns metadata only
  • opens no server playback session

This is good for Bluetooth/System UI resume requests, but it does not itself guarantee that an Android Auto live playback session has a current media item after that session is newly created.

Android's current car guidance says a media app should retain the previous session state between drives, including the last played media item; STATE_NONE should only be used when the app genuinely has nothing to play:
https://developer.android.com/training/cars/media/enable-playback

Media3 also documents playback resumption as the mechanism for reconstructing stored playlist/metadata after the service has been terminated:
https://developer.android.com/media/media3/session/background-playback

6. AutoLibrary.lastPlayed() is device-local only

Current implementation:

AutoLibrary.lastPlayed()
→ active profile
→ RememberedBookRepository.rememberedBook(profileId)
→ resolve that ID against accessible cached books
→ reject it only if finished

The underlying helper deliberately says that REST/realtime progress from another client must not replace a valid locally remembered book.

That is a sensible precedence rule once this device has playback ownership.

7. The remembered book is written only by actual local playback

SessionSyncCoordinator.onPlayingChanged(true)
→ RememberedBookRecorder.onPlaying(currentMediaItem)
→ persist profile/book ID in DataStore.

Arming or merely opening a book does not claim local ownership.

Therefore a fresh install / cleared app data / profile with no local playback has no remembered book, even if Audiobookshelf has a clear latest-played item on the server.

8. Fresh app startup currently cannot discover a server latest-played book

ShelfPlayerApplication.onCreate() does:

sessionRestorer.restoreActiveSession()
→ applyStartupMode(auto.lastPlayed()?.id)

But SessionRestorer.restoreActiveSession() explicitly restores the saved credential only; it performs no network read.

So a fresh state with no local remembered ID passes null to startup restoration even when the server has recent playback.

9. BookWave already has server-side recency sources

No new Audiobookshelf API contract is required.

Two existing paths are relevant:

A. Account progress
SyncAccountUseCase performs the cheap authorize/account refresh and writes every server listening position into Room, including updatedAt.

This already handles “book played on another device”.

B. Listening sessions
GET /api/me/listening-sessions is already implemented and tested.
RecentBookHotSetHydrator.recentBookCandidates() reads one bounded page and explicitly preserves the server's newest-first order.

That path is a good fallback when a truly fresh cache does not yet contain enough progress/library state.

Root cause

There are two related gaps:

  1. Session restoration gap: the active Android Auto Media3 session can be recreated with an empty player, and the only car-specific population path is tied to device auto-start policy.
  2. Fresh-state identity gap: the shared lastPlayed() resolver only understands device-local remembered ownership, so it returns null until this installation has actually played something.

The result is a valid server account with resumable content but an Android Auto session that can legitimately expose no default/current book.

Proposed repair direction

Introduce one shared resume/default candidate resolver rather than letting Android Auto, startup mode, browse Continue, and onPlaybackResumption each infer “last book” differently.

Recommended precedence:

  1. Live Media3 current item wins.
    • If the player already holds an item for the active profile, do not replace it.
  2. Valid device-local remembered book wins next.
    • Preserve the existing BW-PLAY-01 rule: server activity must not silently displace a valid book this phone actually played.
  3. Server-derived fallback only when there is no valid local candidate.
    • Prefer already-synced accessible Room progress ordered by newest updatedAt.
    • If the state is genuinely fresh and that cache is not populated yet, use the existing bounded newest-first listening-sessions read, intersect it with the active profile's permitted/visible library, hydrate the selected item as needed, and return the first valid unfinished book.
  4. No candidate → remain empty with a non-fatal diagnostic.
  5. Locked profile → do not expose title/author/artwork or arm playback.
    • Preserve existing lock/privacy behavior.

Important implementation boundary

Do not solve this by keeping PlaybackService alive forever.

Also avoid opening a remote /play session merely to discover/display metadata unless Media3 truly requires a prepared playable item for the car surface. Opening /play has server/session side effects and should remain as close as possible to actual arming/playback intent.

The implementation should explicitly separate:

  • a resumable/default presentation candidate;
  • a fresh playable queue created when Arm/AutoPlay/explicit Play requires one.

If Android Auto requires a real current Player item to avoid STATE_NONE, the repair must make that held/default item safe to expose without allowing a stale URI/session to play. The standard Play path must atomically resolve/refresh it into a fresh openQueue() before audio starts.

Device policy semantics to preserve

This repair must not accidentally turn Never into ArmOnly or ArmOnly into AutoPlay.

The final implementation should make the distinction explicit in tests:

  • displaying/restoring resume metadata/current identity is not permission to start audio;
  • only the existing policy / explicit Play path may open or start playback according to the selected behavior.

If Media3 cannot expose a default car item without functionally arming the Player, document that constraint here before implementation so the product semantics are chosen deliberately rather than by accident.

Suggested code boundary

Likely affected areas:

  • new shared domain/playback resume-candidate resolver
  • AutoLibrary.lastPlayed()/resumeItem()
  • PlaybackService.LibraryCallback.onPlaybackResumption()
  • PlaybackService.LibraryCallback.onPostConnect()
  • startup restoration after SessionRestorer.restoreActiveSession()
  • server/account progress/listening-session fallback wiring
  • tests for local-vs-server precedence and Android Auto empty-session restoration

Avoid making the Android Auto browse tree itself the owner of this state; #65 should remain browse/presentation IA.

Acceptance criteria

  • If Media3 already holds a book, connecting Android Auto shows that same book; no replacement occurs.
  • If the playback service was recreated with an empty player, Android Auto exposes the latest valid resumable book for the active unlocked profile instead of an empty/defaultless playback surface.
  • A paused/restored default book does not start audio merely because Android Auto connected.
  • A valid device-local remembered book outranks newer server activity from another client.
  • If no valid local remembered book exists, a fresh installation/profile can obtain the latest valid unfinished book from server-derived state.
  • Server fallback is permission/profile scoped and cannot surface an inaccessible book.
  • A finished/inaccessible/deleted local remembered item falls through safely rather than leaving the car permanently blank.
  • A locked profile does not leak title, author, cover, or playable state to Android Auto.
  • DevicePolicy.Never, ArmOnly, Ask, and AutoPlay retain their audio-start semantics.
  • Explicit Play from the restored/default item resolves a fresh playable server session and uses current server progress before audio starts.
  • onPlaybackResumption(false) remains fast and locally satisfiable; it does not require network access during boot/system metadata probing.
  • Unit tests pin candidate precedence: live → local remembered → server fallback → none.
  • Unit/integration tests prove a recreated empty Media3 session is repopulated for Android Auto without autoplay.
  • Mutation/regression proof fails if the empty-session restore is removed.
  • Physical Android Auto acceptance verifies: fresh app state, paused prior book, service/process recreation, car reconnect, and explicit Play from the displayed default book.
  • #65 — Android Auto browse home; adjacent, not owner of this defect.
  • #36 — car arrival/departure playback continuity; must not regress.
  • ROUTE-001 — media-button resume.
  • ROUTE-002 — per-device playback policy.
  • ROUTE-003 — startup mode.
  • BW-PLAY-01 — device-local remembered playback ownership.
## Problem When BookWave is connected to Android Auto while nothing is actively playing, the Android Auto playback surface can have no default/current book. The desired behavior is: 1. If the live Media3 player/session is already holding a book, keep and display that book even while paused/not playing. 2. If the playback service/session has been recreated and the player is empty, restore the active profile's latest resumable book. 3. On a genuinely fresh BookWave state where no device-local remembered book exists, derive the latest played book from the server and use it as the fallback resume/default item. 4. None of this should start audio merely because Android Auto connected. This issue is the staging area for the investigation and eventual repair. Investigation baseline: `main` = `ca080a875f95e7e50a3944e1810cf9c76194c167` on 2026-09-24. ## Not a duplicate of #65 #65 owns the Android Auto browse information architecture (Continue → Series → Authors → Profiles), artwork, and profile switching. This defect is below that browse tree: it is about what the actual Media3 playback session exposes as its current/default resumable book when playback is idle or the service has been recreated. ## Current logic ### 1. A newly created PlaybackService starts with an empty player `PlaybackService.onCreate()` builds the ExoPlayer and `MediaLibrarySession`, but does not install a media item. Relevant code: - `playback/.../PlaybackService.kt` around 300–374 - `MediaLibrarySession.Builder(this, sessionPlayer, LibraryCallback())` So a fresh service has no `currentMediaItem` until some later path loads one. ### 2. A live held book is already preserved `LibraryCallback.onPostConnect()` exits immediately when `current.mediaItemCount > 0`. That is good: Android Auto does not replace a book that the current Media3 player is already holding. The problem begins when the service/player has been destroyed and recreated. ### 3. BookWave intentionally destroys paused/empty playback sessions `PlaybackService.onTaskRemoved()` delegates the lifecycle decision to Media3. The code comment explicitly records that Media3 stops paused/empty sessions and `onDestroy()` releases both the session and player so a stale in-memory item cannot later be resumed accidentally. Relevant code: - `PlaybackService.kt` around 473–517 This is correct lifecycle hygiene and should not be reversed by keeping the service alive indefinitely. It does mean, however, that the next Android Auto connection starts from an empty Media3 player and needs a deterministic restoration path. ### 4. Android Auto restoration is currently coupled to the car device policy The only current car-connect path that repopulates an empty player is: `PlaybackService.LibraryCallback.onPostConnect()` → `CarConnection.decide(...)` → `startLastBook(current, play = ...)` Current actions: - `AutoPlay` → open last book and play - `ArmOnly` / `Ask` → open last book and prepare it paused - `Never` → do nothing - locked profile → suppress `startLastBook()` then calls: `auto.lastPlayed()` → `openQueue()` → `setMediaItem()` → `prepare()` This means “what Android Auto can show as the current book” is accidentally coupled to “what a newly connected car is allowed to do to playback”. The two concepts should be separated: - **resume/default presentation state** - **device auto-start policy** The existing lock/privacy suppression remains important and must not be weakened. ### 5. Media3 playback resumption exists, but it is callback-driven BookWave already implements both halves of Media3 1.11 playback resumption: `onPlaybackResumption(isForPlayback = true)` - calls `auto.lastPlayed()` - opens a fresh server playback session - returns a playable queue - Media3 installs/prepares/plays it `onPlaybackResumption(isForPlayback = false)` - calls `auto.resumeItem()` - returns metadata only - opens no server playback session This is good for Bluetooth/System UI resume requests, but it does not itself guarantee that an Android Auto live playback session has a current media item after that session is newly created. Android's current car guidance says a media app should retain the previous session state between drives, including the last played media item; `STATE_NONE` should only be used when the app genuinely has nothing to play: https://developer.android.com/training/cars/media/enable-playback Media3 also documents playback resumption as the mechanism for reconstructing stored playlist/metadata after the service has been terminated: https://developer.android.com/media/media3/session/background-playback ### 6. `AutoLibrary.lastPlayed()` is device-local only Current implementation: `AutoLibrary.lastPlayed()` → active profile → `RememberedBookRepository.rememberedBook(profileId)` → resolve that ID against accessible cached books → reject it only if finished The underlying helper deliberately says that REST/realtime progress from another client must **not** replace a valid locally remembered book. That is a sensible precedence rule once this device has playback ownership. ### 7. The remembered book is written only by actual local playback `SessionSyncCoordinator.onPlayingChanged(true)` → `RememberedBookRecorder.onPlaying(currentMediaItem)` → persist profile/book ID in DataStore. Arming or merely opening a book does not claim local ownership. Therefore a fresh install / cleared app data / profile with no local playback has no remembered book, even if Audiobookshelf has a clear latest-played item on the server. ### 8. Fresh app startup currently cannot discover a server latest-played book `ShelfPlayerApplication.onCreate()` does: `sessionRestorer.restoreActiveSession()` → `applyStartupMode(auto.lastPlayed()?.id)` But `SessionRestorer.restoreActiveSession()` explicitly restores the saved credential only; it performs no network read. So a fresh state with no local remembered ID passes `null` to startup restoration even when the server has recent playback. ### 9. BookWave already has server-side recency sources No new Audiobookshelf API contract is required. Two existing paths are relevant: **A. Account progress** `SyncAccountUseCase` performs the cheap authorize/account refresh and writes every server listening position into Room, including `updatedAt`. This already handles “book played on another device”. **B. Listening sessions** `GET /api/me/listening-sessions` is already implemented and tested. `RecentBookHotSetHydrator.recentBookCandidates()` reads one bounded page and explicitly preserves the server's newest-first order. That path is a good fallback when a truly fresh cache does not yet contain enough progress/library state. ## Root cause There are two related gaps: 1. **Session restoration gap:** the active Android Auto Media3 session can be recreated with an empty player, and the only car-specific population path is tied to device auto-start policy. 2. **Fresh-state identity gap:** the shared `lastPlayed()` resolver only understands device-local remembered ownership, so it returns null until this installation has actually played something. The result is a valid server account with resumable content but an Android Auto session that can legitimately expose no default/current book. ## Proposed repair direction Introduce one shared **resume/default candidate resolver** rather than letting Android Auto, startup mode, browse Continue, and `onPlaybackResumption` each infer “last book” differently. Recommended precedence: 1. **Live Media3 current item wins.** - If the player already holds an item for the active profile, do not replace it. 2. **Valid device-local remembered book wins next.** - Preserve the existing BW-PLAY-01 rule: server activity must not silently displace a valid book this phone actually played. 3. **Server-derived fallback only when there is no valid local candidate.** - Prefer already-synced accessible Room progress ordered by newest `updatedAt`. - If the state is genuinely fresh and that cache is not populated yet, use the existing bounded newest-first listening-sessions read, intersect it with the active profile's permitted/visible library, hydrate the selected item as needed, and return the first valid unfinished book. 4. **No candidate → remain empty with a non-fatal diagnostic.** 5. **Locked profile → do not expose title/author/artwork or arm playback.** - Preserve existing lock/privacy behavior. ### Important implementation boundary Do **not** solve this by keeping `PlaybackService` alive forever. Also avoid opening a remote `/play` session merely to discover/display metadata unless Media3 truly requires a prepared playable item for the car surface. Opening `/play` has server/session side effects and should remain as close as possible to actual arming/playback intent. The implementation should explicitly separate: - a resumable/default **presentation candidate**; - a fresh **playable queue** created when Arm/AutoPlay/explicit Play requires one. If Android Auto requires a real current Player item to avoid `STATE_NONE`, the repair must make that held/default item safe to expose without allowing a stale URI/session to play. The standard Play path must atomically resolve/refresh it into a fresh `openQueue()` before audio starts. ## Device policy semantics to preserve This repair must not accidentally turn `Never` into `ArmOnly` or `ArmOnly` into `AutoPlay`. The final implementation should make the distinction explicit in tests: - displaying/restoring resume metadata/current identity is not permission to start audio; - only the existing policy / explicit Play path may open or start playback according to the selected behavior. If Media3 cannot expose a default car item without functionally arming the Player, document that constraint here before implementation so the product semantics are chosen deliberately rather than by accident. ## Suggested code boundary Likely affected areas: - new shared domain/playback resume-candidate resolver - `AutoLibrary.lastPlayed()/resumeItem()` - `PlaybackService.LibraryCallback.onPlaybackResumption()` - `PlaybackService.LibraryCallback.onPostConnect()` - startup restoration after `SessionRestorer.restoreActiveSession()` - server/account progress/listening-session fallback wiring - tests for local-vs-server precedence and Android Auto empty-session restoration Avoid making the Android Auto browse tree itself the owner of this state; #65 should remain browse/presentation IA. ## Acceptance criteria - [ ] If Media3 already holds a book, connecting Android Auto shows that same book; no replacement occurs. - [ ] If the playback service was recreated with an empty player, Android Auto exposes the latest valid resumable book for the active unlocked profile instead of an empty/defaultless playback surface. - [ ] A paused/restored default book does not start audio merely because Android Auto connected. - [ ] A valid device-local remembered book outranks newer server activity from another client. - [ ] If no valid local remembered book exists, a fresh installation/profile can obtain the latest valid unfinished book from server-derived state. - [ ] Server fallback is permission/profile scoped and cannot surface an inaccessible book. - [ ] A finished/inaccessible/deleted local remembered item falls through safely rather than leaving the car permanently blank. - [ ] A locked profile does not leak title, author, cover, or playable state to Android Auto. - [ ] `DevicePolicy.Never`, `ArmOnly`, `Ask`, and `AutoPlay` retain their audio-start semantics. - [ ] Explicit Play from the restored/default item resolves a fresh playable server session and uses current server progress before audio starts. - [ ] `onPlaybackResumption(false)` remains fast and locally satisfiable; it does not require network access during boot/system metadata probing. - [ ] Unit tests pin candidate precedence: live → local remembered → server fallback → none. - [ ] Unit/integration tests prove a recreated empty Media3 session is repopulated for Android Auto without autoplay. - [ ] Mutation/regression proof fails if the empty-session restore is removed. - [ ] Physical Android Auto acceptance verifies: fresh app state, paused prior book, service/process recreation, car reconnect, and explicit Play from the displayed default book. ## Related - #65 — Android Auto browse home; adjacent, not owner of this defect. - #36 — car arrival/departure playback continuity; must not regress. - ROUTE-001 — media-button resume. - ROUTE-002 — per-device playback policy. - ROUTE-003 — startup mode. - BW-PLAY-01 — device-local remembered playback ownership.
Author
Owner

Investigation refinement — existing Continue shelf can supply the cached server fallback

A second pass found that the repair can reuse more existing domain logic than the initial issue body suggested.

Existing inconsistency inside AutoLibrary

AutoLibrary already has two different definitions of “what should I continue?”:

  • resumeRow()/resumeItem()/lastPlayed() uses only RememberedBookRepository.
  • continueRows() and empty voice search use HomeShelves.continueListening.

HomeShelves.continueListening is already:

  • profile-scoped through the accessible Room book projection;
  • unfinished-only;
  • sorted by progress.updatedAt newest first;
  • fed by server progress written by SyncAccountUseCase and realtime updates.

So it is entirely possible today for Android Auto's Continue browse destination / empty search to know the newest server-progress book while the resume/default path returns nothing.

That is a concrete semantic split, not just a lifecycle hypothesis.

Smaller cached fallback

The local/cached portion of a shared candidate resolver can likely be:

  1. resolve the remembered local ID against the active profile's accessible books;
  2. if that returns a valid unfinished book, use it;
  3. otherwise use the first HomeShelves.continueListening book.

This preserves the existing “a valid book actually played on this phone wins” rule while allowing server-synced progress to seed a profile that has no valid local owner.

There is no reason to create another progress sort for this; HomeShelves.continueListening already pins the predicate/order in unit tests.

Fresh-network case is still separate

SyncAccountUseCase performs the cheap account refresh and writes every server position into Room. ForegroundRealtimeSyncCoordinator launches that reconciliation whenever the app becomes foreground authority.

However:

  • startup restoration is launched independently from ShelfPlayerApplication.onCreate();
  • the account reconcile happens later/independently;
  • a MediaLibraryService started by Android Auto does not necessarily imply the phone UI has foregrounded.

Therefore a genuinely cold/fresh resume request can still race ahead of server progress hydration.

For that case, do not simply trust a listening-session item ID. Reuse the same admission rule already proven by RecentBookHotSetHydrator:

  • listening sessions are recency hints only;
  • the selected item must resolve inside the active profile's accessible/admitted catalogue before metadata or playback is exposed.

One more place that must change with the candidate semantics

AutoLibrary.profileBoundaryCounts() currently reports RECENT_ROOT child count from the local remembered ID only.

If resumeRow() gains a server-progress fallback but this count remains unchanged, Android Auto can be told that the resume root has 0 children while a subsequent read returns 1. The resolver/count logic should share the same candidate semantics.

Implementation consequence

The likely repair boundary is now:

  • centralize local/cached candidate selection (remembered local book first, then continueListening.firstOrNull());
  • use that same resolver for resumeRow/resumeItem, onPlaybackResumption, car empty-session restoration, startup restore, and recent-root count;
  • add a bounded authenticated server hydration only when that shared local/cached resolver has no candidate;
  • keep onPlaybackResumption(false) fast/local-only for boot/SystemUI metadata probes;
  • never let the server fallback replace a still-valid locally remembered book.

This should be tested specifically with:

  1. local remembered book + newer remote progress → local wins;
  2. no local remembered book + cached server progress → newest Continue item wins;
  3. invalid/finished local remembered book + cached server progress → fallback wins;
  4. no local/cached candidate + server listening session for an inaccessible book → nothing leaks;
  5. fresh admissible server candidate → becomes resumable without autoplay.
## Investigation refinement — existing Continue shelf can supply the cached server fallback A second pass found that the repair can reuse more existing domain logic than the initial issue body suggested. ### Existing inconsistency inside AutoLibrary `AutoLibrary` already has two different definitions of “what should I continue?”: - `resumeRow()/resumeItem()/lastPlayed()` uses **only** `RememberedBookRepository`. - `continueRows()` and empty voice search use `HomeShelves.continueListening`. `HomeShelves.continueListening` is already: - profile-scoped through the accessible Room book projection; - unfinished-only; - sorted by `progress.updatedAt` newest first; - fed by server progress written by `SyncAccountUseCase` and realtime updates. So it is entirely possible today for Android Auto's Continue browse destination / empty search to know the newest server-progress book while the resume/default path returns **nothing**. That is a concrete semantic split, not just a lifecycle hypothesis. ### Smaller cached fallback The local/cached portion of a shared candidate resolver can likely be: 1. resolve the remembered local ID against the active profile's accessible books; 2. if that returns a valid unfinished book, use it; 3. otherwise use the first `HomeShelves.continueListening` book. This preserves the existing “a valid book actually played on this phone wins” rule while allowing server-synced progress to seed a profile that has no valid local owner. There is no reason to create another progress sort for this; `HomeShelves.continueListening` already pins the predicate/order in unit tests. ### Fresh-network case is still separate `SyncAccountUseCase` performs the cheap account refresh and writes every server position into Room. `ForegroundRealtimeSyncCoordinator` launches that reconciliation whenever the app becomes foreground authority. However: - startup restoration is launched independently from `ShelfPlayerApplication.onCreate()`; - the account reconcile happens later/independently; - a MediaLibraryService started by Android Auto does not necessarily imply the phone UI has foregrounded. Therefore a genuinely cold/fresh resume request can still race ahead of server progress hydration. For that case, do not simply trust a listening-session item ID. Reuse the same admission rule already proven by `RecentBookHotSetHydrator`: - listening sessions are **recency hints only**; - the selected item must resolve inside the active profile's accessible/admitted catalogue before metadata or playback is exposed. ### One more place that must change with the candidate semantics `AutoLibrary.profileBoundaryCounts()` currently reports `RECENT_ROOT` child count from the local remembered ID only. If `resumeRow()` gains a server-progress fallback but this count remains unchanged, Android Auto can be told that the resume root has 0 children while a subsequent read returns 1. The resolver/count logic should share the same candidate semantics. ### Implementation consequence The likely repair boundary is now: - centralize local/cached candidate selection (remembered local book first, then `continueListening.firstOrNull()`); - use that same resolver for `resumeRow/resumeItem`, `onPlaybackResumption`, car empty-session restoration, startup restore, and recent-root count; - add a bounded authenticated server hydration only when that shared local/cached resolver has no candidate; - keep `onPlaybackResumption(false)` fast/local-only for boot/SystemUI metadata probes; - never let the server fallback replace a still-valid locally remembered book. This should be tested specifically with: 1. local remembered book + newer remote progress → local wins; 2. no local remembered book + cached server progress → newest Continue item wins; 3. invalid/finished local remembered book + cached server progress → fallback wins; 4. no local/cached candidate + server listening session for an inaccessible book → nothing leaks; 5. fresh admissible server candidate → becomes resumable without autoplay.
Author
Owner

CI failure investigation — run #273 / failed HEAD 728477d22f42dba4da047631f4404aa17fd1eab4

Forgejo PR verification run #273 failed after exercising the independent quality gates. The consolidated diagnostics exposed all of the following distinct failures:

1. ktlint — 2 findings

  • domain/.../LastPlayed.kt:27 — expression-body formatting (standard:function-signature).
  • playback/.../AutoLibrary.kt:3 — import ordering after adding the resume-candidate alias/KTX URI import.

Repair now on branch:

  • 689a51f — format resume candidate expression.
  • 2467444 — order imports.

2. Detekt — 3 ReturnCount findings

  • SessionSyncCoordinator.snapshot() — 5 returns, limit 4.
  • PlaybackService.positionSnapshot() — 5 returns, limit 4.
  • PlaybackService.materializeHeldResume() — 5 returns, limit 4.

These were guard-shape/static-policy failures rather than behavioral failures. The holder checks remain intact while null/placeholder and authorization cases are combined/restructured.

Repair now on branch:

  • 7c6bb54 — keep session-sync holder guard within ReturnCount.
  • 252e645 — simplify idle-resume guards within static policy.

3. Android Lint — 1 error

AutoLibrary.kt:343 used Uri.parse(RESUME_PLACEHOLDER_URI) while Android KTX is already present.

Repair:

  • 2467444 — uses RESUME_PLACEHOLDER_URI.toUri().

This same lint error appeared under both :playback:lintDebug and :app:lintDebug; it is one source defect propagated through two lint tasks, not two different defects.

4. Unit test — 1 failure

SessionSyncCoordinatorTest.held resume metadata is never synced as an active playback position

Root cause is the test environment, not the production holder guard:

  • the test constructs the marker using android.os.Bundle.putBoolean(...);
  • it was running as a plain JVM test;
  • local Android stub behavior does not provide trustworthy real Bundle mutation semantics here, so the resume-placeholder bit was not reliably observed;
  • production Media3 uses the real Android Bundle implementation.

Repair:

  • f9e4c41 — runs this Bundle-backed test class with RobolectricTestRunner, preserving the production-like Bundle semantics the assertion actually depends on.

Workflow/reporting observation

Run #273 did a useful --continue style sweep: despite early Detekt/ktlint failures it still reported the unit test, Android Lint, schema and dependency results. That is good and is why all known failures could be repaired in one pass.

There is one reporting imprecision worth watching rather than changing immediately:

  • the consolidated report placed the Android Lint UseKtx finding under “Compiler / build errors” as well;
  • it also said “Compilation failed” in the coverage-completeness note even though the recorded failures were lint/static/test tasks, not a Kotlin compiler task.

Per the current plan, leave the workflow unchanged unless the next verification exposes additional failures that #273 should have surfaced but did not.

Current verification

PR #90 now points at repaired HEAD f9e4c41718d0334b50a15cac80e5d904e8f02cdc, still based directly on current main and mergeable.

A new exact-head PR verification run #274 is currently executing. Its result will be compared against #273 specifically to determine whether the workflow missed any independent failure class.

## CI failure investigation — run #273 / failed HEAD `728477d22f42dba4da047631f4404aa17fd1eab4` Forgejo PR verification run #273 failed after exercising the independent quality gates. The consolidated diagnostics exposed all of the following distinct failures: ### 1. ktlint — 2 findings - `domain/.../LastPlayed.kt:27` — expression-body formatting (`standard:function-signature`). - `playback/.../AutoLibrary.kt:3` — import ordering after adding the resume-candidate alias/KTX URI import. Repair now on branch: - `689a51f` — format resume candidate expression. - `2467444` — order imports. ### 2. Detekt — 3 ReturnCount findings - `SessionSyncCoordinator.snapshot()` — 5 returns, limit 4. - `PlaybackService.positionSnapshot()` — 5 returns, limit 4. - `PlaybackService.materializeHeldResume()` — 5 returns, limit 4. These were guard-shape/static-policy failures rather than behavioral failures. The holder checks remain intact while null/placeholder and authorization cases are combined/restructured. Repair now on branch: - `7c6bb54` — keep session-sync holder guard within ReturnCount. - `252e645` — simplify idle-resume guards within static policy. ### 3. Android Lint — 1 error `AutoLibrary.kt:343` used `Uri.parse(RESUME_PLACEHOLDER_URI)` while Android KTX is already present. Repair: - `2467444` — uses `RESUME_PLACEHOLDER_URI.toUri()`. This same lint error appeared under both `:playback:lintDebug` and `:app:lintDebug`; it is one source defect propagated through two lint tasks, not two different defects. ### 4. Unit test — 1 failure `SessionSyncCoordinatorTest.held resume metadata is never synced as an active playback position` Root cause is the test environment, not the production holder guard: - the test constructs the marker using `android.os.Bundle.putBoolean(...)`; - it was running as a plain JVM test; - local Android stub behavior does not provide trustworthy real `Bundle` mutation semantics here, so the resume-placeholder bit was not reliably observed; - production Media3 uses the real Android Bundle implementation. Repair: - `f9e4c41` — runs this Bundle-backed test class with `RobolectricTestRunner`, preserving the production-like Bundle semantics the assertion actually depends on. ### Workflow/reporting observation Run #273 did a useful `--continue` style sweep: despite early Detekt/ktlint failures it still reported the unit test, Android Lint, schema and dependency results. That is good and is why all known failures could be repaired in one pass. There is one reporting imprecision worth watching rather than changing immediately: - the consolidated report placed the Android Lint `UseKtx` finding under “Compiler / build errors” as well; - it also said “Compilation failed” in the coverage-completeness note even though the recorded failures were lint/static/test tasks, not a Kotlin compiler task. Per the current plan, leave the workflow unchanged unless the next verification exposes additional failures that #273 should have surfaced but did not. ### Current verification PR #90 now points at repaired HEAD `f9e4c41718d0334b50a15cac80e5d904e8f02cdc`, still based directly on current `main` and mergeable. A new exact-head PR verification run #274 is currently executing. Its result will be compared against #273 specifically to determine whether the workflow missed any independent failure class.
Author
Owner

CI repair verification — run #274

The repaired PR head is now:

f9e4c41718d0334b50a15cac80e5d904e8f02cdc

Exact-head Forgejo PR verification run #274 completed successfully.

Result:

  • preflight: PASS
  • fast/static gates: PASS
  • verifyDebug: PASS
  • unit tests: PASS
  • ktlint: PASS
  • Detekt: PASS
  • Android Lint: PASS
  • Room schema check: PASS
  • dependency resolution: PASS
  • published BookWave / PR verification commit status: SUCCESS

The full Gradle verification reported:

BUILD SUCCESSFUL in 5m 13s
1121 actionable tasks: 506 executed, 157 from cache, 458 up-to-date

No second-wave failure appeared after repairing run #273's known failures. Therefore the current workflow was sufficient to expose the complete failure set for this PR, and no workflow change is justified by this evidence.

One reporting-quality observation remains for future CI work: run #273's consolidated diagnostics duplicated the UseKtx Android Lint finding under “Compiler / build errors” and described the incomplete downstream coverage as “Compilation failed” even though no Kotlin compiler task was the failing cause. That wording can be improved under the CI architecture work (#85), but it did not hide any actual failure in this PR.

PR #90 is currently mergeable, up to date with main, and exact-head checks are green. Physical Android Auto acceptance remains separate from CI.

## CI repair verification — run #274 The repaired PR head is now: `f9e4c41718d0334b50a15cac80e5d904e8f02cdc` Exact-head Forgejo PR verification run #274 completed successfully. Result: - preflight: PASS - fast/static gates: PASS - `verifyDebug`: PASS - unit tests: PASS - ktlint: PASS - Detekt: PASS - Android Lint: PASS - Room schema check: PASS - dependency resolution: PASS - published `BookWave / PR verification` commit status: SUCCESS The full Gradle verification reported: `BUILD SUCCESSFUL in 5m 13s` `1121 actionable tasks: 506 executed, 157 from cache, 458 up-to-date` No second-wave failure appeared after repairing run #273's known failures. Therefore the current workflow was sufficient to expose the complete failure set for this PR, and no workflow change is justified by this evidence. One reporting-quality observation remains for future CI work: run #273's consolidated diagnostics duplicated the `UseKtx` Android Lint finding under “Compiler / build errors” and described the incomplete downstream coverage as “Compilation failed” even though no Kotlin compiler task was the failing cause. That wording can be improved under the CI architecture work (#85), but it did not hide any actual failure in this PR. PR #90 is currently mergeable, up to date with `main`, and exact-head checks are green. Physical Android Auto acceptance remains separate from CI.
Author
Owner

Implementation + CI staging update

PR #90 implements this issue on mcp/issue-88-android-auto-held-resume.

Verified implementation head: f9e4c41718d0334b50a15cac80e5d904e8f02cdc
Base: main@88ae231ddc01897d83e24968bed5443ea861aedd
Forgejo Actions: run #274 — PASS
Commit status: BookWave / PR verification — success
PR readiness: mergeable, 0 behind main, no CI blockers.

Implemented behavior:

  • a live Media3 current item remains authoritative and is not replaced on car connection;
  • resume selection is now local remembered book first, then newest unfinished server-synced Continue candidate;
  • when no local/cached candidate exists, cold startup / playback resumption performs the existing account reconciliation to hydrate server progress;
  • Never-policy Android Auto can hold a metadata-only current book without Audiobookshelf /play, prepare, or autoplay;
  • the holder uses an inert app-local MediaSource and is explicitly excluded from ready-to-play pass-through and progress/session writes;
  • explicit Play materializes the holder into a fresh server-backed queue, then enters the shared resume-freshness path;
  • lock state and newer controller intent are rechecked after suspension so a stale network result cannot override Pause/Stop/seek/media replacement/profile changes;
  • Arm / Ask / AutoPlay retain their existing audio-start semantics;
  • metadata-only Media3 resumption remains local-only and is withheld while the profile is locked;
  • recent-root child counts share the same candidate semantics.

Regression coverage pins candidate precedence, cached/server fallback, inert holder construction/source safety, progress-write exclusion, cold-start wiring and callback reachability. The first CI pass found style/static/lint issues plus a JVM Android-Bundle test-fixture mismatch; those were repaired, and the exact final head passed the complete manual PR gate.

Still requires physical acceptance

The Forgejo runner has no Android device/emulator attached, so these criteria remain open for device/DHU/car evidence:

  • fresh app state where latest progress exists only on the server;
  • paused prior book survives service/process recreation as the displayed default;
  • car reconnect with Never shows the held book and stays silent;
  • Arm/Ask/AutoPlay preserve their expected audio behavior;
  • explicit Play from the displayed held book opens a fresh playable session and resumes at current server position;
  • locked profile exposes no title/author/artwork/playable state.

This issue remains the acceptance staging area until that physical evidence is recorded.

## Implementation + CI staging update PR #90 implements this issue on `mcp/issue-88-android-auto-held-resume`. Verified implementation head: `f9e4c41718d0334b50a15cac80e5d904e8f02cdc` Base: `main@88ae231ddc01897d83e24968bed5443ea861aedd` Forgejo Actions: run #274 — PASS Commit status: `BookWave / PR verification` — success PR readiness: mergeable, 0 behind main, no CI blockers. Implemented behavior: - a live Media3 current item remains authoritative and is not replaced on car connection; - resume selection is now local remembered book first, then newest unfinished server-synced Continue candidate; - when no local/cached candidate exists, cold startup / playback resumption performs the existing account reconciliation to hydrate server progress; - Never-policy Android Auto can hold a metadata-only current book without Audiobookshelf `/play`, prepare, or autoplay; - the holder uses an inert app-local MediaSource and is explicitly excluded from ready-to-play pass-through and progress/session writes; - explicit Play materializes the holder into a fresh server-backed queue, then enters the shared resume-freshness path; - lock state and newer controller intent are rechecked after suspension so a stale network result cannot override Pause/Stop/seek/media replacement/profile changes; - Arm / Ask / AutoPlay retain their existing audio-start semantics; - metadata-only Media3 resumption remains local-only and is withheld while the profile is locked; - recent-root child counts share the same candidate semantics. Regression coverage pins candidate precedence, cached/server fallback, inert holder construction/source safety, progress-write exclusion, cold-start wiring and callback reachability. The first CI pass found style/static/lint issues plus a JVM Android-Bundle test-fixture mismatch; those were repaired, and the exact final head passed the complete manual PR gate. ### Still requires physical acceptance The Forgejo runner has no Android device/emulator attached, so these criteria remain open for device/DHU/car evidence: - fresh app state where latest progress exists only on the server; - paused prior book survives service/process recreation as the displayed default; - car reconnect with Never shows the held book and stays silent; - Arm/Ask/AutoPlay preserve their expected audio behavior; - explicit Play from the displayed held book opens a fresh playable session and resumes at current server position; - locked profile exposes no title/author/artwork/playable state. This issue remains the acceptance staging area until that physical evidence is recorded.
Author
Owner

Physical acceptance still failing — add an Android Auto startup Media3 handoff trace

The owner reports that Android Auto can still start without displaying the expected current/playing/default book after the #88 implementation. Reopen acceptance and instrument the actual Media3 ↔ Android Auto startup race rather than inferring it from later browse logs.

What Android Auto can currently receive at startup

There are several distinct Media3 surfaces, and they can race independently:

  1. Live Player / MediaSession current item

    • player.currentMediaItem / timeline is what the playback surface can treat as the current item.
    • For a Never-policy car, onPostConnect() currently launches a coroutine and may later call holdLastBook(), which installs the inert #88 resume placeholder with current.setMediaItem(...).
    • This happens asynchronously after the controller connection is accepted.
  2. Recent/resume library root

    • onGetLibraryRoot(... params.isRecent=true) immediately returns AutoLibrary.recentRoot().
    • That root is browsable; it is not itself the playable book.
  3. Recent/resume child

    • If Gearhead asks for children of the recent root, onGetChildren(RECENT_ROOT) returns resumeRow().
    • This is the playable/default resume row and can exist independently of whether the Player already holds the same book.
  4. Normal browse children

    • Continue / Series / Authors eventually return playable book MediaItem rows.
    • These are browse identities, not necessarily the Player's current item.
  5. Playback-resumption metadata

    • onPlaybackResumption(isForPlayback=false) returns one metadata-only resumable MediaItem when available.
  6. Playback-resumption queue

    • onPlaybackResumption(isForPlayback=true) opens/resolves a fresh playable queue and returns the item Media3 will install/prepare/play.
  7. Controller selection

    • onAddMediaItems / onSetMediaItems resolve Android Auto selections into the item(s) handed back to Media3.

These are related but not one callback. A valid resume row can be handed to Android Auto while player.currentMediaItem is still empty, or the Player can be populated after Gearhead has already decided its initial surface.

Concrete startup race already visible in the code

onPostConnect() returns immediately and does:

scope.launch {
    ...
    AutoStartAction.None -> holdLastBook(current)
}

At the same time, Gearhead is free to call onGetLibraryRoot, onGetChildren, resumption callbacks, and inspect the session/player state.

Therefore the next diagnostic build must record the exact callback/event ordering with a monotonic timestamp.

Required diagnostic: Android Auto startup handoff trace

Create one short-lived Auto startup trace id for each Gearhead/automotive controller connection, e.g. autoTrace=17. Keep it alive through the initial startup/browse/resumption window.

Every event below should log:

  • autoTrace
  • monotonic elapsed time from controller connect, preferably milliseconds
  • controller package/classification
  • callback/event name
  • current Player snapshot before the callback/action
  • item(s) requested
  • item(s) returned/installed
  • completion time for async callbacks

Safe MediaItem fingerprint

Do not dump private stream URLs or full server/library data. For every MediaItem use one compact fingerprint:

  • kind: holder / playable-book / browse-book / root / tab / series / author / profile / unknown
  • short deterministic media-id fingerprint (or existing public opaque id where safe)
  • isPlayable
  • isBrowsable
  • resumePlaceholder=true/false
  • owner-profile fingerprint
  • hasUri=true/false
  • URI class only: inert-placeholder / content / http(s) / none — never the URI value
  • hasArtwork=true/false
  • duration if known
  • current/start position when relevant

This lets one trace prove that the same logical book flowed through the different Media3 surfaces without putting private titles or stream URLs into diagnostics.

Events/callbacks to instrument

Controller/session boundary

onConnect

  • Player snapshot before accepting Gearhead:
    • mediaItemCount
    • current item fingerprint or none
    • currentMediaItemIndex
    • playbackState
    • playWhenReady
    • currentPosition
  • controller classification and granted commands.

onPostConnect

  • entry snapshot;
  • chosen AutoStartAction;
  • whether holder/start-last-book work was launched;
  • log both async start and async completion;
  • Player snapshot after completion.

This is important because current onPostConnect work is asynchronous and is a prime race candidate.

Player item changes

Instrument Player.Listener.onMediaItemTransition for this trace:

  • transition reason;
  • previous fingerprint if retained;
  • new fingerprint;
  • timeline count/index;
  • placeholder-vs-real;
  • position.

Also log when #88 explicitly calls:

  • current.setMediaItem(held.item, held.startPositionMs);
  • materialization replaces holder with the server-backed queue.

Library root

onGetLibraryRoot

  • params.isRecent;
  • Player snapshot at callback entry;
  • exact root fingerprint returned;
  • callback completion latency.

Browse children

onGetChildren

  • parent id/kind;
  • page/pageSize;
  • Player current item fingerprint at entry;
  • all items in the returned page, in order, using the safe fingerprint;
  • total child count and returned-page count;
  • callback completion latency.

For RECENT_ROOT specifically, log:

  • resume candidate source: live/current, remembered-local, cached-server-progress, refreshed-server-progress, none;
  • returned child fingerprint(s).

For TAB_CONTINUE, include the ordered playable item fingerprints so we can compare the resume/default candidate with the first Continue row.

Get item

onGetItem

  • asked fingerprint/media-id kind;
  • resolved item fingerprint or unresolved;
  • current Player fingerprint.

Playback resumption

onPlaybackResumption(false)

  • entry Player snapshot;
  • candidate source;
  • exact item fingerprint returned, or empty;
  • latency.

onPlaybackResumption(true)

  • same, plus:
    • queue item fingerprint;
    • authoritative start position;
    • whether /play was opened;
    • result returned to Media3.

Controller-set media

The existing logSelection is useful but currently records only branch/kind/counts. Expand it for the startup trace to include:

onAddMediaItems

  • every asked item fingerprint, in order;
  • every resolved/handed-back item fingerprint, in order.

onSetMediaItems

  • every asked item fingerprint;
  • selected/resolved item fingerprint;
  • exact handed-back MediaItems list;
  • asked startIndex/startPosition;
  • returned startIndex/startPosition;
  • Player snapshot before resolution and after Media3 applies the result (via player transition log).

Candidate-resolution trace

Instrument #88's resolver as a separate decision line:

Resume candidate resolved source=<live|remembered|cached-progress|refreshed-progress|none> candidate=<fingerprint>

Include candidate rejection reasons where relevant:

  • finished;
  • inaccessible;
  • missing from active profile;
  • locked;
  • stale remembered id;
  • no synced progress;
  • refresh produced no candidate.

This will distinguish candidate selection failed from candidate selected but reached Android Auto too late.

What the physical trace must answer

One cold Android Auto connection should let us reconstruct, in timestamp order:

  1. when Gearhead connected;
  2. whether Player already had an item;
  3. which resume/default candidate BookWave knew at that moment;
  4. whether Gearhead first requested recent root, normal root, resumption metadata, or something else;
  5. every playable item returned to Gearhead and in what order;
  6. when #88 installed the held Media3 item;
  7. whether Gearhead had already completed its initial home/player construction before that install;
  8. whether Media3 later notified Gearhead of the new current item;
  9. whether a resume row and Player current item referred to the same logical book;
  10. whether Android Auto ignored a correct item, or BookWave never handed it one in time.

Example of the desired shape

autoTrace=17 +000ms onConnect playerItem=none count=0
autoTrace=17 +006ms onGetLibraryRoot recent=true returned=recent-root
autoTrace=17 +011ms onPostConnect action=None async=started playerItem=none
autoTrace=17 +020ms onGetChildren parent=recent returned=[book#A holder=false]
autoTrace=17 +143ms resumeCandidate source=remembered candidate=book#A
autoTrace=17 +147ms holdLastBook setMediaItem=book#A placeholder=true
autoTrace=17 +149ms playerMediaItemTransition new=book#A placeholder=true
autoTrace=17 +151ms onPostConnect async=complete playerItem=book#A

If Android Auto still shows no item with a trace like that, we then know the app did hand it the right book and the remaining question is Media3/session notification semantics. If instead onGetChildren/resumption returns empty before the candidate appears, the bug is BookWave's startup sequencing.

Acceptance status

#88 remains open. CI success for PR #90 is not physical acceptance.

Before closing again, capture at least one real projected Android Auto cold/reconnect trace where the expected held/latest book is visible and correlate the displayed item to the exact MediaItem fingerprint BookWave handed to Media3/Gearhead.

## Physical acceptance still failing — add an Android Auto startup Media3 handoff trace The owner reports that Android Auto can still start without displaying the expected current/playing/default book after the #88 implementation. Reopen acceptance and instrument the actual Media3 ↔ Android Auto startup race rather than inferring it from later browse logs. ### What Android Auto can currently receive at startup There are several distinct Media3 surfaces, and they can race independently: 1. **Live Player / MediaSession current item** - `player.currentMediaItem` / timeline is what the playback surface can treat as the current item. - For a Never-policy car, `onPostConnect()` currently launches a coroutine and may later call `holdLastBook()`, which installs the inert #88 resume placeholder with `current.setMediaItem(...)`. - This happens asynchronously after the controller connection is accepted. 2. **Recent/resume library root** - `onGetLibraryRoot(... params.isRecent=true)` immediately returns `AutoLibrary.recentRoot()`. - That root is browsable; it is not itself the playable book. 3. **Recent/resume child** - If Gearhead asks for children of the recent root, `onGetChildren(RECENT_ROOT)` returns `resumeRow()`. - This is the playable/default resume row and can exist independently of whether the Player already holds the same book. 4. **Normal browse children** - Continue / Series / Authors eventually return playable book `MediaItem` rows. - These are browse identities, not necessarily the Player's current item. 5. **Playback-resumption metadata** - `onPlaybackResumption(isForPlayback=false)` returns one metadata-only resumable `MediaItem` when available. 6. **Playback-resumption queue** - `onPlaybackResumption(isForPlayback=true)` opens/resolves a fresh playable queue and returns the item Media3 will install/prepare/play. 7. **Controller selection** - `onAddMediaItems` / `onSetMediaItems` resolve Android Auto selections into the item(s) handed back to Media3. These are related but not one callback. A valid resume row can be handed to Android Auto while `player.currentMediaItem` is still empty, or the Player can be populated after Gearhead has already decided its initial surface. ### Concrete startup race already visible in the code `onPostConnect()` returns immediately and does: ``` scope.launch { ... AutoStartAction.None -> holdLastBook(current) } ``` At the same time, Gearhead is free to call `onGetLibraryRoot`, `onGetChildren`, resumption callbacks, and inspect the session/player state. Therefore the next diagnostic build must record the exact callback/event ordering with a monotonic timestamp. ## Required diagnostic: Android Auto startup handoff trace Create one short-lived **Auto startup trace id** for each Gearhead/automotive controller connection, e.g. `autoTrace=17`. Keep it alive through the initial startup/browse/resumption window. Every event below should log: - `autoTrace` - monotonic elapsed time from controller connect, preferably milliseconds - controller package/classification - callback/event name - current Player snapshot before the callback/action - item(s) requested - item(s) returned/installed - completion time for async callbacks ### Safe MediaItem fingerprint Do not dump private stream URLs or full server/library data. For every MediaItem use one compact fingerprint: - `kind`: holder / playable-book / browse-book / root / tab / series / author / profile / unknown - short deterministic media-id fingerprint (or existing public opaque id where safe) - `isPlayable` - `isBrowsable` - `resumePlaceholder=true/false` - owner-profile fingerprint - `hasUri=true/false` - URI class only: inert-placeholder / content / http(s) / none — **never the URI value** - `hasArtwork=true/false` - duration if known - current/start position when relevant This lets one trace prove that the same logical book flowed through the different Media3 surfaces without putting private titles or stream URLs into diagnostics. ### Events/callbacks to instrument #### Controller/session boundary **onConnect** - Player snapshot before accepting Gearhead: - mediaItemCount - current item fingerprint or none - currentMediaItemIndex - playbackState - playWhenReady - currentPosition - controller classification and granted commands. **onPostConnect** - entry snapshot; - chosen `AutoStartAction`; - whether holder/start-last-book work was launched; - log both **async start** and **async completion**; - Player snapshot after completion. This is important because current `onPostConnect` work is asynchronous and is a prime race candidate. #### Player item changes Instrument `Player.Listener.onMediaItemTransition` for this trace: - transition reason; - previous fingerprint if retained; - new fingerprint; - timeline count/index; - placeholder-vs-real; - position. Also log when #88 explicitly calls: - `current.setMediaItem(held.item, held.startPositionMs)`; - materialization replaces holder with the server-backed queue. #### Library root **onGetLibraryRoot** - `params.isRecent`; - Player snapshot at callback entry; - exact root fingerprint returned; - callback completion latency. #### Browse children **onGetChildren** - parent id/kind; - page/pageSize; - Player current item fingerprint at entry; - **all items in the returned page**, in order, using the safe fingerprint; - total child count and returned-page count; - callback completion latency. For `RECENT_ROOT` specifically, log: - resume candidate source: live/current, remembered-local, cached-server-progress, refreshed-server-progress, none; - returned child fingerprint(s). For `TAB_CONTINUE`, include the ordered playable item fingerprints so we can compare the resume/default candidate with the first Continue row. #### Get item **onGetItem** - asked fingerprint/media-id kind; - resolved item fingerprint or unresolved; - current Player fingerprint. #### Playback resumption **onPlaybackResumption(false)** - entry Player snapshot; - candidate source; - exact item fingerprint returned, or empty; - latency. **onPlaybackResumption(true)** - same, plus: - queue item fingerprint; - authoritative start position; - whether /play was opened; - result returned to Media3. #### Controller-set media The existing `logSelection` is useful but currently records only branch/kind/counts. Expand it for the startup trace to include: **onAddMediaItems** - every asked item fingerprint, in order; - every resolved/handed-back item fingerprint, in order. **onSetMediaItems** - every asked item fingerprint; - selected/resolved item fingerprint; - exact handed-back MediaItems list; - asked startIndex/startPosition; - returned startIndex/startPosition; - Player snapshot before resolution and after Media3 applies the result (via player transition log). ### Candidate-resolution trace Instrument #88's resolver as a separate decision line: `Resume candidate resolved source=<live|remembered|cached-progress|refreshed-progress|none> candidate=<fingerprint>` Include candidate rejection reasons where relevant: - finished; - inaccessible; - missing from active profile; - locked; - stale remembered id; - no synced progress; - refresh produced no candidate. This will distinguish **candidate selection failed** from **candidate selected but reached Android Auto too late**. ## What the physical trace must answer One cold Android Auto connection should let us reconstruct, in timestamp order: 1. when Gearhead connected; 2. whether Player already had an item; 3. which resume/default candidate BookWave knew at that moment; 4. whether Gearhead first requested recent root, normal root, resumption metadata, or something else; 5. every playable item returned to Gearhead and in what order; 6. when #88 installed the held Media3 item; 7. whether Gearhead had already completed its initial home/player construction before that install; 8. whether Media3 later notified Gearhead of the new current item; 9. whether a resume row and Player current item referred to the same logical book; 10. whether Android Auto ignored a correct item, or BookWave never handed it one in time. ### Example of the desired shape ``` autoTrace=17 +000ms onConnect playerItem=none count=0 autoTrace=17 +006ms onGetLibraryRoot recent=true returned=recent-root autoTrace=17 +011ms onPostConnect action=None async=started playerItem=none autoTrace=17 +020ms onGetChildren parent=recent returned=[book#A holder=false] autoTrace=17 +143ms resumeCandidate source=remembered candidate=book#A autoTrace=17 +147ms holdLastBook setMediaItem=book#A placeholder=true autoTrace=17 +149ms playerMediaItemTransition new=book#A placeholder=true autoTrace=17 +151ms onPostConnect async=complete playerItem=book#A ``` If Android Auto still shows no item with a trace like that, we then know the app *did* hand it the right book and the remaining question is Media3/session notification semantics. If instead `onGetChildren`/resumption returns empty before the candidate appears, the bug is BookWave's startup sequencing. ## Acceptance status #88 remains open. CI success for PR #90 is not physical acceptance. Before closing again, capture at least one real projected Android Auto cold/reconnect trace where the expected held/latest book is visible and correlate the displayed item to the exact MediaItem fingerprint BookWave handed to Media3/Gearhead.
Author
Owner

Diagnostics implementation staged — Android Auto Media3 startup handoff race

Implementation branch: mcp/issues-36-88-android-auto-diagnostics
Current head: 70f9811f7fd92770865ce061540f9c7a1a708ac4
Base: main@68ac79ace9f9d38d450458ad28a1ffe4d0b632af
Base relation at handoff: 0 behind main.

The updated diagnostics now record the startup race directly instead of inferring it from later browse/player behavior.

Correlated Android Auto startup trace

For a Gearhead/car connection, the trace records the order/timing of:

  • controller connection;
  • live Player state/current item at connection;
  • onPostConnect entry;
  • selected car policy;
  • async holder/playable installation start and completion;
  • current Media3 item transitions;
  • recent/normal library-root responses;
  • onGetChildren pages;
  • onGetItem;
  • search-result pages;
  • onPlaybackResumption(false/true);
  • onAddMediaItems;
  • onSetMediaItems;
  • the exact playable items returned/installed in each of those paths;
  • requested and returned start index/position where Media3 exposes them;
  • callback/async elapsed time.

If the local/cached resume resolver is empty and #88 falls through to the authenticated account refresh, the trace explicitly records that refresh and its duration.

Privacy-safe MediaItem fingerprint

Playable/current items are correlated without putting private media data in the event log. The fingerprint contains:

  • item kind (holder / playable book / browse kind);
  • media id as the existing redacted/hashed Identifier field;
  • playable / browsable flags;
  • resume-placeholder flag;
  • owner profile as a hashed Identifier;
  • URI presence and URI class only (inert-placeholder / http / content / file / data / none), never the URI;
  • artwork-present flag;
  • current/start position where relevant.

No book title, subtitle, server URL, stream URL, search query, or raw profile/media id is added to diagnostics.

Event-log filter

A dedicated Android Auto category chip is now available in the in-app Event Log. It isolates the correlated car/Auto trace, while relevant route/output recomputation is mirrored into the same category so the filtered view remains diagnostically complete.

Regression coverage was added for:

  • safe holder/playable MediaItem fingerprinting with Robolectric Android semantics;
  • Android Auto category filtering.

CI / PR state

No CI has been started.

No PR has been opened because creating one currently auto-runs the Quick PR gate. This preserves the owner's instruction to start CI manually.

#88 remains open pending a physical trace proving what Gearhead was handed versus what it actually displayed.

## Diagnostics implementation staged — Android Auto Media3 startup handoff race Implementation branch: `mcp/issues-36-88-android-auto-diagnostics` Current head: `70f9811f7fd92770865ce061540f9c7a1a708ac4` Base: `main@68ac79ace9f9d38d450458ad28a1ffe4d0b632af` Base relation at handoff: 0 behind main. The updated diagnostics now record the startup race directly instead of inferring it from later browse/player behavior. ### Correlated Android Auto startup trace For a Gearhead/car connection, the trace records the order/timing of: - controller connection; - live Player state/current item at connection; - `onPostConnect` entry; - selected car policy; - async holder/playable installation start and completion; - current Media3 item transitions; - recent/normal library-root responses; - `onGetChildren` pages; - `onGetItem`; - search-result pages; - `onPlaybackResumption(false/true)`; - `onAddMediaItems`; - `onSetMediaItems`; - the exact playable items returned/installed in each of those paths; - requested and returned start index/position where Media3 exposes them; - callback/async elapsed time. If the local/cached resume resolver is empty and #88 falls through to the authenticated account refresh, the trace explicitly records that refresh and its duration. ### Privacy-safe MediaItem fingerprint Playable/current items are correlated without putting private media data in the event log. The fingerprint contains: - item kind (holder / playable book / browse kind); - media id as the existing redacted/hashed Identifier field; - playable / browsable flags; - resume-placeholder flag; - owner profile as a hashed Identifier; - URI presence and URI **class** only (inert-placeholder / http / content / file / data / none), never the URI; - artwork-present flag; - current/start position where relevant. No book title, subtitle, server URL, stream URL, search query, or raw profile/media id is added to diagnostics. ### Event-log filter A dedicated **Android Auto** category chip is now available in the in-app Event Log. It isolates the correlated car/Auto trace, while relevant route/output recomputation is mirrored into the same category so the filtered view remains diagnostically complete. Regression coverage was added for: - safe holder/playable MediaItem fingerprinting with Robolectric Android semantics; - Android Auto category filtering. ### CI / PR state No CI has been started. No PR has been opened because creating one currently auto-runs the Quick PR gate. This preserves the owner's instruction to start CI manually. #88 remains open pending a physical trace proving what Gearhead was handed versus what it actually displayed.
Sign in to join this conversation.
No labels
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
alexander/Audiobookshelf-Manager-Claude#88
No description provided.