返回 CodeWhale
runtime_state.rs
根目录 / crates / engine / src / core / engine / tests / runtime_state.rs
1 //! Engine state that must stay truthful across a boundary: the live MCP
2 //! catalog (C02-07/C02-16), a session switch (C02-08/C02-17), a user-input
3 //! wait (C02-19), an `/edit` whose replacement never starts (C02-02), and a
4 //! malformed MCP config (C02-18). No fixture reaches a provider or a shell.
5
6 use super::*;
7 use crate::llm_client::mock::MockLlmClient;
8
9 fn quiet_engine(config: EngineConfig) -> (Engine, EngineHandle) {
10 Engine::new_with_model_client(
11 config,
12 &Config::default(),
13 Arc::new(MockLlmClient::new(Vec::new())),
14 )
15 }
16
17 async fn session_snapshot(handle: &EngineHandle) -> SessionSnapshot {
18 let (tx, rx) = tokio::sync::oneshot::channel();
19 handle
20 .send(Op::GetSessionSnapshot {
21 tx: Arc::new(StdMutex::new(Some(tx))),
22 })
23 .await
24 .unwrap();
25 tokio::time::timeout(model_turn_event_timeout(), rx)
26 .await
27 .expect("snapshot response")
28 .expect("snapshot")
29 }
30
31 #[test]
32 fn live_mcp_refresh_drops_tools_the_pool_no_longer_lists() {
33 // C02-07: the caller's universe is what the pool lists *now*. After a
34 // live 401 that is only the synthetic login tool — never the dead one.
35 let mut catalog = vec![api_tool("mcp_alpha_search"), api_tool("exec_shell")];
36 let mut active: HashSet<String> = ["mcp_alpha_search", "exec_shell"]
37 .into_iter()
38 .map(str::to_string)
39 .collect();
40 let universe: HashSet<String> = ["mcp_alpha_authenticate".to_string()].into();
41 let changed = replace_runtime_mcp_tools(
42 &mut catalog,
43 &mut active,
44 &universe,
45 vec![api_tool("mcp_alpha_authenticate")],
46 AppMode::Agent,
47 &HashSet::new(),
48 crate::model_profile::ToolSurfaceBudget::Standard,
49 );
50 let names: Vec<&str> = catalog.iter().map(|tool| tool.name.as_str()).collect();
51 assert_eq!(names, vec!["exec_shell", "mcp_alpha_authenticate"]);
52 assert!(
53 !active.contains("mcp_alpha_search"),
54 "a dead tool is not callable"
55 );
56 assert!(changed);
57 }
58
59 #[test]
60 fn live_mcp_refresh_reports_a_schema_only_edit() {
61 // C02-16: the same names with an edited description is a change the
62 // prefix check must hear about; an identical refresh is not.
63 let refresh = |catalog: &mut Vec<Tool>, active: &mut HashSet<String>, tool: Tool| {
64 replace_runtime_mcp_tools(
65 catalog,
66 active,
67 &["mcp_alpha_read".to_string()].into(),
68 vec![tool],
69 AppMode::Agent,
70 &HashSet::new(),
71 crate::model_profile::ToolSurfaceBudget::Standard,
72 )
73 };
74 let mut catalog = vec![api_tool("exec_shell")];
75 let mut active = HashSet::new();
76 refresh(&mut catalog, &mut active, api_tool("mcp_alpha_read"));
77 let mut edited = api_tool("mcp_alpha_read");
78 edited.description = "Read a resource (now paginated)".to_string();
79 assert!(refresh(&mut catalog, &mut active, edited.clone()));
80 assert!(!refresh(&mut catalog, &mut active, edited));
81 }
82
83 async fn engine_mid_mcp_boot_with_usage() -> (Engine, EngineHandle, tokio::task::JoinHandle<()>) {
84 let workspace = tempdir().unwrap();
85 let (mut engine, handle) = quiet_engine(deterministic_engine_config(workspace.path()));
86 engine.session.total_usage.input_tokens = 1_000;
87 engine.session.total_usage.output_tokens = 200;
88 let boot = tokio::spawn(std::future::pending::<()>());
89 engine.mcp_boot_task = Some(boot.abort_handle());
90 engine.mcp_boot_in_flight = true;
91 engine.mcp_boot_generation = Some(7);
92 engine.mcp_connection_errors.insert(
93 "previous-server".to_string(),
94 "previous failure".to_string(),
95 );
96 // A same-conversation re-sync keeps its usage and its boot pass.
97 let same = engine.session.id.clone();
98 assert!(engine.install_synced_session_id(same).is_none());
99 assert_eq!(engine.session_snapshot().total_tokens, 1_200);
100 assert!(engine.mcp_boot_in_flight);
101 (engine, handle, boot)
102 }
103
104 #[tokio::test]
105 async fn a_session_boundary_does_not_inherit_the_previous_usage() {
106 // C02-17: session A's tokens are not session B's.
107 let (mut engine, _handle, _boot) = engine_mid_mcp_boot_with_usage().await;
108 assert!(
109 engine
110 .install_synced_session_id("next-session".to_string())
111 .is_some()
112 );
113 assert_eq!(engine.session_snapshot().total_tokens, 0);
114 }
115
116 #[tokio::test]
117 async fn a_session_boundary_abandons_the_previous_mcp_boot() {
118 // C02-08: the dropped pool's pass is aborted and its state cleared.
119 let (mut engine, _handle, boot) = engine_mid_mcp_boot_with_usage().await;
120 assert!(
121 engine
122 .install_synced_session_id("next-session".to_string())
123 .is_some()
124 );
125 assert!(!engine.mcp_boot_in_flight);
126 assert_eq!(engine.mcp_boot_generation, None);
127 assert!(engine.mcp_boot_rx.is_none());
128 assert!(engine.mcp_connection_errors.is_empty());
129 let joined = tokio::time::timeout(Duration::from_secs(5), boot)
130 .await
131 .expect("the previous boot pass must stop promptly");
132 assert!(joined.unwrap_err().is_cancelled(), "the pass was aborted");
133 }
134
135 fn user_input_request() -> crate::tools::user_input::UserInputRequest {
136 serde_json::from_value(serde_json::json!({
137 "questions":[{"id":"choice","question":"Answer?","allow_free_text":true}]
138 }))
139 .unwrap()
140 }
141
142 #[tokio::test]
143 async fn a_session_boundary_discards_and_stops_the_previous_mcp_supervisor() {
144 let workspace = tempdir().unwrap();
145 let (mut engine, _handle) = quiet_engine(deterministic_engine_config(workspace.path()));
146 let (tx, rx) = mpsc::channel(1);
147 tx.send(McpSupervisorUpdate {
148 died: vec![("previous-server".to_string(), "stale diagnosis".to_string())],
149 failed: Vec::new(),
150 recovered: Vec::new(),
151 parked: Vec::new(),
152 refreshed: Vec::new(),
153 })
154 .await
155 .unwrap();
156 engine.mcp_supervisor_rx = Some(rx);
157
158 // A reconnect future retains its connection resources across await. The
159 // boundary must abort that future, not merely drop a Weak pool owner.
160 let held = Arc::new(());
161 let weak = Arc::downgrade(&held);
162 let (started_tx, started_rx) = tokio::sync::oneshot::channel();
163 let supervisor = tokio::spawn(async move {
164 let _held = held;
165 started_tx.send(()).unwrap();
166 std::future::pending::<()>().await;
167 });
168 started_rx.await.unwrap();
169 engine.mcp_supervisor_task = Some(supervisor.abort_handle());
170 assert!(
171 engine
172 .install_synced_session_id("next-session".to_string())
173 .is_some()
174 );
175 assert!(
176 engine.mcp_supervisor_rx.is_none(),
177 "queued diagnoses retired"
178 );
179 assert!(engine.mcp_supervisor_task.is_none());
180 let joined = tokio::time::timeout(Duration::from_secs(1), supervisor)
181 .await
182 .expect("the previous supervisor must stop promptly");
183 assert!(joined.unwrap_err().is_cancelled());
184 assert!(weak.upgrade().is_none(), "reconnect resources released");
185 assert!(tx.is_closed(), "old diagnoses cannot cross the boundary");
186
187 engine.ensure_mcp_pool().await.unwrap();
188 assert!(engine.mcp_supervisor_rx.is_some(), "the next pool is armed");
189 assert!(engine.mcp_supervisor_task.is_some());
190 assert!(engine.mcp_connection_errors.is_empty());
191 engine.drop_mcp_pool();
192 }
193
194 #[tokio::test]
195 async fn an_undeliverable_user_input_request_fails_fast() {
196 // C02-19: the question cannot reach a host (its event channel is closed,
197 // while the answer channel stays open), so nobody can ever answer it.
198 let workspace = tempdir().unwrap();
199 let (mut engine, handle) = quiet_engine(EngineConfig {
200 user_input_responder: true,
201 ..deterministic_engine_config(workspace.path())
202 });
203 engine.config.user_input_responder = false;
204 assert!(matches!(
205 engine
206 .await_user_input("unavailable", user_input_request())
207 .await,
208 Err(ToolError::ExecutionFailed { .. })
209 ));
210 assert!(handle.rx_event.write().await.try_recv().is_err());
211 engine.config.user_input_responder = true;
212 engine.host_profile = EngineHostProfile::Child;
213 assert!(matches!(
214 engine.await_user_input("child", user_input_request()).await,
215 Err(ToolError::ExecutionFailed { .. })
216 ));
217 engine.host_profile = EngineHostProfile::Normal;
218 let (tiny, _tiny_rx) = mpsc::channel(1);
219 let regular = std::mem::replace(&mut engine.tx_event, tiny);
220 assert!(matches!(
221 engine.await_user_input("tiny", user_input_request()).await,
222 Err(ToolError::ExecutionFailed { .. })
223 ));
224 engine.tx_event = regular;
225 for timed_out in [false, true] {
226 let (full, mut full_rx) = mpsc::channel(2);
227 full.send(Event::Status {
228 message: "first".into(),
229 })
230 .await
231 .unwrap();
232 full.send(Event::Status {
233 message: "second".into(),
234 })
235 .await
236 .unwrap();
237 let regular = std::mem::replace(&mut engine.tx_event, full);
238 // The probe below must be able to elapse before the user-input timer.
239 // A 2 ms probe against a 10 ms timer left only 8 ms of headroom, which
240 // Windows' ~15.6 ms timer granularity exceeds, so the timer won and the
241 // "still waiting" assertion inverted. Keep a gap no scheduler can eat.
242 engine.config.user_input_timeout = timed_out.then_some(Duration::from_millis(200));
243 let withdrawal = CancellationToken::new();
244 let invocation_clock = std::sync::Mutex::new(crate::tools::codemode::PauseClock::new());
245 {
246 let wait = engine.await_user_input_withdrawal(
247 "undisplayed",
248 user_input_request(),
249 withdrawal.clone(),
250 Some(&invocation_clock),
251 );
252 tokio::pin!(wait);
253 assert!(
254 tokio::time::timeout(Duration::from_millis(50), &mut wait)
255 .await
256 .is_err()
257 );
258 assert!(
259 invocation_clock
260 .lock()
261 .unwrap()
262 .remaining(Duration::from_millis(1))
263 .is_none()
264 );
265 if timed_out {
266 assert!(matches!(wait.await, Err(ToolError::Timeout { .. })));
267 } else {
268 withdrawal.cancel();
269 assert!(matches!(wait.await, Err(ToolError::Cancelled { .. })));
270 }
271 }
272 assert!(matches!(full_rx.try_recv(), Ok(Event::Status { .. })));
273 assert!(matches!(full_rx.try_recv(), Ok(Event::Status { .. })));
274 assert!(full_rx.try_recv().is_err());
275 engine.tx_event = regular;
276 }
277 engine.config.user_input_timeout = None;
278 {
279 let wait = engine.await_user_input("disconnected", user_input_request());
280 tokio::pin!(wait);
281 assert!(
282 tokio::time::timeout(Duration::from_millis(2), &mut wait)
283 .await
284 .is_err()
285 );
286 assert!(
287 matches!(handle.rx_event.write().await.recv().await,Some(Event::UserInputRequired {id,..}) if id == "disconnected")
288 );
289 handle.rx_event.write().await.close();
290 assert!(matches!(wait.await, Err(ToolError::ExecutionFailed { .. })));
291 }
292 assert!(
293 matches!(handle.rx_event.write().await.recv().await,Some(Event::UserInputClosed {id,outcome:crate::core::events::UserInputClosedOutcome::Unavailable}) if id == "disconnected")
294 );
295 handle.rx_event.write().await.close();
296 let result = tokio::time::timeout(
297 Duration::from_secs(5),
298 engine.await_user_input("ask-undeliverable", user_input_request()),
299 )
300 .await
301 .expect("an undeliverable question must not wait for an answer");
302 assert!(
303 matches!(result, Err(ToolError::ExecutionFailed { .. })),
304 "{result:?}"
305 );
306 }
307
308 #[tokio::test]
309 async fn an_open_user_input_question_is_not_charged_to_the_turn() {
310 // C02-19: a delivered question the person leaves open is human time, not
311 // the agent's; the per-turn wall clock does not advance across it.
312 let workspace = tempdir().unwrap();
313 let wait = Duration::from_millis(400);
314 let (mut engine, _handle) = quiet_engine(EngineConfig {
315 user_input_responder: true,
316 user_input_timeout: Some(wait),
317 ..deterministic_engine_config(workspace.path())
318 });
319 let before = engine.turn_wall_clock.spent();
320 let result = engine
321 .await_user_input("ask-unanswered", user_input_request())
322 .await;
323 assert!(
324 matches!(result, Err(ToolError::Timeout { .. })),
325 "{result:?}"
326 );
327 let charged = engine.turn_wall_clock.spent().saturating_sub(before);
328 assert!(
329 charged < wait / 2,
330 "the human wait was charged to the turn budget: {charged:?}"
331 );
332 for withdraw in [false, true] {
333 let (mut engine, handle) = quiet_engine(EngineConfig {
334 user_input_responder: true,
335 ..deterministic_engine_config(workspace.path())
336 });
337 let withdrawal = CancellationToken::new();
338 let invocation_clock = std::sync::Mutex::new(crate::tools::codemode::PauseClock::new());
339 let (accepted, rejected) = tokio::sync::oneshot::channel();
340 {
341 let wait = engine.await_user_input_withdrawal(
342 "withdrawn",
343 user_input_request(),
344 withdrawal.clone(),
345 Some(&invocation_clock),
346 );
347 tokio::pin!(wait);
348 assert!(
349 tokio::time::timeout(Duration::from_millis(5), &mut wait)
350 .await
351 .is_err()
352 );
353 assert!(
354 invocation_clock
355 .lock()
356 .unwrap()
357 .remaining(Duration::from_millis(1))
358 .is_some()
359 );
360 handle
361 .tx_user_input
362 .send(UserInputDecision::Submitted {
363 id: "withdrawn".into(),
364 response: UserInputResponse {
365 answers: Vec::new(),
366 },
367 accepted,
368 })
369 .await
370 .unwrap();
371 if withdraw {
372 withdrawal.cancel();
373 assert!(matches!(wait.await, Err(ToolError::Cancelled { .. })));
374 }
375 }
376 assert!(!rejected.await.unwrap());
377 assert!(
378 matches!(handle.rx_event.write().await.recv().await, Some(Event::UserInputRequired {id,..}) if id == "withdrawn")
379 );
380 assert!(
381 matches!(handle.rx_event.write().await.recv().await, Some(Event::UserInputClosed {id,outcome:crate::core::events::UserInputClosedOutcome::Cancelled}) if id == "withdrawn")
382 );
383 let resumed = engine.turn_wall_clock.spent();
384 tokio::time::sleep(Duration::from_millis(20)).await;
385 assert!(
386 invocation_clock
387 .lock()
388 .unwrap()
389 .remaining(Duration::from_millis(1))
390 .is_none()
391 );
392 assert!(
393 engine.turn_wall_clock.spent().saturating_sub(resumed) >= Duration::from_millis(15)
394 );
395 }
396 }
397
398 #[tokio::test]
399 async fn open_human_waits_pause_tools_phase_stall_watchdog() {
400 let workspace = tempdir().unwrap();
401 let (mut engine, handle) = quiet_engine(EngineConfig {
402 user_input_responder: true,
403 ..deterministic_engine_config(workspace.path())
404 });
405 let heartbeat = Arc::clone(handle.turn_heartbeat());
406 heartbeat.begin_turn("turn-human-wait");
407 heartbeat.enter(
408 crate::core::engine::turn_heartbeat::TurnPhase::Tools,
409 Some("request_user_input".into()),
410 Some(crate::core::engine::turn_heartbeat::TOOLS_PHASE_BOUND),
411 );
412 let overdue = || {
413 tokio::time::Instant::now()
414 + crate::core::engine::turn_heartbeat::TOOLS_PHASE_BOUND
415 + Duration::from_secs(60)
416 };
417
418 let withdrawal = CancellationToken::new();
419 {
420 let wait = engine.await_user_input_withdrawal(
421 "ask-paused",
422 user_input_request(),
423 withdrawal.clone(),
424 None,
425 );
426 tokio::pin!(wait);
427 let mut events = handle.rx_event.write().await;
428 tokio::time::timeout(Duration::from_secs(5), async {
429 loop {
430 tokio::select! {
431 biased;
432 result = &mut wait => panic!("user input wait returned early: {result:?}"),
433 event = events.recv() => {
434 if matches!(event, Some(Event::UserInputRequired { ref id, .. }) if id == "ask-paused") {
435 break;
436 }
437 }
438 }
439 }
440 })
441 .await
442 .expect("UserInputRequired must arrive");
443 drop(events);
444 assert!(heartbeat.detect_slow_at(overdue()).is_none());
445 assert!(heartbeat.detect_stall_at(overdue()).is_none());
446 withdrawal.cancel();
447 assert!(matches!(wait.await, Err(ToolError::Cancelled { .. })));
448 }
449 assert!(heartbeat.detect_stall_at(overdue()).is_some());
450
451 heartbeat.enter(
452 crate::core::engine::turn_heartbeat::TurnPhase::Tools,
453 Some("exec_shell".into()),
454 Some(crate::core::engine::turn_heartbeat::TOOLS_PHASE_BOUND),
455 );
456 let approval_withdraw = CancellationToken::new();
457 {
458 let event = Event::ApprovalRequired {
459 publication: None,
460 id: "approval-paused".into(),
461 tool_name: "exec_shell".into(),
462 approval_key: "exec_shell:test".into(),
463 approval_grouping_key: "exec_shell".into(),
464 input: serde_json::json!({}),
465 description: "run command".into(),
466 intent_summary: None,
467 approval_force_prompt: false,
468 };
469 let wait = engine.request_tool_approval_until(
470 "approval-paused",
471 "exec_shell",
472 event,
473 Some(&approval_withdraw),
474 );
475 tokio::pin!(wait);
476 let mut events = handle.rx_event.write().await;
477 tokio::time::timeout(Duration::from_secs(5), async {
478 loop {
479 tokio::select! {
480 biased;
481 result = &mut wait => panic!("approval wait returned early: {result:?}"),
482 event = events.recv() => {
483 if matches!(event, Some(Event::ApprovalRequired { ref id, .. }) if id == "approval-paused") {
484 break;
485 }
486 }
487 }
488 }
489 })
490 .await
491 .expect("ApprovalRequired must arrive");
492 drop(events);
493 assert!(
494 tokio::time::timeout(Duration::from_millis(20), &mut wait)
495 .await
496 .is_err()
497 );
498 assert!(heartbeat.detect_slow_at(overdue()).is_none());
499 assert!(heartbeat.detect_stall_at(overdue()).is_none());
500 approval_withdraw.cancel();
501 assert!(matches!(wait.await, Err(ToolError::Cancelled { .. })));
502 }
503 assert!(heartbeat.detect_stall_at(overdue()).is_some());
504 }
505
506 #[tokio::test]
507 async fn user_input_acknowledges_only_live_answer_or_cancellation() {
508 for timeout in [None, Some(Duration::ZERO)] {
509 for cancel in [false, true] {
510 for typed in [false, true] {
511 let workspace = tempdir().unwrap();
512 let (mut engine, handle) = quiet_engine(EngineConfig {
513 user_input_responder: true,
514 user_input_timeout: timeout,
515 ..deterministic_engine_config(workspace.path())
516 });
517 let mut request = user_input_request();
518 request.require_typed_answers = typed;
519 let waiter =
520 tokio::spawn(
521 async move { engine.await_user_input("live-question", request).await },
522 );
523 assert!(matches!(handle.rx_event.write().await.recv().await,
524 Some(Event::UserInputRequired {id, ..}) if id == "live-question"));
525 if cancel {
526 handle
527 .cancel_user_input("live-question")
528 .await
529 .expect("live cancel accepted");
530 let error = waiter.await.unwrap().unwrap_err();
531 if typed {
532 assert_eq!(
533 error.metadata(),
534 Some(&serde_json::json!({"user_question_error": "ASK_CANCELLED"}))
535 );
536 } else {
537 assert!(matches!(&error, ToolError::Cancelled { .. }));
538 assert!(error.metadata().is_none());
539 }
540 } else {
541 if typed {
542 assert!(
543 handle
544 .submit_user_input(
545 "live-question",
546 UserInputResponse {
547 answers: Vec::new()
548 }
549 )
550 .await
551 .is_err()
552 );
553 }
554 let response = if typed {
555 serde_json::from_value(serde_json::json!({"answers":[{"id":"choice","kind":"custom","label":"","value":"answer"}]})).unwrap()
556 } else {
557 UserInputResponse {
558 answers: Vec::new(),
559 }
560 };
561 handle
562 .submit_user_input("live-question", response)
563 .await
564 .expect("live answer accepted");
565 assert!(waiter.await.unwrap().is_ok());
566 }
567 loop {
568 if let Some(Event::UserInputClosed { id, outcome }) = tokio::time::timeout(
569 Duration::from_secs(1),
570 handle.rx_event.write().await.recv(),
571 )
572 .await
573 .expect("close receipt must arrive")
574 {
575 assert_eq!(id, "live-question");
576 assert_eq!(
577 outcome,
578 if cancel {
579 crate::core::events::UserInputClosedOutcome::Cancelled
580 } else {
581 crate::core::events::UserInputClosedOutcome::Answered
582 }
583 );
584 break;
585 }
586 }
587 }
588 }
589 }
590 }
591
592 #[tokio::test]
593 async fn user_input_expired_deadline_or_cancellation_rejects_ready_reply() {
594 for canceled in [false, true] {
595 let workspace = tempdir().unwrap();
596 let (mut engine, handle) = quiet_engine(EngineConfig {
597 user_input_responder: true,
598 user_input_timeout: (!canceled).then_some(Duration::from_millis(200)),
599 ..deterministic_engine_config(workspace.path())
600 });
601 let cancel = engine.cancel_token.clone();
602 let wait = engine.await_user_input("expired-question", user_input_request());
603 tokio::pin!(wait);
604 assert!(
605 tokio::time::timeout(Duration::from_millis(5), &mut wait)
606 .await
607 .is_err()
608 );
609 if canceled {
610 cancel.cancel();
611 } else {
612 // Stop polling the wait until its actual absolute deadline has
613 // elapsed, then make both the mailbox and terminal bound ready.
614 tokio::time::sleep(Duration::from_millis(230)).await;
615 }
616 let submission = handle.submit_user_input(
617 "expired-question",
618 UserInputResponse {
619 answers: Vec::new(),
620 },
621 );
622 tokio::pin!(submission);
623 assert!(
624 tokio::time::timeout(Duration::from_millis(5), &mut submission)
625 .await
626 .is_err()
627 );
628 let outcome = wait.await;
629 if canceled {
630 assert!(matches!(outcome, Err(ToolError::Cancelled { .. })));
631 } else {
632 assert!(matches!(outcome, Err(ToolError::Timeout { .. })));
633 }
634 assert!(
635 tokio::time::timeout(Duration::from_secs(1), submission)
636 .await
637 .expect("wait exit must reject the queued verdict")
638 .is_err()
639 );
640 }
641 }
642
643 #[tokio::test]
644 async fn user_input_mismatched_and_abandoned_replies_do_not_end_live_wait() {
645 let workspace = tempdir().unwrap();
646 let (mut engine, handle) = quiet_engine(EngineConfig {
647 user_input_responder: true,
648 ..deterministic_engine_config(workspace.path())
649 });
650 let waiter = tokio::spawn(async move {
651 engine
652 .await_user_input("current-question", user_input_request())
653 .await
654 });
655 assert!(matches!(
656 handle.rx_event.write().await.recv().await,
657 Some(Event::UserInputRequired { .. })
658 ));
659 assert!(
660 handle
661 .submit_user_input(
662 "old-question",
663 UserInputResponse {
664 answers: Vec::new()
665 }
666 )
667 .await
668 .is_err()
669 );
670 assert!(handle.cancel_user_input("old-question").await.is_err());
671 for cancel in [false, true] {
672 let (accepted, receiver) = tokio::sync::oneshot::channel();
673 drop(receiver);
674 let decision = if cancel {
675 UserInputDecision::Cancelled {
676 id: "current-question".into(),
677 accepted,
678 }
679 } else {
680 UserInputDecision::Submitted {
681 id: "current-question".into(),
682 response: UserInputResponse {
683 answers: Vec::new(),
684 },
685 accepted,
686 }
687 };
688 handle.tx_user_input.send(decision).await.unwrap();
689 }
690 handle
691 .submit_user_input(
692 "current-question",
693 UserInputResponse {
694 answers: vec![crate::tools::user_input::UserInputAnswer {
695 kind: None,
696 id: "choice".into(),
697 label: "Live".into(),
698 value: "accepted-live-reply".into(),
699 }],
700 },
701 )
702 .await
703 .expect("current response accepted after rejected decisions");
704 let response = waiter.await.unwrap().expect("live waiter completed");
705 assert_eq!(response.answers[0].value, "accepted-live-reply");
706 }
707
708 #[tokio::test]
709 #[allow(clippy::await_holding_lock)]
710 async fn edit_last_turn_restores_the_exchange_when_the_replacement_never_starts() {
711 // C02-02: `/edit` cuts the last exchange, then dispatches the new text.
712 // A dispatch that never starts must hand the cut exchange back.
713 let _lock = lock_test_env();
714 let tmp = tempdir().unwrap();
715 let api_config = Config::default().with_legacy_root(
716 Some("test-key".to_string()),
717 Some("http://127.0.0.1:9".to_string()),
718 );
719 let (mut engine, handle) = Engine::new_with_model_client(
720 EngineConfig {
721 workspace: tmp.path().to_path_buf(),
722 model: "deepseek-v4-pro".to_string(),
723 snapshots_enabled: false,
724 subagents_enabled: false,
725 ..Default::default()
726 },
727 &api_config,
728 Arc::new(MockLlmClient::new(Vec::new())),
729 );
730 // No model client: the replacement send returns NotStarted.
731 engine.model_client = None;
732 let run = tokio::spawn(engine.run());
733 let text = |role: Role, text: &str| Message {
734 role,
735 content: vec![ContentBlock::Text {
736 text: text.to_string(),
737 cache_control: None,
738 }],
739 };
740 handle
741 .send(Op::SyncSession {
742 expected: None,
743 control: crate::core::ops::SessionControlId::new(),
744 session_id: Some("edit-restore".to_string()),
745 messages: vec![
746 text(Role::User, "original prompt"),
747 text(Role::Assistant, "original answer"),
748 ],
749 system_prompt: None,
750 system_prompt_override: false,
751 model: "deepseek-v4-pro".to_string(),
752 workspace: tmp.path().to_path_buf(),
753 mode: AppMode::Agent,
754 agent_preset: None,
755 })
756 .await
757 .unwrap();
758 let before = session_snapshot(&handle).await;
759 assert_eq!(before.messages.len(), 2);
760 handle
761 .send(Op::EditLastTurn {
762 new_message: "edited prompt".to_string(),
763 submission_id: None,
764 })
765 .await
766 .unwrap();
767 let after = session_snapshot(&handle).await;
768 assert_eq!(
769 after.messages, before.messages,
770 "a replacement that never started must not cost the original exchange"
771 );
772 handle.send(Op::Shutdown).await.unwrap();
773 run.await.unwrap();
774 }
775
776 async fn sync_with_mode(
777 handle: &EngineHandle,
778 workspace: &std::path::Path,
779 session_id: &str,
780 messages: Vec<Message>,
781 agent_preset: Option<&str>,
782 ) {
783 handle
784 .send(Op::SyncSession {
785 expected: None,
786 control: crate::core::ops::SessionControlId::new(),
787 session_id: Some(session_id.to_string()),
788 messages,
789 system_prompt: None,
790 system_prompt_override: false,
791 model: "deepseek-v4-pro".to_string(),
792 workspace: workspace.to_path_buf(),
793 mode: AppMode::Agent,
794 agent_preset: agent_preset.map(str::to_string),
795 })
796 .await
797 .unwrap();
798 }
799
800 fn user_text(text: &str) -> Message {
801 Message {
802 role: Role::User,
803 content: vec![ContentBlock::Text {
804 text: text.to_string(),
805 cache_control: None,
806 }],
807 }
808 }
809
810 #[tokio::test]
811 async fn sync_session_installs_the_conversation_mode_on_the_engine_session() {
812 let tmp = tempdir().unwrap();
813 let (engine, handle) = quiet_engine(deterministic_engine_config(tmp.path()));
814 let run = tokio::spawn(engine.run());
815 assert_eq!(session_snapshot(&handle).await.agent_preset, None);
816 sync_with_mode(
817 &handle,
818 tmp.path(),
819 "blank-one",
820 Vec::new(),
821 Some("creator"),
822 )
823 .await;
824 assert_eq!(
825 session_snapshot(&handle).await.agent_preset.as_deref(),
826 Some("creator")
827 );
828 sync_with_mode(&handle, tmp.path(), "blank-one", Vec::new(), None).await;
829 assert_eq!(
830 session_snapshot(&handle).await.agent_preset,
831 None,
832 "a still-blank conversation may change its mode"
833 );
834 sync_with_mode(
835 &handle,
836 tmp.path(),
837 "other",
838 vec![user_text("hi")],
839 Some("creator"),
840 )
841 .await;
842 assert_eq!(
843 session_snapshot(&handle).await.agent_preset.as_deref(),
844 Some("creator"),
845 "another conversation installs its own mode"
846 );
847 sync_with_mode(&handle, tmp.path(), "fresh", Vec::new(), None).await;
848 assert_eq!(session_snapshot(&handle).await.agent_preset, None);
849 handle.send(Op::Shutdown).await.unwrap();
850 run.await.unwrap();
851 }
852
853 #[tokio::test]
854 async fn a_sync_of_the_same_conversation_with_messages_cannot_change_its_conversation_mode() {
855 let tmp = tempdir().unwrap();
856 let (engine, handle) = quiet_engine(deterministic_engine_config(tmp.path()));
857 let run = tokio::spawn(engine.run());
858 let history = vec![user_text("first message")];
859 sync_with_mode(
860 &handle,
861 tmp.path(),
862 "locked",
863 history.clone(),
864 Some("creator"),
865 )
866 .await;
867 sync_with_mode(&handle, tmp.path(), "locked", history.clone(), None).await;
868 assert_eq!(
869 session_snapshot(&handle).await.agent_preset.as_deref(),
870 Some("creator")
871 );
872 sync_with_mode(&handle, tmp.path(), "locked", history, Some("minimal")).await;
873 assert_eq!(
874 session_snapshot(&handle).await.agent_preset.as_deref(),
875 Some("creator")
876 );
877 handle.send(Op::Shutdown).await.unwrap();
878 run.await.unwrap();
879 }
880
881 #[tokio::test]
882 async fn malformed_mcp_config_is_reported_instead_of_silently_empty() {
883 // C02-18: an unreadable config still yields an empty, reloadable pool,
884 // but the person is told the configured servers are gone.
885 let workspace = tempdir().unwrap();
886 let config_path = workspace.path().join("mcp.json");
887 fs::write(&config_path, "{ this is not json").unwrap();
888 let (mut engine, handle) = quiet_engine(deterministic_engine_config(workspace.path()));
889 engine.session.mcp_config_path = config_path;
890 engine
891 .ensure_mcp_pool()
892 .await
893 .expect("a reloadable empty pool still exists");
894 let mut rx = handle.rx_event.write().await;
895 let reported = std::iter::from_fn(|| rx.try_recv().ok()).any(|event| {
896 matches!(
897 event,
898 Event::Status { ref message } if message.contains("MCP config could not be loaded")
899 )
900 });
901 assert!(reported, "a malformed MCP config must not fail silently");
902 }
903
903 lines RUST