Skip to main content

ag_ui/client/transport/
replay.rs

1//! A transport that replays a scripted list of events.
2//!
3//! Testing a client against a live agent is slow, flaky, and needs a model. It
4//! is also unnecessary: the agent's half of the conversation is just a list of
5//! events. [`ReplayTransport`] serves one — and records the
6//! [`RunAgentInput`]s it was handed, which is how a test asserts that a resume
7//! carried the right answers.
8//!
9//! The script is typed, but it stands in for a remote agent, so each event is
10//! serialized and read back through the compatibility boundary
11//! ([`TransportStream::enforced`]): a test sees what a client makes of the
12//! bytes, warnings included.
13//!
14//! ```
15//! use ag_ui::client::transport::ReplayTransport;
16//! use ag_ui::Event;
17//!
18//! let transport = ReplayTransport::new([
19//!     Event::run_started("thread-1", "run-1"),
20//!     Event::run_finished_success("thread-1", "run-1"),
21//! ]);
22//! ```
23
24use std::collections::VecDeque;
25use std::sync::{Arc, Mutex, MutexGuard};
26
27use crate::{Event, RunAgentInput};
28
29use crate::client::error::Error;
30use crate::client::transport::{Transport, TransportFuture, TransportStream};
31
32/// A [`Transport`] that answers each run from a script.
33///
34/// Cloning shares the script and the recording, so a test can keep a handle
35/// after handing one to a [`Thread`](crate::client::Thread).
36#[derive(Clone, Debug, Default)]
37pub struct ReplayTransport {
38    inner: Arc<Mutex<Script>>,
39    matching_requests: bool,
40}
41
42#[derive(Debug, Default)]
43struct Script {
44    runs: VecDeque<Vec<Event>>,
45    requests: Vec<RunAgentInput>,
46}
47
48impl ReplayTransport {
49    /// A transport that answers the first run with these events, and every
50    /// later run with an error.
51    pub fn new(events: impl IntoIterator<Item = Event>) -> Self {
52        Self::with_runs([events.into_iter().collect::<Vec<_>>()])
53    }
54
55    /// A transport that answers each run with the next list in the script.
56    ///
57    /// This is what a human-in-the-loop round trip needs: the first run pauses
58    /// on an interrupt, the second — the resume — carries on.
59    pub fn with_runs(runs: impl IntoIterator<Item = Vec<Event>>) -> Self {
60        Self {
61            matching_requests: false,
62            inner: Arc::new(Mutex::new(Script {
63                runs: runs.into_iter().collect(),
64                requests: Vec::new(),
65            })),
66        }
67    }
68
69    /// Rebind each script's first RUN_STARTED and its matching RUN_FINISHED
70    /// to the actual request IDs, including IDs in the start event's input echo.
71    /// The echo preserves the recorded history. Unmatched terminal IDs stay unchanged so
72    /// malformed fixtures still fail. The default replays events literally.
73    ///
74    /// In a script of several runs this makes the first one the requested
75    /// run. To script runs replayed ahead of it, leave this off and give the
76    /// last run the id set with
77    /// [`Thread::set_next_run_id`](crate::client::Thread::set_next_run_id).
78    #[must_use]
79    pub fn matching_requests(mut self) -> Self {
80        self.matching_requests = true;
81        self
82    }
83
84    /// Every request this transport has been handed, in order.
85    pub fn requests(&self) -> Vec<RunAgentInput> {
86        self.lock().requests.clone()
87    }
88
89    /// The most recent request, if there has been one.
90    pub fn last_request(&self) -> Option<RunAgentInput> {
91        self.lock().requests.last().cloned()
92    }
93
94    /// How many runs are left in the script.
95    pub fn remaining(&self) -> usize {
96        self.lock().runs.len()
97    }
98
99    /// A poisoned lock still holds a perfectly good script — a test that
100    /// panicked mid-assert should fail on that panic, not on this mutex.
101    fn lock(&self) -> MutexGuard<'_, Script> {
102        self.inner.lock().unwrap_or_else(|error| error.into_inner())
103    }
104}
105
106impl Transport for ReplayTransport {
107    fn run(&self, input: RunAgentInput) -> TransportFuture {
108        let mut script = self.lock();
109        script.requests.push(input.clone());
110        let mut next = script.runs.pop_front();
111        if self.matching_requests {
112            if let Some(events) = &mut next {
113                let original = events.iter().find_map(|event| match event {
114                    Event::RunStarted(e) => Some((e.thread_id.clone(), e.run_id.clone())),
115                    _ => None,
116                });
117                if let Some((thread_id, run_id)) = original {
118                    for event in events {
119                        match event {
120                            Event::RunStarted(e)
121                                if e.thread_id == thread_id && e.run_id == run_id =>
122                            {
123                                if let Some(echo) = e.input.as_mut().filter(|echo| {
124                                    echo.thread_id == thread_id && echo.run_id == run_id
125                                }) {
126                                    echo.thread_id = input.thread_id.clone();
127                                    echo.run_id = input.run_id.clone();
128                                }
129                                e.thread_id = input.thread_id.clone();
130                                e.run_id = input.run_id.clone();
131                            }
132                            Event::RunFinished(e)
133                                if e.thread_id == thread_id && e.run_id == run_id =>
134                            {
135                                e.thread_id = input.thread_id.clone();
136                                e.run_id = input.run_id.clone();
137                            }
138                            _ => {}
139                        }
140                    }
141                }
142            }
143        }
144        drop(script);
145
146        Box::pin(async move {
147            let Some(events) = next else {
148                return Err(Error::Transport(
149                    "the replay script has no runs left".into(),
150                ));
151            };
152            let stream = futures_util::stream::iter(events.into_iter().map(Ok));
153            Ok(TransportStream::typed(stream).enforced())
154        })
155    }
156}