Skip to content

feat(ios): Cloud TTS engine wiring — makes Cloud TTS reachable - #477

Closed
libravault-xyz wants to merge 4 commits into
feature/cloudtts-ios-vendorsfrom
feature/cloudtts-ios-engine
Closed

libravault-xyz wants to merge 4 commits into
feature/cloudtts-ios-vendorsfrom
feature/cloudtts-ios-engine

Conversation

@libravault-xyz

Copy link
Copy Markdown
Collaborator

What

PR 3 of 4 for iOS's half of Premium Cloud TTS Voices (BYOK) — progress toward #452. Stacked on the not-yet-merged vendors PR (#476) — base branch is feature/cloudtts-ios-vendors, not dev; will retarget once #476 merges. First PR where CloudTtsEngine is actually reachable via TTSEngineType.cloud — mirrors Android's engine-wiring PR (#468).

Changes

  • 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 (the bridge is a singleton with no dependencies of its own). 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. 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, not a hypothetical one) and returns without falling back — the Swift equivalent of Android's runCatchingCancellable fix (kotlin.runCatching also catches CancellationException, which turned pressing Stop mid-request into the fallback engine audibly starting up). 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.
  • 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, confirmed against workflow run 32392013297, not re-discovered here). Split into load()/play() the same way that file is, so decode failures are testable without touching audio hardware.
  • NSLock-guarded continuation resolution in AVAudioPlayerCloudPlayback: stop() (main actor) and the AVAudioPlayerDelegate finish callback (AVAudioPlayer's own thread) can race to resolve the same CheckedContinuation, 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, rather than waiting to rediscover it.

Testing

CloudTtsEngineTests — gate/config fallback paths (not subscribed, consent off, no provider, empty voice id, unconfigured provider), the happy path (synthesize → play, no fallback), vendor/playback failure fallback, the cancellation-doesn't-fall-back regression test, pause/resume routing (cloud vs. fallback), initialize(). All against 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 — hand-writing a valid MP3 fixture byte-for-byte wasn't done here, unlike that file's hand-written WAV. A real coverage gap, not silently claimed as covered.

Also not covered: a DomainBridgeTests case exercising switchTTSEngine(to: .cloud) through the real LibravaultDomainBridge.shared singleton — deliberately skipped to avoid new cross-test global-state coupling (existing DomainBridgeTests share that singleton across test methods); CloudTtsEngine's own unit tests already cover the actual gate/fallback logic, which is the real risk surface.

Known limitation of this PR

No Xcode/macOS available in the environment this was written in — verified by careful manual review against this codebase's established conventions. Real verification is this PR's own CI run.

Part of #452. Depends on #476.

…gate (#472)

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.
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.
@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 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 is correct and current — re-ran classify_pr_risk.py origin/feature/cloudtts-ios-vendors feature/cloudtts-ios-engine against the latest commit (29ace31) myself: 672 changed lines vs. the 400-line auto-merge threshold, no sensitive-path match. That alone already forces human-merge regardless of anything below.

Code read (the diff itself)

I read the full diff, not the description. CloudTtsEngine/CloudPlayback/DomainBridge/AppState/TTSEngineProtocol all check out against ground truth:

  • Every type/method this PR calls into from the not-yet-merged base (CloudTtsGate.canUseCloudTts, CloudVoicePreferences.load*/save*, CloudApiKeyStore.load, CloudTtsProvider.synthesize, RealCloudTtsProvider, KeychainCloudApiKeyStore) exists with the exact signature used here — verified by reading each file, not assuming from the PR prose.
  • bridge.configureCloudTts(billingManager:) really is called in AppState.init before ttsEngineType = userPreferencesPersistence.loadTTSEngineType() — the ordering claim in the comment is accurate (AppState.swift:214-227).
  • The NSLock-guarded finishContinuation in AVAudioPlayerCloudPlayback — read through the stop()/audioPlayerDidFinishPlaying/resolveContinuation interplay for a double-resume; the nil-out-under-lock pattern correctly makes a second resolver a no-op. No bug found there.
  • Cancellation handling in performSpeak (CancellationError + URLError(.cancelled) both skip fallback) matches the PRD'd behavior and is exercised by testStopCancelsInFlightSynthesizeCallWithoutFallingBack.
  • TTSEngineType.cloud / switchTTSEngine's new switch branch / gate-closed fallback logging: correct, no dead code or unreachable branch.

I did not find a new, independent bug introduced by this PR's own diff.

Why this still can't be verified end-to-end — the actual blocker

This is exactly the "confirm CI against ground truth, don't take the sentence at face value" case the review mindset calls out:

  • ios-app-build.yml never ran on this PR at all. gh pr checks 477 / the check-suites API show no iOS build job — not skipped-with-a-path-filter-reason, genuinely absent — because this PR's base is feature/cloudtts-ios-vendors, and that workflow's pull_request.branches trigger only matches dev/feat/v3-ios-port. This is the exact, already-diagnosed gap in #475 ("ios-app-build.yml never triggers for PRs stacked on an unmerged base branch"), filed during review of this same stack's PR #473. #475 is still open/unfixed, and #477 is a second live instance of it: none of this PR's new Swift (CloudTtsEngine.swift, CloudPlayback.swift, the two new test files) has ever been compiled or executed by CI.
  • This PR was also never seen by the QA agent — gh pr view 477 --json comments shows only the pr-intake.yml backstop comment (opened outside the pipeline, no linked issue, routed straight to status:needs-review). So neither automated stage that would normally run the real test suite actually did.
  • The branch this stacks on has a known, still-open, CI-confirmed bug: #474 — ElevenLabsAdapter's voiceID path-traversal guard doesn't actually percent-encode /, and its own regression test asserts the wrong expected value (would fail if it ever ran — which, per #475, it didn't, until PR #476's build finally surfaced it: gh run view 32654874693 shows ElevenLabsAdapterTests.testSlashInVoiceIDIsPercentEncodedNotSplitIntoExtraPathSegments failing for real on 2026-08-23T17:32). #476 is still open with that failing check. This PR is stacked directly on top of that unresolved state.
  • AGENTS.md's "rebase feature branches onto dev before opening a PR" convention (line 184) wasn't followed here either — three PRs deep on unmerged branches is exactly how the CI gap above went unnoticed for #473 and is repeating for #477.

None of this is a defect in the code this diff adds — CloudTtsEngine/CloudPlayback read correctly on inspection — but "I read it carefully and it looks right" is not the bar this pipeline is supposed to clear, and per the review mindset, being unable to confirm CI actually validated this code is treated the same as a CONFIRMED finding: it forces human-merge on its own, independent of the diff-size label.

Not filing new issues — #474 and #475 already cover both root causes exactly (searched gh issue list --search first); this PR is another instance of both, not a new bug. Recommend a human hold this until #476 merges clean (fixing #474) and either #475 is fixed or this stack is retargeted straight at dev so ios-app-build.yml actually runs and gives a real signal before merge.

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