diff --git a/.changeset/add_livekit_session_crate.md b/.changeset/add_livekit_session_crate.md new file mode 100644 index 0000000000..f660cbcfe4 --- /dev/null +++ b/.changeset/add_livekit_session_crate.md @@ -0,0 +1,5 @@ +--- +livekit-session: minor +--- + +Add the `livekit-session` crate, whose `Session` fetches credentials from a token source, connects a room, publishes the platform microphone and plays the agent's audio by default (`SessionOptions::with_platform_audio`), projects the agent's state (`AgentState`) into a `watch` channel, and merges chat and transcripts into one message feed, with a README and an `examples/session` voice and text chat. diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 2c5010edd8..4f5cb1abfc 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -11,4 +11,5 @@ /livekit-wakeword/ @pham-tuan-binh /livekit-net/ @jhugman /livekit-token-source/ @MaxHeimbrock +/livekit-session/ @MaxHeimbrock /livekit-signaling/ @lukasIO diff --git a/AGENTS.md b/AGENTS.md index 03ade23f3d..8117ee6971 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -129,13 +129,13 @@ check = [ ] ``` -A crate with no such table is not feature-checked at all. Today eleven crates are `"powerset"`, `livekit` and `livekit-api` are `"curated"`, and `livekit-ffi` deliberately declares nothing. +A crate with no such table is not feature-checked at all. Today twelve crates are `"powerset"`, `livekit`, `livekit-api` and `livekit-session` are `"curated"`, and `livekit-ffi` deliberately declares nothing. - **When adding a workspace crate**, give it `mode = "powerset"` and stop there - Its features are then picked up automatically as they are added, and no CI file changes - Reach for `"curated"` only when the powerset is genuinely too expensive — that is a real loss of coverage, so it needs a reason recorded next to the table - cargo-hack only varies the features of packages it is given. A crate with no table still gets built as a dependency, which makes it easy to assume it is covered when it is not -- **When adding a feature to a `"curated"` crate** (`livekit`, `livekit-api`), add the configurations a user would plausibly select to that crate's `check` list +- **When adding a feature to a `"curated"` crate** (`livekit`, `livekit-api`, `livekit-session`), add the configurations a user would plausibly select to that crate's `check` list - A curated crate's new feature is invisible to this job until it is listed there — this is the standing cost of `"curated"` - Each entry is a complete feature set, run as `--no-default-features --features `. Spell defaults as `"default"`, since a bare `[]` already means "no features at all" - Pair the feature with what it realistically ships alongside (a TLS backend together with `native`, say) rather than listing it on its own diff --git a/Cargo.lock b/Cargo.lock index f75d12d96a..c30c2806ae 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3994,6 +3994,24 @@ dependencies = [ "uuid", ] +[[package]] +name = "livekit-session" +version = "0.0.0" +dependencies = [ + "anyhow", + "async-trait", + "futures-util", + "livekit", + "livekit-api", + "livekit-protocol", + "livekit-token", + "livekit-token-source", + "log", + "thiserror 2.0.19", + "tokio", + "tokio-stream", +] + [[package]] name = "livekit-signaling" version = "0.4.0" @@ -6852,6 +6870,18 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "session" +version = "0.1.0" +dependencies = [ + "clap", + "env_logger 0.11.11", + "futures-util", + "livekit-session", + "livekit-token-source", + "tokio", +] + [[package]] name = "sha1" version = "0.10.7" diff --git a/Cargo.toml b/Cargo.toml index 376a64f9d7..f44bb45106 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,6 +13,7 @@ members = [ "livekit-telemetry", "livekit-token", "livekit-token-source", + "livekit-session", "livekit-ffi-node-bindings", "livekit-capture", "livekit-net", @@ -41,6 +42,7 @@ members = [ "examples/rpc", "examples/save_to_disk", "examples/screensharing", + "examples/session", "examples/telemetry_ping", "examples/token_source", "examples/webhooks", @@ -62,6 +64,7 @@ livekit-capture = { version = "0.3.2", path = "livekit-capture" } livekit-ffi = { version = "0.17.0", path = "livekit-ffi" } livekit-datatrack = { version = "0.3.1", path = "livekit-datatrack" } livekit-telemetry = { version = "0.3.1", path = "livekit-telemetry" } +livekit-session = { version = "0.0.0", path = "livekit-session" } livekit-signaling = { version = "0.4.0", path = "livekit-signaling" } livekit-token = { version = "0.6.0", path = "livekit-token" } livekit-token-source = { version = "0.2.1", path = "livekit-token-source" } diff --git a/examples/session/Cargo.toml b/examples/session/Cargo.toml new file mode 100644 index 0000000000..4be41d6262 --- /dev/null +++ b/examples/session/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "session" +version = "0.1.0" +edition.workspace = true +publish = false + +[dependencies] +clap = { workspace = true, features = ["derive", "env"] } +env_logger = { workspace = true } +futures-util = { workspace = true } +livekit-session = { workspace = true, features = ["rustls-tls-native-roots"] } +livekit-token-source = { workspace = true } +tokio = { workspace = true, features = ["full"] } diff --git a/examples/session/README.md b/examples/session/README.md new file mode 100644 index 0000000000..432970b19f --- /dev/null +++ b/examples/session/README.md @@ -0,0 +1,31 @@ +# Session + +A conversation with a LiveKit agent, built on `livekit-session`. The microphone is published and +the agent's audio is played through platform audio, with echo cancellation, so no headphones are +needed. Lines typed on stdin are sent to the agent as well; the agent's replies, what you say once +transcribed, and state changes are printed as they arrive. + +Credentials come from a [development token server](https://docs.livekit.io/frontends/build/authentication/development-token-server/), +which also dispatches the agent: + +```bash +LIVEKIT_TOKEN_SERVER_ID= LIVEKIT_AGENT_NAME= cargo run -p session +``` + +Or from a pre-generated token, whose room configuration dispatches the agent: + +```bash +LIVEKIT_URL=wss://.livekit.cloud LIVEKIT_TOKEN= cargo run -p session +``` + +Every variable also has a flag (`--token-server-id`, `--agent-name`, `--url`, `--token`); see +`cargo run -p session -- --help`. + +Pass `--text` to leave the audio devices alone and talk by typing only, e.g. on a machine without +a microphone. The agent then needs to accept text input. + +```bash +cargo run -p session -- --text +``` + +Close stdin (Ctrl-D) to end the session. diff --git a/examples/session/src/main.rs b/examples/session/src/main.rs new file mode 100644 index 0000000000..47e0a30f8a --- /dev/null +++ b/examples/session/src/main.rs @@ -0,0 +1,127 @@ +use std::error::Error; +use std::time::Duration; + +use clap::Parser; +use futures_util::StreamExt; +use livekit_session::{ + Message, MessageOrigin, Session, SessionEvent, SessionOptions, SessionState, +}; + +use livekit_token_source::{development_token_server, literal, TokenSourceFetchOptions}; +use tokio::io::{AsyncBufReadExt, BufReader}; + +/// A conversation with a LiveKit agent over voice and typed text +#[derive(Parser, Debug)] +#[command(author, version, about, long_about = None)] +struct Args { + /// LiveKit server URL, used together with --token + #[arg(long, env = "LIVEKIT_URL")] + url: Option, + + /// Pre-generated token whose room configuration dispatches the agent + #[arg(long, env = "LIVEKIT_TOKEN", hide_env_values = true)] + token: Option, + + /// Development token server ID, used when no URL and token are given + #[arg(long, env = "LIVEKIT_TOKEN_SERVER_ID")] + token_server_id: Option, + + /// Agent for the development token server to dispatch + #[arg(long, env = "LIVEKIT_AGENT_NAME")] + agent_name: Option, + + /// Leave the audio devices alone and talk by typing only + #[arg(long)] + text: bool, +} + +/// Creates session options with credentials from a pre-generated token if one +/// is given, and from a development token server otherwise. +fn create_options(args: Args) -> Result> { + if let (Some(url), Some(token)) = (args.url, args.token) { + return Ok(SessionOptions::new_fixed_source(literal(url, token))); + } + let token_server_id = args + .token_server_id + .ok_or("pass --token-server-id, or --url and --token (or set the LIVEKIT_* variables)")?; + let mut fetch_options = TokenSourceFetchOptions::new(); + if let Some(agent_name) = args.agent_name { + fetch_options = fetch_options.with_agent_name(agent_name); + } + Ok(SessionOptions::new_configurable_source( + development_token_server(token_server_id), + fetch_options, + )) +} + +/// Prints a message once it is complete. The user's own input is skipped, as +/// it is already on screen. +fn print_message(message: &Message) { + if !message.is_final { + return; + } + let speaker = match message.origin { + MessageOrigin::AgentTranscript => "agent", + MessageOrigin::UserTranscript => "you (transcribed)", + MessageOrigin::UserInput => return, + _ => message.participant_identity.as_str(), + }; + println!("{speaker}: {}", message.text); +} + +fn print_state(state: &SessionState) { + println!("[{:?}, agent {:?}]", state.connection, state.agent); +} + +#[tokio::main] +async fn main() -> Result<(), Box> { + env_logger::init(); + let args = Args::parse(); + + // By default the session captures the microphone and plays the agent's + // audio, with echo cancellation between the two. `--text` keeps the + // conversation to typed lines, e.g. on a machine without audio devices. + let text = args.text; + let session_options = create_options(args)? + .with_agent_connect_timeout(Duration::from_secs(15)) + .with_platform_audio(!text); + let session = Session::new(session_options); + let mut events = session.subscribe(); + session.start().await?; + + // `changed` reports only later updates, so print where the session starts. + let mut state = session.state(); + print_state(&state.borrow_and_update()); + let mut lines = BufReader::new(tokio::io::stdin()).lines(); + loop { + tokio::select! { + changed = state.changed() => { + if changed.is_err() { + break; + } + let current = state.borrow_and_update().clone(); + println!("{:?}", session); + if !current.connection.is_connected() { + break; + } + } + Some(event) = events.next() => { + if let SessionEvent::MessageUpserted(message) = event { + print_message(&message); + } + } + line = lines.next_line() => match line? { + Some(line) if line.trim().is_empty() => {} + Some(line) => { + if let Err(err) = session.send_text(line.trim()).await { + eprintln!("failed to send: {err}"); + } + } + None => break, + }, + } + } + + session.end().await; + Ok(()) +} diff --git a/livekit-session/Cargo.toml b/livekit-session/Cargo.toml new file mode 100644 index 0000000000..ef6e1a0269 --- /dev/null +++ b/livekit-session/Cargo.toml @@ -0,0 +1,63 @@ +[package] +name = "livekit-session" +description = "Agent sessions for the LiveKit Rust SDK" +version = "0.0.0" +license.workspace = true +edition.workspace = true +repository.workspace = true +readme = "README.md" + +[features] +default = ["native"] + +# Backend and TLS pass-throughs, forwarded to both the room connection +# (livekit) and the token fetch (livekit-token-source). +native = ["livekit/native", "livekit-token-source/native"] +native-tls = ["livekit/native-tls", "livekit-token-source/native-tls"] +native-tls-vendored = ["livekit/native-tls-vendored", "livekit-token-source/native-tls-vendored"] +rustls-tls-native-roots = [ + "livekit/rustls-tls-native-roots", + "livekit-token-source/rustls-tls-native-roots", +] +rustls-tls-webpki-roots = [ + "livekit/rustls-tls-webpki-roots", + "livekit-token-source/rustls-tls-webpki-roots", +] + +# End-to-end tests against a running `livekit-server --dev`. +__lk-e2e-test = [] + +# How CI checks this crate's features, read by +# `.github/workflows/feature-combinations-curated.yml` via `cargo metadata`. +# See the equivalent table in `livekit/Cargo.toml` for the encoding. +# +# Curated rather than a powerset: every TLS feature is forwarded to `livekit`, +# so most powerset entries rebuild `livekit` underneath, and depth 2 would +# spend 22 checks mostly on two TLS backends at once or `__lk-e2e-test` paired +# with something unrelated, which nobody can select. The TLS forwards +# themselves are covered by `livekit`'s own list. +[package.metadata.feature-combinations] +mode = "curated" +check = [ + ["default"], # a plain `cargo check` + [], # --no-default-features + ["native", "rustls-tls-webpki-roots"], + ["default", "rustls-tls-native-roots"], # defaults *plus* one +] + +[dependencies] +futures-util = { workspace = true, features = ["std"] } +livekit = { workspace = true } +livekit-token-source = { workspace = true } +log = { workspace = true } +thiserror = { workspace = true } +tokio = { workspace = true, features = ["macros", "rt", "sync", "time"] } +tokio-stream = { workspace = true, features = ["sync"] } + +[dev-dependencies] +anyhow = { workspace = true } +async-trait = "0.1" +livekit-api = { workspace = true } +livekit-protocol = { workspace = true } +livekit-token = { workspace = true } +tokio = { workspace = true, features = ["io-util", "macros", "net", "rt-multi-thread", "sync", "time"] } diff --git a/livekit-session/README.md b/livekit-session/README.md new file mode 100644 index 0000000000..7277989079 --- /dev/null +++ b/livekit-session/README.md @@ -0,0 +1,109 @@ +# LiveKit Session + +Agent sessions for the LiveKit Rust SDK. A `Session` is the single entry point for a conversation +with an agent: it fetches credentials from a [token source](../livekit-token-source), connects a +room, publishes the microphone, projects what the agent is doing, and merges chat and transcripts +into one ordered message feed. It follows the same model as the Session in the JavaScript, Swift, +Android and Flutter SDKs. + +```rust +use livekit_session::{Session, SessionOptions}; +use livekit_token_source::{development_token_server, TokenSourceFetchOptions}; + +let token_source = development_token_server(""); +let fetch_options = TokenSourceFetchOptions::new().with_agent_name("my-agent"); +let session = Session::new(SessionOptions::new_configurable_source(token_source, fetch_options)); + +session.start().await?; +session.state().wait_for(|state| state.agent.is_connected()).await?; +session.send_text("Hello!").await?; +``` + +See [`examples/session`](../examples/session) for a complete text chat. + +## Credentials + +`Session::new` takes a `SessionOptions`, which holds the token source. Which `SessionOptions` +constructor to use depends on the kind of token source: + +- `SessionOptions::new_configurable_source` takes a configurable source with its + `TokenSourceFetchOptions`, for the agent to dispatch (as above), agent metadata, a room name or a + participant identity; +- `SessionOptions::new_fixed_source` takes a fixed source, such as a `literal` one holding a + pre-generated token. + +Every `start` fetches credentials anew, so pass the source itself rather than one wrapped in +`cached()`. Agents do not rejoin a room that already existed, and a cached token names the previous +room. + +## Lifecycle + +`start` fetches credentials and connects the room. It resolves once the room is connected, not +once the agent is. Calling it again while the session is connecting or connected fails with +`AlreadyStarted`. `end` closes the room, or cancels a `start` still in progress, and does nothing +when there is nothing to end. + +Dropping the last `Session` handle also closes the room. `room()` returns the connected room for +anything the session does not do itself, such as publishing a camera. + +## State + +`state()` returns a `tokio::sync::watch::Receiver`: `borrow()` reads the current +value, and `wait_for` awaits a condition. A `SessionState` holds the connection state (`connection`) +and the agent state (`agent`): + +| Agent state | Meaning | +| --- | --- | +| `Disconnected` | The session is not connected | +| `Connecting` | No agent is in the room yet | +| `Joined(agent)` | An agent joined the room, in a conversation or not | +| `Failed(Timeout { .. })` | No agent became conversational within `agent_connect_timeout` (20 s by default) of connecting | +| `Failed(Left)` | The agent left while the room stayed connected | + +`Joined` carries an `Agent`: its identity, its tracks, and its `AgentActivity`, what the agent +reports through its `lk.agent.state` attribute. `Failed` is not final: an agent that joins, or +becomes conversational, replaces it. An agent that timed out but is still in the room stays +available in `Timeout`. + +Most code needs only the methods on `AgentState`: + +- `is_connected`, `is_pending` and `is_finished` tell where the agent is. `is_connected` is true + only while the agent is listening, thinking or speaking; +- `activity()` and `identity()` tell what the agent in the room is doing and who it is; +- `audio_track()` and `avatar_video_track()` return the agent's microphone and its avatar's camera, + for an app that wants their frames, e.g. for a visualizer or to show the avatar. + +```rust +let mut state = session.state(); +let state = state.wait_for(|state| state.agent.audio_track().is_some()).await?.clone(); +let audio = state.agent.audio_track(); +``` + +The tracks are part of the state, so the state changes when a track arrives, goes, or is replaced. +A `SessionState` kept after the session moved on keeps its tracks alive: drop it when a newer one +arrives. + +## Messages + +`messages()` returns the feed, `subscribe()` streams changes to it, and `send_text` sends chat to +the agent. The feed merges: + +- transcripts of the agent and of the local user, from `lk.transcription`, updated in place as + they grow; +- the local user's input sent with `send_text`, added once the send succeeds; +- chat sent by other participants, from `lk.chat`. + +Messages are ordered by `seq`, the order in which they were first received, rather than by their +timestamps, which come from the sender's clock. `restore_messages` replaces the feed with a saved +conversation. + +## Things the session owns + +- **The `lk.chat` and `lk.transcription` text streams.** The session takes their readers, so an + app subscribed to the room sees those `TextStreamOpened` events with the reader already taken. + Streams on other topics are left to the app. +- **Platform audio.** By default `start` captures the microphone and publishes it as the local + participant's microphone track, and the agent's audio plays through the speakers, until the + session ends. `SessionOptions::with_platform_audio(false)` turns this off, for a conversation by text alone + or to publish audio of your own through `room()`. Device selection and audio processing are + shared by every `PlatformAudio` in the process, so configure them on one of your own. diff --git a/livekit-session/src/actor.rs b/livekit-session/src/actor.rs new file mode 100644 index 0000000000..ffcd3b9610 --- /dev/null +++ b/livekit-session/src/actor.rs @@ -0,0 +1,477 @@ +// Copyright 2026 LiveKit, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::future; +use std::pin::Pin; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; +use std::time::Duration; + +use futures_util::stream::{self, BoxStream, SelectAll}; +use futures_util::StreamExt; +use livekit::options::TrackPublishOptions; +use livekit::prelude::*; +use livekit::{ + ConnectionState, DisconnectReason, StreamReader, StreamResult, TakeCell, TextStreamInfo, + TextStreamReader, +}; +use tokio::sync::{broadcast, mpsc, oneshot, watch}; +use tokio::time::Sleep; + +use crate::agent::{Agent, AgentTracker}; +use crate::constants::{TOPIC_CHAT, TOPIC_TRANSCRIPTION}; +use crate::messages::{ + Message, MessageOrigin, MessageStore, MessageUpdate, TranscriptAggregator, TranscriptStream, +}; +use crate::session::{SessionConnectionState, SessionEvent, SessionState}; + +/// State shared between a [`Session`](crate::Session) and its actors. Holds no +/// reference back to either, so it never keeps them alive. +pub(crate) struct Shared { + /// The generation of the `start()` that currently owns the state. An + /// actor from an earlier `start()` that is still shutting down must not + /// overwrite the state of a newer one. + generation: Mutex, + state: watch::Sender, + messages: Mutex, + events: broadcast::Sender, + /// Every state published, so tests can assert on states a `watch` + /// receiver would skip. + #[cfg(test)] + pub(crate) history: Mutex>, +} + +impl Shared { + /// Creates the state, keeping up to `event_buffer_size` events for a + /// subscriber that falls behind. Panics if it is zero. + pub(crate) fn new(event_buffer_size: usize) -> Self { + Self { + generation: Mutex::new(0), + state: watch::Sender::new(SessionState::default()), + messages: Mutex::default(), + events: broadcast::Sender::new(event_buffer_size), + #[cfg(test)] + history: Mutex::default(), + } + } + + /// Starts a new generation, publishing its first state. + pub(crate) fn begin(&self, state: SessionState) -> u64 { + let mut generation = lock(&self.generation); + *generation += 1; + self.set(state); + *generation + } + + /// Publishes `state` if `generation` is still current. + pub(crate) fn publish(&self, generation: u64, state: SessionState) { + let current = lock(&self.generation); + if *current == generation { + self.set(state); + } + } + + fn set(&self, state: SessionState) { + #[cfg(test)] + lock(&self.history).push(state.clone()); + self.state.send_if_modified(|current| { + if *current == state { + return false; + } + *current = state; + true + }); + } + + pub(crate) fn watch(&self) -> watch::Receiver { + self.state.subscribe() + } + + pub(crate) fn subscribe(&self) -> broadcast::Receiver { + self.events.subscribe() + } + + /// Adds or updates a message and notifies subscribers. The event is + /// dispatched under the store's lock, so subscribers see updates in the + /// order the store applied them. + pub(crate) fn upsert(&self, update: MessageUpdate) -> Message { + let mut messages = lock(&self.messages); + let message = messages.upsert(update); + // Fails only when there is no subscriber. + _ = self.events.send(SessionEvent::MessageUpserted(message.clone())); + message + } + + pub(crate) fn restore(&self, restored: impl IntoIterator) { + // Built before locking, so that the caller's iterator never runs + // under the lock. + let restored = MessageStore::restored(restored); + let mut messages = lock(&self.messages); + *messages = restored; + _ = self.events.send(SessionEvent::MessagesRestored); + } + + pub(crate) fn messages(&self) -> Vec { + lock(&self.messages).messages().to_vec() + } + + /// The number of messages in the feed. + pub(crate) fn message_count(&self) -> usize { + lock(&self.messages).messages().len() + } + + #[cfg(all(test, feature = "__lk-e2e-test"))] + pub(crate) fn subscriber_count(&self) -> usize { + self.events.receiver_count() + } +} + +/// Locks `mutex`, recovering from poisoning: every value guarded here is left +/// consistent between statements, so a panicking holder cannot corrupt it. +pub(crate) fn lock(mutex: &Mutex) -> MutexGuard<'_, T> { + mutex.lock().unwrap_or_else(PoisonError::into_inner) +} + +/// A connected room, handed to the actor that will run it. +pub(crate) struct Connection { + pub room: Arc, + pub events: mpsc::UnboundedReceiver, + /// The audio devices behind the published microphone, if any. + pub platform_audio: Option, + /// How long an agent gets to become conversational. + pub agent_timeout: Duration, +} + +/// An incoming text stream the session reads. +#[non_exhaustive] +enum ReaderEvent { + TranscriptChunk(Arc, StreamResult), + TranscriptEnd(Arc), + Chat { + info: TextStreamInfo, + participant_identity: ParticipantIdentity, + text: StreamResult, + }, +} + +/// An `lk.transcription` stream being read. +struct Transcript { + stream: TranscriptStream, + /// Kept for its attributes, which the trailer can still update. + info: TextStreamInfo, +} + +#[non_exhaustive] +enum Event { + Stop, + Room(RoomEvent), + Reader(ReaderEvent), + AgentDeadline, +} + +#[non_exhaustive] +/// How the actor stopped. +enum Exit { + /// [`Session::end`](crate::Session::end) was called, or every + /// [`Session`](crate::Session) handle was dropped. + Stopped, + /// The room disconnected. + Disconnected(DisconnectReason), + /// The microphone failed to publish. + Microphone(RoomError), +} + +/// Runs one connected room for one `start()`: publishes the microphone, +/// projects the agent state, reads the session's text streams, and closes the +/// room when the session ends or is dropped. +/// +/// Owns the room from the moment it is connected, so that a `start()` dropped +/// while the microphone publishes leaves nothing behind to close. Holds no +/// [`Session`](crate::Session) and no `stop` sender, so dropping the last +/// session handle closes `stop` and stops the actor. +pub(crate) struct SessionActor { + generation: u64, + room: Arc, + /// The microphone to publish, and the speakers. Kept running for as long + /// as the room: dropped with the actor, once the room is closed. + platform_audio: Option, + room_events: mpsc::UnboundedReceiver, + /// Never carries a value: the session stops the actor by dropping the + /// sender. + stop: mpsc::Receiver<()>, + /// Answers the `start()` that spawned the actor once the microphone is + /// published, or failed to. Dropped unanswered if the actor stops first. + ready: Option>>, + /// The session's text streams, read here rather than in tasks of their + /// own, so that the transcript aggregator has a single writer. + readers: SelectAll>, + /// How long an agent gets to become conversational, counted once the + /// microphone, if any, is published. + agent_timeout: Duration, + agent_deadline: Option>>, + connection: SessionConnectionState, + tracker: AgentTracker, + aggregator: TranscriptAggregator, + shared: Arc, +} + +impl SessionActor { + pub(crate) fn new( + generation: u64, + connection: Connection, + stop: mpsc::Receiver<()>, + ready: oneshot::Sender>, + shared: Arc, + ) -> Self { + let state = match connection.room.connection_state() { + ConnectionState::Reconnecting => SessionConnectionState::Reconnecting, + ConnectionState::Connected => SessionConnectionState::Connected, + ConnectionState::Disconnected => SessionConnectionState::Disconnected, + }; + Self { + generation, + room: connection.room, + platform_audio: connection.platform_audio, + room_events: connection.events, + stop, + ready: Some(ready), + readers: SelectAll::new(), + agent_timeout: connection.agent_timeout, + agent_deadline: None, + connection: state, + tracker: AgentTracker::default(), + aggregator: TranscriptAggregator::default(), + shared, + } + } + + /// Projects the agent state, and publishes the session state. + pub(crate) fn refresh(&mut self) { + let agent = Agent::find(self.room.remote_participants().values()); + let agent_state = self.tracker.project(self.connection, agent); + if agent_state.is_connected() { + self.agent_deadline = None; + } + self.shared.publish( + self.generation, + SessionState { connection: self.connection, agent: agent_state }, + ); + } + + pub(crate) async fn run(mut self) { + let exit = match self.publish_microphone().await { + Ok(()) => self.serve().await, + Err(exit) => exit, + }; + + // Closed before the final state, so that a `start()` prompted by it + // already finds this actor gone. + self.stop.close(); + let failure = match exit { + Exit::Stopped => { + self.close_room().await; + None + } + Exit::Disconnected(reason) => { + log::info!("session room disconnected: {reason:?}"); + None + } + Exit::Microphone(err) => { + self.close_room().await; + Some(err) + } + }; + self.shared.publish(self.generation, SessionState::default()); + // Answered once the room is closed and the state final, so that a + // failed `start()` returns to an idle session. A `start()` stopped + // before the microphone was published learns so when `ready` is + // dropped with the actor. + if let Some(err) = failure { + self.report(Err(err)); + } + } + + /// Publishes the platform microphone, if any, then reports the room as + /// connected, to the state and to the `start()` waiting on it. Stops + /// instead if the session ends first. + async fn publish_microphone(&mut self) -> Result<(), Exit> { + if let Some(audio) = &self.platform_audio { + let track = LocalAudioTrack::create_audio_track("microphone", audio.rtc_source()); + let options = + TrackPublishOptions { source: TrackSource::Microphone, ..Default::default() }; + let local_participant = self.room.local_participant(); + let publish = local_participant.publish_track(LocalTrack::Audio(track), options); + tokio::select! { + biased; + _ = self.stop.recv() => return Err(Exit::Stopped), + result = publish => { + result.map_err(Exit::Microphone)?; + } + } + } + self.agent_deadline = Some(Box::pin(tokio::time::sleep(self.agent_timeout))); + self.refresh(); + self.report(Ok(())); + Ok(()) + } + + /// Runs the room until the session ends or the room disconnects. + async fn serve(&mut self) -> Exit { + loop { + let deadline = &mut self.agent_deadline; + let deadline = async move { + match deadline.as_mut() { + Some(deadline) => deadline.await, + None => future::pending().await, + } + }; + let event = tokio::select! { + _ = self.stop.recv() => Event::Stop, + Some(event) = self.room_events.recv() => Event::Room(event), + Some(event) = self.readers.next() => Event::Reader(event), + () = deadline => Event::AgentDeadline, + }; + match event { + Event::Stop => return Exit::Stopped, + Event::Room(RoomEvent::Disconnected { reason }) => { + return Exit::Disconnected(reason) + } + Event::Room(event) => self.on_room_event(event), + Event::Reader(event) => self.on_reader_event(event), + Event::AgentDeadline => self.on_agent_deadline(), + } + } + } + + async fn close_room(&mut self) { + if let Err(err) = self.room.close().await { + log::warn!("failed to close the session room: {err}"); + } + } + + /// Answers the `start()` that spawned the actor, unless it was dropped or + /// already answered. + fn report(&mut self, result: Result<(), RoomError>) { + if let Some(ready) = self.ready.take() { + let _ = ready.send(result); + } + } + + fn on_room_event(&mut self, event: RoomEvent) { + match event { + RoomEvent::TextStreamOpened { reader, topic, participant_identity } => { + self.on_text_stream(&reader, &topic, participant_identity); + return; + } + RoomEvent::Reconnecting + | RoomEvent::ConnectionStateChanged(ConnectionState::Reconnecting) => { + self.connection = SessionConnectionState::Reconnecting; + } + RoomEvent::Reconnected + | RoomEvent::ConnectionStateChanged(ConnectionState::Connected) => { + self.connection = SessionConnectionState::Connected; + } + RoomEvent::ParticipantConnected(_) + | RoomEvent::ParticipantDisconnected(_) + | RoomEvent::ParticipantAttributesChanged { .. } + | RoomEvent::TrackPublished { .. } + | RoomEvent::TrackUnpublished { .. } + | RoomEvent::TrackSubscribed { .. } + | RoomEvent::TrackUnsubscribed { .. } => {} + _ => return, + } + self.refresh(); + } + + /// Takes the reader of a stream on a topic the session owns. Streams on + /// other topics are left untaken for the app. + fn on_text_stream( + &mut self, + reader: &TakeCell, + topic: &str, + participant_identity: ParticipantIdentity, + ) { + if topic != TOPIC_TRANSCRIPTION && topic != TOPIC_CHAT { + return; + } + let Some(reader) = reader.take() else { + log::warn!("a {topic} stream was taken before the session could read it"); + return; + }; + let info = reader.info().clone(); + + if topic == TOPIC_CHAT { + let read = async move { + ReaderEvent::Chat { info, participant_identity, text: reader.read_all().await } + }; + self.readers.push(stream::once(read).boxed()); + return; + } + + let is_local = participant_identity == self.room.local_participant().identity(); + let transcript = Arc::new(Transcript { + stream: TranscriptStream { + id: info.id.clone(), + timestamp: info.timestamp.into(), + participant_identity, + is_local, + }, + info, + }); + let end = stream::once(future::ready(ReaderEvent::TranscriptEnd(transcript.clone()))); + let chunks = + reader.map(move |chunk| ReaderEvent::TranscriptChunk(transcript.clone(), chunk)); + self.readers.push(chunks.chain(end).boxed()); + } + + fn on_reader_event(&mut self, event: ReaderEvent) { + let update = match event { + ReaderEvent::TranscriptChunk(transcript, Ok(chunk)) => { + self.aggregator.on_chunk(&transcript.stream, &transcript.info.attributes(), &chunk) + } + ReaderEvent::TranscriptChunk(transcript, Err(err)) => { + log::warn!("failed to read transcript stream {}: {err}", transcript.stream.id); + None + } + ReaderEvent::TranscriptEnd(transcript) => { + self.aggregator.on_stream_end(&transcript.stream, &transcript.info.attributes()) + } + ReaderEvent::Chat { info, participant_identity, text: Ok(text) } => { + Some(MessageUpdate { + id: info.id, + timestamp: info.timestamp.into(), + origin: MessageOrigin::Chat, + participant_identity, + text, + is_final: true, + }) + } + ReaderEvent::Chat { info, text: Err(err), .. } => { + log::warn!("failed to read chat stream {}: {err}", info.id); + None + } + }; + if let Some(update) = update { + self.shared.upsert(update); + } + } + + fn on_agent_deadline(&mut self) { + self.agent_deadline = None; + let agent = Agent::find(self.room.remote_participants().values()); + if self.tracker.time_out(self.connection, agent.as_ref()) { + log::info!("agent did not become conversational in time"); + } + self.refresh(); + } +} diff --git a/livekit-session/src/agent.rs b/livekit-session/src/agent.rs new file mode 100644 index 0000000000..32e03f187a --- /dev/null +++ b/livekit-session/src/agent.rs @@ -0,0 +1,715 @@ +// Copyright 2026 LiveKit, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::collections::HashMap; + +use livekit::prelude::*; +use livekit::ParticipantKind; + +use crate::constants::{ATTRIBUTE_AGENT_STATE, ATTRIBUTE_PUBLISH_ON_BEHALF}; +use crate::session::SessionConnectionState; + +/// The session's agent, projected from the room: whether it is there, and +/// what it is doing. +/// +/// This enum answers the first question. The [`Agent`] inside +/// [`Joined`](Self::Joined) answers the second, and holds the agent's +/// tracks. +/// +/// Most code needs only the methods: [`is_connected`](Self::is_connected) to +/// show that the agent is there, [`can_listen`](Self::can_listen) to show +/// that the user can speak, [`is_pending`](Self::is_pending) to show +/// that it is on its way, [`is_finished`](Self::is_finished) to show that it +/// is gone or never came, and [`activity`](Self::activity), +/// [`audio_track`](Self::audio_track) and +/// [`avatar_video_track`](Self::avatar_video_track) to read the agent +/// whichever variant holds it. +/// +/// ```no_run +/// # use livekit_session::{AgentActivity, Session}; +/// # async fn run(session: Session) -> Result<(), Box> { +/// let mut state = session.state(); +/// let state = state.wait_for(|state| state.agent.audio_track().is_some()).await?.clone(); +/// if state.agent.activity() == Some(AgentActivity::Speaking) { +/// let _audio = state.agent.audio_track(); +/// } +/// # Ok(()) +/// # } +/// ``` +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum AgentState { + /// The session is not connected. + Disconnected, + /// The session is connecting, or is connected and no agent has joined yet. + Connecting, + /// An agent joined the room. It is not necessarily in a conversation + /// yet: see [`is_connected`](Self::is_connected). + Joined(Agent), + /// The agent did not become conversational in time, or left the room. + /// + /// Not final: an agent that joins or becomes conversational afterwards + /// replaces this state. + Failed(AgentFailure), +} + +impl AgentState { + /// Whether the agent is in the room and in a conversation: listening, + /// thinking or speaking. + /// + /// Stricter than [`Joined`](Self::Joined): an agent that joined and is + /// still [`Initializing`](AgentActivity::Initializing) is not connected. + pub fn is_connected(&self) -> bool { + matches!(self, Self::Joined(agent) if agent.activity.is_conversational()) + } + + /// Whether the user can speak to the agent: it is listening, thinking or + /// speaking. + /// + /// Same as [`is_connected`](Self::is_connected) for now. Once the session + /// supports a pre-connect audio buffer, this also holds while the session + /// is connecting and buffering the user's speech for the agent. + pub fn can_listen(&self) -> bool { + self.is_connected() + } + + /// Whether an agent is expected but not yet conversational: connecting, + /// initializing, or idle. + pub fn is_pending(&self) -> bool { + match self { + Self::Connecting => true, + Self::Joined(agent) => { + matches!(agent.activity, AgentActivity::Initializing | AgentActivity::Idle) + } + _ => false, + } + } + + /// Whether the agent is gone or never came: the session is disconnected, + /// or the agent [`Failed`](Self::Failed). + /// + /// A failure can still recover, so this becomes `false` again if an agent + /// joins later. Call [`Session::end`](crate::Session::end) to give up. + pub fn is_finished(&self) -> bool { + matches!(self, Self::Disconnected | Self::Failed(_)) + } + + /// The identity of the agent in the room, if there is one. + pub fn identity(&self) -> Option<&ParticipantIdentity> { + self.agent().map(Agent::identity) + } + + /// What the agent in the room is doing, if there is one. An agent that + /// [`Failed`](Self::Failed) but is still in the room reports its activity + /// too. + pub fn activity(&self) -> Option { + self.agent().map(Agent::activity) + } + + /// The agent's microphone track, once subscribed. + pub fn audio_track(&self) -> Option<&RemoteAudioTrack> { + self.agent()?.audio_track() + } + + /// The camera track of the agent's avatar, once subscribed. + pub fn avatar_video_track(&self) -> Option<&RemoteVideoTrack> { + self.agent()?.avatar_video_track() + } + + /// The agent in the room, whichever variant holds it. + fn agent(&self) -> Option<&Agent> { + match self { + Self::Joined(agent) => Some(agent), + Self::Failed(AgentFailure::Timeout { agent }) => agent.as_ref(), + Self::Failed(AgentFailure::Left { .. }) | Self::Disconnected | Self::Connecting => None, + } + } +} + +/// An agent in the room at one point in time: who it is, what it is doing, +/// and its tracks. +/// +/// A snapshot, like the [`SessionState`](crate::SessionState) it comes from: +/// it does not change when the agent does. A value kept after the session +/// moved on keeps its tracks alive, so drop it when a newer state arrives. +/// +/// Two agents are equal when their identity, their activity and the `sid`s +/// of their tracks are. +#[derive(Clone, Debug)] +pub struct Agent { + identity: ParticipantIdentity, + activity: AgentActivity, + audio_track: Option, + avatar_video_track: Option, +} + +impl Agent { + /// The identity of the agent's participant. + pub fn identity(&self) -> &ParticipantIdentity { + &self.identity + } + + /// What the agent is doing. + pub fn activity(&self) -> AgentActivity { + self.activity + } + + /// The agent's microphone track, once subscribed. + pub fn audio_track(&self) -> Option<&RemoteAudioTrack> { + self.audio_track.as_ref() + } + + /// The camera track of the agent's avatar, once subscribed. An avatar is + /// a separate participant publishing on the agent's behalf. + pub fn avatar_video_track(&self) -> Option<&RemoteVideoTrack> { + self.avatar_video_track.as_ref() + } + + /// Finds the session's agent among the remote participants (see + /// [`find_agent`]) and takes its snapshot. This is the only place that + /// decides which participant is the agent. + pub(crate) fn find<'a, P: AgentCandidate + 'a>( + participants: impl IntoIterator + Clone, + ) -> Option { + let agent = find_agent(participants.clone())?; + let identity = agent.identity(); + let avatar_video_track = + find_avatar_worker(participants, &identity).and_then(AgentCandidate::camera_track); + let attributes = agent.attributes(); + let activity = attributes.get(ATTRIBUTE_AGENT_STATE).map(String::as_str); + Some(Self { + identity, + activity: AgentActivity::from_attribute(activity), + audio_track: agent.microphone_track(), + avatar_video_track, + }) + } +} + +impl PartialEq for Agent { + fn eq(&self, other: &Self) -> bool { + self.identity == other.identity + && self.activity == other.activity + && self.audio_track.as_ref().map(RemoteAudioTrack::sid) + == other.audio_track.as_ref().map(RemoteAudioTrack::sid) + && self.avatar_video_track.as_ref().map(RemoteVideoTrack::sid) + == other.avatar_video_track.as_ref().map(RemoteVideoTrack::sid) + } +} + +impl Eq for Agent {} + +/// What an agent in the room is doing, as reported through its +/// `lk.agent.state` attribute. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum AgentActivity { + /// The agent joined and is starting up. + Initializing, + /// The agent joined but is not in a conversation. + Idle, + /// The agent is listening to the user. + Listening, + /// The agent is preparing a reply. + Thinking, + /// The agent is replying. + Speaking, + /// The agent reports an activity this SDK does not recognize. + Unknown, +} + +impl AgentActivity { + /// Whether the agent is in a conversation: listening, thinking or + /// speaking. + pub(crate) fn is_conversational(self) -> bool { + matches!(self, Self::Listening | Self::Thinking | Self::Speaking) + } + + /// Parses the agent's `lk.agent.state` attribute. A missing attribute + /// means [`Idle`](Self::Idle); an unrecognized one means + /// [`Unknown`](Self::Unknown). + fn from_attribute(value: Option<&str>) -> Self { + match value { + None => Self::Idle, + Some("idle") => Self::Idle, + Some("initializing") => Self::Initializing, + Some("listening") => Self::Listening, + Some("thinking") => Self::Thinking, + Some("speaking") => Self::Speaking, + Some(_) => Self::Unknown, + } + } +} + +/// Why an agent is [`AgentState::Failed`]. +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum AgentFailure { + /// No agent became conversational within + /// [`SessionOptions::with_agent_connect_timeout`](crate::SessionOptions::with_agent_connect_timeout). + #[non_exhaustive] + Timeout { + /// The agent that was too slow, if one is in the room. + agent: Option, + }, + /// The agent left the room while the session stayed connected. + #[non_exhaustive] + Left { + /// The identity of the agent that left. + identity: ParticipantIdentity, + }, +} + +/// A remote participant, as far as agent projection is concerned. +pub(crate) trait AgentCandidate { + fn identity(&self) -> ParticipantIdentity; + fn kind(&self) -> ParticipantKind; + fn attributes(&self) -> HashMap; + /// The participant's microphone track, once subscribed. + fn microphone_track(&self) -> Option; + /// The participant's camera track, once subscribed. + fn camera_track(&self) -> Option; +} + +impl AgentCandidate for RemoteParticipant { + fn identity(&self) -> ParticipantIdentity { + RemoteParticipant::identity(self) + } + + fn kind(&self) -> ParticipantKind { + RemoteParticipant::kind(self) + } + + fn attributes(&self) -> HashMap { + RemoteParticipant::attributes(self) + } + + fn microphone_track(&self) -> Option { + self.track_publications().into_values().find_map(|publication| { + match (publication.source(), publication.track()) { + (TrackSource::Microphone, Some(RemoteTrack::Audio(track))) => Some(track), + _ => None, + } + }) + } + + fn camera_track(&self) -> Option { + self.track_publications().into_values().find_map(|publication| { + match (publication.source(), publication.track()) { + (TrackSource::Camera, Some(RemoteTrack::Video(track))) => Some(track), + _ => None, + } + }) + } +} + +/// Finds the agent: a participant of kind agent that is not publishing on +/// behalf of another participant (that would be an avatar worker). +/// +/// With several agents, the lowest identity wins, so the choice does not +/// change between calls. +fn find_agent<'a, P: AgentCandidate>( + participants: impl IntoIterator, +) -> Option<&'a P> { + participants + .into_iter() + .filter(|p| { + p.kind() == ParticipantKind::Agent + && !p.attributes().contains_key(ATTRIBUTE_PUBLISH_ON_BEHALF) + }) + .min_by_key(|p| p.identity()) +} + +/// Finds the avatar worker publishing on behalf of `agent`. +fn find_avatar_worker<'a, P: AgentCandidate>( + participants: impl IntoIterator, + agent: &ParticipantIdentity, +) -> Option<&'a P> { + participants.into_iter().find(|p| { + p.attributes() + .get(ATTRIBUTE_PUBLISH_ON_BEHALF) + .is_some_and(|v| v.as_str() == agent.as_str()) + }) +} + +/// Projects [`AgentState`] from the room, remembering what the projection +/// needs across calls: the last agent seen, and whether the agent-connect +/// timeout fired. +#[derive(Debug, Default)] +pub(crate) struct AgentTracker { + /// The last agent seen since connecting, reported if it leaves. + last_agent: Option, + /// Set when the agent-connect timeout fired, to the agent present at the + /// time (`None` if there was none). + timed_out: Option>, +} + +impl AgentTracker { + /// Projects the agent state for the given connection state and the agent + /// in the room, as [`Agent::find`] returns it. + pub(crate) fn project( + &mut self, + connection: SessionConnectionState, + agent: Option, + ) -> AgentState { + match connection { + SessionConnectionState::Disconnected => { + *self = Self::default(); + return AgentState::Disconnected; + } + SessionConnectionState::Connecting => return AgentState::Connecting, + SessionConnectionState::Connected | SessionConnectionState::Reconnecting => {} + } + + let Some(agent) = agent else { + // A full reconnect removes every participant, so an agent missing + // while reconnecting has not necessarily left. + if let (Some(identity), SessionConnectionState::Connected) = + (&self.last_agent, connection) + { + return AgentState::Failed(AgentFailure::Left { identity: identity.clone() }); + } + if self.timed_out == Some(None) { + return AgentState::Failed(AgentFailure::Timeout { agent: None }); + } + return AgentState::Connecting; + }; + + if self.last_agent.as_ref() != Some(&agent.identity) { + self.last_agent = Some(agent.identity.clone()); + } + if agent.activity.is_conversational() { + self.timed_out = None; + return AgentState::Joined(agent); + } + // The timeout holds only for the agent that was too slow: one that + // joins afterwards reports its own activity. + match &self.timed_out { + Some(Some(timed_out)) if *timed_out == agent.identity => { + AgentState::Failed(AgentFailure::Timeout { agent: Some(agent) }) + } + _ => AgentState::Joined(agent), + } + } + + /// Records the agent-connect timeout firing. Returns `false` when it does + /// not count, because the session is not connected or the agent is + /// already conversational. + pub(crate) fn time_out( + &mut self, + connection: SessionConnectionState, + agent: Option<&Agent>, + ) -> bool { + if !connection.is_connected() { + return false; + } + if agent.is_some_and(|agent| agent.activity.is_conversational()) { + return false; + } + self.timed_out = Some(agent.map(|agent| agent.identity.clone())); + true + } +} + +#[cfg(test)] +mod tests { + use super::*; + + use AgentActivity::{Idle, Initializing, Listening, Speaking, Thinking, Unknown}; + use SessionConnectionState::{Connected, Connecting, Disconnected, Reconnecting}; + + const NO_ONE: &[Fake] = &[]; + + #[derive(Clone)] + struct Fake { + identity: &'static str, + kind: ParticipantKind, + attributes: Vec<(&'static str, &'static str)>, + } + + impl Fake { + fn agent(identity: &'static str, state: Option<&'static str>) -> Self { + let attributes = state.map(|s| vec![(ATTRIBUTE_AGENT_STATE, s)]).unwrap_or_default(); + Self { identity, kind: ParticipantKind::Agent, attributes } + } + + fn standard(identity: &'static str) -> Self { + Self { identity, kind: ParticipantKind::Standard, attributes: vec![] } + } + + fn avatar_for(identity: &'static str, agent: &'static str) -> Self { + Self { + identity, + kind: ParticipantKind::Agent, + attributes: vec![(ATTRIBUTE_PUBLISH_ON_BEHALF, agent)], + } + } + } + + impl AgentCandidate for Fake { + fn microphone_track(&self) -> Option { + None + } + + fn camera_track(&self) -> Option { + None + } + + fn identity(&self) -> ParticipantIdentity { + self.identity.to_owned().into() + } + + fn kind(&self) -> ParticipantKind { + self.kind + } + + fn attributes(&self) -> HashMap { + self.attributes.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect() + } + } + + fn project(tracker: &mut AgentTracker, participants: &[Fake]) -> AgentState { + project_in(tracker, Connected, participants) + } + + fn project_in( + tracker: &mut AgentTracker, + connection: SessionConnectionState, + participants: &[Fake], + ) -> AgentState { + tracker.project(connection, Agent::find(participants)) + } + + fn time_out( + tracker: &mut AgentTracker, + connection: SessionConnectionState, + participants: &[Fake], + ) -> bool { + tracker.time_out(connection, Agent::find(participants).as_ref()) + } + + fn agent(identity: &str, activity: AgentActivity) -> Agent { + Agent { + identity: identity.to_owned().into(), + activity, + audio_track: None, + avatar_video_track: None, + } + } + + /// The agent `"agent"` joined, doing `activity`. + fn connected(activity: AgentActivity) -> AgentState { + AgentState::Joined(agent("agent", activity)) + } + + fn timed_out(agent: Option) -> AgentState { + AgentState::Failed(AgentFailure::Timeout { agent }) + } + + /// The agent `identity` left. + fn left(identity: &str) -> AgentState { + AgentState::Failed(AgentFailure::Left { identity: identity.to_owned().into() }) + } + + #[test] + fn attribute_values_map_to_states() { + let mut tracker = AgentTracker::default(); + for (value, state) in [ + ("initializing", connected(Initializing)), + ("idle", connected(Idle)), + ("listening", connected(Listening)), + ("thinking", connected(Thinking)), + ("speaking", connected(Speaking)), + ] { + assert_eq!(project(&mut tracker, &[Fake::agent("agent", Some(value))]), state); + } + } + + #[test] + fn missing_attribute_is_idle_and_unrecognized_is_unknown() { + let mut tracker = AgentTracker::default(); + assert_eq!(project(&mut tracker, &[Fake::agent("agent", None)]), connected(Idle)); + assert_eq!( + project(&mut tracker, &[Fake::agent("agent", Some("dancing"))]), + connected(Unknown) + ); + } + + #[test] + fn avatar_worker_is_never_the_agent() { + let mut tracker = AgentTracker::default(); + let participants = [Fake::avatar_for("avatar", "agent"), Fake::standard("user")]; + assert_eq!(project(&mut tracker, &participants), AgentState::Connecting); + + let participants = + [Fake::avatar_for("avatar", "agent"), Fake::agent("agent", Some("speaking"))]; + assert_eq!(find_agent(&participants).map(|p| p.identity), Some("agent")); + assert_eq!( + find_avatar_worker(&participants, &"agent".to_owned().into()).map(|p| p.identity), + Some("avatar") + ); + } + + #[test] + fn lowest_identity_wins_among_several_agents() { + let participants = [Fake::agent("b", None), Fake::agent("a", None)]; + assert_eq!(find_agent(&participants).map(|p| p.identity), Some("a")); + } + + #[test] + fn session_state_takes_precedence() { + let mut tracker = AgentTracker::default(); + let participants = [Fake::agent("agent", Some("speaking"))]; + assert_eq!(project_in(&mut tracker, Disconnected, &participants), AgentState::Disconnected); + assert_eq!(project_in(&mut tracker, Connecting, &participants), AgentState::Connecting); + assert_eq!(project_in(&mut tracker, Reconnecting, &participants), connected(Speaking)); + } + + #[test] + fn agent_leaving_while_connected_is_left() { + let mut tracker = AgentTracker::default(); + assert_eq!(project(&mut tracker, NO_ONE), AgentState::Connecting); + project(&mut tracker, &[Fake::agent("agent", Some("listening"))]); + assert_eq!(project(&mut tracker, NO_ONE), left("agent")); + } + + #[test] + fn left_names_the_last_agent_seen() { + let mut tracker = AgentTracker::default(); + project(&mut tracker, &[Fake::agent("b", Some("listening"))]); + project(&mut tracker, &[Fake::agent("a", Some("listening"))]); + assert_eq!(project(&mut tracker, NO_ONE), left("a")); + } + + #[test] + fn agent_missing_while_reconnecting_is_not_left() { + let mut tracker = AgentTracker::default(); + project(&mut tracker, &[Fake::agent("agent", Some("listening"))]); + assert_eq!(project_in(&mut tracker, Reconnecting, NO_ONE), AgentState::Connecting); + assert_eq!( + project_in(&mut tracker, Reconnecting, &[Fake::agent("agent", Some("listening"))]), + connected(Listening) + ); + } + + #[test] + fn left_recovers_when_an_agent_returns() { + let mut tracker = AgentTracker::default(); + project(&mut tracker, &[Fake::agent("agent", Some("listening"))]); + assert_eq!(project(&mut tracker, NO_ONE), left("agent")); + assert_eq!( + project(&mut tracker, &[Fake::agent("agent-2", Some("initializing"))]), + AgentState::Joined(agent("agent-2", Initializing)) + ); + } + + #[test] + fn disconnect_forgets_the_last_agent() { + let mut tracker = AgentTracker::default(); + project(&mut tracker, &[Fake::agent("agent", Some("listening"))]); + project_in(&mut tracker, Disconnected, NO_ONE); + assert_eq!(project_in(&mut tracker, Connecting, NO_ONE), AgentState::Connecting); + assert_eq!(project(&mut tracker, NO_ONE), AgentState::Connecting); + } + + #[test] + fn timeout_without_agent_fails_until_an_agent_joins() { + let mut tracker = AgentTracker::default(); + assert!(time_out(&mut tracker, Connected, NO_ONE)); + assert_eq!(project(&mut tracker, NO_ONE), timed_out(None)); + assert_eq!( + project(&mut tracker, &[Fake::agent("agent", Some("initializing"))]), + connected(Initializing) + ); + } + + #[test] + fn timeout_with_initializing_agent_fails_until_it_is_conversational() { + let mut tracker = AgentTracker::default(); + let stuck = [Fake::agent("agent", Some("initializing"))]; + assert!(time_out(&mut tracker, Connected, &stuck)); + // The agent that was too slow stays reachable. + assert_eq!(project(&mut tracker, &stuck), timed_out(Some(agent("agent", Initializing)))); + assert_eq!( + project(&mut tracker, &[Fake::agent("agent", Some("listening"))]), + connected(Listening) + ); + // Recovered for good: falling back to idle is not a timeout. + assert_eq!(project(&mut tracker, &[Fake::agent("agent", Some("idle"))]), connected(Idle)); + } + + #[test] + fn timeout_does_not_count_once_conversational_or_disconnected() { + let mut tracker = AgentTracker::default(); + assert!(!time_out(&mut tracker, Connected, &[Fake::agent("agent", Some("speaking"))])); + assert!(!time_out(&mut tracker, Connecting, NO_ONE)); + assert!(!time_out(&mut tracker, Disconnected, NO_ONE)); + assert_eq!(project(&mut tracker, NO_ONE), AgentState::Connecting); + } + + #[test] + fn predicates_match_for_every_state() { + let states = [ + AgentState::Disconnected, + AgentState::Connecting, + connected(Initializing), + connected(Idle), + connected(Listening), + connected(Thinking), + connected(Speaking), + connected(Unknown), + timed_out(None), + timed_out(Some(agent("agent", Initializing))), + left("agent"), + ]; + for state in &states { + let activity = state.activity(); + assert_eq!( + state.is_connected(), + matches!(state, AgentState::Joined(_)) + && matches!(activity, Some(Listening | Thinking | Speaking)), + "{state:?}" + ); + assert_eq!(state.can_listen(), state.is_connected(), "{state:?}"); + assert_eq!( + state.is_pending(), + matches!(state, AgentState::Connecting) + || matches!(state, AgentState::Joined(_)) + && matches!(activity, Some(Initializing | Idle)), + "{state:?}" + ); + assert_eq!( + state.is_finished(), + matches!(state, AgentState::Disconnected | AgentState::Failed(_)), + "{state:?}" + ); + } + assert!(!connected(Initializing).is_connected()); + assert!(!connected(Unknown).is_pending()); + } + + #[test] + fn accessors_read_the_agent_from_either_variant() { + let stuck = timed_out(Some(agent("agent", Initializing))); + assert_eq!(stuck.identity().map(ParticipantIdentity::as_str), Some("agent")); + assert_eq!(stuck.activity(), Some(Initializing)); + assert_eq!(connected(Speaking).activity(), Some(Speaking)); + for state in [AgentState::Disconnected, AgentState::Connecting] { + assert_eq!(state.identity(), None); + assert_eq!(state.activity(), None); + assert!(state.audio_track().is_none()); + assert!(state.avatar_video_track().is_none()); + } + } +} diff --git a/livekit-session/src/constants.rs b/livekit-session/src/constants.rs new file mode 100644 index 0000000000..23d3470ba6 --- /dev/null +++ b/livekit-session/src/constants.rs @@ -0,0 +1,46 @@ +// Copyright 2026 LiveKit, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! The interop contract with `livekit-agents`: topics, attribute keys and +//! defaults shared by every SDK that ships a session. + +use std::time::Duration; + +/// Text-stream topic for chat: user input sent to the agent, and chat from +/// other participants. +pub(crate) const TOPIC_CHAT: &str = "lk.chat"; + +/// Text-stream topic agents publish agent and user transcripts on. +pub(crate) const TOPIC_TRANSCRIPTION: &str = "lk.transcription"; + +/// Participant attribute holding the agent's conversational activity. +pub(crate) const ATTRIBUTE_AGENT_STATE: &str = "lk.agent.state"; + +/// Participant attribute set on an avatar worker, naming the agent it +/// publishes for. Note the underscore, unlike [`ATTRIBUTE_AGENT_STATE`]. +pub(crate) const ATTRIBUTE_PUBLISH_ON_BEHALF: &str = "lk.publish_on_behalf"; + +/// Text-stream attribute identifying a transcript segment across the streams +/// that carry it. +pub(crate) const ATTRIBUTE_SEGMENT_ID: &str = "lk.segment_id"; + +/// Text-stream attribute marking a transcript segment as complete, written as +/// the string `"true"` or `"false"`. +pub(crate) const ATTRIBUTE_TRANSCRIPTION_FINAL: &str = "lk.transcription_final"; + +/// How long after connecting an agent gets to become conversational. +pub(crate) const DEFAULT_AGENT_CONNECT_TIMEOUT: Duration = Duration::from_secs(20); + +/// How many message feed events are kept for a subscriber that falls behind. +pub(crate) const DEFAULT_EVENT_BUFFER_SIZE: usize = 256; diff --git a/livekit-session/src/e2e_tests.rs b/livekit-session/src/e2e_tests.rs new file mode 100644 index 0000000000..6ff702e008 --- /dev/null +++ b/livekit-session/src/e2e_tests.rs @@ -0,0 +1,454 @@ +// Copyright 2026 LiveKit, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! End-to-end tests against a running `livekit-server --dev` that assert on +//! the crate's internals: the session's lifecycle, its actor, and every state +//! it published. The tests of the public API alone are in +//! `tests/session_test.rs`, which shares the helpers in `tests/common`. +//! +//! Environment variables (the same as `livekit`'s e2e suites): +//! - LIVEKIT_URL (default ws://localhost:7880) +//! - LIVEKIT_API_KEY (default "devkey") +//! - LIVEKIT_API_SECRET (default "secret") +//! +//! Run: +//! cargo test -p livekit-session --features __lk-e2e-test + +use std::sync::{Arc, Weak}; +use std::time::Duration; + +use anyhow::{anyhow, bail, Result}; +use async_trait::async_trait; +use livekit::prelude::*; +use livekit::SimulateScenario; +use livekit_api::services::room::RoomClient; +use livekit_token_source::{ + literal, TokenSourceConfigurable, TokenSourceError, TokenSourceFetchOptions, + TokenSourceLiteral, TokenSourceResponse, TokenSourceResult, +}; +use tokio::io::AsyncReadExt; +use tokio::net::TcpListener; +use tokio::sync::mpsc::UnboundedReceiver; +use tokio::sync::oneshot; +use tokio::time::{sleep, timeout}; + +use crate::actor::{lock, Shared}; +use crate::session::Lifecycle; +use crate::*; +use common::*; + +#[path = "../tests/common/mod.rs"] +mod common; + +fn weak_shared(session: &Session) -> Weak { + Arc::downgrade(&session.inner.shared) +} + +fn is_idle(session: &Session) -> bool { + matches!(*lock(&session.inner.lifecycle), Lifecycle::Idle) +} + +/// [`text_options`] for a room that gives up after its first failed join. +fn text_options_without_retries(token_source: TokenSourceLiteral) -> SessionOptions { + let mut room_options = RoomOptions::default(); + room_options.join_retries = 0; + text_options(token_source).with_room_options(room_options) +} + +/// Options for a session that fetches from `token_source` with no fetch +/// options and stays off the machine's audio devices. +fn configurable_text_options( + token_source: impl TokenSourceConfigurable + Send + Sync + 'static, +) -> SessionOptions { + SessionOptions::new_configurable_source(token_source, TokenSourceFetchOptions::new()) + .with_platform_audio(false) +} + +#[tokio::test(flavor = "multi_thread")] +async fn start_projects_the_agent_and_end_disconnects() -> Result<()> { + let env = TestEnv::new(); + let session = Session::new(text_options(env.user_source(false))); + assert_eq!(current(&session), SessionState::default()); + assert!(session.room().is_none()); + + session.start().await?; + assert_eq!(current(&session).connection, SessionConnectionState::Connected); + assert_eq!(current(&session).agent, AgentState::Connecting); + assert!(matches!(session.start().await, Err(SessionStartError::AlreadyStarted))); + let room = session.room().ok_or_else(|| anyhow!("no room"))?; + assert!(room.local_participant().track_publications().is_empty()); + drop(room); + + let mut state = session.state(); + let wait = tokio::spawn(async move { + state.wait_for(|s| s.agent.is_connected()).await.map(|s| s.clone()).ok() + }); + let (agent, _agent_events) = env.join_agent(AGENT, "listening").await?; + let connected = timeout(WAIT, wait).await??.ok_or_else(|| anyhow!("state closed"))?; + assert!(Expect::Joined(AgentActivity::Listening).matches(&connected.agent)); + + set_agent_state(&agent, "speaking").await?; + wait_for_agent(&session, Expect::Joined(AgentActivity::Speaking)).await?; + + session.end().await; + assert_eq!(current(&session), SessionState::default()); + assert!(session.room().is_none()); + // Ending again is a no-op. + session.end().await; + assert_eq!(current(&session), SessionState::default()); + assert!(is_idle(&session)); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread")] +async fn full_reconnect_does_not_report_left() -> Result<()> { + let env = TestEnv::new(); + let session = Session::new(text_options(env.user_source(false))); + session.start().await?; + let (_agent, _agent_events) = env.join_agent(AGENT, "listening").await?; + wait_for_agent(&session, Expect::Joined(AgentActivity::Listening)).await?; + lock(&session.inner.shared.history).clear(); + + let room = session.room().ok_or_else(|| anyhow!("no room"))?; + room.simulate_scenario(SimulateScenario::FullReconnect).await?; + eventually("a reconnect and the agent's return", || { + let history = lock(&session.inner.shared.history); + history.iter().any(|s| s.connection == SessionConnectionState::Reconnecting) + && history.last().is_some_and(|s| { + s.connection == SessionConnectionState::Connected + && Expect::Joined(AgentActivity::Listening).matches(&s.agent) + }) + }) + .await?; + + let history = lock(&session.inner.shared.history).clone(); + assert!( + !history.iter().any(|s| Expect::Left.matches(&s.agent)), + "a full reconnect was reported as the agent leaving: {history:?}" + ); + session.end().await; + Ok(()) +} + +#[tokio::test(flavor = "multi_thread")] +async fn restarting_after_a_server_side_disconnect() -> Result<()> { + let env = TestEnv::new(); + let session = Session::new(text_options(env.user_source(false))); + let rooms = + RoomClient::with_api_key(&env.url.replacen("ws", "http", 1), &env.api_key, &env.api_secret); + let disconnect = || async { + rooms.remove_participant(&env.room, USER).await?; + wait_for(&session, "disconnect", |s| s.connection == SessionConnectionState::Disconnected) + .await?; + anyhow::Ok(()) + }; + + session.start().await?; + let stale_room = Arc::downgrade(&session.room().ok_or_else(|| anyhow!("no room"))?); + disconnect().await?; + assert!(session.room().is_none()); + + // Restarting joins the stopped actor and releases its room. + session.start().await?; + assert!(stale_room.upgrade().is_none(), "the disconnected room is still held"); + disconnect().await?; + // Ending after a disconnect is a no-op. + session.end().await; + assert!(is_idle(&session)); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_rejected_token_fails_the_start() -> Result<()> { + let env = TestEnv::new(); + let options = text_options_without_retries(literal(env.url.clone(), "not a token")); + let session = Session::new(options); + assert!(matches!(session.start().await, Err(SessionStartError::Connect(_)))); + assert_eq!(current(&session), SessionState::default()); + assert!(is_idle(&session)); + Ok(()) +} + +/// A source that never answers, so `start` stays connecting. +struct PendingSource; + +#[async_trait] +impl TokenSourceConfigurable for PendingSource { + async fn fetch(&self, _: &TokenSourceFetchOptions) -> TokenSourceResult { + std::future::pending().await + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn end_cancels_a_pending_start() -> Result<()> { + let session = Session::new(configurable_text_options(PendingSource)); + let start = tokio::spawn({ + let session = session.clone(); + async move { session.start().await } + }); + wait_for(&session, "connecting", |s| s.connection == SessionConnectionState::Connecting) + .await?; + + session.end().await; + assert!(matches!(start.await?, Err(SessionStartError::Cancelled))); + assert_eq!(current(&session), SessionState::default()); + assert!(is_idle(&session)); + Ok(()) +} + +/// A signal server that accepts one connection and never answers, so +/// `Room::connect` stays in its handshake. +struct SilentServer { + url: String, + /// Resolves once the client connected. + accepted: oneshot::Receiver<()>, + /// Resolves once the client hung up. + closed: oneshot::Receiver<()>, +} + +impl SilentServer { + async fn bind() -> Result { + let listener = TcpListener::bind("127.0.0.1:0").await?; + let url = format!("ws://{}", listener.local_addr()?); + let (accepted_tx, accepted) = oneshot::channel(); + let (closed_tx, closed) = oneshot::channel(); + tokio::spawn(async move { + let Ok((mut socket, _)) = listener.accept().await else { + return; + }; + let _ = accepted_tx.send(()); + // Reads the handshake request and anything after it, answering + // nothing, until the client closes the connection. + let mut buf = [0; 1024]; + while matches!(socket.read(&mut buf).await, Ok(n) if n > 0) {} + let _ = closed_tx.send(()); + }); + Ok(Self { url, accepted, closed }) + } + + /// A session connecting to this server. + fn session(&self, env: &TestEnv) -> Session { + Session::new(self.session_options(env)) + } + + /// Options for a session connecting to this server. + fn session_options(&self, env: &TestEnv) -> SessionOptions { + let mut room_options = RoomOptions::default(); + room_options.join_retries = 0; + // Long enough that only a cancel can end the handshake. + room_options.connect_timeout = Duration::from_secs(60); + text_options(literal(self.url.clone(), env.token(USER, |t| t))) + .with_room_options(room_options) + } +} + +/// Asserts that a start cancelled during `Room::connect` hung up on the server, +/// left the session idle without spawning an actor, and leaves no task behind. +async fn assert_cancelled_connect_left_nothing( + session: &Session, + closed: oneshot::Receiver<()>, + baseline_tasks: usize, +) -> Result<()> { + timeout(WAIT, closed) + .await + .map_err(|_| anyhow!("the half-open signal connection was not closed"))??; + assert_eq!(current(session), SessionState::default()); + assert!(is_idle(session)); + assert_eq!(weak_shared(session).strong_count(), 1, "an actor was spawned"); + + let metrics = tokio::runtime::Handle::current().metrics(); + eventually("tasks to return to baseline", || metrics.num_alive_tasks() <= baseline_tasks).await +} + +#[tokio::test(flavor = "multi_thread")] +async fn end_cancels_a_start_during_connect() -> Result<()> { + let env = TestEnv::new(); + let baseline_tasks = tokio::runtime::Handle::current().metrics().num_alive_tasks(); + let server = SilentServer::bind().await?; + let session = server.session(&env); + let start = tokio::spawn({ + let session = session.clone(); + async move { session.start().await } + }); + timeout(WAIT, server.accepted).await??; + + session.end().await; + assert!(matches!(start.await?, Err(SessionStartError::Cancelled))); + assert_cancelled_connect_left_nothing(&session, server.closed, baseline_tasks).await +} + +#[tokio::test(flavor = "multi_thread")] +async fn dropping_a_start_during_connect_resets_the_session() -> Result<()> { + let env = TestEnv::new(); + let baseline_tasks = tokio::runtime::Handle::current().metrics().num_alive_tasks(); + let server = SilentServer::bind().await?; + let session = server.session(&env); + let mut start = Box::pin(session.start()); + tokio::select! { + result = &mut start => bail!("start resolved during the handshake: {result:?}"), + accepted = timeout(WAIT, server.accepted) => accepted??, + } + + drop(start); + assert_cancelled_connect_left_nothing(&session, server.closed, baseline_tasks).await +} + +#[tokio::test(flavor = "multi_thread")] +async fn dropping_a_pending_start_resets_the_session() -> Result<()> { + let session = Session::new(configurable_text_options(PendingSource)); + assert!(timeout(Duration::from_millis(100), session.start()).await.is_err()); + assert_eq!(current(&session), SessionState::default()); + assert!(is_idle(&session)); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_failed_microphone_publish_closes_the_room() -> Result<()> { + let Some(_probe) = microphone_probe() else { + return Ok(()); + }; + let env = TestEnv::new(); + // Keeps the room open, so that the server can be asked who is in it. + let (_observer, _) = env.join_observer().await?; + let baseline_tasks = tokio::runtime::Handle::current().metrics().num_alive_tasks(); + let session = Session::new(SessionOptions::new_fixed_source(env.unpublishable_user_source())); + + // The server rejects the publish, which fails the start. + let result = timeout(WAIT, session.start()).await?; + assert!(matches!(result, Err(SessionStartError::Microphone(_))), "{result:?}"); + assert_eq!(current(&session), SessionState::default()); + assert!(is_idle(&session)); + eventually("the actor to stop", || weak_shared(&session).strong_count() == 1).await?; + let metrics = tokio::runtime::Handle::current().metrics(); + eventually("tasks to return to baseline", || metrics.num_alive_tasks() <= baseline_tasks) + .await?; + + // The user joins and leaves so quickly that the server may fold the two + // into nothing, so the observer cannot wait for the leave. Ask the server + // instead. This runs after the task check, as the HTTP client can spawn + // tasks of its own. + let rooms = + RoomClient::with_api_key(&env.url.replacen("ws", "http", 1), &env.api_key, &env.api_secret); + timeout(WAIT, async { + while rooms.list_participants(&env.room).await?.iter().any(|p| p.identity == USER) { + sleep(Duration::from_millis(100)).await; + } + anyhow::Ok(()) + }) + .await + .map_err(|_| anyhow!("timed out waiting for the user to leave the room"))? +} + +// Lifecycle (AGENTS.md "Memory lifecycle") + +#[tokio::test(flavor = "multi_thread")] +async fn dropping_the_session_closes_the_room() -> Result<()> { + let env = TestEnv::new(); + let (_observer, mut observer_events) = env.join_observer().await?; + let session = Session::new(text_options(env.user_source(false))); + session.start().await?; + // Otherwise the server may fold the user's join and leave into nothing. + next_participant_event(&mut observer_events, |event| { + matches!(event, RoomEvent::ParticipantConnected(p) if p.identity().as_str() == USER) + }) + .await?; + + let room = session.room().ok_or_else(|| anyhow!("no room"))?; + let weak_room = Arc::downgrade(&room); + let weak_shared = weak_shared(&session); + drop(room); + drop(session); + + eventually("the actor to stop", || weak_shared.upgrade().is_none()).await?; + eventually("the room to be released", || weak_room.upgrade().is_none()).await?; + next_participant_event(&mut observer_events, |event| { + matches!(event, RoomEvent::ParticipantDisconnected(p) if p.identity().as_str() == USER) + }) + .await +} + +async fn next_participant_event( + events: &mut UnboundedReceiver, + mut predicate: impl FnMut(&RoomEvent) -> bool, +) -> Result<()> { + timeout(WAIT, async { + while let Some(event) = events.recv().await { + if predicate(&event) { + return Ok(()); + } + } + bail!("room events ended") + }) + .await + .map_err(|_| anyhow!("timed out waiting for a participant event"))? +} + +#[tokio::test(flavor = "multi_thread")] +async fn repeated_start_and_end_leave_nothing_behind() -> Result<()> { + let env = TestEnv::new(); + let session = Session::new(text_options(env.user_source(false))); + let metrics = tokio::runtime::Handle::current().metrics(); + let settle = || async { + // Room teardown finishes in tasks of its own after close returns. + sleep(Duration::from_millis(500)).await; + metrics.num_alive_tasks() + }; + + session.start().await?; + session.end().await; + let after_one = settle().await; + for _ in 0..3 { + session.start().await?; + session.end().await; + } + let after_four = settle().await; + assert!(after_four <= after_one, "tasks grew from {after_one} to {after_four}"); + assert_eq!(session.inner.shared.subscriber_count(), 0); + + let weak_shared = weak_shared(&session); + assert_eq!(weak_shared.strong_count(), 1, "only the session holds the shared state"); + drop(session); + assert!(weak_shared.upgrade().is_none()); + Ok(()) +} + +/// A source that always fails. +struct FailingSource; + +#[async_trait] +impl TokenSourceConfigurable for FailingSource { + async fn fetch(&self, _: &TokenSourceFetchOptions) -> TokenSourceResult { + Err(TokenSourceError::Server { status: 500, body: "test".into() }) + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn failed_starts_spawn_nothing() -> Result<()> { + let session = Session::new(configurable_text_options(FailingSource)); + for _ in 0..2 { + assert!(matches!(session.start().await, Err(SessionStartError::Token(_)))); + assert_eq!(current(&session), SessionState::default()); + assert!(is_idle(&session)); + } + assert_eq!(weak_shared(&session).strong_count(), 1); + + let env = TestEnv::new(); + let options = text_options_without_retries(literal("ws://127.0.0.1:1", env.token(USER, |t| t))); + let session = Session::new(options); + assert!(matches!(session.start().await, Err(SessionStartError::Connect(_)))); + assert_eq!(current(&session), SessionState::default()); + assert!(is_idle(&session)); + assert_eq!(weak_shared(&session).strong_count(), 1); + Ok(()) +} diff --git a/livekit-session/src/error.rs b/livekit-session/src/error.rs new file mode 100644 index 0000000000..0d8191d047 --- /dev/null +++ b/livekit-session/src/error.rs @@ -0,0 +1,56 @@ +// Copyright 2026 LiveKit, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use livekit::{AudioError, RoomError, StreamError}; +use livekit_token_source::TokenSourceError; +use thiserror::Error; + +/// Why [`Session::start`](crate::Session::start) failed. +#[derive(Debug, Error)] +#[non_exhaustive] +pub enum SessionStartError { + /// The session is already connecting or connected. + #[error("session is already started")] + AlreadyStarted, + /// [`Session::end`](crate::Session::end) was called before the connection + /// completed. + #[error("session ended before it connected")] + Cancelled, + /// The token source failed to provide credentials. + #[error("failed to fetch credentials: {0}")] + Token(#[from] TokenSourceError), + /// The room failed to connect. + #[error("failed to connect: {0}")] + Connect(RoomError), + /// Platform audio could not be started, e.g. on a machine without audio + /// devices. See + /// [`SessionOptions::with_platform_audio`](crate::SessionOptions::with_platform_audio). + #[error("failed to start platform audio: {0}")] + PlatformAudio(#[from] AudioError), + /// The microphone track failed to publish. + #[error("failed to publish the microphone: {0}")] + Microphone(RoomError), +} + +/// Why [`Session::send_text`](crate::Session::send_text) failed. +#[derive(Debug, Error)] +#[non_exhaustive] +pub enum MessageSendError { + /// The session has no connected room. + #[error("session is not connected")] + NotConnected, + /// The text stream failed to send. + #[error("failed to send: {0}")] + Stream(#[from] StreamError), +} diff --git a/livekit-session/src/lib.rs b/livekit-session/src/lib.rs new file mode 100644 index 0000000000..1fba1cc4e2 --- /dev/null +++ b/livekit-session/src/lib.rs @@ -0,0 +1,42 @@ +// Copyright 2026 LiveKit, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Agent sessions for the LiveKit Rust SDK. +//! +//! A session is the single entry point for a conversation with an agent: it +//! fetches credentials from a token source, connects a room, projects what the +//! agent is doing as [`AgentState`], and merges chat and transcripts into one +//! ordered feed of [`Message`]s. + +mod actor; +mod agent; +mod constants; +mod error; +mod messages; +mod session; + +// Lets the helpers in `tests/common`, which `e2e_tests` shares with the +// integration tests, name this crate the way an integration test does. +#[cfg(all(test, feature = "__lk-e2e-test"))] +extern crate self as livekit_session; + +#[cfg(all(test, feature = "__lk-e2e-test"))] +mod e2e_tests; + +pub use agent::{Agent, AgentActivity, AgentFailure, AgentState}; +pub use error::{MessageSendError, SessionStartError}; +pub use messages::{Message, MessageOrigin}; +pub use session::{ + Session, SessionConnectionState, SessionEvent, SessionEventStream, SessionOptions, SessionState, +}; diff --git a/livekit-session/src/messages.rs b/livekit-session/src/messages.rs new file mode 100644 index 0000000000..362299cec3 --- /dev/null +++ b/livekit-session/src/messages.rs @@ -0,0 +1,547 @@ +// Copyright 2026 LiveKit, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::collections::{hash_map::Entry, HashMap}; +use std::time::SystemTime; + +use livekit::prelude::ParticipantIdentity; + +use crate::constants::{ATTRIBUTE_SEGMENT_ID, ATTRIBUTE_TRANSCRIPTION_FINAL}; + +/// One entry of a session's message feed: a transcript segment or a chat +/// message. +/// +/// A message is identified by [`id`](Self::id) together with +/// [`participant_identity`](Self::participant_identity). A transcript is +/// updated in place as it grows, keeping its `seq` and `timestamp`. +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub struct Message { + /// The transcript segment id, or the text-stream id for chat and user + /// input. + pub id: String, + /// Position in the feed, assigned when the message is first received. + /// Messages are ordered by this rather than by `timestamp`, which comes + /// from the sender's clock. + pub seq: u64, + /// When the sender started the message, by the sender's clock. + pub timestamp: SystemTime, + /// Where the message came from. + pub origin: MessageOrigin, + /// The participant who sent or spoke the message. + pub participant_identity: ParticipantIdentity, + /// The text received so far. + pub text: String, + /// Whether `text` is complete. An incomplete transcript is updated again. + pub is_final: bool, +} + +impl Message { + /// Creates a final message timestamped now, e.g. to rebuild a saved + /// conversation for [`Session::restore_messages`](crate::Session::restore_messages). + /// + /// [`seq`](Self::seq) is zero until the message enters a feed, which + /// assigns it. + /// + /// ``` + /// # use std::time::{Duration, UNIX_EPOCH}; + /// # use livekit::prelude::ParticipantIdentity; + /// use livekit_session::{Message, MessageOrigin}; + /// + /// # let identity = ParticipantIdentity::from("user".to_owned()); + /// # let saved_at = UNIX_EPOCH + Duration::from_secs(1_800_000_000); + /// let message = Message::new("msg-1", MessageOrigin::UserInput, identity, "hello") + /// .with_timestamp(saved_at); + /// + /// assert_eq!(message.text, "hello"); + /// assert!(message.is_final); + /// ``` + pub fn new( + id: impl Into, + origin: MessageOrigin, + participant_identity: ParticipantIdentity, + text: impl Into, + ) -> Self { + Self { + id: id.into(), + seq: 0, + timestamp: SystemTime::now(), + origin, + participant_identity, + text: text.into(), + is_final: true, + } + } + + /// Sets [`timestamp`](Self::timestamp), which defaults to the time of + /// creation. + pub fn with_timestamp(mut self, timestamp: SystemTime) -> Self { + self.timestamp = timestamp; + self + } + + /// Sets [`is_final`](Self::is_final), which defaults to `true`. + pub fn with_is_final(mut self, is_final: bool) -> Self { + self.is_final = is_final; + self + } +} + +/// Where a [`Message`] came from. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum MessageOrigin { + /// A transcript of what the agent said. + AgentTranscript, + /// A transcript of what the local user said. + UserTranscript, + /// Text the local user sent with [`Session::send_text`](crate::Session::send_text). + UserInput, + /// Chat sent by another participant. + Chat, +} + +/// A message as a source reports it, before the store assigns its `seq`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct MessageUpdate { + pub id: String, + pub timestamp: SystemTime, + pub origin: MessageOrigin, + pub participant_identity: ParticipantIdentity, + pub text: String, + pub is_final: bool, +} + +/// An incoming `lk.transcription` stream. Its attributes are passed +/// separately on every call, since a trailer can still change them. +#[derive(Clone, Debug)] +pub(crate) struct TranscriptStream { + pub id: String, + pub timestamp: SystemTime, + pub participant_identity: ParticipantIdentity, + /// Whether the transcript is of the local user, i.e. the agent sent it on + /// the local participant's behalf. + pub is_local: bool, +} + +impl TranscriptStream { + /// The segment id, falling back to the stream id when the agent sent + /// none. + fn segment_id(&self, attributes: &HashMap) -> String { + attributes.get(ATTRIBUTE_SEGMENT_ID).cloned().unwrap_or_else(|| self.id.clone()) + } + + fn origin(&self) -> MessageOrigin { + if self.is_local { + MessageOrigin::UserTranscript + } else { + MessageOrigin::AgentTranscript + } + } +} + +/// Parses `lk.transcription_final`. Agents write the strings `"true"` and +/// `"false"`; anything else counts as absent. +fn parse_final(attributes: &HashMap) -> Option { + let value = attributes.get(ATTRIBUTE_TRANSCRIPTION_FINAL)?.trim(); + if value.eq_ignore_ascii_case("true") { + Some(true) + } else if value.eq_ignore_ascii_case("false") { + Some(false) + } else { + None + } +} + +/// A transcript segment still being received. +#[derive(Debug)] +struct Partial { + text: String, + /// The timestamp of the segment's first stream, kept as the segment grows. + timestamp: SystemTime, + /// The stream that last wrote the segment. + stream_id: String, +} + +/// Turns `lk.transcription` chunks into transcript messages. +/// +/// Agents send transcripts in two shapes on the same topic. Agent speech is +/// one stream whose chunks append to the text, finalized by the stream's +/// trailer. User speech is a new stream per interim result, each carrying the +/// full text so far, with the last one marked final. Both are handled by one +/// rule: a chunk appends when it arrives on the stream that last wrote the +/// segment, and replaces the text when it arrives on a new stream. +#[derive(Debug, Default)] +pub(crate) struct TranscriptAggregator { + /// Keyed by segment and participant: the same segment id from two + /// participants is two messages. + partials: HashMap<(String, ParticipantIdentity), Partial>, +} + +impl TranscriptAggregator { + /// Applies a chunk, returning the updated message. Empty chunks change + /// nothing. + pub(crate) fn on_chunk( + &mut self, + stream: &TranscriptStream, + attributes: &HashMap, + chunk: &str, + ) -> Option { + if chunk.is_empty() { + return None; + } + let segment_id = stream.segment_id(attributes); + let key = (segment_id.clone(), stream.participant_identity.clone()); + + if !self.partials.contains_key(&key) { + // A new segment means the participant's previous turn is over. + self.partials.retain(|(segment, participant), _| { + participant != &stream.participant_identity || segment == &segment_id + }); + } + let partial = self.partials.entry(key).or_insert_with(|| Partial { + text: String::new(), + timestamp: stream.timestamp, + stream_id: stream.id.clone(), + }); + if partial.stream_id == stream.id { + partial.text.push_str(chunk); + } else { + partial.text = chunk.to_owned(); + partial.stream_id = stream.id.clone(); + } + + Some(MessageUpdate { + id: segment_id, + timestamp: partial.timestamp, + origin: stream.origin(), + participant_identity: stream.participant_identity.clone(), + text: partial.text.clone(), + is_final: false, + }) + } + + /// Handles the end of a stream, returning the finalized message if the + /// stream completed its segment. + /// + /// A stream completes its segment unless it is explicitly marked not + /// final (an interim user transcript) or a newer stream has taken the + /// segment over. + pub(crate) fn on_stream_end( + &mut self, + stream: &TranscriptStream, + attributes: &HashMap, + ) -> Option { + if parse_final(attributes) == Some(false) { + return None; + } + let segment_id = stream.segment_id(attributes); + let key = (segment_id, stream.participant_identity.clone()); + if self.partials.get(&key)?.stream_id != stream.id { + return None; + } + let ((id, participant_identity), partial) = self.partials.remove_entry(&key)?; + + Some(MessageUpdate { + id, + timestamp: partial.timestamp, + origin: stream.origin(), + participant_identity, + text: partial.text, + is_final: true, + }) + } +} + +/// The message feed: messages deduplicated by id and participant, in receive +/// order. +#[derive(Debug, Default)] +pub(crate) struct MessageStore { + /// Ordered by `seq`. + messages: Vec, + index: HashMap<(String, ParticipantIdentity), usize>, + next_seq: u64, +} + +impl MessageStore { + /// Inserts a new message, or updates an existing one in place, keeping its + /// `seq`. + pub(crate) fn upsert(&mut self, update: MessageUpdate) -> Message { + let key = (update.id, update.participant_identity); + if let Some(&position) = self.index.get(&key) { + let message = &mut self.messages[position]; + message.timestamp = update.timestamp; + message.origin = update.origin; + message.text = update.text; + message.is_final = update.is_final; + return message.clone(); + } + + let (id, participant_identity) = key.clone(); + let message = Message { + id, + seq: self.next_seq, + timestamp: update.timestamp, + origin: update.origin, + participant_identity, + text: update.text, + is_final: update.is_final, + }; + self.next_seq += 1; + self.index.insert(key, self.messages.len()); + self.messages.push(message.clone()); + message + } + + /// All messages, ordered by `seq`. + pub(crate) fn messages(&self) -> &[Message] { + &self.messages + } + + /// A feed of `messages`, numbered from zero in the order given. Of + /// messages sharing an id and participant, the last wins and takes the + /// place of the first. + pub(crate) fn restored(messages: impl IntoIterator) -> Self { + let mut store = Self::default(); + for mut message in messages { + let key = (message.id.clone(), message.participant_identity.clone()); + match store.index.entry(key) { + Entry::Occupied(entry) => { + let existing = &mut store.messages[*entry.get()]; + message.seq = existing.seq; + *existing = message; + } + Entry::Vacant(entry) => { + message.seq = store.next_seq; + store.next_seq += 1; + entry.insert(store.messages.len()); + store.messages.push(message); + } + } + } + store + } +} + +#[cfg(test)] +mod tests { + use super::*; + + use std::time::{Duration, UNIX_EPOCH}; + + fn at(seconds: u64) -> SystemTime { + UNIX_EPOCH + Duration::from_secs(1_800_000_000 + seconds) + } + + fn stream(id: &str, participant: &str, seconds: u64) -> TranscriptStream { + TranscriptStream { + id: id.into(), + timestamp: at(seconds), + participant_identity: participant.to_owned().into(), + is_local: participant == "user", + } + } + + fn attributes(pairs: &[(&str, &str)]) -> HashMap { + pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect() + } + + fn segment(id: &str, is_final: &str) -> HashMap { + attributes(&[(ATTRIBUTE_SEGMENT_ID, id), (ATTRIBUTE_TRANSCRIPTION_FINAL, is_final)]) + } + + fn text(update: Option) -> Option<(String, bool)> { + update.map(|update| (update.text, update.is_final)) + } + + #[test] + fn chunks_on_one_stream_append() { + let mut aggregator = TranscriptAggregator::default(); + let agent = stream("s1", "agent", 0); + let open = segment("seg", "false"); + + aggregator.on_chunk(&agent, &open, "Hello"); + aggregator.on_chunk(&agent, &open, " world"); + let update = aggregator.on_chunk(&agent, &open, "!").unwrap(); + assert_eq!(update.text, "Hello world!"); + assert_eq!(update.origin, MessageOrigin::AgentTranscript); + assert!(!update.is_final); + + // The trailer marks the segment final before the stream ends. + let update = aggregator.on_stream_end(&agent, &segment("seg", "true")).unwrap(); + assert_eq!((update.id.as_str(), update.text.as_str()), ("seg", "Hello world!")); + assert!(update.is_final); + assert!(aggregator.partials.is_empty()); + } + + #[test] + fn a_new_stream_for_the_same_segment_replaces() { + let mut aggregator = TranscriptAggregator::default(); + let interim = segment("seg", "false"); + + let first = stream("s1", "user", 0); + aggregator.on_chunk(&first, &interim, "Hello"); + assert_eq!(aggregator.on_stream_end(&first, &interim), None); + + let second = stream("s2", "user", 5); + let update = aggregator.on_chunk(&second, &interim, "Hello world").unwrap(); + assert_eq!(update.text, "Hello world"); + assert_eq!(update.origin, MessageOrigin::UserTranscript); + assert_eq!(update.timestamp, at(0), "timestamp stays at the segment's first stream"); + aggregator.on_stream_end(&second, &interim); + + let last = stream("s3", "user", 9); + let done = segment("seg", "true"); + aggregator.on_chunk(&last, &done, "Hello world!"); + let update = aggregator.on_stream_end(&last, &done).unwrap(); + assert_eq!((update.text.as_str(), update.is_final), ("Hello world!", true)); + assert_eq!(update.timestamp, at(0)); + } + + #[test] + fn id_falls_back_to_the_stream_id() { + let mut aggregator = TranscriptAggregator::default(); + let update = aggregator.on_chunk(&stream("s1", "agent", 0), &HashMap::new(), "Hi").unwrap(); + assert_eq!(update.id, "s1"); + } + + #[test] + fn final_attribute_parsing() { + for (value, parsed) in [ + ("true", Some(true)), + ("TRUE", Some(true)), + (" true ", Some(true)), + ("false", Some(false)), + ("yes", None), + ] { + let attrs = attributes(&[(ATTRIBUTE_TRANSCRIPTION_FINAL, value)]); + assert_eq!(parse_final(&attrs), parsed, "{value:?}"); + } + assert_eq!(parse_final(&HashMap::new()), None); + } + + #[test] + fn stream_ending_without_final_attribute_finalizes() { + let mut aggregator = TranscriptAggregator::default(); + let agent = stream("s1", "agent", 0); + let attrs = attributes(&[(ATTRIBUTE_SEGMENT_ID, "seg")]); + aggregator.on_chunk(&agent, &attrs, "Hi"); + assert_eq!(text(aggregator.on_stream_end(&agent, &attrs)), Some(("Hi".into(), true))); + } + + #[test] + fn stream_ending_after_being_superseded_does_not_finalize() { + let mut aggregator = TranscriptAggregator::default(); + let attrs = attributes(&[(ATTRIBUTE_SEGMENT_ID, "seg")]); + let first = stream("s1", "user", 0); + let second = stream("s2", "user", 1); + aggregator.on_chunk(&first, &attrs, "Hel"); + aggregator.on_chunk(&second, &attrs, "Hello"); + assert_eq!(aggregator.on_stream_end(&first, &attrs), None); + assert_eq!(text(aggregator.on_stream_end(&second, &attrs)), Some(("Hello".into(), true))); + } + + #[test] + fn empty_chunks_are_skipped() { + let mut aggregator = TranscriptAggregator::default(); + assert_eq!(aggregator.on_chunk(&stream("s1", "agent", 0), &HashMap::new(), ""), None); + assert!(aggregator.partials.is_empty()); + } + + #[test] + fn same_segment_from_two_participants_is_two_messages() { + let mut aggregator = TranscriptAggregator::default(); + let mut store = MessageStore::default(); + let attrs = segment("seg", "false"); + store.upsert(aggregator.on_chunk(&stream("s1", "agent", 0), &attrs, "A").unwrap()); + store.upsert(aggregator.on_chunk(&stream("s2", "user", 0), &attrs, "B").unwrap()); + assert_eq!(aggregator.partials.len(), 2); + assert_eq!(store.messages().len(), 2); + } + + #[test] + fn a_new_segment_drops_the_participants_previous_partials() { + let mut aggregator = TranscriptAggregator::default(); + aggregator.on_chunk(&stream("s1", "agent", 0), &segment("one", "false"), "first"); + aggregator.on_chunk(&stream("s2", "user", 0), &segment("one", "false"), "mine"); + aggregator.on_chunk(&stream("s3", "agent", 1), &segment("two", "false"), "second"); + + let mut keys: Vec<_> = aggregator + .partials + .keys() + .map(|(segment, participant)| (segment.as_str(), participant.as_str())) + .collect(); + keys.sort(); + assert_eq!(keys, [("one", "user"), ("two", "agent")]); + } + + fn update(id: &str, seconds: u64, text: &str) -> MessageUpdate { + MessageUpdate { + id: id.into(), + timestamp: at(seconds), + origin: MessageOrigin::Chat, + participant_identity: "remote".to_owned().into(), + text: text.into(), + is_final: true, + } + } + + #[test] + fn upsert_keeps_seq_and_orders_by_receive_order() { + let mut store = MessageStore::default(); + // The second message has the earlier sender clock. + assert_eq!(store.upsert(update("a", 10, "first")).seq, 0); + assert_eq!(store.upsert(update("b", 0, "second")).seq, 1); + let updated = store.upsert(update("a", 10, "first, edited")); + assert_eq!(updated.seq, 0); + + let feed: Vec<_> = store.messages().iter().map(|m| (m.id.as_str(), m.seq)).collect(); + assert_eq!(feed, [("a", 0), ("b", 1)]); + assert_eq!(store.messages()[0].text, "first, edited"); + } + + #[test] + fn restore_keeps_the_given_order_and_renumbers() { + let mut store = MessageStore::default(); + + // Received first, but stamped later by a skewed sender clock. + let mut first = store.upsert(update("first", 20, "first")); + first.seq = 7; + let mut second = first.clone(); + second.id = "second".into(); + second.timestamp = at(10); + second.seq = 3; + + let mut store = MessageStore::restored([first, second]); + let feed: Vec<_> = store.messages().iter().map(|m| (m.id.as_str(), m.seq)).collect(); + assert_eq!(feed, [("first", 0), ("second", 1)]); + assert_eq!(store.upsert(update("next", 0, "next")).seq, 2); + } + + #[test] + fn restore_keeps_the_last_of_duplicates_in_the_first_position() { + let mut store = MessageStore::default(); + let first = store.upsert(update("first", 0, "partial")); + let second = store.upsert(update("second", 1, "second")); + let mut grown = first.clone(); + grown.text = "complete".into(); + + let mut store = MessageStore::restored([first, second, grown]); + let feed: Vec<_> = + store.messages().iter().map(|m| (m.id.as_str(), m.seq, m.text.as_str())).collect(); + assert_eq!(feed, [("first", 0, "complete"), ("second", 1, "second")]); + assert_eq!(store.upsert(update("first", 0, "again")).seq, 0); + assert_eq!(store.upsert(update("next", 0, "next")).seq, 2); + } +} diff --git a/livekit-session/src/session.rs b/livekit-session/src/session.rs new file mode 100644 index 0000000000..b3d64da295 --- /dev/null +++ b/livekit-session/src/session.rs @@ -0,0 +1,721 @@ +// Copyright 2026 LiveKit, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::pin::Pin; +use std::sync::{Arc, Mutex, TryLockError}; +use std::task::{ready, Context, Poll}; +use std::time::Duration; +use std::{fmt, mem}; + +use futures_util::Stream; +use livekit::prelude::*; +use livekit::SendTextOptions; +use livekit_token_source::{ + TokenSourceConfigurable, TokenSourceFetchOptions, TokenSourceFixed, TokenSourceResponse, + TokenSourceResult, +}; +use tokio::sync::{broadcast, mpsc, oneshot, watch}; +use tokio::task::JoinHandle; +use tokio_stream::wrappers::errors::BroadcastStreamRecvError; +use tokio_stream::wrappers::BroadcastStream; + +use crate::actor::{lock, Connection, SessionActor, Shared}; +use crate::agent::AgentState; +use crate::constants::{DEFAULT_AGENT_CONNECT_TIMEOUT, DEFAULT_EVENT_BUFFER_SIZE, TOPIC_CHAT}; +use crate::error::{MessageSendError, SessionStartError}; +use crate::messages::{Message, MessageOrigin, MessageUpdate}; + +/// Where a [`Session`] gets its credentials, chosen by the [`SessionOptions`] +/// constructor used. +/// +/// The sources are behind an `Arc`, so a clone shares the source instead of +/// copying it: `dyn` types cannot implement `Clone`. +// Built once per session and kept behind an `Arc`, so its size does not matter. +#[derive(Clone)] +#[allow(clippy::large_enum_variant)] +pub(crate) enum SessionTokenSource { + /// A source whose credentials take no options. + Fixed(Arc), + /// A source fetched with the given options, e.g. to dispatch an agent. + Configurable(Arc, TokenSourceFetchOptions), +} + +impl SessionTokenSource { + async fn fetch(&self) -> TokenSourceResult { + match self { + Self::Fixed(source) => source.fetch().await, + Self::Configurable(source, options) => source.fetch(options).await, + } + } +} + +/// Prints only the kind of source. The source and the fetch options can hold +/// credentials. +impl fmt::Debug for SessionTokenSource { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Fixed(_) => f.write_str("Fixed"), + Self::Configurable(..) => f.write_str("Configurable"), + } + } +} + +/// The inputs of a [`Session`]: where it gets its credentials, and how it +/// connects. +/// +/// Create it with [`new_configurable_source`](Self::new_configurable_source) +/// or [`new_fixed_source`](Self::new_fixed_source), which select the token +/// source. Then change the defaults through the `with_*` setters. +#[derive(Clone, Debug)] +pub struct SessionOptions { + source: SessionTokenSource, + agent_connect_timeout: Duration, + room_options: RoomOptions, + platform_audio: bool, + event_buffer_size: usize, +} + +impl SessionOptions { + /// Creates options that fetch credentials from `source` with + /// `fetch_options`, e.g. to dispatch an agent with + /// [`TokenSourceFetchOptions::with_agent_name`]. + /// + /// Every [`Session::start`] fetches anew, so pass the source itself rather + /// than one wrapped in [`cached`](TokenSourceConfigurable::cached): agents + /// do not rejoin a room that already existed, and a cached token names the + /// previous room. + pub fn new_configurable_source( + source: impl TokenSourceConfigurable + Send + Sync + 'static, + fetch_options: TokenSourceFetchOptions, + ) -> Self { + Self::from_source(SessionTokenSource::Configurable(Arc::new(source), fetch_options)) + } + + /// Creates options that get credentials from a fixed `source`, such as a + /// [`literal`](livekit_token_source::literal) one. + pub fn new_fixed_source(source: impl TokenSourceFixed + Send + Sync + 'static) -> Self { + Self::from_source(SessionTokenSource::Fixed(Arc::new(source))) + } + + /// Stands in for `..Default::default()`, which needs a source. + fn from_source(source: SessionTokenSource) -> Self { + Self { + source, + agent_connect_timeout: DEFAULT_AGENT_CONNECT_TIMEOUT, + room_options: RoomOptions::default(), + platform_audio: true, + event_buffer_size: DEFAULT_EVENT_BUFFER_SIZE, + } + } + + /// Sets how long after connecting an agent gets to become conversational + /// before the agent state reports + /// [`AgentFailure::Timeout`](crate::AgentFailure::Timeout). Defaults to 20 + /// seconds. + /// + /// Armed on every connect, whether or not the token names an agent: an + /// agent registered without a name is dispatched into every new room. + pub fn with_agent_connect_timeout(mut self, timeout: Duration) -> Self { + self.agent_connect_timeout = timeout; + self + } + + /// Sets the options for the session's room, including + /// [`encryption`](RoomOptions::encryption), which can be toggled once + /// connected through [`Session::room`]. + pub fn with_room_options(mut self, room_options: RoomOptions) -> Self { + self.room_options = room_options; + self + } + + /// Sets whether [`start`](Session::start) uses the platform's audio + /// devices: the microphone is captured and published as the local + /// participant's [`TrackSource::Microphone`] track, and the agent's audio + /// plays through the speakers, until the session ends. Defaults to `true`. + /// + /// `start` fails with [`SessionStartError::PlatformAudio`] on a machine + /// without audio devices. Turn this off to converse by text alone, or to + /// publish audio of your own through [`Session::room`]. + /// + /// Device selection and audio processing are shared by every + /// [`PlatformAudio`] in the process, so configure them on one of your own. + pub fn with_platform_audio(mut self, platform_audio: bool) -> Self { + self.platform_audio = platform_audio; + self + } + + /// Sets how many message feed events the session keeps for a subscriber + /// that falls behind, see [`Session::subscribe`]. Defaults to 256. + /// + /// Zero is not a valid size, and is clamped to one. + pub fn with_event_buffer_size(mut self, mut events: usize) -> Self { + if events == 0 { + log::warn!("zero is not a valid event buffer size, using one"); + events = 1; + } + self.event_buffer_size = events; + self + } +} + +/// A change to a [`Session`]'s message feed. State changes are observed +/// through [`Session::state`] instead. +#[derive(Clone, Debug)] +#[non_exhaustive] +pub enum SessionEvent { + /// A message was added, or updated in place (a growing transcript). + MessageUpserted(Message), + /// The feed was replaced by [`Session::restore_messages`]. + MessagesRestored, +} + +/// A stream of [`SessionEvent`]s from a [`Session`], created by +/// [`Session::subscribe`]. +/// +/// Ends after the session is dropped. Drop the stream to unsubscribe. +#[derive(Debug)] +pub struct SessionEventStream { + inner: BroadcastStream, +} + +impl SessionEventStream { + pub(crate) fn new(events: broadcast::Receiver) -> Self { + Self { inner: BroadcastStream::new(events) } + } +} + +impl Stream for SessionEventStream { + type Item = SessionEvent; + + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = self.get_mut(); + loop { + match ready!(Pin::new(&mut this.inner).poll_next(cx)) { + Some(Ok(event)) => return Poll::Ready(Some(event)), + Some(Err(BroadcastStreamRecvError::Lagged(missed))) => { + log::warn!("a session event subscriber lagged and missed {missed} events"); + } + None => return Poll::Ready(None), + } + } + } +} + +/// A conversation with a LiveKit agent. +/// +/// [`start`](Self::start) fetches credentials and connects a room; the agent is +/// dispatched by the token, or automatically when it is registered without a +/// name. From then on the session projects what the agent +/// is doing ([`state`](Self::state)) and merges chat and transcripts into one +/// feed ([`messages`](Self::messages), [`subscribe`](Self::subscribe)). +/// +/// The session reads every text stream on the `lk.chat` and `lk.transcription` +/// topics itself: an app subscribed to the [`room`](Self::room) sees those +/// streams' [`RoomEvent::TextStreamOpened`] with the reader already taken. +/// Streams on other topics are left to the app. +/// +/// By default `start` also captures the platform microphone, publishes it as +/// the local participant's microphone track, and plays the agent through the +/// speakers, until the session ends. [`SessionOptions::with_platform_audio`] turns +/// that off. +/// +/// Handles are cheap to clone and share one session. Dropping the last handle +/// closes the room. +/// +/// ```no_run +/// use livekit_session::{Session, SessionOptions}; +/// use livekit_token_source::{development_token_server, TokenSourceFetchOptions}; +/// +/// # async fn run() -> Result<(), Box> { +/// let token_source = development_token_server("my-token-server-id"); +/// let fetch_options = TokenSourceFetchOptions::new().with_agent_name("my-agent"); +/// let session = Session::new(SessionOptions::new_configurable_source(token_source, fetch_options)); +/// +/// session.start().await?; +/// session.state().wait_for(|state| state.agent.is_connected()).await?; +/// session.send_text("Hello!").await?; +/// # Ok(()) +/// # } +/// ``` +#[derive(Clone)] +pub struct Session { + pub(crate) inner: Arc, +} + +pub(crate) struct Inner { + options: SessionOptions, + pub(crate) shared: Arc, + pub(crate) lifecycle: Mutex, +} + +/// Prints a snapshot of the session's status. Omits the message contents, +/// the token source and the room options, which can hold user content and +/// credentials. +impl fmt::Debug for Session { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let inner = &self.inner; + // Never block: the caller can hold the lifecycle lock. + let lifecycle = match inner.lifecycle.try_lock() { + Ok(lifecycle) => lifecycle.name(), + Err(TryLockError::Poisoned(poisoned)) => poisoned.into_inner().name(), + Err(TryLockError::WouldBlock) => "", + }; + let state = inner.shared.watch(); + let state = state.borrow(); + f.debug_struct("Session") + .field("lifecycle", &format_args!("{lifecycle}")) + .field("connection", &state.connection) + .field("agent", &state.agent) + .field("messages", &inner.shared.message_count()) + .field("agent_connect_timeout", &inner.options.agent_connect_timeout) + .field("platform_audio", &inner.options.platform_audio) + .finish_non_exhaustive() + } +} + +pub(crate) enum Lifecycle { + Idle, + Starting { generation: u64, cancel: oneshot::Sender<()> }, + Running(Running), +} + +pub(crate) struct Running { + /// The `start()` that spawned the actor. + generation: u64, + room: Arc, + /// Dropped to stop the actor. + stop: mpsc::Sender<()>, + task: JoinHandle<()>, +} + +impl Running { + /// Stops the actor, unless it already stopped on its own, and waits for + /// it. + async fn join(self) { + drop(self.stop); + if let Err(err) = self.task.await { + log::error!("session actor failed: {err}"); + } + } +} + +impl Lifecycle { + /// The name of the variant, for [`Session`]'s `Debug` output. + fn name(&self) -> &'static str { + match self { + Self::Idle => "Idle", + Self::Starting { .. } => "Starting", + Self::Running(_) => "Running", + } + } + + /// The running room, unless its actor has already stopped on its own. + fn room(&self) -> Option<&Arc> { + match self { + Self::Running(running) if !running.stop.is_closed() => Some(&running.room), + _ => None, + } + } + + /// Takes the running state of `generation`, leaving the lifecycle idle. + /// `None` if an `end` or a later `start` already replaced it. + fn take_running(&mut self, generation: u64) -> Option { + match self { + Self::Running(running) if running.generation == generation => {} + _ => return None, + } + match mem::replace(self, Self::Idle) { + Self::Running(running) => Some(running), + _ => None, + } + } +} + +impl Session { + /// Creates a session from `options`, which also select its token source. + /// Nothing happens until [`start`](Self::start). + pub fn new(options: SessionOptions) -> Self { + Self { + inner: Arc::new(Inner { + shared: Arc::new(Shared::new(options.event_buffer_size)), + options, + lifecycle: Mutex::new(Lifecycle::Idle), + }), + } + } + + /// Fetches credentials, connects the room, and publishes the microphone + /// (see [`SessionOptions::with_platform_audio`]). + /// + /// Resolves once the room is connected, not once the agent is: wait for + /// that on [`state`](Self::state). Fails with + /// [`AlreadyStarted`](SessionStartError::AlreadyStarted) while the session + /// is connecting or connected. + /// + /// Dropping the future before it resolves leaves the session + /// disconnected; a room connected by then is closed in the background. + pub async fn start(&self) -> Result<(), SessionStartError> { + let (cancel_tx, cancel_rx) = oneshot::channel(); + let (generation, stale) = { + let mut lifecycle = lock(&self.inner.lifecycle); + if matches!(*lifecycle, Lifecycle::Starting { .. }) || lifecycle.room().is_some() { + return Err(SessionStartError::AlreadyStarted); + } + let generation = self.inner.shared.begin(SessionState { + connection: SessionConnectionState::Connecting, + agent: AgentState::Connecting, + }); + let starting = Lifecycle::Starting { generation, cancel: cancel_tx }; + let stale = match mem::replace(&mut *lifecycle, starting) { + Lifecycle::Running(running) => Some(running), + _ => None, + }; + (generation, stale) + }; + let mut guard = StartGuard { inner: &self.inner, generation, armed: true }; + // The actor of a room that disconnected on its own, which has stopped + // or is about to. + if let Some(stale) = stale { + stale.join().await; + } + + let connection = tokio::select! { + connection = self.connect() => connection, + _ = cancel_rx => Err(SessionStartError::Cancelled), + }; + let connection = connection?; + + // The connected room is handed to its actor before anything else is + // awaited: from here on, dropping this future stops the actor, which + // closes the room, rather than dropping a room nobody would close. + let room = connection.room.clone(); + let (stop_tx, stop_rx) = mpsc::channel(1); + let (ready_tx, ready_rx) = oneshot::channel(); + let shared = self.inner.shared.clone(); + let actor = SessionActor::new(generation, connection, stop_rx, ready_tx, shared); + { + let mut lifecycle = lock(&self.inner.lifecycle); + let task = tokio::spawn(actor.run()); + if !matches!(*lifecycle, Lifecycle::Starting { generation: g, .. } if g == generation) { + // `end` was called just as the connection completed. The + // actor, finding its `stop` sender gone, closes the room. + drop(stop_tx); + return Err(SessionStartError::Cancelled); + } + *lifecycle = Lifecycle::Running(Running { generation, room, stop: stop_tx, task }); + } + + // The actor publishes the microphone, then answers. Dropping the + // receiver does not stop it; the guard does. + let ready = ready_rx.await; + guard.armed = false; + match ready { + Ok(Ok(())) => Ok(()), + Ok(Err(err)) => { + // The actor closed the room and is stopping. + let failed = lock(&self.inner.lifecycle).take_running(generation); + if let Some(failed) = failed { + failed.join().await; + } + Err(SessionStartError::Microphone(err)) + } + // `end` stopped the actor before the microphone was published. + Err(_) => Err(SessionStartError::Cancelled), + } + } + + async fn connect(&self) -> Result { + let options = &self.inner.options; + let credentials = options.source.fetch().await?; + // Platform audio has to exist before the room connects. + let platform_audio = options.platform_audio.then(PlatformAudio::new).transpose()?; + let (room, events) = Room::connect( + &credentials.server_url, + &credentials.participant_token, + options.room_options.clone(), + ) + .await + .map_err(SessionStartError::Connect)?; + Ok(Connection { + room: Arc::new(room), + events, + platform_audio, + agent_timeout: options.agent_connect_timeout, + }) + } + + /// Closes the room, or cancels a [`start`](Self::start) still in progress. + /// + /// Does nothing when there is nothing to end, including after the room + /// disconnected on its own. A room that fails to close cleanly is logged, + /// and the session has ended regardless. + /// + /// The session can be started again as soon as `end` is called, before + /// the room has finished closing. + pub async fn end(&self) { + let running = { + let mut lifecycle = lock(&self.inner.lifecycle); + match mem::replace(&mut *lifecycle, Lifecycle::Idle) { + Lifecycle::Idle => return, + Lifecycle::Starting { generation, cancel } => { + let _ = cancel.send(()); + self.inner.shared.publish(generation, SessionState::default()); + return; + } + Lifecycle::Running(running) => running, + } + }; + running.join().await; + } + + /// A receiver of the session's state. [`borrow`](watch::Receiver::borrow) + /// reads the current value, and [`wait_for`](watch::Receiver::wait_for) + /// awaits a condition. + pub fn state(&self) -> watch::Receiver { + self.inner.shared.watch() + } + + /// The session's room, while it is connected or reconnecting. + /// + /// The room is closed once the session ends, even if the caller still + /// holds it. + pub fn room(&self) -> Option> { + lock(&self.inner.lifecycle).room().cloned() + } + + /// Sends `text` to the agent as chat, and adds it to the feed as + /// [`MessageOrigin::UserInput`] once sent. A failed send adds nothing. + pub async fn send_text(&self, text: &str) -> Result { + let room = self.room().ok_or(MessageSendError::NotConnected)?; + let local_participant = room.local_participant(); + let info = + local_participant.send_text(text, SendTextOptions::new_with_topic(TOPIC_CHAT)).await?; + Ok(self.inner.shared.upsert(MessageUpdate { + id: info.id, + timestamp: info.timestamp.into(), + origin: MessageOrigin::UserInput, + participant_identity: local_participant.identity(), + text: text.to_owned(), + is_final: true, + })) + } + + /// The message feed, ordered by [`Message::seq`]. + pub fn messages(&self) -> Vec { + self.inner.shared.messages() + } + + /// Replaces the feed with `messages`, e.g. a conversation saved from an + /// earlier run. They keep the order given and are renumbered from zero; + /// later messages follow them. Of messages sharing an id and participant, + /// the last wins and takes the place of the first. + /// + /// Takes the messages by value; pass `saved.iter().cloned()` to keep + /// them. + pub fn restore_messages(&self, messages: impl IntoIterator) { + self.inner.shared.restore(messages); + } + + /// Subscribes to changes to the message feed. The stream yields the + /// changes made after this call. + /// + /// The session never blocks on a slow subscriber. It keeps a bounded + /// number of events, set by [`SessionOptions::with_event_buffer_size`]: a + /// subscriber that falls further behind loses the oldest ones, and a + /// warning is logged. [`messages`](Self::messages) always returns the + /// complete feed. Drop the stream to unsubscribe. + pub fn subscribe(&self) -> SessionEventStream { + SessionEventStream::new(self.inner.shared.subscribe()) + } +} + +/// Resets the session when a [`Session::start`] fails or is dropped before +/// it resolves. An actor already spawned is stopped instead, so that it +/// closes its room and publishes the final state. +struct StartGuard<'a> { + inner: &'a Inner, + generation: u64, + armed: bool, +} + +impl Drop for StartGuard<'_> { + fn drop(&mut self) { + if !self.armed { + return; + } + let mut lifecycle = lock(&self.inner.lifecycle); + if matches!(*lifecycle, Lifecycle::Starting { generation, .. } if generation == self.generation) + { + *lifecycle = Lifecycle::Idle; + self.inner.shared.publish(self.generation, SessionState::default()); + return; + } + // Dropped while the actor was publishing the microphone. Dropping its + // `stop` sender stops it. + drop(lifecycle.take_running(self.generation)); + } +} + +/// The connection state of a [`Session`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum SessionConnectionState { + /// Not started, ended, or disconnected. + Disconnected, + /// Fetching credentials and connecting the room. + Connecting, + /// The room is connected. + Connected, + /// The room lost its connection and is reconnecting. + Reconnecting, +} + +impl SessionConnectionState { + /// Whether a room exists and is connected or recovering its connection. + pub fn is_connected(self) -> bool { + matches!(self, Self::Connected | Self::Reconnecting) + } +} + +/// The observable state of a [`Session`] at one point in time. +/// +/// Holds the agent's tracks (see [`AgentState::audio_track`]), so a value +/// kept after the session moved on keeps those tracks alive. +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub struct SessionState { + /// The state of the session's connection. + pub connection: SessionConnectionState, + /// Whether the agent is there, what it is doing, and its tracks. + pub agent: AgentState, +} + +impl Default for SessionState { + fn default() -> Self { + Self { connection: SessionConnectionState::Disconnected, agent: AgentState::Disconnected } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + use async_trait::async_trait; + use futures_util::StreamExt; + use livekit_token_source::TokenSourceError; + + /// Records the options it is fetched with, then fails. + struct RecordingSource(Arc>>); + + #[async_trait] + impl TokenSourceConfigurable for RecordingSource { + async fn fetch( + &self, + options: &TokenSourceFetchOptions, + ) -> TokenSourceResult { + *lock(&self.0) = Some(options.clone()); + Err(TokenSourceError::Server { status: 500, body: "test".into() }) + } + } + + #[tokio::test] + async fn fetches_with_the_fetch_options() { + let fetched = Arc::default(); + let source = RecordingSource(Arc::clone(&fetched)); + let fetch_options = TokenSourceFetchOptions::new().with_agent_name("my-agent"); + let options = SessionOptions::new_configurable_source(source, fetch_options) + .with_platform_audio(false); + let session = Session::new(options); + + assert!(matches!(session.start().await, Err(SessionStartError::Token(_)))); + let options = lock(&fetched).take().expect("source was not fetched"); + assert_eq!(options, TokenSourceFetchOptions::new().with_agent_name("my-agent")); + } + + #[test] + fn debug_prints_status_without_blocking() { + let source = RecordingSource(Arc::default()); + let fetch_options = TokenSourceFetchOptions::new().with_agent_name("my-agent"); + let options = SessionOptions::new_configurable_source(source, fetch_options) + .with_platform_audio(false); + let session = Session::new(options); + + let idle = format!("{session:?}"); + assert!(idle.starts_with( + "Session { lifecycle: Idle, connection: Disconnected, agent: Disconnected, messages: 0" + )); + assert!(!idle.contains("my-agent")); + + let _held = lock(&session.inner.lifecycle); + assert!(format!("{session:?}").contains("lifecycle: ")); + } + + fn update(id: &str, text: &str) -> MessageUpdate { + MessageUpdate { + id: id.into(), + timestamp: std::time::UNIX_EPOCH, + origin: MessageOrigin::Chat, + participant_identity: "remote".to_owned().into(), + text: text.into(), + is_final: false, + } + } + + fn upserted_text(event: Option) -> String { + match event { + Some(SessionEvent::MessageUpserted(message)) => message.text, + other => panic!("expected an upsert, got {other:?}"), + } + } + + #[tokio::test] + async fn subscriber_gets_events_in_order_until_the_session_is_dropped() { + let shared = Shared::new(DEFAULT_EVENT_BUFFER_SIZE); + let mut events = SessionEventStream::new(shared.subscribe()); + shared.upsert(update("a", "Hel")); + shared.upsert(update("a", "Hello")); + shared.restore([]); + + assert_eq!(upserted_text(events.next().await), "Hel"); + assert_eq!(upserted_text(events.next().await), "Hello"); + assert!(matches!(events.next().await, Some(SessionEvent::MessagesRestored))); + + drop(shared); + assert!(events.next().await.is_none()); + } + + #[tokio::test] + async fn lagging_subscriber_continues_with_the_oldest_kept_event() { + let shared = Shared::new(4); + let mut events = SessionEventStream::new(shared.subscribe()); + for chunk in 0..6 { + shared.upsert(update("a", &format!("chunk {chunk}"))); + } + + // The two oldest events are lost. The rest arrive, then live events. + for chunk in 2..6 { + assert_eq!(upserted_text(events.next().await), format!("chunk {chunk}")); + } + shared.upsert(update("a", "live")); + assert_eq!(upserted_text(events.next().await), "live"); + } + + #[test] + fn zero_event_buffer_size_is_clamped_to_one() { + let options = + SessionOptions::new_fixed_source(livekit_token_source::literal("url", "token")); + assert_eq!(options.event_buffer_size, DEFAULT_EVENT_BUFFER_SIZE); + assert_eq!(options.with_event_buffer_size(0).event_buffer_size, 1); + } +} diff --git a/livekit-session/tests/common/mod.rs b/livekit-session/tests/common/mod.rs new file mode 100644 index 0000000000..db77e073cd --- /dev/null +++ b/livekit-session/tests/common/mod.rs @@ -0,0 +1,233 @@ +// Copyright 2026 LiveKit, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Helpers shared by the end-to-end tests: the black-box ones in +//! `tests/session_test.rs`, and the white-box ones in `src/e2e_tests.rs`, +//! which include this file by path. + +// Each of the two test crates uses only some of the helpers. +#![allow(dead_code)] + +use std::collections::HashMap; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use anyhow::{anyhow, Result}; +use livekit::prelude::*; +use livekit_session::{ + AgentActivity, AgentFailure, AgentState, Session, SessionOptions, SessionState, +}; +use livekit_token::{AccessToken, VideoGrants}; +use livekit_token_source::{literal, TokenSourceLiteral}; +use tokio::sync::mpsc::UnboundedReceiver; +use tokio::time::{sleep, timeout}; + +// The attributes an agent sets, spelled out so that the tests pin the wire +// names independently of the crate's own constants. +const ATTRIBUTE_AGENT_STATE: &str = "lk.agent.state"; +const ATTRIBUTE_PUBLISH_ON_BEHALF: &str = "lk.publish_on_behalf"; + +pub const USER: &str = "user"; +pub const AGENT: &str = "agent"; +pub const WAIT: Duration = Duration::from_secs(10); + +pub struct TestEnv { + pub url: String, + pub api_key: String, + pub api_secret: String, + pub room: String, +} + +impl TestEnv { + pub fn new() -> Self { + // The clock alone can repeat across tests started in parallel. + static ROOMS: AtomicUsize = AtomicUsize::new(0); + let nanos = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos(); + let count = ROOMS.fetch_add(1, Ordering::Relaxed); + Self { + url: std::env::var("LIVEKIT_URL").unwrap_or_else(|_| "ws://localhost:7880".into()), + api_key: std::env::var("LIVEKIT_API_KEY").unwrap_or_else(|_| "devkey".into()), + api_secret: std::env::var("LIVEKIT_API_SECRET").unwrap_or_else(|_| "secret".into()), + room: format!("session_test_{nanos}_{count}"), + } + } + + /// The grants of every token: joining the test's room, and setting + /// attributes. + pub fn grants(&self) -> VideoGrants { + VideoGrants { + room_join: true, + room: self.room.clone(), + can_update_own_metadata: Some(true), + ..Default::default() + } + } + + pub fn token( + &self, + identity: &str, + customize: impl FnOnce(AccessToken) -> AccessToken, + ) -> String { + let token = AccessToken::with_api_key(&self.api_key, &self.api_secret) + .with_ttl(Duration::from_secs(30 * 60)) + .with_grants(self.grants()) + .with_identity(identity); + customize(token).to_jwt().expect("Failed to sign token") + } + + /// Credentials for the session's user, optionally dispatching an agent. + pub fn user_source(&self, dispatch: bool) -> TokenSourceLiteral { + let token = self.token(USER, |token| { + if !dispatch { + return token; + } + token.with_room_config(livekit_protocol::RoomConfiguration { + agents: vec![livekit_protocol::RoomAgentDispatch { + agent_name: "test-agent".into(), + ..Default::default() + }], + ..Default::default() + }) + }); + literal(self.url.clone(), token) + } + + /// Credentials for a user who may join but not publish. The server + /// rejects such a user's microphone publish. + pub fn unpublishable_user_source(&self) -> TokenSourceLiteral { + let token = self.token(USER, |token| { + token.with_grants(VideoGrants { can_publish: Some(false), ..self.grants() }) + }); + literal(self.url.clone(), token) + } + + /// Joins a participant of kind agent reporting `state`. + pub async fn join_agent( + &self, + identity: &str, + state: &str, + ) -> Result<(Room, UnboundedReceiver)> { + let token = self.token(identity, |token| { + token + .with_kind("agent") + .with_attributes([(ATTRIBUTE_AGENT_STATE.to_owned(), state.to_owned())]) + }); + Ok(Room::connect(&self.url, &token, RoomOptions::default()).await?) + } + + /// Joins an avatar worker: a participant of kind agent publishing on + /// behalf of `agent`. + pub async fn join_avatar_worker( + &self, + identity: &str, + agent: &str, + ) -> Result<(Room, UnboundedReceiver)> { + let token = self.token(identity, |token| { + token + .with_kind("agent") + .with_attributes([(ATTRIBUTE_PUBLISH_ON_BEHALF.to_owned(), agent.to_owned())]) + }); + Ok(Room::connect(&self.url, &token, RoomOptions::default()).await?) + } + + pub async fn join_observer(&self) -> Result<(Room, UnboundedReceiver)> { + let token = self.token("observer", |token| token); + Ok(Room::connect(&self.url, &token, RoomOptions::default()).await?) + } +} + +pub async fn set_agent_state(agent: &Room, state: &str) -> Result<()> { + agent + .local_participant() + .set_attributes(HashMap::from([(ATTRIBUTE_AGENT_STATE.to_owned(), state.to_owned())])) + .await?; + Ok(()) +} + +pub async fn wait_for( + session: &Session, + what: &str, + predicate: impl FnMut(&SessionState) -> bool, +) -> Result { + let mut state = session.state(); + let reached = timeout(WAIT, state.wait_for(predicate)) + .await + .map_err(|_| anyhow!("timed out waiting for {what}; last {:?}", current(session)))??; + Ok(reached.clone()) +} + +/// What a test expects of the agent state, without the agent's tracks. +#[derive(Clone, Copy, Debug)] +pub enum Expect { + /// [`AgentState::Joined`] with the agent `AGENT` doing the activity. + Joined(AgentActivity), + /// [`AgentFailure::Timeout`], with or without an agent in the room. + TimedOut, + /// [`AgentFailure::Left`] by the agent `AGENT`. + Left, +} + +impl Expect { + pub fn matches(self, state: &AgentState) -> bool { + match (self, state) { + (Self::Joined(activity), AgentState::Joined(agent)) => { + agent.identity().as_str() == AGENT && agent.activity() == activity + } + (Self::TimedOut, AgentState::Failed(AgentFailure::Timeout { .. })) => true, + (Self::Left, AgentState::Failed(AgentFailure::Left { identity, .. })) => { + identity.as_str() == AGENT + } + _ => false, + } + } +} + +pub async fn wait_for_agent(session: &Session, expect: Expect) -> Result<()> { + wait_for(session, &format!("{expect:?}"), |s| expect.matches(&s.agent)).await?; + Ok(()) +} + +pub async fn eventually(what: &str, mut condition: impl FnMut() -> bool) -> Result<()> { + timeout(WAIT, async { + while !condition() { + sleep(Duration::from_millis(20)).await; + } + }) + .await + .map_err(|_| anyhow!("timed out waiting for {what}")) +} + +pub fn current(session: &Session) -> SessionState { + session.state().borrow().clone() +} + +/// Options for a session that gets credentials from `token_source` and stays +/// off the machine's audio devices. +pub fn text_options(token_source: TokenSourceLiteral) -> SessionOptions { + SessionOptions::new_fixed_source(token_source).with_platform_audio(false) +} + +/// The machine's audio devices, or `None` when it has no microphone to +/// publish, logging that the test is skipped. +pub fn microphone_probe() -> Option { + let Ok(probe) = PlatformAudio::new() else { + log::info!("skipping: this machine has no audio devices"); + return None; + }; + if probe.recording_devices().next().is_none() { + log::info!("skipping: this machine has no microphone"); + return None; + } + Some(probe) +} diff --git a/livekit-session/tests/session_test.rs b/livekit-session/tests/session_test.rs new file mode 100644 index 0000000000..a23dcfff7f --- /dev/null +++ b/livekit-session/tests/session_test.rs @@ -0,0 +1,388 @@ +// Copyright 2026 LiveKit, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! End-to-end tests of the public API against a running +//! `livekit-server --dev`, with a second room standing in for the agent. +//! The tests that assert on the crate's internals are in `src/e2e_tests.rs`. +//! +//! Environment variables (the same as `livekit`'s e2e suites): +//! - LIVEKIT_URL (default ws://localhost:7880) +//! - LIVEKIT_API_KEY (default "devkey") +//! - LIVEKIT_API_SECRET (default "secret") +//! +//! Run: +//! cargo test -p livekit-session --features __lk-e2e-test + +#![cfg(feature = "__lk-e2e-test")] + +use std::collections::HashMap; +use std::time::Duration; + +use anyhow::{anyhow, bail, Result}; +use futures_util::StreamExt; +use livekit::options::TrackPublishOptions; +use livekit::prelude::*; +use livekit::webrtc::audio_source::native::NativeAudioSource; +use livekit::webrtc::prelude::{AudioSourceOptions, RtcVideoSource, VideoResolution}; +use livekit::webrtc::video_source::native::NativeVideoSource; +use livekit::{SendTextOptions, StreamReader, StreamTextOptions, StreamWriter}; +use livekit_session::*; +use tokio::time::timeout; + +use common::*; + +mod common; + +// The topics and attributes of the agent's side of the protocol, spelled out +// so that the tests pin the wire names independently of the crate's own +// constants. +const TOPIC_CHAT: &str = "lk.chat"; +const TOPIC_TRANSCRIPTION: &str = "lk.transcription"; +const ATTRIBUTE_SEGMENT_ID: &str = "lk.segment_id"; +const ATTRIBUTE_TRANSCRIPTION_FINAL: &str = "lk.transcription_final"; + +#[tokio::test(flavor = "multi_thread")] +async fn start_publishes_the_microphone_and_end_releases_the_audio_devices() -> Result<()> { + // Shares the platform audio handle with the session, to observe the + // session's reference to it. + let Some(probe) = microphone_probe() else { + return Ok(()); + }; + let env = TestEnv::new(); + let session = Session::new(SessionOptions::new_fixed_source(env.user_source(false))); + + session.start().await?; + assert_eq!(probe.ref_count(), 2); + let room = session.room().ok_or_else(|| anyhow!("no room"))?; + let publications = room.local_participant().track_publications(); + assert!(publications.values().any(|p| p.source() == TrackSource::Microphone)); + drop(room); + + session.end().await; + assert_eq!(probe.ref_count(), 1); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread")] +async fn agent_leaving_is_reported_as_left() -> Result<()> { + let env = TestEnv::new(); + let session = Session::new(text_options(env.user_source(false))); + session.start().await?; + let (agent, _agent_events) = env.join_agent(AGENT, "listening").await?; + wait_for_agent(&session, Expect::Joined(AgentActivity::Listening)).await?; + + agent.close().await?; + wait_for_agent(&session, Expect::Left).await?; + session.end().await; + Ok(()) +} + +#[tokio::test(flavor = "multi_thread")] +async fn timeout_fires_without_an_agent_and_a_late_agent_recovers() -> Result<()> { + let env = TestEnv::new(); + let options = + text_options(env.user_source(true)).with_agent_connect_timeout(Duration::from_millis(500)); + let session = Session::new(options); + session.start().await?; + wait_for_agent(&session, Expect::TimedOut).await?; + + let (_agent, _agent_events) = env.join_agent(AGENT, "listening").await?; + wait_for_agent(&session, Expect::Joined(AgentActivity::Listening)).await?; + session.end().await; + Ok(()) +} + +#[tokio::test(flavor = "multi_thread")] +async fn timeout_is_armed_without_dispatch() -> Result<()> { + let env = TestEnv::new(); + let options = + text_options(env.user_source(false)).with_agent_connect_timeout(Duration::from_millis(500)); + // An agent registered without a name is dispatched automatically, so a + // token naming none still waits for one. + let session = Session::new(options); + session.start().await?; + wait_for_agent(&session, Expect::TimedOut).await?; + session.end().await; + Ok(()) +} + +#[tokio::test(flavor = "multi_thread")] +async fn timeout_fires_for_an_agent_stuck_initializing() -> Result<()> { + let env = TestEnv::new(); + let options = + text_options(env.user_source(true)).with_agent_connect_timeout(Duration::from_millis(500)); + // Joined first, so the agent is present before the timeout can fire. + let (agent, _agent_events) = env.join_agent(AGENT, "initializing").await?; + let session = Session::new(options); + session.start().await?; + wait_for_agent(&session, Expect::TimedOut).await?; + + set_agent_state(&agent, "listening").await?; + wait_for_agent(&session, Expect::Joined(AgentActivity::Listening)).await?; + session.end().await; + Ok(()) +} + +async fn next_message( + events: &mut SessionEventStream, + mut predicate: impl FnMut(&Message) -> bool, +) -> Result { + timeout(WAIT, async { + while let Some(event) = events.next().await { + if let SessionEvent::MessageUpserted(message) = event { + if predicate(&message) { + return Ok(message); + } + } + } + bail!("session events ended") + }) + .await? +} + +#[tokio::test(flavor = "multi_thread")] +async fn messages_merge_chat_and_transcripts() -> Result<()> { + let env = TestEnv::new(); + let session = Session::new(text_options(env.user_source(false))); + let mut events = session.subscribe(); + session.start().await?; + let (agent, mut agent_events) = env.join_agent(AGENT, "listening").await?; + wait_for_agent(&session, Expect::Joined(AgentActivity::Listening)).await?; + + // User input reaches the agent on lk.chat, under the id the feed uses. + let sent = session.send_text("hello agent").await?; + assert_eq!((sent.origin, sent.text.as_str()), (MessageOrigin::UserInput, "hello agent")); + let received = timeout(WAIT, async { + while let Some(event) = agent_events.recv().await { + if let RoomEvent::TextStreamOpened { reader, topic, .. } = event { + if topic == TOPIC_CHAT { + let reader = reader.take().ok_or_else(|| anyhow!("reader taken"))?; + let id = reader.info().id.clone(); + return Ok((id, reader.read_all().await?)); + } + } + } + bail!("agent events ended") + }) + .await??; + assert_eq!(received, (sent.id.clone(), "hello agent".to_owned())); + + // An agent transcript appends on one stream, finalized by the trailer. + let mut options = StreamTextOptions::new_with_topic(TOPIC_TRANSCRIPTION); + options.attributes = HashMap::from([ + (ATTRIBUTE_SEGMENT_ID.to_owned(), "seg-1".to_owned()), + (ATTRIBUTE_TRANSCRIPTION_FINAL.to_owned(), "false".to_owned()), + ]); + let writer = agent.local_participant().stream_text(options).await?; + writer.write("Hel").await?; + writer.write("lo").await?; + let partial = next_message(&mut events, |m| m.id == "seg-1" && m.text == "Hello").await?; + assert!(!partial.is_final); + writer + .close_with_options( + None, + Some(HashMap::from([(ATTRIBUTE_TRANSCRIPTION_FINAL.to_owned(), "true".to_owned())])), + ) + .await?; + let done = next_message(&mut events, |m| m.id == "seg-1" && m.is_final).await?; + assert_eq!(done.origin, MessageOrigin::AgentTranscript); + assert_eq!(done.text, "Hello"); + assert_eq!(done.seq, partial.seq); + assert_eq!(done.participant_identity.as_str(), AGENT); + + // Chat from the agent reaches the feed too. + agent + .local_participant() + .send_text("hello user", SendTextOptions::new_with_topic(TOPIC_CHAT)) + .await?; + let chat = next_message(&mut events, |m| m.origin == MessageOrigin::Chat).await?; + assert_eq!(chat.text, "hello user"); + + let feed: Vec<_> = session.messages().into_iter().map(|m| (m.origin, m.text)).collect(); + assert_eq!( + feed, + [ + (MessageOrigin::UserInput, "hello agent".to_owned()), + (MessageOrigin::AgentTranscript, "Hello".to_owned()), + (MessageOrigin::Chat, "hello user".to_owned()), + ] + ); + + // A failed send adds nothing. + session.end().await; + assert!(matches!(session.send_text("too late").await, Err(MessageSendError::NotConnected))); + assert_eq!(session.messages().len(), 3); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread")] +async fn streams_on_other_topics_are_left_to_the_app() -> Result<()> { + let env = TestEnv::new(); + let session = Session::new(text_options(env.user_source(false))); + session.start().await?; + let mut app_events = session.room().ok_or_else(|| anyhow!("no room"))?.subscribe(); + let (agent, _agent_events) = env.join_agent(AGENT, "listening").await?; + wait_for_agent(&session, Expect::Joined(AgentActivity::Listening)).await?; + + agent + .local_participant() + .send_text("for the app", SendTextOptions::new_with_topic("app.custom")) + .await?; + let text = timeout(WAIT, async { + while let Some(event) = app_events.recv().await { + if let RoomEvent::TextStreamOpened { reader, topic, .. } = event { + if topic == "app.custom" { + let reader = reader.take().ok_or_else(|| anyhow!("session took the reader"))?; + return Ok(reader.read_all().await?); + } + } + } + bail!("app events ended") + }) + .await??; + assert_eq!(text, "for the app"); + session.end().await; + Ok(()) +} + +// Agent media + +/// An avatar worker whose identity sorts before [`AGENT`], so that only its +/// publish-on-behalf attribute tells it apart from the agent. +const AVATAR: &str = "a-avatar"; + +/// Publishes a silent audio track from `room` as `source`. +async fn publish_audio(room: &Room, source: TrackSource) -> Result { + let rtc_source = NativeAudioSource::new(AudioSourceOptions::default(), 48_000, 1, 100); + let track = LocalAudioTrack::create_audio_track("audio", RtcAudioSource::Native(rtc_source)); + let options = TrackPublishOptions { source, ..Default::default() }; + Ok(room.local_participant().publish_track(LocalTrack::Audio(track), options).await?) +} + +/// Publishes a blank video track from `room` as `source`. +async fn publish_video(room: &Room, source: TrackSource) -> Result { + let rtc_source = NativeVideoSource::new(VideoResolution { width: 16, height: 16 }, false); + let track = LocalVideoTrack::create_video_track("video", RtcVideoSource::Native(rtc_source)); + let options = TrackPublishOptions { source, ..Default::default() }; + Ok(room.local_participant().publish_track(LocalTrack::Video(track), options).await?) +} + +/// Whether the session's room has subscribed to the remote track `sid`. +fn is_subscribed(session: &Session, sid: &TrackSid) -> bool { + let Some(room) = session.room() else { + return false; + }; + room.remote_participants() + .values() + .any(|p| p.track_publications().get(sid).is_some_and(|p| p.is_subscribed())) +} + +#[tokio::test(flavor = "multi_thread")] +async fn agent_audio_track_is_the_agents_microphone_once_subscribed() -> Result<()> { + let env = TestEnv::new(); + let session = Session::new(text_options(env.user_source(false))); + assert!(current(&session).agent.audio_track().is_none()); + session.start().await?; + let (agent, _agent_events) = env.join_agent(AGENT, "listening").await?; + wait_for_agent(&session, Expect::Joined(AgentActivity::Listening)).await?; + assert!(current(&session).agent.audio_track().is_none()); + + // Only the microphone is the agent's voice. + let other = publish_audio(&agent, TrackSource::ScreenshareAudio).await?; + eventually("the screen share audio to be subscribed", || is_subscribed(&session, &other.sid())) + .await?; + assert!(current(&session).agent.audio_track().is_none()); + + let microphone = publish_audio(&agent, TrackSource::Microphone).await?; + let state = + wait_for(&session, "the agent's audio track", |s| s.agent.audio_track().is_some()).await?; + assert_eq!(state.agent.audio_track().map(RemoteAudioTrack::sid), Some(microphone.sid())); + // The track comes with the agent it belongs to, and what that agent does. + assert_eq!(state.agent.identity().map(ParticipantIdentity::as_str), Some(AGENT)); + assert_eq!(state.agent.activity(), Some(AgentActivity::Listening)); + drop(state); + + agent.local_participant().unpublish_track(µphone.sid()).await?; + wait_for(&session, "the agent's audio track to go", |s| s.agent.audio_track().is_none()) + .await?; + + session.end().await; + assert_eq!(current(&session), SessionState::default()); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread")] +async fn agent_avatar_video_track_is_the_avatar_workers_camera_once_subscribed() -> Result<()> { + let env = TestEnv::new(); + let session = Session::new(text_options(env.user_source(false))); + session.start().await?; + let (agent, _agent_events) = env.join_agent(AGENT, "listening").await?; + wait_for_agent(&session, Expect::Joined(AgentActivity::Listening)).await?; + assert!(current(&session).agent.avatar_video_track().is_none()); + + // The agent's own camera is not an avatar. + let agent_camera = publish_video(&agent, TrackSource::Camera).await?; + eventually("the agent's camera to be subscribed", || { + is_subscribed(&session, &agent_camera.sid()) + }) + .await?; + assert!(current(&session).agent.avatar_video_track().is_none()); + + let (avatar, _avatar_events) = env.join_avatar_worker(AVATAR, AGENT).await?; + let camera = publish_video(&avatar, TrackSource::Camera).await?; + let state = + wait_for(&session, "the avatar's video track", |s| s.agent.avatar_video_track().is_some()) + .await?; + assert_eq!(state.agent.avatar_video_track().map(RemoteVideoTrack::sid), Some(camera.sid())); + assert!(state.agent.audio_track().is_none()); + drop(state); + + // The worker is of kind agent too, and reports no agent state. The state + // still follows the agent, so the worker was not taken for it. + set_agent_state(&agent, "speaking").await?; + wait_for_agent(&session, Expect::Joined(AgentActivity::Speaking)).await?; + + avatar.local_participant().unpublish_track(&camera.sid()).await?; + wait_for(&session, "the avatar's video track to go", |s| { + s.agent.avatar_video_track().is_none() + }) + .await?; + + session.end().await; + assert_eq!(current(&session), SessionState::default()); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread")] +async fn timed_out_agent_keeps_its_audio_track() -> Result<()> { + let env = TestEnv::new(); + let options = + text_options(env.user_source(true)).with_agent_connect_timeout(Duration::from_millis(500)); + // An agent that never reports a state is idle, so it times out while it + // is in the room and publishing. + let (agent, _agent_events) = env.join_agent(AGENT, "idle").await?; + let session = Session::new(options); + session.start().await?; + wait_for_agent(&session, Expect::TimedOut).await?; + + let microphone = publish_audio(&agent, TrackSource::Microphone).await?; + let state = + wait_for(&session, "the agent's audio track", |s| s.agent.audio_track().is_some()).await?; + assert!(Expect::TimedOut.matches(&state.agent)); + assert_eq!(state.agent.audio_track().map(RemoteAudioTrack::sid), Some(microphone.sid())); + drop(state); + + session.end().await; + Ok(()) +} diff --git a/verwalter.toml b/verwalter.toml index e311d7225d..fe6d4bba42 100644 --- a/verwalter.toml +++ b/verwalter.toml @@ -15,6 +15,7 @@ members = [ "livekit-protocol", "livekit-region", "livekit-rpc", + "livekit-session", "livekit-signaling", "livekit-telemetry", "livekit-token",