Skip to content

feat: isolate LiveKit voice into a separate AEPVoice library (Option A) - #165

Closed
nozokada wants to merge 28 commits into
adobe:mainfrom
nozokada:feat/voice-packaging-option-a
Closed

nozokada wants to merge 28 commits into
adobe:mainfrom
nozokada:feat/voice-packaging-option-a

Conversation

@nozokada

Copy link
Copy Markdown
Member

Summary

Repackages the LiveKit voice PoC so that LiveKit/WebRTC is no longer a dependency of the core AEPBrandConcierge distribution. This implements Option A from Documentation/Implementation/voice-packaging-architecture-design.md: a dependency-free interface in the core module plus a separate, opt-in library holding the concrete LiveKit-backed implementation.

Branched fresh from main (the validated PoC commits were cherry-picked, not built on top of the PoC branch), so the history is clean and reviewable.

What changed

  • New VoiceHandling protocol (+ VoiceSessionState, VoiceTranscriptRole) in AEPBrandConcierge — no third-party imports, same opt-in shape as the un-defaulted TextSpeaking.
  • ChatController holds an injected, optional VoiceHandling? instead of owning a concrete instance; threaded through Concierge.show/present, applyPresentationConfiguration, and ConciergeChatSession. The composer voice trigger is hidden when no handler is injected.
  • New AEPVoice library (SPM product + Xcode framework target) holding the LiveKit-backed VoiceSessionController and the data-channel wire types; depends on AEPBrandConcierge + LiveKit.
  • LiveKit removed from the core target/product/podspec (Package.swift, .xcodeproj, .podspec). The demo app links + embeds AEPVoice and injects VoiceSessionController.
  • Tests: voice tests moved into a new AEPVoiceTests target under AEPVoice/Tests/UnitTests/; base-module tests use a dependency-free FakeVoiceHandling and no longer need LiveKit.

Module boundary

  • Core AEPBrandConcierge has zero reference to AEPVoice or LiveKit (verified — not even in doc comments).
  • AEPVoice depends only on the public seam (VoiceHandling / VoiceSessionState / VoiceTranscriptRole).
  • The AEPVoice/ directory (Sources + Tests) is self-contained, ready to extract into its own library later.

Test plan

  • Pure SPM build of both products (core builds with no LiveKit; AEPVoice builds with it)
  • ConciergeDemoApp builds via the workspace
  • pod lib lint passes (core pod is now LiveKit-free)
  • UnitTests (675) + AEPVoiceTests (20) pass
  • On-device voice flow verified working
  • Reviewer sanity check

Notes for reviewers

  • ConciergeDemoApp keeps a LiveKit link even though it doesn't import LiveKit. This is only to make Xcode embed LiveKit's transitive binary xcframeworks into the .app; in this xcodeproj host, Xcode won't embed them through the intermediate AEPVoice.framework (dropping the link builds but crashes at launch — verified). An SPM-integrated host app gets this embedding automatically and never names LiveKit. See the note in Podfile.
  • Voice is SPM-only: LiveKit 2.17.0 can't be resolved via CocoaPods, so voice isn't offered via CocoaPods (the core pod is unaffected).
  • The two lower-level voice design docs (voice-livekit-connection-bootstrap-design.md, voice-livekit-audio-session-design.md) were updated for the new module boundary on the separate docs/livekit-voice-design-docs branch (not part of this PR).

🤖 Generated with Claude Code

Adds LiveKit 2.17.0 as a native Xcode Swift Package dependency on the
AEPBrandConcierge and ConciergeDemoApp targets (not via CocoaPods: LiveKit's
CocoaPods distribution stopped at 2.0.18, and the newer required LiveKitUniFFI
dependency was never published to CocoaPods trunk at all, so 2.17.0 cannot be
resolved that way). Podfile/podspec are updated with comments explaining this
gap for CocoaPods-based consumers.

Also removes APPLICATION_EXTENSION_API_ONLY from the AEPBrandConcierge target:
LiveKit's camera capture code is not app-extension-safe, so building this SDK
as extension-safe is no longer possible once LiveKit is linked.
Wire model + bootstrap plumbing for LiveKit voice, ahead of the LiveKit
dependency itself. No LiveKit dependency is added in this phase.

- VoicePayload model and ConversationResponse.voice (additive, optional;
  relies on synthesized Codable, so text-turn decode is unchanged)
- LiveKitSessionBootstrap: validated resolved-credentials type
- ConciergeChatService.createVoiceBootstrapPayload / bootstrapVoiceSession,
  reusing streamChat's endpoint/session/auth-token/consent plumbing and the
  existing SSE delegate path; resolves on a response.voice livekit_session
  payload, with completion/error semantics matching streamChat
- Extract the shared conversation-event envelope out of createChatPayload
- Unit tests: bootstrap payload shape, decode with/without voice, and the
  bootstrap request path (delivers credentials, no-payload completion,
  network error, unbuildable URL)

Wire type/field names mirror the shared backend worker contract used by web.
…sh (Phase 2)

Introduce VoiceSessionController — the sibling to SpeechController that owns
the LiveKit Room for a voice session. This phase covers connection, mic
publish, and remote-audio subscribe; the data-channel turn state machine and
ChatController wiring are a later phase.

- start(url:token:)/stop() bracket the Room connect/disconnect lifecycle and
  drive a small State enum (idle/connecting/listening/failed); LiveKit
  auto-subscribes and renders the remote (TTS) audio track
- Hand the full-duplex, echo-cancelled audio policy to LiveKit's AudioManager
  (.playAndRecord/.videoChat + speaker/Bluetooth/AirPlay options, mixWithOthers
  omitted) rather than calling AVAudioSession directly — LiveKit stays the sole
  session owner while a Room exists
- Request record permission via the non-deprecated AVAudioApplication API on
  iOS 17+
- Audio-session interruption handling: mute the mic on .began, restore on
  .ended with .shouldResume
- Unit tests for the audio policy values and initial state; connect/mic/
  interruption behavior is validated on real devices per the audio-session
  design (not meaningfully testable in the simulator)
Swift mirror of the worker's data-channel wire contract (LiveKitContracts.ts)
and its parser (voiceStreamingUtils.ts). Type/field names are copied verbatim
from the TypeScript source since the backend worker is shared across clients
(NFR-03).

- Models/Voice/DataChannelMessage: DataChannelMessage enum + TranscriptDeltaData,
  TurnDoneData, UiPayloadData, SessionNoticeData, EndReason — only the subset the
  buffered-transcript PoC consumes (ui_payload is parsed but not yet rendered)
- DataChannelMessageParser: normalizes both on-wire formats — type-based (user STT
  transcript_delta, session_notice) and event-based (assistant text_delta/
  turn_completed/…) — mirroring parseDataChannelMessage, including the turnId
  omit-when-empty and EndReason validate-against-known-set rules
- Unit tests mirroring voiceStreamingUtils.test.ts coverage
… (Phase 3.2/3.3)

Connect the bootstrap (Phase 1) and VoiceSessionController (Phase 2) into the
chat, and buffer the voice transcript into the existing message list per FR-05.

- VoiceSessionController: receive data-channel frames (didReceiveData), parse via
  DataChannelMessageParser, and buffer transcript/turn text — user transcript_delta
  (accumulated to final) and assistant turn_done.fullText — into bufferedTranscript;
  tear down on a worker session_ended notice
- ChatController: own the VoiceSessionController; startVoiceSession() bootstraps
  credentials then connects the Room; stopVoiceSession() ends it. On session end
  (user- or worker-initiated) the buffered transcript is appended to `messages` as
  plain bubbles; a failed start surfaces a user-visible message (FR-07)
- ChatState.voiceSession gates text input, dictation mic, and send off for the
  session's duration, and voice start is gated against a processing turn / active
  dictation (FR-06 mutual exclusion)
- Unit tests for the transcript→bubble mapping, gating, and start/stop guards; the
  end-to-end connect/turn flow is validated on device per the design docs
A functional tap target to start/stop a LiveKit voice session from the chat
composer, so the Phase 3 flow can be exercised on device. This is a demo
trigger, not the final voice-mode UI (separate design).

- ChatComposer: waveform toggle button (red while active), wired via new
  defaulted props so existing call sites (snapshot tests) are unaffected
- ChatComposerContainer: toggles start/stopVoiceSession and routes
  composerEditable through the controller so text input gates off during a
  voice session (FR-06)
Demo-only: switches ConciergeDemoApp to the mobileapp://conciergetestapp/home
surface and the matching stage appId/configId so the LiveKit voice bootstrap
can be exercised on device. Environment-specific — drop this commit before any
merge to main.
Verified against the working stage voice client (bc-voice-test/sdk-load): the
initial Phase 1 assumption that bootstrap reuses the text-turn endpoint/shape
was wrong.

- Endpoint: voice bootstrap POSTs to /brand-concierge-voice/conversations, not
  the text path /brand-concierge/conversations (createUrl now takes a path)
- Payload: the discriminator rides in conversation.data.type = "livekit-bootstrap"
  (the same data slot the text turn uses for its auth part), not a top-level
  conversation.type; publishMic is not sent. Voice bootstrap authenticates via
  Edge identity/ECID, so the app auth token is not attached
- Update the payload-shape unit tests accordingly
…demo only)

Replaces the earlier (invalid) datastream with the values captured from the
working voice client: datastream/edge configId c906f3b3…, IMS org
0F211E64…_AdobeOrg (so the ECID is minted under the datastream's org), and the
matching web surface. Environment-specific — drop before any merge to main.
Reverts the sdk-load environment values I mistakenly swapped in. Uses the
official Kings setup: appId staging/a0ff8cfcfb87/…/launch-481f6ff16749 and
surface mobileapp://conciergetestapp/home, with the existing datastream/server
override. The voice fix is the endpoint/payload change, not the config.
Replace the buffer-until-session-end approach (FR-05 v1) with incremental
rendering, now that the demo confirmed the end-to-end flow works.

- VoiceSessionController: emit onTranscriptUpdate(role, runningText, isFinal) as
  data-channel messages arrive — user transcript_delta accumulated to final,
  assistant text_delta streamed and finalized by turn_done — instead of buffering
- ChatController: applyVoiceTranscriptUpdate updates the in-progress user/assistant
  bubble in place (or starts a new one), closing it on final; per-role turn indices
  reused across turns. finishVoiceSession no longer appends a buffered transcript
- Tests for the live-render logic (in-place update, per-turn new bubbles, ordering,
  gated to an active session)

Still deferred (web LiveKitVoiceManager parity): barge-in, watchdogs, turnId
staleness, rich ui_payload rendering.
Two issues surfaced on device:

1. UI "echo": the user bubble concatenated every partial ("hello tell mehello
   tell me about..."). User STT sends a cumulative snapshot on each
   transcript_delta (not an incremental piece), so it must be used directly, not
   appended. Assistant text_delta stays incremental (append). Matches web.

2. Audio echo (TTS captured as input): the mic stayed open during the assistant's
   turn, so the device's own TTS was transcribed back as user input. Mute the mic
   on user-final (and on an assistant-first greeting) and reopen it on turn_done —
   the half-duplex mic management web does via mute-on-enter-processing. Barge-in
   stays deferred.
…(barge-in)

Correcting the earlier over-mute: web does NOT mute for the whole assistant turn.
It mutes only during the brief "processing" gap (user-final → assistant starts
responding), then unmutes on enter-responding and relies on AEC to keep the TTS
out of the captured signal — which is what makes barge-in work.

- Mute on user transcript final (processing gap only)
- Unmute as soon as the assistant starts responding (first text_delta) and on
  turn_done — mic stays live during the assistant's speech so the user can
  interrupt; AEC removes the TTS echo
…init

The room was only disconnected via the voice toggle button — closing the chat or
backgrounding the app while a session was active left the room connected
server-side (observed: a room held open for over an hour). Add three teardown
paths:

- ChatView.onDisappear now calls stopVoiceSession() (no-op when inactive)
- VoiceSessionController ends the session on UIApplication.didEnterBackground
  (foreground-only per the audio-session design)
- deinit disconnects the room as a safety net if torn down without stop()
Previously the mic was only published after Room.connect() completed, so speech
spoken before the "publish success" moment was dropped (the user had to wait for
the mic track to publish before being heard).

Use room.withPreConnectAudio { connect } so LiveKit captures mic audio while the
Room connects and flushes it to the agent once the mic track publishes (connect
auto-publishes the recorded track with the preconnect option). The worker already
supports this (preconnect_audio_timeout_s). Falls back to the plain connect +
setMicrophone path if the preconnect capture can't start, so a working session is
never regressed.
…e chirp)

The per-turn mute during the processing gap (user-final → assistant responds)
made iOS play a mic state-change sound on every mute/unmute — audibly annoying
each turn. Remove it: the mic now stays live for the whole session. Echo is
still handled by AEC (verified on device) and barge-in keeps working, so the
mute was only a minor optimization. The phone-call interruption mute is
unaffected.
Surface the conversation session ID in the header as a small monospaced chip
that copies to the clipboard on tap, to make correlating a run with the LiveKit
room / worker logs easy (the value matches the request sessionId and the room
name). Compiled only in DEBUG builds, so it never ships in release.

- ChatController.sessionId exposes configuration.sessionId
- ChatTopBar renders the chip (UIPasteboard copy + brief "Copied" feedback)
…eads

AudioManager.shared.sessionConfiguration is dead as of LiveKit 2.17.0 —
AudioSessionEngineObserver.selectConfiguration only consults
isSpeakerOutputPreferred/isPlatformVoiceProcessingExpected, so the fixed
AudioSessionConfiguration set here never reached AVAudioSession. Switch to
isSpeakerOutputPreferred (which does resolve to the same .playAndRecordSpeaker
preset), re-asserted per session in start() rather than once in init(), since
AudioManager.shared is process-wide state this class doesn't own.

Drop the audioSessionCategory/audioSessionMode/audioSessionCategoryOptions
constants and their tests now that configureAudioSessionPolicy() no longer
builds an AudioSessionConfiguration from them; the rationale they documented
moves into configureAudioSessionPolicy()'s doc comment.
Introduce the dependency-free VoiceHandling protocol (plus VoiceSessionState /
VoiceTranscriptRole) in AEPBrandConcierge, and move the concrete LiveKit-backed
VoiceSessionController and its data-channel wire types into a new, separate
AEPVoice library/target that depends on AEPBrandConcierge and LiveKit.

ChatController now holds an injected, optional VoiceHandling? (same opt-in shape
as the un-defaulted TextSpeaking) instead of owning a concrete instance; the
composer voice trigger is hidden when no handler is injected. The public
Concierge.show/present APIs and ConciergeChatSession thread the handler through.

LiveKit moves off the core AEPBrandConcierge target/pod onto AEPVoice in both
Package.swift and the Xcode project; the demo app links + embeds AEPVoice and
injects VoiceSessionController. Core AEPBrandConcierge no longer references
LiveKit at all.
Move VoiceSessionControllerTests and DataChannelMessageParserTests into a new
AEPVoiceTests target (they now @testable import AEPVoice) so the base UnitTests
target no longer needs LiveKit. Add a dependency-free FakeVoiceHandling double
for ChatController/presentation tests, and thread voiceHandler through the
ConciergeChatSession and applyPresentationConfiguration test call sites.
…t-free

The LiveKit-backed sources moved out of AEPBrandConcierge/Sources into AEPVoice,
so the source_files glob no longer picks up an unconditional 'import LiveKit' and
'pod lib lint' passes. Rewrite the NOTE to explain voice lives in the separate
AEPVoice SPM library and is intentionally not offered via CocoaPods.
… group

Mirror AEPBrandConcierge's layout so AEPVoice is a self-contained unit ready to
extract into its own library later: move the voice tests to
AEPVoice/Tests/UnitTests/ and reorganize the Xcode project so a single top-level
AEPVoice group holds Sources and Tests/UnitTests (instead of separate AEPVoice /
AEPVoiceTests top-level groups). Targets and build membership are unchanged.
The demo doesn't import LiveKit; the link exists only so Xcode embeds LiveKit's
transitive binary xcframeworks (LiveKitWebRTC, RustLiveKitUniFFI) into the .app.
Xcode's xcodeproj-based package integration doesn't auto-embed those through the
intermediate AEPVoice.framework — removing the link builds but crashes at launch
(verified). SPM-integrated host apps get this embedding automatically.
Remove comments that merely restate the code across the Option A changes; keep
only rationale not derivable from the source (LiveKit isolation, the demo's
embedding-only LiveKit link, the CocoaPods gap) and real contracts (main-thread
callbacks, cumulative transcript text).
Data-channel turn handling is present in this file (not deferred), and it now
surfaces state/transcript via the VoiceHandling callbacks instead of touching
ChatController directly.
…oller

SpeechController is internal to AEPBrandConcierge and VoiceSessionController now
lives in the separate AEPVoice library, so they are no longer co-located peers.
Keep the substantive point — a separate voice path, not built on dictation,
mutually exclusive, no shared code.
Keep AEPBrandConcierge free of any mention of the downstream AEPVoice library
(strict layering); VoiceHandling's doc no longer names a specific implementation.
@nozokada

Copy link
Copy Markdown
Member Author

Superseded by the plugin-based voice integration, so closing this proof of concept:

@nozokada nozokada closed this Oct 19, 2026
@nozokada
nozokada deleted the feat/voice-packaging-option-a branch November 24, 2026 23:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant