Android Auto should restore the latest played book into an idle Media3 session #88
Loading…
Reference in a new issue
No description provided.
Delete branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
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:
This issue is the staging area for the investigation and eventual repair.
Investigation baseline:
main=ca080a875f95e7e50a3944e1810cf9c76194c167on 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 andMediaLibrarySession, but does not install a media item.Relevant code:
playback/.../PlaybackService.ktaround 300–374MediaLibrarySession.Builder(this, sessionPlayer, LibraryCallback())So a fresh service has no
currentMediaItemuntil some later path loads one.2. A live held book is already preserved
LibraryCallback.onPostConnect()exits immediately whencurrent.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 andonDestroy()releases both the session and player so a stale in-memory item cannot later be resumed accidentally.Relevant code:
PlaybackService.ktaround 473–517This 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 playArmOnly/Ask→ open last book and prepare it pausedNever→ do nothingstartLastBook()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:
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)auto.lastPlayed()onPlaybackResumption(isForPlayback = false)auto.resumeItem()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_NONEshould 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 onlyCurrent 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
nullto 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
SyncAccountUseCaseperforms the cheap authorize/account refresh and writes every server listening position into Room, includingupdatedAt.This already handles “book played on another device”.
B. Listening sessions
GET /api/me/listening-sessionsis 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:
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
onPlaybackResumptioneach infer “last book” differently.Recommended precedence:
updatedAt.Important implementation boundary
Do not solve this by keeping
PlaybackServicealive forever.Also avoid opening a remote
/playsession merely to discover/display metadata unless Media3 truly requires a prepared playable item for the car surface. Opening/playhas server/session side effects and should remain as close as possible to actual arming/playback intent.The implementation should explicitly separate:
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 freshopenQueue()before audio starts.Device policy semantics to preserve
This repair must not accidentally turn
NeverintoArmOnlyorArmOnlyintoAutoPlay.The final implementation should make the distinction explicit in tests:
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:
AutoLibrary.lastPlayed()/resumeItem()PlaybackService.LibraryCallback.onPlaybackResumption()PlaybackService.LibraryCallback.onPostConnect()SessionRestorer.restoreActiveSession()Avoid making the Android Auto browse tree itself the owner of this state; #65 should remain browse/presentation IA.
Acceptance criteria
DevicePolicy.Never,ArmOnly,Ask, andAutoPlayretain their audio-start semantics.onPlaybackResumption(false)remains fast and locally satisfiable; it does not require network access during boot/system metadata probing.Related
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
AutoLibraryalready has two different definitions of “what should I continue?”:resumeRow()/resumeItem()/lastPlayed()uses onlyRememberedBookRepository.continueRows()and empty voice search useHomeShelves.continueListening.HomeShelves.continueListeningis already:progress.updatedAtnewest first;SyncAccountUseCaseand 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:
HomeShelves.continueListeningbook.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.continueListeningalready pins the predicate/order in unit tests.Fresh-network case is still separate
SyncAccountUseCaseperforms the cheap account refresh and writes every server position into Room.ForegroundRealtimeSyncCoordinatorlaunches that reconciliation whenever the app becomes foreground authority.However:
ShelfPlayerApplication.onCreate();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:One more place that must change with the candidate semantics
AutoLibrary.profileBoundaryCounts()currently reportsRECENT_ROOTchild 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:
continueListening.firstOrNull());resumeRow/resumeItem,onPlaybackResumption, car empty-session restoration, startup restore, and recent-root count;onPlaybackResumption(false)fast/local-only for boot/SystemUI metadata probes;This should be tested specifically with:
CI failure investigation — run #273 / failed HEAD
728477d22f42dba4da047631f4404aa17fd1eab4Forgejo 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:343usedUri.parse(RESUME_PLACEHOLDER_URI)while Android KTX is already present.Repair:
2467444— usesRESUME_PLACEHOLDER_URI.toUri().This same lint error appeared under both
:playback:lintDebugand: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 positionRoot cause is the test environment, not the production holder guard:
android.os.Bundle.putBoolean(...);Bundlemutation semantics here, so the resume-placeholder bit was not reliably observed;Repair:
f9e4c41— runs this Bundle-backed test class withRobolectricTestRunner, preserving the production-like Bundle semantics the assertion actually depends on.Workflow/reporting observation
Run #273 did a useful
--continuestyle 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:
UseKtxfinding under “Compiler / build errors” as well;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 currentmainand 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 repair verification — run #274
The repaired PR head is now:
f9e4c41718d0334b50a15cac80e5d904e8f02cdcExact-head Forgejo PR verification run #274 completed successfully.
Result:
verifyDebug: PASSBookWave / PR verificationcommit status: SUCCESSThe full Gradle verification reported:
BUILD SUCCESSFUL in 5m 13s1121 actionable tasks: 506 executed, 157 from cache, 458 up-to-dateNo 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
UseKtxAndroid 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.Implementation + CI staging update
PR #90 implements this issue on
mcp/issue-88-android-auto-held-resume.Verified implementation head:
f9e4c41718d0334b50a15cac80e5d904e8f02cdcBase:
main@88ae231ddc01897d83e24968bed5443ea861aeddForgejo Actions: run #274 — PASS
Commit status:
BookWave / PR verification— successPR readiness: mergeable, 0 behind main, no CI blockers.
Implemented behavior:
/play, prepare, or autoplay;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:
This issue remains the acceptance staging area until that physical evidence is recorded.
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:
Live Player / MediaSession current item
player.currentMediaItem/ timeline is what the playback surface can treat as the current item.onPostConnect()currently launches a coroutine and may later callholdLastBook(), which installs the inert #88 resume placeholder withcurrent.setMediaItem(...).Recent/resume library root
onGetLibraryRoot(... params.isRecent=true)immediately returnsAutoLibrary.recentRoot().Recent/resume child
onGetChildren(RECENT_ROOT)returnsresumeRow().Normal browse children
MediaItemrows.Playback-resumption metadata
onPlaybackResumption(isForPlayback=false)returns one metadata-only resumableMediaItemwhen available.Playback-resumption queue
onPlaybackResumption(isForPlayback=true)opens/resolves a fresh playable queue and returns the item Media3 will install/prepare/play.Controller selection
onAddMediaItems/onSetMediaItemsresolve 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.currentMediaItemis 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: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:
autoTraceSafe 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 / unknownisPlayableisBrowsableresumePlaceholder=true/falsehasUri=true/falsehasArtwork=true/falseThis 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
onPostConnect
AutoStartAction;This is important because current
onPostConnectwork is asynchronous and is a prime race candidate.Player item changes
Instrument
Player.Listener.onMediaItemTransitionfor this trace:Also log when #88 explicitly calls:
current.setMediaItem(held.item, held.startPositionMs);Library root
onGetLibraryRoot
params.isRecent;Browse children
onGetChildren
For
RECENT_ROOTspecifically, log: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
Playback resumption
onPlaybackResumption(false)
onPlaybackResumption(true)
Controller-set media
The existing
logSelectionis useful but currently records only branch/kind/counts. Expand it for the startup trace to include:onAddMediaItems
onSetMediaItems
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:
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:
Example of the desired shape
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.
Diagnostics implementation staged — Android Auto Media3 startup handoff race
Implementation branch:
mcp/issues-36-88-android-auto-diagnosticsCurrent head:
70f9811f7fd92770865ce061540f9c7a1a708ac4Base:
main@68ac79ace9f9d38d450458ad28a1ffe4d0b632afBase 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:
onPostConnectentry;onGetChildrenpages;onGetItem;onPlaybackResumption(false/true);onAddMediaItems;onSetMediaItems;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:
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:
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.