返回 CodeWhale
session_lifecycle_regression_tests.rs
根目录 / crates / tui / src / commands / session_lifecycle_regression_tests.rs
1 //! Regression coverage retained from the pre-FEAT-023 lifecycle implementation.
2 //!
3 //! These tests dispatch through the public command seam so moving host logic
4 //! behind `CommandSessionLifecycleContext` cannot silently reduce the existing
5 //! persistence, reset, and deferred-load guarantees.
6
7 use std::time::Instant;
8
9 use tempfile::TempDir;
10
11 use crate::commands::CommandResult;
12 use crate::test_support::SealedHome;
13 use crate::tui::app::{App, AppAction, TuiOptions, TurnCacheRecord};
14 use crate::tui::history::HistoryCell;
15 use codewhale_config::AppMode;
16 use codewhale_engine::reasoning_preference::ReasoningEffort;
17 use codewhale_engine::session_manager::create_saved_session_with_id_and_mode;
18 use codewhale_models::Role;
19 use codewhale_runtime::config::Config;
20
21 fn dispatch_lifecycle(app: &mut App, name: &str, arg: Option<&str>) -> CommandResult {
22 let command = match arg {
23 Some(arg) => format!("/{name} {arg}"),
24 None => format!("/{name}"),
25 };
26 crate::commands::execute(&command, app)
27 }
28
29 fn save(app: &mut App, path: Option<&str>) -> CommandResult {
30 dispatch_lifecycle(app, "save", path)
31 }
32
33 fn fork(app: &mut App) -> CommandResult {
34 dispatch_lifecycle(app, "fork", None)
35 }
36
37 fn new_session(app: &mut App, arg: Option<&str>) -> CommandResult {
38 dispatch_lifecycle(app, "new", arg)
39 }
40
41 pub(crate) async fn acknowledge_new_session(app: &mut App, result: &CommandResult) {
42 use codewhale_engine::core::engine::{Engine, EngineConfig};
43 use codewhale_engine::core::ops::Op;
44 let Some(AppAction::NewSession { sync, force, draft }) = result.action.as_ref() else {
45 panic!("expected new-session request");
46 };
47 let config = Config::default();
48 let (engine, handle) = Engine::new(
49 EngineConfig {
50 session_id: app.current_session_id.clone(),
51 model: app.model.clone(),
52 workspace: app.workspace.clone(),
53 snapshots_enabled: false,
54 subagents_enabled: false,
55 plugin_registry: Some(std::sync::Arc::new(
56 codewhale_plugins::PluginRegistry::empty(&app.workspace),
57 )),
58 ..EngineConfig::default()
59 },
60 &config,
61 );
62 let env_ticket = crate::test_support::env_scope_ticket();
63 let runtime = tokio::runtime::Handle::current();
64 let run = tokio::task::spawn_blocking(move || {
65 let _membership = crate::test_support::join_env_scope(env_ticket);
66 runtime.block_on(engine.run())
67 });
68 let control = app.session_sync_control();
69 handle
70 .send(Op::SyncSession {
71 expected: None,
72 control,
73 session_id: app.current_session_id.clone(),
74 messages: app.api_messages.as_ref().clone(),
75 system_prompt: app.system_prompt.clone(),
76 system_prompt_override: false,
77 model: app.model.clone(),
78 workspace: app.workspace.clone(),
79 mode: app.mode,
80 agent_preset: app.agent_preset(),
81 })
82 .await
83 .expect("install current fixture session");
84 handle
85 .get_session_snapshot()
86 .await
87 .expect("current fixture acknowledgement");
88 crate::tui::ui::begin_fresh_session(app, &handle, sync.clone(), *force, draft.clone())
89 .expect("prepare fresh transition");
90 tokio::time::timeout(std::time::Duration::from_secs(5), async {
91 while app.pending_fresh_session.is_some() {
92 crate::tui::ui::poll_fresh_session(app, &handle);
93 tokio::task::yield_now().await;
94 }
95 })
96 .await
97 .expect("fresh Engine acknowledgement");
98 assert_eq!(app.current_session_id, sync.session_id);
99 handle
100 .send(Op::Shutdown)
101 .await
102 .expect("shutdown fixture Engine");
103 run.await.expect("fixture Engine stopped");
104 }
105
106 fn load(app: &mut App, path: Option<&str>) -> CommandResult {
107 dispatch_lifecycle(app, "load", path)
108 }
109
110 fn compact(app: &mut App, arg: Option<&str>) -> CommandResult {
111 dispatch_lifecycle(app, "compact", arg)
112 }
113
114 fn sessions(app: &mut App, arg: Option<&str>) -> CommandResult {
115 dispatch_lifecycle(app, "sessions", arg)
116 }
117
118 fn create_test_app_with_tmpdir(tmpdir: &TempDir) -> App {
119 let options = TuiOptions {
120 skills_dir: tmpdir.path().join("skills"),
121 memory_path: tmpdir.path().join("memory.md"),
122 mcp_config_path: tmpdir.path().join("mcp.json"),
123 ..crate::tui::test_support::test_tui_options(tmpdir.path())
124 };
125 App::new(options, &Config::default())
126 }
127
128 #[test]
129 fn test_save_creates_file_and_sets_session_id() {
130 let tmpdir = TempDir::new().unwrap();
131 let _home = SealedHome::new();
132 let mut app = create_test_app_with_tmpdir(&tmpdir);
133 let save_path = tmpdir.path().join("test_session.json");
134
135 let result = save(&mut app, Some(save_path.to_str().unwrap()));
136 assert!(result.message.is_some());
137 let msg = result.message.unwrap();
138 assert!(msg.contains("Session saved to"));
139 assert!(msg.contains("ID:"));
140 assert!(app.current_session_id.is_some());
141 assert!(save_path.exists());
142 }
143
144 #[test]
145 fn save_preserves_artifact_registry() {
146 let tmpdir = TempDir::new().unwrap();
147 let _home = SealedHome::new();
148 let mut app = create_test_app_with_tmpdir(&tmpdir);
149 let save_path = tmpdir.path().join("artifact_session.json");
150 app.session_artifacts
151 .push(codewhale_runtime::artifacts::ArtifactRecord {
152 id: "art_call_big".to_string(),
153 kind: codewhale_runtime::artifacts::ArtifactKind::ToolOutput,
154 session_id: "artifact-session".to_string(),
155 tool_call_id: "call-big".to_string(),
156 tool_name: "exec_shell".to_string(),
157 created_at: chrono::Utc::now(),
158 byte_size: 512_000,
159 preview: "cargo test output".to_string(),
160 storage_path: tmpdir.path().join("call-big.txt"),
161 });
162
163 let result = save(&mut app, Some(save_path.to_str().unwrap()));
164
165 assert!(!result.is_error);
166 let saved: codewhale_engine::session_manager::SavedSession =
167 serde_json::from_str(&std::fs::read_to_string(save_path).unwrap()).unwrap();
168 assert_eq!(saved.artifacts, app.session_artifacts);
169 }
170
171 #[test]
172 fn save_preserves_latest_auto_route_receipt() {
173 let tmpdir = TempDir::new().unwrap();
174 let _home = SealedHome::new();
175 let mut app = create_test_app_with_tmpdir(&tmpdir);
176 let save_path = tmpdir.path().join("auto_route_session.json");
177 let receipt = codewhale_engine::model_routing::AutoRouteReceipt {
178 tier: codewhale_engine::model_routing::AutoRouteTier::Fast,
179 pair: codewhale_engine::model_routing::AutoRoutePair {
180 strong: codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL.to_string(),
181 fast: Some(
182 codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_TURBO_MODEL.to_string(),
183 ),
184 },
185 scope: codewhale_engine::model_routing::AutoRouteScope::ResolvedProvider,
186 data_path: codewhale_engine::model_routing::AutoRouteDataPath::LocalHeuristic,
187 reason: codewhale_engine::model_routing::AutoRouteReason::LocalFallback(
188 codewhale_engine::model_routing::AutoRouteHeuristicReason::DeclaredDefault,
189 ),
190 decision: None,
191 router_failure: None,
192 };
193 app.set_model_selection("auto".to_string());
194 app.last_effective_provider = Some(codewhale_config::ProviderKind::Zai);
195 app.last_effective_provider_identity = Some("zai".to_string());
196 app.last_effective_model =
197 Some(codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_TURBO_MODEL.to_string());
198 app.last_auto_route_receipt = Some(receipt.clone());
199 app.last_effective_reasoning_effort =
200 Some(codewhale_engine::reasoning_preference::EffectiveReasoningEffort::ThinkingEnabledGranularityUnavailable);
201
202 let result = save(&mut app, Some(save_path.to_str().unwrap()));
203
204 assert!(!result.is_error);
205 let saved: codewhale_engine::session_manager::SavedSession =
206 serde_json::from_str(&std::fs::read_to_string(save_path).unwrap()).unwrap();
207 let route = saved.last_auto_route.expect("latest Auto route");
208 assert_eq!(route.provider, codewhale_config::ProviderKind::Zai);
209 assert_eq!(route.provider_identity, "zai");
210 assert_eq!(
211 route.model,
212 codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_TURBO_MODEL
213 );
214 assert_eq!(route.receipt, receipt);
215 assert_eq!(
216 route.effective_reasoning_effort,
217 Some(codewhale_models::reasoning_effort_tier::ReasoningEffortTier::ThinkingEnabledGranularityUnavailable)
218 );
219 }
220
221 #[test]
222 fn fork_saves_parent_and_switches_to_child_session() {
223 let tmpdir = TempDir::new().unwrap();
224 let _home = SealedHome::new();
225 let mut app = create_test_app_with_tmpdir(&tmpdir);
226 app.set_provider_identity(codewhale_config::ProviderKind::Custom, "lm-studio");
227 app.current_session_id = Some("parent-session".to_string());
228 app.capture_session_fixture_source();
229 let mut cached_parent = create_saved_session_with_id_and_mode(
230 "parent-session".to_string(),
231 &[],
232 &app.model,
233 &app.workspace,
234 0,
235 None,
236 Some(app.mode.label()),
237 )
238 .metadata;
239 cached_parent.title = "Custom Parent".to_string();
240 cached_parent.created_at = "2026-01-02T03:04:05Z"
241 .parse()
242 .expect("fixed parent timestamp");
243 app.current_session_metadata = Some(cached_parent.clone());
244 app.session_title = Some(cached_parent.title.clone());
245 app.api_messages_mut().push(codewhale_models::Message {
246 role: Role::User,
247 content: vec![codewhale_models::ContentBlock::Text {
248 text: "try another path".to_string(),
249 cache_control: None,
250 }],
251 });
252 {
253 let mut todos = app.todos.try_lock().expect("todos lock");
254 todos.add(
255 "preserve fork Work".to_string(),
256 codewhale_engine::tools::todo::TodoStatus::InProgress,
257 );
258 }
259 {
260 let mut plan = app.plan_state.try_lock().expect("plan lock");
261 plan.update(codewhale_engine::tools::plan::UpdatePlanArgs {
262 objective: Some("Fork without Work drift".to_string()),
263 ..codewhale_engine::tools::plan::UpdatePlanArgs::default()
264 });
265 }
266 app.cycle_effort();
267 let expected_work = app
268 .work_state_snapshot()
269 .expect("Work snapshot")
270 .expect("graph-backed Work state");
271 assert!(
272 expected_work.graph.is_some(),
273 "fork fixture must use a graph"
274 );
275
276 let result = fork(&mut app);
277
278 assert!(!result.is_error, "{:?}", result.message);
279 let new_id = app.current_session_id.clone().expect("fork session id");
280 assert_ne!(new_id, "parent-session");
281 assert!(result.message.as_deref().unwrap_or("").contains("Forked"));
282 assert!(matches!(result.action, Some(AppAction::SyncSession { .. })));
283
284 let manager = codewhale_engine::session_manager::SessionManager::default_location().unwrap();
285 let parent = manager
286 .load_session("parent-session")
287 .expect("parent saved");
288 let child = manager.load_session(&new_id).expect("child saved");
289 assert_eq!(parent.messages.len(), 1);
290 assert_eq!(parent.metadata.model_provider, "custom");
291 assert_eq!(
292 parent.metadata.model_provider_id.as_deref(),
293 Some("lm-studio")
294 );
295 assert_eq!(parent.metadata.title, cached_parent.title);
296 assert_eq!(parent.metadata.created_at, cached_parent.created_at);
297 assert_eq!(
298 child.metadata.parent_session_id.as_deref(),
299 Some("parent-session")
300 );
301 assert_eq!(child.metadata.forked_from_message_count, Some(1));
302 assert_eq!(child.metadata.model_provider, "custom");
303 assert_eq!(
304 child.metadata.model_provider_id.as_deref(),
305 Some("lm-studio")
306 );
307 assert_eq!(parent.work_state.as_ref(), Some(&expected_work));
308 assert_eq!(child.work_state.as_ref(), Some(&expected_work));
309 let cached_child = app
310 .current_session_metadata
311 .as_ref()
312 .expect("child metadata cached");
313 assert_eq!(cached_child.id, child.metadata.id);
314 assert_eq!(cached_child.title, child.metadata.title);
315 assert_eq!(cached_child.created_at, child.metadata.created_at);
316 assert_eq!(
317 cached_child.parent_session_id,
318 child.metadata.parent_session_id
319 );
320 assert_eq!(
321 app.session_title.as_deref(),
322 Some(child.metadata.title.as_str())
323 );
324 }
325
326 #[test]
327 fn fork_rejects_active_runtime_without_switching_sessions() {
328 let tmpdir = TempDir::new().unwrap();
329 let _home = SealedHome::new();
330 let mut app = create_test_app_with_tmpdir(&tmpdir);
331 app.current_session_id = Some("parent-session".to_string());
332 app.capture_session_fixture_source();
333 app.api_messages_mut().push(codewhale_models::Message {
334 role: Role::User,
335 content: vec![codewhale_models::ContentBlock::Text {
336 text: "still running".to_string(),
337 cache_control: None,
338 }],
339 });
340 app.is_loading = true;
341
342 let result = fork(&mut app);
343
344 assert!(result.is_error);
345 assert!(result.action.is_none());
346 assert_eq!(app.current_session_id.as_deref(), Some("parent-session"));
347 assert_eq!(app.api_messages.len(), 1);
348 }
349
350 #[tokio::test]
351 async fn new_session_from_resumed_state_creates_distinct_empty_session() {
352 let tmpdir = TempDir::new().unwrap();
353 let _home = SealedHome::new();
354 let mut app = create_test_app_with_tmpdir(&tmpdir);
355 app.current_session_id = Some("old-session".to_string());
356 app.capture_session_fixture_source();
357 app.session_title = Some("Old Session".to_string());
358 app.api_messages_mut().push(codewhale_models::Message {
359 role: Role::User,
360 content: vec![codewhale_models::ContentBlock::Text {
361 text: "continue this thread".to_string(),
362 cache_control: None,
363 }],
364 });
365 app.add_message(HistoryCell::System {
366 content: "old transcript".to_string(),
367 });
368 app.system_prompt = Some(codewhale_models::SystemPrompt::Text(
369 "old prompt".to_string(),
370 ));
371 app.session.total_tokens = 123;
372 app.session.session_cost = 1.25;
373
374 let result = new_session(&mut app, None);
375
376 assert!(!result.is_error, "{:?}", result.message);
377 assert_eq!(app.current_session_id.as_deref(), Some("old-session"));
378 assert_eq!(app.api_messages.len(), 1);
379 assert_eq!(app.session.session_cost, 1.25);
380 assert!(result.message.is_none());
381 acknowledge_new_session(&mut app, &result).await;
382 let new_id = app.current_session_id.clone().expect("new session id");
383 assert_ne!(new_id, "old-session");
384 assert_eq!(app.session_title.as_deref(), Some("New Session"));
385 assert!(app.api_messages.is_empty());
386 assert_eq!(app.history.len(), 1);
387 assert!(
388 matches!(&app.history[0], HistoryCell::System { content } if content.starts_with("Started new session ") && content.contains(&new_id.chars().take(8).collect::<String>()))
389 );
390 assert!(app.system_prompt.is_none());
391 assert_eq!(app.session.total_tokens, 0);
392 assert_eq!(app.session.session_cost, 0.0);
393 assert!(
394 app.visible_notice_text()
395 .as_deref()
396 .unwrap_or_default()
397 .contains("/resume")
398 );
399 match result.action {
400 Some(AppAction::NewSession {
401 sync:
402 codewhale_command_contract::facets::SessionSyncPayload {
403 session_id,
404 messages,
405 system_prompt,
406 ..
407 },
408 force: false,
409 draft: None,
410 }) => {
411 assert_eq!(session_id.as_deref(), Some(new_id.as_str()));
412 assert!(messages.is_empty());
413 assert!(system_prompt.is_none());
414 }
415 other => panic!("expected NewSession action, got {other:?}"),
416 }
417 }
418
419 #[tokio::test]
420 async fn new_session_forgets_denials_and_session_grants() {
421 conversation_reset_forgets_approvals("new").await;
422 }
423
424 #[tokio::test]
425 async fn clear_session_forgets_denials_and_session_grants() {
426 conversation_reset_forgets_approvals("clear").await;
427 }
428
429 async fn conversation_reset_forgets_approvals(command: &str) {
430 // UX-8: a Deny used to outlive `/new` for the whole process ("Restart
431 // Codewhale to reconsider it"); a fresh conversation starts clean.
432 let tmpdir = TempDir::new().unwrap();
433 let _home = SealedHome::new();
434 let mut app = create_test_app_with_tmpdir(&tmpdir);
435 app.current_session_id = Some("old-session".to_string());
436 app.capture_session_fixture_source();
437 app.approval_session_denied
438 .insert("shell:rm -rf build:call-1".to_string());
439 app.approval_session_approved
440 .insert("shell:git status".to_string());
441 // A child agent's pending approval card from the old conversation.
442 let child_id = "agent:agent_a:approval:boot:1";
443 crate::tui::ui::push_approval_request_view(
444 &mut app,
445 child_id,
446 "exec_shell",
447 "agent_a wants to run 'exec_shell'",
448 &serde_json::json!({"command": "cargo build"}),
449 "k",
450 "g",
451 None,
452 codewhale_runtime::config::ApprovalDefaultSelection::Deny,
453 None,
454 );
455 crate::tui::pending_requests::record(
456 &mut app,
457 child_id,
458 crate::tui::pending_requests::PendingChildRequest {
459 agent_id: "agent_a".to_string(),
460 tool_name: "exec_shell".to_string(),
461 description: String::new(),
462 input: serde_json::json!({}),
463 approval_key: "k".to_string(),
464 approval_grouping_key: "g".to_string(),
465 intent_summary: None,
466 requested_at: std::time::Instant::now(),
467 },
468 );
469
470 let result = dispatch_lifecycle(&mut app, command, None);
471
472 if command == "new" {
473 assert!(matches!(result.action, Some(AppAction::NewSession { .. })));
474 assert!(!app.pending_child_requests.is_empty());
475 acknowledge_new_session(&mut app, &result).await;
476 } else {
477 assert!(matches!(result.action, Some(AppAction::SyncSession { .. })));
478 }
479 assert!(
480 app.pending_child_requests.is_empty() && app.view_stack.is_empty(),
481 "an old conversation's child approval card must not follow /{command}"
482 );
483 assert!(
484 app.approval_session_denied.is_empty(),
485 "a denied call must prompt again after /{command}"
486 );
487 assert!(
488 app.approval_session_approved.is_empty(),
489 "an approve-for-session grant must not follow the user into /{command}"
490 );
491 }
492
493 #[test]
494 fn new_session_blocks_unsent_input_without_force() {
495 let tmpdir = TempDir::new().unwrap();
496 let _home = SealedHome::new();
497 let mut app = create_test_app_with_tmpdir(&tmpdir);
498 app.current_session_id = Some("old-session".to_string());
499 app.capture_session_fixture_source();
500 app.input = "draft text".to_string();
501
502 let result = new_session(&mut app, None);
503
504 assert!(result.is_error);
505 assert_eq!(app.current_session_id.as_deref(), Some("old-session"));
506 assert_eq!(app.input, "draft text");
507 assert!(result.action.is_none());
508 assert!(
509 result
510 .message
511 .as_deref()
512 .unwrap_or_default()
513 .contains("/new --force")
514 );
515 }
516
517 #[tokio::test]
518 async fn new_session_force_discards_unsent_input() {
519 let tmpdir = TempDir::new().unwrap();
520 let _home = SealedHome::new();
521 let mut app = create_test_app_with_tmpdir(&tmpdir);
522 app.current_session_id = Some("old-session".to_string());
523 app.capture_session_fixture_source();
524 app.input = "draft text".to_string();
525
526 let result = new_session(&mut app, Some("--force"));
527
528 assert!(!result.is_error, "{:?}", result.message);
529 assert_eq!(app.current_session_id.as_deref(), Some("old-session"));
530 assert_eq!(app.input, "draft text");
531 acknowledge_new_session(&mut app, &result).await;
532 assert_ne!(app.current_session_id.as_deref(), Some("old-session"));
533 assert!(app.input.is_empty());
534 assert!(matches!(
535 result.action,
536 Some(AppAction::NewSession { force: true, .. })
537 ));
538 }
539
540 #[test]
541 fn new_session_blocks_in_flight_turn_without_force() {
542 let tmpdir = TempDir::new().unwrap();
543 let _home = SealedHome::new();
544 let mut app = create_test_app_with_tmpdir(&tmpdir);
545 app.current_session_id = Some("old-session".to_string());
546 app.capture_session_fixture_source();
547 app.is_loading = true;
548
549 let result = new_session(&mut app, None);
550
551 assert!(result.is_error);
552 assert_eq!(app.current_session_id.as_deref(), Some("old-session"));
553 assert!(result.action.is_none());
554 }
555
556 #[test]
557 fn new_session_force_cannot_detach_an_in_flight_turn() {
558 let tmpdir = TempDir::new().unwrap();
559 let _home = SealedHome::new();
560 let mut app = create_test_app_with_tmpdir(&tmpdir);
561 app.current_session_id = Some("old-session".to_string());
562 app.capture_session_fixture_source();
563 app.api_messages_mut().push(codewhale_models::Message {
564 role: Role::User,
565 content: vec![],
566 });
567 app.is_loading = true;
568 app.runtime_turn_status = Some("in_progress".to_string());
569
570 let result = new_session(&mut app, Some("--force"));
571
572 assert!(result.is_error);
573 assert!(result.action.is_none());
574 assert_eq!(app.current_session_id.as_deref(), Some("old-session"));
575 assert_eq!(app.api_messages.len(), 1);
576 let message = result.message.as_deref().unwrap_or_default();
577 assert!(
578 message.contains("Cannot start a new session while runtime work is active"),
579 "{message}"
580 );
581 assert!(
582 message.contains("the session is still busy with the current turn"),
583 "the refusal names the live turn: {message}"
584 );
585 }
586
587 #[test]
588 fn load_rejects_an_active_runtime_before_reading_or_mutating() {
589 let tmpdir = TempDir::new().unwrap();
590 let _home = SealedHome::new();
591 let mut app = create_test_app_with_tmpdir(&tmpdir);
592 app.current_session_id = Some("old-session".to_string());
593 app.capture_session_fixture_source();
594 app.api_messages_mut().push(codewhale_models::Message {
595 role: Role::User,
596 content: vec![],
597 });
598 app.task_panel.push(crate::tui::app::TaskPanelEntry {
599 exit_code: None,
600 id: "queued-late-producer".to_string(),
601 status: "queued".to_string(),
602 prompt_summary: "queued".to_string(),
603 duration_ms: None,
604 kind: crate::tui::app::TaskPanelEntryKind::Background,
605 stale: false,
606 elapsed_since_output_ms: None,
607 owner_agent_id: None,
608 owner_agent_name: None,
609 current_tool: None,
610 role: None,
611 files_touched: 0,
612 });
613
614 let result = load(&mut app, Some("does-not-exist.json"));
615
616 assert!(result.is_error);
617 assert!(result.action.is_none());
618 assert_eq!(app.current_session_id.as_deref(), Some("old-session"));
619 assert_eq!(app.api_messages.len(), 1);
620 assert!(
621 result
622 .message
623 .as_deref()
624 .is_some_and(|message| message.contains("runtime work is active"))
625 );
626 }
627
628 #[test]
629 fn test_save_with_default_path_uses_managed_sessions_dir() {
630 let tmpdir = TempDir::new().unwrap();
631 // The seal points the managed sessions directory inside its own temp dir
632 // rather than the real user home.
633 let home = SealedHome::new();
634 let sessions_dir = home.codewhale_home().join("sessions");
635 std::fs::create_dir_all(&sessions_dir).unwrap();
636 let mut app = create_test_app_with_tmpdir(&tmpdir);
637 let result = save(&mut app, None);
638 assert!(result.message.is_some());
639 let msg = result.message.unwrap();
640 // Give it a moment to ensure file is written
641 std::thread::sleep(std::time::Duration::from_millis(10));
642 let entries: Vec<_> = if sessions_dir.exists() {
643 std::fs::read_dir(&sessions_dir)
644 .unwrap()
645 .filter_map(|e| e.ok())
646 .filter(|e| e.file_name().to_string_lossy().ends_with(".json"))
647 .collect()
648 } else {
649 Vec::new()
650 };
651 // Session should be saved to the managed dir, not the workspace root.
652 assert!(
653 !entries.is_empty(),
654 "expected session file in {sessions_dir:?}, got none; msg: {msg}"
655 );
656 let session_id = app
657 .current_session_id
658 .as_deref()
659 .expect("current session id");
660 assert!(sessions_dir.join(format!("{session_id}.json")).exists());
661 }
662
663 #[test]
664 fn test_save_serialization_error() {
665 let tmpdir = TempDir::new().unwrap();
666 let _home = SealedHome::new();
667 let mut app = create_test_app_with_tmpdir(&tmpdir);
668 // This should work normally since SavedSession is serializable
669 // Testing error path would require mocking, which is complex
670 let save_path = tmpdir.path().join("test.json");
671 let result = save(&mut app, Some(save_path.to_str().unwrap()));
672 assert!(result.message.is_some());
673 }
674
675 #[test]
676 fn test_load_without_path_returns_error() {
677 let tmpdir = TempDir::new().unwrap();
678 let _home = SealedHome::new();
679 let mut app = create_test_app_with_tmpdir(&tmpdir);
680 let result = load(&mut app, None);
681 assert!(result.message.is_some());
682 assert!(result.message.unwrap().contains("Usage: /load"));
683 }
684
685 #[test]
686 fn test_load_nonexistent_file_returns_error() {
687 let tmpdir = TempDir::new().unwrap();
688 let _home = SealedHome::new();
689 let mut app = create_test_app_with_tmpdir(&tmpdir);
690 let result = load(&mut app, Some("nonexistent.json"));
691 assert!(result.message.is_some());
692 assert!(result.message.unwrap().contains("Failed to read"));
693 }
694
695 #[test]
696 fn test_load_invalid_json_returns_error() {
697 let tmpdir = TempDir::new().unwrap();
698 let _home = SealedHome::new();
699 let mut app = create_test_app_with_tmpdir(&tmpdir);
700 let bad_file = tmpdir.path().join("bad.json");
701 std::fs::write(&bad_file, "not valid json").unwrap();
702 let result = load(&mut app, Some(bad_file.to_str().unwrap()));
703 assert!(result.message.is_some());
704 assert!(result.message.unwrap().contains("Failed to parse"));
705 }
706
707 #[test]
708 fn test_load_valid_session_defers_state_restore_to_event_loop() {
709 let tmpdir = TempDir::new().unwrap();
710 let _home = SealedHome::new();
711 let mut app1 = create_test_app_with_tmpdir(&tmpdir);
712 // Set up some state to save
713 app1.api_messages_mut().push(codewhale_models::Message {
714 role: Role::User,
715 content: vec![codewhale_models::ContentBlock::Text {
716 text: "Hello".to_string(),
717 cache_control: None,
718 }],
719 });
720 app1.session.total_tokens = 500;
721 app1.set_mode(AppMode::Plan);
722 let save_path = tmpdir.path().join("test.json");
723 save(&mut app1, Some(save_path.to_str().unwrap()));
724
725 // Create new app and load
726 let mut app2 = create_test_app_with_tmpdir(&tmpdir);
727 app2.system_prompt = Some(codewhale_models::SystemPrompt::Text(
728 "stale prompt from prior session".to_string(),
729 ));
730 app2.session_context_references.push(
731 codewhale_engine::session_manager::SessionContextReference {
732 message_index: 0,
733 reference: codewhale_core::ContextReference {
734 kind: codewhale_core::ContextReferenceKind::File,
735 source: codewhale_core::ContextReferenceSource::AtMention,
736 badge: "file".to_string(),
737 label: "stale.rs".to_string(),
738 target: tmpdir.path().join("stale.rs").display().to_string(),
739 included: true,
740 expanded: true,
741 detail: None,
742 },
743 },
744 );
745 let result = load(&mut app2, Some(save_path.to_str().unwrap()));
746 assert_eq!(result.message, None);
747 assert!(app2.api_messages.is_empty());
748 assert_eq!(app2.session.total_tokens, 0);
749 assert!(app2.current_session_id.is_none());
750 assert!(app2.system_prompt.is_some());
751 assert_eq!(app2.session_context_references.len(), 1);
752 assert!(matches!(
753 result.action,
754 Some(AppAction::LoadSession(path)) if path == save_path
755 ));
756 }
757
758 #[test]
759 fn explicit_save_persists_work_state_and_load_defers_application() {
760 let tmpdir = TempDir::new().unwrap();
761 let _home = SealedHome::new();
762 let mut saved_app = create_test_app_with_tmpdir(&tmpdir);
763 {
764 let mut todos = saved_app.todos.try_lock().expect("todos lock");
765 todos.add(
766 "persist me".to_string(),
767 codewhale_engine::tools::todo::TodoStatus::InProgress,
768 );
769 }
770 {
771 let mut plan = saved_app.plan_state.try_lock().expect("plan lock");
772 plan.update(codewhale_engine::tools::plan::UpdatePlanArgs {
773 objective: Some("Resume exactly".to_string()),
774 ..codewhale_engine::tools::plan::UpdatePlanArgs::default()
775 });
776 }
777 let expected = saved_app.work_state_snapshot().expect("snapshot");
778 let save_path = tmpdir.path().join("work_state.json");
779 let saved = save(&mut saved_app, Some(save_path.to_str().unwrap()));
780 assert!(!saved.is_error, "{:?}", saved.message);
781
782 let mut loaded_app = create_test_app_with_tmpdir(&tmpdir);
783 let loaded = load(&mut loaded_app, Some(save_path.to_str().unwrap()));
784 assert!(!loaded.is_error, "{:?}", loaded.message);
785 assert_eq!(loaded_app.work_state_snapshot().expect("snapshot"), None);
786 assert!(matches!(
787 loaded.action,
788 Some(AppAction::LoadSession(path)) if path == save_path
789 ));
790 let saved_session: codewhale_engine::session_manager::SavedSession =
791 serde_json::from_str(&std::fs::read_to_string(&save_path).expect("saved session file"))
792 .expect("saved session JSON");
793 assert_eq!(saved_session.work_state, expected);
794 }
795
796 #[test]
797 fn new_session_is_all_or_nothing_when_work_state_is_busy() {
798 let tmpdir = TempDir::new().unwrap();
799 let _home = SealedHome::new();
800 let mut app = create_test_app_with_tmpdir(&tmpdir);
801 app.api_messages_mut().push(codewhale_models::Message {
802 role: Role::User,
803 content: vec![],
804 });
805 app.current_session_id = Some("current-session".to_string());
806 app.capture_session_fixture_source();
807 let todos = app.todos.clone();
808 let _held = todos.try_lock().expect("hold todos lock");
809
810 let result = new_session(&mut app, Some("--force"));
811
812 assert!(result.is_error);
813 assert_eq!(app.api_messages.len(), 1);
814 assert_eq!(app.current_session_id.as_deref(), Some("current-session"));
815 assert!(result.action.is_none());
816 }
817
818 #[test]
819 fn load_auto_model_session_defers_model_restore_to_event_loop() {
820 let tmpdir = TempDir::new().unwrap();
821 let _home = SealedHome::new();
822 let mut saved_app = create_test_app_with_tmpdir(&tmpdir);
823 saved_app.set_model_selection("auto".to_string());
824 saved_app.last_effective_model = Some("deepseek-v4-flash".to_string());
825 saved_app.last_effective_reasoning_effort = Some(
826 codewhale_engine::reasoning_preference::EffectiveReasoningEffort::Tier(
827 ReasoningEffort::Low,
828 ),
829 );
830 let save_path = tmpdir.path().join("auto_model.json");
831 save(&mut saved_app, Some(save_path.to_str().unwrap()));
832
833 let mut app = create_test_app_with_tmpdir(&tmpdir);
834 app.set_model_selection("deepseek-v4-flash".to_string());
835 app.reasoning_effort = ReasoningEffort::High;
836 let result = load(&mut app, Some(save_path.to_str().unwrap()));
837
838 assert!(!result.is_error);
839 assert!(!app.auto_model);
840 assert_eq!(app.model, "deepseek-v4-flash");
841 assert_eq!(app.reasoning_effort, ReasoningEffort::High);
842 assert!(matches!(
843 result.action,
844 Some(AppAction::LoadSession(path)) if path == save_path
845 ));
846 }
847
848 #[test]
849 fn load_defers_artifact_registry_restore_to_event_loop() {
850 let tmpdir = TempDir::new().unwrap();
851 let _home = SealedHome::new();
852 let mut saved_app = create_test_app_with_tmpdir(&tmpdir);
853 saved_app
854 .session_artifacts
855 .push(codewhale_runtime::artifacts::ArtifactRecord {
856 id: "art_call_big".to_string(),
857 kind: codewhale_runtime::artifacts::ArtifactKind::ToolOutput,
858 session_id: "artifact-session".to_string(),
859 tool_call_id: "call-big".to_string(),
860 tool_name: "exec_shell".to_string(),
861 created_at: chrono::Utc::now(),
862 byte_size: 128,
863 preview: "checking crate".to_string(),
864 storage_path: tmpdir.path().join("call-big.txt"),
865 });
866 let save_path = tmpdir.path().join("artifact_load.json");
867 save(&mut saved_app, Some(save_path.to_str().unwrap()));
868
869 let mut app = create_test_app_with_tmpdir(&tmpdir);
870 app.session_artifacts
871 .push(codewhale_runtime::artifacts::ArtifactRecord {
872 id: "art_stale".to_string(),
873 kind: codewhale_runtime::artifacts::ArtifactKind::ToolOutput,
874 session_id: "stale-session".to_string(),
875 tool_call_id: "stale".to_string(),
876 tool_name: "exec_shell".to_string(),
877 created_at: chrono::Utc::now(),
878 byte_size: 1,
879 preview: "stale".to_string(),
880 storage_path: tmpdir.path().join("stale.txt"),
881 });
882
883 let result = load(&mut app, Some(save_path.to_str().unwrap()));
884
885 assert!(!result.is_error);
886 assert_eq!(app.session_artifacts.len(), 1);
887 assert_eq!(app.session_artifacts[0].id, "art_stale");
888 assert!(matches!(
889 result.action,
890 Some(AppAction::LoadSession(path)) if path == save_path
891 ));
892 }
893
894 #[test]
895 fn load_defers_telemetry_reset_to_event_loop() {
896 let tmpdir = TempDir::new().unwrap();
897 let _home = SealedHome::new();
898 let mut saved_app = create_test_app_with_tmpdir(&tmpdir);
899 saved_app
900 .api_messages_mut()
901 .push(codewhale_models::Message {
902 role: Role::User,
903 content: vec![codewhale_models::ContentBlock::Text {
904 text: "checkpoint".to_string(),
905 cache_control: None,
906 }],
907 });
908 saved_app.session.total_tokens = 500;
909 let save_path = tmpdir.path().join("checkpoint.json");
910 save(&mut saved_app, Some(save_path.to_str().unwrap()));
911
912 let mut app = create_test_app_with_tmpdir(&tmpdir);
913 app.session.session_cost = 1.25;
914 app.session.session_cost_cny = 9.13;
915 app.session.subagent_cost = 0.75;
916 app.session.subagent_cost_cny = 5.48;
917 app.session.subagent_usage_sources.insert(
918 codewhale_engine::cost_status::usage_source_fingerprint("response-test"),
919 );
920 app.session.displayed_cost_high_water = 2.0;
921 app.session.displayed_cost_high_water_cny = 14.61;
922 app.session.last_prompt_tokens = Some(120);
923 app.session.last_completion_tokens = Some(35);
924 app.session.last_prompt_cache_hit_tokens = Some(80);
925 app.session.last_prompt_cache_miss_tokens = Some(40);
926 app.session.last_reasoning_replay_tokens = Some(12);
927 app.push_turn_cache_record(TurnCacheRecord {
928 provider: None,
929 provider_identity: None,
930 model: None,
931 auto_model: false,
932 input_tokens: 120,
933 output_tokens: 35,
934 cache_hit_tokens: Some(80),
935 cache_miss_tokens: Some(40),
936 reasoning_replay_tokens: Some(12),
937 cache_write_tokens: None,
938 reasoning_tokens: None,
939 cost_audit: None,
940 recorded_at: Instant::now(),
941 });
942
943 let result = load(&mut app, Some(save_path.to_str().unwrap()));
944
945 assert_eq!(result.message, None);
946 assert_eq!(app.session.total_tokens, 0);
947 assert_eq!(app.session.session_cost, 1.25);
948 assert_eq!(app.session.session_cost_cny, 9.13);
949 assert_eq!(app.session.subagent_cost, 0.75);
950 assert_eq!(app.session.subagent_cost_cny, 5.48);
951 assert_eq!(app.session.turn_cache_history.len(), 1);
952 assert!(matches!(
953 result.action,
954 Some(AppAction::LoadSession(path)) if path == save_path
955 ));
956 }
957
958 #[test]
959 fn test_compact_toggles_state() {
960 let tmpdir = TempDir::new().unwrap();
961 let _home = SealedHome::new();
962 let mut app = create_test_app_with_tmpdir(&tmpdir);
963
964 let result = compact(&mut app, None);
965 assert!(result.message.is_some());
966 let msg = result.message.unwrap();
967 assert!(msg.contains("Making room"), "{msg}");
968 assert!(matches!(
969 result.action,
970 Some(AppAction::CompactContext { focus: None })
971 ));
972 }
973
974 #[test]
975 fn compact_command_forwards_a_trimmed_focus_argument() {
976 let tmpdir = TempDir::new().unwrap();
977 let _home = SealedHome::new();
978 let mut app = create_test_app_with_tmpdir(&tmpdir);
979
980 let result = compact(&mut app, Some(" the auth refactor "));
981 assert!(matches!(
982 result.action,
983 Some(AppAction::CompactContext { focus: Some(ref focus) }) if focus == "the auth refactor"
984 ));
985 assert!(
986 result
987 .message
988 .as_deref()
989 .is_some_and(|msg| msg.contains("focus: the auth refactor")),
990 "{result:?}"
991 );
992
993 // Whitespace-only arguments behave like no focus at all.
994 let blank = compact(&mut app, Some(" "));
995 assert!(matches!(
996 blank.action,
997 Some(AppAction::CompactContext { focus: None })
998 ));
999 }
1000
1001 #[test]
1002 fn test_sessions_pushes_picker_view() {
1003 let tmpdir = TempDir::new().unwrap();
1004 let _home = SealedHome::new();
1005 let mut app = create_test_app_with_tmpdir(&tmpdir);
1006 let initial_kind = app.view_stack.top_kind();
1007
1008 let result = sessions(&mut app, None);
1009 assert_eq!(result.message, None);
1010 assert!(result.action.is_none());
1011 // View should have changed (session picker should be on top)
1012 assert_ne!(app.view_stack.top_kind(), initial_kind);
1013 }
1014
1015 #[test]
1016 fn test_sessions_show_subcommand_pushes_picker_view() {
1017 // `/sessions show` and `/sessions list` are explicit aliases
1018 // for the no-arg picker form. Verify they don't fall through
1019 // to the prune branch.
1020 let tmpdir = TempDir::new().unwrap();
1021 let _home = SealedHome::new();
1022 let mut app = create_test_app_with_tmpdir(&tmpdir);
1023 let initial_kind = app.view_stack.top_kind();
1024 let result = sessions(&mut app, Some("show"));
1025 assert_eq!(result.message, None);
1026 assert_ne!(app.view_stack.top_kind(), initial_kind);
1027 }
1028
1029 #[test]
1030 fn test_sessions_prune_requires_days_argument() {
1031 let tmpdir = TempDir::new().unwrap();
1032 let _home = SealedHome::new();
1033 let mut app = create_test_app_with_tmpdir(&tmpdir);
1034 let result = sessions(&mut app, Some("prune"));
1035 assert!(result.is_error);
1036 assert!(
1037 result.message.as_deref().unwrap_or("").contains("usage"),
1038 "expected usage hint: {:?}",
1039 result.message
1040 );
1041 }
1042
1043 #[test]
1044 fn test_sessions_prune_rejects_non_positive_days() {
1045 let tmpdir = TempDir::new().unwrap();
1046 let _home = SealedHome::new();
1047 let mut app = create_test_app_with_tmpdir(&tmpdir);
1048 for bad in ["0", "-3", "abc", "3.14"] {
1049 let result = sessions(&mut app, Some(&format!("prune {bad}")));
1050 assert!(result.is_error, "expected error for `{bad}`");
1051 }
1052 }
1053
1054 #[test]
1055 fn test_sessions_unknown_subcommand_errors() {
1056 let tmpdir = TempDir::new().unwrap();
1057 let _home = SealedHome::new();
1058 let mut app = create_test_app_with_tmpdir(&tmpdir);
1059 let result = sessions(&mut app, Some("teleport"));
1060 assert!(result.is_error);
1061 assert!(
1062 result
1063 .message
1064 .as_deref()
1065 .unwrap_or("")
1066 .contains("unknown subcommand"),
1067 "expected unknown-subcommand error: {:?}",
1068 result.message
1069 );
1070 }
1071
1072 #[test]
1073 fn branch_snapshot_roundtrip_preserves_siblings_ids_stamps_and_engine_projection() {
1074 let root = TempDir::new().unwrap();
1075 let _home = SealedHome::new();
1076 let mut app = create_test_app_with_tmpdir(&root);
1077 let message = |text: &str| codewhale_models::Message {
1078 role: Role::User,
1079 content: vec![codewhale_models::ContentBlock::Text {
1080 text: text.into(),
1081 cache_control: None,
1082 }],
1083 };
1084 for text in ["root", "chosen", "abandoned"] {
1085 app.push_api_message(message(text));
1086 }
1087 assert!(!save(&mut app, None).is_error);
1088 let id = app.current_session_id.clone().unwrap();
1089 let manager = codewhale_engine::session_manager::SessionManager::default_location().unwrap();
1090 let initial = manager.load_session(&id).unwrap();
1091 let original = initial.journal.as_ref().unwrap().entries.clone();
1092 let chosen = original[1].id.clone();
1093 let result = dispatch_lifecycle(&mut app, "branch", Some(&chosen));
1094 assert!(!result.is_error, "{:?}", result.message);
1095 let Some(AppAction::SyncSession {
1096 messages,
1097 session_id,
1098 ..
1099 }) = result.action
1100 else {
1101 panic!("branch must synchronize the existing engine");
1102 };
1103 assert_eq!(session_id.as_deref(), Some(id.as_str()));
1104 assert_eq!(messages, vec![message("root"), message("chosen")]);
1105 assert_eq!(app.api_messages.as_ref(), &messages);
1106 assert!(
1107 !app.history
1108 .iter()
1109 .any(|cell| format!("{cell:?}").contains("abandoned"))
1110 );
1111 app.push_api_message(message("new path"));
1112 for _ in 0..2 {
1113 let snapshot = crate::tui::ui::build_session_snapshot(&mut app, &manager).unwrap();
1114 manager.save_session_owned(snapshot).unwrap();
1115 }
1116 let saved = manager.load_session(&id).unwrap();
1117 let journal = saved.journal.as_ref().unwrap();
1118 assert_eq!(
1119 &journal.entries[..3],
1120 original.as_slice(),
1121 "all old IDs, stamps and content survive"
1122 );
1123 assert_eq!(journal.entries.len(), 4, "a second save appends nothing");
1124 assert_eq!(
1125 journal.entries[3].parent_id.as_deref(),
1126 Some(chosen.as_str())
1127 );
1128 assert_eq!(journal.leaves().len(), 2);
1129 assert_eq!(
1130 saved.messages,
1131 vec![message("root"), message("chosen"), message("new path")]
1132 );
1133 // Restoring and forking must retain the tree as well.
1134 app.restore_api_messages(saved.messages.clone(), &saved);
1135 let forked = fork(&mut app);
1136 assert!(!forked.is_error, "{:?}", forked.message);
1137 let child = manager
1138 .load_session(app.current_session_id.as_deref().unwrap())
1139 .unwrap();
1140 assert_eq!(child.journal.as_ref().unwrap().entries, journal.entries);
1141 assert_eq!(child.metadata.spawn_depth, 1);
1142 let snapshot = crate::tui::ui::build_session_snapshot(&mut app, &manager).unwrap();
1143 assert_eq!(snapshot.journal.unwrap().entries, journal.entries);
1144 }
1145
1146 fn mode_test_message(text: &str) -> codewhale_models::Message {
1147 codewhale_models::Message {
1148 role: Role::User,
1149 content: vec![codewhale_models::ContentBlock::Text {
1150 text: text.to_string(),
1151 cache_control: None,
1152 }],
1153 }
1154 }
1155
1156 fn saved_file_value(path: &std::path::Path) -> serde_json::Value {
1157 serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
1158 }
1159
1160 #[tokio::test]
1161 #[allow(clippy::await_holding_lock)]
1162 async fn new_creator_starts_a_creator_session_and_saves_agent_preset() {
1163 let _available = codewhale_engine::conversation_modes::CreatorAvailabilityGuard::set(None);
1164 let tmpdir = TempDir::new().unwrap();
1165 let _home = SealedHome::new();
1166 let mut app = create_test_app_with_tmpdir(&tmpdir);
1167 app.current_session_id = Some("old-session".to_string());
1168 app.capture_session_fixture_source();
1169
1170 let result = new_session(&mut app, Some("creator"));
1171 assert!(!result.is_error, "{:?}", result.message);
1172 match result.action.as_ref() {
1173 Some(AppAction::NewSession { sync, .. }) => {
1174 assert_eq!(sync.agent_preset.as_deref(), Some("creator"));
1175 }
1176 other => panic!("expected NewSession, got {other:?}"),
1177 }
1178 assert_eq!(
1179 app.conversation_mode, None,
1180 "nothing changes before the Engine acknowledges"
1181 );
1182 acknowledge_new_session(&mut app, &result).await;
1183 assert_eq!(app.conversation_mode.as_deref(), Some("creator"));
1184 assert_eq!(app.agent_preset().as_deref(), Some("creator"));
1185
1186 app.push_api_message(mode_test_message("hello"));
1187 let creator_path = tmpdir.path().join("creator.json");
1188 assert!(!save(&mut app, Some(creator_path.to_str().unwrap())).is_error);
1189 assert_eq!(saved_file_value(&creator_path)["agent_preset"], "creator");
1190
1191 let mut standard = create_test_app_with_tmpdir(&tmpdir);
1192 standard.push_api_message(mode_test_message("hello"));
1193 let standard_path = tmpdir.path().join("standard.json");
1194 assert!(!save(&mut standard, Some(standard_path.to_str().unwrap())).is_error);
1195 assert!(
1196 saved_file_value(&standard_path)
1197 .get("agent_preset")
1198 .is_none()
1199 );
1200 }
1201
1202 #[tokio::test]
1203 #[allow(clippy::await_holding_lock)]
1204 async fn new_without_argument_starts_standard_from_a_creator_session() {
1205 let _available = codewhale_engine::conversation_modes::CreatorAvailabilityGuard::set(None);
1206 let tmpdir = TempDir::new().unwrap();
1207 let _home = SealedHome::new();
1208 let mut app = create_test_app_with_tmpdir(&tmpdir);
1209 app.current_session_id = Some("old-session".to_string());
1210 app.capture_session_fixture_source();
1211 app.install_conversation_mode(Some("creator".to_string()), None);
1212 app.push_api_message(mode_test_message("a creator conversation"));
1213
1214 let result = new_session(&mut app, None);
1215 assert!(!result.is_error, "{:?}", result.message);
1216 match result.action.as_ref() {
1217 Some(AppAction::NewSession { sync, .. }) => assert_eq!(sync.agent_preset, None),
1218 other => panic!("expected NewSession, got {other:?}"),
1219 }
1220 acknowledge_new_session(&mut app, &result).await;
1221 assert_eq!(
1222 app.conversation_mode, None,
1223 "never silently from the last one"
1224 );
1225
1226 let explicit = new_session(&mut app, Some("standard --force"));
1227 match explicit.action.as_ref() {
1228 Some(AppAction::NewSession {
1229 sync, force: true, ..
1230 }) => assert_eq!(sync.agent_preset, None),
1231 other => panic!("expected a forced NewSession, got {other:?}"),
1232 }
1233 }
1234
1235 #[test]
1236 #[allow(clippy::await_holding_lock)]
1237 fn new_with_an_unknown_mode_is_refused_with_the_mode_list_and_changes_nothing() {
1238 let _available = codewhale_engine::conversation_modes::CreatorAvailabilityGuard::set(None);
1239 let tmpdir = TempDir::new().unwrap();
1240 let _home = SealedHome::new();
1241 let mut app = create_test_app_with_tmpdir(&tmpdir);
1242 app.current_session_id = Some("old-session".to_string());
1243 app.capture_session_fixture_source();
1244 app.install_conversation_mode(Some("creator".to_string()), None);
1245
1246 let result = new_session(&mut app, Some("minimal"));
1247 assert!(result.is_error);
1248 let text = result.message.as_deref().unwrap_or_default();
1249 assert!(
1250 text.contains("minimal") && text.contains("standard, creator"),
1251 "{text}"
1252 );
1253 assert!(result.action.is_none());
1254 assert_eq!(app.current_session_id.as_deref(), Some("old-session"));
1255 assert_eq!(app.conversation_mode.as_deref(), Some("creator"));
1256 assert!(app.pending_fresh_session.is_none());
1257
1258 drop(_available);
1259 let _unavailable = codewhale_engine::conversation_modes::CreatorAvailabilityGuard::set(Some(
1260 codewhale_engine::conversation_modes::CREATOR_KEY_OFF_REASON,
1261 ));
1262 let result = new_session(&mut app, Some("creator"));
1263 assert!(result.is_error);
1264 assert!(
1265 result
1266 .message
1267 .as_deref()
1268 .unwrap_or_default()
1269 .contains(codewhale_engine::conversation_modes::CREATOR_KEY_OFF_REASON),
1270 "{:?}",
1271 result.message
1272 );
1273 assert!(result.action.is_none());
1274 }
1275
1275 lines RUST