Skip to content

feat(android): core:cloudtts engine wiring — makes Cloud TTS reachable (#451) - #468

Merged
libravault-xyz merged 2 commits into
devfrom
feature/cloudtts-android-engine
Aug 23, 2026
Merged

libravault-xyz merged 2 commits into
devfrom
feature/cloudtts-android-engine

Conversation

@libravault-xyz

Copy link
Copy Markdown
Collaborator

What

PR 3 of 4 for Android's half of Premium Cloud TTS Voices (BYOK) — part of #451. Builds on the merged foundation (#462) and vendor-adapters (#465) PRs. This is the PR that first makes the feature reachable at runtime — CloudTtsEngine now exists and is wired into core:tts's engine-selection machinery.

The core:tts / core:cloudtts dependency-direction problem

core:tts is unflavored (shared by feature:reader); core:cloudtts is flavored (fdroid/play). An unflavored module can't cleanly depend on a flavored one — confirmed precedent: feature:settings had to gain its own flavor dimension just to depend on core:billing. Giving core:tts a flavor dimension too would cascade onto feature:reader, for a module with nothing to do with distribution channel.

Resolved via Dagger multibinding (new idiom for this repo — flagging explicitly for review, not slipping it in quietly): TtsEngineFactory now injects Map<TtsEngineType, Provider<TtsEngine>> instead of two concrete constructor params. core:tts contributes ANDROID/POCKET_TTS; core:cloudtts's own (unflavored) Hilt module contributes CLOUD — from outside core:tts, assembled at :app's SingletonComponent. core:tts never compiles against core:cloudtts.

CloudTtsEngine

  • Re-checks CloudTtsGate before every chunk, not just once at engine selection — a subscription lapsing or consent being revoked mid-utterance stops new cloud calls immediately.
  • Falls back to the on-device engine on: closed gate, no provider/voice selected, no saved credentials, HTTP failure, or playback failure. The fallback engine is resolved from the same multibinding map CloudTtsEngine is itself bound into (engines[TtsEngineType.ANDROID]) — Provider-based multibinding maps can reference their own sibling entries without a DI cycle, so no separate qualifier was needed.
  • Forwards the fallback engine's state/completionEvent/stopEvent into its own flows for as long as fallback is active, so a caller observing CloudTtsEngine doesn't see stale/frozen status the moment a fallback happens.
  • New CloudPlayback interface + MediaPlayerCloudPlayback real impl — vendor responses are already-encoded audio, unlike core:tts's PCM-over-AudioTrack PocketPlayback. Fed via MediaDataSource, no temp file.

Preferences

TtsPreferences gained selectedCloudProviderFlow/setSelectedCloudProvider — stored as the raw CloudProviderId.name string, not the type itself, for the same core:tts/core:cloudtts decoupling reason as the multibinding key. Reuses the existing selectedVoiceFlow for the cloud voice ID (no new key needed — same pattern that already serves the other two engines).

Testing

./gradlew :core:tts:testDebugUnitTest :core:cloudtts:testPlayDebugUnitTest :core:cloudtts:testFdroidDebugUnitTest

BUILD SUCCESSFUL, 182 tests (up from 103), all passing. New CloudTtsEngineTest covers every fallback trigger plus the success path, using a real TtsPreferences (temp-file DataStore, not a mock) and fakes for everything else.

Worth calling out: writing this test surfaced a genuine kotlinx-coroutines-test gotcha — DataStore does its file I/O on its own real-Dispatchers.IO scope by default, invisible to advanceUntilIdle()'s virtual clock, so a coroutine launched on a TestDispatcher that reads through it can still be mid-flight the instant the test asserts. Fixed by giving the test's DataStore instance the same dispatcher as the code under test (UnconfinedTestDispatcher(testScheduler)) rather than the default. Documented in the test file for the next person who hits it.

Verification caveat (stated plainly, not glossed over)

Hilt's actual component assembly — does TtsEngineType.CLOUD really resolve at app runtime — can't be fully verified until :app depends on core:cloudtts, which happens in the next PR (Settings UI), not this one. What I did verify here: core:cloudtts and core:tts each compile and test correctly standalone, and the multibinding pattern itself is a well-established Dagger idiom. Full end-to-end Hilt graph resolution is the next PR's job to prove — flagging so nobody mistakes "compiles" for "verified wired."

Not in this PR

Settings UI, disclosure modal, provider/voice picker (needed to actually populate selectedCloudProviderFlow/selectedVoiceFlow/credentials in a real app) — next PR.

Part of #451.

#451)

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<TtsEngineType, Provider<TtsEngine>>
  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.
@github-actions github-actions Bot added the risk:high Touches a sensitive path or exceeds diff-size threshold — always human merge label Aug 23, 2026
@libravault-pipeline-bot libravault-pipeline-bot Bot added the status:needs-review QA passed, awaiting principal-review-agent label Aug 23, 2026
@github-actions

Copy link
Copy Markdown
Contributor

This PR was opened outside the automated pipeline (author isn't libravault-pipeline-bot[bot]) and doesn't link an issue (no Closes #N-style line in its body), so there's no acceptance criteria for qa-agent.yml to verify against — it would otherwise sit with no risk/status label and nothing downstream would pick it up (see issue #223's actual history, and issue #343 for this issue-less case specifically). This deterministic backstop (pr-intake.yml) classified its risk and applied status:needs-review to route it straight to principal review.

@github-actions

Copy link
Copy Markdown
Contributor

📱 iOS Build Status: PASSED

⏭️ iOS Simulator Build & Unit Tests - skipped
✅ 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 github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Principal review — verdict: human-merge

Risk label: risk:high, sanity-checked by re-running .github/scripts/classify_pr_risk.py origin/dev <head> myself — it reports the same result independently (diff is 777 changed lines, over the 400-line auto-merge threshold), so the label is current, not stale. No sensitive_paths glob is hit; size alone forces risk:high here.

Pipeline note for the human who picks this up: per the github-actions comment on this PR, it was opened outside the normal dev-agent → qa-agent flow (author isn't libravault-pipeline-bot[bot], no Closes #N) and routed straight to status:needs-review by the pr-intake.yml backstop. That means no QA agent verified this before I did — everything below is from my own direct verification, not a re-check of someone else's pass.

Verification performed

  • Read the full diff (not just the description) across all 9 changed files.
  • Confirmed all referenced pre-existing types (CloudTtsGate, CloudTtsProvider, CloudApiKeyStore, CloudProviderId, CloudCredentialFields, TtsAudioFocusManager) actually exist and match the shapes used.
  • Ran the exact suite the PR claims passes, myself, on the checked-out head commit:
    ./gradlew :core:tts:testDebugUnitTest :core:cloudtts:testPlayDebugUnitTest :core:cloudtts:testFdroidDebugUnitTest → BUILD SUCCESSFUL, 0 failures/errors across the generated TEST-*.xml reports (207 tests total across the three targets by my count from the XML tests= attributes — I get a different number than the PR's "182", might be counting flavors differently, not a blocker, just flagging the discrepancy for whoever double-checks coverage numbers later).
  • Checked .github/agent-policy.yml's sensitive_paths — none of core/cloudtts/** or core/tts/** match any entry; no undisclosed sensitive-path touch.
  • Checked issue #451's history for the required human sign-off on the new-networking-call policy before confirming this PR doesn't need to re-litigate it: a collaborator-associated human (libravault-xyz) posted an explicit "Human authorization to proceed (security-sensitive gate acknowledged)" / "Human authorization to proceed stands" on #451 before the vendor-adapter work (#465) started. This PR doesn't add any new network call beyond what #465 already had signed off — it only wires the existing CloudTtsProvider into engine selection — so no new sign-off gap here.
  • Traced TtsEngineFactory's Dagger multibinding change end-to-end (TtsModule, CloudTtsModule, TtsEngineTypeKey) — the "core:tts never compiles against core:cloudtts" claim in the PR description checks out; core:tts's own module only contributes ANDROID/POCKET_TTS, core:cloudtts's module contributes CLOUD, both assembled at :app's SingletonComponent. Consistent with the existing feature:settings/core:billing precedent cited in the description.

CONFIRMED finding — filed as #469

CloudTtsEngine.speak()/stop() don't actually cancel an in-flight cloud-synthesis call once the utterance is past its first chunk, letting stale audio resurrect after the engine reports itself stopped.

speak() only tracks the coroutine for chunk 0:

speakJob = scope.launch {
    val chunks = splitIntoChunks(text)
    speakChunk(chunks, 0)
}

speakChunk calls playback.play(audioBytes, onCompletion = { scope.launch { speakChunk(chunks, index + 1) } }, ...) — playback.play doesn't suspend, so speakJob finishes as soon as chunk 0 starts playing. Every later chunk is driven by a brand-new, untracked scope.launch fired from the previous chunk's onCompletion/onError callback — a sibling coroutine under the shared @Singleton CoroutineScope(Dispatchers.Default) (TtsModule.provideTtsCoroutineScope), not a child of speakJob. stop()/speak() calling speakJob?.cancel() cannot reach it.

Concrete sequence: long chapter (> MAX_CHUNK_CHARS = 3900 chars) → chunk 0 finishes → untracked Job B starts synthesizing chunk 1 → user hits Stop (or TtsEngineProvider.switchEngine swaps engines, which also calls oldEngine.stop()) → engine reports IDLE/emits stopEvent, but Job B keeps running in the background → chunk 1's HTTP response arrives later → playback.play() fires anyway, and audio starts playing again after the user already stopped it (or after switching to a different engine entirely). Also means a stop doesn't actually abort the in-flight, user-paid vendor API call.

Not hypothetical from a code-reading standpoint, but I didn't have a device/emulator in this environment to reproduce it end-to-end — flagging it as CONFIRMED because it's a straightforward trace of the actual control flow, not a guess, but a human/QA pass with a running app should double check before treating my repro sequence as gospel.

Root cause of the gap: CloudTtsEngineTest only ever sends "hello"/"hello world" (always chunk 0 only), so the untracked-continuation path introduced by chunking has zero test coverage — AGENTS.md asks for boundary coverage on new code paths, and the multi-chunk boundary is exactly what's missing.

Filed as #469 with a suggested fix direction (bridge playback.play's callback back into the suspending chain instead of firing a fresh top-level launch, so the whole chunk sequence cancels as one unit).

Other notes (non-blocking)

  • fallBackTo's remainingText = chunks.subList(index, chunks.size).joinToString(" ") collapses the original sentence-boundary splits back into one string with single spaces — harmless content-wise, not a bug, just noting it in case it ever matters for punctuation-sensitive vendors.
  • Everything else in the diff (preferences key handling, TtsEngineFactory/TtsEngineFactoryTest changes, CloudPlayback/MediaPlayerCloudPlayback) reads correctly and matches its own documentation.

Outcome

risk:high (diff size, confirmed current) and a CONFIRMED finding (#469) — both independently already require human-merge per policy. Routing there.

@github-actions github-actions Bot added status:needs-human-merge Principal review done, requires human merge decision and removed status:needs-review QA passed, awaiting principal-review-agent labels Aug 23, 2026
…edup

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-xyz

Copy link
Copy Markdown
Collaborator Author

Ran an independent review pass (code-review skill, high effort) — found 2 high-severity bugs and fixed both, plus 3 real cleanups. (1) kotlin.runCatching in all 5 vendor adapters (from the already-merged PR #465) also swallows CancellationException, so stop() cancelling an in-flight cloud request looked like an ordinary failure and triggered fallback-and-speak instead of actually stopping — fixed at the root with a new runCatchingCancellable() helper, swapped into all 10 call sites. (2) each chunk after the first was launched via an untracked scope.launch{} from a playback callback, so stop() couldn't cancel an already-in-flight later chunk — restructured into one continuous coroutine with CloudPlayback bridged via suspendCancellableCoroutine, so cancellation now reliably propagates. Also: CloudPlayback/MediaPlayer wasn't thread-safe across the two threads that actually call it (fixed with synchronized), provider/voice/credentials were redundantly re-resolved every chunk (now resolved once per speak() call), and a real shared-preference-key staleness risk (selectedVoiceFlow shared across all 3 engine types) is now prominently documented for the Settings UI PR to handle. Added tests for both bugs, including one that simulates a genuinely in-flight network call via awaitCancellation(). 211 tests now, all passing.

@github-actions

Copy link
Copy Markdown
Contributor

📱 iOS Build Status: PASSED

⏭️ iOS Simulator Build & Unit Tests - skipped
✅ 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

@libravault-xyz
libravault-xyz merged commit 47081ca into dev Aug 23, 2026
8 checks passed
@libravault-xyz
libravault-xyz deleted the feature/cloudtts-android-engine branch August 23, 2026 15:00
libravault-xyz added a commit that referenced this pull request Aug 24, 2026
* feat(ios): core Cloud TTS foundation — Keychain store, consent, pure gate

PR 1 of 4 for iOS's half of Premium Cloud TTS Voices (BYOK), issue #452.
Mirrors Android's core:cloudtts foundation (#462), adapted where iOS's
own conventions genuinely differ rather than ported literally.

New Sources/Features/CloudTTS/:
- CloudProviderId — the PRD's closed 5-vendor list (§3).
- CloudCredentialFields — per-provider required-field sets (Amazon
  Polly's SigV4 needs 3 fields, Azure needs 2, the rest need 1 bearer
  key) — same reasoning as Android's identical Map<String,String>
  credential shape, kept in sync by hand.
- CloudApiKeyStore protocol + KeychainCloudApiKeyStore — one
  kSecClassGenericPassword item per provider, kSecAttrAccessibleWhen
  UnlockedThisDeviceOnly. Deliberately does NOT additionally wrap
  through HardwareKeyWrap/the Secure Enclave the way Android's
  RealCloudApiKeyStore wraps through HardwareKeyWrapFactory before
  writing to DataStore — that extra layer exists on Android because a
  DataStore file has no OS-level encryption-at-rest of its own; the
  Keychain already provides that here, and a BYOK vendor key isn't
  LibraVault's root of trust the way the vault master key is.
- CloudVoicePreferences — consent/selected-provider/selected-voice-id,
  mirrors SupporterStatusPersistence's shape (not bolted onto
  UserPreferencesPersistence, whose existing keys use the opposite
  "true by default" polarity).
- CloudTtsGate — pure function, not a class wrapping live
  StoreKitBillingManager/CloudVoicePreferences: StoreKitBillingManager
  needs a live SKTestSession to test for real (documented Xcode 26.5
  CLI gap), so the actual AND logic lives in a function of two Bools
  instead, letting CloudTtsGateTests cover all four quadrants with no
  StoreKit dependency at all.
- CloudTtsProvider protocol — shared shape for the 5 vendor adapters
  (next PR).

Tests: CloudTtsGateTests (4-quadrant + explicit "subscription alone
never opens the gate" regression guard), CloudVoicePreferencesTests,
CloudCredentialFieldsTests, CloudApiKeyStoreTests (real Keychain
round-trip — guarded with the same errSecMissingEntitlement XCTSkip
pattern SecureEnclaveHardwareKeyWrapTests already uses for this CI
job's CODE_SIGNING_ALLOWED=NO environment), FakeCloudApiKeyStore for
downstream test targets (engine/UI PRs).

No Xcode/macOS available in this environment — verified by careful
manual review against this codebase's existing conventions (matched
HardwareKeyWrap/SecureEnclaveHardwareKeyWrapFactory's Keychain query
style, SupporterStatusPersistence's UserDefaults shape, and the
skipIfKeychainKeyPersistenceUnavailable CI gotcha) rather than a local
build; real verification is this PR's CI run (ios-app-build.yml).

Closes nothing yet — first of 4 iOS PRs for #452.

* feat(ios): Cloud TTS vendor adapters — 5 vendors + AWS SigV4 signer

PR 2 of 4 for iOS's half of Premium Cloud TTS Voices (BYOK), progress
toward #452. Builds on the (as-yet-unmerged) foundation PR (#472).
Direct Swift port of Android's 5 vendor adapters (#465) + AwsSigV4Signer
(#467/#466) — same verified real API shapes, same algorithm, ported
rather than re-researched from scratch so both platforms stay provably
aligned.

New Sources/Features/CloudTTS/Vendors/:
- CloudTtsFixedHosts — the fixed, closed set of hosts (PRD §7); Azure/
  Polly pin the host *pattern* (region-scoped), not a literal.
- VendorTtsAdapter protocol + shared executeOrFail/localeFromVoiceID/
  jsonBody helpers. Deliberately NOT guarded by the isRunningUnderXCTest
  check TTSEngineBridge/PocketTTSEngine/StoreKitBillingManager use —
  that guard exists specifically for audio-hardware activation hangs
  in the CI Simulator, which a plain URLSession HTTP call has no
  dependency on; applying it here would also silently no-op every
  adapter test against MockURLProtocol. The engine PR's AVAudioPlayer-
  based playback is where that guard actually belongs, matching the
  precedent's real scope.
- ElevenLabsAdapter/OpenAIAdapter/GoogleCloudTtsAdapter/AzureSpeechAdapter/
  AmazonPollyAdapter — same per-vendor auth/body/host shapes as their
  Kotlin counterparts (xi-api-key header, bearer token, API-key query
  param + base64 JSON response, region-scoped SSML + Ocp-Apim key,
  SigV4).
- AwsSigV4Signer — direct port of the Kotlin signer, using CryptoKit
  (already a dependency here) instead of javax.crypto. Reuses the SAME
  known-answer test vectors already cross-checked against botocore for
  Android (#466), rather than re-deriving a second independent check —
  if both platforms' signers match the same pinned values, they're
  provably computing the same algorithm.
- RealCloudTtsProvider — dispatches to the right vendor adapter by
  CloudProviderId. No fdroid-equivalent NoOp needed (iOS has one
  distribution channel).

Testing: MockURLProtocol (hand-rolled URLProtocol mock — this repo has
no network-test dependency, matching the "no new deps" constraint) +
per-vendor test suites mirroring the Kotlin MockWebServer tests'
coverage (auth header/body shape, non-2xx fails closed, missing-
credential fails closed, path-traversal/XML-injection regression
guards for the two adapters with caller-controlled path/SSML content),
AwsSigV4SignerTests (structural + the reused known-answer vectors),
CloudTtsFixedHostsRegressionTests, RealCloudTtsProviderTests (dispatch
correctness via which real host each provider's request lands on).

No Xcode/macOS available in this environment — verified by careful
manual review and direct comparison against the already-reviewed,
already-merged Kotlin implementation, not a local build. Real
verification is this PR's own CI run.

Part of #452. Depends on #472 (not yet merged) — this branch merges
that branch's commits in directly so it builds/tests standalone;
retarget to dev once #472 merges.

* feat(ios): Cloud TTS engine wiring — makes Cloud TTS reachable

PR 3 of 4 for iOS's half of Premium Cloud TTS Voices (BYOK), progress
toward #452. Builds on the (as-yet-unmerged) vendors PR (#476). First
PR where CloudTtsEngine is actually reachable via TTSEngineType.cloud
— mirrors Android's engine-wiring PR (#468).

- TTSEngineType gains `.cloud`; LibravaultDomainBridge.switchTTSEngine
  (to:)'s ternary becomes a switch with a new .cloud branch.
- New configureCloudTts(billingManager:) on the bridge singleton — its
  only path to a live StoreKitBillingManager, called once from
  AppState.init before ttsEngineType's own didSet can ever request
  .cloud (ordering documented at both call sites).
- CloudTtsEngine (@mainactor, TTSEngineProtocol): re-checks
  CloudTtsGate on every speak() call, not just once at engine
  selection — subscribed+consent+configured-provider+voice-id all
  required, matching Android's engine. Falls back to the on-device
  engine (TTSEngineBridge) on gate-closed, not-configured, vendor
  failure, or playback failure — never a silent stall.
- Explicitly does NOT fall back on cancellation: catches both
  CancellationError (Task cancellation) AND URLError(.cancelled)
  (URLSession's own cancellation surfacing, a real Foundation nuance
  distinct from CancellationError) and returns without falling back —
  the Swift equivalent of Android's runCatchingCancellable fix.
  Covered by a dedicated regression test using a hangUntilCancelled
  fake provider, mirroring Android's SuspendingCloudTtsProvider/
  awaitCancellation() test.
- isSubscribedProvider is an injected @mainactor closure, not a direct
  StoreKitBillingManager dependency — keeps CloudTtsEngine's own unit
  tests fully StoreKit-free (only a thin wiring test would ever need
  real StoreKit, per the implementation plan's "Known gaps" section).
- CloudPlayback / AVAudioPlayerCloudPlayback: AVAudioPlayer-backed,
  always hints .mp3 (every vendor adapter explicitly requests MP3 —
  no per-format sniffing needed here, unlike VaultAudioPlaybackEngine's
  arbitrary-import case). Reuses that same file's already-proven-
  necessary "always pass an explicit fileTypeHint" fix (omitting it
  silently reports duration 0 instead of throwing — a real CI-caught
  bug there, not re-discovered here). Split into load()/play() the
  same way, so decode failures are testable without touching audio
  hardware. NSLock-guarded continuation resolution: stop() (main
  actor) and the AVAudioPlayerDelegate finish callback (AVAudioPlayer's
  own thread) can race to resolve the same continuation, which is a
  fatal double-resume, not just a logic bug — proactively applying the
  same fix Android's MediaPlayerCloudPlayback needed after review found
  the identical race there.

Testing: CloudTtsEngineTests (gate/config fallback paths, happy path,
vendor/playback failure fallback, the cancellation-doesn't-fall-back
regression test, pause/resume routing, initialize()) with fully
scripted fakes (FakeCloudTtsProvider/FakeCloudPlayback/FakeTTSEngine —
no real network/audio in any test); AVAudioPlayerCloudPlaybackTests
(load() decode-failure cases only, mirroring
VaultAudioPlaybackEngineTests' isRunningUnderXCTest-safe scope —
flagged explicitly: no "successfully decodes real MP3" test, since
hand-writing a valid MP3 fixture wasn't done here, unlike that file's
hand-written WAV).

No Xcode/macOS available in this environment — verified by careful
manual review, matching this codebase's established conventions
(VaultAudioPlaybackEngine's fileTypeHint/isRunningUnderXCTest split,
AppState's @MainActor-default-argument-initialization-order gotcha,
Android's runCatchingCancellable precedent). Real verification is this
PR's own CI run.

Part of #452. Depends on #476.

* fix(cloudtts-ios): ElevenLabs voiceID path segment wasn't actually percent-encoded

Real CI failure, not caught locally (no Xcode available when this was
first written): URL.appendingPathComponent(_:) does NOT percent-encode
"/" in its argument the way Kotlin's addPathSegment (singular) does —
it treats "/" as a literal path separator (that's the whole point of
the method: appendingPathComponent("a/b/c") is the same as three
separate appends). A voiceID containing a slash was therefore NOT
percent-encoded as one opaque segment as the code's own comment
claimed — CI's testSlashInVoiceIDIsPercentEncodedNotSplitIntoExtra
PathSegments failed for real against
api.elevenlabs.io/v1/text-to-speech/abc/../admin, the exact path-
traversal shape that test exists to catch.

Fixed by percent-encoding voiceID myself first (CharacterSet
.urlPathAllowed minus "/", so "/" becomes "%2F") and assigning it via
URLComponents.percentEncodedPath, which stores/uses already-encoded
content as-is rather than re-interpreting it. No other adapter has
this bug: ElevenLabs is the only one that puts voiceID into a URL
path segment — the other four put it in a JSON body or XML-escaped
SSML, neither of which goes through appendingPathComponent.

Verified: this is exactly what the existing regression test already
asserted (abc%2F..%2Fadmin) — no test change needed, only the
production code was wrong.

* fix(ios): resolve Task<Void, Never> type mismatch in CloudTtsEngine.speak()

self?.performSpeak(...) inside the weak-self Task closure inferred
Task<()?, Never> (optional chaining on an async call returning Void
still returns Void?), which doesn't match the declared
activeTask: Task<Void, Never>?. Unwrap self with guard let first so
the closure's return type is plain Void.

Fixes the Swift compile error blocking PR #478's CI (Build & Test iOS
(Simulator)).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk:high Touches a sensitive path or exceeds diff-size threshold — always human merge status:needs-human-merge Principal review done, requires human merge decision

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant