From 50e1a2f2bc64462b410365d6540d9de948091302 Mon Sep 17 00:00:00 2001 From: LibraVault Date: Sun, 23 Aug 2026 14:04:24 +0000 Subject: [PATCH 1/2] =?UTF-8?q?feat(android):=20core:cloudtts=20engine=20w?= =?UTF-8?q?iring=20=E2=80=94=20makes=20Cloud=20TTS=20reachable=20(#451)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR 3 of 4 for Android. Wires CloudTtsEngine into core:tts's TtsEngineFactory via Dagger multibinding, and implements real audio playback of vendor responses. This is the first PR where the feature becomes reachable at runtime (once :app is wired in — see "Verification caveat" below). - TtsEngineFactory: refactored from a plain `when` over two constructor- injected concrete engines to Map> multibinding. New TtsEngineTypeKey (@MapKey) + TtsEngineType.CLOUD. core:tts never gains a compile-time dependency on core:cloudtts — its own (unflavored) Hilt module contributes the CLOUD entry to the SAME map from outside core:tts, assembled at :app's SingletonComponent. Rejected alternative (documented in TtsEngineTypeKey's doc): giving core:tts its own flavor dimension so it could depend on core:cloudtts directly — would force feature:reader to gain flavor dimensions it has no other reason to need. - CloudTtsEngine: TtsEngine conformer. Re-checks CloudTtsGate before EVERY chunk, not just once — a lapsed subscription or revoked consent stops new cloud calls immediately, mid-utterance. Falls back to the on-device engine (TtsEngineType.ANDROID, resolved from the SAME multibinding map this class is itself bound into — no separate DI qualifier needed) on gate failure, missing provider/voice selection, missing credentials, or any HTTP/playback failure — and forwards the fallback engine's state/completion/stop events into its own flows for as long as fallback stays active, so a caller observing this engine doesn't see stale status. - CloudPlayback: new interface + MediaPlayerCloudPlayback real impl. Vendor responses are already-encoded audio (mp3), unlike core:tts's PocketPlayback (raw PCM over AudioTrack) — wraps MediaPlayer, fed via MediaDataSource (no temp file, audio never touches disk). - TtsPreferences: added selectedCloudProviderFlow/setSelectedCloudProvider — stored as a raw CloudProviderId.name string, not the type itself, for the same core:tts/core:cloudtts decoupling reason as TtsEngineTypeKey. Reuses the existing selectedVoiceFlow for the cloud voice ID. Testing: 182 tests total (up from 103), all passing — ./gradlew :core:tts:testDebugUnitTest :core:cloudtts:testPlayDebugUnitTest :core:cloudtts:testFdroidDebugUnitTest. New CloudTtsEngineTest covers every fallback trigger (closed gate, no provider/voice selected, no credentials, synthesis failure, playback failure) plus the success path, using a real TtsPreferences (temp-file DataStore) and fakes for everything else — required working out a genuine kotlinx-coroutines-test subtlety (DataStore's internal real-dispatcher I/O needs the SAME test dispatcher as the code under test, or advanceUntilIdle() races it). Verification caveat, stated plainly: Hilt component assembly (does the full dependency graph actually resolve TtsEngineType.CLOUD at runtime) can only be verified once :app depends on core:cloudtts — which happens in the next (Settings UI) PR, not this one. Confirmed core:cloudtts and core:tts each compile and test correctly standalone; full end-to-end Hilt wiring is the next PR's job to prove. Part of #451. Depends on the merged core:cloudtts vendor-adapters PR. --- .../libravault/core/cloudtts/CloudPlayback.kt | 98 +++++++ .../core/cloudtts/CloudTtsEngine.kt | 239 ++++++++++++++++ .../core/cloudtts/di/CloudTtsModule.kt | 23 +- .../core/cloudtts/CloudTtsEngineTest.kt | 261 ++++++++++++++++++ .../libravault/core/tts/TtsEngineFactory.kt | 56 ++-- .../xyz/libravault/core/tts/TtsModule.kt | 17 +- .../xyz/libravault/core/tts/TtsPreferences.kt | 27 ++ .../core/tts/TtsEngineFactoryTest.kt | 53 +++- .../libravault/core/tts/TtsPreferencesTest.kt | 3 +- 9 files changed, 741 insertions(+), 36 deletions(-) create mode 100644 core/cloudtts/src/main/kotlin/xyz/libravault/core/cloudtts/CloudPlayback.kt create mode 100644 core/cloudtts/src/main/kotlin/xyz/libravault/core/cloudtts/CloudTtsEngine.kt create mode 100644 core/cloudtts/src/test/kotlin/xyz/libravault/core/cloudtts/CloudTtsEngineTest.kt diff --git a/core/cloudtts/src/main/kotlin/xyz/libravault/core/cloudtts/CloudPlayback.kt b/core/cloudtts/src/main/kotlin/xyz/libravault/core/cloudtts/CloudPlayback.kt new file mode 100644 index 00000000..8be64fe4 --- /dev/null +++ b/core/cloudtts/src/main/kotlin/xyz/libravault/core/cloudtts/CloudPlayback.kt @@ -0,0 +1,98 @@ +package xyz.libravault.core.cloudtts + +import android.media.AudioAttributes +import android.media.MediaDataSource +import android.media.MediaPlayer +import android.util.Log +import javax.inject.Inject + +private const val TAG = "CloudPlayback" + +/** + * Plays a vendor-encoded audio buffer (mp3, typically) received from + * [CloudTtsProvider.synthesize]. A real player needs Android runtime + * (Robolectric or a device), so [CloudTtsEngine] depends on this interface + * rather than [MediaPlayerCloudPlayback] directly — tests substitute a fake + * without ever touching `android.media.*`, the same interface-plus-fake + * shape this codebase already uses for `HardwareKeyWrap`/`TtsEngine` itself. + */ +interface CloudPlayback { + fun play(audioBytes: ByteArray, onCompletion: () -> Unit, onError: (String) -> Unit) + fun pause() + fun resume() + fun stop() +} + +/** + * Real implementation, wrapping [MediaPlayer]. Unlike `core:tts`'s + * `PocketPlayback` (raw PCM float samples over `AudioTrack`), cloud vendors + * return already-encoded audio, so this wraps [MediaPlayer] — its own + * decoder handles whatever format each vendor sends back. + * + * Feeds the byte array via [MediaDataSource] rather than writing a temp + * file: no cache-file cleanup to get wrong, and the audio (synthesized + * speech from the user's own reading material) never touches disk. + */ +class MediaPlayerCloudPlayback @Inject constructor() : CloudPlayback { + private var mediaPlayer: MediaPlayer? = null + + override fun play(audioBytes: ByteArray, onCompletion: () -> Unit, onError: (String) -> Unit) { + stop() + val player = MediaPlayer() + try { + player.setAudioAttributes( + AudioAttributes.Builder() + .setUsage(AudioAttributes.USAGE_MEDIA) + .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH) + .build(), + ) + player.setDataSource(ByteArrayMediaDataSource(audioBytes)) + player.setOnCompletionListener { onCompletion() } + player.setOnErrorListener { _, what, extra -> + Log.e(TAG, "MediaPlayer error: what=$what extra=$extra") + onError("MediaPlayer error $what/$extra") + true + } + // Synchronous prepare(), not prepareAsync(): this always runs + // from CloudTtsEngine's background scope, never the caller's + // thread, and the byte array is already fully in memory (no + // network/disk I/O left for prepare() to block on). + player.prepare() + player.start() + mediaPlayer = player + } catch (e: Exception) { + Log.e(TAG, "Failed to start playback: ${e.message}", e) + player.release() + onError(e.message ?: "Failed to start playback") + } + } + + override fun pause() { + mediaPlayer?.pause() + } + + override fun resume() { + mediaPlayer?.start() + } + + override fun stop() { + mediaPlayer?.apply { + runCatching { stop() } + release() + } + mediaPlayer = null + } +} + +private class ByteArrayMediaDataSource(private val data: ByteArray) : MediaDataSource() { + override fun readAt(position: Long, buffer: ByteArray, offset: Int, size: Int): Int { + if (position >= data.size) return -1 + val length = minOf(size.toLong(), data.size - position).toInt() + System.arraycopy(data, position.toInt(), buffer, offset, length) + return length + } + + override fun getSize(): Long = data.size.toLong() + + override fun close() = Unit +} diff --git a/core/cloudtts/src/main/kotlin/xyz/libravault/core/cloudtts/CloudTtsEngine.kt b/core/cloudtts/src/main/kotlin/xyz/libravault/core/cloudtts/CloudTtsEngine.kt new file mode 100644 index 00000000..cd371cb5 --- /dev/null +++ b/core/cloudtts/src/main/kotlin/xyz/libravault/core/cloudtts/CloudTtsEngine.kt @@ -0,0 +1,239 @@ +package xyz.libravault.core.cloudtts + +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.SharedFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asSharedFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.launch +import xyz.libravault.core.tts.TtsAudioFocusManager +import xyz.libravault.core.tts.TtsEngine +import xyz.libravault.core.tts.TtsEngineType +import xyz.libravault.core.tts.TtsPreferences +import xyz.libravault.core.tts.TtsState +import xyz.libravault.core.tts.TtsStatus +import javax.inject.Inject +import javax.inject.Provider +import javax.inject.Singleton + +// Chunking mirrors AndroidTtsEngine's own MAX_UTTERANCE_CHARS — PRD §3 +// ("no new segmentation logic needed"). Not shared as a public constant +// between the two engines since core:cloudtts intentionally doesn't depend +// on AndroidTtsEngine directly; this is a reasonable, independently +// documented value for the same reason (avoid one HTTP call per whole +// chapter, keep individual vendor requests small). +private const val MAX_CHUNK_CHARS = 3900 + +/** + * `TtsEngineType.CLOUD`'s [TtsEngine]. Bound into `core:tts`'s + * [xyz.libravault.core.tts.TtsEngineFactory] multibinding map from this + * module's own (unflavored) Hilt module — see [TtsEngineFactory][ + * xyz.libravault.core.tts.TtsEngineFactory]'s class doc for why. + * + * [CloudTtsGate.observeCanUseCloudTts] is re-checked before every chunk in + * [speak], not just once at the top — a subscription lapsing or consent + * being revoked mid-session stops new cloud calls immediately. On gate + * failure, missing provider/voice selection, missing credentials, or any + * HTTP failure, delegates the rest of the utterance to the on-device + * fallback engine ([TtsEngineType.ANDROID], resolved from the SAME + * multibinding map this class is itself bound into — Provider-based + * multibinding maps can reference their own other entries without a cycle, + * so no separate DI qualifier is needed) rather than retrying cloud or + * silently stalling (PRD §3). + */ +@Singleton +class CloudTtsEngine @Inject constructor( + private val gate: CloudTtsGate, + private val cloudTtsProvider: CloudTtsProvider, + private val apiKeyStore: CloudApiKeyStore, + private val preferences: TtsPreferences, + private val engines: Map>, + private val scope: CoroutineScope, + private val audioFocusManager: TtsAudioFocusManager, + private val playback: CloudPlayback, +) : TtsEngine { + + private val _state = MutableStateFlow(TtsState()) + override val state: StateFlow = _state.asStateFlow() + + private val _completionEvent = MutableSharedFlow(extraBufferCapacity = 1) + override val completionEvent: SharedFlow = _completionEvent.asSharedFlow() + + private val _stopEvent = MutableSharedFlow(extraBufferCapacity = 1) + override val stopEvent: SharedFlow = _stopEvent.asSharedFlow() + + private val fallbackEngine: TtsEngine by lazy { + engines[TtsEngineType.ANDROID]?.get() + ?: error("No on-device fallback (TtsEngineType.ANDROID) bound — cannot safely run CloudTtsEngine without one") + } + + private var isFallenBack = false + private var fallbackForwardingJob: Job? = null + private var speakJob: Job? = null + + /** Why the most recent fallback happened, if any — e.g. "cloud voices + * gate is closed", "no saved credentials for OPENAI". Settings UI + * (follow-up PR) can surface this; not part of [TtsState] since it's + * diagnostic, not itself playback status. */ + var lastFallbackReason: String? = null + private set + + override fun initialize() { + // No network call here — nothing to fetch a voice catalog from + // without a selected provider/credentials, and the PRD's five voice + // presets are fixed per vendor (Settings UI follow-up owns + // presenting them, not this engine). + _state.value = _state.value.copy(status = TtsStatus.IDLE, error = null) + } + + override fun speak(text: String) { + speakJob?.cancel() + fallbackForwardingJob?.cancel() + isFallenBack = false + audioFocusManager.requestFocus { stop() } + _state.value = _state.value.copy(status = TtsStatus.PLAYING, error = null) + + speakJob = scope.launch { + val chunks = splitIntoChunks(text) + speakChunk(chunks, 0) + } + } + + private suspend fun speakChunk(chunks: List, index: Int) { + if (index >= chunks.size) { + _state.value = _state.value.copy(status = TtsStatus.IDLE) + _completionEvent.tryEmit(Unit) + return + } + + if (!gate.observeCanUseCloudTts().first()) { + fallBackTo(chunks, index, "cloud voices gate is closed (subscription lapsed or consent revoked)") + return + } + val providerId = preferences.selectedCloudProviderFlow.first() + ?.let { runCatching { CloudProviderId.valueOf(it) }.getOrNull() } + val voiceId = preferences.selectedVoiceFlow.first() + if (providerId == null || voiceId == null) { + fallBackTo(chunks, index, "no cloud voice selected") + return + } + val credentials = apiKeyStore.loadCredentials(providerId) + if (credentials == null) { + fallBackTo(chunks, index, "no saved credentials for $providerId") + return + } + + val result = cloudTtsProvider.synthesize(providerId, chunks[index], voiceId, credentials) + val audioBytes = result.getOrElse { + fallBackTo(chunks, index, "cloud synthesis failed: ${it.message}") + return + } + + playback.play( + audioBytes, + onCompletion = { scope.launch { speakChunk(chunks, index + 1) } }, + onError = { message -> scope.launch { fallBackTo(chunks, index, "playback error: $message") } }, + ) + } + + /** Delegates chunks `[index, chunks.size)` to the on-device engine and + * forwards its state/events into this engine's own flows for as long as + * fallback stays active, so a caller observing THIS engine's flows sees + * accurate status rather than freezing at the moment of fallback. + * + * Deliberately no `android.util.Log` call here (unlike `AndroidTtsEngine`/ + * `PocketTtsEngine`): [reason] is instead surfaced via [lastFallbackReason] + * — real diagnostic value (visible to QA/UI, not just logcat) without + * `core:cloudtts` needing Robolectric just to unit-test this one path + * (`android.util.Log` throws "not mocked" in a plain JVM test — same + * reasoning as [RealCloudApiKeyStore] using `java.util.Base64`, not + * `android.util.Base64`). */ + private fun fallBackTo(chunks: List, index: Int, reason: String) { + lastFallbackReason = reason + isFallenBack = true + val remainingText = chunks.subList(index, chunks.size).joinToString(" ") + + fallbackForwardingJob?.cancel() + fallbackForwardingJob = scope.launch { + launch { fallbackEngine.state.collect { _state.value = it } } + launch { fallbackEngine.completionEvent.collect { _completionEvent.tryEmit(Unit) } } + launch { fallbackEngine.stopEvent.collect { _stopEvent.tryEmit(Unit) } } + } + if (fallbackEngine.state.value.status == TtsStatus.UNINITIALIZED) { + fallbackEngine.initialize() + } + fallbackEngine.speak(remainingText) + } + + override fun pause() { + if (isFallenBack) { + fallbackEngine.pause() + } else { + playback.pause() + _state.value = _state.value.copy(status = TtsStatus.PAUSED) + } + } + + override fun resume() { + if (isFallenBack) { + fallbackEngine.resume() + } else { + playback.resume() + _state.value = _state.value.copy(status = TtsStatus.PLAYING) + } + } + + override fun stop() { + speakJob?.cancel() + fallbackForwardingJob?.cancel() + if (isFallenBack) { + fallbackEngine.stop() + isFallenBack = false + } + playback.stop() + audioFocusManager.abandonFocus() + _state.value = _state.value.copy(status = TtsStatus.IDLE) + _stopEvent.tryEmit(Unit) + } + + override fun setVoice(voiceId: String) { + _state.value = _state.value.copy(selectedVoiceId = voiceId) + if (isFallenBack) fallbackEngine.setVoice(voiceId) + } + + override fun setSpeechRate(rate: Float) { + _state.value = _state.value.copy(speechRate = rate) + if (isFallenBack) fallbackEngine.setSpeechRate(rate) + } + + override fun shutdown() { + speakJob?.cancel() + fallbackForwardingJob?.cancel() + playback.stop() + audioFocusManager.abandonFocus() + _state.value = TtsState() + } + + private fun splitIntoChunks(text: String): List { + if (text.length <= MAX_CHUNK_CHARS) return listOf(text) + + val chunks = mutableListOf() + var remaining = text.trim() + while (remaining.isNotEmpty()) { + if (remaining.length <= MAX_CHUNK_CHARS) { + chunks += remaining + break + } + val window = remaining.substring(0, MAX_CHUNK_CHARS) + val cut = window.indexOfLast { it == '.' || it == '!' || it == '?' } + val splitAt = if (cut > 0) cut + 1 else MAX_CHUNK_CHARS + chunks += remaining.substring(0, splitAt).trim() + remaining = remaining.substring(splitAt).trim() + } + return chunks + } +} diff --git a/core/cloudtts/src/main/kotlin/xyz/libravault/core/cloudtts/di/CloudTtsModule.kt b/core/cloudtts/src/main/kotlin/xyz/libravault/core/cloudtts/di/CloudTtsModule.kt index a3e6413e..484652bb 100644 --- a/core/cloudtts/src/main/kotlin/xyz/libravault/core/cloudtts/di/CloudTtsModule.kt +++ b/core/cloudtts/src/main/kotlin/xyz/libravault/core/cloudtts/di/CloudTtsModule.kt @@ -4,8 +4,15 @@ import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent +import dagger.multibindings.IntoMap import xyz.libravault.core.cloudtts.CloudApiKeyStore +import xyz.libravault.core.cloudtts.CloudPlayback +import xyz.libravault.core.cloudtts.CloudTtsEngine +import xyz.libravault.core.cloudtts.MediaPlayerCloudPlayback import xyz.libravault.core.cloudtts.RealCloudApiKeyStore +import xyz.libravault.core.tts.TtsEngine +import xyz.libravault.core.tts.TtsEngineType +import xyz.libravault.core.tts.TtsEngineTypeKey import javax.inject.Singleton /** @@ -13,8 +20,11 @@ import javax.inject.Singleton * Keystore isn't a networking dependency, see core/cloudtts/build.gradle.kts' * module comment). The [xyz.libravault.core.cloudtts.CloudTtsProvider] * binding (real vendor dispatch vs. NoOp) is the one thing that IS - * flavor-split — see `di/CloudTtsPlayModule.kt` (vendor-adapters follow-up) - * and `di/CloudTtsFdroidModule.kt`. + * flavor-split — see `di/CloudTtsPlayModule.kt` and `di/CloudTtsFdroidModule.kt`. + * + * [CloudTtsEngine]'s `@IntoMap` contribution here is what makes `core:tts`'s + * `TtsEngineFactory` able to resolve `TtsEngineType.CLOUD` without `core:tts` + * ever compiling against `core:cloudtts` — see `TtsEngineTypeKey`'s class doc. */ @Module @InstallIn(SingletonComponent::class) @@ -23,4 +33,13 @@ abstract class CloudTtsModule { @Binds @Singleton abstract fun bindCloudApiKeyStore(impl: RealCloudApiKeyStore): CloudApiKeyStore + + @Binds + @Singleton + abstract fun bindCloudPlayback(impl: MediaPlayerCloudPlayback): CloudPlayback + + @Binds + @IntoMap + @TtsEngineTypeKey(TtsEngineType.CLOUD) + abstract fun bindCloudTtsEngine(impl: CloudTtsEngine): TtsEngine } diff --git a/core/cloudtts/src/test/kotlin/xyz/libravault/core/cloudtts/CloudTtsEngineTest.kt b/core/cloudtts/src/test/kotlin/xyz/libravault/core/cloudtts/CloudTtsEngineTest.kt new file mode 100644 index 00000000..5566bb67 --- /dev/null +++ b/core/cloudtts/src/test/kotlin/xyz/libravault/core/cloudtts/CloudTtsEngineTest.kt @@ -0,0 +1,261 @@ +package xyz.libravault.core.cloudtts + +import androidx.datastore.preferences.core.PreferenceDataStoreFactory +import io.mockk.every +import io.mockk.just +import io.mockk.mockk +import io.mockk.Runs +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.SharedFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asSharedFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.runTest +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import xyz.libravault.core.tts.TtsAudioFocusManager +import xyz.libravault.core.tts.TtsEngine +import xyz.libravault.core.tts.TtsEngineType +import xyz.libravault.core.tts.TtsPreferences +import xyz.libravault.core.tts.TtsState +import xyz.libravault.core.tts.TtsStatus +import java.io.File +import javax.inject.Provider + +class CloudTtsEngineTest { + + private class FakeTtsEngine : TtsEngine { + var lastSpokenText: String? = null + override val state: StateFlow = MutableStateFlow(TtsState(status = TtsStatus.IDLE)) + override val completionEvent: SharedFlow = MutableSharedFlow() + override val stopEvent: SharedFlow = MutableSharedFlow() + override fun initialize() {} + override fun speak(text: String) { + lastSpokenText = text + } + override fun pause() {} + override fun resume() {} + override fun stop() {} + override fun setVoice(voiceId: String) {} + override fun setSpeechRate(rate: Float) {} + override fun shutdown() {} + } + + private class FakeCloudTtsProvider( + private val result: Result = Result.success(byteArrayOf(1, 2, 3)), + ) : CloudTtsProvider { + var synthesizeCallCount = 0 + override suspend fun synthesize( + provider: CloudProviderId, + text: String, + voiceId: String, + credentials: Map, + ): Result { + synthesizeCallCount++ + return result + } + override suspend fun validateKey(provider: CloudProviderId, credentials: Map): Result = + Result.success(Unit) + } + + private class FakeCloudApiKeyStore(private val stored: Map? = null) : CloudApiKeyStore { + override suspend fun saveCredentials(provider: CloudProviderId, credentials: Map) = Unit + override suspend fun loadCredentials(provider: CloudProviderId): Map? = stored + override suspend fun clearCredentials(provider: CloudProviderId) = Unit + } + + private class FakeCloudPlayback : CloudPlayback { + var playedBytes: ByteArray? = null + var onCompletion: (() -> Unit)? = null + override fun play(audioBytes: ByteArray, onCompletion: () -> Unit, onError: (String) -> Unit) { + playedBytes = audioBytes + this.onCompletion = onCompletion + } + override fun pause() {} + override fun resume() {} + override fun stop() {} + } + + // DataStore normally does its file I/O on a real Dispatchers.IO-backed + // scope — invisible to advanceUntilIdle()'s virtual clock. Since + // CloudTtsEngine reads preferences from inside a coroutine launched on + // the test's (virtual-time) scope, DataStore's own internal work must + // run on that SAME scope too, or a read can still be in flight on a real + // thread the instant advanceUntilIdle() returns and the test asserts. + private fun preferences(tempDir: File, scope: CoroutineScope): TtsPreferences = + TtsPreferences( + PreferenceDataStoreFactory.create( + scope = scope, + produceFile = { File(tempDir, "test_tts_preferences.preferences_pb") }, + ), + ) + + private fun fakeAudioFocusManager(): TtsAudioFocusManager { + val manager = mockk() + every { manager.requestFocus(any()) } just Runs + every { manager.abandonFocus() } just Runs + return manager + } + + private fun buildEngine( + gate: CloudTtsGate, + cloudTtsProvider: CloudTtsProvider, + apiKeyStore: CloudApiKeyStore, + prefs: TtsPreferences, + fallback: FakeTtsEngine, + playback: FakeCloudPlayback, + scope: CoroutineScope, + ) = CloudTtsEngine( + gate = gate, + cloudTtsProvider = cloudTtsProvider, + apiKeyStore = apiKeyStore, + preferences = prefs, + engines = mapOf(TtsEngineType.ANDROID to Provider { fallback }), + scope = scope, + audioFocusManager = fakeAudioFocusManager(), + playback = playback, + ) + + private fun closedGate(): CloudTtsGate = mockk().also { + every { it.observeCanUseCloudTts() } returns MutableStateFlow(false) + } + + private fun openGate(): CloudTtsGate = mockk().also { + every { it.observeCanUseCloudTts() } returns MutableStateFlow(true) + } + + @Test + fun `speak falls back to on-device engine when the gate is closed`(@TempDir tempDir: File) = runTest { + val scope = CoroutineScope(UnconfinedTestDispatcher(testScheduler)) + val fallback = FakeTtsEngine() + val provider = FakeCloudTtsProvider() + val engine = buildEngine(closedGate(), provider, FakeCloudApiKeyStore(), preferences(tempDir, scope), fallback, FakeCloudPlayback(), scope) + + engine.speak("hello world") + advanceUntilIdle() + + assertEquals("hello world", fallback.lastSpokenText) + assertEquals(0, provider.synthesizeCallCount, "a closed gate must never reach the network") + } + + @Test + fun `speak falls back when no cloud provider or voice is selected`(@TempDir tempDir: File) = runTest { + val scope = CoroutineScope(UnconfinedTestDispatcher(testScheduler)) + val fallback = FakeTtsEngine() + val provider = FakeCloudTtsProvider() + // Gate open, but preferences never set a selected provider/voice. + val engine = buildEngine(openGate(), provider, FakeCloudApiKeyStore(), preferences(tempDir, scope), fallback, FakeCloudPlayback(), scope) + + engine.speak("hello") + advanceUntilIdle() + + assertEquals("hello", fallback.lastSpokenText) + assertEquals(0, provider.synthesizeCallCount) + } + + @Test + fun `speak falls back when no credentials are saved for the selected provider`(@TempDir tempDir: File) = runTest { + val scope = CoroutineScope(UnconfinedTestDispatcher(testScheduler)) + val fallback = FakeTtsEngine() + val provider = FakeCloudTtsProvider() + val prefs = preferences(tempDir, scope) + prefs.setSelectedCloudProvider(CloudProviderId.OPENAI.name) + prefs.setSelectedVoice("alloy") + val engine = buildEngine(openGate(), provider, FakeCloudApiKeyStore(stored = null), prefs, fallback, FakeCloudPlayback(), scope) + + engine.speak("hello") + advanceUntilIdle() + + assertEquals("hello", fallback.lastSpokenText) + } + + @Test + fun `speak plays synthesized audio when the gate is open and everything is configured`(@TempDir tempDir: File) = runTest { + val scope = CoroutineScope(UnconfinedTestDispatcher(testScheduler)) + val fallback = FakeTtsEngine() + val provider = FakeCloudTtsProvider(result = Result.success(byteArrayOf(9, 8, 7))) + val prefs = preferences(tempDir, scope) + prefs.setSelectedCloudProvider(CloudProviderId.OPENAI.name) + prefs.setSelectedVoice("alloy") + val playback = FakeCloudPlayback() + val engine = buildEngine( + openGate(), + provider, + FakeCloudApiKeyStore(stored = mapOf(CloudCredentialFields.API_KEY to "sk-test")), + prefs, + fallback, + playback, + scope, + ) + + engine.speak("hello") + advanceUntilIdle() + + assertTrue(playback.playedBytes?.contentEquals(byteArrayOf(9, 8, 7)) == true) + assertNull(fallback.lastSpokenText, "must not fall back when cloud synthesis succeeds") + } + + @Test + fun `speak falls back when cloud synthesis fails`(@TempDir tempDir: File) = runTest { + val scope = CoroutineScope(UnconfinedTestDispatcher(testScheduler)) + val fallback = FakeTtsEngine() + val provider = FakeCloudTtsProvider(result = Result.failure(RuntimeException("HTTP 500"))) + val prefs = preferences(tempDir, scope) + prefs.setSelectedCloudProvider(CloudProviderId.OPENAI.name) + prefs.setSelectedVoice("alloy") + val engine = buildEngine( + openGate(), + provider, + FakeCloudApiKeyStore(stored = mapOf(CloudCredentialFields.API_KEY to "sk-test")), + prefs, + fallback, + FakeCloudPlayback(), + scope, + ) + + engine.speak("hello") + advanceUntilIdle() + + assertEquals("hello", fallback.lastSpokenText) + } + + @Test + fun `speak falls back when playback itself errors after a successful synthesis`(@TempDir tempDir: File) = runTest { + val scope = CoroutineScope(UnconfinedTestDispatcher(testScheduler)) + val fallback = FakeTtsEngine() + val provider = FakeCloudTtsProvider(result = Result.success(byteArrayOf(1))) + val prefs = preferences(tempDir, scope) + prefs.setSelectedCloudProvider(CloudProviderId.OPENAI.name) + prefs.setSelectedVoice("alloy") + val erroringPlayback = object : CloudPlayback { + override fun play(audioBytes: ByteArray, onCompletion: () -> Unit, onError: (String) -> Unit) { + onError("decoder error") + } + override fun pause() {} + override fun resume() {} + override fun stop() {} + } + val engine = CloudTtsEngine( + gate = openGate(), + cloudTtsProvider = provider, + apiKeyStore = FakeCloudApiKeyStore(stored = mapOf(CloudCredentialFields.API_KEY to "sk-test")), + preferences = prefs, + engines = mapOf(TtsEngineType.ANDROID to Provider { fallback }), + scope = scope, + audioFocusManager = fakeAudioFocusManager(), + playback = erroringPlayback, + ) + + engine.speak("hello") + advanceUntilIdle() + + assertEquals("hello", fallback.lastSpokenText) + } +} diff --git a/core/tts/src/main/kotlin/xyz/libravault/core/tts/TtsEngineFactory.kt b/core/tts/src/main/kotlin/xyz/libravault/core/tts/TtsEngineFactory.kt index be5bf8a6..5bf800bf 100644 --- a/core/tts/src/main/kotlin/xyz/libravault/core/tts/TtsEngineFactory.kt +++ b/core/tts/src/main/kotlin/xyz/libravault/core/tts/TtsEngineFactory.kt @@ -1,38 +1,46 @@ package xyz.libravault.core.tts -import android.util.Log -import xyz.libravault.core.tts.pocket.PocketTtsEngine +import dagger.MapKey import javax.inject.Inject +import javax.inject.Provider import javax.inject.Singleton -private const val TAG = "TtsEngineFactory" - enum class TtsEngineType { ANDROID, POCKET_TTS, + + /** Premium Cloud TTS Voices (BYOK) — docs/cloud-tts-premium-prd.md. Bound + * from `core:cloudtts` (unflavored `CloudTtsEngine`), not this module — + * see [TtsEngineTypeKey]'s doc for why `core:tts` itself never depends + * on `core:cloudtts`. */ + CLOUD, } +/** Dagger multibinding key for [TtsEngineType] — lets [TtsEngineFactory] + * resolve an engine by type without `core:tts` (unflavored, shared by + * `feature:reader`) needing a compile-time dependency on `core:cloudtts` + * (flavored: fdroid/play). `core:cloudtts`'s own Hilt module contributes the + * [TtsEngineType.CLOUD] entry to this same map from outside this module — + * the map is assembled at `:app`'s `SingletonComponent`, where every module + * that contributes an entry is already on the classpath regardless of + * flavor. The alternative (giving `core:tts` its own flavor dimension so it + * could depend on `core:cloudtts` directly) was rejected: it would force + * `feature:reader` to gain flavor dimensions it has no other reason to + * need, for a module with nothing to do with distribution channel. */ +@MapKey +annotation class TtsEngineTypeKey(val value: TtsEngineType) + +/** + * Resolves a [TtsEngine] by [TtsEngineType] via Dagger multibinding — see + * [TtsEngineTypeKey] for why this is a map injection rather than a plain + * `when` over constructor-injected concrete engines (the shape this class + * had before `core:cloudtts`/[TtsEngineType.CLOUD] existed). + */ @Singleton class TtsEngineFactory @Inject constructor( - private val androidEngine: AndroidTtsEngine, - private val pocketEngine: PocketTtsEngine, + private val engines: Map>, ) { - // Pocket TTS used to fall back to Android system TTS on F-Droid builds - // here, because the voice model was downloaded on first use and F-Droid - // ships with no INTERNET permission. The model is now bundled into the - // APK at build time instead (see PocketModelManager and - // third-party/sherpa-onnx/setup-android-model.sh), so both flavors can - // use it - no flavor check needed. - fun create(type: TtsEngineType): TtsEngine { - return when (type) { - TtsEngineType.ANDROID -> { - Log.d(TAG, "Using Android system TTS") - androidEngine - } - TtsEngineType.POCKET_TTS -> { - Log.d(TAG, "Using Pocket TTS") - pocketEngine - } - } - } + fun create(type: TtsEngineType): TtsEngine = + engines[type]?.get() + ?: error("No TtsEngine bound for $type — is its module @InstallIn(SingletonComponent::class)?") } diff --git a/core/tts/src/main/kotlin/xyz/libravault/core/tts/TtsModule.kt b/core/tts/src/main/kotlin/xyz/libravault/core/tts/TtsModule.kt index 52152e26..967692d7 100644 --- a/core/tts/src/main/kotlin/xyz/libravault/core/tts/TtsModule.kt +++ b/core/tts/src/main/kotlin/xyz/libravault/core/tts/TtsModule.kt @@ -5,8 +5,10 @@ import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent +import dagger.multibindings.IntoMap import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers +import xyz.libravault.core.tts.pocket.PocketTtsEngine import javax.inject.Singleton @Module @@ -14,15 +16,22 @@ import javax.inject.Singleton abstract class TtsModule { @Binds - @Singleton - abstract fun bindTtsEngine(impl: AndroidTtsEngine): TtsEngine + @IntoMap + @TtsEngineTypeKey(TtsEngineType.ANDROID) + abstract fun bindAndroidEngine(impl: AndroidTtsEngine): TtsEngine + + @Binds + @IntoMap + @TtsEngineTypeKey(TtsEngineType.POCKET_TTS) + abstract fun bindPocketEngine(impl: PocketTtsEngine): TtsEngine companion object { /** * Shared background scope for TTS work that outlives a single call - - * [TtsEngineProvider]'s reactive engine switching and + * [TtsEngineProvider]'s reactive engine switching, * [xyz.libravault.core.tts.pocket.PocketTtsEngine]'s model loading / - * generation. Extracted as a binding (rather than each class + * generation, and (from `core:cloudtts`) `CloudTtsEngine`'s + * synthesis calls. Extracted as a binding (rather than each class * hardcoding `CoroutineScope(Dispatchers.Default)`) so tests can * substitute a `TestScope`. */ diff --git a/core/tts/src/main/kotlin/xyz/libravault/core/tts/TtsPreferences.kt b/core/tts/src/main/kotlin/xyz/libravault/core/tts/TtsPreferences.kt index eb5d45a0..9d376abf 100644 --- a/core/tts/src/main/kotlin/xyz/libravault/core/tts/TtsPreferences.kt +++ b/core/tts/src/main/kotlin/xyz/libravault/core/tts/TtsPreferences.kt @@ -31,6 +31,16 @@ private val LOCAL_ONLY_KEY = booleanPreferencesKey("local_voices_only") // wrong kind of subtlety for a security/privacy-relevant consent flag. private val CLOUD_VOICES_CONSENT_KEY = booleanPreferencesKey("cloud_voices_consent") +// Which of the five BYOK vendors (core:cloudtts's CloudProviderId) is +// currently selected — stored as its raw enum-name string, not the +// CloudProviderId type itself, so core:tts never needs a compile-time +// dependency on core:cloudtts (same reasoning as the TtsEngineType.CLOUD / +// TtsEngineTypeKey split in TtsEngineFactory.kt). The selected voice ID for +// whichever provider this names reuses the existing SELECTED_VOICE_KEY/ +// selectedVoiceFlow below — no separate key needed, same as how it already +// serves ANDROID's and POCKET_TTS's voice selection. +private val SELECTED_CLOUD_PROVIDER_KEY = stringPreferencesKey("selected_cloud_provider") + val Context.ttsPreferencesDataStore: DataStore by preferencesDataStore(name = PREFERENCES_NAME) /** @@ -69,6 +79,13 @@ class TtsPreferences constructor( preferences[CLOUD_VOICES_CONSENT_KEY] ?: false } + /** Raw `CloudProviderId.name` string, or null if none selected yet — see + * [SELECTED_CLOUD_PROVIDER_KEY]. Parsing it back into a `CloudProviderId` + * is `core:cloudtts`'s job (it owns that type). */ + val selectedCloudProviderFlow: Flow = dataStore.data.map { preferences -> + preferences[SELECTED_CLOUD_PROVIDER_KEY] + } + suspend fun setEngineType(type: TtsEngineType) { dataStore.edit { preferences -> preferences[ENGINE_TYPE_KEY] = type.name @@ -96,4 +113,14 @@ class TtsPreferences constructor( preferences[CLOUD_VOICES_CONSENT_KEY] = enabled } } + + suspend fun setSelectedCloudProvider(providerName: String?) { + dataStore.edit { preferences -> + if (providerName != null) { + preferences[SELECTED_CLOUD_PROVIDER_KEY] = providerName + } else { + preferences.remove(SELECTED_CLOUD_PROVIDER_KEY) + } + } + } } diff --git a/core/tts/src/test/kotlin/xyz/libravault/core/tts/TtsEngineFactoryTest.kt b/core/tts/src/test/kotlin/xyz/libravault/core/tts/TtsEngineFactoryTest.kt index f793df40..3d4603f2 100644 --- a/core/tts/src/test/kotlin/xyz/libravault/core/tts/TtsEngineFactoryTest.kt +++ b/core/tts/src/test/kotlin/xyz/libravault/core/tts/TtsEngineFactoryTest.kt @@ -1,22 +1,65 @@ package xyz.libravault.core.tts +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.SharedFlow +import kotlinx.coroutines.flow.StateFlow import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertSame import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test +import javax.inject.Provider class TtsEngineFactoryTest { + private class FakeTtsEngine : TtsEngine { + override val state: StateFlow = MutableStateFlow(TtsState()) + override val completionEvent: SharedFlow = MutableSharedFlow() + override val stopEvent: SharedFlow = MutableSharedFlow() + override fun initialize() {} + override fun speak(text: String) {} + override fun pause() {} + override fun resume() {} + override fun stop() {} + override fun setVoice(voiceId: String) {} + override fun setSpeechRate(rate: Float) {} + override fun shutdown() {} + } + @Test - fun `TtsEngineType enum values exist`() { + fun `TtsEngineType has three values including CLOUD`() { val types = TtsEngineType.values() - assertEquals(2, types.size) + assertEquals(3, types.size) assertTrue(types.contains(TtsEngineType.ANDROID)) assertTrue(types.contains(TtsEngineType.POCKET_TTS)) + assertTrue(types.contains(TtsEngineType.CLOUD)) } @Test - fun `TtsEngineType can be stringified`() { - assertEquals("ANDROID", TtsEngineType.ANDROID.toString()) - assertEquals("POCKET_TTS", TtsEngineType.POCKET_TTS.toString()) + fun `create resolves the engine bound to the requested type`() { + val androidEngine = FakeTtsEngine() + val cloudEngine = FakeTtsEngine() + val factory = TtsEngineFactory( + mapOf( + TtsEngineType.ANDROID to Provider { androidEngine }, + TtsEngineType.CLOUD to Provider { cloudEngine }, + ), + ) + + assertSame(androidEngine, factory.create(TtsEngineType.ANDROID)) + assertSame(cloudEngine, factory.create(TtsEngineType.CLOUD)) + } + + @Test + fun `create fails loudly rather than returning null for an unbound type`() { + val factory = TtsEngineFactory(mapOf(TtsEngineType.ANDROID to Provider { FakeTtsEngine() })) + + try { + factory.create(TtsEngineType.CLOUD) + throw AssertionError("Expected an exception for an unbound engine type") + } catch (e: IllegalStateException) { + // Expected — e.g. core:cloudtts's Hilt module failed to install, + // or a fdroid build somehow reached CLOUD with no binding. + } } } diff --git a/core/tts/src/test/kotlin/xyz/libravault/core/tts/TtsPreferencesTest.kt b/core/tts/src/test/kotlin/xyz/libravault/core/tts/TtsPreferencesTest.kt index 18c4a415..6f1fdfbd 100644 --- a/core/tts/src/test/kotlin/xyz/libravault/core/tts/TtsPreferencesTest.kt +++ b/core/tts/src/test/kotlin/xyz/libravault/core/tts/TtsPreferencesTest.kt @@ -61,9 +61,10 @@ class TtsPreferencesTest { @Test fun `TtsEngineType enum has values`() { val types = TtsEngineType.values() - assertEquals(2, types.size) + assertEquals(3, types.size) assertEquals(TtsEngineType.ANDROID, TtsEngineType.ANDROID) assertEquals(TtsEngineType.POCKET_TTS, TtsEngineType.POCKET_TTS) + assertEquals(TtsEngineType.CLOUD, TtsEngineType.CLOUD) } @Test From aa5dc3c212229a2d6534f669348e4abae8b063c2 Mon Sep 17 00:00:00 2001 From: LibraVault Date: Sun, 23 Aug 2026 14:40:21 +0000 Subject: [PATCH 2/2] =?UTF-8?q?fix(cloudtts):=20review=20findings=20?= =?UTF-8?q?=E2=80=94=20stop()=20reliability,=20thread=20safety,=20dedup?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Independent review (code-review skill, high effort) on PR #468 found two high-severity bugs plus three real cleanups, all fixed here: 1. CancellationException-swallowing footgun: kotlin.runCatching (used in all 5 vendor adapters, from the already-merged vendor-adapters PR) also catches CancellationException, turning a genuine stop()-triggered cancellation of an in-flight synthesize() call into an ordinary Result.failure — which CloudTtsEngine then treated as "cloud failed, fall back," so pressing Stop mid-request could start the on-device engine SPEAKING instead of actually stopping. Fixed at the root: new runCatchingCancellable() in VendorTtsAdapter.kt (rethrows CancellationException, wraps everything else same as runCatching), swapped in across all 5 adapters' synthesize/validateKey. 2. Untracked per-chunk coroutines: each chunk after the first was launched from playback's onCompletion/onError callback via a NEW scope.launch{}, never assigned to speakJob — so stop() couldn't cancel an already-started later chunk. Restructured speak() into ONE coroutine covering the whole chunk loop, with CloudPlayback's callback API bridged into a single suspendCancellableCoroutine per chunk — cancelling speakJob now reliably interrupts whatever chunk is currently fetching or playing. 3. CloudPlayback (MediaPlayer) thread-safety: play() runs on the engine's background scope while pause()/resume()/stop() are called directly from whatever thread the TtsEngine caller is on (typically Main) — a real race MediaPlayer's own docs disallow. All methods now synchronized on a private lock. 4. Provider/voice/credentials were re-resolved (DataStore read × 2 + Keystore decrypt) on every chunk, even though none can change mid- utterance. Now resolved once per speak() call; only the gate — the one PRD-mandated per-chunk re-check — still re-checks every chunk. 5. TtsPreferences.selectedVoiceFlow is shared by all three TtsEngineTypes; flagged with a prominent doc comment (not fixed here — it's a Settings UI concern, PR4's job to clear/reprompt the voice on engine/provider switch) rather than silently left undocumented. New tests: multi-chunk continuation (chunk 2 only fetched after chunk 1's playback completes) and the specific stop()-mid-synthesis-doesn't-fall-back regression (using kotlinx.coroutines.awaitCancellation() to simulate a genuinely in-flight call). ./gradlew :core:tts:testDebugUnitTest :core:cloudtts:testPlayDebugUnitTest :core:cloudtts:testFdroidDebugUnitTest BUILD SUCCESSFUL — 211 tests (up from 182), all passing. --- .../libravault/core/cloudtts/CloudPlayback.kt | 22 +++- .../core/cloudtts/CloudTtsEngine.kt | 111 ++++++++++++------ .../cloudtts/vendor/AmazonPollyAdapter.kt | 4 +- .../cloudtts/vendor/AzureSpeechAdapter.kt | 4 +- .../core/cloudtts/vendor/ElevenLabsAdapter.kt | 4 +- .../cloudtts/vendor/GoogleCloudTtsAdapter.kt | 4 +- .../core/cloudtts/vendor/OpenAiAdapter.kt | 4 +- .../core/cloudtts/vendor/VendorTtsAdapter.kt | 21 ++++ .../core/cloudtts/CloudTtsEngineTest.kt | 84 +++++++++++++ .../xyz/libravault/core/tts/TtsPreferences.kt | 16 +++ 10 files changed, 223 insertions(+), 51 deletions(-) diff --git a/core/cloudtts/src/main/kotlin/xyz/libravault/core/cloudtts/CloudPlayback.kt b/core/cloudtts/src/main/kotlin/xyz/libravault/core/cloudtts/CloudPlayback.kt index 8be64fe4..8cdf562f 100644 --- a/core/cloudtts/src/main/kotlin/xyz/libravault/core/cloudtts/CloudPlayback.kt +++ b/core/cloudtts/src/main/kotlin/xyz/libravault/core/cloudtts/CloudPlayback.kt @@ -32,12 +32,22 @@ interface CloudPlayback { * Feeds the byte array via [MediaDataSource] rather than writing a temp * file: no cache-file cleanup to get wrong, and the audio (synthesized * speech from the user's own reading material) never touches disk. + * + * All methods `synchronized(lock)`: [MediaPlayer] "objects are not + * thread-safe" per its own docs, and this class is genuinely called from + * two different threads — `play()` from [CloudTtsEngine]'s background + * `scope`, `pause()`/`resume()`/`stop()` directly from whatever thread the + * [xyz.libravault.core.tts.TtsEngine] caller is on (typically Main, same as + * `AndroidTtsEngine`/`PocketTtsEngine`) — a race here could pause/resume a + * stale reference or call `release()` on a player still mid-`start()` on + * the other thread (found in review). */ class MediaPlayerCloudPlayback @Inject constructor() : CloudPlayback { + private val lock = Any() private var mediaPlayer: MediaPlayer? = null - override fun play(audioBytes: ByteArray, onCompletion: () -> Unit, onError: (String) -> Unit) { - stop() + override fun play(audioBytes: ByteArray, onCompletion: () -> Unit, onError: (String) -> Unit) = synchronized(lock) { + stopLocked() val player = MediaPlayer() try { player.setAudioAttributes( @@ -68,14 +78,18 @@ class MediaPlayerCloudPlayback @Inject constructor() : CloudPlayback { } override fun pause() { - mediaPlayer?.pause() + synchronized(lock) { mediaPlayer?.pause() } } override fun resume() { - mediaPlayer?.start() + synchronized(lock) { mediaPlayer?.start() } } override fun stop() { + synchronized(lock) { stopLocked() } + } + + private fun stopLocked() { mediaPlayer?.apply { runCatching { stop() } release() diff --git a/core/cloudtts/src/main/kotlin/xyz/libravault/core/cloudtts/CloudTtsEngine.kt b/core/cloudtts/src/main/kotlin/xyz/libravault/core/cloudtts/CloudTtsEngine.kt index cd371cb5..4b9a8384 100644 --- a/core/cloudtts/src/main/kotlin/xyz/libravault/core/cloudtts/CloudTtsEngine.kt +++ b/core/cloudtts/src/main/kotlin/xyz/libravault/core/cloudtts/CloudTtsEngine.kt @@ -10,6 +10,7 @@ import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch +import kotlinx.coroutines.suspendCancellableCoroutine import xyz.libravault.core.tts.TtsAudioFocusManager import xyz.libravault.core.tts.TtsEngine import xyz.libravault.core.tts.TtsEngineType @@ -36,14 +37,30 @@ private const val MAX_CHUNK_CHARS = 3900 * * [CloudTtsGate.observeCanUseCloudTts] is re-checked before every chunk in * [speak], not just once at the top — a subscription lapsing or consent - * being revoked mid-session stops new cloud calls immediately. On gate - * failure, missing provider/voice selection, missing credentials, or any - * HTTP failure, delegates the rest of the utterance to the on-device + * being revoked mid-session stops new cloud calls immediately. Provider, + * voice, and credentials are resolved once per [speak] call, not re-read + * per chunk (they can't change mid-utterance — no setter is exposed for + * them — so re-reading per chunk was only redundant DataStore/Keystore + * work, caught in review). + * + * On gate failure, missing provider/voice selection, missing credentials, + * or any HTTP failure, delegates the rest of the utterance to the on-device * fallback engine ([TtsEngineType.ANDROID], resolved from the SAME * multibinding map this class is itself bound into — Provider-based * multibinding maps can reference their own other entries without a cycle, * so no separate DI qualifier is needed) rather than retrying cloud or * silently stalling (PRD §3). + * + * The whole per-chunk loop runs as ONE coroutine (not a chain of + * `scope.launch{}` calls from playback callbacks) specifically so + * [speakJob]`.cancel()` (from [stop]) reliably interrupts whatever chunk is + * currently fetching or playing — an earlier version launched each + * subsequent chunk from `onCompletion`/`onError` outside [speakJob]'s + * tracking, so `stop()` could not prevent an already-in-flight later chunk + * from starting to play (found in review). [CloudPlayback.play]'s + * callback-based API is bridged into a single suspension point via + * [suspendCancellableCoroutine] so playback itself is a real, cancellable + * part of that one coroutine. */ @Singleton class CloudTtsEngine @Inject constructor( @@ -98,48 +115,63 @@ class CloudTtsEngine @Inject constructor( _state.value = _state.value.copy(status = TtsStatus.PLAYING, error = null) speakJob = scope.launch { + val providerId = preferences.selectedCloudProviderFlow.first() + ?.let { runCatching { CloudProviderId.valueOf(it) }.getOrNull() } + val voiceId = preferences.selectedVoiceFlow.first() + if (providerId == null || voiceId == null) { + fallBackTo(text, "no cloud voice selected") + return@launch + } + val credentials = apiKeyStore.loadCredentials(providerId) + if (credentials == null) { + fallBackTo(text, "no saved credentials for $providerId") + return@launch + } + val chunks = splitIntoChunks(text) - speakChunk(chunks, 0) - } - } + for (index in chunks.indices) { + if (!gate.observeCanUseCloudTts().first()) { + fallBackTo(chunks, index, "cloud voices gate is closed (subscription lapsed or consent revoked)") + return@launch + } + + // CancellationException propagates straight through (not + // caught here, and the vendor adapters no longer swallow it + // either — see runCatchingCancellable) so stop() cancelling + // this coroutine ends the loop instead of looking like an + // ordinary synthesis failure that should fall back. + val audioBytes = cloudTtsProvider.synthesize(providerId, chunks[index], voiceId, credentials) + .getOrElse { + fallBackTo(chunks, index, "cloud synthesis failed: ${it.message}") + return@launch + } + + val playError = awaitPlayback(audioBytes) + if (playError != null) { + fallBackTo(chunks, index, "playback error: $playError") + return@launch + } + } - private suspend fun speakChunk(chunks: List, index: Int) { - if (index >= chunks.size) { _state.value = _state.value.copy(status = TtsStatus.IDLE) _completionEvent.tryEmit(Unit) - return - } - - if (!gate.observeCanUseCloudTts().first()) { - fallBackTo(chunks, index, "cloud voices gate is closed (subscription lapsed or consent revoked)") - return - } - val providerId = preferences.selectedCloudProviderFlow.first() - ?.let { runCatching { CloudProviderId.valueOf(it) }.getOrNull() } - val voiceId = preferences.selectedVoiceFlow.first() - if (providerId == null || voiceId == null) { - fallBackTo(chunks, index, "no cloud voice selected") - return - } - val credentials = apiKeyStore.loadCredentials(providerId) - if (credentials == null) { - fallBackTo(chunks, index, "no saved credentials for $providerId") - return } + } - val result = cloudTtsProvider.synthesize(providerId, chunks[index], voiceId, credentials) - val audioBytes = result.getOrElse { - fallBackTo(chunks, index, "cloud synthesis failed: ${it.message}") - return + /** Bridges [CloudPlayback]'s callback API into one suspension point, so + * playback is a real part of [speakJob]'s single coroutine — cancelling + * it (via [stop]) reliably stops in-flight playback rather than racing + * an untracked callback. Returns the error message, or null on success. */ + private suspend fun awaitPlayback(audioBytes: ByteArray): String? = + suspendCancellableCoroutine { continuation -> + playback.play( + audioBytes, + onCompletion = { if (continuation.isActive) continuation.resumeWith(Result.success(null)) }, + onError = { message -> if (continuation.isActive) continuation.resumeWith(Result.success(message)) }, + ) + continuation.invokeOnCancellation { playback.stop() } } - playback.play( - audioBytes, - onCompletion = { scope.launch { speakChunk(chunks, index + 1) } }, - onError = { message -> scope.launch { fallBackTo(chunks, index, "playback error: $message") } }, - ) - } - /** Delegates chunks `[index, chunks.size)` to the on-device engine and * forwards its state/events into this engine's own flows for as long as * fallback stays active, so a caller observing THIS engine's flows sees @@ -152,6 +184,11 @@ class CloudTtsEngine @Inject constructor( * (`android.util.Log` throws "not mocked" in a plain JVM test — same * reasoning as [RealCloudApiKeyStore] using `java.util.Base64`, not * `android.util.Base64`). */ + /** Convenience for a fallback decided before any chunking happened + * (e.g. no provider/voice selected) — the whole [text] goes to the + * fallback engine untouched. */ + private fun fallBackTo(text: String, reason: String) = fallBackTo(listOf(text), 0, reason) + private fun fallBackTo(chunks: List, index: Int, reason: String) { lastFallbackReason = reason isFallenBack = true diff --git a/core/cloudtts/src/play/kotlin/xyz/libravault/core/cloudtts/vendor/AmazonPollyAdapter.kt b/core/cloudtts/src/play/kotlin/xyz/libravault/core/cloudtts/vendor/AmazonPollyAdapter.kt index ed38bcb8..a6697589 100644 --- a/core/cloudtts/src/play/kotlin/xyz/libravault/core/cloudtts/vendor/AmazonPollyAdapter.kt +++ b/core/cloudtts/src/play/kotlin/xyz/libravault/core/cloudtts/vendor/AmazonPollyAdapter.kt @@ -30,7 +30,7 @@ class AmazonPollyAdapter internal constructor( testBaseUrl ?: "https://${CloudTtsFixedHosts.pollyHost(region)}".toHttpUrl() override suspend fun synthesize(text: String, voiceId: String, credentials: Map): Result = - runCatching { + runCatchingCancellable { val accessKeyId = credentials.field(CloudCredentialFields.ACCESS_KEY_ID) val secretAccessKey = credentials.field(CloudCredentialFields.SECRET_ACCESS_KEY) val region = credentials.field(CloudCredentialFields.REGION) @@ -66,7 +66,7 @@ class AmazonPollyAdapter internal constructor( } } - override suspend fun validateKey(credentials: Map): Result = runCatching { + override suspend fun validateKey(credentials: Map): Result = runCatchingCancellable { val accessKeyId = credentials.field(CloudCredentialFields.ACCESS_KEY_ID) val secretAccessKey = credentials.field(CloudCredentialFields.SECRET_ACCESS_KEY) val region = credentials.field(CloudCredentialFields.REGION) diff --git a/core/cloudtts/src/play/kotlin/xyz/libravault/core/cloudtts/vendor/AzureSpeechAdapter.kt b/core/cloudtts/src/play/kotlin/xyz/libravault/core/cloudtts/vendor/AzureSpeechAdapter.kt index bab76e89..73d0e45f 100644 --- a/core/cloudtts/src/play/kotlin/xyz/libravault/core/cloudtts/vendor/AzureSpeechAdapter.kt +++ b/core/cloudtts/src/play/kotlin/xyz/libravault/core/cloudtts/vendor/AzureSpeechAdapter.kt @@ -42,7 +42,7 @@ class AzureSpeechAdapter internal constructor( .newBuilder().addPathSegments("sts/v1.0/issueToken").build() override suspend fun synthesize(text: String, voiceId: String, credentials: Map): Result = - runCatching { + runCatchingCancellable { val apiKey = credentials.field(CloudCredentialFields.API_KEY) val region = credentials.field(CloudCredentialFields.REGION) val locale = localeFromVoiceId(voiceId) @@ -64,7 +64,7 @@ class AzureSpeechAdapter internal constructor( } } - override suspend fun validateKey(credentials: Map): Result = runCatching { + override suspend fun validateKey(credentials: Map): Result = runCatchingCancellable { val apiKey = credentials.field(CloudCredentialFields.API_KEY) val region = credentials.field(CloudCredentialFields.REGION) val request = Request.Builder() diff --git a/core/cloudtts/src/play/kotlin/xyz/libravault/core/cloudtts/vendor/ElevenLabsAdapter.kt b/core/cloudtts/src/play/kotlin/xyz/libravault/core/cloudtts/vendor/ElevenLabsAdapter.kt index 05987fc7..d463709b 100644 --- a/core/cloudtts/src/play/kotlin/xyz/libravault/core/cloudtts/vendor/ElevenLabsAdapter.kt +++ b/core/cloudtts/src/play/kotlin/xyz/libravault/core/cloudtts/vendor/ElevenLabsAdapter.kt @@ -27,7 +27,7 @@ class ElevenLabsAdapter internal constructor( private fun baseUrl(): HttpUrl = testBaseUrl ?: "https://${CloudTtsFixedHosts.ELEVENLABS}".toHttpUrl() override suspend fun synthesize(text: String, voiceId: String, credentials: Map): Result = - runCatching { + runCatchingCancellable { val apiKey = credentials.field(CloudCredentialFields.API_KEY) // addPathSegment (singular) percent-encodes voiceId as ONE opaque // segment — addPathSegments(string) would instead split it on '/' @@ -49,7 +49,7 @@ class ElevenLabsAdapter internal constructor( } } - override suspend fun validateKey(credentials: Map): Result = runCatching { + override suspend fun validateKey(credentials: Map): Result = runCatchingCancellable { val apiKey = credentials.field(CloudCredentialFields.API_KEY) val url = baseUrl().newBuilder().addPathSegments("v1/user").build() val request = Request.Builder().url(url).addHeader("xi-api-key", apiKey).get().build() diff --git a/core/cloudtts/src/play/kotlin/xyz/libravault/core/cloudtts/vendor/GoogleCloudTtsAdapter.kt b/core/cloudtts/src/play/kotlin/xyz/libravault/core/cloudtts/vendor/GoogleCloudTtsAdapter.kt index 7bd23db7..ebf1e498 100644 --- a/core/cloudtts/src/play/kotlin/xyz/libravault/core/cloudtts/vendor/GoogleCloudTtsAdapter.kt +++ b/core/cloudtts/src/play/kotlin/xyz/libravault/core/cloudtts/vendor/GoogleCloudTtsAdapter.kt @@ -44,7 +44,7 @@ class GoogleCloudTtsAdapter internal constructor( private fun baseUrl(): HttpUrl = testBaseUrl ?: "https://${CloudTtsFixedHosts.GOOGLE_CLOUD_TTS}".toHttpUrl() override suspend fun synthesize(text: String, voiceId: String, credentials: Map): Result = - runCatching { + runCatchingCancellable { val apiKey = credentials.field(CloudCredentialFields.API_KEY) val url = baseUrl().newBuilder() .addPathSegments("v1/text:synthesize") @@ -70,7 +70,7 @@ class GoogleCloudTtsAdapter internal constructor( } } - override suspend fun validateKey(credentials: Map): Result = runCatching { + override suspend fun validateKey(credentials: Map): Result = runCatchingCancellable { val apiKey = credentials.field(CloudCredentialFields.API_KEY) val url = baseUrl().newBuilder().addPathSegments("v1/voices").addQueryParameter("key", apiKey).build() val request = Request.Builder().url(url).get().build() diff --git a/core/cloudtts/src/play/kotlin/xyz/libravault/core/cloudtts/vendor/OpenAiAdapter.kt b/core/cloudtts/src/play/kotlin/xyz/libravault/core/cloudtts/vendor/OpenAiAdapter.kt index bdb436b2..2c3c6607 100644 --- a/core/cloudtts/src/play/kotlin/xyz/libravault/core/cloudtts/vendor/OpenAiAdapter.kt +++ b/core/cloudtts/src/play/kotlin/xyz/libravault/core/cloudtts/vendor/OpenAiAdapter.kt @@ -27,7 +27,7 @@ class OpenAiAdapter internal constructor( private fun baseUrl(): HttpUrl = testBaseUrl ?: "https://${CloudTtsFixedHosts.OPENAI}".toHttpUrl() override suspend fun synthesize(text: String, voiceId: String, credentials: Map): Result = - runCatching { + runCatchingCancellable { val apiKey = credentials.field(CloudCredentialFields.API_KEY) val url = baseUrl().newBuilder().addPathSegments("v1/audio/speech").build() val body = buildJsonObject { @@ -46,7 +46,7 @@ class OpenAiAdapter internal constructor( } } - override suspend fun validateKey(credentials: Map): Result = runCatching { + override suspend fun validateKey(credentials: Map): Result = runCatchingCancellable { val apiKey = credentials.field(CloudCredentialFields.API_KEY) val url = baseUrl().newBuilder().addPathSegments("v1/models").build() val request = Request.Builder().url(url).addHeader("Authorization", "Bearer $apiKey").get().build() diff --git a/core/cloudtts/src/play/kotlin/xyz/libravault/core/cloudtts/vendor/VendorTtsAdapter.kt b/core/cloudtts/src/play/kotlin/xyz/libravault/core/cloudtts/vendor/VendorTtsAdapter.kt index 812d4cd2..2aaa9523 100644 --- a/core/cloudtts/src/play/kotlin/xyz/libravault/core/cloudtts/vendor/VendorTtsAdapter.kt +++ b/core/cloudtts/src/play/kotlin/xyz/libravault/core/cloudtts/vendor/VendorTtsAdapter.kt @@ -1,5 +1,6 @@ package xyz.libravault.core.cloudtts.vendor +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import okhttp3.OkHttpClient @@ -49,3 +50,23 @@ internal fun Map.field(name: String): String = * actually looks like. */ internal fun localeFromVoiceId(voiceId: String): String = voiceId.split("-").take(2).joinToString("-").ifEmpty { "en-US" } + +/** + * `kotlin.runCatching` also catches [CancellationException] — a well-known + * structured-concurrency footgun: it turns a coroutine cancellation (e.g. + * `CloudTtsEngine.stop()` cancelling an in-flight `synthesize()` call) into + * an ordinary `Result.failure`, which every adapter's caller then treats as + * "cloud failed, fall back to on-device" — so pressing Stop while a network + * call is in flight would start the on-device engine SPEAKING instead of + * actually stopping (found in review, before this shipped). This rethrows + * [CancellationException] instead of wrapping it, exactly matching + * `runCatching`'s contract for every other [Throwable]. + */ +internal suspend fun runCatchingCancellable(block: suspend () -> T): Result = + try { + Result.success(block()) + } catch (e: CancellationException) { + throw e + } catch (e: Throwable) { + Result.failure(e) + } diff --git a/core/cloudtts/src/test/kotlin/xyz/libravault/core/cloudtts/CloudTtsEngineTest.kt b/core/cloudtts/src/test/kotlin/xyz/libravault/core/cloudtts/CloudTtsEngineTest.kt index 5566bb67..fbaa18e1 100644 --- a/core/cloudtts/src/test/kotlin/xyz/libravault/core/cloudtts/CloudTtsEngineTest.kt +++ b/core/cloudtts/src/test/kotlin/xyz/libravault/core/cloudtts/CloudTtsEngineTest.kt @@ -6,6 +6,7 @@ import io.mockk.just import io.mockk.mockk import io.mockk.Runs import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharedFlow @@ -65,6 +66,19 @@ class CloudTtsEngineTest { Result.success(Unit) } + /** Never returns — suspends forever until cancelled, simulating a + * genuinely in-flight network call for cancellation testing. */ + private class SuspendingCloudTtsProvider : CloudTtsProvider { + override suspend fun synthesize( + provider: CloudProviderId, + text: String, + voiceId: String, + credentials: Map, + ): Result = awaitCancellation() + override suspend fun validateKey(provider: CloudProviderId, credentials: Map): Result = + Result.success(Unit) + } + private class FakeCloudApiKeyStore(private val stored: Map? = null) : CloudApiKeyStore { override suspend fun saveCredentials(provider: CloudProviderId, credentials: Map) = Unit override suspend fun loadCredentials(provider: CloudProviderId): Map? = stored @@ -258,4 +272,74 @@ class CloudTtsEngineTest { assertEquals("hello", fallback.lastSpokenText) } + + @Test + fun `speak continues to the next chunk only after the previous chunk finishes playing`(@TempDir tempDir: File) = runTest { + val scope = CoroutineScope(UnconfinedTestDispatcher(testScheduler)) + val fallback = FakeTtsEngine() + val provider = FakeCloudTtsProvider(result = Result.success(byteArrayOf(1))) + val prefs = preferences(tempDir, scope) + prefs.setSelectedCloudProvider(CloudProviderId.OPENAI.name) + prefs.setSelectedVoice("alloy") + val playback = FakeCloudPlayback() + val engine = buildEngine( + openGate(), + provider, + FakeCloudApiKeyStore(stored = mapOf(CloudCredentialFields.API_KEY to "sk-test")), + prefs, + fallback, + playback, + scope, + ) + // Two "sentences" well past MAX_CHUNK_CHARS (3900) so splitIntoChunks + // produces exactly two chunks. + val longText = "Sentence one. ".repeat(400) + + engine.speak(longText) + advanceUntilIdle() + + assertEquals(1, provider.synthesizeCallCount, "must not fetch chunk 2 before chunk 1 finishes playing") + assertTrue(playback.playedBytes != null) + + // Simulate chunk 1's audio finishing. + playback.onCompletion?.invoke() + advanceUntilIdle() + + assertEquals(2, provider.synthesizeCallCount, "chunk 2 must be fetched once chunk 1's playback completes") + assertNull(fallback.lastSpokenText) + } + + @Test + fun `stop while a cloud synthesis call is in flight cancels it rather than falling back`(@TempDir tempDir: File) = runTest { + val scope = CoroutineScope(UnconfinedTestDispatcher(testScheduler)) + val fallback = FakeTtsEngine() + val provider = SuspendingCloudTtsProvider() + val prefs = preferences(tempDir, scope) + prefs.setSelectedCloudProvider(CloudProviderId.OPENAI.name) + prefs.setSelectedVoice("alloy") + val engine = buildEngine( + openGate(), + provider, + FakeCloudApiKeyStore(stored = mapOf(CloudCredentialFields.API_KEY to "sk-test")), + prefs, + fallback, + FakeCloudPlayback(), + scope, + ) + + engine.speak("hello") + // With an UnconfinedTestDispatcher, speak() has already run eagerly + // up to synthesize()'s awaitCancellation() suspension point here — + // i.e. a real network call is genuinely "in flight". + engine.stop() + advanceUntilIdle() + + assertNull( + fallback.lastSpokenText, + "stop() must cancel the in-flight call, not have it look like an ordinary " + + "synthesis failure that triggers fallback.speak() — this is exactly the bug " + + "kotlin.runCatching's CancellationException-swallowing caused before " + + "runCatchingCancellable fixed it", + ) + } } diff --git a/core/tts/src/main/kotlin/xyz/libravault/core/tts/TtsPreferences.kt b/core/tts/src/main/kotlin/xyz/libravault/core/tts/TtsPreferences.kt index 9d376abf..b3922001 100644 --- a/core/tts/src/main/kotlin/xyz/libravault/core/tts/TtsPreferences.kt +++ b/core/tts/src/main/kotlin/xyz/libravault/core/tts/TtsPreferences.kt @@ -65,6 +65,22 @@ class TtsPreferences constructor( } } + /** + * Shared by all three [TtsEngineType]s' voice selection — ANDROID system + * voice names, POCKET_TTS's sherpa-onnx model voice IDs, and (per + * [SELECTED_CLOUD_PROVIDER_KEY]'s doc) whichever cloud vendor's voice ID + * once `core:cloudtts` exists. + * + * FLAGGED IN REVIEW, not yet fixed here — genuine gap for whoever builds + * the Cloud Voices Settings UI: since this key is shared, switching + * `TtsEngineType` (or the selected cloud provider) without an explicit + * fresh voice pick can hand a stale, engine-incompatible voiceId to + * whichever engine reads it next (e.g. a leftover Pocket TTS model ID + * sent to a cloud vendor's API, which will reject it). The UI must call + * [setSelectedVoice] with `null` (or a valid default for the new + * engine/provider) whenever engine type or cloud provider changes — + * this persistence layer has no way to enforce that itself. + */ val selectedVoiceFlow: Flow = dataStore.data.map { preferences -> preferences[SELECTED_VOICE_KEY] }