Repository navigation
Add the Session API crate - #1593
MaxHeimbrock wants to merge 57 commits into
Conversation
79fda31 to
97b4696
Compare
97b4696 to
ce21dc6
Compare
2d28c8d to
16e31a5
Compare
Changeset ✓This PR includes a changeset covering all affected packages:
|
This comment was marked as resolved.
This comment was marked as resolved.
48cb99a to
690e6bf
Compare
This comment was marked as resolved.
This comment was marked as resolved.
99c83dc to
5f9d744
Compare
There was a problem hiding this comment.
Note
Newer findings are available below. Devin Review posted a newer report on this PR, in addition to the findings presented here.
Devin Review found 1 new potential issue.
1 flag not posted on this PR by your GitHub settings — view it in Devin Review. (Configure)
| } | ||
| // Dropped while the actor was publishing the microphone. Dropping its | ||
| // `stop` sender stops it. | ||
| drop(lifecycle.take_running(self.generation)); |
There was a problem hiding this comment.
🟡 Cancelled starts detach room tasks
Dropping start() during microphone publication drops the Running task handle without joining it. The actor closes in the background, but no owner observes its completion or failure.
Learn more
A running session keeps the actor's JoinHandle in Running, and Running::join normally drops the stop sender and awaits that handle. Here take_running removes the only handle, then drops it without awaiting. Tokio detaches the actor, so no owner can observe a failed shutdown or guarantee a join. The same unowned task path occurs when the lifecycle changes after spawning the actor.
Example: A caller times out session.start() while the microphone publication is pending. Its guard signals stop but discards the task handle; the actor closes the room asynchronously without a joiner.
Recommended fix: Arrange for both cancellation paths to transfer Running to a named shutdown owner that awaits Running::join, while preserving background teardown when start() is dropped. Add a lifecycle test that verifies the shutdown owner joins the task.
Was this helpful? React with 👍 or 👎 to provide feedback.
This comment was marked as outdated.
This comment was marked as outdated.
daa2e7d to
f79aa64
Compare
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.
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.
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.
…ing 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.
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.
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.
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.
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.
…d avatar track as well as the participant identity
Fix test after debug session reorder
…multi agent use case
…pre-connect buffer logic implemented
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.
19a5c09 to
941c3ed
Compare
New
livekit-sessioncrate withSession. Similar to the other session APIs in https://docs.livekit.io/frontends/build/sessions/.Look at the example or my PR in the Rust dev client for usage.
Disclaimer: I mostly used Claude to write this. I am still not a Rust expert. I tried to find wholes as much as possible, look at the developer facing APIs and test it myself through the Rust dev client.
Decisions I took:
The platform audio is activated for the user by default, opt out via the session options (
with_platform_audio = false).If you pass a cached token source, you will run into issues reusing the same token. This is a footgun we accept, since invalidating tokens after use is not easy to expose in the current design. Also fixed token sources are allowed, which cause the same problem.
We don't plan to expose this Rust session via FFI for now.
Using the actor pattern according to AGENT.md.
Public API
Every enum is
#[non_exhaustive], and so areSessionStateandMessage.SessionOptionsandAgenthave private fields. AMessageforrestore_messagesis built withMessage::new.SessionClone,DebugSession::new(token_source, options)TokenSourceFixed, e.g.literalSession::with_fetch_options(token_source, fetch_options, options)TokenSourceConfigurablewith fullTokenSourceFetchOptionsSession::with_agent(token_source, agent_name, options)with_fetch_optionsthat dispatchesagent_nameSession::start(&self) -> Result<(), SessionStartError>Session::end(&self)start; idempotentSession::state(&self) -> watch::Receiver<SessionState>borrow) and changes (changed,wait_for). The agent and its tracks are read from hereSession::room(&self) -> Option<Arc<Room>>Session::send_text(&self, text: &str) -> Result<Message, MessageSendError>lk.chatand adds it to the feed once sentSession::messages(&self) -> Vec<Message>seqSession::restore_messages(&self, messages: impl IntoIterator<Item = Message>)Session::subscribe(&self) -> mpsc::UnboundedReceiver<SessionEvent>SessionOptionsDefaultwith_agent_connect_timeout(20 s default),with_room_options, andwith_platform_audio(trueby default: the microphone is published and the agent's audio played)SessionState { connection, agent }Clone,Defaultstate(). NotCopy: it holds the agent's tracks, so a kept value keeps them aliveSessionConnectionStateCopyDisconnected,Connecting,Connected,Reconnecting;is_connected()AgentStateCloneDisconnected,Connecting,Joined(Agent),Failed(AgentFailure);is_connected(),is_pending(),is_finished(), andidentity(),activity(),audio_track(),avatar_video_track()to read the agent whichever variant holds itAgentCloneidentity(),activity(),audio_track()(its microphone, once subscribed),avatar_video_track()(the avatar worker's camera, once subscribed). Equality compares identity, activity and tracksidsAgentActivityCopyInitializing,Idle,Listening,Thinking,Speaking,Unknown; from thelk.agent.stateattributeAgentFailureTimeout { agent: Option<Agent> }(the slow agent, if one is in the room),LeftSessionEventMessageUpserted(Message),MessagesRestoredMessage { id, seq, timestamp, origin, participant_identity, text, is_final }id+participant_identity.Message::new(id, origin, participant_identity, text)creates a final message timestamped now; builderswith_timestamp,with_is_finalMessageOriginCopyAgentTranscript,UserTranscript,UserInput,ChatSessionStartErrorAlreadyStarted,Cancelled,Token(TokenSourceError),Connect(RoomError),PlatformAudio(AudioError)(no audio devices),Microphone(RoomError)(the microphone failed to publish; the room is closed again)MessageSendErrorNotConnected,Stream(StreamError)Commits
Group 1. Crate scaffolding
Group 2. Message feed
5. feat(session): add the Message model and the MessageStore feed
6. test(session): cover MessageStore ordering, upsert and restore
7. IMPORTANT(session): aggregate lk.transcription streams into transcript messages
8. test(session): cover transcript aggregation
Group 3. Agent projection
9. feat(session): add AgentState and AgentFailure
10. feat(session): find the agent, its avatar worker and their tracks
11. IMPORTANT(session): project AgentState with timeout and leave detection
12. test(session): cover agent discovery and state parsing
13. test(session): cover agent projection across reconnects, leaves and timeouts
Group 4. Session runtime
14. feat(session): add the Dispatcher fan-out
15. test(session): cover Dispatcher pruning
16. feat(session): add the state shared between a session and its actor
17. feat(session): add SessionOptions, SessionState and SessionEvent
18. feat(session): add the Session handle and its constructors
19. IMPORTANT(session): add the session actor and its agent-state projection
20. IMPORTANT(session): read chat and transcript streams in the actor
21. IMPORTANT(session): start and end a session
22. feat(session): expose state, room, agent tracks and the message feed
23. test(session): assert with_agent fetches with the agent name
Group 5. End-to-end tests
24. test(session): add the e2e harness with a stand-in agent
25. test(session): e2e agent state follows joins, leaves and reconnects
26. test(session): e2e agent connect timeout
27. test(session): e2e start publishes the platform microphone
28. test(session): e2e the feed merges chat and transcripts
29. test(session): e2e agent audio and avatar video tracks
30. test(session): e2e restart after a disconnect and a rejected token
31. test(session): e2e end and drop cancel a pending start
32. test(session): e2e a start cancelled during the handshake leaves nothing behind
33. test(session): e2e memory lifecycle
Group 6. Docs, example and changeset
34. docs(session): add the crate README
35. feat(example): add the session voice and text chat example
36. chore(session): add the changeset