返回 CodeWhale
test_cases_01.rs
根目录 / crates / engine / src / core / engine / tests / test_cases_01.rs
1 const WORKING_SET_SUMMARY_MARKER: &str = "## Repo Working Set";
2
3 #[tokio::test]
4 async fn event_capacity_cancel_before_admission_has_no_started_turn_and_keeps_classifier_cost() {
5 use crate::llm_client::mock::{MockLlmClient, canned};
6 let _cost = crate::cost_status::test_scope();
7 let workspace = tempdir().unwrap();
8 let config = Config::default();
9 let mock = Arc::new(MockLlmClient::new(vec![canned::simple_text_turn(
10 "must not run",
11 )]));
12 let mut engine_config = deterministic_engine_config(workspace.path());
13 engine_config.features.disable(Feature::Mcp);
14 let (mut engine, handle) = Engine::new_with_model_client(engine_config, &config, mock.clone());
15 let (tx, rx) = mpsc::channel(1);
16 engine.tx_event = tx;
17 let mut handle = handle;
18 handle.rx_event = Arc::new(RwLock::new(rx));
19 engine
20 .tx_event
21 .try_send(Event::status("existing idle receipt"))
22 .unwrap();
23 let mut op = external_user_message_op("not admitted", AppMode::Agent, &config);
24 let Op::SendMessage(spec) = &mut op else {
25 unreachable!()
26 };
27 spec.initial_routed_usage
28 .records
29 .push(crate::cost_status::RuntimeUsageRecord::legacy(
30 "event-capacity:classifier",
31 crate::cost_status::EffectiveRouteUsage {
32 route: crate::cost_status::EffectiveRouteEnvelope::capture(
33 None,
34 ProviderKind::Openai,
35 "openai",
36 "classifier",
37 None,
38 chrono::Utc::now(),
39 ),
40 usage: Usage {
41 input_tokens: 7,
42 output_tokens: 3,
43 ..Usage::default()
44 },
45 },
46 ));
47 let controls = Arc::clone(&engine.turn_controls);
48 handle.send(op).await.unwrap();
49 let task = tokio::spawn(engine.run());
50 tokio::time::timeout(Duration::from_secs(2), async {
51 loop {
52 if controls.lock().unwrap().active.is_some() {
53 break;
54 }
55 tokio::task::yield_now().await;
56 }
57 })
58 .await
59 .expect("queued op enters the existing control scope");
60 handle.cancel();
61 // The oneshot snapshot can settle while the event receiver remains full.
62 let snapshot = tokio::time::timeout(Duration::from_secs(2), handle.get_session_snapshot())
63 .await
64 .expect("cancel releases admission reservation")
65 .unwrap();
66 assert!(
67 snapshot.messages.is_empty(),
68 "no session mutation before admission"
69 );
70 assert_eq!(mock.call_count(), 0);
71 assert!(controls.lock().unwrap().active.is_none());
72 let cost = crate::cost_status::drain();
73 assert!(
74 cost.usage_source_fingerprints
75 .contains(&crate::cost_status::usage_source_fingerprint(
76 "event-capacity:classifier"
77 ),),
78 "already billed classifier work remains accounted"
79 );
80 let mut events = handle.rx_event.write().await;
81 assert!(matches!(events.try_recv(), Ok(Event::Status { .. })));
82 assert!(
83 events.try_recv().is_err(),
84 "unadmitted work has no fabricated terminal event"
85 );
86 drop(events);
87 handle.send(Op::Shutdown).await.unwrap();
88 tokio::time::timeout(Duration::from_secs(2), task)
89 .await
90 .unwrap()
91 .unwrap();
92 }
93
94 #[tokio::test]
95 async fn event_capacity_admitted_full_channel_settles_once_with_partial_usage_without_drain() {
96 use crate::llm_client::mock::{MockLlmClient, canned};
97 let _cost = crate::cost_status::test_scope();
98 let workspace = tempdir().unwrap();
99 let config = Config::default();
100 let mock = Arc::new(MockLlmClient::new(Vec::new()));
101 let mut engine_config = deterministic_engine_config(workspace.path());
102 engine_config.features.disable(Feature::Mcp);
103 let (engine, handle) = Engine::new_with_model_client(engine_config, &config, mock.clone());
104 let tx = engine.tx_event.clone();
105 let entered = Arc::new(tokio::sync::Notify::new());
106 let filled = Arc::clone(&entered);
107 mock.push_factory(move |_| {
108 while tx.try_send(Event::status("backpressure receipt")).is_ok() {}
109 filled.notify_one();
110 vec![
111 canned::message_start("billed-before-cancel"),
112 canned::message_delta(
113 "end_turn",
114 Some(Usage {
115 input_tokens: 11,
116 output_tokens: 5,
117 ..Usage::default()
118 }),
119 ),
120 canned::text_block_start(0),
121 canned::text_delta(0, "must not render after cancellation"),
122 canned::message_stop(),
123 ]
124 });
125 let controls = Arc::clone(&engine.turn_controls);
126 let task = tokio::spawn(engine.run());
127 handle
128 .send(external_user_message_op(
129 "admitted",
130 AppMode::Agent,
131 &config,
132 ))
133 .await
134 .unwrap();
135 tokio::time::timeout(Duration::from_secs(2), entered.notified())
136 .await
137 .unwrap();
138 handle.cancel();
139 let snapshot = tokio::time::timeout(Duration::from_secs(2), handle.get_session_snapshot())
140 .await
141 .expect("admitted cancellation settles before any event drain")
142 .unwrap();
143 assert_eq!(mock.call_count(), 1);
144 assert_eq!(
145 snapshot.total_tokens, 16,
146 "known partial provider usage survives cancellation"
147 );
148 assert!(controls.lock().unwrap().active.is_none());
149 let mut events = handle.rx_event.write().await;
150 let mut started = 0;
151 let mut completed = 0;
152 let mut terminal_was_last = false;
153 while let Ok(event) = events.try_recv() {
154 assert!(
155 !terminal_was_last,
156 "completion stays after prior accepted observations"
157 );
158 match event {
159 Event::TurnStarted { .. } => started += 1,
160 Event::TurnComplete {
161 status,
162 usage,
163 parent_route_usage,
164 error,
165 ..
166 } => {
167 completed += 1;
168 terminal_was_last = true;
169 assert_eq!(status, TurnOutcomeStatus::Interrupted);
170 assert!(
171 error.is_none(),
172 "cancellation is not a provider failure: {error:?}"
173 );
174 assert_eq!((usage.input_tokens, usage.output_tokens), (11, 5));
175 assert_eq!(usage, parent_route_usage);
176 }
177 Event::MessageDelta { content, .. } => assert!(!content.contains("must not render")),
178 _ => {}
179 }
180 }
181 assert_eq!((started, completed), (1, 1));
182 assert!(terminal_was_last);
183 drop(events);
184 handle.send(Op::Shutdown).await.unwrap();
185 tokio::time::timeout(Duration::from_secs(2), task)
186 .await
187 .unwrap()
188 .unwrap();
189 }
190
191 #[tokio::test]
192 async fn event_capacity_invalid_images_release_queued_control_and_keep_classifier_receipt() {
193 use crate::llm_client::mock::MockLlmClient;
194 for full in [false, true] {
195 let _cost = crate::cost_status::test_scope();
196 let workspace = tempdir().unwrap();
197 let config = Config::default();
198 let mock = Arc::new(MockLlmClient::new(Vec::new()));
199 let mut engine_config = deterministic_engine_config(workspace.path());
200 engine_config.features.disable(Feature::Mcp);
201 let (engine, handle) = Engine::new_with_model_client(engine_config, &config, mock.clone());
202 if full {
203 while engine.tx_event.try_send(Event::status("occupied")).is_ok() {}
204 }
205 let controls = Arc::clone(&engine.turn_controls);
206 let mut op = external_user_message_op("invalid attachment", AppMode::Agent, &config);
207 let Op::SendMessage(spec) = &mut op else {
208 unreachable!()
209 };
210 spec.images
211 .push(codewhale_app_server_protocol::runtime::RuntimeImageInput {
212 mime: "image/png".into(),
213 data_base64: "invalid@base64".into(),
214 });
215 spec.initial_routed_usage
216 .records
217 .push(crate::cost_status::RuntimeUsageRecord::legacy(
218 "event-capacity:invalid-image-classifier",
219 crate::cost_status::EffectiveRouteUsage {
220 route: crate::cost_status::EffectiveRouteEnvelope::capture(
221 None,
222 ProviderKind::Openai,
223 "openai",
224 "classifier",
225 None,
226 chrono::Utc::now(),
227 ),
228 usage: Usage {
229 input_tokens: 7,
230 output_tokens: 3,
231 ..Usage::default()
232 },
233 },
234 ));
235 handle.send(op).await.unwrap();
236 let task = tokio::spawn(engine.run());
237 if full {
238 tokio::time::timeout(Duration::from_secs(2), async {
239 loop {
240 if controls.lock().unwrap().active.is_some() {
241 break;
242 }
243 tokio::task::yield_now().await;
244 }
245 })
246 .await
247 .unwrap();
248 handle.cancel();
249 }
250 let snapshot = tokio::time::timeout(Duration::from_secs(2), handle.get_session_snapshot())
251 .await
252 .expect("rejected input releases the current control")
253 .unwrap();
254 assert!(snapshot.messages.is_empty());
255 assert_eq!(mock.call_count(), 0);
256 assert!(controls.lock().unwrap().active.is_none());
257 let cost = crate::cost_status::drain();
258 assert!(cost.usage_source_fingerprints.contains(
259 &crate::cost_status::usage_source_fingerprint(
260 "event-capacity:invalid-image-classifier"
261 ),
262 ));
263 let mut events = handle.rx_event.write().await;
264 let mut invalid_errors = 0;
265 while let Ok(event) = events.try_recv() {
266 assert!(!matches!(
267 event,
268 Event::TurnStarted { .. } | Event::TurnComplete { .. }
269 ));
270 if let Event::Error { envelope, .. } = event {
271 assert_eq!(envelope.code, "image_input_invalid");
272 invalid_errors += 1;
273 }
274 }
275 assert_eq!(
276 invalid_errors,
277 usize::from(!full),
278 "a cancelled full-channel rejection is not fabricated as delivered"
279 );
280 drop(events);
281 handle.send(Op::Shutdown).await.unwrap();
282 tokio::time::timeout(Duration::from_secs(2), task)
283 .await
284 .unwrap()
285 .unwrap();
286 }
287 }
288
289 #[tokio::test]
290 async fn event_capacity_releases_all_admitted_senders_and_keeps_idle_receipts_lossless() {
291 let workspace = tempdir().unwrap();
292 let (mut engine, _handle) = Engine::new(
293 deterministic_engine_config(workspace.path()),
294 &Config::default(),
295 );
296 let (tx, mut rx) = mpsc::channel(1);
297 engine.tx_event = tx;
298 engine.tx_event.try_send(Event::status("occupied")).unwrap();
299 let turn = engine.begin_turn_control();
300 let mut senders =
301 Box::pin(futures_util::future::join_all((0..8).map(|_| {
302 engine.send_event(Event::status("admitted observation"))
303 })));
304 assert!(
305 tokio::time::timeout(Duration::from_millis(20), &mut senders)
306 .await
307 .is_err()
308 );
309 engine.cancel_token.cancel();
310 let outcomes = tokio::time::timeout(Duration::from_secs(1), &mut senders)
311 .await
312 .unwrap();
313 assert_eq!(outcomes, vec![Err(streaming::EventSendError::Cancelled); 8]);
314 drop(senders);
315 assert!(matches!(rx.try_recv(), Ok(Event::Status { .. })));
316 // A cancelled turn still delivers its usage/status receipts when they
317 // fit immediately. The stream suffix remains strictly cancelled.
318 engine
319 .send_event(Event::status(
320 "cancelled turn receipt with available capacity",
321 ))
322 .await
323 .unwrap();
324 assert!(
325 matches!(rx.try_recv(), Ok(Event::Status { message, .. }) if message == "cancelled turn receipt with available capacity")
326 );
327 assert!(
328 !engine
329 .send_stream_event(Event::status("forbidden stream suffix"))
330 .await
331 );
332 assert!(rx.try_recv().is_err());
333 engine
334 .tx_event
335 .try_send(Event::status("occupied before idle receipt"))
336 .unwrap();
337 drop(turn);
338 let mut idle = Box::pin(engine.send_event(Event::status("idle receipt after cancelled turn")));
339 assert!(
340 tokio::time::timeout(Duration::from_millis(20), &mut idle)
341 .await
342 .is_err()
343 );
344 assert!(matches!(rx.try_recv(), Ok(Event::Status { .. })));
345 tokio::time::timeout(Duration::from_secs(1), &mut idle)
346 .await
347 .unwrap()
348 .unwrap();
349 drop(idle);
350 assert!(
351 matches!(rx.try_recv(), Ok(Event::Status { message, .. }) if message == "idle receipt after cancelled turn")
352 );
353 assert!(rx.try_recv().is_err());
354 }
355
356 #[tokio::test]
357 async fn event_capacity_parallel_tool_fanout_is_not_capped_per_turn() {
358 struct Counter(std::sync::atomic::AtomicUsize);
359 #[async_trait::async_trait]
360 impl codewhale_workflow_js::ToolInvoker for Counter {
361 async fn invoke(
362 &self,
363 _: codewhale_workflow_js::ToolCallRequest,
364 ) -> Result<codewhale_workflow_js::ToolCallResponse, codewhale_workflow_js::DriverError>
365 {
366 self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
367 tokio::task::yield_now().await;
368 Ok(codewhale_workflow_js::ToolCallResponse {
369 ok: true,
370 result: json!(null),
371 })
372 }
373 }
374 let invoker = Arc::new(Counter(std::sync::atomic::AtomicUsize::new(0)));
375 for program in 1..=2 {
376 let result = codewhale_workflow_js::WorkflowVm::new().run_tools_script(
377 r#"const calls = await Promise.allSettled(Array.from({length:256}, () => tools.call('read', {})));
378 return {ok:calls.filter(x=>x.status==='fulfilled').length,
379 rejected:calls.filter(x=>x.status==='rejected' && x.reason.kind==='admission').length};"#,
380 json!(null),
381 Arc::new(codewhale_workflow_js::testing::FakeDriver::new()),
382 invoker.clone(), codewhale_workflow_js::WorkflowRunCancel::new(),
383 ).await.unwrap();
384 assert_eq!(result, json!({"ok":256,"rejected":0}));
385 assert_eq!(
386 invoker.0.load(std::sync::atomic::Ordering::SeqCst),
387 256 * program
388 );
389 }
390 }
391
392 #[tokio::test]
393 async fn event_capacity_admitted_user_shell_cancels_before_side_effect_and_settles_without_drain() {
394 let workspace = tempdir().unwrap();
395 let marker = workspace.path().join("shell-must-not-start.txt");
396 let mut engine_config = deterministic_engine_config(workspace.path());
397 engine_config.features.disable(Feature::Mcp);
398 let (engine, handle) = Engine::new(engine_config, &Config::default());
399 // Leave precisely the two lifecycle slots free. TurnStarted fills one;
400 // the reserved terminal owns the other. The next tool observation must
401 // wait before the human-provenance command can reach its executor.
402 for _ in 0..engine.tx_event.max_capacity() - 2 {
403 engine
404 .tx_event
405 .try_send(Event::status("prior receipt"))
406 .unwrap();
407 }
408 let controls = Arc::clone(&engine.turn_controls);
409 handle
410 .send(Op::RunShellCommand {
411 command: format!("echo must-not-run > \"{}\"", marker.display()),
412 mode: AppMode::Agent,
413 allow_shell: true,
414 trust_mode: true,
415 auto_approve: true,
416 approval_mode: ApprovalMode::Bypass,
417 })
418 .await
419 .unwrap();
420 let task = tokio::spawn(engine.run());
421 tokio::time::timeout(Duration::from_secs(2), async {
422 loop {
423 if controls.lock().unwrap().active.is_some() {
424 break;
425 }
426 tokio::task::yield_now().await;
427 }
428 })
429 .await
430 .unwrap();
431 handle.cancel();
432 tokio::time::timeout(Duration::from_secs(2), handle.get_session_snapshot())
433 .await
434 .expect("shell cancellation settles before any event drain")
435 .unwrap();
436 assert!(
437 !marker.exists(),
438 "cancellation preserves the execution gate"
439 );
440 assert!(controls.lock().unwrap().active.is_none());
441 let mut events = handle.rx_event.write().await;
442 let mut started = 0;
443 let mut completed = 0;
444 let mut terminal_was_last = false;
445 while let Ok(event) = events.try_recv() {
446 assert!(!terminal_was_last);
447 match event {
448 Event::TurnStarted { .. } => started += 1,
449 Event::TurnComplete { status, usage, .. } => {
450 completed += 1;
451 terminal_was_last = true;
452 assert_eq!(status, TurnOutcomeStatus::Interrupted);
453 assert_eq!(usage, Usage::default());
454 }
455 _ => {}
456 }
457 }
458 assert_eq!((started, completed), (1, 1));
459 assert!(terminal_was_last);
460 drop(events);
461 handle.send(Op::Shutdown).await.unwrap();
462 tokio::time::timeout(Duration::from_secs(2), task)
463 .await
464 .unwrap()
465 .unwrap();
466 }
467
468 #[tokio::test]
469 async fn event_capacity_cancelled_parallel_tool_keeps_completed_span_and_call_when_available() {
470 use crate::llm_client::mock::{MockLlmClient, canned};
471 use crate::tools::spec::{
472 ApprovalRequirement, PreparedToolCall, ResourceClaim, ToolCapability, ToolSpec,
473 };
474 use codewhale_protocol::engine_owner::OwnerOperationOutcome;
475 use std::sync::atomic::{AtomicUsize, Ordering};
476
477 struct CompleteThenCancel {
478 cancel: tokio_util::sync::CancellationToken,
479 tx: mpsc::Sender<Event>,
480 fill_queue: bool,
481 executed: Arc<AtomicUsize>,
482 }
483 #[async_trait::async_trait]
484 impl ToolSpec for CompleteThenCancel {
485 // Registered under the canonical read identity so the engine's
486 // central resource authority (not this fixture) grants the disjoint
487 // ReadPath claims that form one real parallel chunk.
488 fn name(&self) -> &str {
489 "read_file"
490 }
491 fn description(&self) -> &str {
492 "Finish an observed operation before firing its turn cancellation token."
493 }
494 fn input_schema(&self) -> Value {
495 json!({"type": "object"})
496 }
497 fn capabilities(&self) -> Vec<ToolCapability> {
498 vec![ToolCapability::ReadOnly]
499 }
500 fn supports_parallel(&self) -> bool {
501 true
502 }
503 fn prepare(
504 &self,
505 input: Value,
506 context: &ToolContext,
507 ) -> Result<PreparedToolCall, ToolError> {
508 let path = input["path"].as_str().expect("fixture path");
509 Ok(PreparedToolCall {
510 name: self.name().to_string(),
511 description: self.description().to_string(),
512 read_only: true,
513 supports_parallel: true,
514 starts_detached: false,
515 approval: ApprovalRequirement::Auto,
516 // Replaced by `registered_resource_claims`; kept honest anyway.
517 resources: vec![ResourceClaim::ReadPath(context.workspace.join(path))],
518 input,
519 })
520 }
521 async fn execute(&self, _: Value, _: &ToolContext) -> Result<ToolResult, ToolError> {
522 self.executed.fetch_add(1, Ordering::SeqCst);
523 if self.fill_queue {
524 while self
525 .tx
526 .try_send(Event::status("full at tool completion"))
527 .is_ok()
528 {}
529 }
530 self.cancel.cancel();
531 Ok(ToolResult::success("completed before cancellation"))
532 }
533 }
534
535 for fill_queue in [false, true] {
536 let workspace = tempdir().unwrap();
537 for path in ["one", "two"] {
538 std::fs::write(workspace.path().join(path), path).unwrap();
539 }
540 let mock = Arc::new(MockLlmClient::new(vec![
541 tool_batch_turn(&[
542 ("one", "read_file", r#"{"path":"one"}"#),
543 ("two", "read_file", r#"{"path":"two"}"#),
544 ]),
545 canned::simple_text_turn("must not run after cancellation"),
546 ]));
547 let (mut engine, handle) = Engine::new_with_model_client(
548 deterministic_engine_config(workspace.path()),
549 &Config::default(),
550 mock.clone(),
551 );
552 let turn_guard = engine.begin_turn_control();
553 let executed = Arc::new(AtomicUsize::new(0));
554 let mut registry = crate::tools::ToolRegistry::new(ToolContext::new(workspace.path()));
555 registry.register(Arc::new(CompleteThenCancel {
556 cancel: engine.cancel_token.clone(),
557 tx: engine.tx_event.clone(),
558 fill_queue,
559 executed: executed.clone(),
560 }));
561 let tools = Some(registry.to_api_tools_with_cache(true));
562 let policy = test_tool_surface(&engine, registry, tools, AppMode::Agent);
563 let mut turn = TurnContext::new(4);
564 let (status, error) = tokio::time::timeout(
565 Duration::from_secs(2),
566 engine.run_turn(&mut turn, policy, None, None),
567 )
568 .await
569 .expect("actual parallel tool completion cannot park on a full cancelled queue");
570 assert_eq!(status, TurnOutcomeStatus::Interrupted, "{error:?}");
571 assert!(error.is_none());
572 assert_eq!(
573 executed.load(Ordering::SeqCst),
574 1,
575 "the peer never executes"
576 );
577 assert_eq!(
578 mock.call_count(),
579 1,
580 "no provider continuation after cancellation"
581 );
582 let mut rx = handle.rx_event.write().await;
583 let events: Vec<_> = std::iter::from_fn(|| rx.try_recv().ok()).collect();
584 assert!(events.iter().any(|event| matches!(event,
585 Event::Status { message } if message == "Executing 2 read-only tools in 1 parallel chunk(s)"
586 )), "fixture must exercise one actual two-tool parallel chunk");
587 let starts: Vec<_> = events
588 .iter()
589 .filter_map(|event| match event {
590 Event::OperationActivityStarted {
591 span_id,
592 activity_kind,
593 ..
594 } => Some((span_id, activity_kind)),
595 _ => None,
596 })
597 .collect();
598 assert_eq!(starts.len(), 1, "one actual tool activity was admitted");
599 let completed: Vec<_> = events
600 .iter()
601 .filter_map(|event| match event {
602 Event::OperationActivityCompleted {
603 span_id,
604 activity_kind,
605 outcome,
606 ..
607 } => Some((span_id, activity_kind, outcome)),
608 _ => None,
609 })
610 .collect();
611 let calls: Vec<_> = events
612 .iter()
613 .filter_map(|event| match event {
614 Event::ToolCallComplete {
615 id,
616 model_call,
617 result,
618 ..
619 } => Some((id, model_call, result)),
620 _ => None,
621 })
622 .collect();
623 if fill_queue {
624 assert_eq!(
625 completed.len(),
626 1,
627 "the span reserved at admission keeps its completion on a full queue"
628 );
629 assert_eq!(completed[0].0, starts[0].0, "retain the span relationship");
630 assert_eq!(completed[0].1, starts[0].1);
631 assert_eq!(*completed[0].2, OwnerOperationOutcome::Succeeded);
632 assert!(
633 calls.is_empty(),
634 "cancelled full waits do not invent tool-call delivery"
635 );
636 } else {
637 assert_eq!(
638 completed.len(),
639 1,
640 "preserve the completed activity after cancellation"
641 );
642 assert_eq!(completed[0].0, starts[0].0, "retain the span relationship");
643 assert_eq!(completed[0].1, starts[0].1);
644 assert_eq!(*completed[0].2, OwnerOperationOutcome::Succeeded);
645 assert_eq!(
646 calls.len(),
647 2,
648 "completed call and cancelled peer both settle exactly once"
649 );
650 let succeeded: Vec<_> = calls
651 .iter()
652 .filter(|(_, _, result)| result.as_ref().is_ok_and(|result| result.success))
653 .collect();
654 assert_eq!(succeeded.len(), 1);
655 let cancelled_peer = calls
656 .iter()
657 .find(|(_, _, result)| !result.as_ref().is_ok_and(|result| result.success))
658 .expect("cancelled peer has its own completion");
659 let peer = cancelled_peer
660 .2
661 .as_ref()
662 .expect("legacy cancelled peer result");
663 assert_eq!(peer.metadata.as_ref().unwrap()["cancelled"], true);
664 assert_eq!(peer.metadata.as_ref().unwrap()["cleanup_confirmed"], false);
665 assert_eq!(
666 succeeded[0].2.as_ref().unwrap().content,
667 "completed before cancellation"
668 );
669 assert!(
670 starts[0].0.starts_with(&format!("{}#", succeeded[0].0)),
671 "span retains its completed execution identity"
672 );
673 let provider_ids: HashSet<_> = calls
674 .iter()
675 .map(|(_, model_call, _)| model_call.as_ref().unwrap().provider_id.as_str())
676 .collect();
677 assert_eq!(provider_ids, HashSet::from(["one", "two"]));
678 let call_starts: HashSet<_> = events
679 .iter()
680 .filter_map(|event| match event {
681 Event::ToolCallStarted { id, .. } => Some(id),
682 _ => None,
683 })
684 .collect();
685 assert!(calls.iter().all(|(id, _, _)| call_starts.contains(id)));
686 }
687 drop(rx);
688 drop(turn_guard);
689 }
690 }
691
692 const REPRESENTATIVE_FIXTURE_ID: &str = "representative-v1";
693 const REPRESENTATIVE_PROJECT_AUTHORITY: &str = "REPRESENTATIVE_PROJECT_AUTHORITY";
694 const REPRESENTATIVE_PROJECT_AUTHORITY_BODY: &str = concat!(
695 "# Representative Project Authority\n\n",
696 "REPRESENTATIVE_PROJECT_AUTHORITY\n\n",
697 "- Keep all work local to the isolated fixture workspace.\n",
698 "- Treat the checked-in repository instructions as the authority for edits.\n",
699 "- Preserve unrelated files and report unsupported checks as unrun.\n",
700 "- Prefer one owner for each runtime fact and delete duplicated derivations.\n",
701 "- Use deterministic provider-free tests before claiming a behavior is verified.\n",
702 "- Keep durable state atomic, recoverable, and explicit about unavailable facts.\n",
703 "- Do not contact remotes, providers, registries, or production services.\n",
704 "- Record exact measurements and distinguish source proof from installed proof.\n",
705 );
706
707 #[test]
708 fn snapshot_notice_precedes_first_provider_call_and_is_owned_by_session() {
709 use crate::llm_client::mock::{MockLlmClient, canned};
710 let _env = lock_test_env();
711 let root = tempdir().unwrap();
712 let _home = EnvVarGuard::set("CODEWHALE_HOME", root.path());
713 let _user_home = EnvVarGuard::set("HOME", root.path());
714 let _user_profile = EnvVarGuard::set("USERPROFILE", root.path());
715 let workspace = root.path().join("workspace");
716 fs::create_dir(&workspace).unwrap();
717 fs::write(workspace.join("large.txt"), vec![b'x'; 4096]).unwrap();
718 let runtime = tokio::runtime::Builder::new_current_thread()
719 .enable_all()
720 .build()
721 .unwrap();
722 runtime.block_on(async {
723 // A resumed Engine for session-a must not warn again. Session-b in
724 // the same process/workspace must receive its own first-turn notice.
725 for (session_id, expected_notices) in [("session-a", 1), ("session-b", 1), ("session-a", 0)]
726 {
727 let config = Config::default();
728 let client = std::sync::Arc::new(MockLlmClient::new(Vec::new()));
729 let (engine, handle) = Engine::new_with_model_client(
730 EngineConfig {
731 session_id: Some(session_id.into()),
732 snapshots_enabled: true,
733 snapshots_max_workspace_bytes: 1024,
734 ..deterministic_engine_config(&workspace)
735 },
736 &config,
737 client.clone(),
738 );
739 let events = std::sync::Arc::clone(&handle.rx_event);
740 let observations = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
741 let observed = std::sync::Arc::clone(&observations);
742 client.push_factory(move |_| {
743 let mut events = events.try_write().expect("fixture owns the event receiver");
744 let mut notices = Vec::new();
745 while let Ok(event) = events.try_recv() {
746 if let Event::SnapshotsDisabled { reason, .. } = event {
747 notices.push(reason);
748 }
749 }
750 observed.lock().unwrap().push(notices);
751 canned::simple_text_turn("snapshot fixture done")
752 });
753 let run = tokio::spawn(engine.run());
754 handle
755 .send(external_user_message_op(
756 "check snapshots",
757 AppMode::Agent,
758 &config,
759 ))
760 .await
761 .unwrap();
762 let snapshot =
763 tokio::time::timeout(Duration::from_secs(10), handle.get_session_snapshot())
764 .await
765 .unwrap()
766 .unwrap();
767 // The Engine catches provider panics, so assertions inside the
768 // factory are not a test oracle. Inspect its observations here.
769 {
770 let observed = observations.lock().unwrap();
771 assert_eq!(
772 observed.len(),
773 1,
774 "factory must have recorded an observation"
775 );
776 assert_eq!(
777 observed[0].len(),
778 expected_notices,
779 "notice must precede provider dispatch for this session"
780 );
781 assert!(observed[0].iter().all(|reason| {
782 // One rendered line: consequence, cause, and the remedy
783 // that lifts this gate, each stated once.
784 reason.lines().count() == 1
785 && reason.contains("Snapshots and /undo are off")
786 && reason
787 .matches(crate::core::turn::SNAPSHOTS_CAP_CONFIG_KEY)
788 .count()
789 == 1
790 }));
791 }
792 assert_eq!(client.call_count(), 1);
793 assert!(
794 serde_json::to_string(&snapshot.messages)
795 .unwrap()
796 .contains("snapshot fixture done")
797 );
798 handle.send(Op::Shutdown).await.unwrap();
799 tokio::time::timeout(Duration::from_secs(10), run)
800 .await
801 .unwrap()
802 .unwrap();
803 }
804 });
805 // Await the owned blocking post-turn snapshots before restoring test home.
806 drop(runtime);
807 }
808
809 /// A recording host (`record_restore_points`) receives every workspace
810 /// snapshot receipt of a turn before its `TurnComplete`: the pre-turn restore
811 /// point, a `tool` snapshot naming the file-mutating call and the paths it
812 /// declared, the `post_tool` snapshot closing it, and the post-turn state. A
813 /// read-only call takes none. The pre/post-turn trees bracket exactly the
814 /// turn's write, so a host derives the turn's workspace delta from them.
815 #[test]
816 fn recorded_snapshot_receipts_bracket_the_turn_and_its_file_writes() {
817 use crate::llm_client::mock::{MockLlmClient, canned};
818 use codewhale_snapshot::WorkspaceSnapshotKind;
819 let _env = lock_test_env();
820 let root = tempdir().unwrap();
821 let _home = EnvVarGuard::set("CODEWHALE_HOME", root.path());
822 let _user_home = EnvVarGuard::set("HOME", root.path());
823 let _user_profile = EnvVarGuard::set("USERPROFILE", root.path());
824 let workspace = root.path().join("workspace");
825 fs::create_dir(&workspace).unwrap();
826 fs::write(workspace.join("README.md"), "fixture\n").unwrap();
827 let runtime = tokio::runtime::Builder::new_current_thread()
828 .enable_all()
829 .build()
830 .unwrap();
831 runtime.block_on(async {
832 let config = Config::default();
833 let client = std::sync::Arc::new(MockLlmClient::new(vec![
834 canned::tool_call_turn(
835 "call-write",
836 "write",
837 r#"{"path":"out.md","content":"out\n"}"#,
838 ),
839 canned::tool_call_turn("call-read", "read", r#"{"path":"README.md"}"#),
840 canned::simple_text_turn("done"),
841 ]));
842 let (engine, handle) = Engine::new_with_model_client(
843 EngineConfig {
844 session_id: Some("session-restore".into()),
845 snapshots_enabled: true,
846 snapshots_max_workspace_bytes: 0,
847 record_restore_points: true,
848 ..deterministic_engine_config(&workspace)
849 },
850 &config,
851 client,
852 );
853 let run = tokio::spawn(engine.run());
854 let Op::SendMessage(mut spec) =
855 external_user_message_op("write out.md", AppMode::Agent, &config)
856 else {
857 unreachable!("external_user_message_op builds a SendMessage");
858 };
859 spec.auto_approve = true;
860 spec.trust_mode = true;
861 spec.approval_mode = ApprovalMode::Bypass;
862 handle.send(Op::SendMessage(spec)).await.unwrap();
863
864 let mut completions = HashMap::new();
865 let mut local_ids = HashMap::new();
866 let mut receipts = Vec::new();
867 let mut rx = handle.rx_event.write().await;
868 while let Some(event) = tokio::time::timeout(model_turn_event_timeout(), rx.recv())
869 .await
870 .expect("turn events")
871 {
872 match event {
873 Event::ToolCallStarted {
874 id,
875 model_call: Some(model_call),
876 ..
877 } => {
878 uuid::Uuid::parse_str(&id).expect("host execution id");
879 assert_ne!(id, model_call.provider_id);
880 assert!(local_ids.insert(model_call.provider_id, id).is_none());
881 }
882 Event::ToolCallComplete {
883 id,
884 result,
885 model_call: Some(model_call),
886 ..
887 } => {
888 assert_eq!(local_ids.get(&model_call.provider_id), Some(&id));
889 completions.insert(model_call.provider_id, result.expect("tool result"));
890 }
891 Event::WorkspaceSnapshotTaken { snapshot } => receipts.push(snapshot),
892 Event::TurnComplete { status, error, .. } => {
893 assert_eq!(status, TurnOutcomeStatus::Completed, "{error:?}");
894 break;
895 }
896 _ => {}
897 }
898 }
899 drop(rx);
900
901 assert!(completions.get("call-write").expect("write ran").success);
902 assert!(completions.get("call-read").expect("read ran").success);
903 assert_eq!(local_ids.len(), 2);
904 assert_ne!(local_ids["call-write"], local_ids["call-read"]);
905 // Every receipt, post-turn included, arrived before TurnComplete.
906 assert_eq!(
907 receipts
908 .iter()
909 .map(|receipt| (receipt.kind, receipt.tool_call_id.as_deref()))
910 .collect::<Vec<_>>(),
911 [
912 (WorkspaceSnapshotKind::PreTurn, None),
913 (
914 WorkspaceSnapshotKind::Tool,
915 Some(local_ids["call-write"].as_str())
916 ),
917 (
918 WorkspaceSnapshotKind::PostTool,
919 Some(local_ids["call-write"].as_str())
920 ),
921 (WorkspaceSnapshotKind::PostTurn, None),
922 ],
923 "a read-only call takes no restore point: {receipts:?}"
924 );
925 assert!(
926 receipts
927 .iter()
928 .all(|receipt| receipt.session_id == "session-restore")
929 );
930 assert_eq!(
931 receipts[1].write_paths.as_deref(),
932 Some(&["out.md".to_string()][..])
933 );
934 assert_eq!(
935 receipts[2].changed_paths.as_deref(),
936 Some(&["out.md".to_string()][..])
937 );
938
939 let repo = codewhale_snapshot::SnapshotRepo::open_existing(&workspace)
940 .unwrap()
941 .expect("snapshot repo");
942 let listed = repo.list(usize::MAX).unwrap();
943 assert!(
944 listed.iter().any(|snapshot| receipts[1].matches(snapshot)
945 && snapshot.label == format!("tool:{}", local_ids["call-write"])),
946 "the tool receipt names a live snapshot"
947 );
948 let delta = repo
949 .diff_snapshots(
950 &codewhale_snapshot::SnapshotId::parse(&receipts[0].tree_id).unwrap(),
951 &codewhale_snapshot::SnapshotId::parse(&receipts[3].tree_id).unwrap(),
952 100,
953 )
954 .unwrap();
955 assert_eq!(
956 delta
957 .entries
958 .iter()
959 .map(|entry| entry.path.as_str())
960 .collect::<Vec<_>>(),
961 ["out.md"],
962 "the pre/post-turn trees bracket exactly this turn's write"
963 );
964
965 handle.send(Op::Shutdown).await.unwrap();
966 tokio::time::timeout(Duration::from_secs(10), run)
967 .await
968 .unwrap()
969 .unwrap();
970 });
971 // Await the owned blocking post-turn snapshots before restoring test home.
972 drop(runtime);
973 }
974
975 #[test]
976 fn preview_request_error_preserves_non_semantic_context_chain() {
977 let error = anyhow::Error::msg("root cause").context("request preparation failed");
978 assert_eq!(
979 preview_request_error_user_message("en", &error),
980 "request preparation failed: root cause"
981 );
982 assert_eq!(
983 initial_stream_error_user_message("en", &error),
984 "request preparation failed: root cause"
985 );
986 }
987
988 #[test]
989 fn initial_stream_failure_preserves_sanitized_context_and_typed_category() {
990 let error = anyhow::Error::new(crate::llm_client::LlmError::InvalidRequest {
991 status: 400,
992 message: "image input is unsupported; api_key=fixture-credential-value".to_string(),
993 })
994 .context("Responses API request failed");
995 let display = initial_stream_error_user_message("en", &error);
996 assert!(
997 display.contains("Responses API request failed"),
998 "{display}"
999 );
1000 assert!(display.contains("Invalid request (400)"), "{display}");
1001 assert!(display.contains("image input is unsupported"), "{display}");
1002 assert!(!display.contains("fixture-credential-value"), "{display}");
1003 assert!(display.contains("[redacted]"), "{display}");
1004
1005 // The real boundary classifies the original error independently of its
1006 // expanded display text. Preserve the typed terminal invalid-input result.
1007 let policy_message = error.to_string();
1008 let mut envelope = crate::llm_error_envelope::envelope_for_llm_error(error, policy_message);
1009 envelope.message = display;
1010 assert_eq!(
1011 envelope.category,
1012 codewhale_error_taxonomy::ErrorCategory::InvalidInput
1013 );
1014 assert!(!envelope.recoverable);
1015 assert_eq!(envelope.code, "llm_invalid_request");
1016 }
1017 const REPRESENTATIVE_INLINE_INSTRUCTIONS: &str = "REPRESENTATIVE_INLINE_INSTRUCTIONS";
1018 const REPRESENTATIVE_SKILL_DESCRIPTION: &str = "REPRESENTATIVE_SKILL_DESCRIPTION";
1019 const REPRESENTATIVE_MEMORY_CHECKPOINT: &str = "REPRESENTATIVE_MEMORY_CHECKPOINT";
1020 const REPRESENTATIVE_GOAL_OBJECTIVE: &str = "REPRESENTATIVE_GOAL_OBJECTIVE";
1021
1022 #[test]
1023 fn cancellation_wins_at_the_terminal_child_settlement_seam() {
1024 assert_eq!(
1025 terminal_turn_status_at_settlement(TurnOutcomeStatus::Completed, true),
1026 TurnOutcomeStatus::Interrupted
1027 );
1028 assert_eq!(
1029 terminal_turn_status_at_settlement(TurnOutcomeStatus::Completed, false),
1030 TurnOutcomeStatus::Completed
1031 );
1032 assert_eq!(
1033 terminal_turn_status_at_settlement(TurnOutcomeStatus::Failed, true),
1034 TurnOutcomeStatus::Failed
1035 );
1036 }
1037
1038 #[tokio::test]
1039 async fn terminal_barrier_keeps_healthy_child_and_late_completion_alive() {
1040 use std::sync::atomic::Ordering;
1041 let turn_token = CancellationToken::new();
1042 let (mailbox, _receiver) = Mailbox::new(turn_token.clone());
1043 let children = Arc::new(ForegroundChildRegistry::new());
1044 let child_token = turn_token.child_token();
1045 let registration = children
1046 .register(child_token.clone(), "agent_healthy")
1047 .unwrap();
1048 let parking = registration.parking_signal();
1049 let (complete_tx, mut complete_rx) = tokio::sync::mpsc::unbounded_channel();
1050 let (release_tx, release_rx) = tokio::sync::oneshot::channel();
1051 let child = tokio::spawn(async move {
1052 release_rx.await.unwrap();
1053 assert!(!child_token.is_cancelled());
1054 complete_tx.send("existing completion inbox").unwrap();
1055 drop(registration);
1056 });
1057 let (flush_tx, flush_rx) = tokio::sync::oneshot::channel();
1058 let drain_handle = tokio::spawn(async {
1059 let _ = flush_rx.await;
1060 });
1061 let barrier = TurnMailboxBarrier {
1062 mailbox,
1063 cancel_token: turn_token.clone(),
1064 foreground_children: Arc::clone(&children),
1065 flush_tx,
1066 drain_handle,
1067 settle_grace: Duration::from_secs(1),
1068 };
1069 tokio::time::timeout(Duration::from_secs(1), barrier.continue_and_flush())
1070 .await
1071 .unwrap();
1072 assert_eq!(children.active_count(), 1);
1073 assert!(!turn_token.is_cancelled());
1074 assert!(!parking.load(Ordering::Acquire));
1075 release_tx.send(()).unwrap();
1076 assert_eq!(complete_rx.recv().await, Some("existing completion inbox"));
1077 child.await.unwrap();
1078 assert_eq!(children.active_count(), 0);
1079 }
1080
1081 #[tokio::test]
1082 async fn terminal_barrier_explicit_cancel_still_joins_owned_child() {
1083 let turn_token = CancellationToken::new();
1084 let (mailbox, _receiver) = Mailbox::new(turn_token.clone());
1085 let children = Arc::new(ForegroundChildRegistry::new());
1086 let child_token = turn_token.child_token();
1087 let registration = children
1088 .register(child_token.clone(), "agent_owned")
1089 .unwrap();
1090 let child = tokio::spawn(async move {
1091 child_token.cancelled().await;
1092 drop(registration);
1093 });
1094 let (flush_tx, flush_rx) = tokio::sync::oneshot::channel();
1095 let drain_handle = tokio::spawn(async {
1096 let _ = flush_rx.await;
1097 });
1098 let barrier = TurnMailboxBarrier {
1099 mailbox,
1100 cancel_token: turn_token,
1101 foreground_children: Arc::clone(&children),
1102 flush_tx,
1103 drain_handle,
1104 settle_grace: Duration::from_secs(1),
1105 };
1106 let unsettled = tokio::time::timeout(Duration::from_secs(1), barrier.cancel_and_flush())
1107 .await
1108 .unwrap();
1109 assert!(unsettled.is_empty(), "cooperative children join cleanly");
1110 child.await.unwrap();
1111 assert_eq!(children.active_count(), 0);
1112 }
1113
1114 /// Regression for #6184: a foreground child parked on an await that never
1115 /// observes its cancel token must not withhold the terminal turn event. The
1116 /// join gives up at `settle_grace` and names the child it left behind.
1117 #[tokio::test]
1118 async fn terminal_barrier_cancel_names_child_that_ignores_cancellation() {
1119 let turn_token = CancellationToken::new();
1120 let (mailbox, _receiver) = Mailbox::new(turn_token.clone());
1121 let children = Arc::new(ForegroundChildRegistry::new());
1122 let child_token = turn_token.child_token();
1123 // The fake child keeps its registration for the whole test — it never
1124 // observes the cancel token, like a task parked on a blocking await.
1125 let registration = children
1126 .register(child_token.clone(), "agent_stuck")
1127 .unwrap();
1128 let (flush_tx, flush_rx) = tokio::sync::oneshot::channel();
1129 let drain_handle = tokio::spawn(async {
1130 let _ = flush_rx.await;
1131 });
1132 let barrier = TurnMailboxBarrier {
1133 mailbox,
1134 cancel_token: turn_token.clone(),
1135 foreground_children: Arc::clone(&children),
1136 flush_tx,
1137 drain_handle,
1138 settle_grace: Duration::from_millis(50),
1139 };
1140 // Esc latches the turn token before the barrier runs, so the grace
1141 // window — not the token — is the bound under test.
1142 turn_token.cancel();
1143 let unsettled = tokio::time::timeout(Duration::from_secs(1), barrier.cancel_and_flush())
1144 .await
1145 .expect("the bounded join must not wait on a parked child");
1146 assert_eq!(unsettled, vec!["agent_stuck".to_string()]);
1147 assert!(
1148 child_token.is_cancelled(),
1149 "the bounded join still cancels the child's token"
1150 );
1151 assert_eq!(
1152 children.active_count(),
1153 1,
1154 "the stuck child is left registered — leaked, not awaited"
1155 );
1156 drop(registration);
1157 assert_eq!(children.active_count(), 0);
1158 }
1159
1160 /// Regression for #6184: the mailbox drainer parked in an untimed
1161 /// `tx_event.send().await` (event channel full, UI not draining) must not
1162 /// withhold the terminal turn event. `flush` gives up at `settle_grace` and
1163 /// aborts the drainer, so the turn settles instead of waiting hours.
1164 #[tokio::test]
1165 async fn terminal_barrier_flush_bounds_a_drainer_parked_on_a_full_event_channel() {
1166 let turn_token = CancellationToken::new();
1167 let (mailbox, _receiver) = Mailbox::new(turn_token.clone());
1168 let children = Arc::new(ForegroundChildRegistry::new());
1169 // The wedged shape from the report: a one-slot event channel, already
1170 // full, with nobody draining — so the drainer's forward parks in `send`.
1171 let (event_tx, mut event_rx) = tokio::sync::mpsc::channel::<()>(1);
1172 event_tx.send(()).await.unwrap();
1173 let drain_handle = tokio::spawn(async move {
1174 // Parked forever: the channel is full and the receiver never drains.
1175 let _ = event_tx.send(()).await;
1176 });
1177 // Give the drainer a moment to park before the flush races it.
1178 tokio::task::yield_now().await;
1179 let (flush_tx, _flush_rx) = tokio::sync::oneshot::channel();
1180 let barrier = TurnMailboxBarrier {
1181 mailbox,
1182 cancel_token: turn_token,
1183 foreground_children: Arc::clone(&children),
1184 flush_tx,
1185 drain_handle,
1186 settle_grace: Duration::from_millis(50),
1187 };
1188 let started = Instant::now();
1189 tokio::time::timeout(Duration::from_secs(2), barrier.continue_and_flush())
1190 .await
1191 .expect("flush must give up at its grace, not park with the drainer");
1192 assert!(
1193 started.elapsed() < Duration::from_secs(2),
1194 "flush returned in {:?}",
1195 started.elapsed()
1196 );
1197 // Abort receipt: an aborted drainer drops its sender half, so the
1198 // buffered item drains and the channel then reads closed.
1199 assert!(event_rx.recv().await.is_some());
1200 assert!(
1201 event_rx.recv().await.is_none(),
1202 "aborted drainer must release the event channel"
1203 );
1204 }
1205
1206 /// A turn that fails without user cancellation runs the same barrier with a
1207 /// live turn token: Esc during the join must still break it rather than sit
1208 /// out the whole grace period (#6184).
1209 #[tokio::test]
1210 async fn terminal_barrier_cancel_join_breaks_on_fresh_esc() {
1211 let turn_token = CancellationToken::new();
1212 let (mailbox, _receiver) = Mailbox::new(turn_token.clone());
1213 let children = Arc::new(ForegroundChildRegistry::new());
1214 let registration = children
1215 .register(turn_token.child_token(), "agent_stuck")
1216 .unwrap();
1217 let (flush_tx, flush_rx) = tokio::sync::oneshot::channel();
1218 let drain_handle = tokio::spawn(async {
1219 let _ = flush_rx.await;
1220 });
1221 let barrier = TurnMailboxBarrier {
1222 mailbox,
1223 cancel_token: turn_token.clone(),
1224 foreground_children: Arc::clone(&children),
1225 flush_tx,
1226 drain_handle,
1227 settle_grace: Duration::from_secs(30),
1228 };
1229 let esc = turn_token.clone();
1230 let esc_task = tokio::spawn(async move {
1231 tokio::time::sleep(Duration::from_millis(20)).await;
1232 esc.cancel();
1233 });
1234 let unsettled = tokio::time::timeout(Duration::from_secs(1), barrier.cancel_and_flush())
1235 .await
1236 .expect("a fresh Esc must break the join before its grace expires");
1237 assert_eq!(unsettled, vec!["agent_stuck".to_string()]);
1238 esc_task.await.unwrap();
1239 drop(registration);
1240 }
1241
1242 #[tokio::test]
1243 async fn a_completed_turn_stays_completed_when_usage_cannot_be_retained() {
1244 use crate::llm_client::mock::{MockLlmClient, canned};
1245
1246 let _cost = crate::cost_status::test_scope();
1247 let workspace = tempdir().expect("tempdir");
1248 let broken_sessions_file = workspace.path().join("not-a-sessions-dir");
1249 std::fs::write(&broken_sessions_file, b"file").expect("create regular file sentinel");
1250
1251 let mut response = canned::simple_text_turn("completed without retained usage");
1252 for event in &mut response {
1253 if let codewhale_models::StreamEvent::MessageDelta { usage, .. } = event {
1254 *usage = Some(Usage {
1255 input_tokens: 12,
1256 output_tokens: 4,
1257 ..Usage::default()
1258 });
1259 }
1260 }
1261 let mock = std::sync::Arc::new(MockLlmClient::new(vec![response]));
1262 let client: crate::core::model_client::SharedModelClient = mock.clone();
1263 let config = Config::default();
1264 let mut engine_config = deterministic_engine_config(workspace.path());
1265 engine_config.runtime_services.accounting_origin =
1266 Some(crate::cost_status::NativeUsageOrigin::session(
1267 crate::cost_status::scope_token(),
1268 broken_sessions_file,
1269 "unretained-session".to_string(),
1270 ));
1271 let (engine, handle) = Engine::new_with_model_client(engine_config, &config, client);
1272 let task = tokio::spawn(engine.run());
1273
1274 handle
1275 .send(external_user_message_op(
1276 "complete with unwritable origin",
1277 AppMode::Agent,
1278 &config,
1279 ))
1280 .await
1281 .expect("send turn");
1282
1283 let mut rx = handle.rx_event.write().await;
1284 let (status, error) = loop {
1285 let event = tokio::time::timeout(model_turn_event_timeout(), rx.recv())
1286 .await
1287 .expect("timed out waiting for TurnComplete")
1288 .expect("engine event channel open");
1289 if let Event::TurnComplete { status, error, .. } = event {
1290 break (status, error);
1291 }
1292 };
1293 drop(rx);
1294 assert_eq!(status, TurnOutcomeStatus::Completed, "{error:?}");
1295 assert!(error.is_none(), "{error:?}");
1296 assert_eq!(mock.call_count(), 1);
1297
1298 handle.send(Op::Shutdown).await.expect("shutdown engine");
1299 task.await.expect("engine task");
1300
1301 let mock2 = std::sync::Arc::new(MockLlmClient::new(vec![canned::simple_text_turn(
1302 "completed despite failing sink",
1303 )]));
1304 let client2: crate::core::model_client::SharedModelClient = mock2.clone();
1305 let mut engine_config2 = deterministic_engine_config(workspace.path());
1306 engine_config2.runtime_services.accounting_origin =
1307 Some(crate::cost_status::NativeUsageOrigin::captured_runtime(
1308 crate::cost_status::scope_token(),
1309 "failing-retained-sink-owner".to_string(),
1310 std::sync::Arc::new(|_| false),
1311 ));
1312 let (engine2, handle2) = Engine::new_with_model_client(engine_config2, &config, client2);
1313 let task2 = tokio::spawn(engine2.run());
1314 handle2
1315 .send(external_user_message_op(
1316 "complete with failing runtime sink",
1317 AppMode::Agent,
1318 &config,
1319 ))
1320 .await
1321 .expect("send second turn");
1322
1323 let mut rx2 = handle2.rx_event.write().await;
1324 let (status2, error2) = loop {
1325 let event = tokio::time::timeout(model_turn_event_timeout(), rx2.recv())
1326 .await
1327 .expect("timed out waiting for second TurnComplete")
1328 .expect("second engine event channel open");
1329 if let Event::TurnComplete { status, error, .. } = event {
1330 break (status, error);
1331 }
1332 };
1333 drop(rx2);
1334 assert_eq!(status2, TurnOutcomeStatus::Completed, "{error2:?}");
1335 assert!(error2.is_none(), "{error2:?}");
1336 assert_eq!(mock2.call_count(), 1);
1337
1338 handle2.send(Op::Shutdown).await.expect("shutdown engine2");
1339 task2.await.expect("engine2 task");
1340 }
1341
1341 lines RUST