返回 CodeWhale
conversation_undo.rs
根目录 / crates / tui / src / tui / ui / tests / conversation_undo.rs
1 //! Exercise command dispatch, the actual UI apply path, Engine requests and disk.
2 use super::*;
3 use codewhale_engine::core::engine::{Engine, EngineConfig};
4 use codewhale_engine::core::events::TurnOutcomeStatus;
5 use codewhale_engine::llm_client::mock::{MockLlmClient, canned};
6 use codewhale_models::{ContentBlock, Message};
7
8 fn prompts(messages: &[Message]) -> Vec<String> {
9 messages
10 .iter()
11 .filter(|message| {
12 matches!(
13 codewhale_models::turn_classify::classify_user_turn_prompt(message),
14 codewhale_models::turn_classify::UserTurnPromptKind::Editable
15 )
16 })
17 .flat_map(|message| &message.content)
18 .filter_map(|block| match block {
19 ContentBlock::Text { text, .. } if !text.starts_with("<turn_meta>") => {
20 Some(text.clone())
21 }
22 _ => None,
23 })
24 .collect()
25 }
26
27 async fn settled(app: &mut App, handle: &EngineHandle, answer: &str) {
28 let mut events = handle.rx_event.write().await;
29 loop {
30 let event = tokio::time::timeout(Duration::from_secs(30), events.recv())
31 .await
32 .expect("turn deadline")
33 .expect("Engine event");
34 if let EngineEvent::TurnComplete { status, error, .. } = event {
35 assert_eq!(status, TurnOutcomeStatus::Completed, "{error:?}");
36 break;
37 }
38 }
39 drop(events);
40 let snapshot = handle
41 .get_session_snapshot()
42 .await
43 .expect("settled snapshot");
44 app.session_write_owner = snapshot
45 .source
46 .clone()
47 .map(codewhale_engine::session_manager::SessionWriteOwner::Engine);
48 app.current_session_id = Some(snapshot.session_id);
49 app.set_api_messages(Arc::new(snapshot.messages));
50 app.system_prompt = snapshot.system_prompt;
51 app.model = snapshot.model;
52 app.is_loading = false;
53 app.push_history_cell(HistoryCell::Assistant {
54 content: answer.into(),
55 streaming: false,
56 });
57 }
58
59 fn sync_snapshot(
60 snapshot: &codewhale_engine::core::ops::SessionSnapshot,
61 control: codewhale_engine::core::ops::SessionControlId,
62 ) -> Op {
63 Op::SyncSession {
64 expected: None,
65 control,
66 session_id: Some(snapshot.session_id.clone()),
67 messages: snapshot.messages.clone(),
68 system_prompt: snapshot.system_prompt.clone(),
69 system_prompt_override: false,
70 model: snapshot.model.clone(),
71 workspace: snapshot.workspace.clone(),
72 mode: AppMode::parse(&snapshot.mode).unwrap(),
73 agent_preset: snapshot.agent_preset.clone(),
74 }
75 }
76
77 async fn flush_persistence(actor: &persistence_actor::PersistActorHandle) {
78 let (reply, receive) = tokio::sync::oneshot::channel();
79 assert!(actor.try_send(PersistRequest::FlushAndReport { reply }));
80 assert!(receive.await.unwrap().failures.is_empty());
81 }
82
83 #[test]
84 fn undo_retry_apply_path_keeps_engine_request_and_reopened_session_consistent() {
85 const PROBE: &str = "CODEWHALE_UNDO_RETRY_APPLY_PROBE";
86 if std::env::var_os(PROBE).is_none() {
87 // The production actor is process-global. Never replace another
88 // test's actor or leave this fixture's closed sender in its process.
89 let output = Command::new(std::env::current_exe().unwrap())
90 .args([
91 "--exact",
92 "tui::ui::tests::conversation_undo::undo_retry_apply_path_keeps_engine_request_and_reopened_session_consistent",
93 "--nocapture",
94 "--test-threads=1",
95 ])
96 .env(PROBE, "1")
97 .output()
98 .expect("isolated UI lifecycle");
99 assert!(
100 output.status.success(),
101 "{}\n{}",
102 String::from_utf8_lossy(&output.stdout),
103 String::from_utf8_lossy(&output.stderr)
104 );
105 assert!(String::from_utf8_lossy(&output.stdout).contains("1 passed"));
106 return;
107 }
108 let _environment = crate::test_support::lock_test_env();
109 let home = TempDir::new().unwrap();
110 let workspace = TempDir::new().unwrap();
111 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path());
112 let runtime = tokio::runtime::Builder::new_current_thread()
113 .enable_all()
114 .build()
115 .unwrap();
116 runtime.block_on(async {
117 let mut config = Config::default().with_legacy_root(
118 Some("mock-credential".into()),
119 Some("http://127.0.0.1:1/v1".into()),
120 );
121 config.set_feature("mcp", false).unwrap();
122 config.set_feature("subagents", false).unwrap();
123 let mut app = App::new(
124 crate::tui::test_support::test_tui_options(workspace.path()),
125 &config,
126 );
127 app.onboarding_needs_api_key = false;
128 app.offline_mode = false;
129 app.mode = AppMode::Agent;
130 let mock = Arc::new(MockLlmClient::new(vec![
131 canned::simple_text_turn("kept answer"),
132 canned::simple_text_turn("undone answer"),
133 canned::simple_text_turn("retry answer one"),
134 canned::simple_text_turn("retry answer two"),
135 canned::simple_text_turn("answer after reopen"),
136 ]));
137 let (engine, mut handle) = Engine::new_with_model_client(
138 EngineConfig {
139 workspace: workspace.path().to_path_buf(),
140 model: app.model.clone(),
141 snapshots_enabled: false,
142 subagents_enabled: false,
143 terminal_chrome_enabled: false,
144 ..EngineConfig::default()
145 },
146 &config,
147 mock.clone(),
148 );
149 let engine_task = tokio::spawn(engine.run());
150 let manager = SessionManager::default_location().unwrap();
151 let initial_id = handle.get_session_snapshot().await.unwrap().session_id;
152 app.set_current_session_id(Some(initial_id.clone()));
153 super::super::session_state::expect_fresh_session(&mut app, &initial_id).unwrap();
154 let (actor, actor_task) =
155 persistence_actor::spawn_persistence_actor(SessionManager::default_location().unwrap());
156 persistence_actor::init_actor(actor.clone());
157 let tasks = TaskManager::start(
158 TaskManagerConfig::from_runtime(&config, workspace.path().into(), None, Some(1)),
159 config.clone(),
160 app.plugin_registry.clone(),
161 "undo-fixture-tasks",
162 None,
163 )
164 .await
165 .unwrap();
166 app.runtime_services.task_manager = Some(tasks.clone());
167 let mut backend = ColorCompatBackend::new(
168 std::io::stdout(),
169 codewhale_palette::ColorDepth::Monochrome,
170 codewhale_palette::PaletteMode::Dark,
171 );
172 backend.set_terminal_size(Size::new(80, 24));
173 let mut terminal = Terminal::new(backend).unwrap();
174
175 for (prompt, answer) in [
176 ("keep this", "kept answer"),
177 ("retry this", "undone answer"),
178 ] {
179 apply_command_result(
180 &mut terminal,
181 &mut app,
182 &mut handle,
183 &mut config,
184 commands::CommandResult {
185 message: None,
186 action: Some(AppAction::SendMessage(prompt.into())),
187 is_error: false,
188 },
189 )
190 .await
191 .unwrap();
192 settled(&mut app, &handle, answer).await;
193 }
194 // Seed the Engine's typed compaction format, then consume the real
195 // SessionUpdated projection. Current projections strip the legacy
196 // system-prompt carrier; history must retain the checkpoint on undo.
197 let checkpoint_text = format!("{}\nRetained earlier facts", codewhale_engine::compaction::SUMMARY_HEADER);
198 let checkpoint = codewhale_engine::compaction::compaction_checkpoint_message(
199 &SystemPrompt::Text(checkpoint_text.clone()),
200 );
201 let mut compacted = handle.get_session_snapshot().await.unwrap();
202 let stable_prompt = compacted.system_prompt.as_ref()
203 .map(codewhale_engine::compaction::summary_prompt_text).unwrap_or_default();
204 compacted.messages.insert(0, checkpoint.clone());
205 compacted.system_prompt = Some(SystemPrompt::Text(format!(
206 "{stable_prompt}\n\n<!-- compaction-summary:begin -->\n{checkpoint_text}\n<!-- compaction-summary:end -->"
207 )));
208 handle.send(sync_snapshot(&compacted, app.session_sync_control())).await.unwrap();
209 loop {
210 let event = handle.rx_event.write().await.recv().await.unwrap();
211 if matches!(&event, EngineEvent::SessionUpdated { messages, .. } if messages.contains(&checkpoint)) {
212 assert!(super::super::event_loop::apply_engine_session_projection(&mut app, &config, event));
213 break;
214 }
215 }
216 assert!(codewhale_engine::compaction::extract_compaction_summary(app.system_prompt.as_ref()).is_none());
217 assert!(app.api_messages.contains(&checkpoint));
218 let id = app.current_session_id.clone().unwrap();
219 flush_persistence(&actor).await;
220 let mut old = build_session_snapshot(&mut app, &manager).unwrap();
221 old.capture_publication(app.session_write_owner.clone().unwrap()).unwrap();
222 let publication = manager.publish_session(&old).unwrap();
223 let path = publication.path.clone();
224 old.adopt_publication(&publication);
225 app.session_write_receipt = old.write_receipt.clone();
226 // The stale in-flight recovery record must not revive the undone turn.
227 assert!(super::super::session_state::try_persist_session(&mut app, PersistRequest::SaveCheckpoint { session: old }));
228 flush_persistence(&actor).await;
229 assert!(
230 serde_json::to_string(
231 &manager
232 .load_session_checkpoint(&id)
233 .unwrap()
234 .unwrap()
235 .messages
236 )
237 .unwrap()
238 .contains("undone answer")
239 );
240
241 for answer in ["retry answer one", "retry answer two"] {
242 let result = commands::execute("/retry", &mut app);
243 assert!(matches!(
244 result.action,
245 Some(AppAction::ConversationUndo { .. })
246 ));
247 apply_command_result(
248 &mut terminal,
249 &mut app,
250 &mut handle,
251 &mut config,
252 result,
253 )
254 .await
255 .unwrap();
256 settled(&mut app, &handle, answer).await;
257 let requests = mock.captured_requests();
258 let last = requests.last().unwrap();
259 assert_eq!(prompts(&last.messages), ["keep this", "retry this"]);
260 assert!(last.messages.contains(&checkpoint), "retry request lost retained checkpoint");
261 assert!(
262 !serde_json::to_string(&last.messages)
263 .unwrap()
264 .contains("undone answer")
265 );
266 let reopened = manager.load_session(&id).unwrap();
267 assert!(reopened.messages.contains(&checkpoint), "durable undo lost retained checkpoint");
268 assert_eq!(
269 prompts(&reopened.messages),
270 ["keep this"],
271 "rollback is durable before replacement inference"
272 );
273 // Dispatch starts a fresh recovery checkpoint. This fixture reads
274 // TurnComplete directly, so it does not run the UI completion save
275 // that would retire that new checkpoint. Inspect its history rather
276 // than incorrectly expecting the replacement turn to have none.
277 flush_persistence(&actor).await;
278 let checkpoint = manager.load_session_checkpoint(&id).unwrap().unwrap();
279 assert_eq!(prompts(&checkpoint.messages), ["keep this", "retry this"]);
280 let checkpoint_text = serde_json::to_string(&checkpoint.messages).unwrap();
281 assert!(!checkpoint_text.contains("undone answer"));
282 assert!(!checkpoint_text.contains("retry answer"));
283 }
284 assert_eq!(mock.captured_requests().len(), 4);
285
286 // Force a real Engine update between successful UI preflight and the
287 // rewind operation. The proxy only orders mailbox operations: snapshots,
288 // mutation, refusal and provider calls still belong to the real Engine.
289 // Same-length history changes must be caught, as must each context field.
290 let alternate_workspace = TempDir::new().unwrap();
291 for (changed_field, before_preflight) in [
292 ("messages", false), ("identity", false), ("model", false),
293 ("workspace", false), ("prompt", false), ("mode", false),
294 ("prompt", true), ("mode", true),
295 ] {
296 let original = handle.get_session_snapshot().await.unwrap();
297 let mut newer = original.clone();
298 match changed_field {
299 "messages" => {
300 let ContentBlock::Text { text, .. } =
301 &mut newer.messages.last_mut().unwrap().content[0]
302 else {
303 panic!("fixture answer should be text");
304 };
305 *text = "a newer owned answer".into();
306 }
307 "identity" => newer.session_id = "newer-conversation".into(),
308 "model" => newer.model = "newer-model".into(),
309 "workspace" => newer.workspace = alternate_workspace.path().to_path_buf(),
310 "prompt" => newer.system_prompt = Some(SystemPrompt::Text("newer instructions".into())),
311 "mode" => newer.mode = AppMode::Plan.as_setting().into(),
312 _ => unreachable!(),
313 }
314 let replacement_control = codewhale_engine::core::ops::SessionControlId::new();
315 newer.source = Some(codewhale_engine::core::ops::SessionSnapshotSource::control(replacement_control.clone()));
316 let replacement = sync_snapshot(&newer, replacement_control);
317 let real_handle = handle.clone();
318 let queued = real_handle.clone();
319 let (proxy_tx, mut proxy_rx) = tokio::sync::mpsc::channel(8);
320 handle.tx_op = proxy_tx;
321 let interleaving = tokio::spawn(async move {
322 let mut replacement = Some(replacement);
323 while let Some(op) = proxy_rx.recv().await {
324 let is_preflight = matches!(&op, Op::GetSessionSnapshot { .. });
325 if is_preflight && before_preflight && let Some(replacement) = replacement.take() {
326 queued.send(replacement).await.unwrap();
327 }
328 queued.send(op).await.unwrap();
329 if is_preflight && let Some(replacement) = replacement.take() {
330 // FIFO puts B after snapshot A, but before the UI can
331 // enqueue its conditional rewind through this proxy.
332 queued.send(replacement).await.unwrap();
333 }
334 }
335 assert!(replacement.is_none(), "preflight snapshot must have run");
336 });
337 app.input = "keep this unsent draft".into();
338 app.cursor_position = 7;
339 let visible = app.api_messages.clone();
340 let visible_id = app.current_session_id.clone();
341 let visible_model = app.model.clone();
342 let visible_workspace = app.workspace.clone();
343 let visible_prompt = app.system_prompt.clone();
344 let history_len = app.history.len();
345 let result = commands::execute("/retry", &mut app);
346 apply_command_result(
347 &mut terminal,
348 &mut app,
349 &mut handle,
350 &mut config,
351 result,
352 )
353 .await
354 .unwrap();
355 handle = real_handle;
356 interleaving.await.unwrap();
357 let current = handle.get_session_snapshot().await.unwrap();
358 let installed = codewhale_engine::core::ops::SessionSnapshot {
359 instruction_assembly: None,
360 ..newer.clone()
361 };
362 assert!(current == installed, "queued {changed_field} update must not be overwritten");
363 assert!(app.api_messages == visible, "visible history changed on refusal");
364 assert!(app.current_session_id == visible_id, "visible identity changed on refusal");
365 assert!(app.model == visible_model, "visible model changed on refusal");
366 assert!(app.workspace == visible_workspace, "visible workspace changed on refusal");
367 assert!(app.system_prompt == visible_prompt, "visible prompt changed on refusal");
368 assert_eq!(app.history.len(), history_len);
369 assert!(matches!(app.history.last(), Some(HistoryCell::Assistant { content, .. }) if content == "retry answer two"));
370 assert_eq!(app.input, "keep this unsent draft");
371 assert_eq!(app.cursor_position, 7);
372 assert_eq!(mock.captured_requests().len(), 4, "refusal must not dispatch retry inference");
373 assert!(app.status_toasts.back().unwrap().text.contains(
374 app.tr(MessageId::ConversationChangedBeforeUndo).as_ref()
375 ));
376 // Restore only the fixture between independent race cases.
377 let restore_control = app.session_sync_control();
378 handle.send(sync_snapshot(&original, restore_control.clone())).await.unwrap();
379 assert!(
380 handle.get_session_snapshot().await.unwrap()
381 == codewhale_engine::core::ops::SessionSnapshot {
382 source: Some(codewhale_engine::core::ops::SessionSnapshotSource::control(restore_control)),
383 instruction_assembly: None,
384 ..original
385 }
386 );
387 }
388
389 // Runtime Chat ownership and a locally active turn must refuse before
390 // even staging a different Engine history or altering the transcript.
391 let before = app.api_messages.clone();
392 app.remote_control.block_runtime_chat_dispatch_for_tests();
393 let result = commands::execute("/retry", &mut app);
394 apply_command_result(
395 &mut terminal,
396 &mut app,
397 &mut handle,
398 &mut config,
399 result,
400 )
401 .await
402 .unwrap();
403 assert_eq!(app.api_messages, before);
404 assert_eq!(mock.captured_requests().len(), 4);
405 app.remote_control = Default::default();
406 app.is_loading = true;
407 let result = commands::execute("/retry", &mut app);
408 apply_command_result(
409 &mut terminal,
410 &mut app,
411 &mut handle,
412 &mut config,
413 result,
414 )
415 .await
416 .unwrap();
417 assert_eq!(app.api_messages, before);
418 app.is_loading = false;
419
420 let result = commands::execute("/undo", &mut app);
421 apply_command_result(
422 &mut terminal,
423 &mut app,
424 &mut handle,
425 &mut config,
426 result,
427 )
428 .await
429 .unwrap();
430 let engine_saved = handle.get_session_snapshot().await.unwrap();
431 let reopened = SessionManager::default_location()
432 .unwrap()
433 .load_session(&id)
434 .unwrap();
435 assert_eq!(prompts(&engine_saved.messages), ["keep this"]);
436 assert_eq!(prompts(&app.api_messages), ["keep this"]);
437 assert_eq!(prompts(&reopened.messages), ["keep this"]);
438 assert!(
439 manager.load_session_checkpoint(&id).unwrap().is_none(),
440 "standalone undo retires the checkpoint without starting new turn work"
441 );
442 assert!(
443 !serde_json::to_string(&reopened.messages)
444 .unwrap()
445 .contains("retry answer")
446 );
447 assert_eq!(
448 mock.captured_requests().len(),
449 4,
450 "undo performs no inference"
451 );
452
453 // Resume the durable record through the existing UI projection and
454 // SyncSession apply action, then inspect the actual next model request.
455 // File LoadSession always respawns a real client, so use the same
456 // loaded-session projection with our injected model client here.
457 apply_loaded_session(&mut app, &mut config, &reopened).unwrap();
458 assert_eq!(
459 app.history.iter().filter_map(|cell| match cell {
460 HistoryCell::User { content } => Some(content.as_str()),
461 _ => None,
462 }).collect::<Vec<_>>(),
463 ["keep this"]
464 );
465 assert!(app.history.iter().any(|cell| {
466 matches!(cell, HistoryCell::System { content } if content == &checkpoint_text)
467 }));
468 assert!(app.api_messages.contains(&checkpoint));
469 let restore = AppAction::SyncSession {
470 session_id: app.current_session_id.clone(),
471 messages: app.api_messages.as_ref().clone(),
472 system_prompt: app.system_prompt.clone(),
473 model: app.model.clone(),
474 workspace: app.workspace.clone(),
475 mode: app.mode,
476 agent_preset: app.agent_preset(),
477 };
478 for action in [restore, AppAction::SendMessage("after reopen".into())] {
479 apply_command_result(
480 &mut terminal,
481 &mut app,
482 &mut handle,
483 &mut config,
484 commands::CommandResult {
485 message: None,
486 action: Some(action),
487 is_error: false,
488 },
489 )
490 .await
491 .unwrap();
492 }
493 settled(&mut app, &handle, "answer after reopen").await;
494 let requests = mock.captured_requests();
495 assert_eq!(requests.len(), 5);
496 assert!(requests.last().unwrap().messages.contains(&checkpoint), "reopened provider request lost checkpoint");
497 assert_eq!(
498 prompts(&requests.last().unwrap().messages),
499 ["keep this", "after reopen"]
500 );
501 let inbound = serde_json::to_string(&requests.last().unwrap().messages).unwrap();
502 assert!(!inbound.contains("retry this"));
503 assert!(!inbound.contains("undone answer"));
504 assert!(!inbound.contains("retry answer"));
505
506 // `/edit` then submit replaces the last exchange: the old prompt and
507 // its answer leave the transcript, the provider request and the saved
508 // session, and the edited prompt takes their place.
509 let loaded = commands::execute("/edit", &mut app);
510 assert!(!loaded.is_error, "{:?}", loaded.message);
511 assert_eq!(app.input, "after reopen");
512 assert!(app.edit_in_progress);
513 let edit_store = Arc::new(SessionManager::default_location().unwrap());
514 let edit_id = id.clone();
515 mock.push_factory(move |_| {
516 let durable = edit_store.load_session_snapshot(&edit_id).unwrap();
517 assert_eq!(
518 prompts(&durable.messages),
519 ["keep this"],
520 "the edit rollback is durable before the replacement provider request"
521 );
522 canned::simple_text_turn("edited answer")
523 });
524 let result = super::super::event_loop::edit_replacement_result(&mut app, "edited prompt")
525 .expect("a pending edit stages a replacement");
526 assert!(!app.edit_in_progress);
527 apply_command_result(
528 &mut terminal,
529 &mut app,
530 &mut handle,
531 &mut config,
532 result,
533 )
534 .await
535 .unwrap();
536 settled(&mut app, &handle, "edited answer").await;
537 let requests = mock.captured_requests();
538 assert_eq!(requests.len(), 6);
539 assert_eq!(
540 prompts(&requests.last().unwrap().messages),
541 ["keep this", "edited prompt"]
542 );
543 let inbound = serde_json::to_string(&requests.last().unwrap().messages).unwrap();
544 assert!(!inbound.contains("after reopen"));
545 assert_eq!(prompts(&app.api_messages), ["keep this", "edited prompt"]);
546 let completed = build_session_snapshot(&mut app, &manager).unwrap();
547 assert!(super::super::session_state::try_persist_session(
548 &mut app,
549 PersistRequest::CompletedCommit { session: completed }
550 ));
551 flush_persistence(&actor).await;
552 assert_eq!(
553 prompts(&manager.load_session_snapshot(&id).unwrap().messages),
554 ["keep this", "edited prompt"],
555 "the completed replacement is durable after its completion save"
556 );
557 assert!(manager.load_session_checkpoint(&id).unwrap().is_none());
558 // With no edit pending, a submit is an ordinary turn.
559 assert!(
560 super::super::event_loop::edit_replacement_result(&mut app, "plain").is_none()
561 );
562
563 // Return to the retained exchange before probing durable-save failure.
564 let result = commands::execute("/undo", &mut app);
565 apply_command_result(
566 &mut terminal,
567 &mut app,
568 &mut handle,
569 &mut config,
570 result,
571 )
572 .await
573 .unwrap();
574 assert_eq!(
575 prompts(&app.api_messages),
576 ["keep this"],
577 "undo status: {:?}; toasts: {:?}; system history: {:?}",
578 app.visible_notice_text(),
579 app.status_toasts.iter().map(|toast| toast.text.as_str()).collect::<Vec<_>>(),
580 app.history.iter().filter_map(|cell| match cell {
581 HistoryCell::System { content } => Some(content.as_str()),
582 _ => None,
583 }).collect::<Vec<_>>()
584 );
585
586 // Portable save failure: block the canonical file with a directory.
587 // Preserve the last durable snapshot as a sibling for inspection.
588 let before_failure = handle.get_session_snapshot().await.unwrap();
589 std::fs::rename(&path, path.with_extension("before-failure")).unwrap();
590 std::fs::create_dir(&path).unwrap();
591 app.input = "unrelated draft".into();
592 app.cursor_position = app.input.chars().count();
593 let result = commands::execute("/retry", &mut app);
594 apply_command_result(
595 &mut terminal,
596 &mut app,
597 &mut handle,
598 &mut config,
599 result,
600 )
601 .await
602 .unwrap();
603 assert_eq!(app.input, "unrelated draft");
604 assert!(app.queued_messages.is_empty());
605 assert!(app.history.iter().any(|cell| matches!(cell, HistoryCell::System { content } if content == "Retry prompt was not sent. Copy it from here to retry:\nkeep this")));
606 assert_eq!(mock.captured_requests().len(), 6);
607 handle.send(sync_snapshot(&before_failure, app.session_sync_control())).await.unwrap();
608 assert_eq!(handle.get_session_snapshot().await.unwrap().messages, before_failure.messages);
609 app.set_api_messages(Arc::new(before_failure.messages));
610 app.push_history_cell(HistoryCell::User { content: "keep this".into() });
611 let loaded = commands::execute("/edit", &mut app);
612 assert!(!loaded.is_error, "{:?}", loaded.message);
613 let result = super::super::event_loop::edit_replacement_result(&mut app, "replacement after failed save")
614 .expect("a pending edit stages a replacement");
615 apply_command_result(
616 &mut terminal,
617 &mut app,
618 &mut handle,
619 &mut config,
620 result,
621 )
622 .await
623 .unwrap();
624 assert_eq!(
625 mock.captured_requests().len(),
626 6,
627 "save failure must forbid retry inference"
628 );
629 assert!(
630 app.status_toasts
631 .back()
632 .unwrap()
633 .text
634 .contains("session save failed")
635 );
636 assert!(
637 app.api_messages.as_slice() == [checkpoint.clone()],
638 "acknowledged undo remains visible after save failure"
639 );
640 assert_eq!(app.input, "replacement after failed save");
641 assert!(!app.edit_in_progress);
642 assert!(super::super::event_loop::edit_replacement_result(&mut app, "replacement after failed save").is_none());
643 assert!(app.status_toasts.back().unwrap().text.contains("Conversation was rewound"));
644 assert!(
645 handle
646 .get_session_snapshot()
647 .await
648 .unwrap()
649 .messages == [checkpoint]
650 );
651
652 handle.send(Op::Shutdown).await.unwrap();
653 engine_task.await.unwrap();
654 app.set_api_messages(Arc::new(reopened.messages));
655 app.push_history_cell(HistoryCell::User {
656 content: "keep this".into(),
657 });
658 let result = commands::execute("/retry", &mut app);
659 let before = app.api_messages.clone();
660 apply_command_result(
661 &mut terminal,
662 &mut app,
663 &mut handle,
664 &mut config,
665 result,
666 )
667 .await
668 .unwrap();
669 assert_eq!(
670 app.api_messages, before,
671 "closed Engine must leave the visible conversation alone"
672 );
673 assert!(
674 app.status_toasts
675 .back()
676 .unwrap()
677 .text
678 .contains("retry was not sent")
679 );
680 assert_eq!(mock.captured_requests().len(), 6);
681 tasks.shutdown_and_wait().await.unwrap();
682 assert!(actor.try_send(PersistRequest::Shutdown));
683 actor_task.await.unwrap();
684 });
685 }
686
687 /// A refused `/edit` rollback has already consumed the revision from the
688 /// composer. It must come back, with edit mode re-armed, not be lost.
689 #[tokio::test]
690 async fn refused_edit_rollback_returns_the_revision_to_the_composer() {
691 use codewhale_engine::task_manager::{
692 TaskExecutionResult, TaskManagerConfig, TaskStatus, TaskTerminalReason,
693 };
694 struct Idle;
695 #[async_trait::async_trait]
696 impl codewhale_engine::task_manager::TaskExecutor for Idle {
697 async fn execute(
698 &self,
699 _: codewhale_engine::task_manager::ExecutionTask,
700 _: tokio::sync::mpsc::Sender<codewhale_engine::task_manager::TaskExecutionEvent>,
701 _: tokio_util::sync::CancellationToken,
702 ) -> TaskExecutionResult {
703 TaskExecutionResult {
704 status: TaskStatus::Completed,
705 result_text: None,
706 error: None,
707 terminal_reason: TaskTerminalReason::Completed,
708 }
709 }
710 }
711 let root = TempDir::new().unwrap();
712 let tasks = TaskManager::start_with_executor(
713 TaskManagerConfig {
714 data_dir: root.path().into(),
715 worker_count: 1,
716 default_workspace: root.path().into(),
717 default_model: "fixture".into(),
718 default_mode: "plan".into(),
719 allow_shell: false,
720 trust_mode: false,
721 execution_limits: codewhale_engine::task_manager::TaskExecutionLimits::default(),
722 human_waits_answerable: false,
723 },
724 Arc::new(Idle),
725 )
726 .await
727 .unwrap();
728 let mut backend = ColorCompatBackend::new(
729 std::io::stdout(),
730 codewhale_palette::ColorDepth::Monochrome,
731 codewhale_palette::PaletteMode::Dark,
732 );
733 backend.set_terminal_size(Size::new(80, 24));
734 let mut terminal = Terminal::new(backend).unwrap();
735 let mut config = Config::default();
736 let mut engine = mock_engine_handle();
737
738 let mut app = create_test_app();
739 app.runtime_services.task_manager = Some(tasks.clone());
740 app.push_history_cell(HistoryCell::User {
741 content: "original prompt".into(),
742 });
743 let loaded = commands::execute("/edit", &mut app);
744 assert!(!loaded.is_error, "{:?}", loaded.message);
745 assert!(app.edit_in_progress);
746 // The user revises the prompt and presses Enter: the composer is consumed
747 // and the replacement is staged behind a rollback.
748 app.input = "revised prompt".into();
749 let submitted = std::mem::take(&mut app.input);
750 let result = super::super::event_loop::edit_replacement_result(&mut app, &submitted)
751 .expect("a pending edit stages a replacement");
752 assert!(!app.edit_in_progress);
753 assert!(app.input.is_empty());
754 // Force the refusal: the rollback is only allowed on an idle app.
755 app.is_loading = true;
756
757 apply_command_result(
758 &mut terminal,
759 &mut app,
760 &mut engine.handle,
761 &mut config,
762 result,
763 )
764 .await
765 .unwrap();
766
767 assert_eq!(app.input, "revised prompt", "the revision is restored");
768 assert_eq!(app.cursor_position, "revised prompt".chars().count());
769 assert!(app.edit_in_progress, "edit mode is active again");
770 assert!(
771 app.history.iter().any(
772 |cell| matches!(cell, HistoryCell::User { content } if content == "original prompt")
773 ),
774 "the refused rollback leaves the original exchange alone"
775 );
776 assert!(
777 app.status_toasts
778 .iter()
779 .any(|toast| toast.text.contains("rollback failed")),
780 "the refusal is still reported"
781 );
782 assert!(
783 engine.rx_op.try_recv().is_err(),
784 "nothing reached the engine"
785 );
786 tasks.shutdown_and_wait().await.unwrap();
787 }
788
789 #[test]
790 fn range_undo_refuses_in_flight_child_and_restores_settled_delegated_writes_across_resume() {
791 const PROBE: &str = "CODEWHALE_DELEGATED_UNDO_PROBE";
792 if std::env::var_os(PROBE).is_none() {
793 let output = Command::new(std::env::current_exe().unwrap())
794 .args([
795 "--exact",
796 "tui::ui::tests::conversation_undo::range_undo_refuses_in_flight_child_and_restores_settled_delegated_writes_across_resume",
797 "--nocapture",
798 "--test-threads=1",
799 ])
800 .env(PROBE, "1")
801 .output()
802 .expect("isolated delegated undo lifecycle");
803 assert!(
804 output.status.success(),
805 "{}\n{}",
806 String::from_utf8_lossy(&output.stdout),
807 String::from_utf8_lossy(&output.stderr)
808 );
809 assert!(String::from_utf8_lossy(&output.stdout).contains("1 passed"));
810 return;
811 }
812
813 let _environment = crate::test_support::lock_test_env();
814 let home = TempDir::new().unwrap();
815 let workspace = TempDir::new().unwrap();
816 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path());
817 let child_files = [
818 "agent_a_1.txt",
819 "agent_a_2.txt",
820 "agent_b_1.txt",
821 "agent_b_2.txt",
822 "agent_c_1.txt",
823 "agent_c_2.txt",
824 ];
825 for path in child_files {
826 std::fs::write(workspace.path().join(path), "before").unwrap();
827 }
828
829 let runtime = tokio::runtime::Builder::new_current_thread()
830 .enable_all()
831 .build()
832 .unwrap();
833 runtime.block_on(async {
834 let mut config = Config::default().with_legacy_root(
835 Some("mock-credential".into()),
836 Some("http://127.0.0.1:1/v1".into()),
837 );
838 config.set_feature("mcp", false).unwrap();
839 config.set_feature("subagents", true).unwrap();
840 let mut app = App::new(
841 crate::tui::test_support::test_tui_options(workspace.path()),
842 &config,
843 );
844 app.onboarding_needs_api_key = false;
845 app.offline_mode = false;
846 app.set_agent_approval_posture(ApprovalMode::Bypass);
847
848 let mock = Arc::new(MockLlmClient::new(vec![canned::tool_call_turn(
849 "call-lead-write",
850 "write_file",
851 r#"{"path":"lead.txt","content":"lead"}"#,
852 )]));
853 let child_workspace = workspace.path().to_path_buf();
854 mock.push_factory(move |_| {
855 for path in child_files {
856 std::fs::write(child_workspace.join(path), "after").unwrap();
857 }
858 canned::simple_text_turn("delegated work settled")
859 });
860
861 let (engine, mut handle) = Engine::new_with_model_client(
862 EngineConfig {
863 workspace: workspace.path().to_path_buf(),
864 model: app.model.clone(),
865 snapshots_enabled: true,
866 record_restore_points: true,
867 subagents_enabled: true,
868 terminal_chrome_enabled: false,
869 ..EngineConfig::default()
870 },
871 &config,
872 mock.clone(),
873 );
874 let engine_task = tokio::spawn(engine.run());
875 let manager = SessionManager::default_location().unwrap();
876 let initial_id = handle.get_session_snapshot().await.unwrap().session_id;
877 app.set_current_session_id(Some(initial_id.clone()));
878 super::super::session_state::expect_fresh_session(&mut app, &initial_id).unwrap();
879 let (actor, actor_task) =
880 persistence_actor::spawn_persistence_actor(SessionManager::default_location().unwrap());
881 persistence_actor::init_actor(actor.clone());
882 let tasks = TaskManager::start(
883 TaskManagerConfig::from_runtime(&config, workspace.path().into(), None, Some(1)),
884 config.clone(),
885 app.plugin_registry.clone(),
886 "delegated-undo-tasks",
887 None,
888 )
889 .await
890 .unwrap();
891 app.runtime_services.task_manager = Some(tasks.clone());
892 let mut backend = ColorCompatBackend::new(
893 std::io::stdout(),
894 codewhale_palette::ColorDepth::Monochrome,
895 codewhale_palette::PaletteMode::Dark,
896 );
897 backend.set_terminal_size(Size::new(80, 24));
898 let mut terminal = Terminal::new(backend).unwrap();
899
900 apply_command_result(
901 &mut terminal,
902 &mut app,
903 &mut handle,
904 &mut config,
905 commands::CommandResult {
906 message: None,
907 action: Some(AppAction::SendMessage("delegate 6 edits".into())),
908 is_error: false,
909 },
910 )
911 .await
912 .unwrap();
913 settled(&mut app, &handle, "delegated work settled").await;
914
915 for (seq, agent_id, pair) in [
916 (1u64, "agent-a", ["agent_a_1.txt", "agent_a_2.txt"]),
917 (2u64, "agent-b", ["agent_b_1.txt", "agent_b_2.txt"]),
918 (3u64, "agent-c", ["agent_c_1.txt", "agent_c_2.txt"]),
919 ] {
920 let msg = codewhale_engine::tools::subagent::MailboxMessage::FileWrites {
921 agent_id: agent_id.into(),
922 turn_seq: 1,
923 paths: pair.into_iter().map(str::to_string).collect(),
924 };
925 crate::tui::subagent_routing::handle_subagent_mailbox_for_turn(
926 &mut app, "turn-1", seq, &msg,
927 );
928 }
929
930 let subagent_mgr = handle.subagent_manager();
931 let running_id = {
932 let mut mgr = subagent_mgr.write().await;
933 let id = mgr.insert_test_running_direct_child("live-worker", workspace.path());
934 mgr.assign_test_session_owner(&id, &initial_id);
935 id
936 };
937 let in_flight_err = apply_range_undo(&mut terminal, &mut app, &handle, &config, 0)
938 .await
939 .unwrap_err();
940 assert!(
941 in_flight_err
942 .to_string()
943 .contains("Wait for delegated work to settle; nothing was undone."),
944 "{in_flight_err:#}"
945 );
946 for path in child_files {
947 assert_eq!(
948 std::fs::read_to_string(workspace.path().join(path)).unwrap(),
949 "after"
950 );
951 }
952 assert_eq!(
953 std::fs::read_to_string(workspace.path().join("lead.txt")).unwrap(),
954 "lead"
955 );
956
957 subagent_mgr
958 .write()
959 .await
960 .cancel_agent(&running_id)
961 .unwrap();
962
963 let completed = build_session_snapshot(&mut app, &manager).unwrap();
964 assert!(super::super::session_state::try_persist_session(
965 &mut app,
966 PersistRequest::CompletedCommit { session: completed }
967 ));
968 flush_persistence(&actor).await;
969 let saved = manager.load_session_snapshot(&initial_id).unwrap();
970 let saved_paths = saved
971 .delegated_writes
972 .get(&1)
973 .expect("persisted delegated writes");
974 assert_eq!(saved_paths.len(), 6);
975 app.delegated_writes.clear();
976 apply_loaded_session(&mut app, &mut config, &saved).unwrap();
977 assert_eq!(
978 app.delegated_writes
979 .get(&(initial_id.clone(), 1))
980 .expect("restored delegated writes")
981 .len(),
982 6
983 );
984 handle
985 .send(Op::SyncSession {
986 expected: None,
987 control: app.session_sync_control(),
988 session_id: app.current_session_id.clone(),
989 messages: app.api_messages.as_ref().clone(),
990 system_prompt: app.system_prompt.clone(),
991 system_prompt_override: false,
992 model: app.model.clone(),
993 workspace: app.workspace.clone(),
994 mode: app.mode,
995 agent_preset: saved.agent_preset.clone(),
996 })
997 .await
998 .unwrap();
999 loop {
1000 let event = handle.rx_event.write().await.recv().await.unwrap();
1001 if matches!(event, EngineEvent::SessionUpdated { .. }) {
1002 break;
1003 }
1004 }
1005 let synced = handle.get_session_snapshot().await.unwrap();
1006 app.system_prompt = synced.system_prompt;
1007 app.model = synced.model;
1008
1009 apply_range_undo(&mut terminal, &mut app, &handle, &config, 0)
1010 .await
1011 .unwrap();
1012 flush_persistence(&actor).await;
1013 for path in child_files {
1014 assert_eq!(
1015 std::fs::read_to_string(workspace.path().join(path)).unwrap(),
1016 "before"
1017 );
1018 }
1019 assert!(!workspace.path().join("lead.txt").exists());
1020 assert!(app.api_messages.is_empty());
1021 assert!(app.delegated_writes.is_empty());
1022 assert!(
1023 manager
1024 .load_session_snapshot(&initial_id)
1025 .unwrap()
1026 .delegated_writes
1027 .is_empty()
1028 );
1029
1030 tasks.shutdown_and_wait().await.unwrap();
1031 handle.send(Op::Shutdown).await.unwrap();
1032 engine_task.await.unwrap();
1033 assert!(actor.try_send(PersistRequest::Shutdown));
1034 actor_task.await.unwrap();
1035 });
1036 }
1037
1037 lines RUST