From bd7863d156d70d96c8289838a801a7a2aa980e8a Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:03:40 +0100 Subject: [PATCH 01/61] feat(session): add the livekit-session crate manifest and module layout This commit adds the manifest of the new `livekit-session` crate and its root module. The manifest declares the crate metadata, the features, and the dependencies. Each TLS feature forwards to `livekit` and to `livekit-token-source`. The two crates then use the same TLS backend. The `__lk-e2e-test` feature enables the end-to-end tests. These tests need a running `livekit-server --dev`. The feature-combinations table uses the curated mode. The comment above the table gives the reason. The root module declares the submodules and re-exports the public types. The submodules follow in the next commits. --- livekit-session/Cargo.toml | 63 ++++++++++++++++++++++++++++++++++++++ livekit-session/src/lib.rs | 33 ++++++++++++++++++++ 2 files changed, 96 insertions(+) create mode 100644 livekit-session/Cargo.toml create mode 100644 livekit-session/src/lib.rs diff --git a/livekit-session/Cargo.toml b/livekit-session/Cargo.toml new file mode 100644 index 0000000000..91ff4dc3c9 --- /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.1.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] +chrono = { workspace = true } +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"] } + +[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/src/lib.rs b/livekit-session/src/lib.rs new file mode 100644 index 0000000000..e80a7ab218 --- /dev/null +++ b/livekit-session/src/lib.rs @@ -0,0 +1,33 @@ +// 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 dispatcher; +mod error; +mod messages; +mod session; + +pub use agent::{AgentFailure, AgentState}; +pub use error::{MessageSendError, SessionStartError}; +pub use messages::{Message, MessageOrigin}; +pub use session::{Session, SessionConnectionState, SessionEvent, SessionOptions, SessionState}; From 39460bf04a593851f92bc699e741a39d46eb8c27 Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:03:40 +0100 Subject: [PATCH 02/61] chore(workspace): register livekit-session with cargo, knope and CODEOWNERS This commit registers the new crate in the workspace. The root `Cargo.toml` adds the crate as a workspace member and as a workspace dependency at version 0.1.0. `Cargo.lock` adds the lock entry of the crate. `knope.toml` adds the release package, so knope can bump the version and write the changelog. `CODEOWNERS` assigns the crate to its owner. `AGENTS.md` adds the crate to the list of curated crates in the feature-combinations section. --- .github/CODEOWNERS | 1 + AGENTS.md | 4 ++-- Cargo.lock | 18 ++++++++++++++++++ Cargo.toml | 2 ++ livekit-protocol/protocol | 2 +- 5 files changed, 24 insertions(+), 3 deletions(-) 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..331dddd9dd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3994,6 +3994,24 @@ dependencies = [ "uuid", ] +[[package]] +name = "livekit-session" +version = "0.1.0" +dependencies = [ + "anyhow", + "async-trait", + "chrono", + "futures-util", + "livekit", + "livekit-api", + "livekit-protocol", + "livekit-token", + "livekit-token-source", + "log", + "thiserror 2.0.19", + "tokio", +] + [[package]] name = "livekit-signaling" version = "0.4.0" diff --git a/Cargo.toml b/Cargo.toml index 376a64f9d7..c776107285 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", @@ -62,6 +63,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.1.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/livekit-protocol/protocol b/livekit-protocol/protocol index d234edab32..c6a16489d6 160000 --- a/livekit-protocol/protocol +++ b/livekit-protocol/protocol @@ -1 +1 @@ -Subproject commit d234edab32b0a9bdad57a7ec93d41bb2db33f1fe +Subproject commit c6a16489d6aa4e3fc310487f007b9997237ef0a0 From e76258c276f212e74eae91bf9b6edd776bab3ee7 Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:03:41 +0100 Subject: [PATCH 03/61] IMPORTANT(session): add the agent interop constants This commit adds the constants that the session shares with `livekit-agents`. The constants are the text-stream topics for chat and transcription, the participant attributes for the agent state and the avatar worker, the text-stream attributes of a transcript segment, and the default agent-connect timeout. These strings are the contract between the session and the agent. A wrong string breaks the session without an error. Compare each value with the `livekit-agents` source before you approve this commit. --- livekit-session/src/constants.rs | 43 ++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 livekit-session/src/constants.rs diff --git a/livekit-session/src/constants.rs b/livekit-session/src/constants.rs new file mode 100644 index 0000000000..61b2391d2b --- /dev/null +++ b/livekit-session/src/constants.rs @@ -0,0 +1,43 @@ +// 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); From 7bd04d9d151d3965206369468851de232bedff0b Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:03:41 +0100 Subject: [PATCH 04/61] feat(session): add the start and send error types This commit adds the two error enums of the crate. `SessionStartError` tells why `Session::start` failed. The variants cover an already started session, a cancelled start, a failed token fetch, a failed room connect, a failed platform-audio start, and a failed microphone publish. `MessageSendError` tells why `Session::send_text` failed. The variants cover a session without a room and a failed text stream. Both enums are `non_exhaustive`, so later changes can add variants without a breaking change. --- livekit-session/src/error.rs | 55 ++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 livekit-session/src/error.rs diff --git a/livekit-session/src/error.rs b/livekit-session/src/error.rs new file mode 100644 index 0000000000..a5b16727ad --- /dev/null +++ b/livekit-session/src/error.rs @@ -0,0 +1,55 @@ +// 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(#[from] RoomError), + /// Platform audio could not be started, e.g. on a machine without audio + /// devices. See [`SessionOptions::platform_audio`](crate::SessionOptions::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), +} From 01eac793c779ba022b9b7087238b280386b62363 Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:03:41 +0100 Subject: [PATCH 05/61] feat(session): add the Message model and the MessageStore feed This commit adds the public `Message` and `MessageOrigin` types, and the private `MessageUpdate` and `MessageStore`. A `Message` is one entry of the feed. Its `id` and its `participant_identity` together identify it. Its `seq` gives the position in the feed. A `MessageUpdate` is a message as a source reports it, before the store assigns a `seq`. The `MessageStore` keeps the messages in receive order. `upsert` adds a new message or updates an existing message in place. The updated message keeps its `seq`. `restore` replaces the feed and numbers the messages from zero. --- livekit-session/src/messages.rs | 132 ++++++++++++++++++++++++++++++++ 1 file changed, 132 insertions(+) create mode 100644 livekit-session/src/messages.rs diff --git a/livekit-session/src/messages.rs b/livekit-session/src/messages.rs new file mode 100644 index 0000000000..2bb72e1a2d --- /dev/null +++ b/livekit-session/src/messages.rs @@ -0,0 +1,132 @@ +// 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 chrono::{DateTime, Utc}; +use livekit::prelude::ParticipantIdentity; + +/// 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)] +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: DateTime, + /// 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, +} + +/// 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: DateTime, + pub origin: MessageOrigin, + pub participant_identity: ParticipantIdentity, + pub text: String, + pub is_final: bool, +} + +/// 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 + } + + /// Replaces the feed with `messages`, numbered from zero in the order + /// given. Of messages sharing an id and participant, the last wins. + pub(crate) fn restore(&mut self, messages: &[Message]) { + *self = Self::default(); + for message in messages { + self.upsert(MessageUpdate { + id: message.id.clone(), + timestamp: message.timestamp, + origin: message.origin, + participant_identity: message.participant_identity.clone(), + text: message.text.clone(), + is_final: message.is_final, + }); + } + } +} From 1e79ba60505ab07a7a420cf17d86ab1c212f0db9 Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:03:41 +0100 Subject: [PATCH 06/61] test(session): cover MessageStore ordering, upsert and restore This commit adds the unit tests of `MessageStore`. The tests show that an update keeps the `seq` of the message, that the feed uses the receive order and not the sender timestamp, and that `restore` keeps the given order and numbers the messages again from zero. --- livekit-session/src/messages.rs | 55 +++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/livekit-session/src/messages.rs b/livekit-session/src/messages.rs index 2bb72e1a2d..9891f95cef 100644 --- a/livekit-session/src/messages.rs +++ b/livekit-session/src/messages.rs @@ -130,3 +130,58 @@ impl MessageStore { } } } + +#[cfg(test)] +mod tests { + use super::*; + + use chrono::TimeZone; + + fn at(seconds: i64) -> DateTime { + Utc.timestamp_opt(1_800_000_000 + seconds, 0).unwrap() + } + + fn update(id: &str, seconds: i64, 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(); + store.upsert(update("stale", 0, "dropped by restore")); + + // 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; + + store.restore(&[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); + } +} From 94e8c2d8b27dbc041a9f503723f8389803f4bbe3 Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:03:41 +0100 Subject: [PATCH 07/61] IMPORTANT(session): aggregate lk.transcription streams into transcript messages This commit adds `TranscriptStream`, `parse_final` and `TranscriptAggregator`. Agents send transcripts in two shapes on the `lk.transcription` topic. Agent speech is one stream. Each chunk appends to the text, and the trailer of the stream finalizes the segment. User speech is a new stream for each interim result. Each stream carries the full text, and the last stream is marked final. The aggregator handles both shapes with one rule. A chunk appends when it arrives on the stream that last wrote the segment. A chunk replaces the text when it arrives on a new stream. A segment is keyed by the segment id and the participant. A new segment from a participant drops the older partial segments of that participant. `on_stream_end` finalizes a segment, unless the stream is marked not final or a newer stream took the segment over. Review this logic with care. It decides what text the user sees and when a transcript is complete. --- livekit-session/src/messages.rs | 143 ++++++++++++++++++++++++++++++++ 1 file changed, 143 insertions(+) diff --git a/livekit-session/src/messages.rs b/livekit-session/src/messages.rs index 9891f95cef..086878ae21 100644 --- a/livekit-session/src/messages.rs +++ b/livekit-session/src/messages.rs @@ -17,6 +17,8 @@ use std::collections::HashMap; use chrono::{DateTime, Utc}; 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. /// @@ -69,6 +71,147 @@ pub(crate) struct MessageUpdate { 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: DateTime, + 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: DateTime, + /// 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)] From 96d387d320a8c232cd82697ad4ae796c82c93828 Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:03:42 +0100 Subject: [PATCH 08/61] test(session): cover transcript aggregation This commit adds the unit tests of `TranscriptAggregator` and `parse_final`. The tests cover appending on one stream, replacing on a new stream, the segment id fallback, the parsing of the final attribute, finalization without the attribute, a superseded stream, empty chunks, the same segment from two participants, and the drop of older partials. --- livekit-session/src/messages.rs | 142 ++++++++++++++++++++++++++++++++ 1 file changed, 142 insertions(+) diff --git a/livekit-session/src/messages.rs b/livekit-session/src/messages.rs index 086878ae21..b87503a307 100644 --- a/livekit-session/src/messages.rs +++ b/livekit-session/src/messages.rs @@ -284,6 +284,148 @@ mod tests { Utc.timestamp_opt(1_800_000_000 + seconds, 0).unwrap() } + fn stream(id: &str, participant: &str, seconds: i64) -> 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: i64, text: &str) -> MessageUpdate { MessageUpdate { id: id.into(), From 5637b84f63ee9349b6a9bfe183f67c2731ffcffd Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:03:42 +0100 Subject: [PATCH 09/61] feat(session): add AgentState and AgentFailure This commit adds the public `AgentState` and `AgentFailure` enums. `AgentState` tells what the agent is doing, as the session projects it from the room. The predicates `is_connected`, `is_pending` and `is_finished` group the states for most callers. `from_attribute` parses the `lk.agent.state` attribute. A missing attribute means `Idle`. An unknown value means `Unknown`. `AgentFailure` gives the reason of a `Failed` state: a timeout, or an agent that left. --- livekit-session/src/agent.rs | 105 +++++++++++++++++++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 livekit-session/src/agent.rs diff --git a/livekit-session/src/agent.rs b/livekit-session/src/agent.rs new file mode 100644 index 0000000000..001c3e43cf --- /dev/null +++ b/livekit-session/src/agent.rs @@ -0,0 +1,105 @@ +// 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; + +/// What the session's agent is doing, projected from the room. +/// +/// Most code needs only the predicates: [`AgentState::is_connected`] to show +/// that the agent is there, [`AgentState::is_pending`] to show that it is on +/// its way, and [`AgentState::is_finished`] to show that it is gone or never +/// came. +#[derive(Clone, Copy, 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, + /// 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 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), + /// The agent reports an activity this SDK does not recognize. + Unknown, +} + +impl AgentState { + /// Whether the agent is in the room and in a conversation: listening, + /// thinking or speaking. + /// + /// Stricter than "an agent participant exists": an agent that is still + /// [`Initializing`](Self::Initializing) is not connected. + pub fn is_connected(self) -> bool { + matches!(self, Self::Listening | Self::Thinking | Self::Speaking) + } + + /// Whether an agent is expected but not yet conversational: connecting, + /// initializing, or idle. + pub fn is_pending(self) -> bool { + matches!(self, Self::Connecting | Self::Initializing | Self::Idle) + } + + /// 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(_)) + } + + /// 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, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum AgentFailure { + /// No agent became conversational within + /// [`SessionOptions::agent_connect_timeout`](crate::SessionOptions::agent_connect_timeout). + Timeout, + /// The agent left the room while the session stayed connected. + Left, +} From 662c23846d6a46fef4a882f62eea936ca08912fd Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:03:42 +0100 Subject: [PATCH 10/61] feat(session): find the agent, its avatar worker and their tracks This commit adds the `AgentCandidate` trait and the lookup functions of the agent module. `AgentCandidate` abstracts a remote participant, so the unit tests can use fake participants. `find_agent` returns the participant of kind agent that does not publish on behalf of another participant. With several agents, the lowest identity wins. `find_avatar_worker` returns the participant that publishes on behalf of the agent. `agent_audio_track` and `agent_avatar_video_track` return the agent's microphone track and the avatar worker's camera track, once subscribed. `activity` reads the agent's state attribute. --- livekit-session/src/agent.rs | 82 ++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/livekit-session/src/agent.rs b/livekit-session/src/agent.rs index 001c3e43cf..b59ac31125 100644 --- a/livekit-session/src/agent.rs +++ b/livekit-session/src/agent.rs @@ -103,3 +103,85 @@ pub enum AgentFailure { /// The agent left the room while the session stayed connected. Left, } + +/// 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; +} + +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) + } +} + +/// 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. +pub(crate) 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`. +pub(crate) 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()) + }) +} + +/// The agent's microphone track, once subscribed. +pub(crate) fn agent_audio_track<'a>( + participants: impl IntoIterator, +) -> Option { + let agent = find_agent(participants)?; + agent.track_publications().into_values().find_map(|publication| { + match (publication.source(), publication.track()) { + (TrackSource::Microphone, Some(RemoteTrack::Audio(track))) => Some(track), + _ => None, + } + }) +} + +/// The camera track of the agent's avatar worker, once subscribed. +pub(crate) fn agent_avatar_video_track<'a>( + participants: impl IntoIterator + Clone, +) -> Option { + let agent = find_agent(participants.clone())?; + let worker = find_avatar_worker(participants, &agent.identity())?; + worker.track_publications().into_values().find_map(|publication| { + match (publication.source(), publication.track()) { + (TrackSource::Camera, Some(RemoteTrack::Video(track))) => Some(track), + _ => None, + } + }) +} + +/// The activity the agent reports through `lk.agent.state`. +fn activity(agent: &impl AgentCandidate) -> AgentState { + AgentState::from_attribute(agent.attributes().get(ATTRIBUTE_AGENT_STATE).map(String::as_str)) +} From 94c3a3b5ad4425f13f6d1ed833b72fe1f0cc2163 Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:03:42 +0100 Subject: [PATCH 11/61] IMPORTANT(session): project AgentState with timeout and leave detection This commit adds `AgentTracker`. The tracker projects the `AgentState` from the connection state and the remote participants. It keeps two facts across calls: whether an agent was ever seen, and whether the agent-connect timeout fired. Without an agent, the projection is `Failed(Left)` when an agent was seen before and the room is connected. A full reconnect removes every participant, so a missing agent while reconnecting is not `Left`. `time_out` records that the agent-connect timeout fired. The timeout holds only for the agent present at that time. An agent that joins later reports its own activity. A `Failed` state is not final. An agent that becomes conversational replaces it. Review the state transitions with care. The UI shows them to the user. --- livekit-session/src/agent.rs | 77 ++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) diff --git a/livekit-session/src/agent.rs b/livekit-session/src/agent.rs index b59ac31125..ae3a6cb4e8 100644 --- a/livekit-session/src/agent.rs +++ b/livekit-session/src/agent.rs @@ -185,3 +185,80 @@ pub(crate) fn agent_avatar_video_track<'a>( fn activity(agent: &impl AgentCandidate) -> AgentState { AgentState::from_attribute(agent.attributes().get(ATTRIBUTE_AGENT_STATE).map(String::as_str)) } + +/// Projects [`AgentState`] from the room, remembering what the projection +/// needs across calls: whether an agent was ever seen, and whether the +/// agent-connect timeout fired. +#[derive(Debug, Default)] +pub(crate) struct AgentTracker { + has_ever_connected: bool, + /// 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 remote + /// participants. + pub(crate) fn project<'a, P: AgentCandidate + 'a>( + &mut self, + connection: SessionConnectionState, + participants: impl IntoIterator, + ) -> AgentState { + match connection { + SessionConnectionState::Disconnected => { + *self = Self::default(); + return AgentState::Disconnected; + } + SessionConnectionState::Connecting => return AgentState::Connecting, + SessionConnectionState::Connected | SessionConnectionState::Reconnecting => {} + } + + let Some(agent) = find_agent(participants) else { + // A full reconnect removes every participant, so an agent missing + // while reconnecting has not necessarily left. + if self.has_ever_connected && connection == SessionConnectionState::Connected { + return AgentState::Failed(AgentFailure::Left); + } + if self.timed_out == Some(None) { + return AgentState::Failed(AgentFailure::Timeout); + } + return AgentState::Connecting; + }; + + self.has_ever_connected = true; + let identity = agent.identity(); + let activity = activity(agent); + if activity.is_connected() { + self.timed_out = None; + return activity; + } + // 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 == identity => { + AgentState::Failed(AgentFailure::Timeout) + } + _ => activity, + } + } + + /// 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<'a, P: AgentCandidate + 'a>( + &mut self, + connection: SessionConnectionState, + participants: impl IntoIterator, + ) -> bool { + if !connection.is_connected() { + return false; + } + let agent = find_agent(participants); + if agent.is_some_and(|agent| activity(agent).is_connected()) { + return false; + } + self.timed_out = Some(agent.map(|agent| agent.identity())); + true + } +} From 925a049f2797c02540a7d71abb6543237ad1fd42 Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:03:42 +0100 Subject: [PATCH 12/61] test(session): cover agent discovery and state parsing This commit adds the test fixtures of the agent module and the first unit tests. `Fake` is a test participant that implements `AgentCandidate`. The tests cover the mapping of attribute values to states, the missing and the unknown attribute, the avatar worker, several agents, and the predicates of every state. --- livekit-session/src/agent.rs | 129 +++++++++++++++++++++++++++++++++++ 1 file changed, 129 insertions(+) diff --git a/livekit-session/src/agent.rs b/livekit-session/src/agent.rs index ae3a6cb4e8..8876d48b91 100644 --- a/livekit-session/src/agent.rs +++ b/livekit-session/src/agent.rs @@ -262,3 +262,132 @@ impl AgentTracker { true } } + +#[cfg(test)] +mod tests { + use super::*; + + 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 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 { + tracker.project(Connected, participants) + } + + #[test] + fn attribute_values_map_to_states() { + let mut tracker = AgentTracker::default(); + for (value, state) in [ + ("initializing", AgentState::Initializing), + ("idle", AgentState::Idle), + ("listening", AgentState::Listening), + ("thinking", AgentState::Thinking), + ("speaking", AgentState::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)]), AgentState::Idle); + assert_eq!( + project(&mut tracker, &[Fake::agent("agent", Some("dancing"))]), + AgentState::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 predicates_match_for_every_state() { + use AgentState::*; + let states = [ + Disconnected, + Connecting, + Initializing, + Idle, + Listening, + Thinking, + Speaking, + Failed(AgentFailure::Timeout), + Failed(AgentFailure::Left), + Unknown, + ]; + for state in states { + assert_eq!( + state.is_connected(), + matches!(state, Listening | Thinking | Speaking), + "{state:?}" + ); + assert_eq!( + state.is_pending(), + matches!(state, Connecting | Initializing | Idle), + "{state:?}" + ); + assert_eq!(state.is_finished(), matches!(state, Disconnected | Failed(_)), "{state:?}"); + } + assert!(!Initializing.is_connected()); + } +} From a3d4c13a1997f8e8f68adcefbbf77b5ee564857f Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:03:43 +0100 Subject: [PATCH 13/61] test(session): cover agent projection across reconnects, leaves and timeouts This commit adds the unit tests of `AgentTracker`. The tests cover the precedence of the connection state, an agent that leaves, an agent missing during a reconnect, a recovery after `Left`, the reset after a disconnect, and the agent-connect timeout with and without an agent. --- livekit-session/src/agent.rs | 82 ++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/livekit-session/src/agent.rs b/livekit-session/src/agent.rs index 8876d48b91..eb1335a3a3 100644 --- a/livekit-session/src/agent.rs +++ b/livekit-session/src/agent.rs @@ -360,6 +360,88 @@ mod tests { 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!(tracker.project(Disconnected, &participants), AgentState::Disconnected); + assert_eq!(tracker.project(Connecting, &participants), AgentState::Connecting); + assert_eq!(tracker.project(Reconnecting, &participants), AgentState::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), AgentState::Failed(AgentFailure::Left)); + } + + #[test] + fn agent_missing_while_reconnecting_is_not_left() { + let mut tracker = AgentTracker::default(); + project(&mut tracker, &[Fake::agent("agent", Some("listening"))]); + assert_eq!(tracker.project(Reconnecting, NO_ONE), AgentState::Connecting); + assert_eq!( + tracker.project(Reconnecting, &[Fake::agent("agent", Some("listening"))]), + AgentState::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), AgentState::Failed(AgentFailure::Left)); + assert_eq!( + project(&mut tracker, &[Fake::agent("agent-2", Some("initializing"))]), + AgentState::Initializing + ); + } + + #[test] + fn disconnect_resets_has_ever_connected() { + let mut tracker = AgentTracker::default(); + project(&mut tracker, &[Fake::agent("agent", Some("listening"))]); + tracker.project(Disconnected, NO_ONE); + assert_eq!(tracker.project(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!(tracker.time_out(Connected, NO_ONE)); + assert_eq!(project(&mut tracker, NO_ONE), AgentState::Failed(AgentFailure::Timeout)); + assert_eq!( + project(&mut tracker, &[Fake::agent("agent", Some("initializing"))]), + AgentState::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!(tracker.time_out(Connected, &stuck)); + assert_eq!(project(&mut tracker, &stuck), AgentState::Failed(AgentFailure::Timeout)); + assert_eq!( + project(&mut tracker, &[Fake::agent("agent", Some("listening"))]), + AgentState::Listening + ); + // Recovered for good: falling back to idle is not a timeout. + assert_eq!(project(&mut tracker, &[Fake::agent("agent", Some("idle"))]), AgentState::Idle); + } + + #[test] + fn timeout_does_not_count_once_conversational_or_disconnected() { + let mut tracker = AgentTracker::default(); + assert!(!tracker.time_out(Connected, &[Fake::agent("agent", Some("speaking"))])); + assert!(!tracker.time_out(Connecting, NO_ONE)); + assert!(!tracker.time_out(Disconnected, NO_ONE)); + assert_eq!(project(&mut tracker, NO_ONE), AgentState::Connecting); + } + #[test] fn predicates_match_for_every_state() { use AgentState::*; From 1cbb509e79c5c2dfec8577909a25dbf15ad8b8b6 Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:03:43 +0100 Subject: [PATCH 14/61] feat(session): add the Dispatcher fan-out This commit adds `Dispatcher`. A `Dispatcher` sends each value to every subscriber. Each subscriber has its own unbounded channel. The dispatcher removes a subscriber on the next dispatch after its receiver is dropped. The `livekit` crate has the same type, but keeps it private. --- livekit-session/src/dispatcher.rs | 46 +++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 livekit-session/src/dispatcher.rs diff --git a/livekit-session/src/dispatcher.rs b/livekit-session/src/dispatcher.rs new file mode 100644 index 0000000000..8014286894 --- /dev/null +++ b/livekit-session/src/dispatcher.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. + +use std::sync::Mutex; + +use tokio::sync::mpsc; + +use crate::actor::lock; + +/// Fans values out to any number of subscribers, each on its own unbounded +/// channel. A subscriber whose receiver is dropped is removed on the next +/// dispatch. +/// +/// `livekit` has the same type, but keeps it private. +pub(crate) struct Dispatcher { + senders: Mutex>>, +} + +impl Default for Dispatcher { + fn default() -> Self { + Self { senders: Mutex::default() } + } +} + +impl Dispatcher { + pub(crate) fn register(&self) -> mpsc::UnboundedReceiver { + let (tx, rx) = mpsc::unbounded_channel(); + lock(&self.senders).push(tx); + rx + } + + pub(crate) fn dispatch(&self, value: &T) { + lock(&self.senders).retain(|sender| sender.send(value.clone()).is_ok()); + } +} From b3449818ad17cb962f25550421c52adc38229662 Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:03:44 +0100 Subject: [PATCH 15/61] test(session): cover Dispatcher pruning This commit adds the unit test of `Dispatcher` and the `len` helper it uses. The test shows that a dropped receiver is removed on the next dispatch, and not on drop. --- livekit-session/src/dispatcher.rs | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/livekit-session/src/dispatcher.rs b/livekit-session/src/dispatcher.rs index 8014286894..761269ca34 100644 --- a/livekit-session/src/dispatcher.rs +++ b/livekit-session/src/dispatcher.rs @@ -43,4 +43,28 @@ impl Dispatcher { pub(crate) fn dispatch(&self, value: &T) { lock(&self.senders).retain(|sender| sender.send(value.clone()).is_ok()); } + + #[cfg(test)] + pub(crate) fn len(&self) -> usize { + lock(&self.senders).len() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn dropped_receiver_is_pruned_on_the_next_dispatch() { + let dispatcher = Dispatcher::default(); + let mut kept = dispatcher.register(); + let dropped = dispatcher.register(); + assert_eq!(dispatcher.len(), 2); + + drop(dropped); + assert_eq!(dispatcher.len(), 2, "pruning happens on dispatch, not on drop"); + dispatcher.dispatch(&1); + assert_eq!(dispatcher.len(), 1); + assert_eq!(kept.try_recv(), Ok(1)); + } } From 673f061550c47a6f8e45f38d9f4788c83144d546 Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:03:46 +0100 Subject: [PATCH 16/61] feat(session): add the state shared between a session and its actor This commit adds `Shared` and the `lock` helper. `Shared` holds the session state, the message store and the event dispatcher. A `Session` and its actor both hold an `Arc`. `Shared` holds no reference back to either, so it keeps neither alive. Each `start` begins a new generation. `publish` writes a state only when its generation is current. An actor of an earlier start that is still shutting down cannot overwrite the state of a newer start. `upsert` dispatches the message event under the store lock. Subscribers see updates in the order the store applied them. The `history` field exists only in tests. It records every published state, so tests can assert on states a `watch` receiver would skip. `lock` locks a mutex and recovers from poisoning. --- livekit-session/src/actor.rs | 132 +++++++++++++++++++++++++++++++++++ 1 file changed, 132 insertions(+) create mode 100644 livekit-session/src/actor.rs diff --git a/livekit-session/src/actor.rs b/livekit-session/src/actor.rs new file mode 100644 index 0000000000..99fa3c8fe7 --- /dev/null +++ b/livekit-session/src/actor.rs @@ -0,0 +1,132 @@ +// 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::prelude::*; +use livekit::{ + ConnectionState, DisconnectReason, StreamReader, StreamResult, TakeCell, TextStreamInfo, + TextStreamReader, +}; +use tokio::sync::{mpsc, watch}; +use tokio::time::Sleep; + +use crate::agent::AgentTracker; +use crate::constants::{TOPIC_CHAT, TOPIC_TRANSCRIPTION}; +use crate::dispatcher::Dispatcher; +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: Dispatcher, + /// Every state published, so tests can assert on states a `watch` + /// receiver would skip. + #[cfg(test)] + pub(crate) history: Mutex>, +} + +impl Shared { + pub(crate) fn new() -> Self { + Self { + generation: Mutex::new(0), + state: watch::Sender::new(SessionState::default()), + messages: Mutex::default(), + events: Dispatcher::default(), + #[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) { + self.state.send_if_modified(|current| { + if *current == state { + return false; + } + *current = state; + true + }); + #[cfg(test)] + lock(&self.history).push(state); + } + + pub(crate) fn watch(&self) -> watch::Receiver { + self.state.subscribe() + } + + pub(crate) fn subscribe(&self) -> mpsc::UnboundedReceiver { + self.events.register() + } + + /// 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); + self.events.dispatch(&SessionEvent::MessageUpserted(message.clone())); + message + } + + pub(crate) fn restore(&self, restored: &[Message]) { + let mut messages = lock(&self.messages); + messages.restore(restored); + self.events.dispatch(&SessionEvent::MessagesRestored); + } + + pub(crate) fn messages(&self) -> Vec { + lock(&self.messages).messages().to_vec() + } + + #[cfg(all(test, feature = "__lk-e2e-test"))] + pub(crate) fn subscriber_count(&self) -> usize { + self.events.len() + } +} + +/// 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) +} From 821e40502ba960c418359d0112aef9933e73fbd0 Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:03:46 +0100 Subject: [PATCH 17/61] feat(session): add SessionOptions, SessionState and SessionEvent This commit adds the public option, state and event types of the session. `SessionOptions` holds the agent-connect timeout, the room options, and the `platform_audio` flag. The flag defaults to `true`. The builder methods set each field. `SessionConnectionState` and `SessionState` describe the session at one point in time. `SessionEvent` reports a change to the message feed. All four types are `non_exhaustive`. --- livekit-session/src/session.rs | 141 +++++++++++++++++++++++++++++++++ 1 file changed, 141 insertions(+) create mode 100644 livekit-session/src/session.rs diff --git a/livekit-session/src/session.rs b/livekit-session/src/session.rs new file mode 100644 index 0000000000..41af29a1fa --- /dev/null +++ b/livekit-session/src/session.rs @@ -0,0 +1,141 @@ +// 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::mem; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use livekit::options::TrackPublishOptions; +use livekit::prelude::*; +use livekit::SendTextOptions; +use livekit_token_source::{ + TokenSourceConfigurable, TokenSourceFetchOptions, TokenSourceFixed, TokenSourceResponse, + TokenSourceResult, +}; +use tokio::sync::{mpsc, oneshot, watch}; +use tokio::task::JoinHandle; + +use crate::actor::{lock, Connection, SessionActor, Shared}; +use crate::agent::{self, AgentState}; +use crate::constants::{DEFAULT_AGENT_CONNECT_TIMEOUT, TOPIC_CHAT}; +use crate::error::{MessageSendError, SessionStartError}; +use crate::messages::{Message, MessageOrigin, MessageUpdate}; + +/// Options for a [`Session`]. +#[derive(Clone, Debug)] +#[non_exhaustive] +pub struct SessionOptions { + /// 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 agent_connect_timeout: Duration, + /// Options for the session's room, including + /// [`encryption`](RoomOptions::encryption), which can be toggled once + /// connected through [`Session::room`]. + pub room_options: RoomOptions, + /// 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 platform_audio: bool, +} + +impl Default for SessionOptions { + fn default() -> Self { + Self { + agent_connect_timeout: DEFAULT_AGENT_CONNECT_TIMEOUT, + room_options: RoomOptions::default(), + platform_audio: true, + } + } +} + +impl SessionOptions { + /// Sets [`agent_connect_timeout`](Self::agent_connect_timeout). + pub fn with_agent_connect_timeout(mut self, timeout: Duration) -> Self { + self.agent_connect_timeout = timeout; + self + } + + /// Sets [`room_options`](Self::room_options). + pub fn with_room_options(mut self, room_options: RoomOptions) -> Self { + self.room_options = room_options; + self + } + + /// Sets [`platform_audio`](Self::platform_audio). + pub fn with_platform_audio(mut self, platform_audio: bool) -> Self { + self.platform_audio = platform_audio; + 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, +} + +/// 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. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub struct SessionState { + /// The state of the session's connection. + pub connection: SessionConnectionState, + /// What the agent is doing. + pub agent: AgentState, +} + +impl Default for SessionState { + fn default() -> Self { + Self { connection: SessionConnectionState::Disconnected, agent: AgentState::Disconnected } + } +} From 3e80c940ea10e58e199d3cff6d9286264938b59c Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:03:46 +0100 Subject: [PATCH 18/61] feat(session): add the Session handle and its constructors This commit adds the `Session` handle and the private types behind it. `SessionTokenSource` wraps a fixed or a configurable token source. The constructor that the caller uses selects the variant. `Session` is a cheap handle around `Inner`. `Inner` holds the token source, the options, the shared state and the `Lifecycle`. `Lifecycle` is `Idle`, `Starting` or `Running`. `Running` holds the room, the stop sender and the actor task. `join` drops the stop sender and waits for the actor. `Session::new` takes a fixed source. `Session::with_fetch_options` takes a configurable source and fetch options. `Session::with_agent` is a shorthand that sets the agent name. --- livekit-session/src/session.rs | 155 +++++++++++++++++++++++++++++++++ 1 file changed, 155 insertions(+) diff --git a/livekit-session/src/session.rs b/livekit-session/src/session.rs index 41af29a1fa..66cafe9192 100644 --- a/livekit-session/src/session.rs +++ b/livekit-session/src/session.rs @@ -32,6 +32,25 @@ use crate::constants::{DEFAULT_AGENT_CONNECT_TIMEOUT, TOPIC_CHAT}; use crate::error::{MessageSendError, SessionStartError}; use crate::messages::{Message, MessageOrigin, MessageUpdate}; +/// Where a [`Session`] gets its credentials, chosen by the constructor used. +// Built once per session and kept behind an `Arc`, so its size does not matter. +#[allow(clippy::large_enum_variant)] +pub(crate) enum SessionTokenSource { + /// A source whose credentials take no options. + Fixed(Box), + /// A source fetched with the given options, e.g. to dispatch an agent. + Configurable(Box, TokenSourceFetchOptions), +} + +impl SessionTokenSource { + async fn fetch(&self) -> TokenSourceResult { + match self { + Self::Fixed(source) => source.fetch().await, + Self::Configurable(source, options) => source.fetch(options).await, + } + } +} + /// Options for a [`Session`]. #[derive(Clone, Debug)] #[non_exhaustive] @@ -103,6 +122,142 @@ pub enum SessionEvent { MessagesRestored, } +/// 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::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; +/// +/// # async fn run() -> Result<(), Box> { +/// let token_source = development_token_server("my-token-server-id"); +/// let session = Session::with_agent(token_source, "my-agent", SessionOptions::default()); +/// +/// 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 { + token_source: SessionTokenSource, + options: SessionOptions, + pub(crate) shared: Arc, + pub(crate) lifecycle: Mutex, +} + +pub(crate) enum Lifecycle { + Idle, + Starting { generation: u64, cancel: oneshot::Sender<()> }, + Running(Running), +} + +pub(crate) struct Running { + 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 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, + } + } +} + +impl Session { + /// Creates a session that gets its credentials from a fixed + /// `token_source`, such as a [`literal`](livekit_token_source::literal) + /// one. Nothing happens until [`start`](Self::start). + pub fn new( + token_source: impl TokenSourceFixed + Send + Sync + 'static, + session_options: SessionOptions, + ) -> Self { + Self::from_source(SessionTokenSource::Fixed(Box::new(token_source)), session_options) + } + + /// Creates a session that fetches its credentials from `token_source` + /// with `fetch_options`. Nothing happens until [`start`](Self::start). + /// + /// Every `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 with_fetch_options( + token_source: impl TokenSourceConfigurable + Send + Sync + 'static, + fetch_options: TokenSourceFetchOptions, + session_options: SessionOptions, + ) -> Self { + Self::from_source( + SessionTokenSource::Configurable(Box::new(token_source), fetch_options), + session_options, + ) + } + + /// Creates a session whose credentials dispatch the agent `agent_name`. + /// + /// Shorthand for [`with_fetch_options`](Self::with_fetch_options) with + /// [`TokenSourceFetchOptions::with_agent_name`]; use that to set further + /// options, such as agent metadata. + pub fn with_agent( + token_source: impl TokenSourceConfigurable + Send + Sync + 'static, + agent_name: &str, + session_options: SessionOptions, + ) -> Self { + let fetch_options = TokenSourceFetchOptions::new().with_agent_name(agent_name); + Self::with_fetch_options(token_source, fetch_options, session_options) + } + + fn from_source(token_source: SessionTokenSource, session_options: SessionOptions) -> Self { + Self { + inner: Arc::new(Inner { + token_source, + options: session_options, + shared: Arc::new(Shared::new()), + lifecycle: Mutex::new(Lifecycle::Idle), + }), + } + } +} + /// The connection state of a [`Session`]. #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] From 668a2e75a51b2c4a8d2b98f50ed00d809357a9ed Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:03:47 +0100 Subject: [PATCH 19/61] IMPORTANT(session): add the session actor and its agent-state projection This commit adds `SessionActor` and the `Connection` it runs. The actor runs one connected room for one `start`. It holds the room, the platform audio, the room events, the stop receiver, the agent deadline and the `AgentTracker`. It holds no `Session` handle, so dropping the last handle stops the actor. `run` selects between the stop channel, the room events and the agent deadline. A `Disconnected` room event or a closed stop channel ends the loop. On exit, the actor closes the stop receiver first. A `start` that follows then finds the actor gone. The actor closes the room when the session stopped it. It then publishes the default state. `on_room_event` tracks the connection state and refreshes the projection on participant and track changes. `on_agent_deadline` records the timeout in the tracker and refreshes the projection. Review the shutdown order and the ownership with care. See the "Memory lifecycle" section of AGENTS.md. --- livekit-session/src/actor.rs | 158 +++++++++++++++++++++++++++++++++++ 1 file changed, 158 insertions(+) diff --git a/livekit-session/src/actor.rs b/livekit-session/src/actor.rs index 99fa3c8fe7..704707ea65 100644 --- a/livekit-session/src/actor.rs +++ b/livekit-session/src/actor.rs @@ -130,3 +130,161 @@ impl Shared { 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, +} + +enum Event { + Stop, + Room(RoomEvent), + AgentDeadline, +} + +/// 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), +} + +/// Runs one connected room for one `start()`: projects the agent state, +/// reads the session's text streams, and closes the room when the session +/// ends or is dropped. +/// +/// 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, + /// Keeps the microphone and speakers 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<()>, + agent_deadline: Option>>, + connection: SessionConnectionState, + tracker: AgentTracker, + shared: Arc, +} + +impl SessionActor { + pub(crate) fn new( + generation: u64, + connection: Connection, + stop: mpsc::Receiver<()>, + shared: Arc, + ) -> Self { + let state = match connection.room.connection_state() { + ConnectionState::Reconnecting => SessionConnectionState::Reconnecting, + ConnectionState::Connected | ConnectionState::Disconnected => { + SessionConnectionState::Connected + } + }; + Self { + generation, + room: connection.room, + _platform_audio: connection.platform_audio, + room_events: connection.events, + stop, + agent_deadline: Some(Box::pin(tokio::time::sleep(connection.agent_timeout))), + connection: state, + tracker: AgentTracker::default(), + shared, + } + } + + /// Projects the agent state and publishes the session state. + pub(crate) fn refresh(&mut self) { + let participants = self.room.remote_participants(); + let agent_state = self.tracker.project(self.connection, participants.values()); + 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 = 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), + () = deadline => Event::AgentDeadline, + }; + match event { + Event::Stop => break Exit::Stopped, + Event::Room(RoomEvent::Disconnected { reason }) => { + break Exit::Disconnected(reason) + } + Event::Room(event) => self.on_room_event(event), + Event::AgentDeadline => self.on_agent_deadline(), + } + }; + + // Closed before the final state, so that a `start()` prompted by it + // already finds this actor gone. + self.stop.close(); + match exit { + Exit::Stopped => { + if let Err(err) = self.room.close().await { + log::warn!("failed to close the session room: {err}"); + } + } + Exit::Disconnected(reason) => { + log::info!("session room disconnected: {reason:?}"); + } + } + self.shared.publish(self.generation, SessionState::default()); + } + + fn on_room_event(&mut self, event: RoomEvent) { + match event { + 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(); + } + + fn on_agent_deadline(&mut self) { + self.agent_deadline = None; + let participants = self.room.remote_participants(); + if self.tracker.time_out(self.connection, participants.values()) { + log::info!("agent did not become conversational in time"); + } + self.refresh(); + } +} From b8c2b61c15cdbfd7eff4f54bb49c9fd4ddab1859 Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:03:47 +0100 Subject: [PATCH 20/61] IMPORTANT(session): read chat and transcript streams in the actor This commit adds the text-stream reading to `SessionActor`. `on_text_stream` takes the reader of a stream on the `lk.chat` or `lk.transcription` topic. It leaves streams on other topics to the app. A chat stream is read in full. A transcription stream is read chunk by chunk, followed by an end marker. The readers are polled in the actor loop, through a `SelectAll`. The `TranscriptAggregator` then has one writer. `on_reader_event` turns each chunk, end or chat into a `MessageUpdate` and upserts it into the shared store. --- livekit-session/src/actor.rs | 104 +++++++++++++++++++++++++++++++++++ 1 file changed, 104 insertions(+) diff --git a/livekit-session/src/actor.rs b/livekit-session/src/actor.rs index 704707ea65..f66dc3805b 100644 --- a/livekit-session/src/actor.rs +++ b/livekit-session/src/actor.rs @@ -141,9 +141,28 @@ pub(crate) struct Connection { pub agent_timeout: Duration, } +/// An incoming text stream the session reads. +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, +} + enum Event { Stop, Room(RoomEvent), + Reader(ReaderEvent), AgentDeadline, } @@ -172,9 +191,13 @@ pub(crate) struct SessionActor { /// Never carries a value: the session stops the actor by dropping the /// sender. stop: mpsc::Receiver<()>, + /// 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>, agent_deadline: Option>>, connection: SessionConnectionState, tracker: AgentTracker, + aggregator: TranscriptAggregator, shared: Arc, } @@ -197,9 +220,11 @@ impl SessionActor { _platform_audio: connection.platform_audio, room_events: connection.events, stop, + readers: SelectAll::new(), agent_deadline: Some(Box::pin(tokio::time::sleep(connection.agent_timeout))), connection: state, tracker: AgentTracker::default(), + aggregator: TranscriptAggregator::default(), shared, } } @@ -229,6 +254,7 @@ impl SessionActor { 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 { @@ -237,6 +263,7 @@ impl SessionActor { break 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(), } }; @@ -259,6 +286,10 @@ impl SessionActor { 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; @@ -279,6 +310,79 @@ impl SessionActor { 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, + 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, + 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 participants = self.room.remote_participants(); From cd02a39788d6e4e551659b7b7b8722a75a06c106 Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:03:47 +0100 Subject: [PATCH 21/61] IMPORTANT(session): start and end a session This commit adds `Session::start`, `Session::end`, `connect`, `publish_microphone` and `StartGuard`. `start` fails with `AlreadyStarted` while the session is starting or running. It begins a new generation, joins a stale actor, and then fetches credentials and connects the room. `end` can cancel this phase. Platform audio is created before the room connects. After the connect, `start` publishes the microphone. This step is not cancellable. A failed publish closes the room. `start` spawns the actor only when the lifecycle still holds its generation. Otherwise `end` was called during the connect. `start` then closes the room and returns `Cancelled`. `StartGuard` resets the lifecycle and the state when `start` fails or is dropped before the actor runs. `end` closes the room through the actor, or cancels a pending start. It does nothing when there is nothing to end. Review the cancellation paths with care. Each path must leave no room, task or audio device behind. --- livekit-session/src/session.rs | 150 +++++++++++++++++++++++++++++++++ 1 file changed, 150 insertions(+) diff --git a/livekit-session/src/session.rs b/livekit-session/src/session.rs index 66cafe9192..5f9329ff32 100644 --- a/livekit-session/src/session.rs +++ b/livekit-session/src/session.rs @@ -256,6 +256,156 @@ impl Session { }), } } + + /// Fetches credentials, connects the room, and publishes the microphone + /// (see [`SessionOptions::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. + 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?; + let room = connection.room.clone(); + // Outside the cancellable select, so that an `end` during the publish + // cannot drop a connected room without closing it; it is honoured + // below instead. + if let Some(audio) = &connection.platform_audio { + if let Err(err) = publish_microphone(&room, audio).await { + if let Err(close_err) = room.close().await { + log::warn!("failed to close the room of a failed start: {close_err}"); + } + return Err(SessionStartError::Microphone(err)); + } + } + let (stop_tx, stop_rx) = mpsc::channel(1); + let mut actor = + SessionActor::new(generation, connection, stop_rx, self.inner.shared.clone()); + + { + let mut lifecycle = lock(&self.inner.lifecycle); + if matches!(*lifecycle, Lifecycle::Starting { generation: g, .. } if g == generation) { + actor.refresh(); + let task = tokio::spawn(actor.run()); + *lifecycle = Lifecycle::Running(Running { room, stop: stop_tx, task }); + guard.armed = false; + return Ok(()); + } + } + + // `end` was called just as the connection completed. The room is + // closed before the actor, and the platform audio it holds, is dropped. + if let Err(err) = room.close().await { + log::warn!("failed to close the room of a cancelled start: {err}"); + } + drop(actor); + Err(SessionStartError::Cancelled) + } + + async fn connect(&self) -> Result { + let options = &self.inner.options; + let credentials = self.inner.token_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?; + 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; + } +} + +/// Publishes the platform microphone as the local participant's microphone +/// track. +async fn publish_microphone(room: &Room, audio: &PlatformAudio) -> RoomResult<()> { + let track = LocalAudioTrack::create_audio_track("microphone", audio.rtc_source()); + let options = TrackPublishOptions { source: TrackSource::Microphone, ..Default::default() }; + room.local_participant().publish_track(LocalTrack::Audio(track), options).await?; + Ok(()) +} + +/// Resets the session when a [`Session::start`] fails or is dropped before +/// the room is running. +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()); + } } /// The connection state of a [`Session`]. From ce275051dd24a983f538f0d9394814decb69c790 Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:03:48 +0100 Subject: [PATCH 22/61] feat(session): expose state, room, agent tracks and the message feed This commit adds the accessor methods of `Session`. `state` returns a `watch` receiver of the session state. `room` returns the room while it is connected or reconnecting. `agent_audio_track` and `agent_avatar_video_track` return the agent's media tracks, once subscribed. `send_text` sends chat to the agent on `lk.chat` and adds the text to the feed once sent. `messages`, `restore_messages` and `subscribe` read, replace and observe the feed. --- livekit-session/src/session.rs | 66 ++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/livekit-session/src/session.rs b/livekit-session/src/session.rs index 5f9329ff32..e4e4ba990d 100644 --- a/livekit-session/src/session.rs +++ b/livekit-session/src/session.rs @@ -375,6 +375,72 @@ impl Session { }; 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() + } + + /// The agent's microphone track, once subscribed. + pub fn agent_audio_track(&self) -> Option { + let room = self.room()?; + agent::agent_audio_track(room.remote_participants().values()) + } + + /// The camera track of the agent's avatar, once subscribed. An avatar is a + /// separate participant publishing on the agent's behalf. + pub fn agent_avatar_video_track(&self) -> Option { + let room = self.room()?; + agent::agent_avatar_video_track(room.remote_participants().values()) + } + + /// 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, + 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. + pub fn restore_messages(&self, messages: &[Message]) { + self.inner.shared.restore(messages); + } + + /// A receiver of changes to the message feed. + /// + /// Unbounded, like [`Room::subscribe`]: the session must never block on a + /// slow subscriber, and the feed's rate is bounded by the conversation. + /// Drop the receiver to unsubscribe; it is removed on the next event. + pub fn subscribe(&self) -> mpsc::UnboundedReceiver { + self.inner.shared.subscribe() + } } /// Publishes the platform microphone as the local participant's microphone From e810c7815c5ac8c484604438eb60ca61e533d055 Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:03:48 +0100 Subject: [PATCH 23/61] test(session): assert with_agent fetches with the agent name This commit adds a unit test of `Session::with_agent`. A recording token source captures the fetch options. The test shows that the options carry the agent name. --- livekit-session/src/session.rs | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/livekit-session/src/session.rs b/livekit-session/src/session.rs index e4e4ba990d..5fae812787 100644 --- a/livekit-session/src/session.rs +++ b/livekit-session/src/session.rs @@ -510,3 +510,37 @@ impl Default for SessionState { Self { connection: SessionConnectionState::Disconnected, agent: AgentState::Disconnected } } } + +#[cfg(test)] +mod tests { + use super::*; + + use async_trait::async_trait; + 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 with_agent_fetches_with_the_agent_name() { + let fetched = Arc::default(); + let source = RecordingSource(Arc::clone(&fetched)); + let options = SessionOptions::default().with_platform_audio(false); + let session = Session::with_agent(source, "my-agent", 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")); + } +} From 57ecc7057f1b69e9c724c62c44ca5afad3f77766 Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:03:48 +0100 Subject: [PATCH 24/61] test(session): add the e2e harness with a stand-in agent This commit adds the end-to-end test module and its harness. The tests run against a `livekit-server --dev` and need the `__lk-e2e-test` feature. `TestEnv` builds tokens for a unique room. It joins a second room as the agent, as an avatar worker, or as an observer. The agent room sets the agent state attribute. The helper functions wait for a session state, poll a condition, and read the private lifecycle of a session. The root module declares the test module behind the feature. --- livekit-session/src/e2e_tests.rs | 199 +++++++++++++++++++++++++++++++ livekit-session/src/lib.rs | 3 + 2 files changed, 202 insertions(+) create mode 100644 livekit-session/src/e2e_tests.rs diff --git a/livekit-session/src/e2e_tests.rs b/livekit-session/src/e2e_tests.rs new file mode 100644 index 0000000000..781f35e4a6 --- /dev/null +++ b/livekit-session/src/e2e_tests.rs @@ -0,0 +1,199 @@ +// 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`, with a second +//! room standing in for the agent. +//! +//! 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::collections::HashMap; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Weak}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use anyhow::{anyhow, bail, Result}; +use async_trait::async_trait; +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, SimulateScenario, StreamReader, StreamTextOptions, StreamWriter}; +use livekit_api::services::room::RoomClient; +use livekit_token::{AccessToken, VideoGrants}; +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::constants::{ + ATTRIBUTE_AGENT_STATE, ATTRIBUTE_PUBLISH_ON_BEHALF, ATTRIBUTE_SEGMENT_ID, + ATTRIBUTE_TRANSCRIPTION_FINAL, TOPIC_CHAT, TOPIC_TRANSCRIPTION, +}; +use crate::session::Lifecycle; +use crate::*; + +const USER: &str = "user"; +const AGENT: &str = "agent"; +const WAIT: Duration = Duration::from_secs(10); + +struct TestEnv { + url: String, + api_key: String, + api_secret: String, + room: String, +} + +impl TestEnv { + 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}"), + } + } + + 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(VideoGrants { + room_join: true, + room: self.room.clone(), + can_update_own_metadata: Some(true), + ..Default::default() + }) + .with_identity(identity); + customize(token).to_jwt().expect("Failed to sign token") + } + + /// Credentials for the session's user, optionally dispatching an agent. + 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) + } + + /// Joins a participant of kind agent reporting `state`. + 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`. + 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?) + } + + async fn join_observer(&self) -> Result<(Room, UnboundedReceiver)> { + let token = self.token("observer", |token| token); + Ok(Room::connect(&self.url, &token, RoomOptions::default()).await?) + } +} + +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(()) +} + +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) +} + +async fn wait_for_agent(session: &Session, agent_state: AgentState) -> Result<()> { + wait_for(session, &format!("{agent_state:?}"), |s| s.agent == agent_state).await?; + Ok(()) +} + +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}")) +} + +fn weak_shared(session: &Session) -> Weak { + Arc::downgrade(&session.inner.shared) +} + +fn is_idle(session: &Session) -> bool { + matches!(*lock(&session.inner.lifecycle), Lifecycle::Idle) +} + +fn current(session: &Session) -> SessionState { + *session.state().borrow() +} + +/// Options for a session that stays off the machine's audio devices. +fn text_options() -> SessionOptions { + SessionOptions::default().with_platform_audio(false) +} diff --git a/livekit-session/src/lib.rs b/livekit-session/src/lib.rs index e80a7ab218..70813ef5da 100644 --- a/livekit-session/src/lib.rs +++ b/livekit-session/src/lib.rs @@ -27,6 +27,9 @@ mod error; mod messages; mod session; +#[cfg(all(test, feature = "__lk-e2e-test"))] +mod e2e_tests; + pub use agent::{AgentFailure, AgentState}; pub use error::{MessageSendError, SessionStartError}; pub use messages::{Message, MessageOrigin}; From 92400970897e6ceca842a787bb4cbb7baf2ffc28 Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:03:48 +0100 Subject: [PATCH 25/61] test(session): e2e agent state follows joins, leaves and reconnects This commit adds the first end-to-end tests of the agent projection. The tests show that a started session reports the agent once it joins, that `end` disconnects and is idempotent, that an agent that leaves is reported as `Left`, and that a full reconnect is not reported as `Left`. --- livekit-session/src/e2e_tests.rs | 81 ++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) diff --git a/livekit-session/src/e2e_tests.rs b/livekit-session/src/e2e_tests.rs index 781f35e4a6..c71231a5e8 100644 --- a/livekit-session/src/e2e_tests.rs +++ b/livekit-session/src/e2e_tests.rs @@ -197,3 +197,84 @@ fn current(session: &Session) -> SessionState { fn text_options() -> SessionOptions { SessionOptions::default().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(env.user_source(false), text_options()); + 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).ok() }, + ); + let (agent, _agent_events) = env.join_agent(AGENT, "listening").await?; + let connected = timeout(WAIT, wait).await??.ok_or_else(|| anyhow!("state closed"))?; + assert_eq!(connected.agent, AgentState::Listening); + + set_agent_state(&agent, "speaking").await?; + wait_for_agent(&session, AgentState::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 agent_leaving_is_reported_as_left() -> Result<()> { + let env = TestEnv::new(); + let session = Session::new(env.user_source(false), text_options()); + session.start().await?; + let (agent, _agent_events) = env.join_agent(AGENT, "listening").await?; + wait_for_agent(&session, AgentState::Listening).await?; + + agent.close().await?; + wait_for_agent(&session, AgentState::Failed(AgentFailure::Left)).await?; + session.end().await; + Ok(()) +} + +#[tokio::test(flavor = "multi_thread")] +async fn full_reconnect_does_not_report_left() -> Result<()> { + let env = TestEnv::new(); + let session = Session::new(env.user_source(false), text_options()); + session.start().await?; + let (_agent, _agent_events) = env.join_agent(AGENT, "listening").await?; + wait_for_agent(&session, AgentState::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 + && s.agent == AgentState::Listening + }) + }) + .await?; + + let history = lock(&session.inner.shared.history).clone(); + assert!( + !history.iter().any(|s| s.agent == AgentState::Failed(AgentFailure::Left)), + "a full reconnect was reported as the agent leaving: {history:?}" + ); + session.end().await; + Ok(()) +} From 75a16ce6739bbb20d33ebc1b3b5f176dfac01e2f Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:03:49 +0100 Subject: [PATCH 26/61] test(session): e2e agent connect timeout This commit adds the end-to-end tests of the agent-connect timeout. The tests show that the timeout fires without an agent, that a late agent recovers the state, that the timeout is armed without an agent dispatch, and that the timeout fires for an agent stuck in `initializing`. --- livekit-session/src/e2e_tests.rs | 46 ++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/livekit-session/src/e2e_tests.rs b/livekit-session/src/e2e_tests.rs index c71231a5e8..450311ad64 100644 --- a/livekit-session/src/e2e_tests.rs +++ b/livekit-session/src/e2e_tests.rs @@ -278,3 +278,49 @@ async fn full_reconnect_does_not_report_left() -> Result<()> { 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 = + SessionOptions { agent_connect_timeout: Duration::from_millis(500), ..text_options() }; + let session = Session::new(env.user_source(true), options); + session.start().await?; + wait_for_agent(&session, AgentState::Failed(AgentFailure::Timeout)).await?; + + let (_agent, _agent_events) = env.join_agent(AGENT, "listening").await?; + wait_for_agent(&session, AgentState::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 = + SessionOptions { agent_connect_timeout: Duration::from_millis(500), ..text_options() }; + // An agent registered without a name is dispatched automatically, so a + // token naming none still waits for one. + let session = Session::new(env.user_source(false), options); + session.start().await?; + wait_for_agent(&session, AgentState::Failed(AgentFailure::Timeout)).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 = + SessionOptions { agent_connect_timeout: Duration::from_millis(500), ..text_options() }; + // 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(env.user_source(true), options); + session.start().await?; + wait_for_agent(&session, AgentState::Failed(AgentFailure::Timeout)).await?; + + set_agent_state(&agent, "listening").await?; + wait_for_agent(&session, AgentState::Listening).await?; + session.end().await; + Ok(()) +} From 2c9bc28103a91602deb6bc022b8792db26d820a5 Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:03:49 +0100 Subject: [PATCH 27/61] test(session): e2e start publishes the platform microphone This commit adds the end-to-end test of the default platform audio. The test shares the platform-audio handle with the session. It shows that `start` publishes the microphone track and that `end` releases the audio devices. The test skips on a machine without a microphone. --- livekit-session/src/e2e_tests.rs | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/livekit-session/src/e2e_tests.rs b/livekit-session/src/e2e_tests.rs index 450311ad64..172a034932 100644 --- a/livekit-session/src/e2e_tests.rs +++ b/livekit-session/src/e2e_tests.rs @@ -235,6 +235,33 @@ async fn start_projects_the_agent_and_end_disconnects() -> Result<()> { Ok(()) } +#[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 Ok(probe) = PlatformAudio::new() else { + log::info!("skipping: this machine has no audio devices"); + return Ok(()); + }; + if probe.recording_devices().next().is_none() { + log::info!("skipping: this machine has no microphone"); + return Ok(()); + } + let env = TestEnv::new(); + let session = Session::new(env.user_source(false), SessionOptions::default()); + + 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(); From 279430dba18c85a8c9071cb83a310a457ffcbab6 Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:03:49 +0100 Subject: [PATCH 28/61] test(session): e2e the feed merges chat and transcripts This commit adds the end-to-end tests of the message feed. The first test shows that user input reaches the agent on `lk.chat`, that an agent transcript grows in place and is finalized by the trailer, that chat from the agent joins the feed, and that a failed send adds nothing. The second test shows that the session leaves streams on other topics to the app. --- livekit-session/src/e2e_tests.rs | 122 +++++++++++++++++++++++++++++++ 1 file changed, 122 insertions(+) diff --git a/livekit-session/src/e2e_tests.rs b/livekit-session/src/e2e_tests.rs index 172a034932..1442855f2a 100644 --- a/livekit-session/src/e2e_tests.rs +++ b/livekit-session/src/e2e_tests.rs @@ -351,3 +351,125 @@ async fn timeout_fires_for_an_agent_stuck_initializing() -> Result<()> { session.end().await; Ok(()) } + +async fn next_message( + events: &mut UnboundedReceiver, + mut predicate: impl FnMut(&Message) -> bool, +) -> Result { + timeout(WAIT, async { + while let Some(event) = events.recv().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(env.user_source(false), text_options()); + let mut events = session.subscribe(); + session.start().await?; + let (agent, mut agent_events) = env.join_agent(AGENT, "listening").await?; + wait_for_agent(&session, AgentState::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(env.user_source(false), text_options()); + 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, AgentState::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(()) +} From 74c9a5b8f0cc397ab447f803ef8a05f0d0affd49 Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:03:50 +0100 Subject: [PATCH 29/61] test(session): e2e agent audio and avatar video tracks This commit adds the end-to-end tests of the agent media accessors. The helpers publish a silent audio track or a blank video track from the agent room. The tests show that only the microphone is the agent's audio, that only the avatar worker's camera is the avatar video, and that an avatar worker of kind agent is not taken for the agent. --- livekit-session/src/e2e_tests.rs | 104 +++++++++++++++++++++++++++++++ 1 file changed, 104 insertions(+) diff --git a/livekit-session/src/e2e_tests.rs b/livekit-session/src/e2e_tests.rs index 1442855f2a..eb9ef50bd6 100644 --- a/livekit-session/src/e2e_tests.rs +++ b/livekit-session/src/e2e_tests.rs @@ -473,3 +473,107 @@ async fn streams_on_other_topics_are_left_to_the_app() -> Result<()> { 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())) +} + +async fn eventually_some(what: &str, mut poll: impl FnMut() -> Option) -> Result { + timeout(WAIT, async { + loop { + if let Some(value) = poll() { + return value; + } + sleep(Duration::from_millis(20)).await; + } + }) + .await + .map_err(|_| anyhow!("timed out waiting for {what}")) +} + +#[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(env.user_source(false), text_options()); + assert!(session.agent_audio_track().is_none()); + session.start().await?; + let (agent, _agent_events) = env.join_agent(AGENT, "listening").await?; + wait_for_agent(&session, AgentState::Listening).await?; + assert!(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!(session.agent_audio_track().is_none()); + + let microphone = publish_audio(&agent, TrackSource::Microphone).await?; + let track = eventually_some("the agent's microphone", || session.agent_audio_track()).await?; + assert_eq!(track.sid(), microphone.sid()); + + session.end().await; + assert!(session.agent_audio_track().is_none()); + 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(env.user_source(false), text_options()); + session.start().await?; + let (agent, _agent_events) = env.join_agent(AGENT, "listening").await?; + wait_for_agent(&session, AgentState::Listening).await?; + assert!(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!(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 track = + eventually_some("the avatar's camera", || session.agent_avatar_video_track()).await?; + assert_eq!(track.sid(), camera.sid()); + assert!(session.agent_audio_track().is_none()); + + // 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, AgentState::Speaking).await?; + + session.end().await; + assert!(session.agent_avatar_video_track().is_none()); + Ok(()) +} From 1163192de75afa59647559c473aa054e292c008f Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:03:50 +0100 Subject: [PATCH 30/61] test(session): e2e restart after a disconnect and a rejected token This commit adds two end-to-end tests of the start path. The first test removes the user from the room through the server API. It shows that the session reports `Disconnected`, that a new `start` releases the old room, and that `end` after a disconnect is a no-op. The second test shows that a rejected token fails `start` with `Connect` and leaves the session idle. --- livekit-session/src/e2e_tests.rs | 40 ++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/livekit-session/src/e2e_tests.rs b/livekit-session/src/e2e_tests.rs index eb9ef50bd6..3ba6ea7bf6 100644 --- a/livekit-session/src/e2e_tests.rs +++ b/livekit-session/src/e2e_tests.rs @@ -577,3 +577,43 @@ async fn agent_avatar_video_track_is_the_avatar_workers_camera_once_subscribed() assert!(session.agent_avatar_video_track().is_none()); Ok(()) } + +#[tokio::test(flavor = "multi_thread")] +async fn restarting_after_a_server_side_disconnect() -> Result<()> { + let env = TestEnv::new(); + let session = Session::new(env.user_source(false), text_options()); + 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 mut options = text_options(); + options.room_options.join_retries = 0; + let session = Session::new(literal(env.url.clone(), "not a token"), options); + assert!(matches!(session.start().await, Err(SessionStartError::Connect(_)))); + assert_eq!(current(&session), SessionState::default()); + assert!(is_idle(&session)); + Ok(()) +} From c099316a87e8998262c68d4b2d4b37b955d84eb5 Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:03:50 +0100 Subject: [PATCH 31/61] test(session): e2e end and drop cancel a pending start This commit adds the end-to-end tests of a start that waits on the token source. `PendingSource` never answers. The tests show that `end` cancels the start with `Cancelled`, and that a dropped `start` future resets the session. --- livekit-session/src/e2e_tests.rs | 38 ++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/livekit-session/src/e2e_tests.rs b/livekit-session/src/e2e_tests.rs index 3ba6ea7bf6..1291deab0d 100644 --- a/livekit-session/src/e2e_tests.rs +++ b/livekit-session/src/e2e_tests.rs @@ -617,3 +617,41 @@ async fn a_rejected_token_fails_the_start() -> Result<()> { 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::with_fetch_options(PendingSource, TokenSourceFetchOptions::new(), text_options()); + 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(()) +} + +#[tokio::test(flavor = "multi_thread")] +async fn dropping_a_pending_start_resets_the_session() -> Result<()> { + let session = + Session::with_fetch_options(PendingSource, TokenSourceFetchOptions::new(), text_options()); + assert!(timeout(Duration::from_millis(100), session.start()).await.is_err()); + assert_eq!(current(&session), SessionState::default()); + assert!(is_idle(&session)); + Ok(()) +} From bd572b88e7e43dd4e9586b6757b4025f9a8f0bf8 Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:03:50 +0100 Subject: [PATCH 32/61] test(session): e2e a start cancelled during the handshake leaves nothing behind This commit adds the end-to-end tests of a start that waits in `Room::connect`. `SilentServer` accepts one connection and never answers. The tests cancel the start with `end` or by a drop of the future. They show that the client hung up, that no actor was spawned, and that the task count returns to the baseline. --- livekit-session/src/e2e_tests.rs | 96 ++++++++++++++++++++++++++++++++ 1 file changed, 96 insertions(+) diff --git a/livekit-session/src/e2e_tests.rs b/livekit-session/src/e2e_tests.rs index 1291deab0d..901be640c1 100644 --- a/livekit-session/src/e2e_tests.rs +++ b/livekit-session/src/e2e_tests.rs @@ -646,6 +646,102 @@ async fn end_cancels_a_pending_start() -> Result<()> { 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(literal(self.url.clone(), env.token(USER, |t| t)), Self::session_options()) + } + + /// Options for a session connecting to this server. + fn session_options() -> SessionOptions { + let mut options = text_options(); + options.room_options.join_retries = 0; + // Long enough that only a cancel can end the handshake. + options.room_options.connect_timeout = Duration::from_secs(60); + 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 = From 8d23ac73d4572991894fbf7b536b2a301e6d367c Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:03:50 +0100 Subject: [PATCH 33/61] test(session): e2e memory lifecycle This commit adds the end-to-end lifecycle tests that AGENTS.md asks for. The tests show that dropping the last `Session` handle closes the room, that repeated start and end cycles leave no task or subscriber behind, and that failed starts spawn nothing. Each test checks observable destruction: a `Weak` that no longer upgrades, a strong count of one, or the task count of the runtime. --- livekit-session/src/e2e_tests.rs | 105 +++++++++++++++++++++++++++++++ 1 file changed, 105 insertions(+) diff --git a/livekit-session/src/e2e_tests.rs b/livekit-session/src/e2e_tests.rs index 901be640c1..2eaf50ebfd 100644 --- a/livekit-session/src/e2e_tests.rs +++ b/livekit-session/src/e2e_tests.rs @@ -751,3 +751,108 @@ async fn dropping_a_pending_start_resets_the_session() -> Result<()> { assert!(is_idle(&session)); Ok(()) } + +// 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(env.user_source(false), text_options()); + 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(env.user_source(false), text_options()); + 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::with_fetch_options(FailingSource, TokenSourceFetchOptions::new(), text_options()); + 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 mut options = text_options(); + options.room_options.join_retries = 0; + let session = Session::new(literal("ws://127.0.0.1:1", env.token(USER, |t| t)), 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(()) +} From 8fb6d40cf964596979e2c555283632bf8b1981c1 Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:03:51 +0100 Subject: [PATCH 34/61] docs(session): add the crate README This commit adds the README of the crate. The README gives a usage example and explains the credentials, the lifecycle, the state table, the message feed, and the things the session owns. --- livekit-session/README.md | 92 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 livekit-session/README.md diff --git a/livekit-session/README.md b/livekit-session/README.md new file mode 100644 index 0000000000..f43b9a154a --- /dev/null +++ b/livekit-session/README.md @@ -0,0 +1,92 @@ +# 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; + +let token_source = development_token_server(""); +let session = Session::with_agent(token_source, "my-agent", SessionOptions::default()); + +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 + +Which constructor to use depends on the kind of token source: + +- `Session::with_agent` takes a configurable source and the name of the agent to dispatch, as + above; +- `Session::with_fetch_options` takes a configurable source with its full `TokenSourceFetchOptions`, + for agent metadata, a room name or a participant identity; +- `Session::new` 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 | +| `Initializing`, `Idle` | The agent joined but is not in a conversation | +| `Listening`, `Thinking`, `Speaking` | The agent is in a conversation | +| `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 | +| `Unknown` | The agent reports an activity this SDK does not recognize | + +`Failed` is not final: an agent that joins, or becomes conversational, replaces it. Most code +needs only the predicates on `AgentState`: `is_connected`, `is_pending` and `is_finished`. + +The agent's microphone and its avatar's camera are available from `agent_audio_track()` and +`agent_avatar_video_track()`, for an app that wants their frames, e.g. for a visualizer. + +## 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::platform_audio` 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. From 50da4324abcd6bb1e8410d89e1c1b04685903e82 Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:03:51 +0100 Subject: [PATCH 35/61] feat(example): add the session voice and text chat example This commit adds `examples/session` and registers it in the workspace. The example creates a session from a pre-generated token or from a development token server. It prints the session state and the completed messages. Lines typed on stdin go to the agent. By default, the example uses the platform audio. The `--text` flag turns it off. `Cargo.lock` adds the lock entry of the example. --- Cargo.lock | 10 ++++ Cargo.toml | 1 + examples/session/Cargo.toml | 11 ++++ examples/session/README.md | 28 ++++++++++ examples/session/src/main.rs | 99 ++++++++++++++++++++++++++++++++++++ 5 files changed, 149 insertions(+) create mode 100644 examples/session/Cargo.toml create mode 100644 examples/session/README.md create mode 100644 examples/session/src/main.rs diff --git a/Cargo.lock b/Cargo.lock index 331dddd9dd..cb8be6bdd2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6870,6 +6870,16 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "session" +version = "0.1.0" +dependencies = [ + "env_logger 0.11.11", + "livekit-session", + "livekit-token-source", + "tokio", +] + [[package]] name = "sha1" version = "0.10.7" diff --git a/Cargo.toml b/Cargo.toml index c776107285..35de60a863 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -42,6 +42,7 @@ members = [ "examples/rpc", "examples/save_to_disk", "examples/screensharing", + "examples/session", "examples/telemetry_ping", "examples/token_source", "examples/webhooks", diff --git a/examples/session/Cargo.toml b/examples/session/Cargo.toml new file mode 100644 index 0000000000..283bbec04a --- /dev/null +++ b/examples/session/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "session" +version = "0.1.0" +edition.workspace = true +publish = false + +[dependencies] +env_logger = { 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..3b7a89870f --- /dev/null +++ b/examples/session/README.md @@ -0,0 +1,28 @@ +# 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 +``` + +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..4132d05b9f --- /dev/null +++ b/examples/session/src/main.rs @@ -0,0 +1,99 @@ +use std::error::Error; +use std::{env, time::Duration}; + +use livekit_session::{ + Message, MessageOrigin, Session, SessionEvent, SessionOptions, SessionState, +}; + +use livekit_token_source::{development_token_server, literal, TokenSourceFetchOptions}; +use tokio::io::{AsyncBufReadExt, BufReader}; + +/// Creates a session with credentials from a pre-generated token if one is +/// given, and from a development token server otherwise. +fn create_session(options: SessionOptions) -> Result> { + if let (Ok(url), Ok(token)) = (env::var("LIVEKIT_URL"), env::var("LIVEKIT_TOKEN")) { + return Ok(Session::new(literal(url, token), options)); + } + let token_server_id = env::var("LIVEKIT_TOKEN_SERVER_ID") + .map_err(|_| "set LIVEKIT_TOKEN_SERVER_ID, or LIVEKIT_URL and LIVEKIT_TOKEN")?; + let mut fetch_options = TokenSourceFetchOptions::new(); + if let Ok(agent_name) = env::var("LIVEKIT_AGENT_NAME") { + fetch_options = fetch_options.with_agent_name(agent_name); + } + Ok(Session::with_fetch_options( + development_token_server(token_server_id), + fetch_options, + 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(); + + // 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_only = env::args().any(|arg| arg == "--text"); + let session_options = SessionOptions::default() + .with_agent_connect_timeout(Duration::from_secs(15)) + .with_platform_audio(!text_only); + let session = create_session(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(); + print_state(¤t); + if !current.connection.is_connected() { + break; + } + } + Some(event) = events.recv() => { + 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(()) +} From 810281dde62c206b80b71c9324bb78f377e23292 Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:03:52 +0100 Subject: [PATCH 36/61] chore(session): add the changeset This commit adds the knope changeset for the new crate. The summary is one line of prose, as the "Documenting changes" section of AGENTS.md requires. --- .changeset/add_livekit_session_crate.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/add_livekit_session_crate.md diff --git a/.changeset/add_livekit_session_crate.md b/.changeset/add_livekit_session_crate.md new file mode 100644 index 0000000000..a25c3917d9 --- /dev/null +++ b/.changeset/add_livekit_session_crate.md @@ -0,0 +1,5 @@ +--- +livekit-session: patch +--- + +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::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. From e288351e6dd69abdf016c4ee871f8c43a1839713 Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Wed, 4 Nov 2026 14:11:22 +0100 Subject: [PATCH 37/61] AgentState is now nested like Swift --- livekit-session/README.md | 11 +-- livekit-session/src/agent.rs | 136 +++++++++++++++++++------------ livekit-session/src/e2e_tests.rs | 24 +++--- livekit-session/src/lib.rs | 2 +- 4 files changed, 105 insertions(+), 68 deletions(-) diff --git a/livekit-session/README.md b/livekit-session/README.md index f43b9a154a..8a3d616c94 100644 --- a/livekit-session/README.md +++ b/livekit-session/README.md @@ -54,14 +54,15 @@ and the agent state (`agent`): | --- | --- | | `Disconnected` | The session is not connected | | `Connecting` | No agent is in the room yet | -| `Initializing`, `Idle` | The agent joined but is not in a conversation | -| `Listening`, `Thinking`, `Speaking` | The agent is in a conversation | +| `Connected(Initializing)`, `Connected(Idle)` | The agent joined but is not in a conversation | +| `Connected(Listening)`, `Connected(Thinking)`, `Connected(Speaking)` | The agent is in a conversation | +| `Connected(Unknown)` | The agent reports an activity this SDK does not recognize | | `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 | -| `Unknown` | The agent reports an activity this SDK does not recognize | -`Failed` is not final: an agent that joins, or becomes conversational, replaces it. Most code -needs only the predicates on `AgentState`: `is_connected`, `is_pending` and `is_finished`. +`Connected` carries an `AgentActivity`, what the agent reports through its `lk.agent.state` +attribute. `Failed` is not final: an agent that joins, or becomes conversational, replaces it. Most +code needs only the predicates on `AgentState`: `is_connected`, `is_pending` and `is_finished`. The agent's microphone and its avatar's camera are available from `agent_audio_track()` and `agent_avatar_video_track()`, for an app that wants their frames, e.g. for a visualizer. diff --git a/livekit-session/src/agent.rs b/livekit-session/src/agent.rs index eb1335a3a3..9a8ca6bd73 100644 --- a/livekit-session/src/agent.rs +++ b/livekit-session/src/agent.rs @@ -20,7 +20,11 @@ use livekit::ParticipantKind; use crate::constants::{ATTRIBUTE_AGENT_STATE, ATTRIBUTE_PUBLISH_ON_BEHALF}; use crate::session::SessionConnectionState; -/// What the session's agent is doing, projected from the room. +/// The session's agent, projected from the room: whether it is there, and +/// what it is doing. +/// +/// This enum answers the first question. The [`AgentActivity`] inside +/// [`Connected`](Self::Connected) answers the second. /// /// Most code needs only the predicates: [`AgentState::is_connected`] to show /// that the agent is there, [`AgentState::is_pending`] to show that it is on @@ -33,23 +37,13 @@ pub enum AgentState { Disconnected, /// The session is connecting, or is connected and no agent has joined yet. Connecting, - /// 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, + /// An agent is in the room, doing the given activity. + Connected(AgentActivity), /// 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), - /// The agent reports an activity this SDK does not recognize. - Unknown, } impl AgentState { @@ -57,15 +51,18 @@ impl AgentState { /// thinking or speaking. /// /// Stricter than "an agent participant exists": an agent that is still - /// [`Initializing`](Self::Initializing) is not connected. + /// [`Initializing`](AgentActivity::Initializing) is not connected. pub fn is_connected(self) -> bool { - matches!(self, Self::Listening | Self::Thinking | Self::Speaking) + matches!(self, Self::Connected(activity) if activity.is_conversational()) } /// Whether an agent is expected but not yet conversational: connecting, /// initializing, or idle. pub fn is_pending(self) -> bool { - matches!(self, Self::Connecting | Self::Initializing | Self::Idle) + matches!( + self, + Self::Connecting | Self::Connected(AgentActivity::Initializing | AgentActivity::Idle) + ) } /// Whether the agent is gone or never came: the session is disconnected, @@ -76,6 +73,33 @@ impl AgentState { pub fn is_finished(self) -> bool { matches!(self, Self::Disconnected | Self::Failed(_)) } +} + +/// 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 @@ -182,8 +206,8 @@ pub(crate) fn agent_avatar_video_track<'a>( } /// The activity the agent reports through `lk.agent.state`. -fn activity(agent: &impl AgentCandidate) -> AgentState { - AgentState::from_attribute(agent.attributes().get(ATTRIBUTE_AGENT_STATE).map(String::as_str)) +fn activity(agent: &impl AgentCandidate) -> AgentActivity { + AgentActivity::from_attribute(agent.attributes().get(ATTRIBUTE_AGENT_STATE).map(String::as_str)) } /// Projects [`AgentState`] from the room, remembering what the projection @@ -229,9 +253,9 @@ impl AgentTracker { self.has_ever_connected = true; let identity = agent.identity(); let activity = activity(agent); - if activity.is_connected() { + if activity.is_conversational() { self.timed_out = None; - return activity; + return AgentState::Connected(activity); } // The timeout holds only for the agent that was too slow: one that // joins afterwards reports its own activity. @@ -239,7 +263,7 @@ impl AgentTracker { Some(Some(timed_out)) if *timed_out == identity => { AgentState::Failed(AgentFailure::Timeout) } - _ => activity, + _ => AgentState::Connected(activity), } } @@ -255,7 +279,7 @@ impl AgentTracker { return false; } let agent = find_agent(participants); - if agent.is_some_and(|agent| activity(agent).is_connected()) { + if agent.is_some_and(|agent| activity(agent).is_conversational()) { return false; } self.timed_out = Some(agent.map(|agent| agent.identity())); @@ -267,6 +291,7 @@ impl AgentTracker { mod tests { use super::*; + use AgentActivity::{Idle, Initializing, Listening, Speaking, Thinking, Unknown}; use SessionConnectionState::{Connected, Connecting, Disconnected, Reconnecting}; const NO_ONE: &[Fake] = &[]; @@ -315,15 +340,19 @@ mod tests { tracker.project(Connected, participants) } + fn connected(activity: AgentActivity) -> AgentState { + AgentState::Connected(activity) + } + #[test] fn attribute_values_map_to_states() { let mut tracker = AgentTracker::default(); for (value, state) in [ - ("initializing", AgentState::Initializing), - ("idle", AgentState::Idle), - ("listening", AgentState::Listening), - ("thinking", AgentState::Thinking), - ("speaking", AgentState::Speaking), + ("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); } @@ -332,10 +361,10 @@ mod tests { #[test] fn missing_attribute_is_idle_and_unrecognized_is_unknown() { let mut tracker = AgentTracker::default(); - assert_eq!(project(&mut tracker, &[Fake::agent("agent", None)]), AgentState::Idle); + assert_eq!(project(&mut tracker, &[Fake::agent("agent", None)]), connected(Idle)); assert_eq!( project(&mut tracker, &[Fake::agent("agent", Some("dancing"))]), - AgentState::Unknown + connected(Unknown) ); } @@ -366,7 +395,7 @@ mod tests { let participants = [Fake::agent("agent", Some("speaking"))]; assert_eq!(tracker.project(Disconnected, &participants), AgentState::Disconnected); assert_eq!(tracker.project(Connecting, &participants), AgentState::Connecting); - assert_eq!(tracker.project(Reconnecting, &participants), AgentState::Speaking); + assert_eq!(tracker.project(Reconnecting, &participants), connected(Speaking)); } #[test] @@ -384,7 +413,7 @@ mod tests { assert_eq!(tracker.project(Reconnecting, NO_ONE), AgentState::Connecting); assert_eq!( tracker.project(Reconnecting, &[Fake::agent("agent", Some("listening"))]), - AgentState::Listening + connected(Listening) ); } @@ -395,7 +424,7 @@ mod tests { assert_eq!(project(&mut tracker, NO_ONE), AgentState::Failed(AgentFailure::Left)); assert_eq!( project(&mut tracker, &[Fake::agent("agent-2", Some("initializing"))]), - AgentState::Initializing + connected(Initializing) ); } @@ -415,7 +444,7 @@ mod tests { assert_eq!(project(&mut tracker, NO_ONE), AgentState::Failed(AgentFailure::Timeout)); assert_eq!( project(&mut tracker, &[Fake::agent("agent", Some("initializing"))]), - AgentState::Initializing + connected(Initializing) ); } @@ -427,10 +456,10 @@ mod tests { assert_eq!(project(&mut tracker, &stuck), AgentState::Failed(AgentFailure::Timeout)); assert_eq!( project(&mut tracker, &[Fake::agent("agent", Some("listening"))]), - AgentState::Listening + connected(Listening) ); // Recovered for good: falling back to idle is not a timeout. - assert_eq!(project(&mut tracker, &[Fake::agent("agent", Some("idle"))]), AgentState::Idle); + assert_eq!(project(&mut tracker, &[Fake::agent("agent", Some("idle"))]), connected(Idle)); } #[test] @@ -444,32 +473,39 @@ mod tests { #[test] fn predicates_match_for_every_state() { - use AgentState::*; let states = [ - Disconnected, - Connecting, - Initializing, - Idle, - Listening, - Thinking, - Speaking, - Failed(AgentFailure::Timeout), - Failed(AgentFailure::Left), - Unknown, + AgentState::Disconnected, + AgentState::Connecting, + connected(Initializing), + connected(Idle), + connected(Listening), + connected(Thinking), + connected(Speaking), + connected(Unknown), + AgentState::Failed(AgentFailure::Timeout), + AgentState::Failed(AgentFailure::Left), ]; for state in states { assert_eq!( state.is_connected(), - matches!(state, Listening | Thinking | Speaking), + matches!(state, AgentState::Connected(Listening | Thinking | Speaking)), "{state:?}" ); assert_eq!( state.is_pending(), - matches!(state, Connecting | Initializing | Idle), + matches!( + state, + AgentState::Connecting | AgentState::Connected(Initializing | Idle) + ), + "{state:?}" + ); + assert_eq!( + state.is_finished(), + matches!(state, AgentState::Disconnected | AgentState::Failed(_)), "{state:?}" ); - assert_eq!(state.is_finished(), matches!(state, Disconnected | Failed(_)), "{state:?}"); } - assert!(!Initializing.is_connected()); + assert!(!connected(Initializing).is_connected()); + assert!(!connected(Unknown).is_pending()); } } diff --git a/livekit-session/src/e2e_tests.rs b/livekit-session/src/e2e_tests.rs index 2eaf50ebfd..92faab3f39 100644 --- a/livekit-session/src/e2e_tests.rs +++ b/livekit-session/src/e2e_tests.rs @@ -220,10 +220,10 @@ async fn start_projects_the_agent_and_end_disconnects() -> Result<()> { ); let (agent, _agent_events) = env.join_agent(AGENT, "listening").await?; let connected = timeout(WAIT, wait).await??.ok_or_else(|| anyhow!("state closed"))?; - assert_eq!(connected.agent, AgentState::Listening); + assert_eq!(connected.agent, AgentState::Connected(AgentActivity::Listening)); set_agent_state(&agent, "speaking").await?; - wait_for_agent(&session, AgentState::Speaking).await?; + wait_for_agent(&session, AgentState::Connected(AgentActivity::Speaking)).await?; session.end().await; assert_eq!(current(&session), SessionState::default()); @@ -268,7 +268,7 @@ async fn agent_leaving_is_reported_as_left() -> Result<()> { let session = Session::new(env.user_source(false), text_options()); session.start().await?; let (agent, _agent_events) = env.join_agent(AGENT, "listening").await?; - wait_for_agent(&session, AgentState::Listening).await?; + wait_for_agent(&session, AgentState::Connected(AgentActivity::Listening)).await?; agent.close().await?; wait_for_agent(&session, AgentState::Failed(AgentFailure::Left)).await?; @@ -282,7 +282,7 @@ async fn full_reconnect_does_not_report_left() -> Result<()> { let session = Session::new(env.user_source(false), text_options()); session.start().await?; let (_agent, _agent_events) = env.join_agent(AGENT, "listening").await?; - wait_for_agent(&session, AgentState::Listening).await?; + wait_for_agent(&session, AgentState::Connected(AgentActivity::Listening)).await?; lock(&session.inner.shared.history).clear(); let room = session.room().ok_or_else(|| anyhow!("no room"))?; @@ -292,7 +292,7 @@ async fn full_reconnect_does_not_report_left() -> Result<()> { history.iter().any(|s| s.connection == SessionConnectionState::Reconnecting) && history.last().is_some_and(|s| { s.connection == SessionConnectionState::Connected - && s.agent == AgentState::Listening + && s.agent == AgentState::Connected(AgentActivity::Listening) }) }) .await?; @@ -316,7 +316,7 @@ async fn timeout_fires_without_an_agent_and_a_late_agent_recovers() -> Result<() wait_for_agent(&session, AgentState::Failed(AgentFailure::Timeout)).await?; let (_agent, _agent_events) = env.join_agent(AGENT, "listening").await?; - wait_for_agent(&session, AgentState::Listening).await?; + wait_for_agent(&session, AgentState::Connected(AgentActivity::Listening)).await?; session.end().await; Ok(()) } @@ -347,7 +347,7 @@ async fn timeout_fires_for_an_agent_stuck_initializing() -> Result<()> { wait_for_agent(&session, AgentState::Failed(AgentFailure::Timeout)).await?; set_agent_state(&agent, "listening").await?; - wait_for_agent(&session, AgentState::Listening).await?; + wait_for_agent(&session, AgentState::Connected(AgentActivity::Listening)).await?; session.end().await; Ok(()) } @@ -376,7 +376,7 @@ async fn messages_merge_chat_and_transcripts() -> Result<()> { let mut events = session.subscribe(); session.start().await?; let (agent, mut agent_events) = env.join_agent(AGENT, "listening").await?; - wait_for_agent(&session, AgentState::Listening).await?; + wait_for_agent(&session, AgentState::Connected(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?; @@ -451,7 +451,7 @@ async fn streams_on_other_topics_are_left_to_the_app() -> Result<()> { 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, AgentState::Listening).await?; + wait_for_agent(&session, AgentState::Connected(AgentActivity::Listening)).await?; agent .local_participant() @@ -526,7 +526,7 @@ async fn agent_audio_track_is_the_agents_microphone_once_subscribed() -> Result< assert!(session.agent_audio_track().is_none()); session.start().await?; let (agent, _agent_events) = env.join_agent(AGENT, "listening").await?; - wait_for_agent(&session, AgentState::Listening).await?; + wait_for_agent(&session, AgentState::Connected(AgentActivity::Listening)).await?; assert!(session.agent_audio_track().is_none()); // Only the microphone is the agent's voice. @@ -550,7 +550,7 @@ async fn agent_avatar_video_track_is_the_avatar_workers_camera_once_subscribed() let session = Session::new(env.user_source(false), text_options()); session.start().await?; let (agent, _agent_events) = env.join_agent(AGENT, "listening").await?; - wait_for_agent(&session, AgentState::Listening).await?; + wait_for_agent(&session, AgentState::Connected(AgentActivity::Listening)).await?; assert!(session.agent_avatar_video_track().is_none()); // The agent's own camera is not an avatar. @@ -571,7 +571,7 @@ async fn agent_avatar_video_track_is_the_avatar_workers_camera_once_subscribed() // 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, AgentState::Speaking).await?; + wait_for_agent(&session, AgentState::Connected(AgentActivity::Speaking)).await?; session.end().await; assert!(session.agent_avatar_video_track().is_none()); diff --git a/livekit-session/src/lib.rs b/livekit-session/src/lib.rs index 70813ef5da..ba8b46a623 100644 --- a/livekit-session/src/lib.rs +++ b/livekit-session/src/lib.rs @@ -30,7 +30,7 @@ mod session; #[cfg(all(test, feature = "__lk-e2e-test"))] mod e2e_tests; -pub use agent::{AgentFailure, AgentState}; +pub use agent::{AgentActivity, AgentFailure, AgentState}; pub use error::{MessageSendError, SessionStartError}; pub use messages::{Message, MessageOrigin}; pub use session::{Session, SessionConnectionState, SessionEvent, SessionOptions, SessionState}; From 22a30efd29159c6ff1bd747476d9e6b5f3ae4eb0 Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Wed, 4 Nov 2026 16:18:36 +0100 Subject: [PATCH 38/61] Moving waiting for publish microphone into the actor --- livekit-session/src/actor.rs | 127 ++++++++++++++++++++++++------- livekit-session/src/e2e_tests.rs | 118 +++++++++++++++++++++++++--- livekit-session/src/session.rs | 92 ++++++++++++---------- 3 files changed, 258 insertions(+), 79 deletions(-) diff --git a/livekit-session/src/actor.rs b/livekit-session/src/actor.rs index f66dc3805b..5ca9fa564d 100644 --- a/livekit-session/src/actor.rs +++ b/livekit-session/src/actor.rs @@ -19,12 +19,13 @@ 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::{mpsc, watch}; +use tokio::sync::{mpsc, oneshot, watch}; use tokio::time::Sleep; use crate::agent::AgentTracker; @@ -173,27 +174,37 @@ enum Exit { Stopped, /// The room disconnected. Disconnected(DisconnectReason), + /// The microphone failed to publish. + Microphone(RoomError), } -/// Runs one connected room for one `start()`: projects the agent state, -/// reads the session's text streams, and closes the room when the session -/// ends or is dropped. +/// 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. /// -/// Holds no [`Session`](crate::Session) and no `stop` sender, so dropping the -/// last session handle closes `stop` and stops the actor. +/// 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, - /// Keeps the microphone and speakers running for as long as the room: - /// dropped with the actor, once the room is closed. - _platform_audio: Option, + /// 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, @@ -206,6 +217,7 @@ impl SessionActor { generation: u64, connection: Connection, stop: mpsc::Receiver<()>, + ready: oneshot::Sender>, shared: Arc, ) -> Self { let state = match connection.room.connection_state() { @@ -217,11 +229,13 @@ impl SessionActor { Self { generation, room: connection.room, - _platform_audio: connection.platform_audio, + platform_audio: connection.platform_audio, room_events: connection.events, stop, + ready: Some(ready), readers: SelectAll::new(), - agent_deadline: Some(Box::pin(tokio::time::sleep(connection.agent_timeout))), + agent_timeout: connection.agent_timeout, + agent_deadline: None, connection: state, tracker: AgentTracker::default(), aggregator: TranscriptAggregator::default(), @@ -243,7 +257,65 @@ impl SessionActor { } pub(crate) async fn run(mut self) { - let exit = loop { + 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() { @@ -258,30 +330,29 @@ impl SessionActor { () = deadline => Event::AgentDeadline, }; match event { - Event::Stop => break Exit::Stopped, + Event::Stop => return Exit::Stopped, Event::Room(RoomEvent::Disconnected { reason }) => { - break Exit::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(), } - }; + } + } - // Closed before the final state, so that a `start()` prompted by it - // already finds this actor gone. - self.stop.close(); - match exit { - Exit::Stopped => { - if let Err(err) = self.room.close().await { - log::warn!("failed to close the session room: {err}"); - } - } - Exit::Disconnected(reason) => { - log::info!("session room disconnected: {reason:?}"); - } + 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); } - self.shared.publish(self.generation, SessionState::default()); } fn on_room_event(&mut self, event: RoomEvent) { diff --git a/livekit-session/src/e2e_tests.rs b/livekit-session/src/e2e_tests.rs index 92faab3f39..afa25cb265 100644 --- a/livekit-session/src/e2e_tests.rs +++ b/livekit-session/src/e2e_tests.rs @@ -59,6 +59,9 @@ use crate::*; const USER: &str = "user"; const AGENT: &str = "agent"; const WAIT: Duration = Duration::from_secs(10); +/// How long the client waits for the server to answer a publish before it +/// gives up on it: `TRACK_PUBLISH_TIMEOUT` in `livekit`'s engine. +const PUBLISH_TIMEOUT: Duration = Duration::from_secs(10); struct TestEnv { url: String, @@ -81,15 +84,21 @@ impl TestEnv { } } + /// The grants of every token: joining the test's room, and setting + /// attributes. + fn grants(&self) -> VideoGrants { + VideoGrants { + room_join: true, + room: self.room.clone(), + can_update_own_metadata: Some(true), + ..Default::default() + } + } + 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(VideoGrants { - room_join: true, - room: self.room.clone(), - can_update_own_metadata: Some(true), - ..Default::default() - }) + .with_grants(self.grants()) .with_identity(identity); customize(token).to_jwt().expect("Failed to sign token") } @@ -111,6 +120,16 @@ impl TestEnv { literal(self.url.clone(), token) } + /// Credentials for a user who may join but not publish. The server + /// answers such a user's microphone publish with nothing, so the publish + /// stays pending until the client gives up on it. + 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`. async fn join_agent( &self, @@ -198,6 +217,20 @@ fn text_options() -> SessionOptions { SessionOptions::default().with_platform_audio(false) } +/// The machine's audio devices, or `None` when it has no microphone to +/// publish, logging that the test is skipped. +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) +} + #[tokio::test(flavor = "multi_thread")] async fn start_projects_the_agent_and_end_disconnects() -> Result<()> { let env = TestEnv::new(); @@ -239,14 +272,9 @@ async fn start_projects_the_agent_and_end_disconnects() -> Result<()> { 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 Ok(probe) = PlatformAudio::new() else { - log::info!("skipping: this machine has no audio devices"); + let Some(probe) = microphone_probe() else { return Ok(()); }; - if probe.recording_devices().next().is_none() { - log::info!("skipping: this machine has no microphone"); - return Ok(()); - } let env = TestEnv::new(); let session = Session::new(env.user_source(false), SessionOptions::default()); @@ -752,6 +780,72 @@ async fn dropping_a_pending_start_resets_the_session() -> Result<()> { Ok(()) } +/// Asserts that a start cut short during the microphone publish closed its +/// room, so the observer sees the user leave, and left no actor or task +/// behind. +async fn assert_cut_short_publish_left_nothing( + session: &Session, + observer_events: &mut UnboundedReceiver, + baseline_tasks: usize, +) -> Result<()> { + next_participant_event(observer_events, |event| { + matches!(event, RoomEvent::ParticipantDisconnected(p) if p.identity().as_str() == USER) + }) + .await?; + eventually("the final state", || current(session) == SessionState::default()).await?; + 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 +} + +#[tokio::test(flavor = "multi_thread")] +async fn dropping_a_start_during_the_microphone_publish_closes_the_room() -> Result<()> { + let Some(_probe) = microphone_probe() else { + return Ok(()); + }; + let env = TestEnv::new(); + let (_observer, mut observer_events) = env.join_observer().await?; + let baseline_tasks = tokio::runtime::Handle::current().metrics().num_alive_tasks(); + let session = Session::new(env.unpublishable_user_source(), SessionOptions::default()); + let mut start = Box::pin(session.start()); + // The session has a room once its actor owns it, which is then publishing. + // The observer must have seen the user join by then, or the server may + // fold the join and the leave into nothing. + let publishing = async { + eventually("the actor to own the room", || session.room().is_some()).await?; + next_participant_event(&mut observer_events, |event| { + matches!(event, RoomEvent::ParticipantConnected(p) if p.identity().as_str() == USER) + }) + .await + }; + tokio::select! { + result = &mut start => bail!("start resolved during the publish: {result:?}"), + publishing = publishing => publishing?, + } + + drop(start); + assert_cut_short_publish_left_nothing(&session, &mut observer_events, baseline_tasks).await +} + +#[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(); + let (_observer, mut observer_events) = env.join_observer().await?; + let baseline_tasks = tokio::runtime::Handle::current().metrics().num_alive_tasks(); + let session = Session::new(env.unpublishable_user_source(), SessionOptions::default()); + + // The client gives up on the unanswered publish after its own timeout. + let result = timeout(PUBLISH_TIMEOUT + WAIT, session.start()).await?; + assert!(matches!(result, Err(SessionStartError::Microphone(_))), "{result:?}"); + assert_eq!(current(&session), SessionState::default()); + assert!(is_idle(&session)); + assert_cut_short_publish_left_nothing(&session, &mut observer_events, baseline_tasks).await +} + // Lifecycle (AGENTS.md "Memory lifecycle") #[tokio::test(flavor = "multi_thread")] diff --git a/livekit-session/src/session.rs b/livekit-session/src/session.rs index 5fae812787..dd5cbbaf89 100644 --- a/livekit-session/src/session.rs +++ b/livekit-session/src/session.rs @@ -16,7 +16,6 @@ use std::mem; use std::sync::{Arc, Mutex}; use std::time::Duration; -use livekit::options::TrackPublishOptions; use livekit::prelude::*; use livekit::SendTextOptions; use livekit_token_source::{ @@ -176,6 +175,8 @@ pub(crate) enum Lifecycle { } pub(crate) struct Running { + /// The `start()` that spawned the actor. + generation: u64, room: Arc, /// Dropped to stop the actor. stop: mpsc::Sender<()>, @@ -201,6 +202,19 @@ impl Lifecycle { _ => 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 { @@ -266,7 +280,7 @@ impl Session { /// is connecting or connected. /// /// Dropping the future before it resolves leaves the session - /// disconnected. + /// 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) = { @@ -297,40 +311,44 @@ impl Session { _ = 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(); - // Outside the cancellable select, so that an `end` during the publish - // cannot drop a connected room without closing it; it is honoured - // below instead. - if let Some(audio) = &connection.platform_audio { - if let Err(err) = publish_microphone(&room, audio).await { - if let Err(close_err) = room.close().await { - log::warn!("failed to close the room of a failed start: {close_err}"); - } - return Err(SessionStartError::Microphone(err)); - } - } let (stop_tx, stop_rx) = mpsc::channel(1); - let mut actor = - SessionActor::new(generation, connection, stop_rx, self.inner.shared.clone()); - + 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); - if matches!(*lifecycle, Lifecycle::Starting { generation: g, .. } if g == generation) { - actor.refresh(); - let task = tokio::spawn(actor.run()); - *lifecycle = Lifecycle::Running(Running { room, stop: stop_tx, task }); - guard.armed = false; - return Ok(()); + 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 }); } - // `end` was called just as the connection completed. The room is - // closed before the actor, and the platform audio it holds, is dropped. - if let Err(err) = room.close().await { - log::warn!("failed to close the room of a cancelled start: {err}"); + // 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), } - drop(actor); - Err(SessionStartError::Cancelled) } async fn connect(&self) -> Result { @@ -443,17 +461,9 @@ impl Session { } } -/// Publishes the platform microphone as the local participant's microphone -/// track. -async fn publish_microphone(room: &Room, audio: &PlatformAudio) -> RoomResult<()> { - let track = LocalAudioTrack::create_audio_track("microphone", audio.rtc_source()); - let options = TrackPublishOptions { source: TrackSource::Microphone, ..Default::default() }; - room.local_participant().publish_track(LocalTrack::Audio(track), options).await?; - Ok(()) -} - /// Resets the session when a [`Session::start`] fails or is dropped before -/// the room is running. +/// 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, @@ -469,8 +479,12 @@ impl Drop for StartGuard<'_> { if matches!(*lifecycle, Lifecycle::Starting { generation, .. } if generation == self.generation) { *lifecycle = Lifecycle::Idle; + self.inner.shared.publish(self.generation, SessionState::default()); + return; } - self.inner.shared.publish(self.generation, SessionState::default()); + // Dropped while the actor was publishing the microphone. Dropping its + // `stop` sender stops it. + drop(lifecycle.take_running(self.generation)); } } From 527eb256bd2b9ff830cd660f8eb1007467bc0b3b Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Mon, 9 Nov 2026 11:56:40 +0000 Subject: [PATCH 39/61] agent tracks can be tracked without touching room --- livekit-session/README.md | 5 ++++- livekit-session/src/actor.rs | 10 +++++++--- livekit-session/src/agent.rs | 30 +++++++++++++++++++++++++++++ livekit-session/src/e2e_tests.rs | 33 +++++++++++++++++--------------- livekit-session/src/lib.rs | 2 +- livekit-session/src/session.rs | 19 ++++++++++++++++-- 6 files changed, 77 insertions(+), 22 deletions(-) diff --git a/livekit-session/README.md b/livekit-session/README.md index 8a3d616c94..5c9e8791f6 100644 --- a/livekit-session/README.md +++ b/livekit-session/README.md @@ -65,7 +65,10 @@ attribute. `Failed` is not final: an agent that joins, or becomes conversational code needs only the predicates on `AgentState`: `is_connected`, `is_pending` and `is_finished`. The agent's microphone and its avatar's camera are available from `agent_audio_track()` and -`agent_avatar_video_track()`, for an app that wants their frames, e.g. for a visualizer. +`agent_avatar_video_track()`, for an app that wants their frames, e.g. for a visualizer or to show +the avatar. `SessionState::agent_tracks` flags which of them are subscribed, so the state watch is +the only signal an app needs: on each change, read the tracks again and compare them by `sid`, as a +track can be replaced while its flag stays set. ## Messages diff --git a/livekit-session/src/actor.rs b/livekit-session/src/actor.rs index 5ca9fa564d..95d44d4a00 100644 --- a/livekit-session/src/actor.rs +++ b/livekit-session/src/actor.rs @@ -28,7 +28,7 @@ use livekit::{ use tokio::sync::{mpsc, oneshot, watch}; use tokio::time::Sleep; -use crate::agent::AgentTracker; +use crate::agent::{AgentTracker, AgentTracks}; use crate::constants::{TOPIC_CHAT, TOPIC_TRANSCRIPTION}; use crate::dispatcher::Dispatcher; use crate::messages::{ @@ -243,7 +243,7 @@ impl SessionActor { } } - /// Projects the agent state and publishes the session state. + /// Projects the agent state and tracks, and publishes the session state. pub(crate) fn refresh(&mut self) { let participants = self.room.remote_participants(); let agent_state = self.tracker.project(self.connection, participants.values()); @@ -252,7 +252,11 @@ impl SessionActor { } self.shared.publish( self.generation, - SessionState { connection: self.connection, agent: agent_state }, + SessionState { + connection: self.connection, + agent: agent_state, + agent_tracks: AgentTracks::project(participants.values()), + }, ); } diff --git a/livekit-session/src/agent.rs b/livekit-session/src/agent.rs index 9a8ca6bd73..32062a33b6 100644 --- a/livekit-session/src/agent.rs +++ b/livekit-session/src/agent.rs @@ -128,6 +128,36 @@ pub enum AgentFailure { Left, } +/// Which of the agent's tracks the session has subscribed. +/// +/// These are flags, not the tracks: get those from +/// [`Session::agent_audio_track`](crate::Session::agent_audio_track) and +/// [`Session::agent_avatar_video_track`](crate::Session::agent_avatar_video_track). +/// Call them again on every change of [`SessionState`](crate::SessionState), +/// not only when a flag changes: a track that is replaced, e.g. when the +/// avatar reconnects, can leave its flag `true`. Compare tracks by their +/// `sid` to find a replacement. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub struct AgentTracks { + /// The agent's microphone is subscribed. + pub audio: bool, + /// The camera of the agent's avatar is subscribed. + pub avatar_video: bool, +} + +impl AgentTracks { + /// Projects the flags from the remote participants. + pub(crate) fn project<'a>( + participants: impl IntoIterator + Clone, + ) -> Self { + Self { + audio: agent_audio_track(participants.clone()).is_some(), + avatar_video: agent_avatar_video_track(participants).is_some(), + } + } +} + /// A remote participant, as far as agent projection is concerned. pub(crate) trait AgentCandidate { fn identity(&self) -> ParticipantIdentity; diff --git a/livekit-session/src/e2e_tests.rs b/livekit-session/src/e2e_tests.rs index afa25cb265..3d5ff884a8 100644 --- a/livekit-session/src/e2e_tests.rs +++ b/livekit-session/src/e2e_tests.rs @@ -534,19 +534,6 @@ fn is_subscribed(session: &Session, sid: &TrackSid) -> bool { .any(|p| p.track_publications().get(sid).is_some_and(|p| p.is_subscribed())) } -async fn eventually_some(what: &str, mut poll: impl FnMut() -> Option) -> Result { - timeout(WAIT, async { - loop { - if let Some(value) = poll() { - return value; - } - sleep(Duration::from_millis(20)).await; - } - }) - .await - .map_err(|_| anyhow!("timed out waiting for {what}")) -} - #[tokio::test(flavor = "multi_thread")] async fn agent_audio_track_is_the_agents_microphone_once_subscribed() -> Result<()> { let env = TestEnv::new(); @@ -562,13 +549,20 @@ async fn agent_audio_track_is_the_agents_microphone_once_subscribed() -> Result< eventually("the screen share audio to be subscribed", || is_subscribed(&session, &other.sid())) .await?; assert!(session.agent_audio_track().is_none()); + assert!(!current(&session).agent_tracks.audio); let microphone = publish_audio(&agent, TrackSource::Microphone).await?; - let track = eventually_some("the agent's microphone", || session.agent_audio_track()).await?; + wait_for(&session, "the agent's audio flag", |s| s.agent_tracks.audio).await?; + let track = session.agent_audio_track().ok_or_else(|| anyhow!("flag set, track missing"))?; assert_eq!(track.sid(), microphone.sid()); + agent.local_participant().unpublish_track(µphone.sid()).await?; + wait_for(&session, "the agent's audio flag to clear", |s| !s.agent_tracks.audio).await?; + assert!(session.agent_audio_track().is_none()); + session.end().await; assert!(session.agent_audio_track().is_none()); + assert_eq!(current(&session).agent_tracks, AgentTracks::default()); Ok(()) } @@ -588,21 +582,30 @@ async fn agent_avatar_video_track_is_the_avatar_workers_camera_once_subscribed() }) .await?; assert!(session.agent_avatar_video_track().is_none()); + assert!(!current(&session).agent_tracks.avatar_video); let (avatar, _avatar_events) = env.join_avatar_worker(AVATAR, AGENT).await?; let camera = publish_video(&avatar, TrackSource::Camera).await?; + wait_for(&session, "the avatar's video flag", |s| s.agent_tracks.avatar_video).await?; let track = - eventually_some("the avatar's camera", || session.agent_avatar_video_track()).await?; + session.agent_avatar_video_track().ok_or_else(|| anyhow!("flag set, track missing"))?; assert_eq!(track.sid(), camera.sid()); assert!(session.agent_audio_track().is_none()); + assert!(!current(&session).agent_tracks.audio); // 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, AgentState::Connected(AgentActivity::Speaking)).await?; + avatar.local_participant().unpublish_track(&camera.sid()).await?; + wait_for(&session, "the avatar's video flag to clear", |s| !s.agent_tracks.avatar_video) + .await?; + assert!(session.agent_avatar_video_track().is_none()); + session.end().await; assert!(session.agent_avatar_video_track().is_none()); + assert_eq!(current(&session).agent_tracks, AgentTracks::default()); Ok(()) } diff --git a/livekit-session/src/lib.rs b/livekit-session/src/lib.rs index ba8b46a623..e3c5ab2376 100644 --- a/livekit-session/src/lib.rs +++ b/livekit-session/src/lib.rs @@ -30,7 +30,7 @@ mod session; #[cfg(all(test, feature = "__lk-e2e-test"))] mod e2e_tests; -pub use agent::{AgentActivity, AgentFailure, AgentState}; +pub use agent::{AgentActivity, AgentFailure, AgentState, AgentTracks}; pub use error::{MessageSendError, SessionStartError}; pub use messages::{Message, MessageOrigin}; pub use session::{Session, SessionConnectionState, SessionEvent, SessionOptions, SessionState}; diff --git a/livekit-session/src/session.rs b/livekit-session/src/session.rs index dd5cbbaf89..5931d78644 100644 --- a/livekit-session/src/session.rs +++ b/livekit-session/src/session.rs @@ -26,7 +26,7 @@ use tokio::sync::{mpsc, oneshot, watch}; use tokio::task::JoinHandle; use crate::actor::{lock, Connection, SessionActor, Shared}; -use crate::agent::{self, AgentState}; +use crate::agent::{self, AgentState, AgentTracks}; use crate::constants::{DEFAULT_AGENT_CONNECT_TIMEOUT, TOPIC_CHAT}; use crate::error::{MessageSendError, SessionStartError}; use crate::messages::{Message, MessageOrigin, MessageUpdate}; @@ -291,6 +291,7 @@ impl Session { let generation = self.inner.shared.begin(SessionState { connection: SessionConnectionState::Connecting, agent: AgentState::Connecting, + agent_tracks: AgentTracks::default(), }); let starting = Lifecycle::Starting { generation, cancel: cancel_tx }; let stale = match mem::replace(&mut *lifecycle, starting) { @@ -410,6 +411,10 @@ impl Session { } /// The agent's microphone track, once subscribed. + /// + /// [`AgentTracks::audio`] in [`SessionState::agent_tracks`] tells when + /// this changes. It can still return `None` after the flag is set, if the + /// track went away in between. pub fn agent_audio_track(&self) -> Option { let room = self.room()?; agent::agent_audio_track(room.remote_participants().values()) @@ -417,6 +422,10 @@ impl Session { /// The camera track of the agent's avatar, once subscribed. An avatar is a /// separate participant publishing on the agent's behalf. + /// + /// [`AgentTracks::avatar_video`] in [`SessionState::agent_tracks`] tells + /// when this changes. It can still return `None` after the flag is set, if + /// the track went away in between. pub fn agent_avatar_video_track(&self) -> Option { let room = self.room()?; agent::agent_avatar_video_track(room.remote_participants().values()) @@ -517,11 +526,17 @@ pub struct SessionState { pub connection: SessionConnectionState, /// What the agent is doing. pub agent: AgentState, + /// Which of the agent's tracks are subscribed. + pub agent_tracks: AgentTracks, } impl Default for SessionState { fn default() -> Self { - Self { connection: SessionConnectionState::Disconnected, agent: AgentState::Disconnected } + Self { + connection: SessionConnectionState::Disconnected, + agent: AgentState::Disconnected, + agent_tracks: AgentTracks::default(), + } } } From 15cb834b9003eb629a27e91b1b96aead9750a1e8 Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Mon, 9 Nov 2026 12:54:42 +0000 Subject: [PATCH 40/61] Session options are now private --- .changeset/add_livekit_session_crate.md | 2 +- livekit-session/README.md | 2 +- livekit-session/src/agent.rs | 2 +- livekit-session/src/e2e_tests.rs | 30 +++++++------ livekit-session/src/error.rs | 3 +- livekit-session/src/session.rs | 58 ++++++++++++------------- 6 files changed, 48 insertions(+), 49 deletions(-) diff --git a/.changeset/add_livekit_session_crate.md b/.changeset/add_livekit_session_crate.md index a25c3917d9..1fd12159b3 100644 --- a/.changeset/add_livekit_session_crate.md +++ b/.changeset/add_livekit_session_crate.md @@ -2,4 +2,4 @@ livekit-session: patch --- -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::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. +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/livekit-session/README.md b/livekit-session/README.md index 5c9e8791f6..1ee9c24fea 100644 --- a/livekit-session/README.md +++ b/livekit-session/README.md @@ -91,6 +91,6 @@ conversation. 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::platform_audio` turns this off, for a conversation by text alone + 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/agent.rs b/livekit-session/src/agent.rs index 32062a33b6..802b40fe36 100644 --- a/livekit-session/src/agent.rs +++ b/livekit-session/src/agent.rs @@ -122,7 +122,7 @@ impl AgentActivity { #[non_exhaustive] pub enum AgentFailure { /// No agent became conversational within - /// [`SessionOptions::agent_connect_timeout`](crate::SessionOptions::agent_connect_timeout). + /// [`SessionOptions::with_agent_connect_timeout`](crate::SessionOptions::with_agent_connect_timeout). Timeout, /// The agent left the room while the session stayed connected. Left, diff --git a/livekit-session/src/e2e_tests.rs b/livekit-session/src/e2e_tests.rs index 3d5ff884a8..2470eb0904 100644 --- a/livekit-session/src/e2e_tests.rs +++ b/livekit-session/src/e2e_tests.rs @@ -217,6 +217,13 @@ fn text_options() -> SessionOptions { SessionOptions::default().with_platform_audio(false) } +/// [`text_options`] for a room that gives up after its first failed join. +fn text_options_without_retries() -> SessionOptions { + let mut room_options = RoomOptions::default(); + room_options.join_retries = 0; + text_options().with_room_options(room_options) +} + /// The machine's audio devices, or `None` when it has no microphone to /// publish, logging that the test is skipped. fn microphone_probe() -> Option { @@ -337,8 +344,7 @@ async fn full_reconnect_does_not_report_left() -> Result<()> { #[tokio::test(flavor = "multi_thread")] async fn timeout_fires_without_an_agent_and_a_late_agent_recovers() -> Result<()> { let env = TestEnv::new(); - let options = - SessionOptions { agent_connect_timeout: Duration::from_millis(500), ..text_options() }; + let options = text_options().with_agent_connect_timeout(Duration::from_millis(500)); let session = Session::new(env.user_source(true), options); session.start().await?; wait_for_agent(&session, AgentState::Failed(AgentFailure::Timeout)).await?; @@ -352,8 +358,7 @@ async fn timeout_fires_without_an_agent_and_a_late_agent_recovers() -> Result<() #[tokio::test(flavor = "multi_thread")] async fn timeout_is_armed_without_dispatch() -> Result<()> { let env = TestEnv::new(); - let options = - SessionOptions { agent_connect_timeout: Duration::from_millis(500), ..text_options() }; + let options = text_options().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(env.user_source(false), options); @@ -366,8 +371,7 @@ async fn timeout_is_armed_without_dispatch() -> Result<()> { #[tokio::test(flavor = "multi_thread")] async fn timeout_fires_for_an_agent_stuck_initializing() -> Result<()> { let env = TestEnv::new(); - let options = - SessionOptions { agent_connect_timeout: Duration::from_millis(500), ..text_options() }; + let options = text_options().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(env.user_source(true), options); @@ -640,8 +644,7 @@ async fn restarting_after_a_server_side_disconnect() -> Result<()> { #[tokio::test(flavor = "multi_thread")] async fn a_rejected_token_fails_the_start() -> Result<()> { let env = TestEnv::new(); - let mut options = text_options(); - options.room_options.join_retries = 0; + let options = text_options_without_retries(); let session = Session::new(literal(env.url.clone(), "not a token"), options); assert!(matches!(session.start().await, Err(SessionStartError::Connect(_)))); assert_eq!(current(&session), SessionState::default()); @@ -714,11 +717,11 @@ impl SilentServer { /// Options for a session connecting to this server. fn session_options() -> SessionOptions { - let mut options = text_options(); - options.room_options.join_retries = 0; + let mut room_options = RoomOptions::default(); + room_options.join_retries = 0; // Long enough that only a cancel can end the handshake. - options.room_options.connect_timeout = Duration::from_secs(60); - options + room_options.connect_timeout = Duration::from_secs(60); + text_options().with_room_options(room_options) } } @@ -944,8 +947,7 @@ async fn failed_starts_spawn_nothing() -> Result<()> { assert_eq!(weak_shared(&session).strong_count(), 1); let env = TestEnv::new(); - let mut options = text_options(); - options.room_options.join_retries = 0; + let options = text_options_without_retries(); let session = Session::new(literal("ws://127.0.0.1:1", env.token(USER, |t| t)), options); assert!(matches!(session.start().await, Err(SessionStartError::Connect(_)))); assert_eq!(current(&session), SessionState::default()); diff --git a/livekit-session/src/error.rs b/livekit-session/src/error.rs index a5b16727ad..b0bfb2695b 100644 --- a/livekit-session/src/error.rs +++ b/livekit-session/src/error.rs @@ -34,7 +34,8 @@ pub enum SessionStartError { #[error("failed to connect: {0}")] Connect(#[from] RoomError), /// Platform audio could not be started, e.g. on a machine without audio - /// devices. See [`SessionOptions::platform_audio`](crate::SessionOptions::platform_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. diff --git a/livekit-session/src/session.rs b/livekit-session/src/session.rs index 5931d78644..2251c1fac0 100644 --- a/livekit-session/src/session.rs +++ b/livekit-session/src/session.rs @@ -50,34 +50,12 @@ impl SessionTokenSource { } } -/// Options for a [`Session`]. +/// Options for a [`Session`], set through the `with_*` methods. #[derive(Clone, Debug)] -#[non_exhaustive] pub struct SessionOptions { - /// 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 agent_connect_timeout: Duration, - /// Options for the session's room, including - /// [`encryption`](RoomOptions::encryption), which can be toggled once - /// connected through [`Session::room`]. - pub room_options: RoomOptions, - /// 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 platform_audio: bool, + agent_connect_timeout: Duration, + room_options: RoomOptions, + platform_audio: bool, } impl Default for SessionOptions { @@ -91,19 +69,37 @@ impl Default for SessionOptions { } impl SessionOptions { - /// Sets [`agent_connect_timeout`](Self::agent_connect_timeout). + /// 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 [`room_options`](Self::room_options). + /// 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 [`platform_audio`](Self::platform_audio). + /// 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 @@ -136,7 +132,7 @@ pub enum SessionEvent { /// /// 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::platform_audio`] turns +/// 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 @@ -272,7 +268,7 @@ impl Session { } /// Fetches credentials, connects the room, and publishes the microphone - /// (see [`SessionOptions::platform_audio`]). + /// (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 From 20f290c922215e6edf1f480bfac48ebd1232a878 Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Mon, 9 Nov 2026 13:23:49 +0000 Subject: [PATCH 41/61] Documented that sids should be compared on state changeds --- livekit-session/README.md | 6 +++--- livekit-session/src/agent.rs | 7 +++---- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/livekit-session/README.md b/livekit-session/README.md index 1ee9c24fea..eafe375e43 100644 --- a/livekit-session/README.md +++ b/livekit-session/README.md @@ -66,9 +66,9 @@ code needs only the predicates on `AgentState`: `is_connected`, `is_pending` and The agent's microphone and its avatar's camera are available from `agent_audio_track()` and `agent_avatar_video_track()`, for an app that wants their frames, e.g. for a visualizer or to show -the avatar. `SessionState::agent_tracks` flags which of them are subscribed, so the state watch is -the only signal an app needs: on each change, read the tracks again and compare them by `sid`, as a -track can be replaced while its flag stays set. +the avatar. `SessionState::agent_tracks` flags which of them are subscribed: read the tracks again +when a flag changes. In edge cases, e.g. an avatar reconnecting, a track can be replaced without its +flag changing, so compare tracks by `sid` whenever you read them. ## Messages diff --git a/livekit-session/src/agent.rs b/livekit-session/src/agent.rs index 802b40fe36..cb3fdb5381 100644 --- a/livekit-session/src/agent.rs +++ b/livekit-session/src/agent.rs @@ -133,10 +133,9 @@ pub enum AgentFailure { /// These are flags, not the tracks: get those from /// [`Session::agent_audio_track`](crate::Session::agent_audio_track) and /// [`Session::agent_avatar_video_track`](crate::Session::agent_avatar_video_track). -/// Call them again on every change of [`SessionState`](crate::SessionState), -/// not only when a flag changes: a track that is replaced, e.g. when the -/// avatar reconnects, can leave its flag `true`. Compare tracks by their -/// `sid` to find a replacement. +/// Read them again when a flag changes. In edge cases, e.g. an avatar +/// reconnecting, a track can be replaced without its flag changing, so +/// compare tracks by their `sid` whenever you read them. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] #[non_exhaustive] pub struct AgentTracks { From bcb88fd2decf9381f30f78093095148fcaf5f522 Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:08:51 +0100 Subject: [PATCH 42/61] Room connection state Disconnected maps to session connection state Disconnected --- livekit-session/src/actor.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/livekit-session/src/actor.rs b/livekit-session/src/actor.rs index 95d44d4a00..5694b81327 100644 --- a/livekit-session/src/actor.rs +++ b/livekit-session/src/actor.rs @@ -222,9 +222,8 @@ impl SessionActor { ) -> Self { let state = match connection.room.connection_state() { ConnectionState::Reconnecting => SessionConnectionState::Reconnecting, - ConnectionState::Connected | ConnectionState::Disconnected => { - SessionConnectionState::Connected - } + ConnectionState::Connected => SessionConnectionState::Connected, + ConnectionState::Disconnected => SessionConnectionState::Disconnected }; Self { generation, From cc01f835042f0cf11232a8dbf345dce560d51a6e Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:12:46 +0100 Subject: [PATCH 43/61] Making actor enums non exhaustive --- livekit-session/src/actor.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/livekit-session/src/actor.rs b/livekit-session/src/actor.rs index 5694b81327..5b45c693dc 100644 --- a/livekit-session/src/actor.rs +++ b/livekit-session/src/actor.rs @@ -143,6 +143,7 @@ pub(crate) struct Connection { } /// An incoming text stream the session reads. +#[non_exhaustive] enum ReaderEvent { TranscriptChunk(Arc, StreamResult), TranscriptEnd(Arc), @@ -160,6 +161,7 @@ struct Transcript { info: TextStreamInfo, } +#[non_exhaustive] enum Event { Stop, Room(RoomEvent), @@ -167,6 +169,7 @@ enum Event { AgentDeadline, } +#[non_exhaustive] /// How the actor stopped. enum Exit { /// [`Session::end`](crate::Session::end) was called, or every From 608ed5c8796c161e51a35a75c168da9b906b95d4 Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Wed, 18 Nov 2026 16:35:41 +0100 Subject: [PATCH 44/61] Agent is a concept that lives in the agent state holding the audio and avatar track as well as the participant identity --- examples/session/src/main.rs | 2 +- livekit-session/README.md | 35 ++- livekit-session/src/actor.rs | 24 +- livekit-session/src/agent.rs | 401 +++++++++++++++++++++---------- livekit-session/src/e2e_tests.rs | 146 +++++++---- livekit-session/src/lib.rs | 2 +- livekit-session/src/session.rs | 39 +-- 7 files changed, 410 insertions(+), 239 deletions(-) diff --git a/examples/session/src/main.rs b/examples/session/src/main.rs index 4132d05b9f..6c8ad61a14 100644 --- a/examples/session/src/main.rs +++ b/examples/session/src/main.rs @@ -71,7 +71,7 @@ async fn main() -> Result<(), Box> { if changed.is_err() { break; } - let current = *state.borrow_and_update(); + let current = state.borrow_and_update().clone(); print_state(¤t); if !current.connection.is_connected() { break; diff --git a/livekit-session/README.md b/livekit-session/README.md index eafe375e43..d0df3e648d 100644 --- a/livekit-session/README.md +++ b/livekit-session/README.md @@ -54,21 +54,32 @@ and the agent state (`agent`): | --- | --- | | `Disconnected` | The session is not connected | | `Connecting` | No agent is in the room yet | -| `Connected(Initializing)`, `Connected(Idle)` | The agent joined but is not in a conversation | -| `Connected(Listening)`, `Connected(Thinking)`, `Connected(Speaking)` | The agent is in a conversation | -| `Connected(Unknown)` | The agent reports an activity this SDK does not recognize | -| `Failed(Timeout)` | No agent became conversational within `agent_connect_timeout` (20 s by default) of connecting | +| `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 | -`Connected` carries an `AgentActivity`, what the agent reports through its `lk.agent.state` -attribute. `Failed` is not final: an agent that joins, or becomes conversational, replaces it. Most -code needs only the predicates on `AgentState`: `is_connected`, `is_pending` and `is_finished`. +`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`. -The agent's microphone and its avatar's camera are available from `agent_audio_track()` and -`agent_avatar_video_track()`, for an app that wants their frames, e.g. for a visualizer or to show -the avatar. `SessionState::agent_tracks` flags which of them are subscribed: read the tracks again -when a flag changes. In edge cases, e.g. an avatar reconnecting, a track can be replaced without its -flag changing, so compare tracks by `sid` whenever you read them. +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 diff --git a/livekit-session/src/actor.rs b/livekit-session/src/actor.rs index 5b45c693dc..c52eb0ac3f 100644 --- a/livekit-session/src/actor.rs +++ b/livekit-session/src/actor.rs @@ -28,7 +28,7 @@ use livekit::{ use tokio::sync::{mpsc, oneshot, watch}; use tokio::time::Sleep; -use crate::agent::{AgentTracker, AgentTracks}; +use crate::agent::{Agent, AgentTracker}; use crate::constants::{TOPIC_CHAT, TOPIC_TRANSCRIPTION}; use crate::dispatcher::Dispatcher; use crate::messages::{ @@ -81,6 +81,8 @@ impl Shared { } fn set(&self, state: SessionState) { + #[cfg(test)] + lock(&self.history).push(state.clone()); self.state.send_if_modified(|current| { if *current == state { return false; @@ -88,8 +90,6 @@ impl Shared { *current = state; true }); - #[cfg(test)] - lock(&self.history).push(state); } pub(crate) fn watch(&self) -> watch::Receiver { @@ -226,7 +226,7 @@ impl SessionActor { let state = match connection.room.connection_state() { ConnectionState::Reconnecting => SessionConnectionState::Reconnecting, ConnectionState::Connected => SessionConnectionState::Connected, - ConnectionState::Disconnected => SessionConnectionState::Disconnected + ConnectionState::Disconnected => SessionConnectionState::Disconnected, }; Self { generation, @@ -245,20 +245,16 @@ impl SessionActor { } } - /// Projects the agent state and tracks, and publishes the session state. + /// Projects the agent state, and publishes the session state. pub(crate) fn refresh(&mut self) { - let participants = self.room.remote_participants(); - let agent_state = self.tracker.project(self.connection, participants.values()); + 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, - agent_tracks: AgentTracks::project(participants.values()), - }, + SessionState { connection: self.connection, agent: agent_state }, ); } @@ -462,8 +458,8 @@ impl SessionActor { fn on_agent_deadline(&mut self) { self.agent_deadline = None; - let participants = self.room.remote_participants(); - if self.tracker.time_out(self.connection, participants.values()) { + 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 index cb3fdb5381..a8c1c84305 100644 --- a/livekit-session/src/agent.rs +++ b/livekit-session/src/agent.rs @@ -23,22 +23,39 @@ 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 [`AgentActivity`] inside -/// [`Connected`](Self::Connected) answers the second. +/// 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 predicates: [`AgentState::is_connected`] to show -/// that the agent is there, [`AgentState::is_pending`] to show that it is on -/// its way, and [`AgentState::is_finished`] to show that it is gone or never -/// came. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +/// Most code needs only the methods: [`is_connected`](Self::is_connected) to +/// show that the agent is there, [`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 is in the room, doing the given activity. - Connected(AgentActivity), + /// 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 @@ -50,19 +67,22 @@ impl AgentState { /// Whether the agent is in the room and in a conversation: listening, /// thinking or speaking. /// - /// Stricter than "an agent participant exists": an agent that is still - /// [`Initializing`](AgentActivity::Initializing) is not connected. - pub fn is_connected(self) -> bool { - matches!(self, Self::Connected(activity) if activity.is_conversational()) + /// 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 an agent is expected but not yet conversational: connecting, /// initializing, or idle. - pub fn is_pending(self) -> bool { - matches!( - self, - Self::Connecting | Self::Connected(AgentActivity::Initializing | AgentActivity::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, @@ -70,11 +90,115 @@ impl AgentState { /// /// 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 { + 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)] @@ -118,50 +242,29 @@ impl AgentActivity { } /// Why an agent is [`AgentState::Failed`]. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[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). - 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. Left, } -/// Which of the agent's tracks the session has subscribed. -/// -/// These are flags, not the tracks: get those from -/// [`Session::agent_audio_track`](crate::Session::agent_audio_track) and -/// [`Session::agent_avatar_video_track`](crate::Session::agent_avatar_video_track). -/// Read them again when a flag changes. In edge cases, e.g. an avatar -/// reconnecting, a track can be replaced without its flag changing, so -/// compare tracks by their `sid` whenever you read them. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -#[non_exhaustive] -pub struct AgentTracks { - /// The agent's microphone is subscribed. - pub audio: bool, - /// The camera of the agent's avatar is subscribed. - pub avatar_video: bool, -} - -impl AgentTracks { - /// Projects the flags from the remote participants. - pub(crate) fn project<'a>( - participants: impl IntoIterator + Clone, - ) -> Self { - Self { - audio: agent_audio_track(participants.clone()).is_some(), - avatar_video: agent_avatar_video_track(participants).is_some(), - } - } -} - /// 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 { @@ -176,6 +279,24 @@ impl AgentCandidate for RemoteParticipant { 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 @@ -183,7 +304,7 @@ impl AgentCandidate for RemoteParticipant { /// /// With several agents, the lowest identity wins, so the choice does not /// change between calls. -pub(crate) fn find_agent<'a, P: AgentCandidate>( +fn find_agent<'a, P: AgentCandidate>( participants: impl IntoIterator, ) -> Option<&'a P> { participants @@ -196,7 +317,7 @@ pub(crate) fn find_agent<'a, P: AgentCandidate>( } /// Finds the avatar worker publishing on behalf of `agent`. -pub(crate) fn find_avatar_worker<'a, P: AgentCandidate>( +fn find_avatar_worker<'a, P: AgentCandidate>( participants: impl IntoIterator, agent: &ParticipantIdentity, ) -> Option<&'a P> { @@ -207,38 +328,6 @@ pub(crate) fn find_avatar_worker<'a, P: AgentCandidate>( }) } -/// The agent's microphone track, once subscribed. -pub(crate) fn agent_audio_track<'a>( - participants: impl IntoIterator, -) -> Option { - let agent = find_agent(participants)?; - agent.track_publications().into_values().find_map(|publication| { - match (publication.source(), publication.track()) { - (TrackSource::Microphone, Some(RemoteTrack::Audio(track))) => Some(track), - _ => None, - } - }) -} - -/// The camera track of the agent's avatar worker, once subscribed. -pub(crate) fn agent_avatar_video_track<'a>( - participants: impl IntoIterator + Clone, -) -> Option { - let agent = find_agent(participants.clone())?; - let worker = find_avatar_worker(participants, &agent.identity())?; - worker.track_publications().into_values().find_map(|publication| { - match (publication.source(), publication.track()) { - (TrackSource::Camera, Some(RemoteTrack::Video(track))) => Some(track), - _ => None, - } - }) -} - -/// The activity the agent reports through `lk.agent.state`. -fn activity(agent: &impl AgentCandidate) -> AgentActivity { - AgentActivity::from_attribute(agent.attributes().get(ATTRIBUTE_AGENT_STATE).map(String::as_str)) -} - /// Projects [`AgentState`] from the room, remembering what the projection /// needs across calls: whether an agent was ever seen, and whether the /// agent-connect timeout fired. @@ -251,12 +340,12 @@ pub(crate) struct AgentTracker { } impl AgentTracker { - /// Projects the agent state for the given connection state and remote - /// participants. - pub(crate) fn project<'a, P: AgentCandidate + 'a>( + /// 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, - participants: impl IntoIterator, + agent: Option, ) -> AgentState { match connection { SessionConnectionState::Disconnected => { @@ -267,51 +356,48 @@ impl AgentTracker { SessionConnectionState::Connected | SessionConnectionState::Reconnecting => {} } - let Some(agent) = find_agent(participants) else { + let Some(agent) = agent else { // A full reconnect removes every participant, so an agent missing // while reconnecting has not necessarily left. if self.has_ever_connected && connection == SessionConnectionState::Connected { return AgentState::Failed(AgentFailure::Left); } if self.timed_out == Some(None) { - return AgentState::Failed(AgentFailure::Timeout); + return AgentState::Failed(AgentFailure::Timeout { agent: None }); } return AgentState::Connecting; }; self.has_ever_connected = true; - let identity = agent.identity(); - let activity = activity(agent); - if activity.is_conversational() { + if agent.activity.is_conversational() { self.timed_out = None; - return AgentState::Connected(activity); + 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 == identity => { - AgentState::Failed(AgentFailure::Timeout) + Some(Some(timed_out)) if *timed_out == agent.identity => { + AgentState::Failed(AgentFailure::Timeout { agent: Some(agent) }) } - _ => AgentState::Connected(activity), + _ => 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<'a, P: AgentCandidate + 'a>( + pub(crate) fn time_out( &mut self, connection: SessionConnectionState, - participants: impl IntoIterator, + agent: Option<&Agent>, ) -> bool { if !connection.is_connected() { return false; } - let agent = find_agent(participants); - if agent.is_some_and(|agent| activity(agent).is_conversational()) { + if agent.is_some_and(|agent| agent.activity.is_conversational()) { return false; } - self.timed_out = Some(agent.map(|agent| agent.identity())); + self.timed_out = Some(agent.map(|agent| agent.identity.clone())); true } } @@ -352,6 +438,14 @@ mod tests { } 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() } @@ -366,13 +460,45 @@ mod tests { } fn project(tracker: &mut AgentTracker, participants: &[Fake]) -> AgentState { - tracker.project(Connected, participants) + 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::Connected(activity) + AgentState::Joined(agent("agent", activity)) } + fn timed_out(agent: Option) -> AgentState { + AgentState::Failed(AgentFailure::Timeout { agent }) + } + + const LEFT: AgentState = AgentState::Failed(AgentFailure::Left); + #[test] fn attribute_values_map_to_states() { let mut tracker = AgentTracker::default(); @@ -422,9 +548,9 @@ mod tests { fn session_state_takes_precedence() { let mut tracker = AgentTracker::default(); let participants = [Fake::agent("agent", Some("speaking"))]; - assert_eq!(tracker.project(Disconnected, &participants), AgentState::Disconnected); - assert_eq!(tracker.project(Connecting, &participants), AgentState::Connecting); - assert_eq!(tracker.project(Reconnecting, &participants), connected(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] @@ -432,16 +558,16 @@ mod tests { 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), AgentState::Failed(AgentFailure::Left)); + assert_eq!(project(&mut tracker, NO_ONE), LEFT); } #[test] fn agent_missing_while_reconnecting_is_not_left() { let mut tracker = AgentTracker::default(); project(&mut tracker, &[Fake::agent("agent", Some("listening"))]); - assert_eq!(tracker.project(Reconnecting, NO_ONE), AgentState::Connecting); + assert_eq!(project_in(&mut tracker, Reconnecting, NO_ONE), AgentState::Connecting); assert_eq!( - tracker.project(Reconnecting, &[Fake::agent("agent", Some("listening"))]), + project_in(&mut tracker, Reconnecting, &[Fake::agent("agent", Some("listening"))]), connected(Listening) ); } @@ -450,10 +576,10 @@ mod tests { 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), AgentState::Failed(AgentFailure::Left)); + assert_eq!(project(&mut tracker, NO_ONE), LEFT); assert_eq!( project(&mut tracker, &[Fake::agent("agent-2", Some("initializing"))]), - connected(Initializing) + AgentState::Joined(agent("agent-2", Initializing)) ); } @@ -461,16 +587,16 @@ mod tests { fn disconnect_resets_has_ever_connected() { let mut tracker = AgentTracker::default(); project(&mut tracker, &[Fake::agent("agent", Some("listening"))]); - tracker.project(Disconnected, NO_ONE); - assert_eq!(tracker.project(Connecting, NO_ONE), AgentState::Connecting); + 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!(tracker.time_out(Connected, NO_ONE)); - assert_eq!(project(&mut tracker, NO_ONE), AgentState::Failed(AgentFailure::Timeout)); + 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) @@ -481,8 +607,9 @@ mod tests { fn timeout_with_initializing_agent_fails_until_it_is_conversational() { let mut tracker = AgentTracker::default(); let stuck = [Fake::agent("agent", Some("initializing"))]; - assert!(tracker.time_out(Connected, &stuck)); - assert_eq!(project(&mut tracker, &stuck), AgentState::Failed(AgentFailure::Timeout)); + 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) @@ -494,9 +621,9 @@ mod tests { #[test] fn timeout_does_not_count_once_conversational_or_disconnected() { let mut tracker = AgentTracker::default(); - assert!(!tracker.time_out(Connected, &[Fake::agent("agent", Some("speaking"))])); - assert!(!tracker.time_out(Connecting, NO_ONE)); - assert!(!tracker.time_out(Disconnected, NO_ONE)); + 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); } @@ -511,21 +638,23 @@ mod tests { connected(Thinking), connected(Speaking), connected(Unknown), - AgentState::Failed(AgentFailure::Timeout), - AgentState::Failed(AgentFailure::Left), + timed_out(None), + timed_out(Some(agent("agent", Initializing))), + LEFT, ]; - for state in states { + for state in &states { + let activity = state.activity(); assert_eq!( state.is_connected(), - matches!(state, AgentState::Connected(Listening | Thinking | Speaking)), + matches!(state, AgentState::Joined(_)) + && matches!(activity, Some(Listening | Thinking | Speaking)), "{state:?}" ); assert_eq!( state.is_pending(), - matches!( - state, - AgentState::Connecting | AgentState::Connected(Initializing | Idle) - ), + matches!(state, AgentState::Connecting) + || matches!(state, AgentState::Joined(_)) + && matches!(activity, Some(Initializing | Idle)), "{state:?}" ); assert_eq!( @@ -537,4 +666,18 @@ mod tests { 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/e2e_tests.rs b/livekit-session/src/e2e_tests.rs index 2470eb0904..5dd7a34e97 100644 --- a/livekit-session/src/e2e_tests.rs +++ b/livekit-session/src/e2e_tests.rs @@ -182,11 +182,35 @@ async fn wait_for( let reached = timeout(WAIT, state.wait_for(predicate)) .await .map_err(|_| anyhow!("timed out waiting for {what}; last {:?}", current(session)))??; - Ok(*reached) + Ok(reached.clone()) } -async fn wait_for_agent(session: &Session, agent_state: AgentState) -> Result<()> { - wait_for(session, &format!("{agent_state:?}"), |s| s.agent == agent_state).await?; +/// What a test expects of the agent state, without the agent's tracks. +#[derive(Clone, Copy, Debug)] +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`]. + Left, +} + +impl Expect { + 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)) => true, + _ => false, + } + } +} + +async fn wait_for_agent(session: &Session, expect: Expect) -> Result<()> { + wait_for(session, &format!("{expect:?}"), |s| expect.matches(&s.agent)).await?; Ok(()) } @@ -209,7 +233,7 @@ fn is_idle(session: &Session) -> bool { } fn current(session: &Session) -> SessionState { - *session.state().borrow() + session.state().borrow().clone() } /// Options for a session that stays off the machine's audio devices. @@ -254,16 +278,15 @@ async fn start_projects_the_agent_and_end_disconnects() -> Result<()> { 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).ok() }, - ); + 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_eq!(connected.agent, AgentState::Connected(AgentActivity::Listening)); + assert!(Expect::Joined(AgentActivity::Listening).matches(&connected.agent)); set_agent_state(&agent, "speaking").await?; - wait_for_agent(&session, AgentState::Connected(AgentActivity::Speaking)).await?; + wait_for_agent(&session, Expect::Joined(AgentActivity::Speaking)).await?; session.end().await; assert_eq!(current(&session), SessionState::default()); @@ -303,10 +326,10 @@ async fn agent_leaving_is_reported_as_left() -> Result<()> { let session = Session::new(env.user_source(false), text_options()); session.start().await?; let (agent, _agent_events) = env.join_agent(AGENT, "listening").await?; - wait_for_agent(&session, AgentState::Connected(AgentActivity::Listening)).await?; + wait_for_agent(&session, Expect::Joined(AgentActivity::Listening)).await?; agent.close().await?; - wait_for_agent(&session, AgentState::Failed(AgentFailure::Left)).await?; + wait_for_agent(&session, Expect::Left).await?; session.end().await; Ok(()) } @@ -317,7 +340,7 @@ async fn full_reconnect_does_not_report_left() -> Result<()> { let session = Session::new(env.user_source(false), text_options()); session.start().await?; let (_agent, _agent_events) = env.join_agent(AGENT, "listening").await?; - wait_for_agent(&session, AgentState::Connected(AgentActivity::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"))?; @@ -327,14 +350,14 @@ async fn full_reconnect_does_not_report_left() -> Result<()> { history.iter().any(|s| s.connection == SessionConnectionState::Reconnecting) && history.last().is_some_and(|s| { s.connection == SessionConnectionState::Connected - && s.agent == AgentState::Connected(AgentActivity::Listening) + && Expect::Joined(AgentActivity::Listening).matches(&s.agent) }) }) .await?; let history = lock(&session.inner.shared.history).clone(); assert!( - !history.iter().any(|s| s.agent == AgentState::Failed(AgentFailure::Left)), + !history.iter().any(|s| Expect::Left.matches(&s.agent)), "a full reconnect was reported as the agent leaving: {history:?}" ); session.end().await; @@ -347,10 +370,10 @@ async fn timeout_fires_without_an_agent_and_a_late_agent_recovers() -> Result<() let options = text_options().with_agent_connect_timeout(Duration::from_millis(500)); let session = Session::new(env.user_source(true), options); session.start().await?; - wait_for_agent(&session, AgentState::Failed(AgentFailure::Timeout)).await?; + wait_for_agent(&session, Expect::TimedOut).await?; let (_agent, _agent_events) = env.join_agent(AGENT, "listening").await?; - wait_for_agent(&session, AgentState::Connected(AgentActivity::Listening)).await?; + wait_for_agent(&session, Expect::Joined(AgentActivity::Listening)).await?; session.end().await; Ok(()) } @@ -363,7 +386,7 @@ async fn timeout_is_armed_without_dispatch() -> Result<()> { // token naming none still waits for one. let session = Session::new(env.user_source(false), options); session.start().await?; - wait_for_agent(&session, AgentState::Failed(AgentFailure::Timeout)).await?; + wait_for_agent(&session, Expect::TimedOut).await?; session.end().await; Ok(()) } @@ -376,10 +399,10 @@ async fn timeout_fires_for_an_agent_stuck_initializing() -> Result<()> { let (agent, _agent_events) = env.join_agent(AGENT, "initializing").await?; let session = Session::new(env.user_source(true), options); session.start().await?; - wait_for_agent(&session, AgentState::Failed(AgentFailure::Timeout)).await?; + wait_for_agent(&session, Expect::TimedOut).await?; set_agent_state(&agent, "listening").await?; - wait_for_agent(&session, AgentState::Connected(AgentActivity::Listening)).await?; + wait_for_agent(&session, Expect::Joined(AgentActivity::Listening)).await?; session.end().await; Ok(()) } @@ -408,7 +431,7 @@ async fn messages_merge_chat_and_transcripts() -> Result<()> { let mut events = session.subscribe(); session.start().await?; let (agent, mut agent_events) = env.join_agent(AGENT, "listening").await?; - wait_for_agent(&session, AgentState::Connected(AgentActivity::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?; @@ -483,7 +506,7 @@ async fn streams_on_other_topics_are_left_to_the_app() -> Result<()> { 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, AgentState::Connected(AgentActivity::Listening)).await?; + wait_for_agent(&session, Expect::Joined(AgentActivity::Listening)).await?; agent .local_participant() @@ -542,31 +565,33 @@ fn is_subscribed(session: &Session, sid: &TrackSid) -> bool { async fn agent_audio_track_is_the_agents_microphone_once_subscribed() -> Result<()> { let env = TestEnv::new(); let session = Session::new(env.user_source(false), text_options()); - assert!(session.agent_audio_track().is_none()); + 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, AgentState::Connected(AgentActivity::Listening)).await?; - assert!(session.agent_audio_track().is_none()); + 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!(session.agent_audio_track().is_none()); - assert!(!current(&session).agent_tracks.audio); + assert!(current(&session).agent.audio_track().is_none()); let microphone = publish_audio(&agent, TrackSource::Microphone).await?; - wait_for(&session, "the agent's audio flag", |s| s.agent_tracks.audio).await?; - let track = session.agent_audio_track().ok_or_else(|| anyhow!("flag set, track missing"))?; - assert_eq!(track.sid(), microphone.sid()); + 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 flag to clear", |s| !s.agent_tracks.audio).await?; - assert!(session.agent_audio_track().is_none()); + wait_for(&session, "the agent's audio track to go", |s| s.agent.audio_track().is_none()) + .await?; session.end().await; - assert!(session.agent_audio_track().is_none()); - assert_eq!(current(&session).agent_tracks, AgentTracks::default()); + assert_eq!(current(&session), SessionState::default()); Ok(()) } @@ -576,8 +601,8 @@ async fn agent_avatar_video_track_is_the_avatar_workers_camera_once_subscribed() let session = Session::new(env.user_source(false), text_options()); session.start().await?; let (agent, _agent_events) = env.join_agent(AGENT, "listening").await?; - wait_for_agent(&session, AgentState::Connected(AgentActivity::Listening)).await?; - assert!(session.agent_avatar_video_track().is_none()); + 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?; @@ -585,31 +610,52 @@ async fn agent_avatar_video_track_is_the_avatar_workers_camera_once_subscribed() is_subscribed(&session, &agent_camera.sid()) }) .await?; - assert!(session.agent_avatar_video_track().is_none()); - assert!(!current(&session).agent_tracks.avatar_video); + 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?; - wait_for(&session, "the avatar's video flag", |s| s.agent_tracks.avatar_video).await?; - let track = - session.agent_avatar_video_track().ok_or_else(|| anyhow!("flag set, track missing"))?; - assert_eq!(track.sid(), camera.sid()); - assert!(session.agent_audio_track().is_none()); - assert!(!current(&session).agent_tracks.audio); + 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, AgentState::Connected(AgentActivity::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 flag to clear", |s| !s.agent_tracks.avatar_video) - .await?; - assert!(session.agent_avatar_video_track().is_none()); + 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().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(env.user_source(true), 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; - assert!(session.agent_avatar_video_track().is_none()); - assert_eq!(current(&session).agent_tracks, AgentTracks::default()); Ok(()) } diff --git a/livekit-session/src/lib.rs b/livekit-session/src/lib.rs index e3c5ab2376..0dd978531f 100644 --- a/livekit-session/src/lib.rs +++ b/livekit-session/src/lib.rs @@ -30,7 +30,7 @@ mod session; #[cfg(all(test, feature = "__lk-e2e-test"))] mod e2e_tests; -pub use agent::{AgentActivity, AgentFailure, AgentState, AgentTracks}; +pub use agent::{Agent, AgentActivity, AgentFailure, AgentState}; pub use error::{MessageSendError, SessionStartError}; pub use messages::{Message, MessageOrigin}; pub use session::{Session, SessionConnectionState, SessionEvent, SessionOptions, SessionState}; diff --git a/livekit-session/src/session.rs b/livekit-session/src/session.rs index 2251c1fac0..27e681a1eb 100644 --- a/livekit-session/src/session.rs +++ b/livekit-session/src/session.rs @@ -26,7 +26,7 @@ use tokio::sync::{mpsc, oneshot, watch}; use tokio::task::JoinHandle; use crate::actor::{lock, Connection, SessionActor, Shared}; -use crate::agent::{self, AgentState, AgentTracks}; +use crate::agent::AgentState; use crate::constants::{DEFAULT_AGENT_CONNECT_TIMEOUT, TOPIC_CHAT}; use crate::error::{MessageSendError, SessionStartError}; use crate::messages::{Message, MessageOrigin, MessageUpdate}; @@ -287,7 +287,6 @@ impl Session { let generation = self.inner.shared.begin(SessionState { connection: SessionConnectionState::Connecting, agent: AgentState::Connecting, - agent_tracks: AgentTracks::default(), }); let starting = Lifecycle::Starting { generation, cancel: cancel_tx }; let stale = match mem::replace(&mut *lifecycle, starting) { @@ -406,27 +405,6 @@ impl Session { lock(&self.inner.lifecycle).room().cloned() } - /// The agent's microphone track, once subscribed. - /// - /// [`AgentTracks::audio`] in [`SessionState::agent_tracks`] tells when - /// this changes. It can still return `None` after the flag is set, if the - /// track went away in between. - pub fn agent_audio_track(&self) -> Option { - let room = self.room()?; - agent::agent_audio_track(room.remote_participants().values()) - } - - /// The camera track of the agent's avatar, once subscribed. An avatar is a - /// separate participant publishing on the agent's behalf. - /// - /// [`AgentTracks::avatar_video`] in [`SessionState::agent_tracks`] tells - /// when this changes. It can still return `None` after the flag is set, if - /// the track went away in between. - pub fn agent_avatar_video_track(&self) -> Option { - let room = self.room()?; - agent::agent_avatar_video_track(room.remote_participants().values()) - } - /// 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 { @@ -515,24 +493,21 @@ impl SessionConnectionState { } /// The observable state of a [`Session`] at one point in time. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +/// +/// 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, - /// What the agent is doing. + /// Whether the agent is there, what it is doing, and its tracks. pub agent: AgentState, - /// Which of the agent's tracks are subscribed. - pub agent_tracks: AgentTracks, } impl Default for SessionState { fn default() -> Self { - Self { - connection: SessionConnectionState::Disconnected, - agent: AgentState::Disconnected, - agent_tracks: AgentTracks::default(), - } + Self { connection: SessionConnectionState::Disconnected, agent: AgentState::Disconnected } } } From b8dada04a135f6e059004c48f586b3130c5076ad Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Wed, 18 Nov 2026 16:39:33 +0100 Subject: [PATCH 45/61] Use clap for example --- Cargo.lock | 1 + examples/session/Cargo.toml | 1 + examples/session/README.md | 3 +++ examples/session/src/main.rs | 45 ++++++++++++++++++++++++++++-------- 4 files changed, 41 insertions(+), 9 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index cb8be6bdd2..bb8a3e5481 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6874,6 +6874,7 @@ dependencies = [ name = "session" version = "0.1.0" dependencies = [ + "clap", "env_logger 0.11.11", "livekit-session", "livekit-token-source", diff --git a/examples/session/Cargo.toml b/examples/session/Cargo.toml index 283bbec04a..020e9d2fd5 100644 --- a/examples/session/Cargo.toml +++ b/examples/session/Cargo.toml @@ -5,6 +5,7 @@ edition.workspace = true publish = false [dependencies] +clap = { workspace = true, features = ["derive", "env"] } env_logger = { workspace = true } livekit-session = { workspace = true, features = ["rustls-tls-native-roots"] } livekit-token-source = { workspace = true } diff --git a/examples/session/README.md b/examples/session/README.md index 3b7a89870f..432970b19f 100644 --- a/examples/session/README.md +++ b/examples/session/README.md @@ -18,6 +18,9 @@ Or from a pre-generated token, whose room configuration dispatches the agent: 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. diff --git a/examples/session/src/main.rs b/examples/session/src/main.rs index 6c8ad61a14..8200d5fec4 100644 --- a/examples/session/src/main.rs +++ b/examples/session/src/main.rs @@ -1,6 +1,7 @@ use std::error::Error; -use std::{env, time::Duration}; +use std::time::Duration; +use clap::Parser; use livekit_session::{ Message, MessageOrigin, Session, SessionEvent, SessionOptions, SessionState, }; @@ -8,16 +9,42 @@ use livekit_session::{ 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 a session with credentials from a pre-generated token if one is /// given, and from a development token server otherwise. -fn create_session(options: SessionOptions) -> Result> { - if let (Ok(url), Ok(token)) = (env::var("LIVEKIT_URL"), env::var("LIVEKIT_TOKEN")) { +fn create_session(args: Args, options: SessionOptions) -> Result> { + if let (Some(url), Some(token)) = (args.url, args.token) { return Ok(Session::new(literal(url, token), options)); } - let token_server_id = env::var("LIVEKIT_TOKEN_SERVER_ID") - .map_err(|_| "set LIVEKIT_TOKEN_SERVER_ID, or LIVEKIT_URL and LIVEKIT_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 Ok(agent_name) = env::var("LIVEKIT_AGENT_NAME") { + if let Some(agent_name) = args.agent_name { fetch_options = fetch_options.with_agent_name(agent_name); } Ok(Session::with_fetch_options( @@ -49,15 +76,15 @@ fn print_state(state: &SessionState) { #[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_only = env::args().any(|arg| arg == "--text"); let session_options = SessionOptions::default() .with_agent_connect_timeout(Duration::from_secs(15)) - .with_platform_audio(!text_only); - let session = create_session(session_options)?; + .with_platform_audio(!args.text); + let session = create_session(args, session_options)?; let mut events = session.subscribe(); session.start().await?; From 4c38411f714234d2dbb27bad33b146ceb663052f Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Wed, 18 Nov 2026 17:15:44 +0100 Subject: [PATCH 46/61] Debug on Session Fix test after debug session reorder --- examples/session/src/main.rs | 4 +-- livekit-session/src/actor.rs | 5 ++++ livekit-session/src/session.rs | 54 ++++++++++++++++++++++++++++++++-- 3 files changed, 59 insertions(+), 4 deletions(-) diff --git a/examples/session/src/main.rs b/examples/session/src/main.rs index 8200d5fec4..4a9f994eb4 100644 --- a/examples/session/src/main.rs +++ b/examples/session/src/main.rs @@ -98,8 +98,8 @@ async fn main() -> Result<(), Box> { if changed.is_err() { break; } - let current = state.borrow_and_update().clone(); - print_state(¤t); + let current = state.borrow_and_update().clone(); + println!("{:?}", session); if !current.connection.is_connected() { break; } diff --git a/livekit-session/src/actor.rs b/livekit-session/src/actor.rs index c52eb0ac3f..80154ce40b 100644 --- a/livekit-session/src/actor.rs +++ b/livekit-session/src/actor.rs @@ -120,6 +120,11 @@ impl Shared { 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.len() diff --git a/livekit-session/src/session.rs b/livekit-session/src/session.rs index 27e681a1eb..94f01fbac8 100644 --- a/livekit-session/src/session.rs +++ b/livekit-session/src/session.rs @@ -12,9 +12,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -use std::mem; -use std::sync::{Arc, Mutex}; +use std::sync::{Arc, Mutex, TryLockError}; use std::time::Duration; +use std::{fmt, mem}; use livekit::prelude::*; use livekit::SendTextOptions; @@ -164,6 +164,31 @@ pub(crate) struct Inner { 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<()> }, @@ -191,6 +216,15 @@ impl Running { } 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 { @@ -543,4 +577,20 @@ mod tests { 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 options = SessionOptions::default().with_platform_audio(false); + let session = Session::with_agent(source, "my-agent", 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: ")); + } } From 9900be5ca85c34f40bedb15531de4acd7b9c760f Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:06:37 +0100 Subject: [PATCH 47/61] Mark message as non exhaustive --- livekit-session/src/messages.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/livekit-session/src/messages.rs b/livekit-session/src/messages.rs index b87503a307..7df5d49c4b 100644 --- a/livekit-session/src/messages.rs +++ b/livekit-session/src/messages.rs @@ -26,6 +26,7 @@ use crate::constants::{ATTRIBUTE_SEGMENT_ID, ATTRIBUTE_TRANSCRIPTION_FINAL}; /// [`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. From 977a6fb9efbeaa53fba1416ef6753a898ef0fe47 Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:18:48 +0100 Subject: [PATCH 48/61] builder lite pattern for message --- livekit-session/src/messages.rs | 51 +++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/livekit-session/src/messages.rs b/livekit-session/src/messages.rs index 7df5d49c4b..e0e114885d 100644 --- a/livekit-session/src/messages.rs +++ b/livekit-session/src/messages.rs @@ -47,6 +47,57 @@ pub struct Message { 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 chrono::{TimeZone, Utc}; + /// # use livekit::prelude::ParticipantIdentity; + /// use livekit_session::{Message, MessageOrigin}; + /// + /// # let identity = ParticipantIdentity::from("user".to_owned()); + /// # let saved_at = Utc.timestamp_opt(1_800_000_000, 0).unwrap(); + /// 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: Utc::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: DateTime) -> 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] From 9627dab5dac8dd24712e7a3ba2449792ab603188 Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:15:45 +0100 Subject: [PATCH 49/61] Message restore makes less copies --- livekit-session/src/actor.rs | 7 +++-- livekit-session/src/messages.rs | 55 +++++++++++++++++++++++---------- livekit-session/src/session.rs | 8 +++-- 3 files changed, 50 insertions(+), 20 deletions(-) diff --git a/livekit-session/src/actor.rs b/livekit-session/src/actor.rs index 80154ce40b..3fb9080f10 100644 --- a/livekit-session/src/actor.rs +++ b/livekit-session/src/actor.rs @@ -110,9 +110,12 @@ impl Shared { message } - pub(crate) fn restore(&self, restored: &[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.restore(restored); + *messages = restored; self.events.dispatch(&SessionEvent::MessagesRestored); } diff --git a/livekit-session/src/messages.rs b/livekit-session/src/messages.rs index e0e114885d..987d6aa98b 100644 --- a/livekit-session/src/messages.rs +++ b/livekit-session/src/messages.rs @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use std::collections::HashMap; +use std::collections::{hash_map::Entry, HashMap}; use chrono::{DateTime, Utc}; use livekit::prelude::ParticipantIdentity; @@ -309,20 +309,28 @@ impl MessageStore { &self.messages } - /// Replaces the feed with `messages`, numbered from zero in the order - /// given. Of messages sharing an id and participant, the last wins. - pub(crate) fn restore(&mut self, messages: &[Message]) { - *self = Self::default(); - for message in messages { - self.upsert(MessageUpdate { - id: message.id.clone(), - timestamp: message.timestamp, - origin: message.origin, - participant_identity: message.participant_identity.clone(), - text: message.text.clone(), - is_final: message.is_final, - }); + /// 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 } } @@ -506,7 +514,6 @@ mod tests { #[test] fn restore_keeps_the_given_order_and_renumbers() { let mut store = MessageStore::default(); - store.upsert(update("stale", 0, "dropped by restore")); // Received first, but stamped later by a skewed sender clock. let mut first = store.upsert(update("first", 20, "first")); @@ -516,9 +523,25 @@ mod tests { second.timestamp = at(10); second.seq = 3; - store.restore(&[first, second]); + 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 index 94f01fbac8..a2b348f2e8 100644 --- a/livekit-session/src/session.rs +++ b/livekit-session/src/session.rs @@ -463,8 +463,12 @@ impl Session { /// 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. - pub fn restore_messages(&self, messages: &[Message]) { + /// 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); } From 7903b02649660b67874c56aa00d30bb270256d1d Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:24:08 +0100 Subject: [PATCH 50/61] Move integration tests out into test folder --- livekit-session/src/e2e_tests.rs | 545 +------------------------- livekit-session/src/lib.rs | 5 + livekit-session/tests/common/mod.rs | 231 +++++++++++ livekit-session/tests/session_test.rs | 384 ++++++++++++++++++ 4 files changed, 631 insertions(+), 534 deletions(-) create mode 100644 livekit-session/tests/common/mod.rs create mode 100644 livekit-session/tests/session_test.rs diff --git a/livekit-session/src/e2e_tests.rs b/livekit-session/src/e2e_tests.rs index 5dd7a34e97..df9afdd568 100644 --- a/livekit-session/src/e2e_tests.rs +++ b/livekit-session/src/e2e_tests.rs @@ -12,8 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! End-to-end tests against a running `livekit-server --dev`, with a second -//! room standing in for the agent. +//! 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) @@ -23,24 +25,17 @@ //! Run: //! cargo test -p livekit-session --features __lk-e2e-test -use std::collections::HashMap; -use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, Weak}; -use std::time::{Duration, SystemTime, UNIX_EPOCH}; +use std::time::Duration; use anyhow::{anyhow, bail, Result}; use async_trait::async_trait; -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, SimulateScenario, StreamReader, StreamTextOptions, StreamWriter}; +use livekit::SimulateScenario; use livekit_api::services::room::RoomClient; -use livekit_token::{AccessToken, VideoGrants}; use livekit_token_source::{ literal, TokenSourceConfigurable, TokenSourceError, TokenSourceFetchOptions, - TokenSourceLiteral, TokenSourceResponse, TokenSourceResult, + TokenSourceResponse, TokenSourceResult, }; use tokio::io::AsyncReadExt; use tokio::net::TcpListener; @@ -49,181 +44,17 @@ use tokio::sync::oneshot; use tokio::time::{sleep, timeout}; use crate::actor::{lock, Shared}; -use crate::constants::{ - ATTRIBUTE_AGENT_STATE, ATTRIBUTE_PUBLISH_ON_BEHALF, ATTRIBUTE_SEGMENT_ID, - ATTRIBUTE_TRANSCRIPTION_FINAL, TOPIC_CHAT, TOPIC_TRANSCRIPTION, -}; use crate::session::Lifecycle; use crate::*; +use common::*; + +#[path = "../tests/common/mod.rs"] +mod common; -const USER: &str = "user"; -const AGENT: &str = "agent"; -const WAIT: Duration = Duration::from_secs(10); /// How long the client waits for the server to answer a publish before it /// gives up on it: `TRACK_PUBLISH_TIMEOUT` in `livekit`'s engine. const PUBLISH_TIMEOUT: Duration = Duration::from_secs(10); -struct TestEnv { - url: String, - api_key: String, - api_secret: String, - room: String, -} - -impl TestEnv { - 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. - fn grants(&self) -> VideoGrants { - VideoGrants { - room_join: true, - room: self.room.clone(), - can_update_own_metadata: Some(true), - ..Default::default() - } - } - - 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. - 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 - /// answers such a user's microphone publish with nothing, so the publish - /// stays pending until the client gives up on it. - 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`. - 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`. - 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?) - } - - async fn join_observer(&self) -> Result<(Room, UnboundedReceiver)> { - let token = self.token("observer", |token| token); - Ok(Room::connect(&self.url, &token, RoomOptions::default()).await?) - } -} - -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(()) -} - -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)] -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`]. - Left, -} - -impl Expect { - 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)) => true, - _ => false, - } - } -} - -async fn wait_for_agent(session: &Session, expect: Expect) -> Result<()> { - wait_for(session, &format!("{expect:?}"), |s| expect.matches(&s.agent)).await?; - Ok(()) -} - -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}")) -} - fn weak_shared(session: &Session) -> Weak { Arc::downgrade(&session.inner.shared) } @@ -232,15 +63,6 @@ fn is_idle(session: &Session) -> bool { matches!(*lock(&session.inner.lifecycle), Lifecycle::Idle) } -fn current(session: &Session) -> SessionState { - session.state().borrow().clone() -} - -/// Options for a session that stays off the machine's audio devices. -fn text_options() -> SessionOptions { - SessionOptions::default().with_platform_audio(false) -} - /// [`text_options`] for a room that gives up after its first failed join. fn text_options_without_retries() -> SessionOptions { let mut room_options = RoomOptions::default(); @@ -248,20 +70,6 @@ fn text_options_without_retries() -> SessionOptions { text_options().with_room_options(room_options) } -/// The machine's audio devices, or `None` when it has no microphone to -/// publish, logging that the test is skipped. -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) -} - #[tokio::test(flavor = "multi_thread")] async fn start_projects_the_agent_and_end_disconnects() -> Result<()> { let env = TestEnv::new(); @@ -298,42 +106,6 @@ async fn start_projects_the_agent_and_end_disconnects() -> Result<()> { Ok(()) } -#[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(env.user_source(false), SessionOptions::default()); - - 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(env.user_source(false), text_options()); - 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 full_reconnect_does_not_report_left() -> Result<()> { let env = TestEnv::new(); @@ -364,301 +136,6 @@ async fn full_reconnect_does_not_report_left() -> Result<()> { 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().with_agent_connect_timeout(Duration::from_millis(500)); - let session = Session::new(env.user_source(true), 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().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(env.user_source(false), 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().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(env.user_source(true), 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 UnboundedReceiver, - mut predicate: impl FnMut(&Message) -> bool, -) -> Result { - timeout(WAIT, async { - while let Some(event) = events.recv().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(env.user_source(false), text_options()); - 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(env.user_source(false), text_options()); - 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(env.user_source(false), text_options()); - 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(env.user_source(false), text_options()); - 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().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(env.user_source(true), 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(()) -} - #[tokio::test(flavor = "multi_thread")] async fn restarting_after_a_server_side_disconnect() -> Result<()> { let env = TestEnv::new(); diff --git a/livekit-session/src/lib.rs b/livekit-session/src/lib.rs index 0dd978531f..acc68a3fd8 100644 --- a/livekit-session/src/lib.rs +++ b/livekit-session/src/lib.rs @@ -27,6 +27,11 @@ 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; diff --git a/livekit-session/tests/common/mod.rs b/livekit-session/tests/common/mod.rs new file mode 100644 index 0000000000..41d54ba2a8 --- /dev/null +++ b/livekit-session/tests/common/mod.rs @@ -0,0 +1,231 @@ +// 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 + /// answers such a user's microphone publish with nothing, so the publish + /// stays pending until the client gives up on it. + 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`]. + 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)) => true, + _ => 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 stays off the machine's audio devices. +pub fn text_options() -> SessionOptions { + SessionOptions::default().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..c401b6b3d1 --- /dev/null +++ b/livekit-session/tests/session_test.rs @@ -0,0 +1,384 @@ +// 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 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::sync::mpsc::UnboundedReceiver; +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(env.user_source(false), SessionOptions::default()); + + 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(env.user_source(false), text_options()); + 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().with_agent_connect_timeout(Duration::from_millis(500)); + let session = Session::new(env.user_source(true), 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().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(env.user_source(false), 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().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(env.user_source(true), 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 UnboundedReceiver, + mut predicate: impl FnMut(&Message) -> bool, +) -> Result { + timeout(WAIT, async { + while let Some(event) = events.recv().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(env.user_source(false), text_options()); + 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(env.user_source(false), text_options()); + 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(env.user_source(false), text_options()); + 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(env.user_source(false), text_options()); + 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().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(env.user_source(true), 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(()) +} From cdb6e42e63495dba0512c7fd135ccf588dd30bba Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:03:15 +0100 Subject: [PATCH 51/61] agent identity is part of the failed left agent state to prepare for multi agent use case --- livekit-session/src/agent.rs | 46 +++++++++++++++++++++-------- livekit-session/tests/common/mod.rs | 6 ++-- 2 files changed, 37 insertions(+), 15 deletions(-) diff --git a/livekit-session/src/agent.rs b/livekit-session/src/agent.rs index a8c1c84305..b4b7d6b34d 100644 --- a/livekit-session/src/agent.rs +++ b/livekit-session/src/agent.rs @@ -121,7 +121,7 @@ impl AgentState { match self { Self::Joined(agent) => Some(agent), Self::Failed(AgentFailure::Timeout { agent }) => agent.as_ref(), - Self::Failed(AgentFailure::Left) | Self::Disconnected | Self::Connecting => None, + Self::Failed(AgentFailure::Left { .. }) | Self::Disconnected | Self::Connecting => None, } } } @@ -253,7 +253,11 @@ pub enum AgentFailure { agent: Option, }, /// The agent left the room while the session stayed connected. - Left, + #[non_exhaustive] + Left { + /// The identity of the agent that left. + identity: ParticipantIdentity, + }, } /// A remote participant, as far as agent projection is concerned. @@ -329,11 +333,12 @@ fn find_avatar_worker<'a, P: AgentCandidate>( } /// Projects [`AgentState`] from the room, remembering what the projection -/// needs across calls: whether an agent was ever seen, and whether the -/// agent-connect timeout fired. +/// needs across calls: the last agent seen, and whether the agent-connect +/// timeout fired. #[derive(Debug, Default)] pub(crate) struct AgentTracker { - has_ever_connected: bool, + /// 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>, @@ -359,8 +364,10 @@ impl AgentTracker { let Some(agent) = agent else { // A full reconnect removes every participant, so an agent missing // while reconnecting has not necessarily left. - if self.has_ever_connected && connection == SessionConnectionState::Connected { - return AgentState::Failed(AgentFailure::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 }); @@ -368,7 +375,9 @@ impl AgentTracker { return AgentState::Connecting; }; - self.has_ever_connected = true; + 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); @@ -497,7 +506,10 @@ mod tests { AgentState::Failed(AgentFailure::Timeout { agent }) } - const LEFT: AgentState = AgentState::Failed(AgentFailure::Left); + /// 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() { @@ -558,7 +570,15 @@ mod tests { 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); + 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] @@ -576,7 +596,7 @@ mod tests { 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); + 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)) @@ -584,7 +604,7 @@ mod tests { } #[test] - fn disconnect_resets_has_ever_connected() { + 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); @@ -640,7 +660,7 @@ mod tests { connected(Unknown), timed_out(None), timed_out(Some(agent("agent", Initializing))), - LEFT, + left("agent"), ]; for state in &states { let activity = state.activity(); diff --git a/livekit-session/tests/common/mod.rs b/livekit-session/tests/common/mod.rs index 41d54ba2a8..744e3a06ca 100644 --- a/livekit-session/tests/common/mod.rs +++ b/livekit-session/tests/common/mod.rs @@ -175,7 +175,7 @@ pub enum Expect { Joined(AgentActivity), /// [`AgentFailure::Timeout`], with or without an agent in the room. TimedOut, - /// [`AgentFailure::Left`]. + /// [`AgentFailure::Left`] by the agent `AGENT`. Left, } @@ -186,7 +186,9 @@ impl Expect { agent.identity().as_str() == AGENT && agent.activity() == activity } (Self::TimedOut, AgentState::Failed(AgentFailure::Timeout { .. })) => true, - (Self::Left, AgentState::Failed(AgentFailure::Left)) => true, + (Self::Left, AgentState::Failed(AgentFailure::Left { identity, .. })) => { + identity.as_str() == AGENT + } _ => false, } } From e20fd1c8fe7871fb3e316a4f73dfb7840c37f047 Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:05:49 +0100 Subject: [PATCH 52/61] Formatting error --- examples/session/src/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/session/src/main.rs b/examples/session/src/main.rs index 4a9f994eb4..bb85f6140c 100644 --- a/examples/session/src/main.rs +++ b/examples/session/src/main.rs @@ -98,7 +98,7 @@ async fn main() -> Result<(), Box> { if changed.is_err() { break; } - let current = state.borrow_and_update().clone(); + let current = state.borrow_and_update().clone(); println!("{:?}", session); if !current.connection.is_connected() { break; From 1a93849c4b261966334092d9f617e7922906eb1a Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:24:51 +0100 Subject: [PATCH 53/61] adapt test to new pattern --- livekit-session/src/e2e_tests.rs | 79 +++++++++-------------------- livekit-session/tests/common/mod.rs | 3 +- 2 files changed, 24 insertions(+), 58 deletions(-) diff --git a/livekit-session/src/e2e_tests.rs b/livekit-session/src/e2e_tests.rs index df9afdd568..e07c4c9c68 100644 --- a/livekit-session/src/e2e_tests.rs +++ b/livekit-session/src/e2e_tests.rs @@ -51,10 +51,6 @@ use common::*; #[path = "../tests/common/mod.rs"] mod common; -/// How long the client waits for the server to answer a publish before it -/// gives up on it: `TRACK_PUBLISH_TIMEOUT` in `livekit`'s engine. -const PUBLISH_TIMEOUT: Duration = Duration::from_secs(10); - fn weak_shared(session: &Session) -> Weak { Arc::downgrade(&session.inner.shared) } @@ -309,70 +305,41 @@ async fn dropping_a_pending_start_resets_the_session() -> Result<()> { Ok(()) } -/// Asserts that a start cut short during the microphone publish closed its -/// room, so the observer sees the user leave, and left no actor or task -/// behind. -async fn assert_cut_short_publish_left_nothing( - session: &Session, - observer_events: &mut UnboundedReceiver, - baseline_tasks: usize, -) -> Result<()> { - next_participant_event(observer_events, |event| { - matches!(event, RoomEvent::ParticipantDisconnected(p) if p.identity().as_str() == USER) - }) - .await?; - eventually("the final state", || current(session) == SessionState::default()).await?; - 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 -} - -#[tokio::test(flavor = "multi_thread")] -async fn dropping_a_start_during_the_microphone_publish_closes_the_room() -> Result<()> { - let Some(_probe) = microphone_probe() else { - return Ok(()); - }; - let env = TestEnv::new(); - let (_observer, mut observer_events) = env.join_observer().await?; - let baseline_tasks = tokio::runtime::Handle::current().metrics().num_alive_tasks(); - let session = Session::new(env.unpublishable_user_source(), SessionOptions::default()); - let mut start = Box::pin(session.start()); - // The session has a room once its actor owns it, which is then publishing. - // The observer must have seen the user join by then, or the server may - // fold the join and the leave into nothing. - let publishing = async { - eventually("the actor to own the room", || session.room().is_some()).await?; - next_participant_event(&mut observer_events, |event| { - matches!(event, RoomEvent::ParticipantConnected(p) if p.identity().as_str() == USER) - }) - .await - }; - tokio::select! { - result = &mut start => bail!("start resolved during the publish: {result:?}"), - publishing = publishing => publishing?, - } - - drop(start); - assert_cut_short_publish_left_nothing(&session, &mut observer_events, baseline_tasks).await -} - #[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(); - let (_observer, mut observer_events) = env.join_observer().await?; + // 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(env.unpublishable_user_source(), SessionOptions::default()); - // The client gives up on the unanswered publish after its own timeout. - let result = timeout(PUBLISH_TIMEOUT + WAIT, session.start()).await?; + // 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)); - assert_cut_short_publish_left_nothing(&session, &mut observer_events, baseline_tasks).await + 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") diff --git a/livekit-session/tests/common/mod.rs b/livekit-session/tests/common/mod.rs index 744e3a06ca..6051d3459a 100644 --- a/livekit-session/tests/common/mod.rs +++ b/livekit-session/tests/common/mod.rs @@ -104,8 +104,7 @@ impl TestEnv { } /// Credentials for a user who may join but not publish. The server - /// answers such a user's microphone publish with nothing, so the publish - /// stays pending until the client gives up on it. + /// 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() }) From 1e1c93181db97f12e2d7eca4ce5f33952ab67de4 Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:08:28 +0100 Subject: [PATCH 54/61] Add canListen which right now maps to is_connected since Rust has no pre-connect buffer logic implemented --- livekit-session/src/agent.rs | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/livekit-session/src/agent.rs b/livekit-session/src/agent.rs index b4b7d6b34d..32e03f187a 100644 --- a/livekit-session/src/agent.rs +++ b/livekit-session/src/agent.rs @@ -28,7 +28,8 @@ use crate::session::SessionConnectionState; /// tracks. /// /// Most code needs only the methods: [`is_connected`](Self::is_connected) to -/// show that the agent is there, [`is_pending`](Self::is_pending) to show +/// 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 @@ -73,6 +74,16 @@ impl AgentState { 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 { @@ -670,6 +681,7 @@ mod tests { && 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) From 67e30dfed2511c1d0bb012f9de671e0ef997c775 Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:28:27 +0100 Subject: [PATCH 55/61] SessionOptions as the builder DESIGN NOTE (draft for review, not committed): the token source is part of `SessionOptions`, so one value holds all the inputs of a `Session`. What we gained: - `Session::new` takes one argument. Code can build, store, and pass the full configuration of a session as one value, e.g. from an app config. - `Session` has one constructor instead of three. The two `new_*_source` constructors of `SessionOptions` tell from their names which kind of source they take, and the `with_*` prefix is left for setters only. - `Inner` keeps one field for its inputs instead of two. What we lost: - `SessionOptions` has no `Default`, because a token source has no sensible default value. Every caller must choose a source first. - Swift parity. The Swift SDK takes the token source next to its options. - The sources are now behind `Arc` instead of `Box`, so that `SessionOptions` stays `Clone`. A clone shares the source. Two sessions built from clones of one `cached()` source share its cache, so the second session can get a token for the room of the first session. - The `with_agent` shorthand. Callers set the agent name on the `TokenSourceFetchOptions` themselves. --- examples/session/src/main.rs | 18 ++-- livekit-session/README.md | 18 ++-- livekit-session/src/e2e_tests.rs | 51 +++++----- livekit-session/src/session.rs | 130 ++++++++++++++------------ livekit-session/tests/common/mod.rs | 7 +- livekit-session/tests/session_test.rs | 32 ++++--- 6 files changed, 138 insertions(+), 118 deletions(-) diff --git a/examples/session/src/main.rs b/examples/session/src/main.rs index bb85f6140c..e2b37dddae 100644 --- a/examples/session/src/main.rs +++ b/examples/session/src/main.rs @@ -34,11 +34,11 @@ struct Args { text: bool, } -/// Creates a session with credentials from a pre-generated token if one is -/// given, and from a development token server otherwise. -fn create_session(args: Args, options: SessionOptions) -> Result> { +/// 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(Session::new(literal(url, token), options)); + return Ok(SessionOptions::new_fixed_source(literal(url, token))); } let token_server_id = args .token_server_id @@ -47,10 +47,9 @@ fn create_session(args: Args, options: SessionOptions) -> Result Result<(), Box> { // 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 session_options = SessionOptions::default() + let text = args.text; + let session_options = create_options(args)? .with_agent_connect_timeout(Duration::from_secs(15)) - .with_platform_audio(!args.text); - let session = create_session(args, session_options)?; + .with_platform_audio(!text); + let session = Session::new(session_options); let mut events = session.subscribe(); session.start().await?; diff --git a/livekit-session/README.md b/livekit-session/README.md index d0df3e648d..7277989079 100644 --- a/livekit-session/README.md +++ b/livekit-session/README.md @@ -8,10 +8,11 @@ Android and Flutter SDKs. ```rust use livekit_session::{Session, SessionOptions}; -use livekit_token_source::development_token_server; +use livekit_token_source::{development_token_server, TokenSourceFetchOptions}; let token_source = development_token_server(""); -let session = Session::with_agent(token_source, "my-agent", SessionOptions::default()); +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?; @@ -22,13 +23,14 @@ See [`examples/session`](../examples/session) for a complete text chat. ## Credentials -Which constructor to use depends on the kind of token source: +`Session::new` takes a `SessionOptions`, which holds the token source. Which `SessionOptions` +constructor to use depends on the kind of token source: -- `Session::with_agent` takes a configurable source and the name of the agent to dispatch, as - above; -- `Session::with_fetch_options` takes a configurable source with its full `TokenSourceFetchOptions`, - for agent metadata, a room name or a participant identity; -- `Session::new` takes a fixed source, such as a `literal` one holding a pre-generated token. +- `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 diff --git a/livekit-session/src/e2e_tests.rs b/livekit-session/src/e2e_tests.rs index e07c4c9c68..6ff702e008 100644 --- a/livekit-session/src/e2e_tests.rs +++ b/livekit-session/src/e2e_tests.rs @@ -35,7 +35,7 @@ use livekit::SimulateScenario; use livekit_api::services::room::RoomClient; use livekit_token_source::{ literal, TokenSourceConfigurable, TokenSourceError, TokenSourceFetchOptions, - TokenSourceResponse, TokenSourceResult, + TokenSourceLiteral, TokenSourceResponse, TokenSourceResult, }; use tokio::io::AsyncReadExt; use tokio::net::TcpListener; @@ -60,16 +60,25 @@ fn is_idle(session: &Session) -> bool { } /// [`text_options`] for a room that gives up after its first failed join. -fn text_options_without_retries() -> SessionOptions { +fn text_options_without_retries(token_source: TokenSourceLiteral) -> SessionOptions { let mut room_options = RoomOptions::default(); room_options.join_retries = 0; - text_options().with_room_options(room_options) + 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(env.user_source(false), text_options()); + let session = Session::new(text_options(env.user_source(false))); assert_eq!(current(&session), SessionState::default()); assert!(session.room().is_none()); @@ -105,7 +114,7 @@ async fn start_projects_the_agent_and_end_disconnects() -> Result<()> { #[tokio::test(flavor = "multi_thread")] async fn full_reconnect_does_not_report_left() -> Result<()> { let env = TestEnv::new(); - let session = Session::new(env.user_source(false), text_options()); + 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?; @@ -135,7 +144,7 @@ async fn full_reconnect_does_not_report_left() -> Result<()> { #[tokio::test(flavor = "multi_thread")] async fn restarting_after_a_server_side_disconnect() -> Result<()> { let env = TestEnv::new(); - let session = Session::new(env.user_source(false), text_options()); + 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 { @@ -163,8 +172,8 @@ async fn restarting_after_a_server_side_disconnect() -> Result<()> { #[tokio::test(flavor = "multi_thread")] async fn a_rejected_token_fails_the_start() -> Result<()> { let env = TestEnv::new(); - let options = text_options_without_retries(); - let session = Session::new(literal(env.url.clone(), "not a token"), options); + 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)); @@ -183,8 +192,7 @@ impl TokenSourceConfigurable for PendingSource { #[tokio::test(flavor = "multi_thread")] async fn end_cancels_a_pending_start() -> Result<()> { - let session = - Session::with_fetch_options(PendingSource, TokenSourceFetchOptions::new(), text_options()); + let session = Session::new(configurable_text_options(PendingSource)); let start = tokio::spawn({ let session = session.clone(); async move { session.start().await } @@ -231,16 +239,17 @@ impl SilentServer { /// A session connecting to this server. fn session(&self, env: &TestEnv) -> Session { - Session::new(literal(self.url.clone(), env.token(USER, |t| t)), Self::session_options()) + Session::new(self.session_options(env)) } /// Options for a session connecting to this server. - fn session_options() -> SessionOptions { + 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().with_room_options(room_options) + text_options(literal(self.url.clone(), env.token(USER, |t| t))) + .with_room_options(room_options) } } @@ -297,8 +306,7 @@ async fn dropping_a_start_during_connect_resets_the_session() -> Result<()> { #[tokio::test(flavor = "multi_thread")] async fn dropping_a_pending_start_resets_the_session() -> Result<()> { - let session = - Session::with_fetch_options(PendingSource, TokenSourceFetchOptions::new(), text_options()); + 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)); @@ -314,7 +322,7 @@ async fn a_failed_microphone_publish_closes_the_room() -> Result<()> { // 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(env.unpublishable_user_source(), SessionOptions::default()); + 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?; @@ -348,7 +356,7 @@ async fn a_failed_microphone_publish_closes_the_room() -> Result<()> { 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(env.user_source(false), text_options()); + 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| { @@ -389,7 +397,7 @@ async fn next_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(env.user_source(false), text_options()); + 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. @@ -427,8 +435,7 @@ impl TokenSourceConfigurable for FailingSource { #[tokio::test(flavor = "multi_thread")] async fn failed_starts_spawn_nothing() -> Result<()> { - let session = - Session::with_fetch_options(FailingSource, TokenSourceFetchOptions::new(), text_options()); + 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()); @@ -437,8 +444,8 @@ async fn failed_starts_spawn_nothing() -> Result<()> { assert_eq!(weak_shared(&session).strong_count(), 1); let env = TestEnv::new(); - let options = text_options_without_retries(); - let session = Session::new(literal("ws://127.0.0.1:1", env.token(USER, |t| t)), options); + 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)); diff --git a/livekit-session/src/session.rs b/livekit-session/src/session.rs index a2b348f2e8..fb54ec77db 100644 --- a/livekit-session/src/session.rs +++ b/livekit-session/src/session.rs @@ -31,14 +31,19 @@ use crate::constants::{DEFAULT_AGENT_CONNECT_TIMEOUT, TOPIC_CHAT}; use crate::error::{MessageSendError, SessionStartError}; use crate::messages::{Message, MessageOrigin, MessageUpdate}; -/// Where a [`Session`] gets its credentials, chosen by the constructor used. +/// 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(Box), + Fixed(Arc), /// A source fetched with the given options, e.g. to dispatch an agent. - Configurable(Box, TokenSourceFetchOptions), + Configurable(Arc, TokenSourceFetchOptions), } impl SessionTokenSource { @@ -50,25 +55,63 @@ impl SessionTokenSource { } } -/// Options for a [`Session`], set through the `with_*` methods. +/// 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, } -impl Default for SessionOptions { - fn default() -> Self { +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, } } -} -impl SessionOptions { /// Sets how long after connecting an agent gets to become conversational /// before the agent state reports /// [`AgentFailure::Timeout`](crate::AgentFailure::Timeout). Defaults to 20 @@ -140,11 +183,12 @@ pub enum SessionEvent { /// /// ```no_run /// use livekit_session::{Session, SessionOptions}; -/// use livekit_token_source::development_token_server; +/// use livekit_token_source::{development_token_server, TokenSourceFetchOptions}; /// /// # async fn run() -> Result<(), Box> { /// let token_source = development_token_server("my-token-server-id"); -/// let session = Session::with_agent(token_source, "my-agent", SessionOptions::default()); +/// 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?; @@ -158,7 +202,6 @@ pub struct Session { } pub(crate) struct Inner { - token_source: SessionTokenSource, options: SessionOptions, pub(crate) shared: Arc, pub(crate) lifecycle: Mutex, @@ -248,53 +291,12 @@ impl Lifecycle { } impl Session { - /// Creates a session that gets its credentials from a fixed - /// `token_source`, such as a [`literal`](livekit_token_source::literal) - /// one. Nothing happens until [`start`](Self::start). - pub fn new( - token_source: impl TokenSourceFixed + Send + Sync + 'static, - session_options: SessionOptions, - ) -> Self { - Self::from_source(SessionTokenSource::Fixed(Box::new(token_source)), session_options) - } - - /// Creates a session that fetches its credentials from `token_source` - /// with `fetch_options`. Nothing happens until [`start`](Self::start). - /// - /// Every `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 with_fetch_options( - token_source: impl TokenSourceConfigurable + Send + Sync + 'static, - fetch_options: TokenSourceFetchOptions, - session_options: SessionOptions, - ) -> Self { - Self::from_source( - SessionTokenSource::Configurable(Box::new(token_source), fetch_options), - session_options, - ) - } - - /// Creates a session whose credentials dispatch the agent `agent_name`. - /// - /// Shorthand for [`with_fetch_options`](Self::with_fetch_options) with - /// [`TokenSourceFetchOptions::with_agent_name`]; use that to set further - /// options, such as agent metadata. - pub fn with_agent( - token_source: impl TokenSourceConfigurable + Send + Sync + 'static, - agent_name: &str, - session_options: SessionOptions, - ) -> Self { - let fetch_options = TokenSourceFetchOptions::new().with_agent_name(agent_name); - Self::with_fetch_options(token_source, fetch_options, session_options) - } - - fn from_source(token_source: SessionTokenSource, session_options: SessionOptions) -> Self { + /// 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 { - token_source, - options: session_options, + options, shared: Arc::new(Shared::new()), lifecycle: Mutex::new(Lifecycle::Idle), }), @@ -383,7 +385,7 @@ impl Session { async fn connect(&self) -> Result { let options = &self.inner.options; - let credentials = self.inner.token_source.fetch().await?; + 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( @@ -571,11 +573,13 @@ mod tests { } #[tokio::test] - async fn with_agent_fetches_with_the_agent_name() { + async fn fetches_with_the_fetch_options() { let fetched = Arc::default(); let source = RecordingSource(Arc::clone(&fetched)); - let options = SessionOptions::default().with_platform_audio(false); - let session = Session::with_agent(source, "my-agent", options); + 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"); @@ -585,8 +589,10 @@ mod tests { #[test] fn debug_prints_status_without_blocking() { let source = RecordingSource(Arc::default()); - let options = SessionOptions::default().with_platform_audio(false); - let session = Session::with_agent(source, "my-agent", options); + 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( diff --git a/livekit-session/tests/common/mod.rs b/livekit-session/tests/common/mod.rs index 6051d3459a..db77e073cd 100644 --- a/livekit-session/tests/common/mod.rs +++ b/livekit-session/tests/common/mod.rs @@ -212,9 +212,10 @@ pub fn current(session: &Session) -> SessionState { session.state().borrow().clone() } -/// Options for a session that stays off the machine's audio devices. -pub fn text_options() -> SessionOptions { - SessionOptions::default().with_platform_audio(false) +/// 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 diff --git a/livekit-session/tests/session_test.rs b/livekit-session/tests/session_test.rs index c401b6b3d1..45ed764fa3 100644 --- a/livekit-session/tests/session_test.rs +++ b/livekit-session/tests/session_test.rs @@ -60,7 +60,7 @@ async fn start_publishes_the_microphone_and_end_releases_the_audio_devices() -> return Ok(()); }; let env = TestEnv::new(); - let session = Session::new(env.user_source(false), SessionOptions::default()); + let session = Session::new(SessionOptions::new_fixed_source(env.user_source(false))); session.start().await?; assert_eq!(probe.ref_count(), 2); @@ -77,7 +77,7 @@ async fn start_publishes_the_microphone_and_end_releases_the_audio_devices() -> #[tokio::test(flavor = "multi_thread")] async fn agent_leaving_is_reported_as_left() -> Result<()> { let env = TestEnv::new(); - let session = Session::new(env.user_source(false), text_options()); + 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?; @@ -91,8 +91,9 @@ async fn agent_leaving_is_reported_as_left() -> Result<()> { #[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().with_agent_connect_timeout(Duration::from_millis(500)); - let session = Session::new(env.user_source(true), options); + 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?; @@ -105,10 +106,11 @@ async fn timeout_fires_without_an_agent_and_a_late_agent_recovers() -> Result<() #[tokio::test(flavor = "multi_thread")] async fn timeout_is_armed_without_dispatch() -> Result<()> { let env = TestEnv::new(); - let options = text_options().with_agent_connect_timeout(Duration::from_millis(500)); + 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(env.user_source(false), options); + let session = Session::new(options); session.start().await?; wait_for_agent(&session, Expect::TimedOut).await?; session.end().await; @@ -118,10 +120,11 @@ async fn timeout_is_armed_without_dispatch() -> Result<()> { #[tokio::test(flavor = "multi_thread")] async fn timeout_fires_for_an_agent_stuck_initializing() -> Result<()> { let env = TestEnv::new(); - let options = text_options().with_agent_connect_timeout(Duration::from_millis(500)); + 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(env.user_source(true), options); + let session = Session::new(options); session.start().await?; wait_for_agent(&session, Expect::TimedOut).await?; @@ -151,7 +154,7 @@ async fn next_message( #[tokio::test(flavor = "multi_thread")] async fn messages_merge_chat_and_transcripts() -> Result<()> { let env = TestEnv::new(); - let session = Session::new(env.user_source(false), text_options()); + 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?; @@ -226,7 +229,7 @@ async fn messages_merge_chat_and_transcripts() -> Result<()> { #[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(env.user_source(false), text_options()); + 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?; @@ -288,7 +291,7 @@ fn is_subscribed(session: &Session, sid: &TrackSid) -> bool { #[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(env.user_source(false), text_options()); + 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?; @@ -322,7 +325,7 @@ async fn agent_audio_track_is_the_agents_microphone_once_subscribed() -> Result< #[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(env.user_source(false), text_options()); + 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?; @@ -364,11 +367,12 @@ async fn agent_avatar_video_track_is_the_avatar_workers_camera_once_subscribed() #[tokio::test(flavor = "multi_thread")] async fn timed_out_agent_keeps_its_audio_track() -> Result<()> { let env = TestEnv::new(); - let options = text_options().with_agent_connect_timeout(Duration::from_millis(500)); + 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(env.user_source(true), options); + let session = Session::new(options); session.start().await?; wait_for_agent(&session, Expect::TimedOut).await?; From 0fe9b1a66d99ec979517aa835a8096dc5f5a8ceb Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Wed, 25 Nov 2026 09:46:11 +0100 Subject: [PATCH 56/61] Remove random implicit error conversion --- livekit-session/src/error.rs | 2 +- livekit-session/src/session.rs | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/livekit-session/src/error.rs b/livekit-session/src/error.rs index b0bfb2695b..0d8191d047 100644 --- a/livekit-session/src/error.rs +++ b/livekit-session/src/error.rs @@ -32,7 +32,7 @@ pub enum SessionStartError { Token(#[from] TokenSourceError), /// The room failed to connect. #[error("failed to connect: {0}")] - Connect(#[from] RoomError), + 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). diff --git a/livekit-session/src/session.rs b/livekit-session/src/session.rs index fb54ec77db..4c2d043057 100644 --- a/livekit-session/src/session.rs +++ b/livekit-session/src/session.rs @@ -393,7 +393,8 @@ impl Session { &credentials.participant_token, options.room_options.clone(), ) - .await?; + .await + .map_err(SessionStartError::Connect)?; Ok(Connection { room: Arc::new(room), events, From ec460afee6fb3826ae8bdd89caaa4e9bad62a65d Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Thu, 26 Nov 2026 16:02:03 +0100 Subject: [PATCH 57/61] Exchanged dispatcher for tokio broadcast and use a new SessionEventStream for events --- Cargo.lock | 2 + examples/session/Cargo.toml | 1 + examples/session/src/main.rs | 3 +- livekit-session/Cargo.toml | 1 + livekit-session/src/actor.rs | 22 +++-- livekit-session/src/constants.rs | 3 + livekit-session/src/dispatcher.rs | 70 -------------- livekit-session/src/lib.rs | 5 +- livekit-session/src/session.rs | 132 ++++++++++++++++++++++++-- livekit-session/tests/session_test.rs | 6 +- 10 files changed, 150 insertions(+), 95 deletions(-) delete mode 100644 livekit-session/src/dispatcher.rs diff --git a/Cargo.lock b/Cargo.lock index bb8a3e5481..7dae2f1600 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4010,6 +4010,7 @@ dependencies = [ "log", "thiserror 2.0.19", "tokio", + "tokio-stream", ] [[package]] @@ -6876,6 +6877,7 @@ version = "0.1.0" dependencies = [ "clap", "env_logger 0.11.11", + "futures-util", "livekit-session", "livekit-token-source", "tokio", diff --git a/examples/session/Cargo.toml b/examples/session/Cargo.toml index 020e9d2fd5..4be41d6262 100644 --- a/examples/session/Cargo.toml +++ b/examples/session/Cargo.toml @@ -7,6 +7,7 @@ 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/src/main.rs b/examples/session/src/main.rs index e2b37dddae..47e0a30f8a 100644 --- a/examples/session/src/main.rs +++ b/examples/session/src/main.rs @@ -2,6 +2,7 @@ use std::error::Error; use std::time::Duration; use clap::Parser; +use futures_util::StreamExt; use livekit_session::{ Message, MessageOrigin, Session, SessionEvent, SessionOptions, SessionState, }; @@ -104,7 +105,7 @@ async fn main() -> Result<(), Box> { break; } } - Some(event) = events.recv() => { + Some(event) = events.next() => { if let SessionEvent::MessageUpserted(message) = event { print_message(&message); } diff --git a/livekit-session/Cargo.toml b/livekit-session/Cargo.toml index 91ff4dc3c9..af8ad64cd5 100644 --- a/livekit-session/Cargo.toml +++ b/livekit-session/Cargo.toml @@ -53,6 +53,7 @@ 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 } diff --git a/livekit-session/src/actor.rs b/livekit-session/src/actor.rs index 3fb9080f10..041dc14764 100644 --- a/livekit-session/src/actor.rs +++ b/livekit-session/src/actor.rs @@ -25,12 +25,11 @@ use livekit::{ ConnectionState, DisconnectReason, StreamReader, StreamResult, TakeCell, TextStreamInfo, TextStreamReader, }; -use tokio::sync::{mpsc, oneshot, watch}; +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::dispatcher::Dispatcher; use crate::messages::{ Message, MessageOrigin, MessageStore, MessageUpdate, TranscriptAggregator, TranscriptStream, }; @@ -45,7 +44,7 @@ pub(crate) struct Shared { generation: Mutex, state: watch::Sender, messages: Mutex, - events: Dispatcher, + events: broadcast::Sender, /// Every state published, so tests can assert on states a `watch` /// receiver would skip. #[cfg(test)] @@ -53,12 +52,14 @@ pub(crate) struct Shared { } impl Shared { - pub(crate) fn new() -> Self { + /// 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: Dispatcher::default(), + events: broadcast::Sender::new(event_buffer_size), #[cfg(test)] history: Mutex::default(), } @@ -96,8 +97,8 @@ impl Shared { self.state.subscribe() } - pub(crate) fn subscribe(&self) -> mpsc::UnboundedReceiver { - self.events.register() + pub(crate) fn subscribe(&self) -> broadcast::Receiver { + self.events.subscribe() } /// Adds or updates a message and notifies subscribers. The event is @@ -106,7 +107,8 @@ impl Shared { pub(crate) fn upsert(&self, update: MessageUpdate) -> Message { let mut messages = lock(&self.messages); let message = messages.upsert(update); - self.events.dispatch(&SessionEvent::MessageUpserted(message.clone())); + // Fails only when there is no subscriber. + _ = self.events.send(SessionEvent::MessageUpserted(message.clone())); message } @@ -116,7 +118,7 @@ impl Shared { let restored = MessageStore::restored(restored); let mut messages = lock(&self.messages); *messages = restored; - self.events.dispatch(&SessionEvent::MessagesRestored); + _ = self.events.send(SessionEvent::MessagesRestored); } pub(crate) fn messages(&self) -> Vec { @@ -130,7 +132,7 @@ impl Shared { #[cfg(all(test, feature = "__lk-e2e-test"))] pub(crate) fn subscriber_count(&self) -> usize { - self.events.len() + self.events.receiver_count() } } diff --git a/livekit-session/src/constants.rs b/livekit-session/src/constants.rs index 61b2391d2b..23d3470ba6 100644 --- a/livekit-session/src/constants.rs +++ b/livekit-session/src/constants.rs @@ -41,3 +41,6 @@ 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/dispatcher.rs b/livekit-session/src/dispatcher.rs deleted file mode 100644 index 761269ca34..0000000000 --- a/livekit-session/src/dispatcher.rs +++ /dev/null @@ -1,70 +0,0 @@ -// 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::sync::Mutex; - -use tokio::sync::mpsc; - -use crate::actor::lock; - -/// Fans values out to any number of subscribers, each on its own unbounded -/// channel. A subscriber whose receiver is dropped is removed on the next -/// dispatch. -/// -/// `livekit` has the same type, but keeps it private. -pub(crate) struct Dispatcher { - senders: Mutex>>, -} - -impl Default for Dispatcher { - fn default() -> Self { - Self { senders: Mutex::default() } - } -} - -impl Dispatcher { - pub(crate) fn register(&self) -> mpsc::UnboundedReceiver { - let (tx, rx) = mpsc::unbounded_channel(); - lock(&self.senders).push(tx); - rx - } - - pub(crate) fn dispatch(&self, value: &T) { - lock(&self.senders).retain(|sender| sender.send(value.clone()).is_ok()); - } - - #[cfg(test)] - pub(crate) fn len(&self) -> usize { - lock(&self.senders).len() - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn dropped_receiver_is_pruned_on_the_next_dispatch() { - let dispatcher = Dispatcher::default(); - let mut kept = dispatcher.register(); - let dropped = dispatcher.register(); - assert_eq!(dispatcher.len(), 2); - - drop(dropped); - assert_eq!(dispatcher.len(), 2, "pruning happens on dispatch, not on drop"); - dispatcher.dispatch(&1); - assert_eq!(dispatcher.len(), 1); - assert_eq!(kept.try_recv(), Ok(1)); - } -} diff --git a/livekit-session/src/lib.rs b/livekit-session/src/lib.rs index acc68a3fd8..1fba1cc4e2 100644 --- a/livekit-session/src/lib.rs +++ b/livekit-session/src/lib.rs @@ -22,7 +22,6 @@ mod actor; mod agent; mod constants; -mod dispatcher; mod error; mod messages; mod session; @@ -38,4 +37,6 @@ 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, SessionOptions, SessionState}; +pub use session::{ + Session, SessionConnectionState, SessionEvent, SessionEventStream, SessionOptions, SessionState, +}; diff --git a/livekit-session/src/session.rs b/livekit-session/src/session.rs index 4c2d043057..ca14afc637 100644 --- a/livekit-session/src/session.rs +++ b/livekit-session/src/session.rs @@ -12,22 +12,27 @@ // 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::{mpsc, oneshot, watch}; +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, TOPIC_CHAT}; +use crate::constants::{DEFAULT_AGENT_CONNECT_TIMEOUT, DEFAULT_EVENT_BUFFER_SIZE, TOPIC_CHAT}; use crate::error::{MessageSendError, SessionStartError}; use crate::messages::{Message, MessageOrigin, MessageUpdate}; @@ -78,6 +83,7 @@ pub struct SessionOptions { agent_connect_timeout: Duration, room_options: RoomOptions, platform_audio: bool, + event_buffer_size: usize, } impl SessionOptions { @@ -109,6 +115,7 @@ impl SessionOptions { agent_connect_timeout: DEFAULT_AGENT_CONNECT_TIMEOUT, room_options: RoomOptions::default(), platform_audio: true, + event_buffer_size: DEFAULT_EVENT_BUFFER_SIZE, } } @@ -147,6 +154,19 @@ impl SessionOptions { 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 @@ -160,6 +180,38 @@ pub enum SessionEvent { 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 @@ -296,8 +348,8 @@ impl Session { pub fn new(options: SessionOptions) -> Self { Self { inner: Arc::new(Inner { + shared: Arc::new(Shared::new(options.event_buffer_size)), options, - shared: Arc::new(Shared::new()), lifecycle: Mutex::new(Lifecycle::Idle), }), } @@ -475,13 +527,16 @@ impl Session { self.inner.shared.restore(messages); } - /// A receiver of changes to the message feed. + /// Subscribes to changes to the message feed. The stream yields the + /// changes made after this call. /// - /// Unbounded, like [`Room::subscribe`]: the session must never block on a - /// slow subscriber, and the feed's rate is bounded by the conversation. - /// Drop the receiver to unsubscribe; it is removed on the next event. - pub fn subscribe(&self) -> mpsc::UnboundedReceiver { - self.inner.shared.subscribe() + /// 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()) } } @@ -557,6 +612,7 @@ 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. @@ -604,4 +660,62 @@ mod tests { let _held = lock(&session.inner.lifecycle); assert!(format!("{session:?}").contains("lifecycle: ")); } + + fn update(id: &str, text: &str) -> MessageUpdate { + MessageUpdate { + id: id.into(), + timestamp: chrono::DateTime::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/session_test.rs b/livekit-session/tests/session_test.rs index 45ed764fa3..a23dcfff7f 100644 --- a/livekit-session/tests/session_test.rs +++ b/livekit-session/tests/session_test.rs @@ -30,6 +30,7 @@ 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; @@ -37,7 +38,6 @@ use livekit::webrtc::prelude::{AudioSourceOptions, RtcVideoSource, VideoResoluti use livekit::webrtc::video_source::native::NativeVideoSource; use livekit::{SendTextOptions, StreamReader, StreamTextOptions, StreamWriter}; use livekit_session::*; -use tokio::sync::mpsc::UnboundedReceiver; use tokio::time::timeout; use common::*; @@ -135,11 +135,11 @@ async fn timeout_fires_for_an_agent_stuck_initializing() -> Result<()> { } async fn next_message( - events: &mut UnboundedReceiver, + events: &mut SessionEventStream, mut predicate: impl FnMut(&Message) -> bool, ) -> Result { timeout(WAIT, async { - while let Some(event) = events.recv().await { + while let Some(event) = events.next().await { if let SessionEvent::MessageUpserted(message) = event { if predicate(&message) { return Ok(message); From 63c8d7194b456aa010d796a7b9a1c60a1316a80e Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Mon, 30 Nov 2026 12:56:42 +0100 Subject: [PATCH 58/61] Use SystemTime for message timestamps instead of chrono Message::timestamp and Message::with_timestamp exposed chrono's DateTime, so users had to depend on chrono at a matching version to set or read a timestamp. Convert the data-stream timestamp to std::time::SystemTime where it enters the session and drop the chrono dependency. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 - livekit-session/Cargo.toml | 1 - livekit-session/src/actor.rs | 4 ++-- livekit-session/src/messages.rs | 28 ++++++++++++++-------------- livekit-session/src/session.rs | 4 ++-- 5 files changed, 18 insertions(+), 20 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7dae2f1600..009e200d4e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4000,7 +4000,6 @@ version = "0.1.0" dependencies = [ "anyhow", "async-trait", - "chrono", "futures-util", "livekit", "livekit-api", diff --git a/livekit-session/Cargo.toml b/livekit-session/Cargo.toml index af8ad64cd5..21ff923672 100644 --- a/livekit-session/Cargo.toml +++ b/livekit-session/Cargo.toml @@ -46,7 +46,6 @@ check = [ ] [dependencies] -chrono = { workspace = true } futures-util = { workspace = true, features = ["std"] } livekit = { workspace = true } livekit-token-source = { workspace = true } diff --git a/livekit-session/src/actor.rs b/livekit-session/src/actor.rs index 041dc14764..ffcd3b9610 100644 --- a/livekit-session/src/actor.rs +++ b/livekit-session/src/actor.rs @@ -422,7 +422,7 @@ impl SessionActor { let transcript = Arc::new(Transcript { stream: TranscriptStream { id: info.id.clone(), - timestamp: info.timestamp, + timestamp: info.timestamp.into(), participant_identity, is_local, }, @@ -449,7 +449,7 @@ impl SessionActor { ReaderEvent::Chat { info, participant_identity, text: Ok(text) } => { Some(MessageUpdate { id: info.id, - timestamp: info.timestamp, + timestamp: info.timestamp.into(), origin: MessageOrigin::Chat, participant_identity, text, diff --git a/livekit-session/src/messages.rs b/livekit-session/src/messages.rs index 987d6aa98b..362299cec3 100644 --- a/livekit-session/src/messages.rs +++ b/livekit-session/src/messages.rs @@ -13,8 +13,8 @@ // limitations under the License. use std::collections::{hash_map::Entry, HashMap}; +use std::time::SystemTime; -use chrono::{DateTime, Utc}; use livekit::prelude::ParticipantIdentity; use crate::constants::{ATTRIBUTE_SEGMENT_ID, ATTRIBUTE_TRANSCRIPTION_FINAL}; @@ -36,7 +36,7 @@ pub struct Message { /// from the sender's clock. pub seq: u64, /// When the sender started the message, by the sender's clock. - pub timestamp: DateTime, + pub timestamp: SystemTime, /// Where the message came from. pub origin: MessageOrigin, /// The participant who sent or spoke the message. @@ -55,12 +55,12 @@ impl Message { /// assigns it. /// /// ``` - /// # use chrono::{TimeZone, Utc}; + /// # 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 = Utc.timestamp_opt(1_800_000_000, 0).unwrap(); + /// # 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); /// @@ -76,7 +76,7 @@ impl Message { Self { id: id.into(), seq: 0, - timestamp: Utc::now(), + timestamp: SystemTime::now(), origin, participant_identity, text: text.into(), @@ -86,7 +86,7 @@ impl Message { /// Sets [`timestamp`](Self::timestamp), which defaults to the time of /// creation. - pub fn with_timestamp(mut self, timestamp: DateTime) -> Self { + pub fn with_timestamp(mut self, timestamp: SystemTime) -> Self { self.timestamp = timestamp; self } @@ -116,7 +116,7 @@ pub enum MessageOrigin { #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct MessageUpdate { pub id: String, - pub timestamp: DateTime, + pub timestamp: SystemTime, pub origin: MessageOrigin, pub participant_identity: ParticipantIdentity, pub text: String, @@ -128,7 +128,7 @@ pub(crate) struct MessageUpdate { #[derive(Clone, Debug)] pub(crate) struct TranscriptStream { pub id: String, - pub timestamp: DateTime, + 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. @@ -169,7 +169,7 @@ fn parse_final(attributes: &HashMap) -> Option { struct Partial { text: String, /// The timestamp of the segment's first stream, kept as the segment grows. - timestamp: DateTime, + timestamp: SystemTime, /// The stream that last wrote the segment. stream_id: String, } @@ -338,13 +338,13 @@ impl MessageStore { mod tests { use super::*; - use chrono::TimeZone; + use std::time::{Duration, UNIX_EPOCH}; - fn at(seconds: i64) -> DateTime { - Utc.timestamp_opt(1_800_000_000 + seconds, 0).unwrap() + fn at(seconds: u64) -> SystemTime { + UNIX_EPOCH + Duration::from_secs(1_800_000_000 + seconds) } - fn stream(id: &str, participant: &str, seconds: i64) -> TranscriptStream { + fn stream(id: &str, participant: &str, seconds: u64) -> TranscriptStream { TranscriptStream { id: id.into(), timestamp: at(seconds), @@ -486,7 +486,7 @@ mod tests { assert_eq!(keys, [("one", "user"), ("two", "agent")]); } - fn update(id: &str, seconds: i64, text: &str) -> MessageUpdate { + fn update(id: &str, seconds: u64, text: &str) -> MessageUpdate { MessageUpdate { id: id.into(), timestamp: at(seconds), diff --git a/livekit-session/src/session.rs b/livekit-session/src/session.rs index ca14afc637..b3d64da295 100644 --- a/livekit-session/src/session.rs +++ b/livekit-session/src/session.rs @@ -503,7 +503,7 @@ impl Session { local_participant.send_text(text, SendTextOptions::new_with_topic(TOPIC_CHAT)).await?; Ok(self.inner.shared.upsert(MessageUpdate { id: info.id, - timestamp: info.timestamp, + timestamp: info.timestamp.into(), origin: MessageOrigin::UserInput, participant_identity: local_participant.identity(), text: text.to_owned(), @@ -664,7 +664,7 @@ mod tests { fn update(id: &str, text: &str) -> MessageUpdate { MessageUpdate { id: id.into(), - timestamp: chrono::DateTime::UNIX_EPOCH, + timestamp: std::time::UNIX_EPOCH, origin: MessageOrigin::Chat, participant_identity: "remote".to_owned().into(), text: text.into(), From 3af5b3cd67bcdb4ca3549ab81efb9db8b5937000 Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Mon, 30 Nov 2026 16:02:18 +0100 Subject: [PATCH 59/61] Add livekit-session to verwalter and change version to 0.0.0 for manual trusted publishing cold start --- .changeset/add_livekit_session_crate.md | 2 +- Cargo.lock | 2 +- Cargo.toml | 24 ++++++++++++------------ livekit-session/Cargo.toml | 2 +- verwalter.toml | 1 + 5 files changed, 16 insertions(+), 15 deletions(-) diff --git a/.changeset/add_livekit_session_crate.md b/.changeset/add_livekit_session_crate.md index 1fd12159b3..f660cbcfe4 100644 --- a/.changeset/add_livekit_session_crate.md +++ b/.changeset/add_livekit_session_crate.md @@ -1,5 +1,5 @@ --- -livekit-session: patch +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/Cargo.lock b/Cargo.lock index 009e200d4e..c30c2806ae 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3996,7 +3996,7 @@ dependencies = [ [[package]] name = "livekit-session" -version = "0.1.0" +version = "0.0.0" dependencies = [ "anyhow", "async-trait", diff --git a/Cargo.toml b/Cargo.toml index 35de60a863..46583b1b46 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -58,18 +58,18 @@ license = "Apache-2.0" device-info = { version = "0.1.1", path = "device-info" } imgproc = { version = "0.3.20", path = "imgproc" } libwebrtc = { version = "0.4.2", path = "libwebrtc" } -livekit = { version = "0.12.2", path = "livekit" } -livekit-api = { version = "0.12.0", path = "livekit-api" } -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.1.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" } -livekit-common = { version = "0.2.1", path = "livekit-common" } -livekit-data-stream = { version = "0.3.1", path = "livekit-data-stream" } +livekit = { version = "0.12.1", path = "livekit" } +livekit-api = { version = "0.11.0", path = "livekit-api" } +livekit-capture = { version = "0.3.1", path = "livekit-capture" } +livekit-ffi = { version = "0.16.0", path = "livekit-ffi" } +livekit-datatrack = { version = "0.3.0", path = "livekit-datatrack" } +livekit-telemetry = { version = "0.3.0", path = "livekit-telemetry" } +livekit-session = { version = "0.0.0", path = "livekit-session" } +livekit-signaling = { version = "0.3.0", path = "livekit-signaling" } +livekit-token = { version = "0.5.0", path = "livekit-token" } +livekit-token-source = { version = "0.2.0", path = "livekit-token-source" } +livekit-common = { version = "0.2.0", path = "livekit-common" } +livekit-data-stream = { version = "0.3.0", path = "livekit-data-stream" } livekit-net = { version = "0.2.0", path = "livekit-net" } livekit-protocol = { version = "0.10.0", path = "livekit-protocol" } livekit-region = { version = "0.1.2", path = "livekit-region" } diff --git a/livekit-session/Cargo.toml b/livekit-session/Cargo.toml index 21ff923672..ef6e1a0269 100644 --- a/livekit-session/Cargo.toml +++ b/livekit-session/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "livekit-session" description = "Agent sessions for the LiveKit Rust SDK" -version = "0.1.0" +version = "0.0.0" license.workspace = true edition.workspace = true repository.workspace = true 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", From 12011d77effe46ca72bc7540d0635ef065b32420 Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Thu, 3 Dec 2026 10:12:19 +0100 Subject: [PATCH 60/61] Move protocol submodule back to main commit --- livekit-protocol/protocol | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/livekit-protocol/protocol b/livekit-protocol/protocol index c6a16489d6..d234edab32 160000 --- a/livekit-protocol/protocol +++ b/livekit-protocol/protocol @@ -1 +1 @@ -Subproject commit c6a16489d6aa4e3fc310487f007b9997237ef0a0 +Subproject commit d234edab32b0a9bdad57a7ec93d41bb2db33f1fe From 84c198a0b42bfe1badce820fd83c76cf93ebd9d7 Mon Sep 17 00:00:00 2001 From: Max Heimbrock <43608204+MaxHeimbrock@users.noreply.github.com> Date: Thu, 3 Dec 2026 10:12:38 +0100 Subject: [PATCH 61/61] Update cargo after rebase --- Cargo.toml | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 46583b1b46..f44bb45106 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -58,18 +58,18 @@ license = "Apache-2.0" device-info = { version = "0.1.1", path = "device-info" } imgproc = { version = "0.3.20", path = "imgproc" } libwebrtc = { version = "0.4.2", path = "libwebrtc" } -livekit = { version = "0.12.1", path = "livekit" } -livekit-api = { version = "0.11.0", path = "livekit-api" } -livekit-capture = { version = "0.3.1", path = "livekit-capture" } -livekit-ffi = { version = "0.16.0", path = "livekit-ffi" } -livekit-datatrack = { version = "0.3.0", path = "livekit-datatrack" } -livekit-telemetry = { version = "0.3.0", path = "livekit-telemetry" } +livekit = { version = "0.12.2", path = "livekit" } +livekit-api = { version = "0.12.0", path = "livekit-api" } +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.3.0", path = "livekit-signaling" } -livekit-token = { version = "0.5.0", path = "livekit-token" } -livekit-token-source = { version = "0.2.0", path = "livekit-token-source" } -livekit-common = { version = "0.2.0", path = "livekit-common" } -livekit-data-stream = { version = "0.3.0", path = "livekit-data-stream" } +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" } +livekit-common = { version = "0.2.1", path = "livekit-common" } +livekit-data-stream = { version = "0.3.1", path = "livekit-data-stream" } livekit-net = { version = "0.2.0", path = "livekit-net" } livekit-protocol = { version = "0.10.0", path = "livekit-protocol" } livekit-region = { version = "0.1.2", path = "livekit-region" }