Skip to main content

ag_ui/server/
progress.rs

1//! Where a run is: what it has open, and what a client that joins it is sent
2//! first.
3//!
4//! A run that outlives the response that started it is read by clients that
5//! were not there when it began: a second window on the same thread, a client
6//! that lost its connection and came back. Such a client cannot be handed the
7//! run's stream from where it now stands. A stream begins with `RUN_STARTED`,
8//! or with `RUN_ERROR` for a run that failed before it began, and a client
9//! rejects any other first event. It rejects what continues or closes
10//! something it never saw open in the same way: the arguments or the end of
11//! a tool call, the end of a step, reasoning content.
12//!
13//! [`RunProgress`] folds the events of a run, as they are sent, into what the
14//! run has open and what each open thing holds so far. From that it builds
15//! the [`Prelude`]: the events that take a client to where the run is. The
16//! run's later events then follow as they are.
17//!
18//! It needs no [`Runner`](crate::server::Runner). A server that builds its
19//! own events observes each one here as it sends it, or replays the ones it
20//! stored.
21//!
22//! ```
23//! # use ag_ui::{Event, Message, TextMessageRole};
24//! # use ag_ui::server::RunProgress;
25//! // The run so far, as stored. The answer is half written.
26//! let stored = [
27//!     Event::run_started("thread-1", "run-1"),
28//!     Event::step_started("answer"),
29//!     Event::text_message_start("msg-2", TextMessageRole::Assistant),
30//!     Event::text_message_content("msg-2", "The capital "),
31//!     Event::text_message_content("msg-2", "of France"),
32//! ];
33//! let mut progress = RunProgress::new();
34//! progress.replay(&stored)?;
35//!
36//! // The messages that are complete: here, the question the run answers.
37//! let question = Message::user("msg-1", "What is the capital of France?");
38//! let prelude = progress.prelude().messages(vec![question.clone()]).into_events();
39//!
40//! assert_eq!(
41//!     prelude,
42//!     [
43//!         Event::run_started("thread-1", "run-1"),
44//!         Event::messages_snapshot(vec![question]),
45//!         Event::step_started("answer"),
46//!         Event::text_message_start("msg-2", TextMessageRole::Assistant),
47//!         Event::text_message_content("msg-2", "The capital of France"),
48//!     ]
49//! );
50//! // Then every event the run sends from here on: " is Paris.", the end of
51//! // the message, the end of the step, `RUN_FINISHED`.
52//! # Ok::<(), ag_ui::server::VerificationError>(())
53//! ```
54//!
55//! # What a prelude holds
56//!
57//! In this order, and nothing else:
58//!
59//! 1. `RUN_STARTED` as the run sent it, without the input echo. A prelude
60//!    always begins with it.
61//! 2. `MESSAGES_SNAPSHOT`, when [`Prelude::messages`] was given the
62//!    conversation, and `STATE_SNAPSHOT`, when [`Prelude::state`] was given
63//!    the state. Neither is sent unless asked for.
64//! 3. `SUBAGENT_STARTED` for each subagent that is active. A finished one is
65//!    restated, with the event that closed it, only when an active one names
66//!    it as its parent: a client rejects an announcement whose parent it
67//!    never saw.
68//! 4. Each thing that is open, in the order they were opened. A step is its
69//!    `STEP_STARTED` and a reasoning block its `REASONING_START`. A text
70//!    message, a tool call and a reasoning message are their start and one
71//!    content event carrying everything produced since.
72//! 5. The terminal event, once the run has ended.
73//!
74//! A tool call that has ended and waits for its result adds nothing. It is
75//! in the conversation, and a client accepts a `TOOL_CALL_RESULT` for a call
76//! it did not see open.
77//!
78//! One thing comes before the snapshot. A `MESSAGES_SNAPSHOT` the run sent
79//! while a message, a reasoning message or a tool call was open, and that
80//! left it out, dropped it on every client, and a snapshot closes nothing:
81//! what the entity sends next has nowhere to go and is dropped too. So with
82//! [`Prelude::messages`] such an entity is opened right after `RUN_STARTED`
83//! (and the subagents, which then come before it), by its start alone, the
84//! snapshot that follows drops it again, and it is taken out of the
85//! messages given. A client ends holding what one that read the run holds.
86//!
87//! An entity that a `*_CHUNK` event opened is restated as one chunk, not as
88//! a start and a content event. A chunk stream ends when something else
89//! arrives in its lane, and an entity opened explicitly would not: the
90//! client would still hold it open at `RUN_FINISHED`.
91//!
92//! Every restated event carries what the event it stands for carried: the
93//! `subagentRunId`, the timestamp, and the metadata of the start merged with
94//! that of the content events since, as a client merges them. `rawEvent` is
95//! left out.
96//!
97//! # The prelude or the stored events, never both
98//!
99//! Replaying is not idempotent. A client appends: a `*_START` for an id it
100//! already holds creates nothing, and the content event after it is added to
101//! what is there. So a client is sent the prelude and then the events that
102//! follow it, or the stored events from the first, and never the stored
103//! events after a prelude that already accounts for them.
104//!
105//! # The conversation is yours to supply
106//!
107//! A prelude restates what is open. What is closed — the earlier turns, the
108//! messages and reasoning messages this run has finished, the tool calls
109//! that ended and their results — is the conversation, and the server holds
110//! it: this module does not rebuild a message list from events. Give it to
111//! [`Prelude::messages`].
112//!
113//! A server that stores events and not messages folds them with the
114//! client's `Applier` (`ag_ui::client::apply::Applier`, behind the `client`
115//! feature), the one implementation of that fold:
116//!
117//! ```
118//! # #[cfg(feature = "client")] {
119//! use ag_ui::client::apply::Applier;
120//! use ag_ui::server::RunProgress;
121//! use ag_ui::{Event, Message, TextMessageRole, ToolCallStartEvent};
122//!
123//! // The request's history, and the run so far: the assistant said what it
124//! // would do, and is half way through the arguments of a search.
125//! let history = vec![Message::user("msg-1", "Find me a flight to Lisbon.")];
126//! let call = ToolCallStartEvent::new("call-1", "search").with_parent_message_id("msg-2");
127//! let stored = [
128//!     Event::run_started("thread-1", "run-1"),
129//!     Event::text_message_start("msg-2", TextMessageRole::Assistant),
130//!     Event::text_message_content("msg-2", "Searching."),
131//!     Event::text_message_end("msg-2"),
132//!     Event::ToolCallStart(call.clone()),
133//!     Event::tool_call_args("call-1", r#"{"to":"#),
134//! ];
135//!
136//! // The messages, as a client that read the run from the start holds them.
137//! let mut applier = Applier::new().with_messages(history.clone());
138//! let mut progress = RunProgress::new();
139//! progress.seed(&history);
140//! for event in &stored {
141//!     applier.apply(event)?;
142//!     progress.observe(event)?;
143//! }
144//!
145//! let prelude = progress.prelude().messages(applier.messages()).into_events();
146//!
147//! // The snapshot holds the call without its arguments, and the stream
148//! // restates them: nothing reaches the client twice.
149//! let Event::MessagesSnapshot(snapshot) = &prelude[1] else { unreachable!() };
150//! let Message::Assistant(assistant) = &snapshot.messages[1] else { unreachable!() };
151//! assert_eq!(assistant.content.as_deref(), Some("Searching."));
152//! assert_eq!(assistant.tool_calls.as_ref().unwrap()[0].function.arguments, "");
153//! assert_eq!(
154//!     prelude[2..],
155//!     [Event::ToolCallStart(call), Event::tool_call_args("call-1", r#"{"to":"#)]
156//! );
157//! # }
158//! # Ok::<(), Box<dyn std::error::Error>>(())
159//! ```
160//!
161//! An `Applier` applies the explicit form. A stream that carries `*_CHUNK`
162//! events goes through the client's `ChunkNormalizer` first.
163//!
164//! # What is open is taken out of the messages
165//!
166//! A message list folded from the events holds what is open as well: the
167//! message being written, the reasoning message being thought, the tool call
168//! with part of its arguments. Sent as it is and followed by each start and
169//! everything so far, it would give the client that text twice.
170//!
171//! So a prelude does one thing with the messages it is given, whatever they
172//! hold: it takes out what it restates. An open text message or reasoning
173//! message keeps its place in the list and whatever else it carries — the
174//! tool calls it made that have ended — and loses its text. An open tool
175//! call stays in its assistant message, without its arguments. The start and
176//! the content event that follow then fill them in, on every client and from
177//! any list: one that holds the open entities as they stand, one that holds
178//! an earlier copy, one that leaves them out. A message the list leaves out
179//! is created by its start, after the messages of the snapshot.
180//!
181//! The other way round was possible: keep the open entities in the
182//! snapshot, set to what the run has produced, and send each start alone.
183//! That works only for an entity the list already holds. One it leaves out
184//! would have to be put in, which needs a place in the list, for a tool call
185//! with no parent a message id that clients derive each in their own way,
186//! and for reasoning would turn a snapshot that says nothing about
187//! reasoning into one that declares all of it. Restating needs none of
188//! that, so it is the only behaviour.
189//!
190//! A client that already holds a different copy of an open entity ends in
191//! the same place. The snapshot replaces its copy of a message the snapshot
192//! carries and drops one it leaves out, and the restated content then lands
193//! on an empty entity. Three cases are beyond what a prelude can do:
194//!
195//! - **An entity that held something before.** A start for an id that was
196//!   in use before, in the history or earlier in the run, adds to what the
197//!   entity held. So does content that follows a `MESSAGES_SNAPSHOT` which
198//!   carried the entity while it was open. The fold knows what was produced
199//!   since and not what was there before, so it takes that ending out of
200//!   the supplied text, where the text ends with it. A list folded from the
201//!   same events does; an earlier copy keeps what it has.
202//! - **Reasoning the snapshot is silent about.** A client keeps its
203//!   reasoning messages through a snapshot that carries none, so a client
204//!   that holds part of an open reasoning message keeps that part, and the
205//!   restated content is added to it. Supply the reasoning messages in the
206//!   list when clients come back holding some. A list folded with the
207//!   `Applier` has them.
208//! - **An entity a snapshot dropped, with no snapshot to drop it again.**
209//!   Without [`Prelude::messages`], and with [`Prelude::reopen_only`], it is
210//!   restated by its start alone, and a client holds it again from there,
211//!   with what the run sends next.
212//!
213//! # A client that holds the run up to a point
214//!
215//! [`Prelude::reopen_only`] is for a client whose position in the stream is
216//! known, such as one that reconnects naming the last event it received.
217//! Replay the stored events up to that point into a `RunProgress` and it
218//! gives each start alone, with no snapshot: the client holds what is open
219//! exactly as it stood there, and is sent the events it missed next.
220//!
221//! # What is not restated
222//!
223//! State, unless [`Prelude::state`] is given it: a `STATE_DELTA` that
224//! follows needs the state it patches. Activities, which are messages and
225//! belong in the list. A reasoning message that has ended inside a block
226//! that has not: it is closed, and so part of the conversation. A subagent
227//! that has finished, unless an active one descends from it: what it said
228//! is in the conversation under its id, and its announcement and outcome
229//! are not sent again.
230
231use std::collections::HashSet;
232
233use serde_json::Value;
234
235use crate::event::BaseEvent;
236use crate::metadata::merge_metadata_into;
237use crate::server::error::VerificationError;
238use crate::server::verify::Verifier;
239use crate::streams::Streams;
240use crate::{
241    Event, InputContent, Message, MessageId, ReasoningMessageChunkEvent,
242    ReasoningMessageStartEvent, ReasoningStartEvent, RunAgentInput, RunStartedEvent,
243    StepStartedEvent, SubagentRunId, SubagentStartedEvent, TextMessageChunkEvent,
244    TextMessageStartEvent, ToolCallChunkEvent, ToolCallId, ToolCallStartEvent, ToolContent,
245    UserContent,
246};
247
248/// The events of a run so far, folded into where the run is.
249///
250/// Feed it every event of the run in the order they are sent, with
251/// [`observe`](Self::observe) or [`replay`](Self::replay). It keeps no log:
252/// what it holds is what is open, the text each open thing has produced, and
253/// the ids the run has used.
254///
255/// It is also the ordering check. With the `verify` feature, `observe`
256/// rejects what [`EventVerifier`](crate::server::verify) rejects and leaves
257/// the fold as it was, so one `RunProgress` can stand where a server that
258/// builds its own events has its verifier. Without the feature nothing is
259/// checked and the fold takes what it is given.
260///
261/// A stream may carry several runs in sequence. The progress is then that
262/// of the run that is open, or of the last one when none is: a
263/// `RUN_STARTED` after a terminal event begins the next run with nothing
264/// open. The runs before it are history, and what they produced is in the
265/// conversation.
266///
267/// See the [module docs](self) for what a prelude is and how it treats the
268/// messages it is given.
269#[derive(Clone, Debug, Default)]
270pub struct RunProgress {
271    verifier: Verifier,
272    /// The chunk streams being assembled: what tells which events a chunk
273    /// stands for, and which entities are open in the chunked spelling.
274    streams: Streams,
275    /// `RUN_STARTED`, without its input echo.
276    started: Option<RunStartedEvent>,
277    /// The terminal events: `RUN_FINISHED` or `RUN_ERROR`, or the first
278    /// followed by the second.
279    ended: Vec<Event>,
280    /// What is open, in the order it was opened.
281    open: Vec<Slot>,
282    /// Every subagent the run announced, in the order they started.
283    subagents: Vec<Announced>,
284    seen: Seen,
285}
286
287/// Something a run has opened and not closed.
288///
289/// `start` is the event that opened it, without its `rawEvent`, and with the
290/// metadata of the content events since merged into its own: what a client
291/// that read them holds on the entity.
292///
293/// Where there is a `chunked` flag, it says the entity was opened by a
294/// `*_CHUNK` event. Its `start` is then the start that chunk stood for, and
295/// the entity has no end event to wait for: it ends when its chunk stream
296/// does. An explicit content or end event naming it would be rejected.
297#[derive(Clone, Debug, PartialEq)]
298#[non_exhaustive]
299pub enum OpenEntity {
300    /// A text message: `TEXT_MESSAGE_START` with no `TEXT_MESSAGE_END` yet.
301    #[non_exhaustive]
302    Message {
303        /// The event that opened it.
304        start: TextMessageStartEvent,
305        /// The text produced since it was opened.
306        content: String,
307        /// Whether a `TEXT_MESSAGE_CHUNK` opened it.
308        chunked: bool,
309    },
310    /// A tool call whose arguments are streaming: `TOOL_CALL_START` with no
311    /// `TOOL_CALL_END` yet. A call that has ended and waits for its result
312    /// is not open.
313    #[non_exhaustive]
314    ToolCall {
315        /// The event that opened it.
316        start: ToolCallStartEvent,
317        /// The argument JSON produced since it was opened. Rarely valid JSON
318        /// yet.
319        args: String,
320        /// Whether a `TOOL_CALL_CHUNK` opened it.
321        chunked: bool,
322    },
323    /// A reasoning block: `REASONING_START` with no `REASONING_END` yet. The
324    /// message inside it is a separate entry, open or not on its own.
325    #[non_exhaustive]
326    ReasoningBlock {
327        /// The event that opened it.
328        start: ReasoningStartEvent,
329    },
330    /// A reasoning message: `REASONING_MESSAGE_START` with no
331    /// `REASONING_MESSAGE_END` yet.
332    #[non_exhaustive]
333    ReasoningMessage {
334        /// The event that opened it.
335        start: ReasoningMessageStartEvent,
336        /// The reasoning text produced since it was opened.
337        content: String,
338        /// Whether a `REASONING_MESSAGE_CHUNK` opened it.
339        chunked: bool,
340    },
341    /// A step: `STEP_STARTED` with no `STEP_FINISHED` yet.
342    #[non_exhaustive]
343    Step {
344        /// The event that opened it.
345        start: StepStartedEvent,
346    },
347    /// An active subagent: `SUBAGENT_STARTED` with neither
348    /// `SUBAGENT_FINISHED` nor `SUBAGENT_ERROR` yet.
349    #[non_exhaustive]
350    Subagent {
351        /// The event that announced it.
352        start: SubagentStartedEvent,
353    },
354}
355
356/// An open entity and what the fold knows about it beyond what it shows.
357#[derive(Clone, Debug)]
358struct Slot {
359    entity: OpenEntity,
360    /// Whether the entity held something before the content recorded here:
361    /// its id was in use before this opening, in the history or earlier in
362    /// the run, or a snapshot has restated it since. What that was the fold
363    /// does not know. A client adds to it.
364    held_before: bool,
365    /// Whether the last `MESSAGES_SNAPSHOT` since the entity opened left it
366    /// out: a client dropped it, and drops what the entity sends next, since
367    /// a snapshot closes nothing and resurrects nothing.
368    dropped: bool,
369}
370
371/// One subagent's lifecycle, as the run sent it.
372#[derive(Clone, Debug)]
373struct Announced {
374    start: SubagentStartedEvent,
375    /// `SUBAGENT_FINISHED` or `SUBAGENT_ERROR`, once it has closed.
376    end: Option<Event>,
377}
378
379/// The ids that have named something able to hold streamed content.
380///
381/// An id names one message, whatever its role: a start for the id of a
382/// message a client holds continues that message, text or reasoning.
383#[derive(Clone, Debug, Default)]
384struct Seen {
385    messages: HashSet<MessageId>,
386    tool_calls: HashSet<ToolCallId>,
387}
388
389impl Seen {
390    /// Records the ids a restated conversation carries.
391    fn conversation(&mut self, messages: &[Message]) {
392        for message in messages {
393            self.messages.insert(message.id().clone());
394            if let Message::Assistant(assistant) = message {
395                for call in assistant.tool_calls.iter().flatten() {
396                    self.tool_calls.insert(call.id.clone());
397                }
398            }
399        }
400    }
401}
402
403impl RunProgress {
404    /// The progress of a run that has sent nothing yet.
405    pub fn new() -> Self {
406        Self::default()
407    }
408
409    /// Learns the conversation the run continues — the request's `messages`
410    /// — before its first event.
411    ///
412    /// A result in the run may answer a call the history made, which the
413    /// ordering check has to know of. The fold has to know which ids were in
414    /// use before the run: a start for one of them adds to a message that
415    /// already holds something.
416    pub fn seed(&mut self, history: &[Message]) {
417        self.verifier.seed(history);
418        self.streams.seed(history);
419        self.seen.conversation(history);
420    }
421
422    /// Checks one event the run is sending, and folds it in.
423    ///
424    /// # Errors
425    ///
426    /// With the `verify` feature, the rule the event broke. A rejected event
427    /// was not sent, so it changes nothing here either.
428    pub fn observe(&mut self, event: &Event) -> Result<(), VerificationError> {
429        self.verifier.observe(event)?;
430        self.fold(event);
431        Ok(())
432    }
433
434    /// Observes the events a run has already sent, in order.
435    ///
436    /// For a server that reads them from its store: when a client joins, or
437    /// when it takes over a run another process was driving. Afterwards the
438    /// progress is where the run is, and [`observe`](Self::observe) carries
439    /// on from there.
440    ///
441    /// # Errors
442    ///
443    /// The first event that breaks a rule, as `observe` reports it. The
444    /// events before it stay folded in.
445    pub fn replay<'a>(
446        &mut self,
447        events: impl IntoIterator<Item = &'a Event>,
448    ) -> Result<(), VerificationError> {
449        events.into_iter().try_for_each(|event| self.observe(event))
450    }
451
452    /// Whether the run has sent its `RUN_STARTED`: the run that is open, or
453    /// the last one of a stream that carried several.
454    pub fn has_started(&self) -> bool {
455        self.started.is_some()
456    }
457
458    /// Whether that run has sent a terminal event, so that no run is open.
459    /// A client that joins now is sent the prelude alone, until a
460    /// `RUN_STARTED` begins the next run.
461    pub fn has_ended(&self) -> bool {
462        !self.ended.is_empty()
463    }
464
465    /// What the run has open, in the order it was opened.
466    ///
467    /// After `RUN_ERROR` this is what the run abandoned.
468    ///
469    /// ```
470    /// # use ag_ui::{Event, TextMessageRole};
471    /// # use ag_ui::server::{OpenEntity, RunProgress};
472    /// let mut progress = RunProgress::new();
473    /// progress.replay(&[
474    ///     Event::run_started("thread-1", "run-1"),
475    ///     Event::step_started("draft"),
476    ///     Event::text_message_start("msg-1", TextMessageRole::Assistant),
477    ///     Event::text_message_content("msg-1", "Dear "),
478    ///     Event::text_message_content("msg-1", "Ada,"),
479    /// ])?;
480    ///
481    /// let open: Vec<&OpenEntity> = progress.open().collect();
482    /// assert!(matches!(open[0], OpenEntity::Step { start, .. } if start.step_name.as_str() == "draft"));
483    /// assert!(matches!(open[1], OpenEntity::Message { content, .. } if content == "Dear Ada,"));
484    /// # Ok::<(), ag_ui::server::VerificationError>(())
485    /// ```
486    pub fn open(&self) -> impl Iterator<Item = &OpenEntity> {
487        self.open.iter().map(|slot| &slot.entity)
488    }
489
490    /// Starts the prelude for a client that joins the run where it now is.
491    ///
492    /// See the [module docs](self) for what it holds. It is empty for a run
493    /// that has not started: there is nothing to catch up on, and the client
494    /// reads the run from its first event.
495    pub fn prelude(&self) -> Prelude<'_> {
496        Prelude {
497            progress: self,
498            input: None,
499            messages: None,
500            state: None,
501            restate: true,
502        }
503    }
504
505    // ---- the fold -------------------------------------------------------
506
507    /// Folds one accepted event in, reading it as the ordering rules do: a
508    /// chunk as the events it stands for, and any event as first ending the
509    /// chunk streams it ends.
510    fn fold(&mut self, event: &Event) {
511        let is_chunk = matches!(
512            event,
513            Event::TextMessageChunk(_) | Event::ToolCallChunk(_) | Event::ReasoningMessageChunk(_)
514        );
515        if !is_chunk && self.streams.is_idle() {
516            // The chunk model learns whose each item is from every event.
517            self.streams.note(event);
518            return self.record(event, false);
519        }
520        let mut stood_for = Vec::new();
521        if is_chunk {
522            // The rules accepted it, so it can be placed. With the `verify`
523            // feature off nothing vouches for it, and a chunk that cannot be
524            // placed stands for nothing.
525            if self.streams.expand(event.clone(), &mut stood_for).is_err() {
526                return;
527            }
528        } else {
529            self.streams.end_for(event, &mut stood_for);
530        }
531        for implied in &stood_for {
532            self.record(implied, true);
533        }
534        if !is_chunk {
535            self.record(event, false);
536        }
537    }
538
539    /// Folds in one event of the explicit form. `chunked` says it is one a
540    /// chunk stood for.
541    fn record(&mut self, event: &Event, chunked: bool) {
542        match event {
543            Event::RunStarted(e) => {
544                // The next run on the same stream. What the run before it
545                // left open ended with it; the ids it used stay in use.
546                if self.has_ended() {
547                    self.started = None;
548                    self.ended.clear();
549                    self.open.clear();
550                    self.subagents.clear();
551                }
552                if let Some(input) = &e.input {
553                    self.seen.conversation(&input.messages);
554                }
555                if self.started.is_none() {
556                    // Field by field, so the input echo, the largest payload
557                    // in the protocol, is not copied only to be dropped.
558                    self.started = Some(RunStartedEvent {
559                        base: restated(&e.base),
560                        thread_id: e.thread_id.clone(),
561                        run_id: e.run_id.clone(),
562                        protocol_version: e.protocol_version.clone(),
563                        parent_run_id: e.parent_run_id.clone(),
564                        input: None,
565                    });
566                }
567            }
568            Event::RunFinished(_) | Event::RunError(_) => {
569                let mut terminal = event.clone();
570                terminal.base_mut().raw_event = None;
571                self.ended.push(terminal);
572            }
573            Event::MessagesSnapshot(e) => {
574                self.seen.conversation(&e.messages);
575                self.restated_by(&e.messages);
576            }
577
578            Event::TextMessageStart(e) => {
579                let held_before = !self.seen.messages.insert(e.message_id.clone());
580                let mut start = e.clone();
581                start.base = restated(&e.base);
582                self.push(
583                    OpenEntity::Message {
584                        start,
585                        content: String::new(),
586                        chunked,
587                    },
588                    held_before,
589                );
590            }
591            Event::TextMessageContent(e) => {
592                let found = self.open.iter_mut().find_map(|slot| match &mut slot.entity {
593                    OpenEntity::Message { start, content, .. }
594                        if start.message_id == e.message_id =>
595                    {
596                        Some((&mut start.base, content))
597                    }
598                    _ => None,
599                });
600                if let Some((base, content)) = found {
601                    content.push_str(&e.delta);
602                    merge_metadata_into(&mut base.metadata, e.base.metadata.as_ref());
603                }
604            }
605            Event::TextMessageEnd(e) => self.close(|entity| {
606                matches!(entity, OpenEntity::Message { start, .. } if start.message_id == e.message_id)
607            }),
608
609            Event::ToolCallStart(e) => {
610                let held_before = !self.seen.tool_calls.insert(e.tool_call_id.clone());
611                let mut start = e.clone();
612                start.base = restated(&e.base);
613                self.push(
614                    OpenEntity::ToolCall {
615                        start,
616                        args: String::new(),
617                        chunked,
618                    },
619                    held_before,
620                );
621            }
622            Event::ToolCallArgs(e) => {
623                let found = self.open.iter_mut().find_map(|slot| match &mut slot.entity {
624                    OpenEntity::ToolCall { start, args, .. }
625                        if start.tool_call_id == e.tool_call_id =>
626                    {
627                        Some((&mut start.base, args))
628                    }
629                    _ => None,
630                });
631                if let Some((base, args)) = found {
632                    args.push_str(&e.delta);
633                    merge_metadata_into(&mut base.metadata, e.base.metadata.as_ref());
634                }
635            }
636            Event::ToolCallEnd(e) => self.close(|entity| {
637                matches!(entity, OpenEntity::ToolCall { start, .. } if start.tool_call_id == e.tool_call_id)
638            }),
639            // A result is a tool message under the id it names: text
640            // streamed into that id later adds to the result.
641            Event::ToolCallResult(e) => {
642                self.seen.messages.insert(e.message_id.clone());
643            }
644
645            Event::ReasoningStart(e) => {
646                let mut start = e.clone();
647                start.base = restated(&e.base);
648                self.push(OpenEntity::ReasoningBlock { start }, false);
649            }
650            Event::ReasoningEnd(e) => self.close(|entity| {
651                matches!(entity, OpenEntity::ReasoningBlock { start } if start.message_id == e.message_id)
652            }),
653            Event::ReasoningMessageStart(e) => {
654                let held_before = !self.seen.messages.insert(e.message_id.clone());
655                let mut start = e.clone();
656                start.base = restated(&e.base);
657                self.push(
658                    OpenEntity::ReasoningMessage {
659                        start,
660                        content: String::new(),
661                        chunked,
662                    },
663                    held_before,
664                );
665            }
666            Event::ReasoningMessageContent(e) => {
667                let found = self.open.iter_mut().find_map(|slot| match &mut slot.entity {
668                    OpenEntity::ReasoningMessage { start, content, .. }
669                        if start.message_id == e.message_id =>
670                    {
671                        Some((&mut start.base, content))
672                    }
673                    _ => None,
674                });
675                if let Some((base, content)) = found {
676                    content.push_str(&e.delta);
677                    merge_metadata_into(&mut base.metadata, e.base.metadata.as_ref());
678                }
679            }
680            Event::ReasoningMessageEnd(e) => self.close(|entity| {
681                matches!(entity, OpenEntity::ReasoningMessage { start, .. } if start.message_id == e.message_id)
682            }),
683
684            Event::StepStarted(e) => {
685                let mut start = e.clone();
686                start.base = restated(&e.base);
687                self.push(OpenEntity::Step { start }, false);
688            }
689            // A step is its owner's: a subagent and its parent may each run
690            // one of the same name.
691            Event::StepFinished(e) => self.close(|entity| {
692                matches!(entity, OpenEntity::Step { start }
693                    if start.step_name == e.step_name && start.subagent_run_id == e.subagent_run_id)
694            }),
695
696            Event::SubagentStarted(e) => {
697                let mut start = e.clone();
698                start.base = restated(&e.base);
699                self.subagents.push(Announced {
700                    start: start.clone(),
701                    end: None,
702                });
703                self.push(OpenEntity::Subagent { start }, false);
704            }
705            Event::SubagentFinished(e) => self.close_subagent(&e.subagent_run_id, event),
706            Event::SubagentError(e) => self.close_subagent(&e.subagent_run_id, event),
707
708            // State, activity, raw, custom and encrypted-value events open
709            // and close nothing. A chunk arrives here as what it stood for.
710            _ => {}
711        }
712    }
713
714    fn push(&mut self, entity: OpenEntity, held_before: bool) {
715        self.open.push(Slot {
716            entity,
717            held_before,
718            dropped: false,
719        });
720    }
721
722    /// Folds in a `MESSAGES_SNAPSHOT` that arrived with something open.
723    ///
724    /// A snapshot replaces the messages it carries and drops the ones it
725    /// leaves out, open or not, and closes nothing. So what an open entity
726    /// has produced starts again from here, on top of the snapshot's copy,
727    /// when the snapshot carries it. When it does not, a client holds the
728    /// entity no more and drops what it sends next: AG-UI 1.0
729    /// (`basic/patterns/snapshots`), "a snapshot is not a merge". A
730    /// reasoning message stays as it was through a snapshot that carries no
731    /// reasoning at all.
732    fn restated_by(&mut self, snapshot: &[Message]) {
733        let carries = |id: &MessageId| snapshot.iter().any(|message| message.id() == id);
734        let carries_call = |id: &ToolCallId| {
735            snapshot.iter().any(|message| match message {
736                Message::Assistant(assistant) => {
737                    let mut calls = assistant.tool_calls.iter().flatten();
738                    calls.any(|call| &call.id == id)
739                }
740                _ => false,
741            })
742        };
743        let declares_reasoning = snapshot
744            .iter()
745            .any(|message| matches!(message, Message::Reasoning(_)));
746        for slot in &mut self.open {
747            let carried = match &mut slot.entity {
748                OpenEntity::Message { start, content, .. } => {
749                    content.clear();
750                    carries(&start.message_id)
751                }
752                OpenEntity::ToolCall { start, args, .. } => {
753                    args.clear();
754                    carries_call(&start.tool_call_id)
755                }
756                OpenEntity::ReasoningMessage { start, content, .. } => {
757                    let carried = carries(&start.message_id);
758                    if !carried && !declares_reasoning {
759                        continue;
760                    }
761                    content.clear();
762                    carried
763                }
764                OpenEntity::ReasoningBlock { .. }
765                | OpenEntity::Step { .. }
766                | OpenEntity::Subagent { .. } => continue,
767            };
768            slot.held_before = carried;
769            slot.dropped = !carried;
770        }
771    }
772
773    fn close(&mut self, is: impl Fn(&OpenEntity) -> bool) {
774        if let Some(index) = self.open.iter().position(|slot| is(&slot.entity)) {
775            self.open.remove(index);
776        }
777    }
778
779    fn close_subagent(&mut self, id: &SubagentRunId, end: &Event) {
780        self.close(
781            |entity| matches!(entity, OpenEntity::Subagent { start } if &start.subagent_run_id == id),
782        );
783        let active =
784            self.subagents.iter_mut().rev().find(|announced| {
785                &announced.start.subagent_run_id == id && announced.end.is_none()
786            });
787        if let Some(announced) = active {
788            let mut end = end.clone();
789            end.base_mut().raw_event = None;
790            announced.end = Some(end);
791        }
792    }
793
794    // ---- the prelude ----------------------------------------------------
795
796    /// Takes out of `messages` what a prelude restates: the text of each
797    /// open message, the arguments of each open tool call, the content of
798    /// each open reasoning message. An open entity a snapshot dropped is
799    /// taken out whole, since a client holds none of it. Everything else
800    /// stays where it is.
801    fn take_out(&self, messages: &mut Vec<Message>) {
802        for slot in self.open.iter().filter(|slot| slot.dropped) {
803            match &slot.entity {
804                OpenEntity::Message {
805                    start: TextMessageStartEvent { message_id, .. },
806                    ..
807                }
808                | OpenEntity::ReasoningMessage {
809                    start: ReasoningMessageStartEvent { message_id, .. },
810                    ..
811                } => messages.retain(|message| message.id() != message_id),
812                OpenEntity::ToolCall { start, .. } => {
813                    for message in messages.iter_mut() {
814                        if let Message::Assistant(assistant) = message {
815                            if let Some(calls) = &mut assistant.tool_calls {
816                                calls.retain(|call| call.id != start.tool_call_id);
817                            }
818                        }
819                    }
820                }
821                _ => {}
822            }
823        }
824        for slot in self.open.iter().filter(|slot| !slot.dropped) {
825            match &slot.entity {
826                // An id names one message, whatever its role: text and
827                // reasoning alike land on the message that has the id.
828                OpenEntity::Message {
829                    start: TextMessageStartEvent { message_id, .. },
830                    content,
831                    ..
832                }
833                | OpenEntity::ReasoningMessage {
834                    start: ReasoningMessageStartEvent { message_id, .. },
835                    content,
836                    ..
837                } => {
838                    let held = messages
839                        .iter_mut()
840                        .filter(|message| message.id() == message_id)
841                        .filter_map(streamed_text);
842                    for text in held {
843                        retract(text, content, slot.held_before);
844                    }
845                }
846                OpenEntity::ToolCall { start, args, .. } => {
847                    let calls = messages.iter_mut().filter_map(|message| match message {
848                        Message::Assistant(assistant) => assistant.tool_calls.as_mut(),
849                        _ => None,
850                    });
851                    for call in calls.flatten() {
852                        if call.id == start.tool_call_id {
853                            retract(&mut call.function.arguments, args, slot.held_before);
854                        }
855                    }
856                }
857                OpenEntity::ReasoningBlock { .. }
858                | OpenEntity::Step { .. }
859                | OpenEntity::Subagent { .. } => {}
860            }
861        }
862    }
863
864    /// The lifecycle of the subagents a joining client has to know: each
865    /// active one, and each finished one that one of those descends from.
866    ///
867    /// In the order they started. A parent starts before its child, so
868    /// every `parentSubagentRunId` names a subagent announced before it.
869    fn subagent_lifecycle(&self, events: &mut Vec<Event>) {
870        let mut needed: HashSet<&SubagentRunId> = HashSet::new();
871        for announced in self.subagents.iter().rev() {
872            let id = &announced.start.subagent_run_id;
873            if announced.end.is_none() {
874                needed.insert(id);
875            }
876            if needed.contains(id) {
877                needed.extend(&announced.start.parent_subagent_run_id);
878            }
879        }
880        for announced in &self.subagents {
881            if needed.contains(&announced.start.subagent_run_id) {
882                events.push(announced.start.clone().into());
883                events.extend(announced.end.clone());
884            }
885        }
886    }
887}
888
889/// The base fields a restated event carries: everything but `rawEvent`,
890/// which is the provider event one event was translated from.
891fn restated(base: &BaseEvent) -> BaseEvent {
892    BaseEvent {
893        timestamp: base.timestamp,
894        raw_event: None,
895        metadata: base.metadata.clone(),
896    }
897}
898
899/// The text of a message that a content event adds to, where it has one:
900/// what a client appends a delta to.
901fn streamed_text(message: &mut Message) -> Option<&mut String> {
902    fn last_text(parts: &mut [InputContent]) -> Option<&mut String> {
903        match parts.last_mut() {
904            Some(InputContent::Text(text)) => Some(&mut text.text),
905            _ => None,
906        }
907    }
908    match message {
909        Message::Assistant(assistant) => assistant.content.as_mut(),
910        Message::System(system) => Some(&mut system.content),
911        Message::Developer(developer) => Some(&mut developer.content),
912        Message::User(user) => match &mut user.content {
913            UserContent::Text(text) => Some(text),
914            UserContent::Parts(parts) => last_text(parts),
915        },
916        Message::Tool(tool) => match &mut tool.content {
917            ToolContent::Text(text) => Some(text),
918            ToolContent::Parts(parts) => last_text(parts),
919        },
920        Message::Reasoning(reasoning) => Some(&mut reasoning.content),
921        Message::Activity(_) => None,
922    }
923}
924
925/// Leaves in `held` what an entity held before the content recorded for it,
926/// given that content.
927fn retract(held: &mut String, since: &str, held_before: bool) {
928    if !held_before {
929        // It held nothing, so whatever the list has under this id was
930        // produced since, however much of it.
931        held.clear();
932    } else if held.ends_with(since) {
933        held.truncate(held.len() - since.len());
934    }
935}
936
937impl OpenEntity {
938    /// Appends the events that re-open this entity for a client: its start,
939    /// and with `content` what it has produced since.
940    fn restate(&self, content: bool, events: &mut Vec<Event>) {
941        let since = |text: &String| (content && !text.is_empty()).then(|| text.clone());
942        match self {
943            Self::Message {
944                start,
945                content,
946                chunked: true,
947            } => {
948                let mut chunk =
949                    TextMessageChunkEvent::new(Some(start.message_id.clone()), since(content));
950                chunk.base = start.base.clone();
951                chunk.role = Some(start.role);
952                chunk.name.clone_from(&start.name);
953                chunk.subagent_run_id.clone_from(&start.subagent_run_id);
954                events.push(chunk.into());
955            }
956            Self::Message {
957                start,
958                content,
959                chunked: false,
960            } => {
961                events.push(start.clone().into());
962                if let Some(delta) = since(content) {
963                    events.push(tagged(
964                        Event::text_message_content(start.message_id.clone(), delta),
965                        &start.subagent_run_id,
966                    ));
967                }
968            }
969            Self::ToolCall {
970                start,
971                args,
972                chunked: true,
973            } => {
974                let mut chunk = ToolCallChunkEvent::new(
975                    Some(start.tool_call_id.clone()),
976                    Some(start.tool_call_name.clone()),
977                    since(args),
978                );
979                chunk.base = start.base.clone();
980                chunk.parent_message_id.clone_from(&start.parent_message_id);
981                chunk.subagent_run_id.clone_from(&start.subagent_run_id);
982                events.push(chunk.into());
983            }
984            Self::ToolCall {
985                start,
986                args,
987                chunked: false,
988            } => {
989                events.push(start.clone().into());
990                if let Some(delta) = since(args) {
991                    events.push(tagged(
992                        Event::tool_call_args(start.tool_call_id.clone(), delta),
993                        &start.subagent_run_id,
994                    ));
995                }
996            }
997            Self::ReasoningMessage {
998                start,
999                content,
1000                chunked: true,
1001            } => {
1002                let mut chunk =
1003                    ReasoningMessageChunkEvent::new(Some(start.message_id.clone()), since(content));
1004                chunk.base = start.base.clone();
1005                chunk.subagent_run_id.clone_from(&start.subagent_run_id);
1006                events.push(chunk.into());
1007            }
1008            Self::ReasoningMessage {
1009                start,
1010                content,
1011                chunked: false,
1012            } => {
1013                events.push(start.clone().into());
1014                if let Some(delta) = since(content) {
1015                    events.push(tagged(
1016                        Event::reasoning_message_content(start.message_id.clone(), delta),
1017                        &start.subagent_run_id,
1018                    ));
1019                }
1020            }
1021            Self::ReasoningBlock { start } => events.push(start.clone().into()),
1022            Self::Step { start } => events.push(start.clone().into()),
1023            // Announced with the other subagents, ahead of everything open.
1024            Self::Subagent { .. } => {}
1025        }
1026    }
1027}
1028
1029/// `event`, attributed as the entity it continues is.
1030fn tagged(mut event: Event, owner: &Option<SubagentRunId>) -> Event {
1031    if let Some(owner) = owner {
1032        event.set_subagent_run_id(owner.clone());
1033    }
1034    event
1035}
1036
1037/// The events that take a joining client to where a run is.
1038///
1039/// Built by [`RunProgress::prelude`]. Each method adds something to send;
1040/// nothing is sent that was not asked for. See the [module docs](self) for
1041/// the order and for the reasoning behind each choice.
1042#[derive(Clone, Debug)]
1043#[must_use = "a prelude is only a description until `into_events` builds it"]
1044pub struct Prelude<'a> {
1045    progress: &'a RunProgress,
1046    input: Option<RunAgentInput>,
1047    messages: Option<Vec<Message>>,
1048    state: Option<Value>,
1049    /// Whether each open entity is sent with what it has produced.
1050    restate: bool,
1051}
1052
1053impl Prelude<'_> {
1054    /// Carries the conversation as `MESSAGES_SNAPSHOT`, right after
1055    /// `RUN_STARTED`.
1056    ///
1057    /// `messages` is everything the thread holds that is complete: the
1058    /// earlier turns and what this run has finished. It may hold what is
1059    /// open as well. The snapshot is these messages with [what the prelude
1060    /// restates taken out](self#what-is-open-is-taken-out-of-the-messages),
1061    /// so no list makes a client hold anything twice.
1062    ///
1063    /// A snapshot is the carrier to prefer. Every client takes it, and it
1064    /// is right for a client that already holds part of the conversation:
1065    /// it replaces the messages it carries and drops the ones it leaves out,
1066    /// where [`echo_input`](Self::echo_input) at most adds.
1067    pub fn messages(mut self, messages: impl Into<Vec<Message>>) -> Self {
1068        self.messages = Some(messages.into());
1069        self.restate = true;
1070        self
1071    }
1072
1073    /// Echoes a request on `RUN_STARTED`, as
1074    /// [`Runner::echo_input`](crate::server::Runner::echo_input) does on a
1075    /// run's own.
1076    ///
1077    /// The reference TypeScript client adds the echoed messages whose ids
1078    /// it does not hold and leaves the ones it holds as they are, so the
1079    /// echo carries the conversation to such a client when it holds none of
1080    /// it. This crate's own client reads the echo for who owns which
1081    /// message and adds nothing to its conversation.
1082    /// [`messages`](Self::messages) is the carrier for the rest. What the
1083    /// prelude restates is taken out of `input.messages` as it is out of a
1084    /// snapshot.
1085    ///
1086    /// The echo is the whole request: state, tools, context and forwarded
1087    /// properties as well as the messages.
1088    pub fn echo_input(mut self, input: RunAgentInput) -> Self {
1089        self.input = Some(input);
1090        self
1091    }
1092
1093    /// Carries the state as `STATE_SNAPSHOT`, before anything is re-opened.
1094    ///
1095    /// For a run that publishes state: the `STATE_DELTA`s that follow patch
1096    /// the state the client holds, and a client that joins holds none.
1097    pub fn state(mut self, state: impl Into<Value>) -> Self {
1098        self.state = Some(state.into());
1099        self
1100    }
1101
1102    /// Re-opens what is open without restating it, and sends no snapshot.
1103    ///
1104    /// For a client known to hold each open entity exactly as it stands at
1105    /// this point of the run: see [the module
1106    /// docs](self#a-client-that-holds-the-run-up-to-a-point). A snapshot
1107    /// would replace what that client holds, so the messages given to
1108    /// [`messages`](Self::messages) are dropped; calling `messages`
1109    /// afterwards goes back to restating.
1110    pub fn reopen_only(mut self) -> Self {
1111        self.messages = None;
1112        self.restate = false;
1113        self
1114    }
1115
1116    /// The prelude, in the order to send it.
1117    pub fn into_events(self) -> Vec<Event> {
1118        let Self {
1119            progress,
1120            input,
1121            messages,
1122            state,
1123            restate,
1124        } = self;
1125        let mut events = Vec::new();
1126        if let Some(started) = &progress.started {
1127            let mut started = started.clone();
1128            started.input = input.map(|mut input| {
1129                if restate {
1130                    progress.take_out(&mut input.messages);
1131                }
1132                Box::new(input)
1133            });
1134            events.push(started.into());
1135            // What a snapshot dropped while it was open is opened ahead of
1136            // the snapshot, which drops it again: the client then holds it
1137            // open with nothing to write to, as one that read the run does,
1138            // and drops what it sends next. Its subagent is announced first.
1139            let dropped = progress.open.iter().filter(|slot| slot.dropped);
1140            let ahead = messages.is_some() && dropped.clone().next().is_some();
1141            if ahead {
1142                progress.subagent_lifecycle(&mut events);
1143                for slot in dropped {
1144                    slot.entity.restate(false, &mut events);
1145                }
1146            }
1147            if let Some(mut messages) = messages {
1148                progress.take_out(&mut messages);
1149                events.push(Event::messages_snapshot(messages));
1150            }
1151            events.extend(state.map(Event::state_snapshot));
1152            if !ahead {
1153                progress.subagent_lifecycle(&mut events);
1154            }
1155            for slot in &progress.open {
1156                if !(ahead && slot.dropped) {
1157                    // A dropped entity has produced nothing a client holds.
1158                    slot.entity.restate(restate && !slot.dropped, &mut events);
1159                }
1160            }
1161        }
1162        events.extend(progress.ended.iter().cloned());
1163        events
1164    }
1165}
1166
1167#[cfg(test)]
1168mod tests {
1169    use super::*;
1170    use crate::TextMessageRole;
1171
1172    fn chunk(id: Option<&str>, delta: &str) -> Event {
1173        Event::text_message_chunk(id.map(MessageId::new), Some(delta.to_owned()))
1174    }
1175
1176    /// Streams that open and close everything, in both spellings, with two
1177    /// lanes at once, and one whose first run fails with things open before
1178    /// two more runs follow it.
1179    fn runs() -> Vec<Vec<Event>> {
1180        let s1 = |event: Event| event.with_subagent_run_id("s1");
1181        vec![
1182            vec![
1183                Event::run_started("t", "r"),
1184                Event::step_started("plan"),
1185                Event::subagent_started("s1", "helper"),
1186                s1(Event::step_started("plan")),
1187                Event::reasoning_start("r1"),
1188                Event::reasoning_message_start("r1"),
1189                Event::reasoning_message_content("r1", "hm"),
1190                s1(Event::text_message_start("m1", TextMessageRole::Assistant)),
1191                Event::tool_call_start("c1", "search"),
1192                Event::reasoning_message_end("r1"),
1193                Event::tool_call_args("c1", "{}"),
1194                s1(Event::text_message_content("m1", "hi")),
1195                Event::reasoning_end("r1"),
1196                Event::tool_call_end("c1"),
1197                s1(Event::text_message_end("m1")),
1198                Event::tool_call_result("m2", "c1", "ok"),
1199                s1(Event::step_finished("plan")),
1200                Event::subagent_finished_success("s1"),
1201                // The same id, open a second time.
1202                Event::text_message_start("m1", TextMessageRole::Assistant),
1203                Event::text_message_end("m1"),
1204                Event::step_finished("plan"),
1205                Event::run_finished_success("t", "r"),
1206            ],
1207            vec![
1208                Event::run_started("t", "r"),
1209                chunk(Some("m1"), "a"),
1210                s1(Event::tool_call_chunk(
1211                    Some("c1".into()),
1212                    Some("search".into()),
1213                    None,
1214                )),
1215                chunk(None, "b"),
1216                // Explicit, in the parent's lane: ends the parent's stream.
1217                Event::text_message_start("m2", TextMessageRole::Assistant),
1218                Event::reasoning_message_chunk(Some("r1".into()), Some("hm".into())),
1219                Event::messages_snapshot(Vec::new()),
1220                chunk(Some("m3"), "c"),
1221                Event::text_message_end("m2"),
1222                Event::run_finished_success("t", "r"),
1223            ],
1224            vec![
1225                Event::run_started("t", "r"),
1226                Event::step_started("plan"),
1227                Event::text_message_start("m1", TextMessageRole::Assistant),
1228                chunk(Some("m2"), "a"),
1229                Event::subagent_started("s1", "helper"),
1230                Event::run_error("gone"),
1231                // The next run on the same stream: nothing is open, and the
1232                // names the failed run used are free.
1233                Event::run_started("t", "r2"),
1234                Event::step_started("plan"),
1235                Event::subagent_started("s1", "helper"),
1236                Event::subagent_finished_success("s1"),
1237                Event::step_finished("plan"),
1238                Event::run_finished_success("t", "r2"),
1239                Event::run_started("t", "r3"),
1240                Event::text_message_start("m1", TextMessageRole::Assistant),
1241            ],
1242        ]
1243    }
1244
1245    #[cfg(feature = "verify")]
1246    #[test]
1247    fn the_fold_has_open_what_the_ordering_rules_have_open() {
1248        use crate::ordering::{OpenSets, Ordering, Policy};
1249
1250        for run in runs() {
1251            let mut rules = Ordering::new(Policy::PRODUCER);
1252            let mut progress = RunProgress::new();
1253            for event in &run {
1254                rules.observe(event).expect("the run is well formed");
1255                progress.observe(event).expect("the run is well formed");
1256
1257                let mut folded = OpenSets::default();
1258                for entity in progress.open() {
1259                    match entity {
1260                        OpenEntity::Message { start, .. } => {
1261                            folded.messages.push(&start.message_id);
1262                        }
1263                        OpenEntity::ToolCall { start, .. } => {
1264                            folded.tool_calls.push(&start.tool_call_id);
1265                        }
1266                        OpenEntity::ReasoningMessage { start, .. } => {
1267                            folded.reasoning_messages.push(&start.message_id);
1268                        }
1269                        OpenEntity::ReasoningBlock { start } => {
1270                            folded.reasoning_blocks.push(&start.message_id);
1271                        }
1272                        OpenEntity::Step { start } => folded.steps.push((
1273                            start.subagent_run_id.as_ref().map(SubagentRunId::as_str),
1274                            &start.step_name,
1275                        )),
1276                        OpenEntity::Subagent { start } => {
1277                            folded.subagents.push(&start.subagent_run_id);
1278                        }
1279                    }
1280                }
1281                assert_eq!(folded, rules.open(), "after {event:?}");
1282            }
1283        }
1284    }
1285
1286    #[test]
1287    fn a_chunk_stream_is_open_in_the_chunked_spelling_until_it_ends() {
1288        let run = &runs()[1];
1289        let mut progress = RunProgress::new();
1290        for event in &run[..4] {
1291            progress.fold(event);
1292        }
1293        let spelled: Vec<(&str, bool)> = progress
1294            .open()
1295            .filter_map(|entity| match entity {
1296                OpenEntity::Message {
1297                    content, chunked, ..
1298                } => Some((content.as_str(), *chunked)),
1299                OpenEntity::ToolCall { args, chunked, .. } => Some((args.as_str(), *chunked)),
1300                _ => None,
1301            })
1302            .collect();
1303        assert_eq!(spelled, [("ab", true), ("", true)]);
1304
1305        // The explicit start ends the parent's stream and opens `m2`.
1306        progress.fold(&run[4]);
1307        let open: Vec<&OpenEntity> = progress.open().collect();
1308        assert!(
1309            matches!(open[..], [
1310                OpenEntity::ToolCall { chunked: true, .. },
1311                OpenEntity::Message { start, chunked: false, .. },
1312            ] if start.message_id.as_str() == "m2"),
1313            "{open:?}"
1314        );
1315    }
1316
1317    #[test]
1318    fn events_no_verifier_vouched_for_are_folded_without_harm() {
1319        // What `observe` rejects with the `verify` feature reaches the fold
1320        // without it.
1321        let mut progress = RunProgress::new();
1322        for event in [
1323            Event::text_message_content("never-opened", "x"),
1324            Event::text_message_end("never-opened"),
1325            Event::tool_call_args("never-opened", "x"),
1326            Event::step_finished("never-started"),
1327            Event::subagent_finished_success("never-started"),
1328            chunk(None, "continues nothing"),
1329            Event::tool_call_chunk(Some("unnamed".into()), None, None),
1330            Event::run_finished_success("t", "r"),
1331        ] {
1332            progress.fold(&event);
1333        }
1334        assert_eq!(progress.open().count(), 0);
1335        assert!(!progress.has_started() && progress.has_ended());
1336    }
1337
1338    #[test]
1339    fn only_what_was_produced_since_the_start_is_taken_out() {
1340        let taken_out = |held: &str, since: &str, held_before: bool| {
1341            let mut held = held.to_owned();
1342            retract(&mut held, since, held_before);
1343            held
1344        };
1345        // Opened for the first time: nothing was there before, so nothing
1346        // stays, whichever copy the list holds.
1347        assert_eq!(taken_out("Hello wor", "Hello wor", false), "");
1348        assert_eq!(taken_out("Hel", "Hello wor", false), "");
1349        assert_eq!(taken_out("Hello world, and more", "Hello wor", false), "");
1350        // Opened again: what was there before stays.
1351        assert_eq!(taken_out("Earlier. Hello", " Hello", true), "Earlier.");
1352        assert_eq!(taken_out("Earlier.", " Hello", true), "Earlier.");
1353        assert_eq!(taken_out("Earlier.", "", true), "Earlier.");
1354    }
1355}