返回 CodeWhale
runtime_store_binding.rs
根目录 / crates / tui / src / tui / ui / tests / runtime_store_binding.rs
1 use super::*;
2 use codewhale_engine::automation_manager::{
3 AutomationManager, AutomationStatus, CreateAutomationRequest, run_now_shared,
4 };
5 use codewhale_engine::runtime_threads::{
6 manager::RuntimeThreadManager, manager::RuntimeThreadManagerConfig,
7 };
8 use codewhale_engine::task_manager::{TaskManager, TaskManagerConfig};
9
10 fn fixture_config() -> Config {
11 let mut config = Config::default().with_legacy_root(
12 Some("local-runtime-binding-fixture".into()),
13 Some("http://127.0.0.1:1/v1".into()),
14 );
15 config.set_feature("mcp", false).unwrap();
16 config.set_feature("subagents", false).unwrap();
17 config
18 }
19
20 #[tokio::test]
21 async fn runtime_store_binding_persists_on_exit_without_a_model_turn() -> anyhow::Result<()> {
22 // The body is built on the heap (`boxed_phase`) rather than inline: a
23 // switch can now adopt a Runtime store, which grew the load future past
24 // what an inline body holds on libtest's test-thread stack.
25 crate::test_support::boxed_phase(
26 runtime_store_binding_persists_on_exit_without_a_model_turn_body,
27 )
28 .await
29 }
30
31 async fn runtime_store_binding_persists_on_exit_without_a_model_turn_body() -> anyhow::Result<()> {
32 let _environment = crate::test_support::lock_test_env();
33 let root = tempfile::tempdir()?;
34 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", root.path());
35 let _runtime = crate::test_support::EnvVarGuard::remove("CODEWHALE_RUNTIME_DIR");
36 let _legacy = crate::test_support::EnvVarGuard::remove("DEEPSEEK_RUNTIME_DIR");
37 let explicit_store = crate::test_support::EnvVarGuard::set(
38 "CODEWHALE_RUNTIME_DIR",
39 root.path().join("original-runtime"),
40 );
41 let mut config = fixture_config();
42 let sessions = SessionManager::default_location()?;
43 let original = codewhale_engine::session_manager::create_saved_session_with_id_and_mode(
44 "legacy-conversation".into(),
45 &[text_message("user", "retain this earlier conversation")],
46 "deepseek-v4-pro",
47 root.path(),
48 0,
49 None,
50 None,
51 );
52 assert!(original.metadata.runtime_store.is_none());
53 sessions.save_session(&original)?;
54 let checkpoint = sessions.save_checkpoint(&original)?;
55 let checkpoint_before = std::fs::read(&checkpoint)?;
56 let original = sessions.load_session_snapshot(&original.metadata.id)?;
57 let mut app = Box::new(create_test_app());
58 apply_loaded_session_with_goal(&mut app, &mut config, original.clone(), None)
59 .map_err(anyhow::Error::msg)?;
60 let task_config = TaskManagerConfig::from_runtime(&config, root.path().into(), None, Some(1));
61 // Each `TaskManager::start` is a large state machine of its own (the launch
62 // path documents ~1.1 MiB for these). Boxed separately so the two do not
63 // both occupy this body's frame at once.
64 let tasks = {
65 let task_config = task_config.clone();
66 let config = config.clone();
67 let plugin_registry = app.plugin_registry.clone();
68 let session_id = original.metadata.id.clone();
69 crate::test_support::boxed_phase(move || async move {
70 TaskManager::start(task_config, config, plugin_registry, &session_id, None).await
71 })
72 .await?
73 };
74 let binding = tasks
75 .session_store_binding()
76 .expect("attached Runtime store");
77 app.runtime_services.task_manager = Some(tasks.clone());
78 let (handle, actor) =
79 persistence_actor::spawn_persistence_actor(SessionManager::default_location()?);
80 // Match clean exit ordering: no Engine turn, checkpoint or snapshot has
81 // been queued by this host before its TaskManager stops.
82 tasks.shutdown_and_wait().await?;
83 assert!(
84 super::super::event_loop::persist_settled_session_on_shutdown(&mut app, &handle)
85 .map_err(anyhow::Error::msg)?
86 );
87 assert!(handle.try_send(PersistRequest::Shutdown));
88 actor.await?;
89 let saved = sessions.load_session(&original.metadata.id)?;
90 assert_eq!(saved.metadata.runtime_store.as_ref(), Some(&binding));
91 assert_eq!(saved.metadata.title, original.metadata.title);
92 assert_eq!(saved.messages, original.messages);
93 assert!(
94 sessions
95 .load_session_checkpoint(&original.metadata.id)?
96 .is_some()
97 );
98 assert_eq!(std::fs::read(checkpoint)?, checkpoint_before);
99 drop(app);
100 drop(tasks);
101 drop(explicit_store);
102 // Ordinary resume now reopens the same authority without an env override.
103 let resumed = {
104 let saved_id = saved.metadata.id.clone();
105 let saved_binding = saved.metadata.runtime_store.clone();
106 let plugin_root = root.path().to_path_buf();
107 crate::test_support::boxed_phase(move || async move {
108 TaskManager::start(
109 task_config,
110 config,
111 Arc::new(codewhale_plugins::PluginRegistry::empty(&plugin_root)),
112 &saved_id,
113 saved_binding.as_ref(),
114 )
115 .await
116 })
117 .await?
118 };
119 assert_eq!(resumed.execution_scope(), binding.execution_scope);
120 resumed.shutdown_and_wait().await?;
121 Ok(())
122 }
123
124 #[tokio::test]
125 async fn runtime_store_binding_exit_preserves_inflight_recovery() -> anyhow::Result<()> {
126 let _environment = crate::test_support::lock_test_env();
127 let root = tempfile::tempdir()?;
128 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", root.path());
129 let sessions = SessionManager::default_location()?;
130 // U02-09: a locally cancelled turn still owes its terminal event.
131 for (loading, dispatch, cancelled) in [
132 (true, false, false),
133 (false, true, false),
134 (false, false, true),
135 ] {
136 let original = codewhale_engine::session_manager::create_saved_session_with_mode(
137 &[],
138 "deepseek-v4-pro",
139 root.path(),
140 0,
141 None,
142 None,
143 );
144 let path = sessions.save_session(&original)?;
145 let checkpoint = sessions.save_checkpoint(&original)?;
146 let saved_before = std::fs::read(&path)?;
147 let checkpoint_before = std::fs::read(&checkpoint)?;
148 let mut app = Box::new(create_test_app());
149 app.current_session_id = Some(original.metadata.id.clone());
150 app.is_loading = loading;
151 app.dispatch_in_flight = dispatch;
152 app.suppress_stream_events_until_turn_complete = cancelled;
153 let (handle, actor) =
154 persistence_actor::spawn_persistence_actor(SessionManager::default_location()?);
155 assert!(
156 !super::super::event_loop::persist_settled_session_on_shutdown(&mut app, &handle)
157 .map_err(anyhow::Error::msg)?
158 );
159 assert!(handle.try_send(PersistRequest::Shutdown));
160 actor.await?;
161 assert_eq!(std::fs::read(path)?, saved_before);
162 assert_eq!(std::fs::read(checkpoint)?, checkpoint_before);
163 }
164 Ok(())
165 }
166
167 /// #6362: this test used to be one async body. Every debug-build temporary
168 /// of that body — the boxed `App` returns, the cloned `Config`s, two session
169 /// snapshots, the task-manager futures — got its own slot in a single poll
170 /// frame, which alone measured 1.1 MiB on the 2 MiB stack libtest gives a
171 /// test thread (gdb frame attribution, 2026-09-20). The phases below are
172 /// built and boxed through `boxed_phase`, so each phase's temporaries die
173 /// with its own poll frame and the outer body holds pointers; inline
174 /// `async {}` phases measured 806 KiB of never-reused slots on the outer
175 /// frame and still overflowed. The test pins the default budget explicitly
176 /// instead of inheriting CI's 16 MiB `RUST_MIN_STACK`, which is what masked
177 /// the overflow.
178 #[test]
179 fn runtime_store_binding_survives_launch_snapshot_and_resume() -> anyhow::Result<()> {
180 use crate::test_support::boxed_phase;
181
182 crate::test_support::block_on_default_test_stack(|| async {
183 let _environment = crate::test_support::lock_test_env();
184 let root = tempfile::tempdir()?;
185 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", root.path());
186 let _runtime = crate::test_support::EnvVarGuard::remove("CODEWHALE_RUNTIME_DIR");
187 let _legacy = crate::test_support::EnvVarGuard::remove("DEEPSEEK_RUNTIME_DIR");
188 let config = boxed_phase(|| async { Box::new(fixture_config()) }).await;
189 let sessions = SessionManager::default_location()?;
190 let task_config =
191 TaskManagerConfig::from_runtime(&config, root.path().into(), None, Some(1));
192 let (root, config, task_config, sessions) =
193 (&root, config.as_ref(), &task_config, &sessions);
194
195 // Phase 1: launch over a saved conversation and bind its Runtime store.
196 let (initial_id, saved_id, binding, automation) = boxed_phase(move || async move {
197 let mut app = Box::new(create_test_app());
198 app.workspace = root.path().into();
199 let initial_id = super::super::event_loop::ensure_runtime_session_id(&mut app);
200 let tasks = TaskManager::start(
201 task_config.clone(),
202 config.clone(),
203 app.plugin_registry.clone(),
204 &initial_id,
205 None,
206 )
207 .await?;
208 app.runtime_services.task_manager = Some(tasks.clone());
209 // A saved initial conversation may later be deleted while another
210 // launch still refers to its Runtime store.
211 let initial = build_session_snapshot(&mut app, sessions).map_err(anyhow::Error::msg)?;
212 sessions.save_session(&initial)?;
213 let launch = begin_launch_session(&mut app, None);
214 assert!(!launch.is_error, "{:?}", launch.message);
215 assert_ne!(app.current_session_id.as_deref(), Some(initial_id.as_str()));
216 let saved = build_session_snapshot(&mut app, sessions).map_err(anyhow::Error::msg)?;
217 let binding = saved
218 .metadata
219 .runtime_store
220 .clone()
221 .expect("attached host binding");
222 assert_eq!(binding.execution_scope, tasks.execution_scope());
223 sessions.save_session(&saved)?;
224 let mut automations = AutomationManager::open(root.path().join("automations"))?;
225 automations.bind_task_manager(&tasks)?;
226 let automation = automations.create_automation(CreateAutomationRequest {
227 destination_thread_id: None,
228 name: "resumed ownership fixture".into(),
229 prompt: "local fixture only".into(),
230 rrule: "FREQ=HOURLY;INTERVAL=1".into(),
231 cwds: vec![root.path().into()],
232 model: None,
233 model_provider: None,
234 model_provider_id: None,
235 mode: None,
236 allow_shell: Some(false),
237 trust_mode: Some(false),
238 auto_approve: Some(false),
239 delivery_mode: None,
240 status: Some(AutomationStatus::Paused),
241 disallowed_tools: Vec::new(),
242 })?;
243 tasks.shutdown_and_wait().await?;
244 drop(app);
245 drop(tasks);
246 drop(automations);
247 Ok::<_, anyhow::Error>((initial_id, saved.metadata.id.clone(), binding, automation))
248 })
249 .await?;
250 sessions.delete_session(&initial_id)?;
251 assert!(
252 binding.data_dir.is_dir(),
253 "transcript deletion cannot erase Runtime authority"
254 );
255 let loaded = sessions.load_session(&saved_id)?;
256 assert_eq!(loaded.metadata.runtime_store.as_ref(), Some(&binding));
257 let mut resumed_config = boxed_phase(|| async { Box::new(config.clone()) }).await;
258 let (loaded, automation) = (&loaded, &automation);
259
260 // Phase 2: resume with the binding and run the automation for real.
261 {
262 let resumed_config = resumed_config.as_mut();
263 boxed_phase(move || async move {
264 let mut resumed = Box::new(create_test_app());
265 apply_loaded_session_with_goal(&mut resumed, resumed_config, loaded.clone(), None)
266 .map_err(anyhow::Error::msg)?;
267 let tasks = TaskManager::start(
268 task_config.clone(),
269 config.clone(),
270 resumed.plugin_registry.clone(),
271 &loaded.metadata.id,
272 loaded.metadata.runtime_store.as_ref(),
273 )
274 .await?;
275 assert_eq!(
276 tasks.execution_scope(),
277 automation.execution_scope.as_deref().unwrap()
278 );
279 resumed.runtime_services.task_manager = Some(tasks.clone());
280 let automations = Arc::new(tokio::sync::Mutex::new(AutomationManager::open(
281 root.path().join("automations"),
282 )?));
283 // The real Run-now admission must now create its durable
284 // receipt. The configured endpoint is closed loopback and no
285 // shell/tool is authorized.
286 let run = run_now_shared(&automations, &automation.id, &tasks).await?;
287 assert!(run.task_id.is_some(), "{run:?}");
288 assert_eq!(
289 automations
290 .lock()
291 .await
292 .list_runs(&automation.id, None)?
293 .len(),
294 1
295 );
296 assert_eq!(
297 automations
298 .lock()
299 .await
300 .get_automation(&automation.id)?
301 .execution_scope,
302 automation.execution_scope
303 );
304 tasks.shutdown_and_wait().await?;
305 drop(resumed);
306 drop(tasks);
307 Ok::<_, anyhow::Error>(())
308 })
309 .await?;
310 }
311
312 // Phase 3: reproduce the old resume path — deriving a store from the
313 // saved conversation id without its binding opens a foreign scope and
314 // cannot run.
315 // Keep this start future out of the outer poll frame too. Its Config
316 // temporaries otherwise stay on the stack underneath every boxed phase.
317 let foreign = boxed_phase(move || async move {
318 TaskManager::start(
319 task_config.clone(),
320 config.clone(),
321 Arc::new(codewhale_plugins::PluginRegistry::empty(root.path())),
322 &loaded.metadata.id,
323 None,
324 )
325 .await
326 })
327 .await?;
328 let foreign = &foreign;
329 boxed_phase(move || async move {
330 let foreign_automations = Arc::new(tokio::sync::Mutex::new(AutomationManager::open(
331 root.path().join("automations"),
332 )?));
333 let definition_path = root
334 .path()
335 .join("automations/automations")
336 .join(format!("{}.json", automation.id));
337 let before_foreign_run = std::fs::read(&definition_path)?;
338 let error = run_now_shared(&foreign_automations, &automation.id, foreign)
339 .await
340 .unwrap_err();
341 assert!(
342 error
343 .to_string()
344 .contains("another Runtime execution scope"),
345 "{error:#}"
346 );
347 assert_eq!(
348 foreign_automations
349 .lock()
350 .await
351 .list_runs(&automation.id, None)?
352 .len(),
353 1
354 );
355 assert_eq!(std::fs::read(definition_path)?, before_foreign_run);
356 Ok::<_, anyhow::Error>(())
357 })
358 .await?;
359
360 // Phase 4: a host that already owns a foreign scope refuses the switch
361 // and keeps its pending input.
362 {
363 let resumed_config = resumed_config.as_mut();
364 boxed_phase(move || async move {
365 let mut other_app = Box::new(create_test_app());
366 other_app.runtime_services.task_manager = Some(foreign.clone());
367 other_app.input = "preserve pending input".into();
368 let old_id = other_app.current_session_id.clone();
369 // The refusal lives on the switch entry point now, not on the
370 // load function behind it: adoption is the switch's job.
371 let next_config = resumed_config.clone();
372 let error = apply_loaded_session_config_snapshot(
373 &mut other_app,
374 resumed_config,
375 loaded.clone(),
376 next_config,
377 false,
378 )
379 .await
380 .expect_err("a foreign execution scope must refuse");
381 // The refusal must name the route that actually works. "Resume
382 // it in a new Codewhale process" was true but unactionable:
383 // starting a new process and then picking the session from
384 // `/resume` returns here, because that is this same switch
385 // path (#6207, #6225).
386 assert!(
387 error.contains("codewhale resume"),
388 "the refusal must point at the direct-open path: {error}"
389 );
390 assert!(
391 error.contains(&loaded.metadata.id),
392 "the refusal must name the session to open: {error}"
393 );
394 assert_eq!(other_app.current_session_id, old_id);
395 assert_eq!(other_app.input, "preserve pending input");
396 Ok::<_, anyhow::Error>(())
397 })
398 .await?;
399 }
400 foreign.shutdown_and_wait().await?;
401 Ok(())
402 })
403 }
404
405 #[cfg(unix)]
406 #[test]
407 fn runtime_store_binding_retention_does_not_follow_session_directory_symlinks() -> anyhow::Result<()>
408 {
409 let _environment = crate::test_support::lock_test_env();
410 let root = tempfile::tempdir()?;
411 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", root.path());
412 let sessions = SessionManager::default_location()?;
413 let saved = codewhale_engine::session_manager::create_saved_session_with_id_and_mode(
414 "linked-session".into(),
415 &[],
416 "fixture",
417 root.path(),
418 0,
419 None,
420 None,
421 );
422 sessions.save_session(&saved)?;
423 let target = root.path().join("unrelated-directory");
424 std::fs::create_dir_all(&target)?;
425 std::fs::write(target.join("keep.txt"), "preserve user data")?;
426 let link = root.path().join("sessions/linked-session");
427 std::os::unix::fs::symlink(&target, &link)?;
428 sessions.delete_session("linked-session")?;
429 assert!(!link.exists());
430 assert_eq!(
431 std::fs::read_to_string(target.join("keep.txt"))?,
432 "preserve user data"
433 );
434 Ok(())
435 }
436
437 #[test]
438 fn runtime_store_binding_rejects_foreign_missing_or_overridden_store() -> anyhow::Result<()> {
439 let _environment = crate::test_support::lock_test_env();
440 let root = tempfile::tempdir()?;
441 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", root.path());
442 let _runtime = crate::test_support::EnvVarGuard::remove("CODEWHALE_RUNTIME_DIR");
443 let _legacy = crate::test_support::EnvVarGuard::remove("DEEPSEEK_RUNTIME_DIR");
444 let config = fixture_config();
445 let cfg = RuntimeThreadManagerConfig::for_session(root.path().join("tasks"), "original");
446 let runtime = RuntimeThreadManager::open(config.clone(), root.path().into(), cfg.clone())?;
447 let binding = runtime.session_store_binding();
448 drop(runtime);
449 let state_path = binding.data_dir.join("state.json");
450 let before = std::fs::read(&state_path)?;
451 let mut wrong = binding.clone();
452 wrong.execution_scope = "0".repeat(64);
453 let open = |binding: &codewhale_engine::runtime_threads::RuntimeStoreBinding| {
454 RuntimeThreadManager::open_for_session(
455 config.clone(),
456 root.path().into(),
457 cfg.clone(),
458 Arc::new(codewhale_plugins::PluginRegistry::empty(root.path())),
459 Some(binding),
460 )
461 };
462 assert!(
463 open(&wrong)
464 .err()
465 .unwrap()
466 .to_string()
467 .contains("ownership does not match")
468 );
469 assert_eq!(std::fs::read(&state_path)?, before);
470 wrong.data_dir = root.path().join("missing-store");
471 assert!(open(&wrong).is_err());
472 assert!(
473 !wrong.data_dir.exists(),
474 "saved binding cannot create a replacement authority"
475 );
476 let _override = crate::test_support::EnvVarGuard::set(
477 "CODEWHALE_RUNTIME_DIR",
478 root.path().join("foreign-override"),
479 );
480 assert!(
481 open(&binding)
482 .err()
483 .unwrap()
484 .to_string()
485 .contains("override conflicts")
486 );
487 Ok(())
488 }
489
490 #[test]
491 fn missing_runtime_store_recovers_without_reusing_authority_or_resurrecting_stale_binding()
492 -> anyhow::Result<()> {
493 let _environment = crate::test_support::lock_test_env();
494 let root = tempfile::tempdir()?;
495 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", root.path());
496 let _runtime = crate::test_support::EnvVarGuard::remove("CODEWHALE_RUNTIME_DIR");
497 let _legacy = crate::test_support::EnvVarGuard::remove("DEEPSEEK_RUNTIME_DIR");
498 let sessions = SessionManager::default_location()?;
499 let mut saved = codewhale_engine::session_manager::create_saved_session_with_id_and_mode(
500 "interrupted".into(),
501 &[text_message("user", "retain my work")],
502 "deepseek-v4-pro",
503 root.path(),
504 0,
505 None,
506 None,
507 );
508 let missing = codewhale_engine::runtime_threads::RuntimeStoreBinding {
509 data_dir: root.path().join("sessions/previous/runtime"),
510 execution_scope: "0".repeat(64),
511 };
512 saved.metadata.runtime_store = Some(missing.clone());
513 sessions.save_session(&saved)?;
514 let stale = saved.clone();
515 let manager = RuntimeThreadManager::open_for_session(
516 fixture_config(),
517 root.path().into(),
518 RuntimeThreadManagerConfig::for_session(root.path().join("tasks"), "interrupted"),
519 Arc::new(codewhale_plugins::PluginRegistry::empty(root.path())),
520 Some(&missing),
521 )?;
522 let recovered = manager.session_store_binding();
523 assert_ne!(recovered.execution_scope, missing.execution_scope);
524 assert_ne!(recovered.data_dir, missing.data_dir);
525 assert!(!missing.data_dir.exists());
526 assert!(
527 RuntimeThreadManager::open_for_session(
528 fixture_config(),
529 root.path().into(),
530 RuntimeThreadManagerConfig::for_session(root.path().join("tasks"), "interrupted"),
531 Arc::new(codewhale_plugins::PluginRegistry::empty(root.path())),
532 Some(&missing),
533 )
534 .is_err(),
535 "concurrent recovery cannot mint a second owner"
536 );
537 // Losing the process before the repaired binding is saved must leave a
538 // retryable, session-scoped store, not an orphan or a second authority.
539 drop(manager);
540 let manager = RuntimeThreadManager::open_for_session(
541 fixture_config(),
542 root.path().into(),
543 RuntimeThreadManagerConfig::for_session(root.path().join("tasks"), "interrupted"),
544 Arc::new(codewhale_plugins::PluginRegistry::empty(root.path())),
545 Some(&missing),
546 )?;
547 assert_eq!(manager.session_store_binding(), recovered);
548 let other_recovery = RuntimeThreadManager::open_for_session(
549 fixture_config(),
550 root.path().into(),
551 RuntimeThreadManagerConfig::for_session(root.path().join("tasks"), "other-interrupted"),
552 Arc::new(codewhale_plugins::PluginRegistry::empty(root.path())),
553 Some(&missing),
554 )?;
555 assert_ne!(
556 other_recovery.session_store_binding().data_dir,
557 recovered.data_dir
558 );
559 assert_ne!(
560 other_recovery.session_store_binding().execution_scope,
561 recovered.execution_scope
562 );
563 saved.metadata.runtime_store = Some(recovered.clone());
564 sessions.save_session(&saved)?;
565 sessions.save_session(&stale)?;
566 sessions.save_checkpoint(&stale)?;
567 let durable = sessions.load_session("interrupted")?;
568 assert_eq!(durable.metadata.runtime_store, Some(recovered.clone()));
569 assert_eq!(durable.messages, stale.messages);
570 let competing = RuntimeThreadManager::open_for_session(
571 fixture_config(),
572 root.path().into(),
573 RuntimeThreadManagerConfig::for_session(root.path().join("tasks"), "competing"),
574 Arc::new(codewhale_plugins::PluginRegistry::empty(root.path())),
575 None,
576 )?;
577 let mut competing_snapshot = stale.clone();
578 competing_snapshot.metadata.runtime_store = Some(competing.session_store_binding());
579 assert!(sessions.save_session(&competing_snapshot).is_err());
580 assert!(sessions.save_checkpoint(&competing_snapshot).is_err());
581 assert_eq!(
582 sessions.load_session("interrupted")?.metadata.runtime_store,
583 Some(recovered),
584 "another valid owner cannot overwrite the completed recovery"
585 );
586 Ok(())
587 }
588
589 #[test]
590 fn picker_recovers_missing_store_into_the_idle_host_and_persists_before_returning()
591 -> anyhow::Result<()> {
592 // Run on the default 2 MiB test stack with the body boxed: a switch can
593 // now adopt a Runtime store, which grew `apply_loaded_session_with_goal`'s
594 // future past what an inline `#[tokio::test]` body holds. `boxed_phase`
595 // keeps those temporaries in the future's own poll frame, and
596 // `block_on_default_test_stack` pins the budget libtest really gives.
597 crate::test_support::block_on_default_test_stack(|| {
598 crate::test_support::boxed_phase(
599 picker_recovers_missing_store_into_the_idle_host_and_persists_before_returning_body,
600 )
601 })
602 }
603
604 async fn picker_recovers_missing_store_into_the_idle_host_and_persists_before_returning_body()
605 -> anyhow::Result<()> {
606 let _environment = crate::test_support::lock_test_env();
607 let root = tempfile::tempdir()?;
608 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", root.path());
609 let _runtime = crate::test_support::EnvVarGuard::remove("CODEWHALE_RUNTIME_DIR");
610 let _legacy = crate::test_support::EnvVarGuard::remove("DEEPSEEK_RUNTIME_DIR");
611 let sessions = SessionManager::default_location()?;
612 let mut config = fixture_config();
613 let mut saved = codewhale_engine::session_manager::create_saved_session_with_id_and_mode(
614 "picker-interrupted".into(),
615 &[text_message("user", "retain my work")],
616 "deepseek-v4-pro",
617 root.path(),
618 0,
619 None,
620 None,
621 );
622 saved.metadata.runtime_store = Some(codewhale_engine::runtime_threads::RuntimeStoreBinding {
623 data_dir: root.path().join("sessions/previous/runtime"),
624 execution_scope: "0".repeat(64),
625 });
626 sessions.save_session(&saved)?;
627 let saved = sessions.load_session_snapshot("picker-interrupted")?;
628 let mut app = Box::new(create_test_app());
629 let tasks = TaskManager::start(
630 TaskManagerConfig::from_runtime(&config, root.path().into(), None, Some(1)),
631 config.clone(),
632 app.plugin_registry.clone(),
633 "picker-current",
634 None,
635 )
636 .await?;
637 let binding = tasks.session_store_binding().expect("current host");
638 app.runtime_services.task_manager = Some(tasks.clone());
639 app.current_session_id = Some("picker-current".into());
640 app.api_messages_mut()
641 .push(text_message("user", "current conversation"));
642 let current_messages = app.api_messages.clone();
643 let plan_state = app.plan_state.clone();
644 let held = plan_state
645 .try_lock()
646 .expect("hold Work state during recovery");
647 assert!(apply_loaded_session_with_goal(&mut app, &mut config, saved.clone(), None).is_err());
648 assert_eq!(app.current_session_id.as_deref(), Some("picker-current"));
649 assert_eq!(app.api_messages, current_messages);
650 assert_eq!(
651 sessions
652 .load_session("picker-interrupted")?
653 .metadata
654 .runtime_store
655 .as_ref(),
656 Some(&binding),
657 "binding repair survives a contended UI restore"
658 );
659 drop(held);
660 let stale_error = apply_loaded_session_with_goal(&mut app, &mut config, saved.clone(), None)
661 .expect_err("the repaired binding invalidates its original picker source");
662 assert!(
663 stale_error.contains("changed after its captured source"),
664 "{stale_error}"
665 );
666 assert_eq!(app.current_session_id.as_deref(), Some("picker-current"));
667 assert_eq!(app.api_messages, current_messages);
668 let recovered = sessions.load_session_snapshot("picker-interrupted")?;
669 apply_loaded_session_with_goal(&mut app, &mut config, recovered, None)
670 .map_err(anyhow::Error::msg)?;
671 assert_eq!(
672 app.current_session_id.as_deref(),
673 Some("picker-interrupted")
674 );
675 let durable = sessions.load_session("picker-interrupted")?;
676 assert_eq!(durable.metadata.runtime_store.as_ref(), Some(&binding));
677 assert_eq!(durable.messages, saved.messages);
678 assert_eq!(
679 app.current_session_metadata.as_ref().unwrap().runtime_store,
680 Some(binding)
681 );
682 sessions.save_session(&saved)?;
683 assert_eq!(
684 sessions
685 .load_session("picker-interrupted")?
686 .metadata
687 .runtime_store,
688 durable.metadata.runtime_store
689 );
690 tasks.shutdown_and_wait().await?;
691 Ok(())
692 }
693
694 /// #6207: a store that exists but is empty, unheld, and scope-free holds
695 /// nothing a session switch could abandon. A force-quit leaves exactly that
696 /// shape — the directory is on disk, ownerless, with zero events — and
697 /// refusing it left the session unopenable while protecting nothing.
698 #[test]
699 fn adoptable_empty_store_reports_nothing_to_abandon() -> anyhow::Result<()> {
700 let _environment = crate::test_support::lock_test_env();
701 let root = tempfile::tempdir()?;
702 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", root.path());
703 let _runtime = crate::test_support::EnvVarGuard::remove("CODEWHALE_RUNTIME_DIR");
704 let _legacy = crate::test_support::EnvVarGuard::remove("DEEPSEEK_RUNTIME_DIR");
705
706 let store_dir = root.path().join("sessions/interrupted/runtime");
707 // Open a real store, so the layout under test is the product's rather than
708 // the test's idea of it.
709 drop(codewhale_engine::runtime_threads::RuntimeThreadStore::open(
710 store_dir.clone(),
711 )?);
712
713 let binding = codewhale_engine::runtime_threads::RuntimeStoreBinding {
714 data_dir: store_dir.clone(),
715 execution_scope: "0".repeat(64),
716 };
717 assert!(
718 !binding.is_missing_session_store()?,
719 "the store exists, so the old predicate cannot recover it"
720 );
721 assert_eq!(
722 binding.adoption_refusal()?,
723 None,
724 "a freshly opened store holds nothing to abandon"
725 );
726 assert!(
727 !binding.has_live_holder()?,
728 "nobody holds the freshly opened store"
729 );
730 assert!(
731 !binding.has_scope_pinned_automation()?,
732 "no automations exist under the fixture home"
733 );
734 assert!(
735 binding.is_adoptable_empty_store()?,
736 "empty, unheld, scope-free: adoptable"
737 );
738
739 // Each work directory must be load-bearing on its own. If `open` gains a
740 // directory that RUNTIME_STORE_WORK_DIRS misses, this is the assertion that
741 // notices, instead of the miss silently widening what a switch will adopt.
742 for dir in [
743 "threads",
744 "turns",
745 "items",
746 "events",
747 "goals",
748 "agent-mail",
749 "turn-operations",
750 ] {
751 let marker = store_dir.join(dir).join("work.json");
752 std::fs::write(&marker, "{}")?;
753 assert_eq!(
754 binding.adoption_refusal()?,
755 Some(codewhale_engine::runtime_threads::StoreAdoptionRefusal::HasDurableWork { dir }),
756 "{dir} holds work; the store must not be adopted"
757 );
758 assert!(
759 !binding.is_adoptable_empty_store()?,
760 "{dir} blocks the adopt"
761 );
762 std::fs::remove_file(&marker)?;
763 }
764 assert!(
765 binding.is_adoptable_empty_store()?,
766 "markers removed: adoptable again"
767 );
768 Ok(())
769 }
770
771 /// #6418: the binding a live host records is its store's canonical root,
772 /// while the configured sessions root is spelled lexically. When those differ
773 /// (a Windows verbatim prefix or short name, a symlinked home on Unix), the
774 /// hand-built bindings above still pass but every *recorded* binding read as
775 /// unconfined, so an empty, unheld store could never be adopted in-session.
776 #[test]
777 fn recorded_binding_is_confined_under_a_non_canonical_home() -> anyhow::Result<()> {
778 let _environment = crate::test_support::lock_test_env();
779 let root = tempfile::tempdir()?;
780 let real_home = root.path().join("real-home");
781 std::fs::create_dir_all(&real_home)?;
782 #[cfg(unix)]
783 let home = {
784 let linked = root.path().join("linked-home");
785 std::os::unix::fs::symlink(&real_home, &linked)?;
786 linked
787 };
788 // Windows needs no fixture: canonical paths there carry `\\?\`.
789 #[cfg(not(unix))]
790 let home = real_home.clone();
791 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &home);
792 let _runtime = crate::test_support::EnvVarGuard::remove("CODEWHALE_RUNTIME_DIR");
793 let _legacy = crate::test_support::EnvVarGuard::remove("DEEPSEEK_RUNTIME_DIR");
794
795 let runtime = RuntimeThreadManager::open(
796 fixture_config(),
797 home.clone(),
798 RuntimeThreadManagerConfig::for_session(home.join("tasks"), "previous"),
799 )?;
800 let binding = runtime.session_store_binding();
801 drop(runtime);
802
803 #[cfg(unix)]
804 assert!(
805 !binding.data_dir.starts_with(&home),
806 "fixture must record a binding spelled differently from the home"
807 );
808 assert!(
809 !binding.is_missing_session_store()?,
810 "the recorded store exists"
811 );
812 assert!(
813 binding.is_adoptable_empty_store()?,
814 "a recorded, empty, unheld store is confined and adoptable"
815 );
816
817 // Confinement still refuses a store outside the sessions root.
818 let outside = codewhale_engine::runtime_threads::RuntimeStoreBinding {
819 data_dir: root.path().join("elsewhere/previous/runtime"),
820 execution_scope: binding.execution_scope.clone(),
821 };
822 std::fs::create_dir_all(&outside.data_dir)?;
823 assert!(!outside.is_adoptable_empty_store()?);
824 Ok(())
825 }
826
827 /// #6207: the race that reverted the first fix — a live foreign TaskManager
828 /// holds the store while its disk state is still empty, so emptiness alone
829 /// cannot tell abandonment from a holder that has not flushed yet. The
830 /// process-owner lock is held for the manager's lifetime, which is what
831 /// distinguishes the two.
832 #[test]
833 fn adoptable_empty_store_refuses_a_live_holder() -> anyhow::Result<()> {
834 let _environment = crate::test_support::lock_test_env();
835 let root = tempfile::tempdir()?;
836 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", root.path());
837 let _runtime = crate::test_support::EnvVarGuard::remove("CODEWHALE_RUNTIME_DIR");
838 let _legacy = crate::test_support::EnvVarGuard::remove("DEEPSEEK_RUNTIME_DIR");
839
840 let store_dir = root.path().join("sessions/held/runtime");
841 drop(codewhale_engine::runtime_threads::RuntimeThreadStore::open(
842 store_dir.clone(),
843 )?);
844 let binding = codewhale_engine::runtime_threads::RuntimeStoreBinding {
845 data_dir: store_dir.clone(),
846 execution_scope: "0".repeat(64),
847 };
848 assert!(binding.is_adoptable_empty_store()?);
849
850 let _held = codewhale_engine::runtime_threads::RuntimeProcessOwnerLock::acquire(&store_dir)?;
851 assert!(
852 binding.has_live_holder()?,
853 "the held owner lock reads as held"
854 );
855 assert!(
856 !binding.is_adoptable_empty_store()?,
857 "a held store must refuse even while its disk state is empty"
858 );
859 drop(_held);
860 assert!(
861 !binding.has_live_holder()?,
862 "releasing the lock releases the hold"
863 );
864 assert!(
865 binding.is_adoptable_empty_store()?,
866 "unheld again: adoptable"
867 );
868 Ok(())
869 }
870
871 /// #6207: scope-pinned automations are recorded outside the store
872 /// directories, so an otherwise empty store with one bound to its scope
873 /// still refuses — adopting it would orphan their scheduled work.
874 #[test]
875 fn adoptable_empty_store_refuses_a_scope_pinned_automation() -> anyhow::Result<()> {
876 let _environment = crate::test_support::lock_test_env();
877 let root = tempfile::tempdir()?;
878 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", root.path());
879 let _runtime = crate::test_support::EnvVarGuard::remove("CODEWHALE_RUNTIME_DIR");
880 let _legacy = crate::test_support::EnvVarGuard::remove("DEEPSEEK_RUNTIME_DIR");
881
882 let store_dir = root.path().join("sessions/pinned/runtime");
883 drop(codewhale_engine::runtime_threads::RuntimeThreadStore::open(
884 store_dir.clone(),
885 )?);
886 let scope = "ab".repeat(32);
887 let binding = codewhale_engine::runtime_threads::RuntimeStoreBinding {
888 data_dir: store_dir.clone(),
889 execution_scope: scope.clone(),
890 };
891 assert!(binding.is_adoptable_empty_store()?);
892
893 let automations = AutomationManager::open(root.path().join("automations"))?;
894 let created = automations.create_automation(CreateAutomationRequest {
895 destination_thread_id: None,
896 name: "scope fixture".into(),
897 prompt: "local fixture only".into(),
898 rrule: "FREQ=HOURLY;INTERVAL=1".into(),
899 cwds: vec![root.path().into()],
900 model: None,
901 model_provider: None,
902 model_provider_id: None,
903 mode: None,
904 allow_shell: Some(false),
905 trust_mode: Some(false),
906 auto_approve: Some(false),
907 delivery_mode: None,
908 status: Some(AutomationStatus::Paused),
909 disallowed_tools: Vec::new(),
910 })?;
911 automations.edit_automation(&created.id, |record| {
912 let mut record = record.ok_or_else(|| anyhow::anyhow!("fresh automation must exist"))?;
913 record.execution_scope = Some(scope.clone());
914 Ok(Some(record))
915 })?;
916 assert!(
917 binding.has_scope_pinned_automation()?,
918 "the bound automation is visible from the binding's scope"
919 );
920 assert!(
921 !binding.is_adoptable_empty_store()?,
922 "a scope-pinned automation blocks the adopt"
923 );
924 Ok(())
925 }
926
927 /// #6207 end to end: the picker adopts an existing-but-empty unheld store
928 /// into the idle host and persists the repaired binding, the way the
929 /// missing-store path already does.
930 #[test]
931 fn picker_adopts_existing_empty_unheld_store() -> anyhow::Result<()> {
932 // Run on the default 2 MiB test stack with the body boxed: a switch can
933 // now adopt a Runtime store, which grew `apply_loaded_session_with_goal`'s
934 // future past what an inline `#[tokio::test]` body holds. `boxed_phase`
935 // keeps those temporaries in the future's own poll frame, and
936 // `block_on_default_test_stack` pins the budget libtest really gives.
937 crate::test_support::block_on_default_test_stack(|| {
938 crate::test_support::boxed_phase(picker_adopts_existing_empty_unheld_store_body)
939 })
940 }
941
942 async fn picker_adopts_existing_empty_unheld_store_body() -> anyhow::Result<()> {
943 let _environment = crate::test_support::lock_test_env();
944 let root = tempfile::tempdir()?;
945 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", root.path());
946 let _runtime = crate::test_support::EnvVarGuard::remove("CODEWHALE_RUNTIME_DIR");
947 let _legacy = crate::test_support::EnvVarGuard::remove("DEEPSEEK_RUNTIME_DIR");
948 let sessions = SessionManager::default_location()?;
949 let mut config = fixture_config();
950
951 let store_dir = root.path().join("sessions/previous/runtime");
952 drop(codewhale_engine::runtime_threads::RuntimeThreadStore::open(
953 store_dir.clone(),
954 )?);
955 let mut saved = codewhale_engine::session_manager::create_saved_session_with_id_and_mode(
956 "picker-adoptable".into(),
957 &[text_message("user", "retain my work")],
958 "deepseek-v4-pro",
959 root.path(),
960 0,
961 None,
962 None,
963 );
964 saved.metadata.runtime_store = Some(codewhale_engine::runtime_threads::RuntimeStoreBinding {
965 data_dir: store_dir,
966 execution_scope: "0".repeat(64),
967 });
968 sessions.save_session(&saved)?;
969 let saved = sessions.load_session_snapshot("picker-adoptable")?;
970
971 let mut app = Box::new(create_test_app());
972 let tasks = TaskManager::start(
973 TaskManagerConfig::from_runtime(&config, root.path().into(), None, Some(1)),
974 config.clone(),
975 app.plugin_registry.clone(),
976 "picker-current",
977 None,
978 )
979 .await?;
980 let binding = tasks.session_store_binding().expect("current host");
981 app.runtime_services.task_manager = Some(tasks.clone());
982 app.current_session_id = Some("picker-current".into());
983
984 apply_loaded_session_with_goal(&mut app, &mut config, saved.clone(), None)
985 .map_err(anyhow::Error::msg)?;
986 assert_eq!(app.current_session_id.as_deref(), Some("picker-adoptable"));
987 let durable = sessions.load_session("picker-adoptable")?;
988 assert_eq!(durable.metadata.runtime_store.as_ref(), Some(&binding));
989 assert_eq!(durable.messages, saved.messages);
990 // #6144 P1a: the store the conversation left is set aside where it was
991 // abandoned, not left on disk with nothing pointing at it. The switch
992 // hands that off the UI runtime. Moving the store precedes writing its
993 // manifest, so wait for both rather than treating the move as completion.
994 let abandoned = root.path().join("sessions/previous/runtime");
995 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
996 let set_aside = loop {
997 let manifest = std::fs::read_dir(root.path().join("sessions/.set-aside"))
998 .into_iter()
999 .flatten()
1000 .flatten()
1001 .map(|run| {
1002 std::fs::read_to_string(run.path().join("MANIFEST.jsonl")).unwrap_or_default()
1003 })
1004 .collect::<String>();
1005 if (!abandoned.exists() && manifest.contains("previous"))
1006 || std::time::Instant::now() >= deadline
1007 {
1008 break manifest;
1009 }
1010 tokio::time::sleep(std::time::Duration::from_millis(20)).await;
1011 };
1012 assert!(!abandoned.exists());
1013 assert!(set_aside.contains("previous"), "{set_aside}");
1014 tasks.shutdown_and_wait().await?;
1015 Ok(())
1016 }
1017
1018 /// #6144 P1a: an abandoned store another document still binds is kept.
1019 /// Drive on the default 2 MiB test stack, not the caller's.
1020 ///
1021 /// `apply_loaded_session_with_goal` grew past what this test's former
1022 /// `#[tokio::test]` body could hold once a switch could adopt a store: the
1023 /// load call, the task manager it rebinds and the session snapshots all share
1024 /// one poll frame. `block_on_default_test_stack` pins the budget libtest
1025 /// actually gives a test thread, so this fails here rather than in CI's
1026 /// 16 MiB `RUST_MIN_STACK`.
1027 #[test]
1028 fn picker_adoption_keeps_a_store_another_document_binds() -> anyhow::Result<()> {
1029 // `boxed_phase` builds the body future on the heap, so its temporaries
1030 // live in that future's own poll frame instead of being inlined into the
1031 // thread's stack frame.
1032 crate::test_support::block_on_default_test_stack(|| {
1033 crate::test_support::boxed_phase(picker_adoption_keeps_a_store_another_document_binds_body)
1034 })
1035 }
1036
1037 async fn picker_adoption_keeps_a_store_another_document_binds_body() -> anyhow::Result<()> {
1038 let _environment = crate::test_support::lock_test_env();
1039 let root = tempfile::tempdir()?;
1040 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", root.path());
1041 let _runtime = crate::test_support::EnvVarGuard::remove("CODEWHALE_RUNTIME_DIR");
1042 let _legacy = crate::test_support::EnvVarGuard::remove("DEEPSEEK_RUNTIME_DIR");
1043 let sessions = SessionManager::default_location()?;
1044 let mut config = fixture_config();
1045
1046 let store_dir = root.path().join("sessions/previous/runtime");
1047 drop(codewhale_engine::runtime_threads::RuntimeThreadStore::open(
1048 store_dir.clone(),
1049 )?);
1050 let binding =
1051 codewhale_engine::runtime_threads::RuntimeStoreBinding::for_store_dir(&store_dir)?;
1052 let mut saved = codewhale_engine::session_manager::create_saved_session_with_id_and_mode(
1053 "picker-adoptable".into(),
1054 &[text_message("user", "retain my work")],
1055 "deepseek-v4-pro",
1056 root.path(),
1057 0,
1058 None,
1059 None,
1060 );
1061 saved.metadata.runtime_store = Some(binding.clone());
1062 sessions.save_session(&saved)?;
1063 let saved = sessions.load_session_snapshot("picker-adoptable")?;
1064 let mut sibling = codewhale_engine::session_manager::create_saved_session_with_id_and_mode(
1065 "same-host-sibling".into(),
1066 &[text_message("user", "saved in the same host")],
1067 "deepseek-v4-pro",
1068 root.path(),
1069 0,
1070 None,
1071 None,
1072 );
1073 sibling.metadata.runtime_store = Some(binding);
1074 sessions.save_session(&sibling)?;
1075
1076 let mut app = Box::new(create_test_app());
1077 let tasks = TaskManager::start(
1078 TaskManagerConfig::from_runtime(&config, root.path().into(), None, Some(1)),
1079 config.clone(),
1080 app.plugin_registry.clone(),
1081 "picker-current",
1082 None,
1083 )
1084 .await?;
1085 app.runtime_services.task_manager = Some(tasks.clone());
1086 app.current_session_id = Some("picker-current".into());
1087 // Boxed like the other phases here: libtest gives a test thread a 2 MiB
1088 // stack, and the load future's state machine outgrew it once the switch
1089 // gained store adoption (`LoadedSessionOutcome` and its checks).
1090 crate::test_support::boxed_phase(move || async move {
1091 apply_loaded_session_with_goal(&mut app, &mut config, saved, None)
1092 .map_err(anyhow::Error::msg)?;
1093 // Give the background retirement time to (wrongly) act.
1094 tokio::time::sleep(std::time::Duration::from_millis(300)).await;
1095 assert!(store_dir.is_dir(), "the sibling still binds it");
1096 Ok::<_, anyhow::Error>(())
1097 })
1098 .await?;
1099 tasks.shutdown_and_wait().await?;
1100 Ok(())
1101 }
1102
1103 /// A store that holds only finished history is no longer a reason to refuse a
1104 /// switch.
1105 ///
1106 /// The rule this replaces refused any target whose `threads/` directory held a
1107 /// record, so a conversation that had ever run under the Runtime could not be
1108 /// opened from inside a running session even though nothing in it was pending.
1109 /// The switch does not abandon the target — that store stays on disk for
1110 /// whichever process opens it next — so the only question worth asking is
1111 /// whether the store being *left* still needs this process.
1112 #[test]
1113 fn switch_adopts_a_store_holding_finished_history() -> anyhow::Result<()> {
1114 // Run on the default 2 MiB test stack with the body boxed: a switch can
1115 // now adopt a Runtime store, which grew `apply_loaded_session_with_goal`'s
1116 // future past what an inline `#[tokio::test]` body holds. `boxed_phase`
1117 // keeps those temporaries in the future's own poll frame, and
1118 // `block_on_default_test_stack` pins the budget libtest really gives.
1119 crate::test_support::block_on_default_test_stack(|| {
1120 crate::test_support::boxed_phase(switch_adopts_a_store_holding_finished_history_body)
1121 })
1122 }
1123
1124 async fn switch_adopts_a_store_holding_finished_history_body() -> anyhow::Result<()> {
1125 let _environment = crate::test_support::lock_test_env();
1126 let root = tempfile::tempdir()?;
1127 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", root.path());
1128 let _runtime = crate::test_support::EnvVarGuard::remove("CODEWHALE_RUNTIME_DIR");
1129 let _legacy = crate::test_support::EnvVarGuard::remove("DEEPSEEK_RUNTIME_DIR");
1130 let sessions = SessionManager::default_location()?;
1131 let mut config = fixture_config();
1132
1133 // A populated target store: one thread record, which is what
1134 // `first_durable_work_dir` reports as `HasDurableWork { dir: "threads" }`.
1135 let target_store = root.path().join("sessions/populated/runtime");
1136 {
1137 let store = crate::runtime_threads::RuntimeThreadStore::open(target_store.clone())?;
1138 let thread = fixture_thread("thr_finished", config.default_model(), root.path());
1139 store.save_thread(&thread)?;
1140 }
1141 let mut saved = crate::session_manager::create_saved_session_with_id_and_mode(
1142 "populated-target".into(),
1143 &[text_message("user", "long conversation")],
1144 "deepseek-v4-pro",
1145 root.path(),
1146 0,
1147 None,
1148 None,
1149 );
1150 // The real binding, not a fabricated scope: adoption validates the store's
1151 // own owner file, and a made-up scope is the *stale* case (recovered onto
1152 // the current host instead).
1153 saved.metadata.runtime_store = Some(
1154 crate::runtime_threads::RuntimeStoreBinding::for_store_dir(&target_store)?,
1155 );
1156 sessions.save_session(&saved)?;
1157
1158 let mut app = Box::new(create_test_app());
1159 // Boxed: `TaskManager::start` is a large state machine and would otherwise
1160 // share this body's frame with the load-and-adopt call below.
1161 let task_config = TaskManagerConfig::from_runtime(&config, root.path().into(), None, Some(1));
1162 let start_config = config.clone();
1163 let plugin_registry = app.plugin_registry.clone();
1164 let tasks = crate::test_support::boxed_phase(move || async move {
1165 TaskManager::start(
1166 task_config,
1167 start_config,
1168 plugin_registry,
1169 "switch-current",
1170 None,
1171 )
1172 .await
1173 })
1174 .await?;
1175 app.runtime_services.task_manager = Some(tasks.clone());
1176 app.current_session_id = Some("switch-current".into());
1177
1178 // Drive the real entry point, not the load function behind it: adoption is
1179 // what the switch does, so the assertion belongs on the host's owner.
1180 let expected_store = target_store.clone();
1181 let next_config = config.clone();
1182 apply_loaded_session_config_snapshot(&mut app, &mut config, saved, next_config, false)
1183 .await
1184 .map_err(anyhow::Error::msg)?;
1185 assert_eq!(app.current_session_id.as_deref(), Some("populated-target"));
1186 // The host must now own the target store. Compare canonical paths: the
1187 // adopted binding is the store's own canonical root, while the fixture
1188 // path may be the /var symlink.
1189 let held = app
1190 .runtime_services
1191 .task_manager
1192 .as_ref()
1193 .expect("host keeps a manager")
1194 .session_store_binding()
1195 .expect("host holds a store");
1196 let held_dir = held
1197 .data_dir
1198 .canonicalize()
1199 .unwrap_or_else(|_| held.data_dir.clone());
1200 let expected_dir = expected_store
1201 .canonicalize()
1202 .unwrap_or_else(|_| expected_store.clone());
1203 assert_eq!(held_dir, expected_dir, "the host adopted the target store");
1204 assert!(target_store.is_dir(), "the target store is never discarded");
1205 if let Some(tasks) = app.runtime_services.task_manager.clone() {
1206 tasks.shutdown_and_wait().await?;
1207 }
1208 Ok(())
1209 }
1210
1211 /// A refused switch leaves the live session, its workspace and its manager
1212 /// exactly as they were.
1213 ///
1214 /// This is the case the review named: adoption used to run *after* the load had
1215 /// already replaced the session id and metadata, and it took the manager out of
1216 /// the App before trying to open the target. A refusal could therefore strand a
1217 /// host with no manager while the UI showed the new conversation. Adoption is
1218 /// now preflight, so a refusal costs nothing.
1219 #[test]
1220 fn refused_switch_keeps_the_live_session_and_its_manager() -> anyhow::Result<()> {
1221 // Run on the default 2 MiB test stack with the body boxed: a switch can
1222 // now adopt a Runtime store, which grew `apply_loaded_session_with_goal`'s
1223 // future past what an inline `#[tokio::test]` body holds. `boxed_phase`
1224 // keeps those temporaries in the future's own poll frame, and
1225 // `block_on_default_test_stack` pins the budget libtest really gives.
1226 crate::test_support::block_on_default_test_stack(|| {
1227 crate::test_support::boxed_phase(refused_switch_keeps_the_live_session_and_its_manager_body)
1228 })
1229 }
1230
1231 async fn refused_switch_keeps_the_live_session_and_its_manager_body() -> anyhow::Result<()> {
1232 let _environment = crate::test_support::lock_test_env();
1233 let root = tempfile::tempdir()?;
1234 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", root.path());
1235 let _runtime = crate::test_support::EnvVarGuard::remove("CODEWHALE_RUNTIME_DIR");
1236 let _legacy = crate::test_support::EnvVarGuard::remove("DEEPSEEK_RUNTIME_DIR");
1237 let sessions = SessionManager::default_location()?;
1238 let mut config = fixture_config();
1239
1240 let target_store = root.path().join("sessions/target/runtime");
1241 {
1242 let store = crate::runtime_threads::RuntimeThreadStore::open(target_store.clone())?;
1243 store.save_thread(&fixture_thread(
1244 "thr_target",
1245 config.default_model(),
1246 root.path(),
1247 ))?;
1248 }
1249 let mut saved = crate::session_manager::create_saved_session_with_id_and_mode(
1250 "refused-target".into(),
1251 &[text_message("user", "elsewhere")],
1252 "deepseek-v4-pro",
1253 root.path(),
1254 0,
1255 None,
1256 None,
1257 );
1258 saved.metadata.runtime_store = Some(
1259 crate::runtime_threads::RuntimeStoreBinding::for_store_dir(&target_store)?,
1260 );
1261 sessions.save_session(&saved)?;
1262
1263 let mut app = Box::new(create_test_app());
1264 // Boxed: `TaskManager::start` is a large state machine, and it would share
1265 // this body's frame with the load call below.
1266 let task_config = TaskManagerConfig::from_runtime(&config, root.path().into(), None, Some(1));
1267 let start_config = config.clone();
1268 let plugin_registry = app.plugin_registry.clone();
1269 let tasks = crate::test_support::boxed_phase(move || async move {
1270 TaskManager::start(
1271 task_config,
1272 start_config,
1273 plugin_registry,
1274 "waiting-current",
1275 None,
1276 )
1277 .await
1278 })
1279 .await?;
1280 app.runtime_services.task_manager = Some(tasks.clone());
1281 app.current_session_id = Some("waiting-current".into());
1282 app.input = "keep my draft".into();
1283
1284 // Refuse the switch the way a live turn does: `session_transition_blocked`
1285 // is consulted before anything is released, so the failure must cost
1286 // nothing. A request waiting on this process is the other refusal
1287 // (`switch_refuses_while_requests_are_waiting`'s predecessor did not exist;
1288 // the in-memory half is covered by `has_unsettled_requests`).
1289 app.runtime_turn_status = Some("in_progress".to_string());
1290 let current = tasks.session_store_binding().expect("host holds a store");
1291 let next_config = config.clone();
1292 let (mut app, error) = crate::test_support::boxed_phase(move || async move {
1293 let result =
1294 apply_loaded_session_config_snapshot(&mut app, &mut config, saved, next_config, false)
1295 .await;
1296 (app, result)
1297 })
1298 .await;
1299 let error = error.expect_err("a store with an active turn must not be released");
1300 assert!(
1301 error.contains("runtime work is active"),
1302 "the refusal must name the active work: {error}"
1303 );
1304 // Nothing about the live session moved.
1305 assert_eq!(app.current_session_id.as_deref(), Some("waiting-current"));
1306 assert_eq!(app.input, "keep my draft");
1307 let held = app
1308 .runtime_services
1309 .task_manager
1310 .as_ref()
1311 .expect("the manager must survive a refused switch")
1312 .session_store_binding()
1313 .expect("host holds a store");
1314 let held_dir = held
1315 .data_dir
1316 .canonicalize()
1317 .unwrap_or_else(|_| held.data_dir.clone());
1318 let expected_dir = current
1319 .data_dir
1320 .canonicalize()
1321 .unwrap_or_else(|_| current.data_dir.clone());
1322 assert_eq!(held_dir, expected_dir, "the host kept its own store");
1323 app.runtime_turn_status = None;
1324 let binding =
1325 codewhale_engine::runtime_threads::RuntimeStoreBinding::for_store_dir(&target_store)?;
1326 let held_target =
1327 codewhale_engine::runtime_threads::RuntimeProcessOwnerLock::acquire(&target_store)?;
1328 let config = fixture_config();
1329 let error = crate::tui::ui::apply::adopt_runtime_store(&mut app, &config, binding)
1330 .await
1331 .expect_err("a competing store owner must refuse the trial open");
1332 assert!(error.contains("could not be opened"), "{error}");
1333 assert_eq!(app.input, "keep my draft");
1334 assert_eq!(tasks.session_store_binding().as_ref(), Some(&current));
1335 drop(
1336 tasks
1337 .prepare_store_release()
1338 .await?
1339 .expect("old Runtime still admits work"),
1340 );
1341 drop(held_target);
1342 tasks.shutdown_and_wait().await?;
1343 Ok(())
1344 }
1345
1346 /// A minimal durable thread record: enough for `first_durable_work_dir` to see
1347 /// the `threads/` directory as non-empty, which is the whole condition under
1348 /// test. Field values are otherwise inert.
1349 fn fixture_thread(
1350 id: &str,
1351 model: String,
1352 workspace: &std::path::Path,
1353 ) -> crate::runtime_threads::ThreadRecord {
1354 crate::runtime_threads::ThreadRecord {
1355 origin: None,
1356 schema_version: 2,
1357 id: id.to_string(),
1358 created_at: chrono::Utc::now(),
1359 updated_at: chrono::Utc::now(),
1360 model: model.to_string(),
1361 model_provider: None,
1362 model_provider_id: None,
1363 reasoning_effort: None,
1364 allowed_tools: None,
1365 disallowed_tools: Vec::new(),
1366 add_dirs: Vec::new(),
1367 workspace: workspace.to_path_buf(),
1368 mode: "agent".to_string(),
1369 whale_id: None,
1370 child_posture: None,
1371 permission_posture: None,
1372 allow_shell: false,
1373 trust_mode: false,
1374 auto_approve: false,
1375 latest_turn_id: None,
1376 latest_response_bookmark: None,
1377 archived: false,
1378 system_prompt: None,
1379 task_id: None,
1380 title: None,
1381 parent_thread_id: None,
1382 parent_edge_kind: None,
1383 run_id: None,
1384 last_read: None,
1385 session_id: None,
1386 saved_session_checkpoint: None,
1387 executor: None,
1388 environment: None,
1389 agent_preset: None,
1390 }
1391 }
1392
1392 lines RUST