Skip to main content

aether_core/testing/
utils.rs

1use std::collections::BTreeMap;
2use std::sync::{Arc, Mutex};
3use std::time::Duration;
4use tokio::sync::{Notify, mpsc};
5
6use crate::context::CompactionConfig;
7use crate::core::{AgentError, Prompt, RetryConfig, agent};
8use crate::events::{
9    AgentCommand, AgentEvent, AgentObserver, Command, ContextEvent, ToolEvent, TurnEvent, UserCommand,
10};
11use crate::mcp::mcp;
12use crate::testing::{AgentTrace, FakeAgentObserver, FakeMcpServer, McpBuilderTestExt};
13use llm::{ChatMessage, Context, LlmError, LlmModel, LlmResponse, ModelSettings, StreamingModelProvider};
14
15use llm::testing::FakeLlmProvider;
16
17pub async fn drain_until(
18    receiver: &mut mpsc::Receiver<AgentEvent>,
19    predicate: impl Fn(&AgentEvent) -> bool,
20) -> Vec<AgentEvent> {
21    let mut events = Vec::new();
22    while let Some(event) = receiver.recv().await {
23        let matched = predicate(&event);
24        events.push(event);
25        if matched {
26            return events;
27        }
28    }
29    panic!("agent event channel closed before predicate matched");
30}
31
32pub fn content_events(events: Vec<AgentEvent>) -> Vec<AgentEvent> {
33    events
34        .into_iter()
35        .filter(|event| {
36            !matches!(
37                event,
38                AgentEvent::Turn(
39                    TurnEvent::Started { .. } | TurnEvent::LlmCallStarted { .. } | TurnEvent::LlmCallEnded { .. }
40                ) | AgentEvent::Tool(ToolEvent::ExecutionStarted { .. } | ToolEvent::DefinitionsUpdated { .. })
41            )
42        })
43        .collect()
44}
45
46pub fn mcp_instructions(entries: &[(&str, &str)]) -> BTreeMap<String, String> {
47    entries.iter().map(|(k, v)| ((*k).to_string(), (*v).to_string())).collect()
48}
49
50pub fn test_agent() -> TestAgentBuilder {
51    TestAgentBuilder::new()
52}
53
54/// An ordered interaction with a test agent.
55pub enum TestAgentStep {
56    Send(Command),
57    WaitFor(Box<dyn Fn(&AgentEvent) -> bool + Send>),
58    /// Run an arbitrary side effect (e.g. releasing a paused LLM stream) between steps.
59    Perform(Box<dyn FnOnce() + Send>),
60}
61
62impl TestAgentStep {
63    pub fn send(command: Command) -> Self {
64        Self::Send(command)
65    }
66
67    pub fn user_text(text: impl Into<String>) -> Self {
68        Self::send(Command::UserCommand(UserCommand::Text { content: vec![llm::ContentBlock::text(text.into())] }))
69    }
70
71    pub fn cancel() -> Self {
72        Self::send(Command::UserCommand(UserCommand::Cancel))
73    }
74
75    pub fn switch_model(provider: impl StreamingModelProvider + 'static) -> Self {
76        Self::send(Command::AgentCommand(AgentCommand::SwitchModel(Box::new(provider))))
77    }
78
79    pub fn replace_conversation(messages: Vec<ChatMessage>) -> Self {
80        Self::send(Command::AgentCommand(AgentCommand::ReplaceConversation(messages)))
81    }
82
83    pub fn perform(action: impl FnOnce() + Send + 'static) -> Self {
84        Self::Perform(Box::new(action))
85    }
86
87    pub fn wait_for(predicate: impl Fn(&AgentEvent) -> bool + Send + 'static) -> Self {
88        Self::WaitFor(Box::new(predicate))
89    }
90
91    pub fn wait_for_turn_end() -> Self {
92        Self::wait_for(|event| matches!(event, AgentEvent::Turn(TurnEvent::Ended { .. })))
93    }
94
95    pub fn wait_for_compaction_start() -> Self {
96        Self::wait_for(|event| matches!(event, AgentEvent::Context(ContextEvent::CompactionStarted { .. })))
97    }
98
99    pub fn wait_for_retry(attempt: u32) -> Self {
100        Self::wait_for(
101            move |event| matches!(event, AgentEvent::Turn(TurnEvent::RetryScheduled { attempt: actual, .. }) if *actual == attempt),
102        )
103    }
104}
105
106/// A fluent sequence of commands and synchronization points for a test agent.
107#[derive(Default)]
108pub struct TestScenario {
109    steps: Vec<TestAgentStep>,
110}
111
112impl TestScenario {
113    pub fn new() -> Self {
114        Self::default()
115    }
116
117    pub fn send(mut self, command: Command) -> Self {
118        self.steps.push(TestAgentStep::send(command));
119        self
120    }
121
122    pub fn user_text(mut self, text: impl Into<String>) -> Self {
123        self.steps.push(TestAgentStep::user_text(text));
124        self
125    }
126
127    pub fn cancel(mut self) -> Self {
128        self.steps.push(TestAgentStep::cancel());
129        self
130    }
131
132    pub fn switch_model(mut self, provider: impl StreamingModelProvider + 'static) -> Self {
133        self.steps.push(TestAgentStep::switch_model(provider));
134        self
135    }
136
137    pub fn replace_conversation(mut self, messages: Vec<ChatMessage>) -> Self {
138        self.steps.push(TestAgentStep::replace_conversation(messages));
139        self
140    }
141
142    pub fn wait_for(mut self, predicate: impl Fn(&AgentEvent) -> bool + Send + 'static) -> Self {
143        self.steps.push(TestAgentStep::wait_for(predicate));
144        self
145    }
146
147    pub fn wait_for_turn_end(mut self) -> Self {
148        self.steps.push(TestAgentStep::wait_for_turn_end());
149        self
150    }
151
152    pub fn wait_for_compaction_start(mut self) -> Self {
153        self.steps.push(TestAgentStep::wait_for_compaction_start());
154        self
155    }
156
157    pub fn wait_for_retry(mut self, attempt: u32) -> Self {
158        self.steps.push(TestAgentStep::wait_for_retry(attempt));
159        self
160    }
161
162    /// Run an arbitrary side effect between scenario steps, e.g. releasing a
163    /// paused LLM stream so a queued message can be injected mid-turn.
164    pub fn perform(mut self, action: impl FnOnce() + Send + 'static) -> Self {
165        self.steps.push(TestAgentStep::perform(action));
166        self
167    }
168}
169
170impl From<Vec<TestAgentStep>> for TestScenario {
171    fn from(steps: Vec<TestAgentStep>) -> Self {
172        Self { steps }
173    }
174}
175
176/// Result of running a test agent, including messages and captured contexts.
177pub struct TestAgentResult {
178    pub messages: Vec<AgentEvent>,
179    pub captured_contexts: Arc<Mutex<Vec<Context>>>,
180}
181
182/// Error returned by [`TestAgentBuilder::run`], [`TestAgentBuilder::run_trace`], and
183/// [`TestAgentBuilder::run_with_context`].
184#[derive(Debug, thiserror::Error)]
185pub enum TestAgentError {
186    #[error(transparent)]
187    Agent(#[from] AgentError),
188    #[error("failed to send command to the test agent: {0}")]
189    SendCommand(#[from] mpsc::error::SendError<Command>),
190}
191
192pub type TestResult<T> = std::result::Result<T, TestAgentError>;
193
194struct ProviderTestConfig {
195    responses: Vec<Vec<Result<LlmResponse, LlmError>>>,
196    model: Option<LlmModel>,
197    context_window: Option<u32>,
198    pause: Option<(usize, usize, Arc<Notify>)>,
199}
200
201struct AgentTestConfig {
202    context_window_override: Option<u32>,
203    timeout: Option<Duration>,
204    max_auto_continues: Option<u32>,
205    retry_config: Option<RetryConfig>,
206    observers: Vec<Box<dyn AgentObserver>>,
207    mcp_server: Option<(String, FakeMcpServer)>,
208    initial_messages: Vec<ChatMessage>,
209    system_prompt: Option<Prompt>,
210    compaction: Option<CompactionConfig>,
211    model_settings: Option<ModelSettings>,
212}
213
214enum TestExecution {
215    CommandsUntilTurnEnd(Vec<Command>),
216    Scenario(TestScenario),
217}
218
219pub struct TestAgentBuilder {
220    provider: ProviderTestConfig,
221    agent: AgentTestConfig,
222    execution: Option<TestExecution>,
223}
224
225impl Default for TestAgentBuilder {
226    fn default() -> Self {
227        Self::new()
228    }
229}
230
231impl TestAgentBuilder {
232    pub fn new() -> Self {
233        Self {
234            provider: ProviderTestConfig { responses: Vec::new(), model: None, context_window: None, pause: None },
235            agent: AgentTestConfig {
236                context_window_override: None,
237                timeout: None,
238                max_auto_continues: None,
239                retry_config: None,
240                observers: Vec::new(),
241                mcp_server: Some(("test".to_string(), FakeMcpServer::new())),
242                initial_messages: Vec::new(),
243                system_prompt: None,
244                compaction: None,
245                model_settings: None,
246            },
247            execution: None,
248        }
249    }
250
251    pub fn commands(self, commands: Vec<Command>) -> Self {
252        self.with_execution(TestExecution::CommandsUntilTurnEnd(commands))
253    }
254
255    pub fn scenario(self, scenario: impl Into<TestScenario>) -> Self {
256        self.with_execution(TestExecution::Scenario(scenario.into()))
257    }
258
259    pub fn user_text(self, text: &str) -> Self {
260        self.commands(vec![Command::UserCommand(UserCommand::Text { content: vec![llm::ContentBlock::text(text)] })])
261    }
262
263    pub fn llm_responses(mut self, llm_responses: &[Vec<LlmResponse>]) -> Self {
264        self.provider.responses = llm_responses.iter().map(|turn| turn.iter().cloned().map(Ok).collect()).collect();
265        self
266    }
267
268    pub fn llm_result_responses(mut self, llm_responses: &[Vec<Result<LlmResponse, LlmError>>]) -> Self {
269        self.provider.responses = Vec::from(llm_responses);
270        self
271    }
272
273    pub fn model(mut self, model: LlmModel) -> Self {
274        self.provider.model = Some(model);
275        self
276    }
277
278    pub fn provider_context_window(mut self, window: Option<u32>) -> Self {
279        self.provider.context_window = window;
280        self
281    }
282
283    pub fn context_window_override(mut self, window: u32) -> Self {
284        self.agent.context_window_override = Some(window);
285        self
286    }
287
288    pub fn tool_timeout(mut self, timeout: Duration) -> Self {
289        self.agent.timeout = Some(timeout);
290        self
291    }
292
293    pub fn max_auto_continues(mut self, max: u32) -> Self {
294        self.agent.max_auto_continues = Some(max);
295        self
296    }
297
298    pub fn retry_config(mut self, config: RetryConfig) -> Self {
299        self.agent.retry_config = Some(config);
300        self
301    }
302
303    /// Run without the default fake MCP server when the scenario does not exercise tools.
304    pub fn without_mcp(mut self) -> Self {
305        self.agent.mcp_server = None;
306        self
307    }
308
309    /// Replace the default fake MCP server with a scripted server.
310    pub fn fake_mcp_server(mut self, name: &str, server: FakeMcpServer) -> Self {
311        self.agent.mcp_server = Some((name.to_string(), server));
312        self
313    }
314
315    /// Pre-populate the context with conversation history.
316    pub fn messages(mut self, messages: Vec<ChatMessage>) -> Self {
317        self.agent.initial_messages = messages;
318        self
319    }
320
321    /// Set the system prompt.
322    pub fn system_prompt(mut self, prompt: Prompt) -> Self {
323        self.agent.system_prompt = Some(prompt);
324        self
325    }
326
327    /// Configure context compaction settings.
328    pub fn compaction_config(mut self, config: CompactionConfig) -> Self {
329        self.agent.compaction = Some(config);
330        self
331    }
332
333    /// Set the model settings applied to every LLM call.
334    pub fn model_settings(mut self, settings: ModelSettings) -> Self {
335        self.agent.model_settings = Some(settings);
336        self
337    }
338
339    /// Pause the fake LLM stream at `turn_index` / `chunk_index` until
340    /// `release.notify_one()` is called. Used for deterministic timing tests.
341    pub fn pause_turn_after(mut self, turn_index: usize, chunk_index: usize, release: Arc<Notify>) -> Self {
342        self.provider.pause = Some((turn_index, chunk_index, release));
343        self
344    }
345
346    /// Attach an observer of the test agent's event stream.
347    pub fn observer(mut self, observer: Box<dyn AgentObserver>) -> Self {
348        self.agent.observers.push(observer);
349        self
350    }
351
352    pub async fn run(self) -> TestResult<Vec<AgentEvent>> {
353        let result = self.run_with_context().await?;
354        Ok(result.messages)
355    }
356
357    /// Runs the test agent with a recording observer attached and returns the
358    /// full event trace, including internal events.
359    pub async fn run_trace(self) -> TestResult<AgentTrace> {
360        let observer = FakeAgentObserver::new();
361        let events = observer.events();
362        self.observer(Box::new(observer)).run().await?;
363        Ok(AgentTrace::from_observer_events(&events))
364    }
365
366    /// Runs the test agent and returns both messages and captured contexts.
367    ///
368    /// Use this when you need to verify what context was passed to the LLM,
369    /// for example when testing that file attachments are properly formatted.
370    pub async fn run_with_context(self) -> TestResult<TestAgentResult> {
371        let Self { provider, agent: config, execution } = self;
372        let mut llm = FakeLlmProvider::from_results(provider.responses).with_context_window(provider.context_window);
373        if let Some(model) = provider.model {
374            llm = llm.with_model(model);
375        }
376        if let Some((turn_index, chunk_index, release)) = provider.pause {
377            llm = llm.pause_turn_after(turn_index, chunk_index, release);
378        }
379        let captured_contexts = llm.captured_contexts();
380
381        let mut mcp_spawn = match config.mcp_server {
382            Some((name, server)) => {
383                Some(mcp("/workspace").with_fake_mcp(name, server).spawn().await.map_err(AgentError::from)?)
384            }
385            None => None,
386        };
387
388        let mut builder = agent(llm);
389        if let Some(spawn) = &mut mcp_spawn {
390            let snapshot = spawn.block_until_ready().await.expect("bootstrap completes");
391            builder = builder.tools(spawn.handle().clone(), snapshot.tool_definitions());
392        }
393        if let Some(timeout) = config.timeout {
394            builder = builder.tool_timeout(timeout);
395        }
396        if let Some(max) = config.max_auto_continues {
397            builder = builder.max_auto_continues(max);
398        }
399        if let Some(retry) = config.retry_config {
400            builder = builder.retry(retry);
401        } else {
402            builder = builder.retry(RetryConfig::disabled());
403        }
404        if let Some(prompt) = config.system_prompt {
405            builder = builder.system_prompt(prompt);
406        }
407        if let Some(compaction) = config.compaction {
408            builder = builder.compaction(compaction);
409        }
410        if let Some(settings) = config.model_settings {
411            builder = builder.model_settings(settings);
412        }
413        builder = builder.context_window(config.context_window_override);
414        if !config.initial_messages.is_empty() {
415            builder = builder.messages(config.initial_messages);
416        }
417        for observer in config.observers {
418            builder = builder.observer(observer);
419        }
420
421        let steps = match execution.expect("test agent requires commands(), user_text(), or scenario()") {
422            TestExecution::CommandsUntilTurnEnd(commands) => {
423                assert!(!commands.is_empty(), "commands() requires at least one command");
424                let mut steps = commands.into_iter().map(TestAgentStep::send).collect::<Vec<_>>();
425                steps.push(TestAgentStep::wait_for_turn_end());
426                steps
427            }
428            TestExecution::Scenario(scenario) => {
429                assert!(!scenario.steps.is_empty(), "scenario() requires at least one step");
430                scenario.steps
431            }
432        };
433        let (tx, mut rx, handle) = builder.spawn().await?;
434        let mut messages = Vec::new();
435
436        for step in steps {
437            match step {
438                TestAgentStep::Send(command) => tx.send(command).await?,
439                TestAgentStep::WaitFor(predicate) => loop {
440                    let message = rx.recv().await.expect("agent event channel closed before scenario step matched");
441                    let matched = predicate(&message);
442                    messages.push(message);
443                    if matched {
444                        break;
445                    }
446                },
447                TestAgentStep::Perform(action) => action(),
448            }
449        }
450        drop(tx);
451
452        handle.await_completion().await;
453
454        Ok(TestAgentResult { messages, captured_contexts })
455    }
456
457    fn with_execution(mut self, execution: TestExecution) -> Self {
458        assert!(self.execution.is_none(), "commands(), user_text(), and scenario() are mutually exclusive");
459        self.execution = Some(execution);
460        self
461    }
462}