| 1 | //! Gherkin acceptance coverage for session command workflows. |
| 2 | |
| 3 | use std::path::PathBuf; |
| 4 | |
| 5 | use chrono::{Duration as ChronoDuration, Utc}; |
| 6 | use cucumber::{World as _, given, then, when, writer::Stats as _}; |
| 7 | use tempfile::TempDir; |
| 8 | |
| 9 | use crate::commands::{self, CommandResult}; |
| 10 | use crate::test_support::{EnvVarGuard, lock_test_env}; |
| 11 | use crate::tui::app::{App, AppAction, TuiOptions}; |
| 12 | use crate::tui::history::HistoryCell; |
| 13 | use crate::tui::views::ModalKind; |
| 14 | use codewhale_engine::session_manager::{ |
| 15 | SavedSession, SessionManager, create_saved_session_with_id_and_mode, |
| 16 | }; |
| 17 | use codewhale_models::{ContentBlock, Message, Role}; |
| 18 | use codewhale_runtime::config::Config; |
| 19 | |
| 20 | const FEATURE_NAME: &str = "Session command workflows"; |
| 21 | const FEATURE_PATH: &str = concat!( |
| 22 | env!("CARGO_MANIFEST_DIR"), |
| 23 | "/tests/features/session_command_workflows.feature" |
| 24 | ); |
| 25 | const SAVE_LOAD_SCENARIO: &str = "Save and export preserve data while load defers restoration"; |
| 26 | const FORK_RESUMABLE_SCENARIO: &str = "Fork keeps the original session resumable"; |
| 27 | const NEW_THEN_FORK_SCENARIO: &str = "New session cannot be forked before messages exist"; |
| 28 | const CLEAR_THEN_FORK_SCENARIO: &str = "Cleared session cannot be forked before messages exist"; |
| 29 | const FORK_THEN_NEW_SCENARIO: &str = "Fork followed by new keeps both saved sessions"; |
| 30 | const FORK_THEN_CLEAR_SCENARIO: &str = "Fork followed by clear keeps both saved sessions"; |
| 31 | const RENAME_SCENARIO: &str = "Rename updates the active saved session title"; |
| 32 | const SESSIONS_LIST_SCENARIO: &str = "Sessions list opens the saved session picker"; |
| 33 | const SESSIONS_PRUNE_SCENARIO: &str = "Sessions prune removes only stale sessions"; |
| 34 | const CONTEXT_MANAGEMENT_SCENARIO: &str = |
| 35 | "Context management commands emit actions without clearing the active session"; |
| 36 | const SINGULAR_SESSION_SCENARIO: &str = "Singular session command is not registered"; |
| 37 | |
| 38 | #[derive(Default, cucumber::World)] |
| 39 | struct SessionCommandWorld { |
| 40 | tmpdir: Option<TempDir>, |
| 41 | app: Option<Box<App>>, |
| 42 | save_path: Option<PathBuf>, |
| 43 | export_path: Option<PathBuf>, |
| 44 | home_path: Option<PathBuf>, |
| 45 | original_session_id: Option<String>, |
| 46 | fork_session_id: Option<String>, |
| 47 | new_session_id: Option<String>, |
| 48 | fresh_session_id: Option<String>, |
| 49 | stale_session_id: Option<String>, |
| 50 | last_message: Option<String>, |
| 51 | last_result_is_error: Option<bool>, |
| 52 | last_action: Option<AppAction>, |
| 53 | } |
| 54 | |
| 55 | impl std::fmt::Debug for SessionCommandWorld { |
| 56 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 57 | f.debug_struct("SessionCommandWorld") |
| 58 | .field("has_tmpdir", &self.tmpdir.is_some()) |
| 59 | .field("has_app", &self.app.is_some()) |
| 60 | .field("save_path", &self.save_path) |
| 61 | .field("export_path", &self.export_path) |
| 62 | .field("home_path", &self.home_path) |
| 63 | .field("original_session_id", &self.original_session_id) |
| 64 | .field("fork_session_id", &self.fork_session_id) |
| 65 | .field("new_session_id", &self.new_session_id) |
| 66 | .field("fresh_session_id", &self.fresh_session_id) |
| 67 | .field("stale_session_id", &self.stale_session_id) |
| 68 | .field("last_message", &self.last_message) |
| 69 | .field("last_result_is_error", &self.last_result_is_error) |
| 70 | .finish() |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | #[given("a CodeWhale session workspace with one user message")] |
| 75 | fn workspace_with_one_user_message(world: &mut SessionCommandWorld) { |
| 76 | let tmpdir = TempDir::new().expect("session workflow TempDir"); |
| 77 | let mut app = create_test_app_with_tmpdir(&tmpdir); |
| 78 | app.api_messages_mut().push(Message { |
| 79 | role: Role::User, |
| 80 | content: vec![ContentBlock::Text { |
| 81 | text: "Remember the whale migration".to_string(), |
| 82 | cache_control: None, |
| 83 | }], |
| 84 | }); |
| 85 | app.add_message(HistoryCell::User { |
| 86 | content: "Remember the whale migration".to_string(), |
| 87 | }); |
| 88 | app.session.total_tokens = 321; |
| 89 | app.session.total_conversation_tokens = 321; |
| 90 | |
| 91 | world.save_path = Some(tmpdir.path().join("saved-session.json")); |
| 92 | world.export_path = Some(tmpdir.path().join("transcript.md")); |
| 93 | world.home_path = Some(tmpdir.path().join("home")); |
| 94 | world.app = Some(Box::new(app)); |
| 95 | world.tmpdir = Some(tmpdir); |
| 96 | } |
| 97 | |
| 98 | #[given("a CodeWhale persisted session workspace with one user message")] |
| 99 | fn persisted_workspace_with_one_user_message(world: &mut SessionCommandWorld) { |
| 100 | workspace_with_one_user_message(world); |
| 101 | let original_id = "original-session".to_string(); |
| 102 | let app = world.app.as_deref_mut().expect("app should exist"); |
| 103 | app.current_session_id = Some(original_id.clone()); |
| 104 | world.original_session_id = Some(original_id); |
| 105 | persist_active_session(world); |
| 106 | } |
| 107 | |
| 108 | #[given("a CodeWhale session workspace with stale and fresh saved sessions")] |
| 109 | fn workspace_with_stale_and_fresh_saved_sessions(world: &mut SessionCommandWorld) { |
| 110 | workspace_with_one_user_message(world); |
| 111 | persist_session_with_age(world, "fresh-session", "Fresh session", 1); |
| 112 | persist_session_with_age(world, "stale-session", "Stale session", 30); |
| 113 | world.fresh_session_id = Some("fresh-session".to_string()); |
| 114 | world.stale_session_id = Some("stale-session".to_string()); |
| 115 | } |
| 116 | |
| 117 | #[when("the user saves the active session")] |
| 118 | fn user_saves_active_session(world: &mut SessionCommandWorld) { |
| 119 | let save_path = world |
| 120 | .save_path |
| 121 | .as_ref() |
| 122 | .expect("save path should exist") |
| 123 | .to_string_lossy() |
| 124 | .to_string(); |
| 125 | let result = execute_isolated(world, &format!("/save {save_path}")); |
| 126 | remember_result(world, &result); |
| 127 | |
| 128 | assert!(!result.is_error, "save failed: {:?}", result.message); |
| 129 | assert!( |
| 130 | world.save_path.as_ref().expect("save path").exists(), |
| 131 | "save command should write the session file" |
| 132 | ); |
| 133 | } |
| 134 | |
| 135 | #[when("the user exports the active transcript")] |
| 136 | fn user_exports_active_transcript(world: &mut SessionCommandWorld) { |
| 137 | let export_path = world |
| 138 | .export_path |
| 139 | .as_ref() |
| 140 | .expect("export path should exist") |
| 141 | .to_string_lossy() |
| 142 | .to_string(); |
| 143 | let result = execute_isolated(world, &format!("/export {export_path}")); |
| 144 | remember_result(world, &result); |
| 145 | |
| 146 | assert!(!result.is_error, "export failed: {:?}", result.message); |
| 147 | assert!( |
| 148 | world.export_path.as_ref().expect("export path").exists(), |
| 149 | "export command should write the transcript" |
| 150 | ); |
| 151 | } |
| 152 | |
| 153 | #[when("the user clears the active conversation")] |
| 154 | fn user_clears_active_conversation(world: &mut SessionCommandWorld) { |
| 155 | let result = execute_isolated(world, "/clear"); |
| 156 | remember_result(world, &result); |
| 157 | |
| 158 | assert!(!result.is_error, "clear failed: {:?}", result.message); |
| 159 | let app = world.app.as_deref().expect("app should exist"); |
| 160 | assert!( |
| 161 | app.api_messages.is_empty(), |
| 162 | "clear command should remove active API messages" |
| 163 | ); |
| 164 | assert_eq!(app.session.total_tokens, 0); |
| 165 | } |
| 166 | |
| 167 | #[when("the user loads the saved session")] |
| 168 | fn user_loads_saved_session(world: &mut SessionCommandWorld) { |
| 169 | let save_path = world |
| 170 | .save_path |
| 171 | .as_ref() |
| 172 | .expect("save path should exist") |
| 173 | .to_string_lossy() |
| 174 | .to_string(); |
| 175 | let result = execute_isolated(world, &format!("/load {save_path}")); |
| 176 | remember_result(world, &result); |
| 177 | |
| 178 | assert!(!result.is_error, "load failed: {:?}", result.message); |
| 179 | world.last_message = result.message; |
| 180 | } |
| 181 | |
| 182 | #[when("the user forks the active session")] |
| 183 | fn user_forks_active_session(world: &mut SessionCommandWorld) { |
| 184 | let result = execute_isolated(world, "/fork"); |
| 185 | remember_result(world, &result); |
| 186 | |
| 187 | assert!(!result.is_error, "fork failed: {:?}", result.message); |
| 188 | let fork_id = world |
| 189 | .app |
| 190 | .as_deref() |
| 191 | .and_then(|app| app.current_session_id.clone()) |
| 192 | .expect("fork command should switch to a child session"); |
| 193 | let forked = load_saved_session(world, &fork_id); |
| 194 | if world.original_session_id.is_none() { |
| 195 | world.original_session_id = forked.metadata.parent_session_id.clone(); |
| 196 | } |
| 197 | world.fork_session_id = Some(fork_id); |
| 198 | } |
| 199 | |
| 200 | #[when("the user tries to fork the active session")] |
| 201 | fn user_tries_to_fork_active_session(world: &mut SessionCommandWorld) { |
| 202 | let result = execute_isolated(world, "/fork"); |
| 203 | remember_result(world, &result); |
| 204 | } |
| 205 | |
| 206 | #[when("the user starts a new session")] |
| 207 | async fn user_starts_new_session(world: &mut SessionCommandWorld) { |
| 208 | let result = execute_isolated(world, "/new"); |
| 209 | remember_result(world, &result); |
| 210 | |
| 211 | assert!(!result.is_error, "new session failed: {:?}", result.message); |
| 212 | let home = world |
| 213 | .home_path |
| 214 | .as_ref() |
| 215 | .expect("isolated test home") |
| 216 | .clone(); |
| 217 | let _lock = lock_test_env(); |
| 218 | let _home = EnvVarGuard::set("HOME", &home); |
| 219 | let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", home.join(".codewhale")); |
| 220 | commands::acknowledge_new_session(world.app.as_deref_mut().expect("app should exist"), &result) |
| 221 | .await; |
| 222 | let new_id = world |
| 223 | .app |
| 224 | .as_deref() |
| 225 | .and_then(|app| app.current_session_id.clone()) |
| 226 | .expect("new command should set an active session id"); |
| 227 | world.new_session_id = Some(new_id); |
| 228 | } |
| 229 | |
| 230 | #[when(regex = r#"^the user renames the active session to "([^"]+)"$"#)] |
| 231 | fn user_renames_active_session(world: &mut SessionCommandWorld, title: String) { |
| 232 | let result = execute_isolated(world, &format!("/rename {title}")); |
| 233 | remember_result(world, &result); |
| 234 | |
| 235 | assert!(!result.is_error, "rename failed: {:?}", result.message); |
| 236 | } |
| 237 | |
| 238 | #[when("the user lists saved sessions")] |
| 239 | fn user_lists_saved_sessions(world: &mut SessionCommandWorld) { |
| 240 | let result = execute_isolated(world, "/sessions list"); |
| 241 | remember_result(world, &result); |
| 242 | |
| 243 | assert!( |
| 244 | !result.is_error, |
| 245 | "sessions list failed: {:?}", |
| 246 | result.message |
| 247 | ); |
| 248 | } |
| 249 | |
| 250 | #[when(regex = r#"^the user prunes sessions older than (\d+) days$"#)] |
| 251 | fn user_prunes_sessions_older_than(world: &mut SessionCommandWorld, days: String) { |
| 252 | let result = execute_isolated(world, &format!("/sessions prune {days}")); |
| 253 | remember_result(world, &result); |
| 254 | |
| 255 | assert!( |
| 256 | !result.is_error, |
| 257 | "sessions prune failed: {:?}", |
| 258 | result.message |
| 259 | ); |
| 260 | } |
| 261 | |
| 262 | #[when("the user compacts context")] |
| 263 | fn user_compacts_context(world: &mut SessionCommandWorld) { |
| 264 | let result = execute_isolated(world, "/compact"); |
| 265 | remember_result(world, &result); |
| 266 | |
| 267 | assert!(!result.is_error, "compact failed: {:?}", result.message); |
| 268 | } |
| 269 | |
| 270 | #[when("the user purges context")] |
| 271 | fn user_purges_context(world: &mut SessionCommandWorld) { |
| 272 | let result = execute_isolated(world, "/purge"); |
| 273 | remember_result(world, &result); |
| 274 | |
| 275 | assert!(!result.is_error, "purge failed: {:?}", result.message); |
| 276 | } |
| 277 | |
| 278 | #[when(regex = r#"^the user prepares a session relay focused on "([^"]+)"$"#)] |
| 279 | fn user_prepares_session_relay_focused_on(world: &mut SessionCommandWorld, focus: String) { |
| 280 | let result = execute_isolated(world, &format!("/relay {focus}")); |
| 281 | remember_result(world, &result); |
| 282 | |
| 283 | assert!(!result.is_error, "relay failed: {:?}", result.message); |
| 284 | } |
| 285 | |
| 286 | #[when("the user runs the singular session command")] |
| 287 | fn user_runs_singular_session_command(world: &mut SessionCommandWorld) { |
| 288 | let result = execute_isolated(world, "/session"); |
| 289 | remember_result(world, &result); |
| 290 | } |
| 291 | |
| 292 | #[then("the active session should contain the saved message")] |
| 293 | fn active_session_contains_saved_message(world: &mut SessionCommandWorld) { |
| 294 | let app = world.app.as_deref().expect("app should exist"); |
| 295 | let message = app |
| 296 | .api_messages |
| 297 | .first() |
| 298 | .expect("loaded session should have one message"); |
| 299 | let content = message |
| 300 | .content |
| 301 | .iter() |
| 302 | .find_map(|block| match block { |
| 303 | ContentBlock::Text { text, .. } => Some(text.as_str()), |
| 304 | _ => None, |
| 305 | }) |
| 306 | .expect("loaded message should have text content"); |
| 307 | |
| 308 | assert_eq!(message.role, "user"); |
| 309 | assert_eq!(content, "Remember the whale migration"); |
| 310 | } |
| 311 | |
| 312 | #[then("the saved session file should contain the saved message")] |
| 313 | fn saved_session_file_contains_saved_message(world: &mut SessionCommandWorld) { |
| 314 | let session = read_saved_session_file(world); |
| 315 | |
| 316 | assert_saved_session_contains_message(&session, "Remember the whale migration"); |
| 317 | } |
| 318 | |
| 319 | #[then("the load action should target the saved session file")] |
| 320 | fn load_action_targets_saved_session_file(world: &mut SessionCommandWorld) { |
| 321 | let save_path = world.save_path.as_ref().expect("save path should exist"); |
| 322 | |
| 323 | assert!(matches!( |
| 324 | world.last_action.as_ref(), |
| 325 | Some(AppAction::LoadSession(path)) if path == save_path |
| 326 | )); |
| 327 | } |
| 328 | |
| 329 | #[then("the exported markdown should contain the active transcript")] |
| 330 | fn exported_markdown_contains_active_transcript(world: &mut SessionCommandWorld) { |
| 331 | let export_path = world |
| 332 | .export_path |
| 333 | .as_ref() |
| 334 | .expect("export path should exist"); |
| 335 | let content = std::fs::read_to_string(export_path) |
| 336 | .unwrap_or_else(|err| panic!("read exported transcript {export_path:?}: {err}")); |
| 337 | |
| 338 | assert!(content.contains("# Codewhale conversation export")); |
| 339 | assert!(content.contains("## 1. user")); |
| 340 | assert!(content.contains("Remember the whale migration")); |
| 341 | } |
| 342 | |
| 343 | #[then("CodeWhale should defer the session-loaded receipt to the event loop")] |
| 344 | fn codewhale_defers_session_loaded_receipt(world: &mut SessionCommandWorld) { |
| 345 | assert_eq!( |
| 346 | world.last_message, None, |
| 347 | "the command layer must not report success before the event loop applies the load action" |
| 348 | ); |
| 349 | } |
| 350 | |
| 351 | #[then("the forked session should reference the original session")] |
| 352 | fn forked_session_references_original_session(world: &mut SessionCommandWorld) { |
| 353 | let original_id = world |
| 354 | .original_session_id |
| 355 | .as_deref() |
| 356 | .expect("original session id should exist"); |
| 357 | let fork_id = world |
| 358 | .fork_session_id |
| 359 | .as_deref() |
| 360 | .expect("fork session id should exist"); |
| 361 | let forked = load_saved_session(world, fork_id); |
| 362 | |
| 363 | assert_eq!( |
| 364 | forked.metadata.parent_session_id.as_deref(), |
| 365 | Some(original_id) |
| 366 | ); |
| 367 | assert_eq!(forked.metadata.forked_from_message_count, Some(1)); |
| 368 | } |
| 369 | |
| 370 | #[then("the original session should still be loadable")] |
| 371 | fn original_session_still_loadable(world: &mut SessionCommandWorld) { |
| 372 | let original_id = world |
| 373 | .original_session_id |
| 374 | .as_deref() |
| 375 | .expect("original session id should exist"); |
| 376 | let original = load_saved_session(world, original_id); |
| 377 | |
| 378 | assert_saved_session_contains_message(&original, "Remember the whale migration"); |
| 379 | } |
| 380 | |
| 381 | #[then("the active session should be the forked session")] |
| 382 | fn active_session_is_forked_session(world: &mut SessionCommandWorld) { |
| 383 | let fork_id = world |
| 384 | .fork_session_id |
| 385 | .as_deref() |
| 386 | .expect("fork session id should exist"); |
| 387 | let app = world.app.as_deref().expect("app should exist"); |
| 388 | |
| 389 | assert_eq!(app.current_session_id.as_deref(), Some(fork_id)); |
| 390 | assert_app_contains_message(app, "Remember the whale migration"); |
| 391 | } |
| 392 | |
| 393 | #[then("CodeWhale should reject the fork because there are no messages")] |
| 394 | fn codewhale_rejects_empty_fork(world: &mut SessionCommandWorld) { |
| 395 | assert_eq!( |
| 396 | world.last_result_is_error, |
| 397 | Some(true), |
| 398 | "last command should have failed" |
| 399 | ); |
| 400 | let message = world |
| 401 | .last_message |
| 402 | .as_deref() |
| 403 | .expect("fork rejection should include a message"); |
| 404 | |
| 405 | assert!( |
| 406 | message.contains("Nothing to fork"), |
| 407 | "unexpected fork rejection message: {message}" |
| 408 | ); |
| 409 | } |
| 410 | |
| 411 | #[then("the active session should be empty")] |
| 412 | fn active_session_empty(world: &mut SessionCommandWorld) { |
| 413 | let app = world.app.as_deref().expect("app should exist"); |
| 414 | |
| 415 | assert!(app.api_messages.is_empty()); |
| 416 | assert_eq!(app.session.total_tokens, 0); |
| 417 | assert_eq!(app.session.total_conversation_tokens, 0); |
| 418 | } |
| 419 | |
| 420 | #[then("the original and forked sessions should remain loadable")] |
| 421 | fn original_and_forked_sessions_remain_loadable(world: &mut SessionCommandWorld) { |
| 422 | let original_id = world |
| 423 | .original_session_id |
| 424 | .as_deref() |
| 425 | .expect("original session id should exist"); |
| 426 | let fork_id = world |
| 427 | .fork_session_id |
| 428 | .as_deref() |
| 429 | .expect("fork session id should exist"); |
| 430 | let original = load_saved_session(world, original_id); |
| 431 | let forked = load_saved_session(world, fork_id); |
| 432 | |
| 433 | assert_saved_session_contains_message(&original, "Remember the whale migration"); |
| 434 | assert_saved_session_contains_message(&forked, "Remember the whale migration"); |
| 435 | assert_eq!( |
| 436 | forked.metadata.parent_session_id.as_deref(), |
| 437 | Some(original_id) |
| 438 | ); |
| 439 | } |
| 440 | |
| 441 | #[then("the active session should be a new empty session")] |
| 442 | fn active_session_is_new_empty_session(world: &mut SessionCommandWorld) { |
| 443 | let original_id = world |
| 444 | .original_session_id |
| 445 | .as_deref() |
| 446 | .expect("original session id should exist"); |
| 447 | let fork_id = world |
| 448 | .fork_session_id |
| 449 | .as_deref() |
| 450 | .expect("fork session id should exist"); |
| 451 | let new_id = world |
| 452 | .new_session_id |
| 453 | .as_deref() |
| 454 | .expect("new session id should exist"); |
| 455 | let app = world.app.as_deref().expect("app should exist"); |
| 456 | |
| 457 | assert_eq!(app.current_session_id.as_deref(), Some(new_id)); |
| 458 | assert_ne!(new_id, original_id); |
| 459 | assert_ne!(new_id, fork_id); |
| 460 | assert!(app.api_messages.is_empty()); |
| 461 | assert_eq!(app.session.total_tokens, 0); |
| 462 | } |
| 463 | |
| 464 | #[then("the active session should be cleared into a fresh empty session")] |
| 465 | fn active_session_cleared_into_fresh_empty_session(world: &mut SessionCommandWorld) { |
| 466 | let app = world.app.as_deref().expect("app should exist"); |
| 467 | |
| 468 | // `/clear` claims the next session id in the App (like `/new`) so the |
| 469 | // engine, the turn-start checkpoint, and autosave all share one id. |
| 470 | let cleared_id = app |
| 471 | .current_session_id |
| 472 | .as_deref() |
| 473 | .expect("/clear should claim a fresh session id"); |
| 474 | assert!( |
| 475 | uuid::Uuid::parse_str(cleared_id).is_ok(), |
| 476 | "fresh session id should be a uuid, got {cleared_id:?}" |
| 477 | ); |
| 478 | for previous in [ |
| 479 | world.original_session_id.as_deref(), |
| 480 | world.fork_session_id.as_deref(), |
| 481 | ] |
| 482 | .into_iter() |
| 483 | .flatten() |
| 484 | { |
| 485 | assert_ne!( |
| 486 | cleared_id, previous, |
| 487 | "/clear must not reuse a saved session id" |
| 488 | ); |
| 489 | } |
| 490 | // When `/clear` was the last command its SyncSession must carry the same |
| 491 | // id; a later `/load` in the same scenario leaves a different action. |
| 492 | if let Some(AppAction::SyncSession { |
| 493 | session_id, |
| 494 | messages, |
| 495 | .. |
| 496 | }) = world.last_action.as_ref() |
| 497 | { |
| 498 | assert_eq!(session_id.as_deref(), Some(cleared_id)); |
| 499 | assert!(messages.is_empty()); |
| 500 | } |
| 501 | assert!(app.api_messages.is_empty()); |
| 502 | assert_eq!(app.session.total_tokens, 0); |
| 503 | } |
| 504 | |
| 505 | #[then(regex = r#"^the active saved session title should be "([^"]+)"$"#)] |
| 506 | fn active_saved_session_title_should_be(world: &mut SessionCommandWorld, expected: String) { |
| 507 | let app = world.app.as_deref().expect("app should exist"); |
| 508 | let session_id = app |
| 509 | .current_session_id |
| 510 | .as_deref() |
| 511 | .expect("active session id should exist"); |
| 512 | let saved = load_saved_session(world, session_id); |
| 513 | |
| 514 | assert_eq!(saved.metadata.title, expected); |
| 515 | } |
| 516 | |
| 517 | #[then("the active session should be the original session")] |
| 518 | fn active_session_is_original_session(world: &mut SessionCommandWorld) { |
| 519 | let original_id = world |
| 520 | .original_session_id |
| 521 | .as_deref() |
| 522 | .expect("original session id should exist"); |
| 523 | let app = world.app.as_deref().expect("app should exist"); |
| 524 | |
| 525 | assert_eq!(app.current_session_id.as_deref(), Some(original_id)); |
| 526 | assert_app_contains_message(app, "Remember the whale migration"); |
| 527 | } |
| 528 | |
| 529 | #[then("the session picker should be open")] |
| 530 | fn session_picker_should_be_open(world: &mut SessionCommandWorld) { |
| 531 | let app = world.app.as_deref().expect("app should exist"); |
| 532 | |
| 533 | assert_eq!(app.view_stack.top_kind(), Some(ModalKind::SessionPicker)); |
| 534 | } |
| 535 | |
| 536 | #[then("CodeWhale should report that one session was pruned")] |
| 537 | fn codewhale_reports_one_session_pruned(world: &mut SessionCommandWorld) { |
| 538 | let message = world |
| 539 | .last_message |
| 540 | .as_deref() |
| 541 | .expect("prune command should produce a message"); |
| 542 | |
| 543 | assert!( |
| 544 | message.contains("pruned 1 session"), |
| 545 | "unexpected prune message: {message}" |
| 546 | ); |
| 547 | } |
| 548 | |
| 549 | #[then("the fresh session should still be loadable")] |
| 550 | fn fresh_session_still_loadable(world: &mut SessionCommandWorld) { |
| 551 | let fresh_id = world |
| 552 | .fresh_session_id |
| 553 | .as_deref() |
| 554 | .expect("fresh session id should exist"); |
| 555 | let fresh = load_saved_session(world, fresh_id); |
| 556 | |
| 557 | assert_eq!(fresh.metadata.title, "Fresh session"); |
| 558 | } |
| 559 | |
| 560 | #[then("the stale session should no longer be loadable")] |
| 561 | fn stale_session_no_longer_loadable(world: &mut SessionCommandWorld) { |
| 562 | let stale_id = world |
| 563 | .stale_session_id |
| 564 | .as_deref() |
| 565 | .expect("stale session id should exist"); |
| 566 | |
| 567 | assert!( |
| 568 | try_load_saved_session(world, stale_id).is_err(), |
| 569 | "stale session should have been pruned" |
| 570 | ); |
| 571 | } |
| 572 | |
| 573 | #[then("CodeWhale should trigger context compaction")] |
| 574 | fn codewhale_triggers_context_compaction(world: &mut SessionCommandWorld) { |
| 575 | assert_eq!( |
| 576 | world.last_result_is_error, |
| 577 | Some(false), |
| 578 | "compact command should succeed" |
| 579 | ); |
| 580 | assert!(matches!( |
| 581 | world.last_action.as_ref(), |
| 582 | Some(AppAction::CompactContext { .. }) |
| 583 | )); |
| 584 | assert_eq!(world.last_message.as_deref(), Some("Making room…")); |
| 585 | } |
| 586 | |
| 587 | #[then("CodeWhale should trigger context purge")] |
| 588 | fn codewhale_triggers_context_purge(world: &mut SessionCommandWorld) { |
| 589 | assert_eq!( |
| 590 | world.last_result_is_error, |
| 591 | Some(false), |
| 592 | "purge command should succeed" |
| 593 | ); |
| 594 | assert!(matches!( |
| 595 | world.last_action.as_ref(), |
| 596 | Some(AppAction::PurgeContext) |
| 597 | )); |
| 598 | assert_eq!( |
| 599 | world.last_message.as_deref(), |
| 600 | Some("Agent context purge triggered...") |
| 601 | ); |
| 602 | } |
| 603 | |
| 604 | #[then(regex = r#"^CodeWhale should send a session relay instruction focused on "([^"]+)"$"#)] |
| 605 | fn codewhale_sends_session_relay_instruction_focused_on( |
| 606 | world: &mut SessionCommandWorld, |
| 607 | focus: String, |
| 608 | ) { |
| 609 | assert_eq!( |
| 610 | world.last_result_is_error, |
| 611 | Some(false), |
| 612 | "relay command should succeed" |
| 613 | ); |
| 614 | let message = match world.last_action.as_ref() { |
| 615 | Some(AppAction::SendMessage(message)) => message, |
| 616 | other => panic!("expected relay SendMessage action, got {other:?}"), |
| 617 | }; |
| 618 | |
| 619 | assert!(message.contains("Write or update `.codewhale/handoff.md`.")); |
| 620 | assert!(message.contains("# Session relay")); |
| 621 | assert!(message.contains("## Verification")); |
| 622 | assert!( |
| 623 | message.contains(&format!("- Requested relay focus: {focus}")), |
| 624 | "relay instruction should include requested focus: {message}" |
| 625 | ); |
| 626 | assert_eq!( |
| 627 | world.last_message.as_deref(), |
| 628 | Some("Preparing session relay at .codewhale/handoff.md...") |
| 629 | ); |
| 630 | } |
| 631 | |
| 632 | #[then("CodeWhale should reject the unknown session command")] |
| 633 | fn codewhale_rejects_unknown_session_command(world: &mut SessionCommandWorld) { |
| 634 | assert_eq!( |
| 635 | world.last_result_is_error, |
| 636 | Some(true), |
| 637 | "singular /session should be rejected" |
| 638 | ); |
| 639 | let message = world |
| 640 | .last_message |
| 641 | .as_deref() |
| 642 | .expect("unknown command should include a message"); |
| 643 | |
| 644 | assert!( |
| 645 | message.contains("Unknown command: /session"), |
| 646 | "unexpected unknown command message: {message}" |
| 647 | ); |
| 648 | assert!( |
| 649 | message.contains("/sessions") || message.contains("/save"), |
| 650 | "unknown command should include a session-related suggestion: {message}" |
| 651 | ); |
| 652 | } |
| 653 | |
| 654 | /// C01-09: `/save <path>` replaces a saved session, never an arbitrary file. |
| 655 | #[tokio::test(flavor = "current_thread")] |
| 656 | async fn save_refuses_to_overwrite_a_file_that_is_not_a_saved_session() { |
| 657 | let mut world = SessionCommandWorld::default(); |
| 658 | workspace_with_one_user_message(&mut world); |
| 659 | let target = world |
| 660 | .tmpdir |
| 661 | .as_ref() |
| 662 | .expect("tmpdir") |
| 663 | .path() |
| 664 | .join("notes.txt"); |
| 665 | std::fs::write(&target, "keep me").expect("seed an unrelated file"); |
| 666 | |
| 667 | let refused = execute_isolated(&mut world, &format!("/save {}", target.display())); |
| 668 | assert!(refused.is_error, "{:?}", refused.message); |
| 669 | assert_eq!( |
| 670 | std::fs::read_to_string(&target).expect("still readable"), |
| 671 | "keep me", |
| 672 | "the unrelated file is untouched" |
| 673 | ); |
| 674 | |
| 675 | let saved = world.save_path.clone().expect("save path"); |
| 676 | for attempt in ["first save", "re-save over the saved session"] { |
| 677 | let result = execute_isolated(&mut world, &format!("/save {}", saved.display())); |
| 678 | assert!(!result.is_error, "{attempt}: {:?}", result.message); |
| 679 | } |
| 680 | } |
| 681 | |
| 682 | #[tokio::test(flavor = "current_thread")] |
| 683 | async fn save_export_and_load_session_workflow() { |
| 684 | run_scenario(SAVE_LOAD_SCENARIO, 10).await; |
| 685 | } |
| 686 | |
| 687 | #[tokio::test(flavor = "current_thread")] |
| 688 | async fn fork_keeps_original_session_resumable() { |
| 689 | run_scenario(FORK_RESUMABLE_SCENARIO, 5).await; |
| 690 | } |
| 691 | |
| 692 | #[tokio::test(flavor = "current_thread")] |
| 693 | async fn new_session_cannot_be_forked_before_messages_exist() { |
| 694 | run_scenario(NEW_THEN_FORK_SCENARIO, 5).await; |
| 695 | } |
| 696 | |
| 697 | #[tokio::test(flavor = "current_thread")] |
| 698 | async fn cleared_session_cannot_be_forked_before_messages_exist() { |
| 699 | run_scenario(CLEAR_THEN_FORK_SCENARIO, 5).await; |
| 700 | } |
| 701 | |
| 702 | #[tokio::test(flavor = "current_thread")] |
| 703 | async fn fork_followed_by_new_keeps_both_saved_sessions() { |
| 704 | run_scenario(FORK_THEN_NEW_SCENARIO, 5).await; |
| 705 | } |
| 706 | |
| 707 | #[tokio::test(flavor = "current_thread")] |
| 708 | async fn fork_followed_by_clear_keeps_both_saved_sessions() { |
| 709 | run_scenario(FORK_THEN_CLEAR_SCENARIO, 5).await; |
| 710 | } |
| 711 | |
| 712 | #[tokio::test(flavor = "current_thread")] |
| 713 | async fn rename_updates_active_saved_session_title() { |
| 714 | run_scenario(RENAME_SCENARIO, 4).await; |
| 715 | } |
| 716 | |
| 717 | #[tokio::test(flavor = "current_thread")] |
| 718 | async fn sessions_list_opens_saved_session_picker() { |
| 719 | run_scenario(SESSIONS_LIST_SCENARIO, 4).await; |
| 720 | } |
| 721 | |
| 722 | #[tokio::test(flavor = "current_thread")] |
| 723 | async fn sessions_prune_removes_only_stale_sessions() { |
| 724 | run_scenario(SESSIONS_PRUNE_SCENARIO, 5).await; |
| 725 | } |
| 726 | |
| 727 | #[tokio::test(flavor = "current_thread")] |
| 728 | async fn context_management_commands_emit_actions_without_clearing_active_session() { |
| 729 | run_scenario(CONTEXT_MANAGEMENT_SCENARIO, 10).await; |
| 730 | } |
| 731 | |
| 732 | #[tokio::test(flavor = "current_thread")] |
| 733 | async fn singular_session_command_is_not_registered() { |
| 734 | run_scenario(SINGULAR_SESSION_SCENARIO, 4).await; |
| 735 | } |
| 736 | |
| 737 | async fn run_scenario(name: &'static str, expected_steps: usize) { |
| 738 | let writer = SessionCommandWorld::cucumber() |
| 739 | .fail_on_skipped() |
| 740 | .with_default_cli() |
| 741 | .filter_run(FEATURE_PATH, move |feature, _, scenario| { |
| 742 | feature.name == FEATURE_NAME && scenario.name == name |
| 743 | }) |
| 744 | .await; |
| 745 | assert_eq!(writer.failed_steps(), 0, "scenario failed: {name}"); |
| 746 | assert_eq!(writer.skipped_steps(), 0, "scenario skipped steps: {name}"); |
| 747 | assert_eq!( |
| 748 | writer.passed_steps(), |
| 749 | expected_steps, |
| 750 | "scenario did not run: {name}" |
| 751 | ); |
| 752 | } |
| 753 | |
| 754 | fn create_test_app_with_tmpdir(tmpdir: &TempDir) -> App { |
| 755 | let options = TuiOptions { |
| 756 | skills_dir: tmpdir.path().join("skills"), |
| 757 | memory_path: tmpdir.path().join("memory.md"), |
| 758 | mcp_config_path: tmpdir.path().join("mcp.json"), |
| 759 | ..crate::tui::test_support::test_tui_options(tmpdir.path()) |
| 760 | }; |
| 761 | App::new(options, &Config::default()) |
| 762 | } |
| 763 | |
| 764 | fn execute_isolated(world: &mut SessionCommandWorld, command: &str) -> CommandResult { |
| 765 | let home = world |
| 766 | .home_path |
| 767 | .as_ref() |
| 768 | .expect("test home should exist") |
| 769 | .clone(); |
| 770 | std::fs::create_dir_all(&home).expect("create isolated test home"); |
| 771 | |
| 772 | let _lock = lock_test_env(); |
| 773 | let _home = EnvVarGuard::set("HOME", &home); |
| 774 | let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", home.join(".codewhale")); |
| 775 | |
| 776 | let app = world.app.as_deref_mut().expect("app should exist"); |
| 777 | commands::user_registry::reload(Some(&app.workspace)); |
| 778 | commands::execute(command, app) |
| 779 | } |
| 780 | |
| 781 | fn remember_result(world: &mut SessionCommandWorld, result: &CommandResult) { |
| 782 | world.last_result_is_error = Some(result.is_error); |
| 783 | world.last_message = result.message.clone(); |
| 784 | world.last_action = result.action.clone(); |
| 785 | } |
| 786 | |
| 787 | fn persist_active_session(world: &mut SessionCommandWorld) { |
| 788 | let app = world.app.as_deref_mut().expect("app should exist"); |
| 789 | let session_id = app |
| 790 | .current_session_id |
| 791 | .as_ref() |
| 792 | .expect("active session id should exist") |
| 793 | .clone(); |
| 794 | let session = create_saved_session_with_id_and_mode( |
| 795 | session_id, |
| 796 | &app.api_messages, |
| 797 | &app.model, |
| 798 | &app.workspace, |
| 799 | u64::from(app.session.total_tokens), |
| 800 | app.system_prompt.as_ref(), |
| 801 | Some(app.mode.label()), |
| 802 | ); |
| 803 | let home = world |
| 804 | .home_path |
| 805 | .as_ref() |
| 806 | .expect("test home should exist") |
| 807 | .clone(); |
| 808 | std::fs::create_dir_all(&home).expect("create isolated test home"); |
| 809 | |
| 810 | let _lock = lock_test_env(); |
| 811 | let _home = EnvVarGuard::set("HOME", &home); |
| 812 | let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", home.join(".codewhale")); |
| 813 | let manager = SessionManager::default_location().expect("open isolated session manager"); |
| 814 | |
| 815 | manager |
| 816 | .save_session(&session) |
| 817 | .expect("persist active session"); |
| 818 | app.capture_session_fixture_source(); |
| 819 | } |
| 820 | |
| 821 | fn persist_session_with_age(world: &SessionCommandWorld, session_id: &str, title: &str, days: i64) { |
| 822 | let app = world.app.as_deref().expect("app should exist"); |
| 823 | let mut session = create_saved_session_with_id_and_mode( |
| 824 | session_id.to_string(), |
| 825 | &app.api_messages, |
| 826 | &app.model, |
| 827 | &app.workspace, |
| 828 | u64::from(app.session.total_tokens), |
| 829 | app.system_prompt.as_ref(), |
| 830 | Some(app.mode.label()), |
| 831 | ); |
| 832 | let timestamp = Utc::now() - ChronoDuration::days(days); |
| 833 | session.metadata.title = title.to_string(); |
| 834 | session.metadata.created_at = timestamp; |
| 835 | session.metadata.updated_at = timestamp; |
| 836 | |
| 837 | let home = world |
| 838 | .home_path |
| 839 | .as_ref() |
| 840 | .expect("test home should exist") |
| 841 | .clone(); |
| 842 | std::fs::create_dir_all(&home).expect("create isolated test home"); |
| 843 | |
| 844 | let _lock = lock_test_env(); |
| 845 | let _home = EnvVarGuard::set("HOME", &home); |
| 846 | let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", home.join(".codewhale")); |
| 847 | let manager = SessionManager::default_location().expect("open isolated session manager"); |
| 848 | |
| 849 | manager.save_session(&session).expect("persist session"); |
| 850 | } |
| 851 | |
| 852 | fn load_saved_session(world: &SessionCommandWorld, session_id: &str) -> SavedSession { |
| 853 | try_load_saved_session(world, session_id) |
| 854 | .unwrap_or_else(|_| panic!("load saved session failed")) |
| 855 | } |
| 856 | |
| 857 | fn try_load_saved_session( |
| 858 | world: &SessionCommandWorld, |
| 859 | session_id: &str, |
| 860 | ) -> std::io::Result<SavedSession> { |
| 861 | let home = world |
| 862 | .home_path |
| 863 | .as_ref() |
| 864 | .expect("test home should exist") |
| 865 | .clone(); |
| 866 | std::fs::create_dir_all(&home).expect("create isolated test home"); |
| 867 | |
| 868 | let _lock = lock_test_env(); |
| 869 | let _home = EnvVarGuard::set("HOME", &home); |
| 870 | let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", home.join(".codewhale")); |
| 871 | let manager = SessionManager::default_location().expect("open isolated session manager"); |
| 872 | |
| 873 | manager.load_session(session_id) |
| 874 | } |
| 875 | |
| 876 | fn read_saved_session_file(world: &SessionCommandWorld) -> SavedSession { |
| 877 | let save_path = world.save_path.as_ref().expect("save path should exist"); |
| 878 | let content = std::fs::read_to_string(save_path) |
| 879 | .unwrap_or_else(|err| panic!("read saved session file {save_path:?}: {err}")); |
| 880 | |
| 881 | serde_json::from_str(&content) |
| 882 | .unwrap_or_else(|err| panic!("parse saved session file {save_path:?}: {err}")) |
| 883 | } |
| 884 | |
| 885 | fn assert_app_contains_message(app: &App, expected: &str) { |
| 886 | let message = app |
| 887 | .api_messages |
| 888 | .first() |
| 889 | .expect("active session should contain one message"); |
| 890 | let content = message |
| 891 | .content |
| 892 | .iter() |
| 893 | .find_map(text_content) |
| 894 | .expect("active message should contain text"); |
| 895 | |
| 896 | assert_eq!(message.role, "user"); |
| 897 | assert_eq!(content, expected); |
| 898 | } |
| 899 | |
| 900 | fn assert_saved_session_contains_message(session: &SavedSession, expected: &str) { |
| 901 | let message = session |
| 902 | .messages |
| 903 | .first() |
| 904 | .expect("saved session should contain one message"); |
| 905 | let content = message |
| 906 | .content |
| 907 | .iter() |
| 908 | .find_map(text_content) |
| 909 | .expect("saved message should contain text"); |
| 910 | |
| 911 | assert_eq!(message.role, "user"); |
| 912 | assert_eq!(content, expected); |
| 913 | } |
| 914 | |
| 915 | fn text_content(block: &ContentBlock) -> Option<&str> { |
| 916 | match block { |
| 917 | ContentBlock::Text { text, .. } => Some(text.as_str()), |
| 918 | _ => None, |
| 919 | } |
| 920 | } |
| 921 |