Skip to main content

ag_ui/server/emit/
message.rs

1//! Streaming one text message.
2
3use crate::{Event, MessageId, TextMessageRole};
4
5use crate::server::emit::EventSink;
6use crate::server::error::Result;
7use crate::server::state::RunState;
8
9/// One open text message.
10///
11/// Created by [`RunContext::assistant_message`](crate::server::RunContext::assistant_message).
12/// `TEXT_MESSAGE_START` has already gone out by the time you hold one; `Drop`
13/// emits `TEXT_MESSAGE_END` if [`end`](Self::end) was not called.
14///
15/// ```
16/// # use ag_ui::RunAgentInput;
17/// # use ag_ui::server::RunContext;
18/// # let (mut ctx, mut events) = RunContext::<()>::new(RunAgentInput::new("t", "r"))?;
19/// let mut message = ctx.assistant_message()?;
20/// for word in ["Hello", ", ", "world"] {
21///     message.delta(word)?;
22/// }
23/// message.end()?;
24/// assert_eq!(events.drain().len(), 5);
25/// # Ok::<(), ag_ui::server::Error>(())
26/// ```
27#[derive(Debug)]
28pub struct MessageHandle<'a, S> {
29    sink: &'a mut EventSink,
30    state: &'a mut RunState<S>,
31    id: MessageId,
32    ended: bool,
33}
34
35impl<'a, S> MessageHandle<'a, S> {
36    /// Emits `TEXT_MESSAGE_START` and takes the message.
37    ///
38    /// Returns `Err` without producing a handle when the start could not be
39    /// emitted, so a failed open never leaves a terminator to be emitted for a
40    /// message that does not exist.
41    pub(crate) fn start(
42        sink: &'a mut EventSink,
43        state: &'a mut RunState<S>,
44        id: MessageId,
45        role: TextMessageRole,
46    ) -> Result<Self> {
47        sink.emit(Event::text_message_start(id.clone(), role))?;
48        Ok(Self {
49            sink,
50            state,
51            id,
52            ended: false,
53        })
54    }
55
56    /// The id every event of this message carries.
57    pub fn id(&self) -> &MessageId {
58        &self.id
59    }
60
61    /// Appends text — `TEXT_MESSAGE_CONTENT`.
62    ///
63    /// No `.await`: see the [module docs](crate::server::emit) for why the emit path is
64    /// synchronous.
65    pub fn delta(&mut self, text: impl Into<String>) -> Result<()> {
66        self.sink
67            .emit(Event::text_message_content(self.id.clone(), text))
68    }
69
70    /// Emits an unrelated event without closing the message.
71    ///
72    /// For the unordered families — `STATE_*`, `ACTIVITY_*`, `CUSTOM`, `RAW` —
73    /// which may legally interleave with a message. Raw events can open another message with a different ID. The caller must
74    /// maintain its lifecycle; the verifier checks IDs and ordering.
75    pub fn emit(&mut self, event: Event) -> Result<()> {
76        self.sink.emit(event)
77    }
78
79    /// Emits `TEXT_MESSAGE_END` and consumes the handle.
80    ///
81    /// Only worth calling over letting the handle drop when you want to see the
82    /// error: `Drop` cannot report one. Like `Drop`, it still closes the
83    /// message after the run was cancelled.
84    pub fn end(mut self) -> Result<()> {
85        self.ended = true;
86        self.sink
87            .emit_forced(Event::text_message_end(self.id.clone()))
88    }
89}
90
91state_access! {
92    /// The run's state, reachable while the message is open — an agent that
93    /// narrates what it is doing changes both in the same breath. See
94    /// [`ToolCallHandle`](crate::server::ToolCallHandle), where this matters most.
95    MessageHandle, published "inside this message's brackets"
96}
97
98impl<S> Drop for MessageHandle<'_, S> {
99    fn drop(&mut self) {
100        if !self.ended {
101            // Past cancellation too: a cancelled run still closes what it
102            // opened. Nowhere to report a failure to; a dead channel makes the
103            // terminator moot anyway.
104            let _ = self
105                .sink
106                .emit_forced(Event::text_message_end(self.id.clone()));
107        }
108    }
109}