| 1 | //! Preserved snapshot/history safety tests outside the portable debug group. |
| 2 | use super::CommandResult; |
| 3 | fn patch_undo(app: &mut App) -> CommandResult { |
| 4 | if app.api_messages.is_empty() && app.history.is_empty() { |
| 5 | return CommandResult::message("Nothing to undo"); |
| 6 | } |
| 7 | let restored = (|| { |
| 8 | let cut = crate::tui::ui::backtrack_api_cut_index(app, 0).ok_or_else(|| { |
| 9 | anyhow::anyhow!("The selected request cannot be matched safely; nothing was undone.") |
| 10 | })?; |
| 11 | let input = super::undo_range_input(app, cut)?; |
| 12 | let plan = super::plan_undo_range(input)?; |
| 13 | super::restore_undo_range(plan) |
| 14 | })(); |
| 15 | match restored { |
| 16 | Ok(summary) => { |
| 17 | let mut result = undo_conversation(app); |
| 18 | result.message = Some(summary); |
| 19 | result |
| 20 | } |
| 21 | Err(error) => CommandResult::error(format!("Nothing was undone. {error:#}")), |
| 22 | } |
| 23 | } |
| 24 | fn undo_conversation(app: &mut App) -> CommandResult { |
| 25 | let undone = super::contract::debug_operations::undo_conversation_for_engine(app); |
| 26 | if undone.removed > 0 { |
| 27 | CommandResult::with_message_and_action( |
| 28 | format!("Removed {} message(s)", undone.removed), |
| 29 | AppAction::ConversationUndo { |
| 30 | sync: undone.sync, |
| 31 | restored_files: 0, |
| 32 | retry_input: None, |
| 33 | edit_replacement: false, |
| 34 | }, |
| 35 | ) |
| 36 | } else { |
| 37 | CommandResult::message("Nothing to undo") |
| 38 | } |
| 39 | } |
| 40 | fn acknowledge_file_undo(app: &mut App, result: &CommandResult) { |
| 41 | let Some(AppAction::ConversationUndo { sync, .. }) = &result.action else { |
| 42 | panic!("file undo did not request a durable conversation rewind"); |
| 43 | }; |
| 44 | assert!(app.api_messages.len() > sync.messages.len()); |
| 45 | if let Some(index) = app |
| 46 | .history |
| 47 | .iter() |
| 48 | .rposition(|cell| matches!(cell, HistoryCell::User { .. })) |
| 49 | { |
| 50 | app.truncate_history_to(index); |
| 51 | } |
| 52 | app.set_api_messages(std::sync::Arc::new(sync.messages.clone())); |
| 53 | } |
| 54 | fn retry(app: &mut App) -> CommandResult { |
| 55 | super::execute("/retry", app) |
| 56 | } |
| 57 | use crate::tui::app::{App, AppAction, TuiOptions}; |
| 58 | use crate::tui::history::HistoryCell; |
| 59 | use codewhale_models::Role; |
| 60 | use codewhale_models::{ContentBlock, Message, Tool}; |
| 61 | use codewhale_runtime::config::Config; |
| 62 | use std::path::PathBuf; |
| 63 | |
| 64 | pub(in crate::commands) fn create_test_app() -> App { |
| 65 | let options = TuiOptions { |
| 66 | skills_dir: PathBuf::from("/tmp/test-skills"), |
| 67 | ..crate::tui::test_support::test_tui_options(PathBuf::from("/tmp/test-workspace")) |
| 68 | }; |
| 69 | let mut app = App::new(options, &Config::default()); |
| 70 | app.ui_locale = codewhale_localization::Locale::En; |
| 71 | app.cost_currency = codewhale_config::pricing::CostCurrency::Usd; |
| 72 | app.api_provider = codewhale_config::ProviderKind::Deepseek; |
| 73 | app |
| 74 | } |
| 75 | |
| 76 | #[test] |
| 77 | fn edit_dispatch_loads_unicode_composer_without_truncating_history() { |
| 78 | let mut app = create_test_app(); |
| 79 | app.push_history_cell(HistoryCell::User { |
| 80 | content: "edit 漢字🙂".into(), |
| 81 | }); |
| 82 | let count = app.history.len(); |
| 83 | let result = super::execute("/edit", &mut app); |
| 84 | assert_eq!( |
| 85 | result.message.as_deref(), |
| 86 | Some("Last message loaded into composer — edit and press Enter to resubmit") |
| 87 | ); |
| 88 | assert_eq!(app.input, "edit 漢字🙂"); |
| 89 | assert_eq!(app.cursor_position, "edit 漢字🙂".chars().count()); |
| 90 | assert!(app.edit_in_progress); |
| 91 | assert_eq!(app.history.len(), count); |
| 92 | assert!(result.action.is_none()); |
| 93 | assert!(!result.is_error); |
| 94 | } |
| 95 | |
| 96 | /// A queued follow-up open for editing must not be overwritten or later sent |
| 97 | /// in place of the `/edit` revision: it goes back to the queue, text intact. |
| 98 | #[test] |
| 99 | fn edit_dispatch_returns_an_open_queued_draft_to_the_queue() { |
| 100 | use crate::tui::app::QueuedMessage; |
| 101 | let mut app = create_test_app(); |
| 102 | app.push_history_cell(HistoryCell::User { |
| 103 | content: "last sent".into(), |
| 104 | }); |
| 105 | app.queued_messages |
| 106 | .push_back(QueuedMessage::new("queued follow-up".to_string(), None)); |
| 107 | assert!(app.pop_last_queued_into_draft()); |
| 108 | assert_eq!(app.input, "queued follow-up"); |
| 109 | assert!(app.queued_draft.is_some()); |
| 110 | |
| 111 | let result = super::execute("/edit", &mut app); |
| 112 | assert!(!result.is_error, "{:?}", result.message); |
| 113 | assert!(app.queued_draft.is_none(), "draft edit is closed"); |
| 114 | assert_eq!( |
| 115 | app.queued_messages |
| 116 | .iter() |
| 117 | .map(|message| message.display.as_str()) |
| 118 | .collect::<Vec<_>>(), |
| 119 | ["queued follow-up"], |
| 120 | "the queued follow-up is back in the queue, exactly once" |
| 121 | ); |
| 122 | assert_eq!(app.input, "last sent"); |
| 123 | assert!(app.edit_in_progress); |
| 124 | } |
| 125 | |
| 126 | #[test] |
| 127 | fn diff_dispatch_reads_only_the_apps_workspace_without_changing_files() { |
| 128 | let workspace = tempfile::tempdir().unwrap(); |
| 129 | let git = |args: &[&str]| { |
| 130 | let result = std::process::Command::new("git") |
| 131 | .args(args) |
| 132 | .current_dir(workspace.path()) |
| 133 | .output() |
| 134 | .unwrap(); |
| 135 | assert!( |
| 136 | result.status.success(), |
| 137 | "{}", |
| 138 | String::from_utf8_lossy(&result.stderr) |
| 139 | ); |
| 140 | String::from_utf8(result.stdout).unwrap() |
| 141 | }; |
| 142 | git(&["init", "--quiet"]); |
| 143 | std::fs::write(workspace.path().join("tracked.txt"), "before\n").unwrap(); |
| 144 | git(&["add", "tracked.txt"]); |
| 145 | git(&[ |
| 146 | "-c", |
| 147 | "user.name=Fixture", |
| 148 | "-c", |
| 149 | "user.email=fixture@example.invalid", |
| 150 | "-c", |
| 151 | "commit.gpgsign=false", |
| 152 | "commit", |
| 153 | "--quiet", |
| 154 | "-m", |
| 155 | "fixture", |
| 156 | ]); |
| 157 | let mut app = create_test_app(); |
| 158 | app.workspace = workspace.path().to_path_buf(); |
| 159 | assert_eq!( |
| 160 | super::execute("/diff", &mut app).message.as_deref(), |
| 161 | Some("No changes since session start") |
| 162 | ); |
| 163 | std::fs::write(workspace.path().join("tracked.txt"), "after\n").unwrap(); |
| 164 | let stat = git(&["diff", "--stat"]); |
| 165 | let result = super::execute("/diff", &mut app); |
| 166 | assert_eq!( |
| 167 | result.message, |
| 168 | Some(format!( |
| 169 | "Changed files (1):\ntracked.txt\n\n── Stat ──\n{}", |
| 170 | stat.trim() |
| 171 | )) |
| 172 | ); |
| 173 | assert!(!result.is_error); |
| 174 | // The changed lines themselves, not only the names and counts. |
| 175 | let Some(AppAction::OpenDiffPager { diff, .. }) = result.action else { |
| 176 | panic!("expected the diff pager: {:?}", result.action); |
| 177 | }; |
| 178 | assert!(diff.contains("-before\n+after\n"), "{diff}"); |
| 179 | assert_eq!( |
| 180 | std::fs::read_to_string(workspace.path().join("tracked.txt")).unwrap(), |
| 181 | "after\n" |
| 182 | ); |
| 183 | } |
| 184 | |
| 185 | /// In a folder that is not a git repository `/diff` used to answer "No |
| 186 | /// changes since session start" after real edits (0.10.1 tutorial, lesson 1). |
| 187 | #[test] |
| 188 | fn diff_outside_a_git_repository_says_so_instead_of_no_changes() { |
| 189 | let workspace = tempfile::tempdir().unwrap(); |
| 190 | let inside_a_repository = std::process::Command::new("git") |
| 191 | .args(["rev-parse", "--is-inside-work-tree"]) |
| 192 | .current_dir(workspace.path()) |
| 193 | .output() |
| 194 | .is_ok_and(|probe| probe.status.success()); |
| 195 | if inside_a_repository { |
| 196 | // The temp directory itself lives in a repository on this machine. |
| 197 | return; |
| 198 | } |
| 199 | std::fs::write(workspace.path().join("edited.txt"), "after\n").unwrap(); |
| 200 | let mut app = create_test_app(); |
| 201 | app.workspace = workspace.path().to_path_buf(); |
| 202 | |
| 203 | let message = super::execute("/diff", &mut app) |
| 204 | .message |
| 205 | .unwrap_or_default(); |
| 206 | |
| 207 | // No restore point and no repository: nothing to compare against, which |
| 208 | // is said plainly rather than reported as "no changes" or as a failure. |
| 209 | assert_eq!( |
| 210 | message, |
| 211 | "Nothing to compare yet: this session has not saved a restore point here, and this folder is not a git repository." |
| 212 | ); |
| 213 | } |
| 214 | |
| 215 | pub(in crate::commands) fn test_tool(name: &str) -> Tool { |
| 216 | Tool { |
| 217 | tool_type: Some("function".to_string()), |
| 218 | name: name.to_string(), |
| 219 | description: format!("{name} test tool"), |
| 220 | input_schema: serde_json::json!({ |
| 221 | "type": "object", |
| 222 | "properties": { |
| 223 | "path": {"type": "string"} |
| 224 | } |
| 225 | }), |
| 226 | allowed_callers: None, |
| 227 | defer_loading: Some(false), |
| 228 | input_examples: None, |
| 229 | strict: Some(true), |
| 230 | cache_control: None, |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | #[test] |
| 235 | fn test_undo_conversation_stages_last_exchange_without_mutating_live_history() { |
| 236 | let mut app = create_test_app(); |
| 237 | app.history.push(HistoryCell::User { |
| 238 | content: "Hello".to_string(), |
| 239 | }); |
| 240 | app.history.push(HistoryCell::Assistant { |
| 241 | content: "Hi".to_string(), |
| 242 | streaming: false, |
| 243 | }); |
| 244 | app.api_messages_mut().push(Message { |
| 245 | role: Role::User, |
| 246 | content: vec![ContentBlock::Text { |
| 247 | text: "Hello".to_string(), |
| 248 | cache_control: None, |
| 249 | }], |
| 250 | }); |
| 251 | app.api_messages_mut().push(Message { |
| 252 | role: Role::Assistant, |
| 253 | content: vec![ContentBlock::Text { |
| 254 | text: "Hi".to_string(), |
| 255 | cache_control: None, |
| 256 | }], |
| 257 | }); |
| 258 | |
| 259 | let initial_history_len = app.history.len(); |
| 260 | let initial_api_len = app.api_messages.len(); |
| 261 | let result = undo_conversation(&mut app); |
| 262 | |
| 263 | assert!(result.message.is_some()); |
| 264 | let msg = result.message.unwrap(); |
| 265 | assert!(msg.contains("Removed")); |
| 266 | assert_eq!( |
| 267 | app.history.len(), |
| 268 | initial_history_len, |
| 269 | "planning leaves live UI untouched" |
| 270 | ); |
| 271 | assert_eq!(app.api_messages.len(), initial_api_len); |
| 272 | assert!( |
| 273 | matches!(result.action, Some(AppAction::ConversationUndo { sync, retry_input: None, .. }) if sync.messages.is_empty()) |
| 274 | ); |
| 275 | } |
| 276 | |
| 277 | #[test] |
| 278 | fn conversation_undo_includes_following_tool_results_and_runtime_notes() { |
| 279 | let mut app = create_test_app(); |
| 280 | app.history.push(HistoryCell::User { |
| 281 | content: "undo this".into(), |
| 282 | }); |
| 283 | let messages: Vec<Message> = serde_json::from_value(serde_json::json!([ |
| 284 | {"role":"user","content":[{"type":"text","text":"keep this"}]}, |
| 285 | {"role":"assistant","content":[{"type":"text","text":"kept answer"}]}, |
| 286 | {"role":"user","content":[{"type":"text","text":"undo this"}]}, |
| 287 | {"role":"assistant","content":[{"type":"tool_use","id":"call-1","name":"read_file","input":{}}]}, |
| 288 | {"role":"user","content":[{"type":"tool_result","tool_use_id":"call-1","content":"undone tool result"}]}, |
| 289 | {"role":"assistant","content":[{"type":"text","text":"undone answer"}]} |
| 290 | ])).unwrap(); |
| 291 | app.set_api_messages(std::sync::Arc::new(messages.clone())); |
| 292 | let result = undo_conversation(&mut app); |
| 293 | let Some(AppAction::ConversationUndo { sync, .. }) = result.action else { |
| 294 | panic!("missing rollback") |
| 295 | }; |
| 296 | assert_eq!(sync.messages, messages[..2]); |
| 297 | assert_eq!(app.api_messages.as_ref(), &messages); |
| 298 | } |
| 299 | |
| 300 | #[test] |
| 301 | fn test_undo_conversation_nothing_to_undo() { |
| 302 | let mut app = create_test_app(); |
| 303 | // Clear any default history |
| 304 | app.history.clear(); |
| 305 | app.api_messages_mut().clear(); |
| 306 | let result = undo_conversation(&mut app); |
| 307 | assert!(result.message.is_some()); |
| 308 | let msg = result.message.unwrap(); |
| 309 | assert!(msg.contains("Nothing to undo") || msg.contains("Removed")); |
| 310 | } |
| 311 | |
| 312 | #[test] |
| 313 | fn test_retry_with_previous_message() { |
| 314 | let mut app = create_test_app(); |
| 315 | app.history.push(HistoryCell::User { |
| 316 | content: "Test message".to_string(), |
| 317 | }); |
| 318 | app.history.push(HistoryCell::Assistant { |
| 319 | content: "Response".to_string(), |
| 320 | streaming: false, |
| 321 | }); |
| 322 | |
| 323 | let result = retry(&mut app); |
| 324 | assert!(result.message.is_some()); |
| 325 | let msg = result.message.unwrap(); |
| 326 | assert!(msg.contains("Retrying")); |
| 327 | assert!(msg.contains("Test message")); |
| 328 | assert!(matches!( |
| 329 | result.action.as_ref(), |
| 330 | Some(AppAction::ConversationUndo { retry_input: Some(input), .. }) if input == "Test message" |
| 331 | )); |
| 332 | } |
| 333 | |
| 334 | #[test] |
| 335 | fn test_retry_no_previous_message() { |
| 336 | let mut app = create_test_app(); |
| 337 | let result = retry(&mut app); |
| 338 | assert!(result.message.is_some()); |
| 339 | let msg = result.message.unwrap(); |
| 340 | assert!(msg.contains("No previous request to retry")); |
| 341 | assert!(result.action.is_none()); |
| 342 | } |
| 343 | |
| 344 | #[test] |
| 345 | fn test_retry_truncates_long_input() { |
| 346 | let mut app = create_test_app(); |
| 347 | let long_input = "x".repeat(100); |
| 348 | app.history.push(HistoryCell::User { |
| 349 | content: long_input.clone(), |
| 350 | }); |
| 351 | app.history.push(HistoryCell::Assistant { |
| 352 | content: "Response".to_string(), |
| 353 | streaming: false, |
| 354 | }); |
| 355 | |
| 356 | let result = retry(&mut app); |
| 357 | assert!(result.message.is_some()); |
| 358 | let msg = result.message.unwrap(); |
| 359 | assert!(msg.contains("Retrying")); |
| 360 | assert!(msg.contains("...")); |
| 361 | } |
| 362 | |
| 363 | #[test] |
| 364 | fn test_patch_undo_requests_durable_rewind_after_restore() { |
| 365 | let fx = UndoFixture::new(); |
| 366 | fx.write("a.txt", "original"); |
| 367 | let messages = fx.record_turn("s1", 1, "please edit a.txt", &[("a.txt", "modified")], true); |
| 368 | let mut app = fx.app("s1"); |
| 369 | push_recorded_turn(&mut app, messages.clone()); |
| 370 | app.is_loading = true; |
| 371 | for command in ["/undo", "/undo force"] { |
| 372 | let result = super::execute(command, &mut app); |
| 373 | assert!(matches!( |
| 374 | result.action, |
| 375 | Some(AppAction::UndoLatestRequest { force }) if force == command.ends_with(" force") |
| 376 | )); |
| 377 | assert_eq!(fx.read("a.txt"), "modified"); |
| 378 | assert_eq!(app.api_messages.as_ref(), &messages); |
| 379 | } |
| 380 | app.is_loading = false; |
| 381 | let result = patch_undo(&mut app); |
| 382 | assert!(!result.is_error, "{:?}", result.message); |
| 383 | assert_eq!(fx.read("a.txt"), "original"); |
| 384 | assert_eq!(app.api_messages.as_ref(), &messages); |
| 385 | assert!( |
| 386 | matches!(result.action, Some(AppAction::ConversationUndo { ref sync, .. }) if sync.messages.is_empty()) |
| 387 | ); |
| 388 | acknowledge_file_undo(&mut app, &result); |
| 389 | assert!(app.api_messages.is_empty() && app.history.is_empty()); |
| 390 | } |
| 391 | |
| 392 | #[test] |
| 393 | fn test_undo_legacy_chain_preserves_files_without_writer_receipts() { |
| 394 | let fx = UndoFixture::new(); |
| 395 | fx.write("a.txt", "zero"); |
| 396 | fx.snapshot("tool:provider-call", "s1"); |
| 397 | fx.write("a.txt", "two"); |
| 398 | let mut app = fx.app("s1"); |
| 399 | push_exchange(&mut app, "chat only"); |
| 400 | let result = patch_undo(&mut app); |
| 401 | assert!(!result.is_error, "{:?}", result.message); |
| 402 | assert_eq!(fx.read("a.txt"), "two"); |
| 403 | assert!(matches!( |
| 404 | result.action, |
| 405 | Some(AppAction::ConversationUndo { .. }) |
| 406 | )); |
| 407 | } |
| 408 | |
| 409 | #[test] |
| 410 | fn test_patch_undo_prunes_pre_turn_context() { |
| 411 | let fx = UndoFixture::new(); |
| 412 | fx.write("a.txt", "alpha"); |
| 413 | let messages = fx.record_turn( |
| 414 | "s1", |
| 415 | 1, |
| 416 | "please edit a.txt", |
| 417 | &[("a.txt", "alpha-fixed")], |
| 418 | true, |
| 419 | ); |
| 420 | let mut app = fx.app("s1"); |
| 421 | push_recorded_turn(&mut app, messages); |
| 422 | let result = patch_undo(&mut app); |
| 423 | assert!(!result.is_error, "{:?}", result.message); |
| 424 | assert_eq!(fx.read("a.txt"), "alpha"); |
| 425 | assert_eq!(app.history.len(), 2); |
| 426 | acknowledge_file_undo(&mut app, &result); |
| 427 | assert!(app.history.is_empty() && app.api_messages.is_empty()); |
| 428 | } |
| 429 | |
| 430 | #[test] |
| 431 | fn test_patch_undo_never_crosses_session_boundary() { |
| 432 | let fx = UndoFixture::new(); |
| 433 | fx.write("a.txt", "a-before"); |
| 434 | let foreign = fx.record_turn("session-a", 1, "edit a.txt", &[("a.txt", "a-after")], true); |
| 435 | fx.write("a.txt", "b-before"); |
| 436 | let current = fx.record_turn("session-b", 1, "edit a.txt", &[("a.txt", "b-after")], true); |
| 437 | let mut wrong = fx.app("session-b"); |
| 438 | push_recorded_turn(&mut wrong, foreign); |
| 439 | let refused = patch_undo(&mut wrong); |
| 440 | assert!(refused.is_error, "{:?}", refused.message); |
| 441 | assert_eq!(fx.read("a.txt"), "b-after"); |
| 442 | let mut app = fx.app("session-b"); |
| 443 | push_recorded_turn(&mut app, current); |
| 444 | let result = patch_undo(&mut app); |
| 445 | assert!(!result.is_error, "{:?}", result.message); |
| 446 | assert_eq!(fx.read("a.txt"), "b-before"); |
| 447 | acknowledge_file_undo(&mut app, &result); |
| 448 | let repeated = patch_undo(&mut app); |
| 449 | assert_eq!(repeated.message.as_deref(), Some("Nothing to undo")); |
| 450 | assert_eq!(fx.read("a.txt"), "b-before"); |
| 451 | } |
| 452 | |
| 453 | #[test] |
| 454 | fn test_undo_reports_that_files_were_not_reverted_when_the_repo_is_unavailable() { |
| 455 | let tmp = tempfile::tempdir().unwrap(); |
| 456 | let _home = crate::test_support::SealedHome::at(tmp.path()); |
| 457 | let file = tmp.path().join("a.txt"); |
| 458 | std::fs::write(&file, "user bytes").unwrap(); |
| 459 | let mut app = create_test_app(); |
| 460 | app.workspace = tmp.path().to_path_buf(); |
| 461 | app.current_session_id = Some("s1".to_string()); |
| 462 | push_exchange(&mut app, "change something"); |
| 463 | app.api_messages_mut() |
| 464 | .insert(1, fixture_call("host-call", "a.txt", "new bytes")); |
| 465 | let before = app.api_messages.as_ref().clone(); |
| 466 | let result = patch_undo(&mut app); |
| 467 | assert!(result.is_error, "{:?}", result.message); |
| 468 | assert!(result.action.is_none()); |
| 469 | assert_eq!(app.api_messages.as_ref(), &before); |
| 470 | assert_eq!(std::fs::read_to_string(file).unwrap(), "user bytes"); |
| 471 | } |
| 472 | |
| 473 | struct UndoFixture { |
| 474 | workspace: PathBuf, |
| 475 | repo: codewhale_snapshot::SnapshotRepo, |
| 476 | _home: crate::test_support::SealedHome, |
| 477 | _tmp: tempfile::TempDir, |
| 478 | } |
| 479 | |
| 480 | impl UndoFixture { |
| 481 | fn new() -> Self { |
| 482 | let tmp = tempfile::tempdir().unwrap(); |
| 483 | let home = crate::test_support::SealedHome::at(tmp.path()); |
| 484 | let workspace = tmp.path().join("ws"); |
| 485 | std::fs::create_dir_all(&workspace).unwrap(); |
| 486 | let repo = codewhale_snapshot::SnapshotRepo::open_or_init(&workspace).unwrap(); |
| 487 | Self { |
| 488 | workspace, |
| 489 | repo, |
| 490 | _home: home, |
| 491 | _tmp: tmp, |
| 492 | } |
| 493 | } |
| 494 | fn write(&self, name: &str, body: &str) { |
| 495 | std::fs::write(self.workspace.join(name), body).unwrap(); |
| 496 | } |
| 497 | fn read(&self, name: &str) -> String { |
| 498 | std::fs::read_to_string(self.workspace.join(name)).unwrap() |
| 499 | } |
| 500 | fn snapshot(&self, label: &str, session: &str) { |
| 501 | self.repo.take_snapshot(label, Some(session)).unwrap(); |
| 502 | } |
| 503 | fn app(&self, session: &str) -> App { |
| 504 | let mut app = create_test_app(); |
| 505 | app.workspace = self.workspace.clone(); |
| 506 | app.current_session_id = Some(session.to_string()); |
| 507 | app |
| 508 | } |
| 509 | fn record_turn( |
| 510 | &self, |
| 511 | session: &str, |
| 512 | seq: u64, |
| 513 | prompt: &str, |
| 514 | writes: &[(&str, &str)], |
| 515 | complete: bool, |
| 516 | ) -> Vec<Message> { |
| 517 | self.snapshot( |
| 518 | &codewhale_engine::core::turn::format_snapshot_label("pre-turn", seq, Some(prompt)), |
| 519 | session, |
| 520 | ); |
| 521 | let mut messages = vec![Message { |
| 522 | role: Role::User, |
| 523 | content: vec![ContentBlock::Text { |
| 524 | text: prompt.to_string(), |
| 525 | cache_control: None, |
| 526 | }], |
| 527 | }]; |
| 528 | for (path, body) in writes { |
| 529 | let id = uuid::Uuid::new_v4().to_string(); |
| 530 | self.snapshot(&format!("tool:{id}"), session); |
| 531 | messages.push(fixture_call(&id, path, body)); |
| 532 | self.write(path, body); |
| 533 | self.snapshot(&format!("post-tool:{id}"), session); |
| 534 | messages.push(Message { |
| 535 | role: Role::User, |
| 536 | content: vec![ContentBlock::ToolResult { |
| 537 | execution_id: Some(id), |
| 538 | tool_use_id: "reused-provider-call".to_string(), |
| 539 | content: "written".to_string(), |
| 540 | is_error: None, |
| 541 | content_blocks: None, |
| 542 | }], |
| 543 | }); |
| 544 | } |
| 545 | if complete { |
| 546 | self.snapshot( |
| 547 | &codewhale_engine::core::turn::format_snapshot_label( |
| 548 | "post-turn", |
| 549 | seq, |
| 550 | Some(prompt), |
| 551 | ), |
| 552 | session, |
| 553 | ); |
| 554 | } |
| 555 | messages.push(Message { |
| 556 | role: Role::Assistant, |
| 557 | content: vec![ContentBlock::Text { |
| 558 | text: "done".to_string(), |
| 559 | cache_control: None, |
| 560 | }], |
| 561 | }); |
| 562 | messages |
| 563 | } |
| 564 | } |
| 565 | |
| 566 | fn fixture_call(execution: &str, path: &str, body: &str) -> Message { |
| 567 | Message { |
| 568 | role: Role::Assistant, |
| 569 | content: vec![ContentBlock::ToolUse { |
| 570 | execution_id: Some(execution.to_string()), |
| 571 | id: "reused-provider-call".to_string(), |
| 572 | name: "write_file".to_string(), |
| 573 | input: serde_json::json!({"path":path,"content":body}), |
| 574 | caller: None, |
| 575 | thought_signature: None, |
| 576 | }], |
| 577 | } |
| 578 | } |
| 579 | |
| 580 | fn push_recorded_turn(app: &mut App, messages: Vec<Message>) { |
| 581 | let ContentBlock::Text { text, .. } = &messages[0].content[0] else { |
| 582 | panic!("missing fixture prompt") |
| 583 | }; |
| 584 | app.history.push(HistoryCell::User { |
| 585 | content: text.clone(), |
| 586 | }); |
| 587 | app.history.push(HistoryCell::Assistant { |
| 588 | content: "done".to_string(), |
| 589 | streaming: false, |
| 590 | }); |
| 591 | app.api_messages_mut().extend(messages); |
| 592 | } |
| 593 | |
| 594 | fn push_exchange(app: &mut App, prompt: &str) { |
| 595 | push_recorded_turn( |
| 596 | app, |
| 597 | vec![ |
| 598 | Message { |
| 599 | role: Role::User, |
| 600 | content: vec![ContentBlock::Text { |
| 601 | text: prompt.to_string(), |
| 602 | cache_control: None, |
| 603 | }], |
| 604 | }, |
| 605 | Message { |
| 606 | role: Role::Assistant, |
| 607 | content: vec![ContentBlock::Text { |
| 608 | text: "done".to_string(), |
| 609 | cache_control: None, |
| 610 | }], |
| 611 | }, |
| 612 | ], |
| 613 | ); |
| 614 | } |
| 615 | |
| 616 | /// `/diff` in a folder that is not a git repository compares against the |
| 617 | /// session's first restore point, so real edits are shown, including a file |
| 618 | /// created after the newest snapshot. It said "No changes since session |
| 619 | /// start" there, because `git diff` prints nothing outside a repository. |
| 620 | #[test] |
| 621 | fn diff_in_a_folder_without_git_shows_the_changes_since_the_sessions_first_restore_point() { |
| 622 | let fx = UndoFixture::new(); |
| 623 | fx.write("duration.mjs", "export const unit = 'ms';\n"); |
| 624 | // Another session's older restore point is not this session's start. |
| 625 | fx.snapshot("pre-turn:1", "other"); |
| 626 | fx.write("duration.mjs", "export const unit = 's';\n"); |
| 627 | fx.snapshot("pre-turn:1", "s1"); |
| 628 | fx.write("duration.mjs", "export const unit = 'min';\n"); |
| 629 | fx.snapshot("post-turn:1", "s1"); |
| 630 | fx.write("notes.txt", "written after the turn\n"); |
| 631 | let snapshots = fx.repo.list(usize::MAX).unwrap().len(); |
| 632 | |
| 633 | let mut app = fx.app("s1"); |
| 634 | let result = super::execute("/diff", &mut app); |
| 635 | |
| 636 | assert!(!result.is_error, "{:?}", result.message); |
| 637 | let message = result.message.clone().unwrap_or_default(); |
| 638 | assert!( |
| 639 | message.starts_with("Changed files (2):\nduration.mjs\nnotes.txt"), |
| 640 | "{message}" |
| 641 | ); |
| 642 | let Some(AppAction::OpenDiffPager { title, diff }) = result.action else { |
| 643 | panic!("expected the diff pager: {:?}", result.action); |
| 644 | }; |
| 645 | assert_eq!(title, "Changes since session start"); |
| 646 | assert!( |
| 647 | diff.contains("-export const unit = 's';\n+export const unit = 'min';\n"), |
| 648 | "{diff}" |
| 649 | ); |
| 650 | assert!(diff.contains("+written after the turn"), "{diff}"); |
| 651 | assert!(!diff.contains("'ms'"), "another session's edit: {diff}"); |
| 652 | // Reading the diff takes no snapshot and changes no file. |
| 653 | assert_eq!(fx.repo.list(usize::MAX).unwrap().len(), snapshots); |
| 654 | assert_eq!(fx.read("notes.txt"), "written after the turn\n"); |
| 655 | |
| 656 | // A session with no restore point here has nothing to compare against, |
| 657 | // and says so instead of reporting no changes. |
| 658 | let mut fresh = fx.app("s2"); |
| 659 | let result = super::execute("/diff", &mut fresh); |
| 660 | assert_eq!( |
| 661 | result.message.as_deref(), |
| 662 | Some( |
| 663 | "Nothing to compare yet: this session has not saved a restore point here, and this folder is not a git repository." |
| 664 | ) |
| 665 | ); |
| 666 | assert!(result.action.is_none()); |
| 667 | } |
| 668 | |
| 669 | #[test] |
| 670 | fn patch_undo_restores_only_the_paths_the_undone_step_changed() { |
| 671 | let fx = UndoFixture::new(); |
| 672 | fx.write("a.txt", "a0"); |
| 673 | fx.write("b.txt", "b0"); |
| 674 | let messages = fx.record_turn( |
| 675 | "s1", |
| 676 | 1, |
| 677 | "edit a.txt and create new.txt", |
| 678 | &[("a.txt", "a1"), ("new.txt", "created by the turn")], |
| 679 | true, |
| 680 | ); |
| 681 | fx.write("b.txt", "b-user"); |
| 682 | fx.write("mine.txt", "user file"); |
| 683 | let mut app = fx.app("s1"); |
| 684 | push_recorded_turn(&mut app, messages); |
| 685 | let result = patch_undo(&mut app); |
| 686 | assert!(!result.is_error, "{:?}", result.message); |
| 687 | assert_eq!(fx.read("a.txt"), "a0"); |
| 688 | assert!(!fx.workspace.join("new.txt").exists()); |
| 689 | assert_eq!(fx.read("b.txt"), "b-user"); |
| 690 | assert_eq!(fx.read("mine.txt"), "user file"); |
| 691 | let message = result.message.unwrap_or_default(); |
| 692 | assert!( |
| 693 | message.contains("a.txt") && message.contains("new.txt"), |
| 694 | "{message}" |
| 695 | ); |
| 696 | } |
| 697 | |
| 698 | #[test] |
| 699 | fn patch_undo_refuses_when_a_changed_path_changed_since() { |
| 700 | let fx = UndoFixture::new(); |
| 701 | fx.write("a.txt", "a0"); |
| 702 | fx.write("b.txt", "b0"); |
| 703 | let messages = fx.record_turn( |
| 704 | "s1", |
| 705 | 1, |
| 706 | "edit both files", |
| 707 | &[("a.txt", "a1"), ("b.txt", "b1")], |
| 708 | true, |
| 709 | ); |
| 710 | fx.write("a.txt", "a-user"); |
| 711 | let before = fx.repo.list(usize::MAX).unwrap().len(); |
| 712 | let mut app = fx.app("s1"); |
| 713 | push_recorded_turn(&mut app, messages.clone()); |
| 714 | let result = patch_undo(&mut app); |
| 715 | assert!(result.is_error, "{:?}", result.message); |
| 716 | assert_eq!(fx.read("a.txt"), "a-user"); |
| 717 | assert_eq!(fx.read("b.txt"), "b1"); |
| 718 | assert_eq!(app.api_messages.as_ref(), &messages); |
| 719 | assert!(result.action.is_none()); |
| 720 | assert_eq!(fx.repo.list(usize::MAX).unwrap().len(), before); |
| 721 | } |
| 722 | |
| 723 | #[test] |
| 724 | fn undo_range_counts_settled_subagent_writes_for_three_agents_and_refuses_foreign_edits() { |
| 725 | let child_files = [ |
| 726 | "agent_a_1.txt", |
| 727 | "agent_a_2.txt", |
| 728 | "agent_b_1.txt", |
| 729 | "agent_b_2.txt", |
| 730 | "agent_c_1.txt", |
| 731 | "agent_c_2.txt", |
| 732 | ]; |
| 733 | let make_agent_turn = |prompt: &str, call_id: &str| { |
| 734 | vec![ |
| 735 | Message { |
| 736 | role: Role::User, |
| 737 | content: vec![ContentBlock::Text { |
| 738 | text: prompt.to_string(), |
| 739 | cache_control: None, |
| 740 | }], |
| 741 | }, |
| 742 | Message { |
| 743 | role: Role::Assistant, |
| 744 | content: vec![ContentBlock::ToolUse { |
| 745 | execution_id: Some(call_id.to_string()), |
| 746 | id: call_id.to_string(), |
| 747 | name: "agent".to_string(), |
| 748 | input: serde_json::json!({"action": "start"}), |
| 749 | caller: None, |
| 750 | thought_signature: None, |
| 751 | }], |
| 752 | }, |
| 753 | Message { |
| 754 | role: Role::User, |
| 755 | content: vec![ContentBlock::ToolResult { |
| 756 | execution_id: Some(call_id.to_string()), |
| 757 | tool_use_id: call_id.to_string(), |
| 758 | content: "started".to_string(), |
| 759 | is_error: None, |
| 760 | content_blocks: None, |
| 761 | }], |
| 762 | }, |
| 763 | Message { |
| 764 | role: Role::Assistant, |
| 765 | content: vec![ContentBlock::Text { |
| 766 | text: "done".to_string(), |
| 767 | cache_control: None, |
| 768 | }], |
| 769 | }, |
| 770 | ] |
| 771 | }; |
| 772 | |
| 773 | { |
| 774 | let fx = UndoFixture::new(); |
| 775 | for path in child_files { |
| 776 | fx.write(path, "before"); |
| 777 | } |
| 778 | fx.snapshot("pre-turn:1: delegate edit", "s1"); |
| 779 | fx.snapshot("tool:agent-start-1", "s1"); |
| 780 | fx.snapshot("post-tool:agent-start-1", "s1"); |
| 781 | for path in child_files { |
| 782 | fx.write(path, "after"); |
| 783 | } |
| 784 | fx.snapshot("post-turn:1: delegate edit", "s1"); |
| 785 | |
| 786 | let mut app = fx.app("s1"); |
| 787 | push_recorded_turn(&mut app, make_agent_turn("delegate edit", "agent-start-1")); |
| 788 | |
| 789 | let refused_without_attribution = patch_undo(&mut app); |
| 790 | assert!( |
| 791 | refused_without_attribution.is_error, |
| 792 | "{:?}", |
| 793 | refused_without_attribution.message |
| 794 | ); |
| 795 | assert!(refused_without_attribution.action.is_none()); |
| 796 | for path in child_files { |
| 797 | assert_eq!(fx.read(path), "after"); |
| 798 | } |
| 799 | |
| 800 | app.delegated_writes.insert( |
| 801 | ("s1".to_string(), 1), |
| 802 | child_files.iter().map(|path| (*path).to_string()).collect(), |
| 803 | ); |
| 804 | let undone = patch_undo(&mut app); |
| 805 | assert!(!undone.is_error, "{:?}", undone.message); |
| 806 | assert!(matches!( |
| 807 | undone.action, |
| 808 | Some(AppAction::ConversationUndo { .. }) |
| 809 | )); |
| 810 | for path in child_files { |
| 811 | assert_eq!(fx.read(path), "before"); |
| 812 | } |
| 813 | acknowledge_file_undo(&mut app, &undone); |
| 814 | assert!(app.api_messages.is_empty()); |
| 815 | } |
| 816 | |
| 817 | { |
| 818 | let foreign_fx = UndoFixture::new(); |
| 819 | for path in child_files { |
| 820 | foreign_fx.write(path, "before"); |
| 821 | } |
| 822 | foreign_fx.write("editor.txt", "editor-before"); |
| 823 | foreign_fx.snapshot("pre-turn:1: foreign check", "s1"); |
| 824 | foreign_fx.snapshot("tool:agent-start-2", "s1"); |
| 825 | foreign_fx.snapshot("post-tool:agent-start-2", "s1"); |
| 826 | for path in child_files { |
| 827 | foreign_fx.write(path, "after"); |
| 828 | } |
| 829 | foreign_fx.write("editor.txt", "editor-during-turn"); |
| 830 | foreign_fx.snapshot("post-turn:1: foreign check", "s1"); |
| 831 | |
| 832 | let mut foreign_app = foreign_fx.app("s1"); |
| 833 | push_recorded_turn( |
| 834 | &mut foreign_app, |
| 835 | make_agent_turn("foreign check", "agent-start-2"), |
| 836 | ); |
| 837 | foreign_app.delegated_writes.insert( |
| 838 | ("s1".to_string(), 1), |
| 839 | child_files.iter().map(|path| (*path).to_string()).collect(), |
| 840 | ); |
| 841 | let refused = patch_undo(&mut foreign_app); |
| 842 | assert!(refused.is_error, "{:?}", refused.message); |
| 843 | assert!(refused.action.is_none()); |
| 844 | let refusal_message = refused.message.expect("refusal message"); |
| 845 | assert!(refusal_message.contains("editor.txt"), "{refusal_message}"); |
| 846 | for path in child_files { |
| 847 | assert!(!refusal_message.contains(path), "{refusal_message}"); |
| 848 | assert_eq!(foreign_fx.read(path), "after"); |
| 849 | } |
| 850 | assert_eq!(foreign_fx.read("editor.txt"), "editor-during-turn"); |
| 851 | } |
| 852 | } |
| 853 | |
| 854 | #[test] |
| 855 | fn undo_takes_back_a_whole_request_in_one_step_without_trust() { |
| 856 | let fx = UndoFixture::new(); |
| 857 | fx.write("duration.mjs", "v0"); |
| 858 | fx.write("duration.test.mjs", "t0"); |
| 859 | let messages = fx.record_turn( |
| 860 | "s1", |
| 861 | 1, |
| 862 | "Whole hours should read 2h", |
| 863 | &[ |
| 864 | ("duration.mjs", "v1"), |
| 865 | ("duration.test.mjs", "t1"), |
| 866 | ("notes.md", "created by the request"), |
| 867 | ], |
| 868 | true, |
| 869 | ); |
| 870 | let before = fx.repo.list(usize::MAX).unwrap().len(); |
| 871 | let mut app = fx.app("s1"); |
| 872 | push_recorded_turn(&mut app, messages); |
| 873 | let result = patch_undo(&mut app); |
| 874 | assert!(!result.is_error, "{:?}", result.message); |
| 875 | assert_eq!(fx.read("duration.mjs"), "v0"); |
| 876 | assert_eq!(fx.read("duration.test.mjs"), "t0"); |
| 877 | assert!(!fx.workspace.join("notes.md").exists()); |
| 878 | assert!(!app.history.is_empty()); |
| 879 | acknowledge_file_undo(&mut app, &result); |
| 880 | assert!(app.history.is_empty() && app.api_messages.is_empty()); |
| 881 | assert!(!app.trust_mode && !app.yolo); |
| 882 | assert!(fx.repo.list(usize::MAX).unwrap().len() > before); |
| 883 | assert_eq!( |
| 884 | patch_undo(&mut app).message.as_deref(), |
| 885 | Some("Nothing to undo") |
| 886 | ); |
| 887 | assert_eq!(fx.read("duration.mjs"), "v0"); |
| 888 | } |
| 889 | |
| 890 | #[test] |
| 891 | fn undo_cuts_the_conversation_at_the_prompt_not_at_a_tool_result() { |
| 892 | let fx = UndoFixture::new(); |
| 893 | fx.write("a.txt", "a0"); |
| 894 | let messages = fx.record_turn("s1", 2, "edit a.txt", &[("a.txt", "a1")], true); |
| 895 | let mut app = fx.app("s1"); |
| 896 | push_exchange(&mut app, "keep this"); |
| 897 | push_recorded_turn(&mut app, messages); |
| 898 | let original = app.api_messages.as_ref().clone(); |
| 899 | let result = patch_undo(&mut app); |
| 900 | assert!(!result.is_error, "{:?}", result.message); |
| 901 | assert_eq!(fx.read("a.txt"), "a0"); |
| 902 | assert_eq!(app.api_messages.as_ref(), &original); |
| 903 | assert!( |
| 904 | matches!(result.action, Some(AppAction::ConversationUndo { ref sync, .. }) if sync.messages == original[..2]) |
| 905 | ); |
| 906 | } |
| 907 | |
| 908 | #[test] |
| 909 | fn undo_never_reverts_files_of_a_request_the_conversation_still_holds() { |
| 910 | let fx = UndoFixture::new(); |
| 911 | fx.write("a.txt", "a0"); |
| 912 | let first = fx.record_turn("s1", 1, "edit a.txt", &[("a.txt", "a1")], true); |
| 913 | let kept = first.len(); |
| 914 | let second = fx.record_turn("s1", 2, "what did you change?", &[], true); |
| 915 | let mut app = fx.app("s1"); |
| 916 | push_recorded_turn(&mut app, first); |
| 917 | push_recorded_turn(&mut app, second); |
| 918 | let result = patch_undo(&mut app); |
| 919 | assert!(!result.is_error, "{:?}", result.message); |
| 920 | assert_eq!(fx.read("a.txt"), "a1"); |
| 921 | acknowledge_file_undo(&mut app, &result); |
| 922 | assert_eq!(app.api_messages.len(), kept); |
| 923 | let result = patch_undo(&mut app); |
| 924 | assert!(!result.is_error, "{:?}", result.message); |
| 925 | assert_eq!(fx.read("a.txt"), "a0"); |
| 926 | acknowledge_file_undo(&mut app, &result); |
| 927 | assert!(app.api_messages.is_empty()); |
| 928 | } |
| 929 | |
| 930 | fn assert_undo_identity_refused(fx: &UndoFixture, app: &mut App) { |
| 931 | let messages = app.api_messages.as_ref().clone(); |
| 932 | let history = app.history.len(); |
| 933 | let contents = fx.read("a.txt"); |
| 934 | let snapshots: Vec<_> = fx |
| 935 | .repo |
| 936 | .list(usize::MAX) |
| 937 | .unwrap() |
| 938 | .into_iter() |
| 939 | .map(|s| s.id) |
| 940 | .collect(); |
| 941 | let result = patch_undo(app); |
| 942 | assert!(result.is_error, "{:?}", result.message); |
| 943 | assert!(result.action.is_none()); |
| 944 | assert_eq!(app.api_messages.as_ref(), &messages); |
| 945 | assert_eq!(app.history.len(), history); |
| 946 | assert_eq!(fx.read("a.txt"), contents); |
| 947 | assert_eq!( |
| 948 | fx.repo |
| 949 | .list(usize::MAX) |
| 950 | .unwrap() |
| 951 | .into_iter() |
| 952 | .map(|s| s.id) |
| 953 | .collect::<Vec<_>>(), |
| 954 | snapshots |
| 955 | ); |
| 956 | } |
| 957 | |
| 958 | #[test] |
| 959 | fn undo_refuses_repeated_requests_with_missing_current_execution_receipts() { |
| 960 | let fx = UndoFixture::new(); |
| 961 | fx.write("a.txt", "a0"); |
| 962 | let mut current = fx.record_turn("s1", 1, "continue", &[("a.txt", "a2")], true); |
| 963 | fx.write("a.txt", "a-user"); |
| 964 | fx.write("a.txt", "a2"); |
| 965 | for message in &mut current { |
| 966 | for block in &mut message.content { |
| 967 | match block { |
| 968 | ContentBlock::ToolUse { execution_id, .. } |
| 969 | | ContentBlock::ToolResult { execution_id, .. } => { |
| 970 | *execution_id = Some("fresh-execution-with-no-restore-point".into()) |
| 971 | } |
| 972 | _ => {} |
| 973 | } |
| 974 | } |
| 975 | } |
| 976 | let mut app = fx.app("s1"); |
| 977 | push_recorded_turn(&mut app, current); |
| 978 | assert_undo_identity_refused(&fx, &mut app); |
| 979 | } |
| 980 | |
| 981 | #[test] |
| 982 | fn undo_matches_execution_identity_with_lossy_shared_prefix_and_first_line_labels() { |
| 983 | let prefix = "x".repeat(100); |
| 984 | for (first, second) in [ |
| 985 | (format!("{prefix} first"), format!("{prefix} second")), |
| 986 | ( |
| 987 | "edit a.txt\nfirst change".into(), |
| 988 | "edit a.txt\nsecond change".into(), |
| 989 | ), |
| 990 | ] { |
| 991 | let fx = UndoFixture::new(); |
| 992 | fx.write("a.txt", "a0"); |
| 993 | let first = fx.record_turn("s1", 1, &first, &[("a.txt", "a1")], true); |
| 994 | let second = fx.record_turn("s1", 2, &second, &[("a.txt", "a2")], true); |
| 995 | let mut app = fx.app("s1"); |
| 996 | push_recorded_turn(&mut app, first); |
| 997 | push_recorded_turn(&mut app, second); |
| 998 | let result = patch_undo(&mut app); |
| 999 | assert!(!result.is_error, "{:?}", result.message); |
| 1000 | assert_eq!(fx.read("a.txt"), "a1"); |
| 1001 | acknowledge_file_undo(&mut app, &result); |
| 1002 | let result = patch_undo(&mut app); |
| 1003 | assert!(!result.is_error, "{:?}", result.message); |
| 1004 | assert_eq!(fx.read("a.txt"), "a0"); |
| 1005 | } |
| 1006 | } |
| 1007 | |
| 1008 | #[test] |
| 1009 | fn undo_matches_unique_truncated_and_multiline_prompt_snippets() { |
| 1010 | for prompt in [ |
| 1011 | "x".repeat(101), |
| 1012 | "edit a.txt\nwith a second line".into(), |
| 1013 | "edit a.txt \nwith trailing whitespace".into(), |
| 1014 | "\nwith an empty first line".into(), |
| 1015 | ] { |
| 1016 | let fx = UndoFixture::new(); |
| 1017 | fx.write("a.txt", "a0"); |
| 1018 | let first = fx.record_turn("s1", 1, &prompt, &[("a.txt", "a1")], true); |
| 1019 | let first_count = first.len(); |
| 1020 | let second = fx.record_turn("s1", 2, "update a.txt again", &[("a.txt", "a2")], true); |
| 1021 | let total = first_count + second.len(); |
| 1022 | let mut app = fx.app("s1"); |
| 1023 | push_recorded_turn(&mut app, first); |
| 1024 | push_recorded_turn(&mut app, second); |
| 1025 | app.session_turn_outcomes = vec![ |
| 1026 | codewhale_engine::session_manager::SavedTurnOutcome::failed( |
| 1027 | "first failure", |
| 1028 | first_count, |
| 1029 | ), |
| 1030 | codewhale_engine::session_manager::SavedTurnOutcome::failed("second failure", total), |
| 1031 | ]; |
| 1032 | let result = patch_undo(&mut app); |
| 1033 | assert!(!result.is_error, "{:?}", result.message); |
| 1034 | assert_eq!(fx.read("a.txt"), "a1"); |
| 1035 | acknowledge_file_undo(&mut app, &result); |
| 1036 | assert_eq!(app.history.len(), 2); |
| 1037 | assert_eq!(app.api_messages.len(), first_count); |
| 1038 | assert_eq!(app.session_turn_outcomes.len(), 1); |
| 1039 | assert_eq!(app.session_turn_outcomes[0].error, "first failure"); |
| 1040 | if prompt.starts_with('\n') { |
| 1041 | assert_undo_identity_refused(&fx, &mut app); |
| 1042 | assert_eq!(fx.read("a.txt"), "a1"); |
| 1043 | assert_eq!(app.session_turn_outcomes.len(), 1); |
| 1044 | assert_eq!(app.session_turn_outcomes[0].error, "first failure"); |
| 1045 | continue; |
| 1046 | } |
| 1047 | let result = patch_undo(&mut app); |
| 1048 | assert!(!result.is_error, "{:?}", result.message); |
| 1049 | assert_eq!(fx.read("a.txt"), "a0"); |
| 1050 | acknowledge_file_undo(&mut app, &result); |
| 1051 | assert!(app.history.is_empty() && app.api_messages.is_empty()); |
| 1052 | assert!(app.session_turn_outcomes.is_empty()); |
| 1053 | } |
| 1054 | } |
| 1055 | |
| 1056 | #[test] |
| 1057 | fn undo_refuses_missing_or_legacy_execution_identity_for_multipart_requests() { |
| 1058 | for kind in 0..4 { |
| 1059 | let fx = UndoFixture::new(); |
| 1060 | fx.write("a.txt", "a0"); |
| 1061 | let mut messages = fx.record_turn("s1", 1, "edit a.txt", &[("a.txt", "a1")], true); |
| 1062 | for message in &mut messages { |
| 1063 | for block in &mut message.content { |
| 1064 | if let ContentBlock::ToolUse { execution_id, .. } = block { |
| 1065 | *execution_id = if kind == 0 { None } else { Some(String::new()) }; |
| 1066 | } |
| 1067 | } |
| 1068 | } |
| 1069 | if kind > 0 { |
| 1070 | messages[0].content.push(if kind == 3 { |
| 1071 | ContentBlock::Text { |
| 1072 | text: "second instruction".into(), |
| 1073 | cache_control: None, |
| 1074 | } |
| 1075 | } else { |
| 1076 | ContentBlock::ImageUrl { |
| 1077 | image_url: codewhale_models::ImageUrlContent { |
| 1078 | url: "data:image/png;base64,AAAA".into(), |
| 1079 | }, |
| 1080 | } |
| 1081 | }); |
| 1082 | } |
| 1083 | let mut app = fx.app("s1"); |
| 1084 | push_recorded_turn(&mut app, messages); |
| 1085 | assert_undo_identity_refused(&fx, &mut app); |
| 1086 | } |
| 1087 | } |
| 1088 | |
| 1089 | #[test] |
| 1090 | fn undo_identity_guard_includes_history_only_requests() { |
| 1091 | let fx = UndoFixture::new(); |
| 1092 | fx.write("a.txt", "a0"); |
| 1093 | fx.record_turn("s1", 1, "continue", &[("a.txt", "a1")], true); |
| 1094 | let mut app = fx.app("s1"); |
| 1095 | for _ in 0..2 { |
| 1096 | app.history.push(HistoryCell::User { |
| 1097 | content: "continue".into(), |
| 1098 | }); |
| 1099 | } |
| 1100 | assert_undo_identity_refused(&fx, &mut app); |
| 1101 | } |
| 1102 | |
| 1103 | #[test] |
| 1104 | fn undo_keeps_lossless_hundred_character_unicode_prompts_available() { |
| 1105 | let fx = UndoFixture::new(); |
| 1106 | fx.write("a.txt", "a0"); |
| 1107 | let messages = fx.record_turn("s1", 1, &"漢".repeat(100), &[("a.txt", "a1")], true); |
| 1108 | let mut app = fx.app("s1"); |
| 1109 | push_recorded_turn(&mut app, messages); |
| 1110 | let result = patch_undo(&mut app); |
| 1111 | assert!(!result.is_error, "{:?}", result.message); |
| 1112 | assert_eq!(fx.read("a.txt"), "a0"); |
| 1113 | acknowledge_file_undo(&mut app, &result); |
| 1114 | assert!(app.history.is_empty() && app.api_messages.is_empty()); |
| 1115 | } |
| 1116 | |
| 1117 | #[test] |
| 1118 | fn undo_takes_a_newer_request_off_before_refusing_an_older_one() { |
| 1119 | let fx = UndoFixture::new(); |
| 1120 | fx.write("a.txt", "a0"); |
| 1121 | let first = fx.record_turn("s1", 1, "edit a.txt", &[("a.txt", "a1")], true); |
| 1122 | let kept = first.len(); |
| 1123 | let second = fx.record_turn("s1", 2, "why?", &[], true); |
| 1124 | fx.write("a.txt", "a-user"); |
| 1125 | let before = fx.repo.list(usize::MAX).unwrap().len(); |
| 1126 | let mut app = fx.app("s1"); |
| 1127 | push_recorded_turn(&mut app, first); |
| 1128 | push_recorded_turn(&mut app, second); |
| 1129 | let result = patch_undo(&mut app); |
| 1130 | assert!(!result.is_error, "{:?}", result.message); |
| 1131 | acknowledge_file_undo(&mut app, &result); |
| 1132 | assert_eq!(app.api_messages.len(), kept); |
| 1133 | let result = patch_undo(&mut app); |
| 1134 | assert!(result.is_error, "{:?}", result.message); |
| 1135 | assert!(result.action.is_none()); |
| 1136 | assert_eq!(fx.read("a.txt"), "a-user"); |
| 1137 | assert_eq!(app.api_messages.len(), kept); |
| 1138 | assert_eq!(app.history.len(), 2); |
| 1139 | assert_eq!(fx.repo.list(usize::MAX).unwrap().len(), before); |
| 1140 | } |
| 1141 | |
| 1142 | #[test] |
| 1143 | fn undo_refuses_an_unmatched_restore_point_after_a_partial_conversation_rewind() { |
| 1144 | let fx = UndoFixture::new(); |
| 1145 | fx.write("a.txt", "a0"); |
| 1146 | let first = fx.record_turn("s1", 1, "say hello", &[], true); |
| 1147 | fx.record_turn("s1", 2, "edit a.txt", &[("a.txt", "a1")], true); |
| 1148 | let mut app = fx.app("s1"); |
| 1149 | push_recorded_turn(&mut app, first); |
| 1150 | let result = patch_undo(&mut app); |
| 1151 | assert!(!result.is_error, "{:?}", result.message); |
| 1152 | assert_eq!(fx.read("a.txt"), "a1"); |
| 1153 | acknowledge_file_undo(&mut app, &result); |
| 1154 | assert!(app.api_messages.is_empty()); |
| 1155 | } |
| 1156 | |
| 1157 | #[test] |
| 1158 | fn undo_after_a_full_conversation_rewind_keeps_unbound_files() { |
| 1159 | let fx = UndoFixture::new(); |
| 1160 | fx.write("a.txt", "a0"); |
| 1161 | fx.record_turn("s1", 1, "edit a.txt", &[("a.txt", "a1")], true); |
| 1162 | let mut app = fx.app("s1"); |
| 1163 | let before = fx.repo.list(usize::MAX).unwrap().len(); |
| 1164 | let result = patch_undo(&mut app); |
| 1165 | assert_eq!(result.message.as_deref(), Some("Nothing to undo")); |
| 1166 | assert_eq!(fx.read("a.txt"), "a1"); |
| 1167 | assert!(app.api_messages.is_empty() && app.history.is_empty()); |
| 1168 | assert_eq!(fx.repo.list(usize::MAX).unwrap().len(), before); |
| 1169 | } |
| 1170 | |
| 1171 | #[test] |
| 1172 | fn undo_of_a_request_without_a_recorded_end_is_refused_even_when_forced() { |
| 1173 | let fx = UndoFixture::new(); |
| 1174 | fx.write("a.txt", "a0"); |
| 1175 | let messages = fx.record_turn("s1", 1, "edit a.txt", &[("a.txt", "a1")], false); |
| 1176 | let before = fx.repo.list(usize::MAX).unwrap().len(); |
| 1177 | let mut app = fx.app("s1"); |
| 1178 | push_recorded_turn(&mut app, messages); |
| 1179 | for (trust, yolo) in [(false, false), (true, false), (false, true)] { |
| 1180 | app.trust_mode = trust; |
| 1181 | app.yolo = yolo; |
| 1182 | for command in ["/undo", "/undo force"] { |
| 1183 | let staged = super::execute(command, &mut app); |
| 1184 | assert!(matches!( |
| 1185 | staged.action, |
| 1186 | Some(AppAction::UndoLatestRequest { .. }) |
| 1187 | )); |
| 1188 | assert_undo_identity_refused(&fx, &mut app); |
| 1189 | } |
| 1190 | } |
| 1191 | assert_eq!(fx.read("a.txt"), "a1"); |
| 1192 | assert_eq!(fx.repo.list(usize::MAX).unwrap().len(), before); |
| 1193 | } |
| 1194 | |
| 1195 | #[test] |
| 1196 | fn undo_keeps_an_edit_the_user_made_after_an_unfinished_request() { |
| 1197 | let fx = UndoFixture::new(); |
| 1198 | fx.write("a.txt", "a0"); |
| 1199 | fx.write("mine.txt", "m0"); |
| 1200 | let first = fx.record_turn("s1", 1, "edit a.txt", &[("a.txt", "a1")], false); |
| 1201 | fx.write("mine.txt", "m-user"); |
| 1202 | let second = fx.record_turn("s1", 2, "edit c.txt", &[("c.txt", "c1")], true); |
| 1203 | let mut app = fx.app("s1"); |
| 1204 | push_recorded_turn(&mut app, first); |
| 1205 | push_recorded_turn(&mut app, second); |
| 1206 | let result = patch_undo(&mut app); |
| 1207 | assert!(!result.is_error, "{:?}", result.message); |
| 1208 | assert!(!fx.workspace.join("c.txt").exists()); |
| 1209 | acknowledge_file_undo(&mut app, &result); |
| 1210 | assert_undo_identity_refused(&fx, &mut app); |
| 1211 | assert_eq!(fx.read("mine.txt"), "m-user"); |
| 1212 | assert_eq!(fx.read("a.txt"), "a1"); |
| 1213 | } |
| 1214 | |
| 1215 | #[test] |
| 1216 | fn patch_undo_finds_restore_points_beyond_the_newest_hundred_snapshots() { |
| 1217 | let fx = UndoFixture::new(); |
| 1218 | fx.write("a.txt", "a0"); |
| 1219 | let messages = fx.record_turn("s1", 1, "edit a.txt", &[("a.txt", "a1")], true); |
| 1220 | for i in 0..101 { |
| 1221 | fx.snapshot(&format!("tool:other-{i}"), "other-session"); |
| 1222 | } |
| 1223 | let mut app = fx.app("s1"); |
| 1224 | push_recorded_turn(&mut app, messages); |
| 1225 | let result = patch_undo(&mut app); |
| 1226 | assert!(!result.is_error, "{:?}", result.message); |
| 1227 | assert_eq!(fx.read("a.txt"), "a0"); |
| 1228 | } |
| 1229 | |
| 1230 | #[test] |
| 1231 | fn patch_undo_restores_turns_a_fork_inherited() { |
| 1232 | let fx = UndoFixture::new(); |
| 1233 | fx.write("a.txt", "a0"); |
| 1234 | let messages = fx.record_turn("source", 1, "edit a.txt", &[("a.txt", "a1")], true); |
| 1235 | let fork = |created_at: chrono::DateTime<chrono::Utc>| { |
| 1236 | let mut app = fx.app("fork"); |
| 1237 | let mut metadata = codewhale_engine::session_manager::create_saved_session( |
| 1238 | &[], |
| 1239 | "model", |
| 1240 | &fx.workspace, |
| 1241 | 0, |
| 1242 | None, |
| 1243 | ) |
| 1244 | .metadata; |
| 1245 | metadata.id = "fork".into(); |
| 1246 | metadata.parent_session_id = Some("source".into()); |
| 1247 | metadata.created_at = created_at; |
| 1248 | app.current_session_metadata = Some(metadata); |
| 1249 | push_recorded_turn(&mut app, messages.clone()); |
| 1250 | app |
| 1251 | }; |
| 1252 | let mut early = fork(chrono::Utc::now() - chrono::Duration::hours(1)); |
| 1253 | let refused = patch_undo(&mut early); |
| 1254 | assert!(refused.is_error, "{:?}", refused.message); |
| 1255 | assert_eq!(fx.read("a.txt"), "a1"); |
| 1256 | let mut app = fork(chrono::Utc::now() + chrono::Duration::seconds(5)); |
| 1257 | let result = patch_undo(&mut app); |
| 1258 | assert!(!result.is_error, "{:?}", result.message); |
| 1259 | assert_eq!(fx.read("a.txt"), "a0"); |
| 1260 | } |
| 1261 | |
| 1262 | #[test] |
| 1263 | fn patch_undo_waits_for_a_pending_post_turn_snapshot() { |
| 1264 | let fx = UndoFixture::new(); |
| 1265 | fx.write("a.txt", "a0"); |
| 1266 | let messages = fx.record_turn("s1", 1, "edit a.txt", &[("a.txt", "a1")], false); |
| 1267 | let pending = codewhale_snapshot::PendingPostTurnSnapshot::reserve(); |
| 1268 | let repo = codewhale_snapshot::SnapshotRepo::open_or_init(&fx.workspace).unwrap(); |
| 1269 | let writer = std::thread::spawn(move || { |
| 1270 | std::thread::sleep(std::time::Duration::from_millis(500)); |
| 1271 | let taken = repo |
| 1272 | .take_snapshot("post-turn:1: edit a.txt", Some("s1")) |
| 1273 | .unwrap(); |
| 1274 | drop(pending); |
| 1275 | taken |
| 1276 | }); |
| 1277 | let mut app = fx.app("s1"); |
| 1278 | push_recorded_turn(&mut app, messages); |
| 1279 | let result = patch_undo(&mut app); |
| 1280 | let post_turn = writer.join().unwrap(); |
| 1281 | assert!(!result.is_error, "{:?}", result.message); |
| 1282 | assert_eq!(fx.read("a.txt"), "a0"); |
| 1283 | let closed = fx |
| 1284 | .repo |
| 1285 | .list(usize::MAX) |
| 1286 | .unwrap() |
| 1287 | .into_iter() |
| 1288 | .find(|snapshot| snapshot.label.starts_with("post-tool:")) |
| 1289 | .unwrap(); |
| 1290 | assert!( |
| 1291 | fx.repo |
| 1292 | .changed_paths_between(&closed.tree, &post_turn.tree) |
| 1293 | .unwrap() |
| 1294 | .is_empty() |
| 1295 | ); |
| 1296 | } |
| 1297 | |
| 1298 | #[cfg(unix)] |
| 1299 | #[test] |
| 1300 | fn patch_undo_refuses_non_regular_paths_without_mutating_older_steps() { |
| 1301 | let fx = UndoFixture::new(); |
| 1302 | fx.write("a.txt", "a0"); |
| 1303 | let first = fx.record_turn("s1", 1, "first edit", &[("a.txt", "a1")], true); |
| 1304 | fx.snapshot("pre-turn:2: second edit", "s1"); |
| 1305 | let id = uuid::Uuid::new_v4().to_string(); |
| 1306 | fx.snapshot(&format!("tool:{id}"), "s1"); |
| 1307 | fx.write("a.txt", "a2"); |
| 1308 | std::os::unix::fs::symlink("a.txt", fx.workspace.join("current")).unwrap(); |
| 1309 | fx.snapshot(&format!("post-tool:{id}"), "s1"); |
| 1310 | fx.snapshot("post-turn:2: second edit", "s1"); |
| 1311 | let mut second = vec![ |
| 1312 | Message { |
| 1313 | role: Role::User, |
| 1314 | content: vec![ContentBlock::Text { |
| 1315 | text: "second edit".into(), |
| 1316 | cache_control: None, |
| 1317 | }], |
| 1318 | }, |
| 1319 | fixture_call(&id, "a.txt", "a2"), |
| 1320 | Message { |
| 1321 | role: Role::Assistant, |
| 1322 | content: vec![ContentBlock::Text { |
| 1323 | text: "done".into(), |
| 1324 | cache_control: None, |
| 1325 | }], |
| 1326 | }, |
| 1327 | ]; |
| 1328 | if let ContentBlock::ToolUse { name, input, .. } = &mut second[1].content[0] { |
| 1329 | *name = "bash".into(); |
| 1330 | *input = serde_json::json!({"command":"fixture writes a.txt and symlink"}); |
| 1331 | } |
| 1332 | let mut app = fx.app("s1"); |
| 1333 | push_recorded_turn(&mut app, first); |
| 1334 | push_recorded_turn(&mut app, second); |
| 1335 | let before = fx.repo.list(usize::MAX).unwrap().len(); |
| 1336 | let result = patch_undo(&mut app); |
| 1337 | assert!(result.is_error, "{:?}", result.message); |
| 1338 | assert_eq!(fx.read("a.txt"), "a2"); |
| 1339 | assert!( |
| 1340 | std::fs::symlink_metadata(fx.workspace.join("current")) |
| 1341 | .unwrap() |
| 1342 | .file_type() |
| 1343 | .is_symlink() |
| 1344 | ); |
| 1345 | assert_eq!(fx.repo.list(usize::MAX).unwrap().len(), before); |
| 1346 | } |
| 1347 | |
| 1348 | #[test] |
| 1349 | fn receipts_command_is_registered_and_reads_the_transcript() { |
| 1350 | assert_eq!( |
| 1351 | crate::commands::get_command_info("receipts").map(|info| info.name), |
| 1352 | Some("receipts") |
| 1353 | ); |
| 1354 | assert_eq!( |
| 1355 | crate::commands::get_command_info("receipt").map(|info| info.name), |
| 1356 | Some("receipts") |
| 1357 | ); |
| 1358 | let mut app = create_test_app(); |
| 1359 | app.current_session_id = None; |
| 1360 | let empty = crate::commands::execute("/receipts", &mut app); |
| 1361 | assert!(!empty.is_error, "{:?}", empty.message); |
| 1362 | assert!( |
| 1363 | empty |
| 1364 | .message |
| 1365 | .as_deref() |
| 1366 | .is_some_and(|text| text.contains("No actions recorded.")), |
| 1367 | "{:?}", |
| 1368 | empty.message |
| 1369 | ); |
| 1370 | |
| 1371 | app.api_messages_mut().push(Message { |
| 1372 | role: Role::User, |
| 1373 | content: vec![ContentBlock::Text { |
| 1374 | text: "run the tests".to_string(), |
| 1375 | cache_control: None, |
| 1376 | }], |
| 1377 | }); |
| 1378 | app.api_messages_mut().push(Message { |
| 1379 | role: Role::Assistant, |
| 1380 | content: vec![ContentBlock::ToolUse { |
| 1381 | execution_id: None, |
| 1382 | id: "call-1".to_string(), |
| 1383 | name: "bash".to_string(), |
| 1384 | input: serde_json::json!({"command": "cargo test"}), |
| 1385 | caller: None, |
| 1386 | thought_signature: None, |
| 1387 | }], |
| 1388 | }); |
| 1389 | app.api_messages_mut().push(Message { |
| 1390 | role: Role::User, |
| 1391 | content: vec![ContentBlock::ToolResult { |
| 1392 | execution_id: None, |
| 1393 | tool_use_id: "call-1".to_string(), |
| 1394 | content: "ok".to_string(), |
| 1395 | is_error: None, |
| 1396 | content_blocks: None, |
| 1397 | }], |
| 1398 | }); |
| 1399 | let listed = crate::commands::execute("/receipts", &mut app); |
| 1400 | let text = listed.message.expect("receipt text"); |
| 1401 | assert!(text.contains("Ran 1 command"), "{text}"); |
| 1402 | assert!(text.contains("1. ran `cargo test`"), "{text}"); |
| 1403 | |
| 1404 | // `$`, `*`, and `_` in a command must reach the note cell as JSON, not |
| 1405 | // as math or emphasis. |
| 1406 | let shell = r#"echo "$HOME" && echo $PATH *_x_*"#; |
| 1407 | app.api_messages_mut().push(Message { |
| 1408 | role: Role::Assistant, |
| 1409 | content: vec![ContentBlock::ToolUse { |
| 1410 | execution_id: None, |
| 1411 | id: "call-2".to_string(), |
| 1412 | name: "bash".to_string(), |
| 1413 | input: serde_json::json!({ "command": shell }), |
| 1414 | caller: None, |
| 1415 | thought_signature: None, |
| 1416 | }], |
| 1417 | }); |
| 1418 | app.api_messages_mut().push(Message { |
| 1419 | role: Role::User, |
| 1420 | content: vec![ContentBlock::ToolResult { |
| 1421 | execution_id: None, |
| 1422 | tool_use_id: "call-2".to_string(), |
| 1423 | content: "ok".to_string(), |
| 1424 | is_error: None, |
| 1425 | content_blocks: None, |
| 1426 | }], |
| 1427 | }); |
| 1428 | let json = crate::commands::execute("/receipts json", &mut app); |
| 1429 | let fenced = json.message.expect("json"); |
| 1430 | let body = fenced |
| 1431 | .strip_prefix("```json\n") |
| 1432 | .and_then(|rest| rest.strip_suffix("\n```")) |
| 1433 | .expect("the JSON is fenced"); |
| 1434 | let value: serde_json::Value = serde_json::from_str(body).expect("valid json"); |
| 1435 | assert_eq!(value["totals"]["commands"], 2); |
| 1436 | let rendered: String = HistoryCell::System { content: fenced } |
| 1437 | .lines(400) |
| 1438 | .iter() |
| 1439 | .map(|line| { |
| 1440 | line.spans |
| 1441 | .iter() |
| 1442 | .map(|span| span.content.as_ref()) |
| 1443 | .collect::<String>() |
| 1444 | }) |
| 1445 | .collect::<Vec<_>>() |
| 1446 | .join("\n"); |
| 1447 | assert!( |
| 1448 | rendered.contains(r#""command": "echo \"$HOME\" && echo $PATH *_x_*""#), |
| 1449 | "{rendered}" |
| 1450 | ); |
| 1451 | let bad = crate::commands::execute("/receipts nope", &mut app); |
| 1452 | assert!(bad.is_error); |
| 1453 | } |
| 1454 | |
| 1455 | #[test] |
| 1456 | fn whole_debug_registry_matches_portable_inventory_and_exact_host_authority() { |
| 1457 | use codewhale_command_contract::handler::{ |
| 1458 | CommandCapabilities as Caps, CommandHandler, ContextParts, |
| 1459 | }; |
| 1460 | let mut app = create_test_app(); |
| 1461 | let portable = codewhale_commands::debug::portable_handlers(); |
| 1462 | assert_eq!(portable.len(), 14); |
| 1463 | for (info, portable_handler) in portable { |
| 1464 | for spelling in std::iter::once(info.name).chain(info.aliases.iter().copied()) { |
| 1465 | let registered = super::registry() |
| 1466 | .get(spelling) |
| 1467 | .expect("registered debug command"); |
| 1468 | assert_eq!(registered.info().name, info.name); |
| 1469 | assert_eq!(registered.info().aliases, info.aliases); |
| 1470 | assert_eq!(registered.info().usage, info.usage); |
| 1471 | let handler = registered |
| 1472 | .contextual_handler() |
| 1473 | .expect("portable host registration"); |
| 1474 | match (portable_handler.clone(), handler) { |
| 1475 | (CommandHandler::Pure(_), CommandHandler::Pure(_)) => { |
| 1476 | assert_eq!(info.name, "preview-request") |
| 1477 | } |
| 1478 | ( |
| 1479 | CommandHandler::Contextual { |
| 1480 | capabilities: expected, |
| 1481 | .. |
| 1482 | }, |
| 1483 | CommandHandler::Contextual { capabilities, .. }, |
| 1484 | ) => { |
| 1485 | assert_eq!(capabilities, expected, "/{spelling}"); |
| 1486 | let mut bundle = app.command_contexts(); |
| 1487 | let ContextParts { |
| 1488 | session, |
| 1489 | model, |
| 1490 | cost, |
| 1491 | mode_policy, |
| 1492 | system_prompt, |
| 1493 | skills, |
| 1494 | workspace, |
| 1495 | presentation, |
| 1496 | media, |
| 1497 | memory, |
| 1498 | project, |
| 1499 | skill_group, |
| 1500 | plugin, |
| 1501 | lifecycle, |
| 1502 | control, |
| 1503 | export, |
| 1504 | structcopy, |
| 1505 | debug_diagnostics, |
| 1506 | debug_receipts, |
| 1507 | debug_change, |
| 1508 | debug_history, |
| 1509 | debug_diff, |
| 1510 | debug_undo, |
| 1511 | permissions, |
| 1512 | config_status, |
| 1513 | config, |
| 1514 | pet, |
| 1515 | trust, |
| 1516 | login, |
| 1517 | work_surface, |
| 1518 | navigation, |
| 1519 | voice_input, |
| 1520 | } = bundle.contexts(capabilities).into_parts(); |
| 1521 | assert!( |
| 1522 | permissions.is_none() |
| 1523 | && config_status.is_none() |
| 1524 | && config.is_none() |
| 1525 | && pet.is_none() |
| 1526 | && trust.is_none() |
| 1527 | && login.is_none() |
| 1528 | && work_surface.is_none() |
| 1529 | && navigation.is_none() |
| 1530 | && voice_input.is_none() |
| 1531 | ); |
| 1532 | for (name, present, capability) in [ |
| 1533 | ("session", session.is_some(), Caps::SESSION), |
| 1534 | ("model", model.is_some(), Caps::MODEL), |
| 1535 | ("cost", cost.is_some(), Caps::COST), |
| 1536 | ("mode_policy", mode_policy.is_some(), Caps::MODE_POLICY), |
| 1537 | ( |
| 1538 | "system_prompt", |
| 1539 | system_prompt.is_some(), |
| 1540 | Caps::SYSTEM_PROMPT, |
| 1541 | ), |
| 1542 | ("skills", skills.is_some(), Caps::SKILLS), |
| 1543 | ("workspace", workspace.is_some(), Caps::WORKSPACE), |
| 1544 | ("presentation", presentation.is_some(), Caps::PRESENTATION), |
| 1545 | ("media", media.is_some(), Caps::MEDIA), |
| 1546 | ("memory", memory.is_some(), Caps::MEMORY), |
| 1547 | ("project", project.is_some(), Caps::PROJECT), |
| 1548 | ("skill_group", skill_group.is_some(), Caps::SKILL_GROUP), |
| 1549 | ("plugin", plugin.is_some(), Caps::PLUGIN), |
| 1550 | ("lifecycle", lifecycle.is_some(), Caps::SESSION_LIFECYCLE), |
| 1551 | ("control", control.is_some(), Caps::SESSION_CONTROL), |
| 1552 | ("export", export.is_some(), Caps::SESSION_EXPORT), |
| 1553 | ("structcopy", structcopy.is_some(), Caps::SESSION_STRUCTCOPY), |
| 1554 | ( |
| 1555 | "debug_diagnostics", |
| 1556 | debug_diagnostics.is_some(), |
| 1557 | Caps::DEBUG_DIAGNOSTICS, |
| 1558 | ), |
| 1559 | ( |
| 1560 | "debug_receipts", |
| 1561 | debug_receipts.is_some(), |
| 1562 | Caps::DEBUG_RECEIPTS, |
| 1563 | ), |
| 1564 | ("debug_change", debug_change.is_some(), Caps::DEBUG_CHANGE), |
| 1565 | ( |
| 1566 | "debug_history", |
| 1567 | debug_history.is_some(), |
| 1568 | Caps::DEBUG_HISTORY, |
| 1569 | ), |
| 1570 | ("debug_diff", debug_diff.is_some(), Caps::DEBUG_DIFF), |
| 1571 | ("debug_undo", debug_undo.is_some(), Caps::DEBUG_UNDO), |
| 1572 | ] { |
| 1573 | assert_eq!( |
| 1574 | present, |
| 1575 | capabilities.contains(capability), |
| 1576 | "/{spelling}: {name}" |
| 1577 | ); |
| 1578 | } |
| 1579 | } |
| 1580 | _ => panic!("host changed /{spelling} handler shape"), |
| 1581 | } |
| 1582 | } |
| 1583 | } |
| 1584 | } |
| 1585 |