返回 CodeWhale
testing.rs
根目录 / crates / workflow-js / src / testing.rs
1 //! Test support: a scriptable in-memory [`WorkflowDriver`].
2 //!
3 //! [`FakeDriver`] records every [`TaskRequest`] and [`ProgressEvent`] it
4 //! receives, answers spawns from substring-matched reply rules (with optional
5 //! delays for ordering tests), and counts `cancel_all` calls. It exists so
6 //! this crate — and the tui wiring that implements the real driver — can be
7 //! exercised without spawning a single real subagent.
8
9 use std::sync::Mutex;
10 use std::sync::atomic::{AtomicUsize, Ordering};
11 use std::time::Duration;
12
13 use async_trait::async_trait;
14 use tokio::sync::oneshot;
15
16 use crate::driver::{ProgressEvent, SpawnedTask, TaskCompletion, TaskRequest, WorkflowDriver};
17 use crate::error::DriverError;
18
19 /// How the fake answers a matched spawn.
20 #[derive(Debug, Clone)]
21 pub enum FakeReply {
22 /// Resolve with this full result text.
23 Complete(String),
24 /// Resolve as a failed subagent.
25 Fail(String),
26 /// Resolve as cancelled.
27 Cancelled,
28 /// Resolve as budget-exhausted mid-flight.
29 BudgetExhausted(String),
30 /// Refuse admission: `spawn_task` returns [`DriverError::Rejected`].
31 Reject(String),
32 /// The driver seam is gone: `spawn_task` returns
33 /// [`DriverError::Unavailable`].
34 Unavailable(String),
35 /// Admit the task, then drop the completion sender without ever sending a
36 /// terminal outcome — the "driver dropped the completion channel" path.
37 DropCompletion,
38 /// Admit the task but never complete it (for cancellation tests). The
39 /// completion sender is held so the channel stays open.
40 Never,
41 /// Never finish admission: `spawn_task` itself stays pending, like a
42 /// saturated concurrency gate (for cancellation tests). The request is
43 /// still recorded, so `spawn_count` shows the task reached admission.
44 HoldAdmission,
45 }
46
47 #[derive(Debug)]
48 struct ReplyRule {
49 needle: String,
50 delay: Option<Duration>,
51 reply: FakeReply,
52 }
53
54 #[derive(Debug, Default)]
55 struct Inner {
56 rules: Vec<ReplyRule>,
57 requests: Vec<TaskRequest>,
58 events: Vec<ProgressEvent>,
59 next_id: u64,
60 held: Vec<(String, oneshot::Sender<TaskCompletion>)>,
61 cancelled: Vec<String>,
62 }
63
64 /// In-memory [`WorkflowDriver`] with scripted replies.
65 ///
66 /// Unmatched spawns complete immediately with `done:<description>`. Rules are
67 /// matched by substring against the request description, first match wins.
68 #[derive(Debug, Default)]
69 pub struct FakeDriver {
70 inner: Mutex<Inner>,
71 cancel_calls: AtomicUsize,
72 }
73
74 impl FakeDriver {
75 /// A fake with no rules and echo replies.
76 pub fn new() -> Self {
77 Self::default()
78 }
79
80 /// Add a reply rule: requests whose description contains `needle` get
81 /// `reply` immediately.
82 pub fn on(&self, needle: &str, reply: FakeReply) {
83 self.on_with_delay_opt(needle, reply, None);
84 }
85
86 /// Like [`FakeDriver::on`], but the completion is delivered after `delay`
87 /// (the spawn itself still returns immediately).
88 pub fn on_with_delay(&self, needle: &str, reply: FakeReply, delay: Duration) {
89 self.on_with_delay_opt(needle, reply, Some(delay));
90 }
91
92 fn on_with_delay_opt(&self, needle: &str, reply: FakeReply, delay: Option<Duration>) {
93 self.lock().rules.push(ReplyRule {
94 needle: needle.to_string(),
95 delay,
96 reply,
97 });
98 }
99
100 /// Every request received so far, in spawn order.
101 pub fn requests(&self) -> Vec<TaskRequest> {
102 self.lock().requests.clone()
103 }
104
105 /// Descriptions of every request, in spawn order.
106 pub fn request_descriptions(&self) -> Vec<String> {
107 self.lock()
108 .requests
109 .iter()
110 .map(|request| request.description.clone())
111 .collect()
112 }
113
114 /// Number of admitted spawn calls.
115 pub fn spawn_count(&self) -> usize {
116 self.lock().requests.len()
117 }
118
119 /// Every progress event received so far, in emit order.
120 pub fn events(&self) -> Vec<ProgressEvent> {
121 self.lock().events.clone()
122 }
123
124 pub fn cancelled_tasks(&self) -> Vec<String> {
125 self.lock().cancelled.clone()
126 }
127
128 /// How many times `cancel_all` has been invoked.
129 pub fn cancel_all_calls(&self) -> usize {
130 self.cancel_calls.load(Ordering::SeqCst)
131 }
132
133 fn lock(&self) -> std::sync::MutexGuard<'_, Inner> {
134 self.inner.lock().expect("FakeDriver mutex poisoned")
135 }
136 }
137
138 #[async_trait]
139 impl WorkflowDriver for FakeDriver {
140 async fn spawn_task(&self, request: TaskRequest) -> Result<SpawnedTask, DriverError> {
141 let (task_id, reply, delay) = {
142 let mut inner = self.lock();
143 let matched = inner
144 .rules
145 .iter()
146 .find(|rule| request.description.contains(&rule.needle))
147 .map(|rule| (rule.reply.clone(), rule.delay));
148 let (reply, delay) = matched.unwrap_or_else(|| {
149 (
150 FakeReply::Complete(format!("done:{}", request.description)),
151 None,
152 )
153 });
154 match reply {
155 FakeReply::Reject(message) => return Err(DriverError::Rejected(message)),
156 FakeReply::Unavailable(message) => {
157 return Err(DriverError::Unavailable(message));
158 }
159 _ => {}
160 }
161 inner.requests.push(request);
162 inner.next_id += 1;
163 (format!("agent_{:04}", inner.next_id), reply, delay)
164 };
165 if matches!(reply, FakeReply::HoldAdmission) {
166 return std::future::pending().await;
167 }
168
169 let (tx, rx) = oneshot::channel();
170 match reply {
171 FakeReply::Never => self.lock().held.push((task_id.clone(), tx)),
172 FakeReply::DropCompletion => drop(tx),
173 reply => {
174 let completion = match reply {
175 FakeReply::Complete(text) => TaskCompletion::Completed { text },
176 FakeReply::Fail(message) => TaskCompletion::Failed { message },
177 FakeReply::Cancelled => TaskCompletion::Cancelled,
178 FakeReply::BudgetExhausted(message) => {
179 TaskCompletion::BudgetExhausted { message }
180 }
181 FakeReply::Reject(_)
182 | FakeReply::Unavailable(_)
183 | FakeReply::Never
184 | FakeReply::HoldAdmission
185 | FakeReply::DropCompletion => unreachable!("handled above"),
186 };
187 match delay {
188 None => {
189 let _ = tx.send(completion);
190 }
191 Some(delay) => {
192 tokio::spawn(async move {
193 tokio::time::sleep(delay).await;
194 let _ = tx.send(completion);
195 });
196 }
197 }
198 }
199 }
200 Ok(SpawnedTask {
201 task_id,
202 completion: rx,
203 })
204 }
205
206 fn cancel_all(&self) {
207 self.cancel_calls.fetch_add(1, Ordering::SeqCst);
208 }
209
210 fn cancel_task(&self, task_id: &str) {
211 let mut inner = self.lock();
212 inner.cancelled.push(task_id.to_string());
213 if let Some(index) = inner.held.iter().position(|(id, _)| id == task_id) {
214 let (_, tx) = inner.held.remove(index);
215 let _ = tx.send(TaskCompletion::Cancelled);
216 }
217 }
218
219 fn progress(&self, event: ProgressEvent) {
220 self.lock().events.push(event);
221 }
222 }
223
223 lines RUST