Skip to content

fix(reader): clear stale readAloudNextChapterProvider on external TTS stop - #281

Merged
github-actions[bot] merged 2 commits into
devfrom
fix/reader-vm-stale-read-aloud-provider
Aug 19, 2026
Merged

github-actions[bot] merged 2 commits into
devfrom
fix/reader-vm-stale-read-aloud-provider

Conversation

@libravault-pipeline-bot

@libravault-pipeline-bot libravault-pipeline-bot Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Summary

ReaderViewModel.readAloudNextChapterProvider — the bookkeeping advanceOnCompletion() uses to know a Read Aloud session is active — was previously cleared only by ReaderViewModel.stopReadAloud(). PR #277's TtsAudioFocusManager makes each TTS engine call stop() on itself directly when it loses audio focus (e.g. an audiobook resumed from the lockscreen while Read Aloud is speaking), which bypasses stopReadAloud() entirely. That left the provider set (non-null) even though the engine had gone IDLE.

Currently harmless (no other production caller shares the singleton TtsEngineProvider engine yet), but the moment one does — a Settings voice-preview feature, or Markdown wiring in #276 — a stale provider left over from an externally-stopped session could hijack that unrelated speak()'s natural completion into "advance the book".

Approach (revised after QA round 1)

The first version of this fix watched readAloudState for a PLAYING/PAUSED -> IDLE edge to clear the provider. QA correctly found this races advanceOnCompletion(): both AndroidTtsEngine.speakNext() and PocketTtsEngine's completion callback set state to IDLE immediately before emitting completionEvent, from the same call — so a natural chapter-to-chapter advance produces the exact same IDLE edge as an external stop. The edge-triggered collector nulled the provider before the completionEvent collector read it, so Read Aloud stopped after the first chapter every time.

Fixed properly this round: TtsEngine now exposes a new stopEvent: SharedFlow<Unit>, emitted only from stop() in both AndroidTtsEngine and PocketTtsEngine. Natural completion never calls stop() in either engine — it's a fundamentally distinct code path from speakNext()/the completion callback — so stopEvent and completionEvent are mutually exclusive at the source, with no ordering/race to reason about. ReaderViewModel.init now clears readAloudNextChapterProvider on stopEvent instead of diffing state.

Testing

  • Added stop emits stopEvent to both AndroidTtsEngineTest and PocketTtsEngineTest, plus losing audio focus while resumed emits stopEvent to PocketTtsEngineTest (mirrors the existing losing audio focus while resumed stops the engine test, which covers the exact TtsAudioFocusManager path from [enhancement] ReaderViewModel.readAloudNextChapterProvider can go stale when TtsAudioFocusManager stops the engine externally #280).
  • Updated external stop via audio focus loss clears the next-chapter provider in ReaderViewModelTest to emit stopEvent alongside the IDLE state transition, matching what the real engines' stop() now does.
  • Added natural completion driven the way production engines actually sequence it still advances — this is QA's exact repro (drive state PLAYING -> IDLE then emit completionEvent, without stopReadAloud()), now asserting the chapter does advance. This is the regression test for QA round 1's finding.
  • ./gradlew :core:tts:testDebugUnitTest :feature:reader:testDebugUnitTest :feature:settings:testFdroidDebugUnitTest — BUILD SUCCESSFUL.
  • ./gradlew testDebugUnitTest testFdroidDebugUnitTest testPlayDebugUnitTest --continue (full JVM suite, both flavors) — BUILD SUCCESSFUL.

Scope / risk

Touches core/tts (interface + both engine implementations) in addition to feature/reader, since a race-free fix needs the distinguishing signal to come from the engine, not be inferred from state alone in the ViewModel. Neither core/tts nor feature/reader is in agent-policy.yml's sensitive_paths — expect risk:low, but flagging the wider blast radius explicitly per policy since it's larger than the original PR's stated scope.

Closes #280

@github-actions github-actions Bot added the risk:low Principal review classified this PR as low risk label Aug 18, 2026
@libravault-pipeline-bot libravault-pipeline-bot Bot added the status:needs-qa PR open, awaiting qa-agent verification label Aug 18, 2026
@claude

claude Bot commented Aug 18, 2026

Copy link
Copy Markdown
Contributor

QA verification — PR #281 vs issue #280

Acceptance criteria (bug report — issue has no explicit checklist, so the bar is "the repro no longer reproduces, with a regression test that proves it"):

  • ✅ Repro scenario (external TtsAudioFocusManager → engine.stop() bypassing stopReadAloud()) is fixed: readAloudNextChapterProvider is now cleared on a PLAYING/PAUSED → IDLE edge, and the new test external stop via audio focus loss clears the next-chapter provider passes.
  • ❌ The fix introduces a critical regression that breaks the core Read Aloud feature it's meant to protect.

What I ran

  • ./gradlew :feature:reader:testDebugUnitTest --tests "xyz.libravault.feature.reader.ReaderViewModelTest" on the PR as-is: BUILD SUCCESSFUL, all tests pass (matches the PR's claim).
  • Per checklist item 3 ("does the test exercise the real component or does it test past the broken part?"), I checked how production TTS engines actually transition state on natural completion, not just external stop. In both AndroidTtsEngine.speakNext() (core/tts/.../AndroidTtsEngine.kt:157-158) and PocketTtsEngine (core/tts/.../PocketTtsEngine.kt:115-116), a natural utterance completion does:
    _state.value = _state.value.copy(status = TtsStatus.IDLE)
    _completionEvent.tryEmit(Unit)
    i.e. the same PLAYING → IDLE transition this PR's new collector watches for happens on every chapter-to-chapter advance, back-to-back with the completionEvent that advanceOnCompletion() listens to — not only on the external-stop path this PR targets.
  • The PR's own test fixture decouples these two flows entirely (ttsEngineStateFlow and ttsCompletionEvent are independent MutableStateFlow/MutableSharedFlow set manually in tests — see ReaderViewModelTest.kt:105-107), so none of the existing tests, including the new regression test, ever drive them together the way production does. The existing completion event advances to the next chapter test (line 456) never touches ttsEngineStateFlow at all, so it stays at the default TtsStatus.UNINITIALIZED and the new collector never engages — this is exactly the "tests mocked past the broken part" failure mode called out in this project's history.
  • I verified this concretely: I temporarily added a test that drives state and completion event in the same order production code does (PLAYING → IDLE → completionEvent.emit), on top of the unmodified PR code:
    ttsEngineStateFlow.value = TtsState(status = TtsStatus.PLAYING)
    ttsEngineStateFlow.value = TtsState(status = TtsStatus.IDLE)
    ttsCompletionEvent.emit(Unit)
    io.mockk.coVerify { fakeTtsEngine.speak("Chapter two.") }
    This fails — speak("Chapter two.") is never called. I reverted this probe afterward (git checkout --); it is not part of any commit.

Root cause

Both viewModelScope.launch collectors (the pre-existing completionEvent collector and the new readAloudState collector added by this PR) observe hot flows updated synchronously, back-to-back, from the same call in the real engines. Because the state mutation (_state.value = IDLE) happens before the completionEvent emission in the source, the new collector's continuation is scheduled/resumed before the completion collector's, so readAloudNextChapterProvider is nulled out before advanceOnCompletion() reads it — turning every natural chapter transition into a silent stop instead of an advance.

Net effect: as written, this PR makes Read Aloud stop after the very first chapter, every time, which is a much worse regression than the stale-provider bug it fixes (which was explicitly "currently harmless" per the issue).

Suggested direction for the dev agent

The edge-trigger needs to distinguish "engine went IDLE because advanceOnCompletion is about to (or does) call speak() again" from "engine went IDLE and nothing else is coming." Two options worth considering: (a) only clear the provider on the IDLE edge if completionEvent did not fire in the same tick / a subsequent speak() isn't already in flight, or (b) have TtsAudioFocusManager's stop path signal an explicit "external stop" distinct from natural completion (e.g. a dedicated reason/event) rather than relying on generic IDLE status, since natural completion and external stop currently produce identical signals (status = IDLE) that this VM-level collector can't tell apart.

AGENTS.md conventions

Branch naming and commit hygiene look fine; no hardcoded versions introduced.

QA verdict: FAIL

@github-actions github-actions Bot removed the status:needs-qa PR open, awaiting qa-agent verification label Aug 18, 2026
@libravault-pipeline-bot libravault-pipeline-bot Bot added the status:in-progress Dev agent is actively implementing label Aug 18, 2026
@github-actions

Copy link
Copy Markdown
Contributor
QA failed its first round — routing back to the dev agent for one automated retry.

@github-actions

Copy link
Copy Markdown
Contributor

📱 iOS Build Status: PASSED

✅ iOS Simulator Build & Unit Tests - success
✅ Android Core Modules - success

iOS UI tests run in a separate, informational job and are not reflected above — check "iOS UI Tests (informational)" for those.

View run details

github-actions Bot added a commit that referenced this pull request Aug 18, 2026
… a racy IDLE edge

QA on PR #281 found that watching `readAloudState` for a PLAYING/PAUSED -> IDLE
edge to clear readAloudNextChapterProvider also fires on every natural
chapter-to-chapter advance (both engines set state IDLE immediately before
emitting completionEvent from the same call), racing the completionEvent
collector and breaking Read Aloud after the first chapter.

TtsEngine now exposes stopEvent, emitted only from stop() - a call natural
completion never makes in either engine, so it can't collide with
completionEvent. ReaderViewModel clears the provider on stopEvent instead.
@github-actions

Copy link
Copy Markdown
Contributor

Addressed the QA round-1 finding directly.

Root cause of the regression QA found: the previous fix cleared readAloudNextChapterProvider on a readAloudState PLAYING/PAUSED -> IDLE edge. Both AndroidTtsEngine and PocketTtsEngine set state to IDLE immediately before emitting completionEvent on natural completion (same call, no intervening suspension) — so that edge fires on every chapter advance, not just an external stop, and racing against the completionEvent collector meant the provider was nulled before advanceOnCompletion() could read it.

Fix: added TtsEngine.stopEvent: SharedFlow<Unit>, emitted only from stop() (both engines). Natural completion (speakNext() / the Pocket completion callback) never calls stop() — it's a separate code path entirely — so stopEvent and completionEvent can't collide, no timing/ordering assumptions needed. ReaderViewModel now clears the provider on stopEvent instead of diffing state.

Added the exact repro from your report as a new test (natural completion driven the way production engines actually sequence it still advances in ReaderViewModelTest) — drives state PLAYING -> IDLE then emits completionEvent, asserts the chapter still advances. Also added stopEvent-emission coverage to both engine test suites, including the TtsAudioFocusManager focus-loss path specifically.

Full JVM suite (testDebugUnitTest testFdroidDebugUnitTest testPlayDebugUnitTest --continue) is green. PR description updated with the revised approach.

@github-actions github-actions Bot removed the status:in-progress Dev agent is actively implementing label Aug 18, 2026
@libravault-pipeline-bot libravault-pipeline-bot Bot added the status:needs-qa PR open, awaiting qa-agent verification label Aug 18, 2026
@claude

claude Bot commented Aug 18, 2026

Copy link
Copy Markdown
Contributor

QA verification — PR #281 vs issue #280

Issue #280 is a bug report (no acceptance checklist), whose "suggested fix" was explicitly revised mid-PR after QA round 1 found a race. Checklist derived from the issue + the PR's own stated regression:

  • ✅ readAloudNextChapterProvider is cleared when the engine is stopped externally (e.g. TtsAudioFocusManager calling stop() directly on audio-focus loss, bypassing stopReadAloud()). Verified: TtsEngine.stopEvent is now emitted only from stop() in both AndroidTtsEngine and PocketTtsEngine (confirmed by reading both files), and ReaderViewModel.init nulls the provider on that event. Covered by ReaderViewModelTest > external stop via audio focus loss clears the next-chapter provider, plus AndroidTtsEngineTest/PocketTtsEngineTest > stop emits stopEvent and PocketTtsEngineTest > losing audio focus while resumed emits stopEvent.
  • ✅ Round-1 regression (QA-found race) is actually fixed, not just claimed fixed. Round 1 keyed the clear off a PLAYING/PAUSED -> IDLE edge on state, which also fires on every natural chapter completion (both engines flip state to IDLE immediately before emitting completionEvent, from the same call) — breaking Read Aloud after chapter 1. I independently verified this: I temporarily swapped ReaderViewModel.kt back to the round-1 commit (bb62c7b) and re-ran ReaderViewModelTest — the new test natural completion driven the way production engines actually sequence it still advances fails against that old code (1/32 tests failed, exactly that one), and passes against the current fix. This is a real regression test, not a trivially-green one.
  • ✅ stopEvent and completionEvent are mutually exclusive at the source — confirmed by reading AndroidTtsEngine.speakNext()/onDone and PocketTtsEngine.speak()'s completion callback: neither calls stop() on natural completion, only stop() itself emits stopEvent.
  • ✅ No relaxed-mock-hides-the-bug gap: ReaderViewModelTest uses real MutableSharedFlow/MutableStateFlow instances wired through a relaxed = true mock engine (only the flow properties are stubbed to real flows), so the collectors under test observe real emission ordering rather than a mock default.
  • ✅ No other production caller of TtsEngine/TtsEngineProvider yet (checked feature/settings and repo-wide) — matches the issue's stated "currently harmless" framing; the new interface member doesn't silently change behavior elsewhere.
  • ✅ AGENTS.md conventions: tests shipped alongside the fix (required for non-trivial changes), branch name fix/reader-vm-stale-read-aloud-provider follows convention, commits use conventional-commit messages, no hardcoded versions.

What I ran

  • ./gradlew :core:tts:testDebugUnitTest :feature:reader:testDebugUnitTest --continue → BUILD SUCCESSFUL. Confirmed via XML results: ReaderViewModelTest 32/32, AndroidTtsEngineTest 14/14, PocketTtsEngineTest 23/23, all other core:tts suites 0 failures.
  • ./gradlew testDebugUnitTest --continue (full JVM suite, all modules) → BUILD SUCCESSFUL, 438 tasks, no failures anywhere else in the tree.
  • Manual regression-proof: reverted ReaderViewModel.kt to the round-1 commit content, re-ran ReaderViewModelTest → 1 failure (natural completion driven the way production engines actually sequence it still advances), confirming the test is a real guard against the exact bug QA round 1 found. Restored the fixed file afterward (working tree is clean, no diff left behind).

No gaps found.

QA verdict: PASS

@github-actions github-actions Bot removed the status:needs-qa PR open, awaiting qa-agent verification label Aug 18, 2026
@libravault-pipeline-bot libravault-pipeline-bot Bot added the status:needs-review QA passed, awaiting principal-review-agent label Aug 18, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Principal review — PR #281

Verdict: auto-merge (risk:low confirmed, no CONFIRMED findings)

Risk classification sanity check

The risk:low label was applied at 15:10:29Z, right after the first commit
(bb62c7b) — but the PR's second commit (2159c4c, the actual race fix) landed
at 15:39:32Z, after the label was set, so the label was stale at review
time. Re-ran classify_pr_risk.py myself against origin/dev...origin/fix/reader-vm-stale-read-aloud-provider:

diff is 138 changed lines and touches no sensitive path
risk:low

Same conclusion holds with the final commit included, so the label (though
stale) was still correct.

Correctness review

Read the full diff plus the surrounding code (not just the hunks):
ReaderViewModel.kt's init block, stopReadAloud/startReadAloud/
advanceOnCompletion, both AndroidTtsEngine/PocketTtsEngine implementations,
and TtsEngineProvider.switchEngine.

  • Verified the PR's central claim directly in the engine sources: stop() is
    the only call site that emits stopEvent in either engine, and natural
    completion (speakNext() / the sherpa-onnx completion callback) only ever
    emits completionEvent, never calls this.stop() (AndroidTtsEngine.speak()
    calls engine.stop() — the raw TextToSpeech object, a different stop
    entirely, due to parameter shadowing). So the two events are genuinely
    mutually exclusive at the source, not just by convention — the race QA
    caught in round 1 is structurally closed, not just less likely.
  • Traced TtsEngineProvider.switchEngine() (engine-swap on a Settings change
    mid-session): oldEngine.stop() runs, then _engine.value = newEngine.
    Since the stopEvent collector is flatMapLatest'd off _engine, there's
    a theoretical window where the old engine's buffered stopEvent could be
    dropped if the child collector is cancelled before it's dispatched. In
    practice this collapses to deterministic, synchronous ordering because
    viewModelScope runs on Dispatchers.Main.immediate and both stop() call
    sites (stopReadAloud(), and AudioManager.OnAudioFocusChangeListener,
    which Android also invokes on the main thread) are themselves on the main
    thread — not flagging this, since it mirrors the pre-existing
    completionEvent/flatMapLatest pattern from feat(reader): wire EPUB Read Aloud mini-bar to TtsEngineProvider #277 rather than introducing
    a new risk shape.
  • No issue with stopReadAloud() re-nulling an already-null provider, or with
    startReadAloud() racing a stale buffered stopEvent from a previous
    session, for the same main-thread-synchronous reason above.

Test verification (didn't take the PR's numbers at face value)

Ran the exact modules myself rather than trusting the PR body's reported
BUILD SUCCESSFUL:

./gradlew :core:tts:testDebugUnitTest :feature:reader:testDebugUnitTest
BUILD SUCCESSFUL — core:tts 111/111, feature:reader all green

Then specifically verified the AGENTS.md "prove a new test can fail" rule for
the regression guard: reverted just the new stopEvent-collector block from
ReaderViewModel.kt and reran ReaderViewModelTest —
external stop via audio focus loss clears the next-chapter provider failed
as expected (AssertionError at line 520), 32/33 other tests unaffected.
Restored the file and reran clean — green again. The regression test is real,
not a test that would pass on the pre-fix code.

Process note for a maintainer (not a code defect, not blocking)

GitHub's own CI never completed on the final commit (2159c4c): JVM Tests,
iOS App Build & Test, and (initially) UI Tests (Emulator) all show
action_required for that SHA — https://github.com/LibraVault/reader/actions/runs/32155802483
— meaning they never actually executed, they didn't fail. The first commit's
identical pull_request trigger ran and passed normally
(https://github.com/LibraVault/reader/actions/runs/32152813987), so this isn't
a fork/first-contributor approval gate — something about re-triggering on the
second push into this PR is landing in action_required instead of running.
I saw the same action_required-on-second-push pattern on two unrelated,
concurrently open PRs today (fix/keystore-hardware-keywrap-androidtest,
test/ios-pocket-tts-engine-coverage), so this looks systemic to the repo's
Actions config/history rather than specific to this PR — worth a maintainer
look independent of this merge. I'm not blocking this PR on it because I
substituted direct verification (above) for the JVM-testable slice, which is
100% of what this diff touches (no iOS or Compose/UI files in the diff), and
the auto-merge workflow's own CI-wait step already treats action_required as
non-success and will fall back to status:needs-human-merge on its own if CI
doesn't resolve within 20 minutes.

Policy checks

@github-actions github-actions Bot added status:needs-info Dev/QA agent needs more detail before proceeding and removed status:needs-review QA passed, awaiting principal-review-agent labels Aug 18, 2026
@github-actions

Copy link
Copy Markdown
Contributor

principal-review's run crashed or exhausted its turn budget (see the workflow run) before reaching a verdict — routed to a human instead of silently leaving this on status:needs-review. Needs a human to either re-run review (re-add status:needs-review) or review this PR directly.

Copy link
Copy Markdown
Collaborator

Automated pipeline health check: Diagnosed the crash behind the comment above. Doesn't clear this routine's self-heal bar — flagging for a human rather than requeuing.

Pulled the job log for run 32157408830 (principal-review.yml, job review):

This PR touches no sensitive path (core/tts, feature/reader only), so a human re-adding status:needs-review for a clean re-run is low-risk — or they can just act on the verdict already posted above directly, since it was fully written out before the cutoff.

Recommend: raise principal-review.yml's turn cap the same way dev-agent.yml's was (#259/#267, now 90) — 40 is now confirmed too low for substantial reviews on this repo, independently on at least 4 PRs in one day (#264, #279, #281, and #279's own comment references a 3rd).


Generated by Claude Code

libravault-xyz added a commit that referenced this pull request Aug 19, 2026
…valid verdict on crash (#298)

Closes #297. --max-turns 40 was too tight — the agent's last action is
writing principal-verdict.txt, so hitting the cap one turn later is
common (PR #281's job log: num_turns 41 vs cap 40). At least 4 same-day
crashes (PRs #257/#264/#281, plus one flagged earlier on #279) threw
away a verdict the agent had already written, routing good work to
status:needs-info instead of using it.

Raised the cap to 65, and changed the crash-handling branch in
'Advance PR based on review verdict' to check principal-verdict.txt
even when the agent step reports failure — only routes to
status:needs-info when there's truly no usable verdict on disk.

Sensitive path (.github/workflows/**) — opening as a direct
human-authored PR for that reason.
github-actions Bot and others added 2 commits August 19, 2026 08:12
… stop

TtsAudioFocusManager can call TtsEngine.stop() directly on audio-focus
loss (e.g. an audiobook resumed from the lockscreen while Read Aloud is
speaking), bypassing ReaderViewModel.stopReadAloud() entirely. That left
readAloudNextChapterProvider set after such a stop even though the engine
had gone IDLE, so a later, unrelated completion event sharing the same
singleton TtsEngineProvider engine could be misread as "advance the book".

Observe readAloudState and clear the provider on any PLAYING/PAUSED ->
IDLE transition, not just via stopReadAloud(). Edge-triggered rather than
level-triggered so it doesn't race the provider assignment in
startReadAloud against the engine's own resting IDLE state before
speak() has run.

Closes #280

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
… a racy IDLE edge

QA on PR #281 found that watching `readAloudState` for a PLAYING/PAUSED -> IDLE
edge to clear readAloudNextChapterProvider also fires on every natural
chapter-to-chapter advance (both engines set state IDLE immediately before
emitting completionEvent from the same call), racing the completionEvent
collector and breaking Read Aloud after the first chapter.

TtsEngine now exposes stopEvent, emitted only from stop() - a call natural
completion never makes in either engine, so it can't collide with
completionEvent. ReaderViewModel clears the provider on stopEvent instead.
@libravault-xyz
libravault-xyz force-pushed the fix/reader-vm-stale-read-aloud-provider branch from 2159c4c to 9f886cf Compare August 19, 2026 08:13
@libravault-xyz

Copy link
Copy Markdown
Collaborator

Rebased onto dev (was stale across several workflow files, including principal-review.yml itself — which is why the previous review round's verdict got silently discarded, see #297/#298). Re-applying status:needs-review to get a fresh review under the fixed turn-cap/crash-handling logic.

@libravault-xyz libravault-xyz added status:needs-review QA passed, awaiting principal-review-agent and removed status:needs-info Dev/QA agent needs more detail before proceeding labels Aug 19, 2026
@github-actions

Copy link
Copy Markdown
Contributor

📱 iOS Build Status: PASSED

✅ iOS Simulator Build & Unit Tests - success
✅ Android Core Modules - success

iOS UI tests run in a separate, informational job and are not reflected above — check "iOS UI Tests (informational)" for those.

View run details

@github-actions

Copy link
Copy Markdown
Contributor

Principal review — PR #281

Verdict: auto-merge (risk:low, no CONFIRMED findings)

What I verified directly (not just read/trusted)

  • Risk label freshness: the risk:low label was set on 2026-08-18T15:10:29Z, right after the first commit (287f67e). The second commit (9f886cf, the reworked fix) landed later that day and the label was never reapplied. Re-ran .github/scripts/classify_pr_risk.py origin/dev origin/fix/reader-vm-stale-read-aloud-provider myself against the current head — still risk:low (138 changed lines, no sensitive-path match). Label is stale-but-correct.
  • Sensitive paths: none of the 7 changed files (core/tts/**, feature/reader/**) match any agent-policy.yml glob. No new networking calls introduced anywhere in the diff.
  • Read the full diff, not the summary — core/tts/TtsEngine.kt/AndroidTtsEngine.kt/PocketTtsEngine.kt, feature/reader/ReaderViewModel.kt, and all four test files.
  • Core correctness claim ("stop() and natural completion are mutually exclusive, so stopEvent can't race completionEvent"): confirmed by reading both engines. AndroidTtsEngine.speak() calls the local TextToSpeech.stop() (the Android object), never this.stop() — so _stopEvent is never emitted from the natural-completion path. PocketTtsEngine.speak() never calls this.stop() either. The only callers of TtsEngine.stop() are ReaderViewModel.stopReadAloud(), the audio-focus-loss callback in each engine's own speak()/resume(), and TtsEngineProvider.switchEngine() (which stops the outgoing engine when the user changes TTS engine in Settings — a genuinely-correct extra case for clearing the stale provider, not a bug).
  • Ran the actual test suites (this box has JDK 17 and network access for Gradle):
    • :core:tts:testDebugUnitTest :feature:reader:testDebugUnitTest → BUILD SUCCESSFUL; confirmed via the JUnit XML reports (not just exit code) that stop emits stopEvent, losing audio focus while resumed emits stopEvent, external stop via audio focus loss clears the next-chapter provider, and natural completion driven the way production engines actually sequence it still advances all ran and passed (0 failures/errors across all three suites).
    • Full JVM suite (testDebugUnitTest testFdroidDebugUnitTest testPlayDebugUnitTest --continue) → clean, 112 updated test-result XMLs, zero failures.
    • CI's own "Unit & Integration Tests (JVM)" check on this PR is independently green, consistent with the local run.
  • AGENTS.md's "prove a new test can fail" rule — the PR body doesn't document doing this, so I did it myself: temporarily removed the new stopEvent collector from ReaderViewModel.init and reran ReaderViewModelTest. Exactly 1 of 32 tests failed — external stop via audio focus loss clears the next-chapter provider, with the precise expected failure (speak("Chapter two.") called when it shouldn't have been, i.e. the stale-provider bug reproducing). Restored the file afterward; git diff against the PR head is empty, so the repo is back to exactly what's on the branch.

Design note (not a finding)

Keying the clear on stopEvent rather than the previous state edge is the right fix for the race QA caught in round 1 — stopEvent and completionEvent are emitted from genuinely disjoint code paths in both engines, so there's no ordering to reason about between the two viewModelScope.launch collectors in init. The TtsEngineProvider.switchEngine() interaction (stopping the outgoing engine also clears readAloudNextChapterProvider) is a reasonable side effect, not a regression — if the user switches Read Aloud's TTS engine mid-book, ending that session is correct.

No correctness, simplification, or efficiency findings. No sensitive paths, no new dependencies, tests are at the right level (pure JVM, matching AGENTS.md's test-type table) and were shown to actually catch the regression they claim to guard.

@github-actions github-actions Bot added status:approved-auto-merge Principal review passed, risk:low — will auto-merge and removed status:needs-review QA passed, awaiting principal-review-agent labels Aug 19, 2026
@github-actions
github-actions Bot merged commit 331d22d into dev Aug 19, 2026
10 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk:low Principal review classified this PR as low risk status:approved-auto-merge Principal review passed, risk:low — will auto-merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[enhancement] ReaderViewModel.readAloudNextChapterProvider can go stale when TtsAudioFocusManager stops the engine externally

1 participant