返回 CodeWhale
queued_approval_tests.rs
根目录 / crates / engine / src / core / queued_approval_tests.rs
1 //! E2 regression (DOGFOOD-DESKTOP-20260922, app #97): approving one call
2 //! must never cancel the calls queued behind it.
3 //!
4 //! The dogfood report showed an approval that failed the call it approved
5 //! and then cancelled the queued calls after it (`request was cancelled
6 //! before this tool ran`). `59c2a1668` fixed the posture re-check for a
7 //! single call; this pins the queue: one model step emits three gated shell
8 //! calls, the second and third wait behind the first approval card, and the
9 //! client republishes its unchanged posture as the desktop app does on every
10 //! approval. Every call must run, in order, and none may come back
11 //! cancelled.
12
13 use std::time::Duration;
14
15 use codewhale_config::AppMode;
16 use codewhale_execpolicy::ApprovalMode;
17 use tempfile::tempdir;
18
19 use crate::compaction::CompactionConfig;
20 use crate::core::engine::{Engine, EngineConfig};
21 use crate::core::events::Event;
22 use crate::core::ops::{Op, TurnSpec, UserInputProvenance};
23 use crate::test_support::lock_test_env;
24 use codewhale_runtime::config::Config;
25
26 const CALLS: [&str; 3] = ["call_e2_first", "call_e2_second", "call_e2_third"];
27
28 fn event_timeout() -> Duration {
29 // The Windows runner shares CPU with the whole TUI test binary; an
30 // approval-gated turn must not be mistaken for a lifecycle failure.
31 if cfg!(windows) {
32 Duration::from_secs(60)
33 } else {
34 Duration::from_secs(10)
35 }
36 }
37
38 /// One SSE response whose single step carries three gated `Bash` calls, each
39 /// writing its own marker file.
40 fn three_gated_calls_sse() -> String {
41 let mut sse = String::new();
42 for (index, id) in CALLS.iter().enumerate() {
43 let arguments = format!("{{\\\"command\\\":\\\"echo {index} > {id}.txt\\\"}}");
44 sse.push_str(&format!(
45 "data: {{\"id\":\"chatcmpl-e2q\",\"choices\":[{{\"index\":0,\"delta\":{{\"tool_calls\":[\
46 {{\"index\":{index},\"id\":\"{id}\",\"type\":\"function\",\"function\":{{\"name\":\"bash\",\
47 \"arguments\":\"{arguments}\"}}}}]}},\"finish_reason\":null}}]}}\n\n"
48 ));
49 }
50 sse.push_str(concat!(
51 "data: {\"id\":\"chatcmpl-e2q\",\"choices\":[{\"index\":0,\"delta\":{},",
52 "\"finish_reason\":\"tool_calls\"}]}\n\n",
53 "data: [DONE]\n\n",
54 ));
55 sse
56 }
57
58 #[tokio::test]
59 #[allow(clippy::await_holding_lock)]
60 async fn approving_the_first_of_three_queued_calls_cancels_none_of_them() {
61 use wiremock::matchers::{body_string_contains, method, path};
62 use wiremock::{Mock, MockServer, ResponseTemplate};
63
64 let _lock = lock_test_env();
65 let workspace = tempdir().expect("tempdir");
66 let server = MockServer::start().await;
67 let done_sse = concat!(
68 "data: {\"id\":\"chatcmpl-e2q-done\",\"choices\":[{\"index\":0,",
69 "\"delta\":{\"content\":\"done\"},\"finish_reason\":null}]}\n\n",
70 "data: {\"id\":\"chatcmpl-e2q-done\",\"choices\":[{\"index\":0,\"delta\":{},",
71 "\"finish_reason\":\"stop\"}]}\n\n",
72 "data: [DONE]\n\n",
73 );
74 // The follow-up request carries the third call's result.
75 Mock::given(method("POST"))
76 .and(path("/v1/chat/completions"))
77 .and(body_string_contains(CALLS[2]))
78 .respond_with(
79 ResponseTemplate::new(200)
80 .insert_header("content-type", "text/event-stream")
81 .set_body_string(done_sse),
82 )
83 .with_priority(1)
84 .mount(&server)
85 .await;
86 Mock::given(method("POST"))
87 .and(path("/v1/chat/completions"))
88 .respond_with(
89 ResponseTemplate::new(200)
90 .insert_header("content-type", "text/event-stream")
91 .set_body_string(three_gated_calls_sse()),
92 )
93 .expect(1)
94 .with_priority(2)
95 .mount(&server)
96 .await;
97
98 let api_config =
99 Config::default().with_legacy_root(Some("test-key".to_string()), Some(server.uri()));
100 let route = crate::route_runtime::resolve_runtime_route(
101 &api_config,
102 api_config.active_provider_identity().unwrap().provider,
103 Some(codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL),
104 )
105 .expect("resolve test route");
106 let (engine, handle) = Engine::new(
107 EngineConfig {
108 model: codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL.to_string(),
109 workspace: workspace.path().to_path_buf(),
110 snapshots_enabled: false,
111 subagents_enabled: false,
112 terminal_chrome_enabled: false,
113 ..EngineConfig::default()
114 },
115 &api_config,
116 );
117 let run_task = tokio::spawn(engine.run());
118 handle
119 .send(Op::SendMessage(TurnSpec {
120 profile_constitution: None,
121 max_output_tokens: None,
122 content: "Record three approval fixtures in the workspace".to_string(),
123 images: Vec::new(),
124 mode: AppMode::Agent,
125 route: Box::new(route),
126 compaction: Box::new(CompactionConfig::default()),
127 initial_routed_usage: Box::default(),
128 goal_objective: None,
129 goal_token_budget: None,
130 goal_status: crate::tools::goal::GoalStatus::Active,
131 reasoning_effort: None,
132 reasoning_effort_auto: false,
133 auto_model: false,
134 allow_shell: true,
135 trust_mode: false,
136 auto_approve: false,
137 approval_mode: ApprovalMode::Suggest,
138 translation_enabled: false,
139 allowed_tools: None,
140 dynamic_tools: Vec::new(),
141 hook_executor: None,
142 verbosity: None,
143 provenance: UserInputProvenance::ExternalUser,
144 input_authorship: crate::core::ops::TurnInputAuthorship::NotPerson,
145 submission_id: None,
146 }))
147 .await
148 .expect("send model turn");
149
150 let mut approvals = 0usize;
151 let mut starts = Vec::new();
152 let mut results = Vec::new();
153 let mut rx = handle.rx_event.write().await;
154 while let Some(event) = tokio::time::timeout(event_timeout(), rx.recv())
155 .await
156 .expect("timed out waiting for turn event")
157 {
158 match event {
159 Event::ToolCallStarted {
160 id,
161 name,
162 model_call,
163 ..
164 } if name == "bash" => {
165 let model_call = model_call.expect("model call correlation");
166 uuid::Uuid::parse_str(&id).expect("host execution id");
167 assert!(!CALLS.contains(&id.as_str()));
168 assert!(!starts.iter().any(|(started, _)| started == &id));
169 starts.push((id, model_call.provider_id));
170 }
171 Event::ApprovalRequired { id, .. } => {
172 assert!(starts.iter().any(|(started, _)| started == &id));
173 assert!(!CALLS.contains(&id.as_str()));
174 approvals += 1;
175 if approvals == 1 {
176 // The desktop client republishes its unchanged posture
177 // alongside the first approval; with two calls queued
178 // behind this card, that must invalidate nothing.
179 handle
180 .try_send(Op::ChangeMode {
181 mode: AppMode::Agent,
182 allow_shell: true,
183 trust_mode: false,
184 auto_approve: false,
185 approval_mode: ApprovalMode::Suggest,
186 configured_sandbox_mode: None,
187 })
188 .expect("republish posture");
189 }
190 handle.approve_tool_call(id).await.expect("approve call");
191 }
192 Event::ToolCallComplete {
193 id,
194 name,
195 result,
196 model_call,
197 } if name == "bash" => {
198 let model_call = model_call.expect("model call correlation");
199 assert!(starts.iter().any(
200 |(started, provider)| started == &id && provider == &model_call.provider_id
201 ));
202 results.push((id, model_call.provider_id, result));
203 }
204 Event::TurnComplete { .. } => break,
205 _ => {}
206 }
207 }
208 drop(rx);
209 handle.send(Op::Shutdown).await.expect("shutdown engine");
210 run_task.await.expect("engine task");
211
212 assert!(
213 approvals >= 1,
214 "the first call waited on an approval card, with the others queued behind it"
215 );
216 assert_eq!(
217 results.len(),
218 CALLS.len(),
219 "every queued call reported a result: {results:?}"
220 );
221 for (id, _, result) in &results {
222 let result = result
223 .as_ref()
224 .unwrap_or_else(|err| panic!("{id} failed after an approval: {err}"));
225 assert!(result.success, "{id}: {result:?}");
226 let content = result.content.to_ascii_lowercase();
227 assert!(
228 !content.contains("cancelled") && !content.contains("canceled"),
229 "{id} was cancelled by an approval: {}",
230 result.content
231 );
232 }
233 let order: Vec<&str> = results
234 .iter()
235 .map(|(_, provider, _)| provider.as_str())
236 .collect();
237 assert_eq!(order, CALLS, "queued calls run in the order the model gave");
238 assert_eq!(
239 starts
240 .iter()
241 .map(|(_, provider)| provider.as_str())
242 .collect::<Vec<_>>(),
243 CALLS,
244 "admitted calls retain the model's order and provider identities"
245 );
246 assert_eq!(
247 results.iter().map(|(id, _, _)| id).collect::<Vec<_>>(),
248 starts.iter().map(|(id, _)| id).collect::<Vec<_>>(),
249 "each admitted execution completes exactly once in queue order"
250 );
251 for id in CALLS {
252 assert!(
253 workspace.path().join(format!("{id}.txt")).exists(),
254 "{id} ran: its marker file exists"
255 );
256 }
257 }
258
258 lines RUST