| 1 | use super::*; |
| 2 | |
| 3 | #[tokio::test] |
| 4 | async fn rejected_manual_compaction_route_closes_typed_lifecycle() { |
| 5 | let _env_lock = lock_test_env(); |
| 6 | let _api_key = EnvVarGuard::remove("DEEPSEEK_API_KEY"); |
| 7 | let route_config = { |
| 8 | let __cw_config_init_0_0 = Some("deepseek".to_string()); |
| 9 | let __cw_config_init_0_1 = |
| 10 | Some(codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL.to_string()); |
| 11 | let mut __cw_config_init_0_value: Config = Config::default(); |
| 12 | __cw_config_init_0_value.provider = __cw_config_init_0_0; |
| 13 | __cw_config_init_0_value.default_text_model = __cw_config_init_0_1; |
| 14 | __cw_config_init_0_value |
| 15 | } |
| 16 | .with_legacy_root(Some(String::new()), None); |
| 17 | let route = resolve_runtime_route( |
| 18 | &route_config, |
| 19 | ProviderKind::Deepseek, |
| 20 | Some(codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL), |
| 21 | ) |
| 22 | .expect("structurally resolve route without credential"); |
| 23 | assert!( |
| 24 | route.clone().validate().is_err(), |
| 25 | "fixture must fail at engine route installation" |
| 26 | ); |
| 27 | let (mut engine, handle) = Engine::new(EngineConfig::default(), &route_config); |
| 28 | |
| 29 | engine |
| 30 | .handle_manual_compaction_op( |
| 31 | "compact-route-invalid".to_string(), |
| 32 | route, |
| 33 | CompactionConfig::default(), |
| 34 | ) |
| 35 | .await; |
| 36 | |
| 37 | let mut started_id = None; |
| 38 | let mut failed_id = None; |
| 39 | let mut order = Vec::new(); |
| 40 | let mut events = handle.rx_event.write().await; |
| 41 | while let Ok(event) = events.try_recv() { |
| 42 | match event { |
| 43 | Event::CompactionStarted { id, auto, .. } => { |
| 44 | assert!(!auto); |
| 45 | started_id = Some(id); |
| 46 | order.push("started"); |
| 47 | } |
| 48 | Event::CompactionFailed { id, auto, message } => { |
| 49 | assert!(!auto); |
| 50 | assert!(message.contains("provider route is not ready")); |
| 51 | failed_id = Some(id); |
| 52 | order.push("failed"); |
| 53 | } |
| 54 | Event::Error { .. } => order.push("error"), |
| 55 | Event::TurnComplete { |
| 56 | turn_id, |
| 57 | submission_id, |
| 58 | compaction_id, |
| 59 | status, |
| 60 | .. |
| 61 | } => { |
| 62 | assert!(turn_id.is_none()); |
| 63 | assert!(submission_id.is_none()); |
| 64 | assert_eq!(compaction_id.as_deref(), Some("compact-route-invalid")); |
| 65 | assert_eq!(status, TurnOutcomeStatus::Failed); |
| 66 | order.push("terminal"); |
| 67 | } |
| 68 | _ => {} |
| 69 | } |
| 70 | } |
| 71 | assert_eq!(order, ["started", "failed", "error", "terminal"]); |
| 72 | assert_eq!(started_id, failed_id); |
| 73 | } |
| 74 | |
| 75 | #[tokio::test] |
| 76 | async fn queued_manual_compaction_cancellation_is_idempotent_and_skips_route_activation() { |
| 77 | let _env_lock = lock_test_env(); |
| 78 | let _api_key = EnvVarGuard::remove("DEEPSEEK_API_KEY"); |
| 79 | let route_config = { |
| 80 | let __cw_config_init_1_0 = Some("deepseek".to_string()); |
| 81 | let __cw_config_init_1_1 = |
| 82 | Some(codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL.to_string()); |
| 83 | let mut __cw_config_init_1_value: Config = Config::default(); |
| 84 | __cw_config_init_1_value.provider = __cw_config_init_1_0; |
| 85 | __cw_config_init_1_value.default_text_model = __cw_config_init_1_1; |
| 86 | __cw_config_init_1_value |
| 87 | } |
| 88 | .with_legacy_root(Some(String::new()), None); |
| 89 | let route = resolve_runtime_route( |
| 90 | &route_config, |
| 91 | ProviderKind::Deepseek, |
| 92 | Some(codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL), |
| 93 | ) |
| 94 | .expect("structurally resolve route without credential"); |
| 95 | let (mut engine, handle) = Engine::new(EngineConfig::default(), &route_config); |
| 96 | let id = "compact-cancel-before-start"; |
| 97 | let before = engine.session_snapshot(); |
| 98 | |
| 99 | handle.cancel_compaction(id).expect("first cancel accepted"); |
| 100 | handle |
| 101 | .cancel_compaction(id) |
| 102 | .expect("replayed cancel remains idempotent"); |
| 103 | engine |
| 104 | .handle_manual_compaction_op(id.to_string(), route, CompactionConfig::default()) |
| 105 | .await; |
| 106 | |
| 107 | assert_eq!(engine.session_snapshot(), before); |
| 108 | |
| 109 | let mut events = handle.rx_event.write().await; |
| 110 | let drained = std::iter::from_fn(|| events.try_recv().ok()).collect::<Vec<_>>(); |
| 111 | assert!(matches!( |
| 112 | drained.as_slice(), |
| 113 | [ |
| 114 | Event::CompactionCancelled { id: cancelled, auto: false, .. }, |
| 115 | Event::TurnComplete { turn_id: None, submission_id: None, |
| 116 | compaction_id: Some(terminal), status: TurnOutcomeStatus::Interrupted, .. } |
| 117 | ] if cancelled == id && terminal == id |
| 118 | )); |
| 119 | assert!( |
| 120 | !drained |
| 121 | .iter() |
| 122 | .any(|event| matches!(event, Event::Error { .. })), |
| 123 | "pre-start cancellation must not activate or validate the provider route" |
| 124 | ); |
| 125 | |
| 126 | let retry = engine |
| 127 | .claim_compaction(id) |
| 128 | .expect("the same stable id can be retried after terminal settlement"); |
| 129 | assert!(!retry.is_cancelled()); |
| 130 | handle |
| 131 | .cancel_compaction(id) |
| 132 | .expect("running cancel accepted"); |
| 133 | assert!( |
| 134 | retry.is_cancelled(), |
| 135 | "running cancellation reaches its token" |
| 136 | ); |
| 137 | engine.finish_compaction(id); |
| 138 | } |
| 139 | |
| 140 | #[tokio::test] |
| 141 | #[allow(clippy::await_holding_lock)] |
| 142 | async fn terminal_correlation_preflight_failures_keep_each_submitted_owner() { |
| 143 | let _env_lock = lock_test_env(); |
| 144 | let _api_key = EnvVarGuard::remove("DEEPSEEK_API_KEY"); |
| 145 | let workspace = tempdir().expect("isolated workspace"); |
| 146 | let route_config = { |
| 147 | let __cw_config_init_2_0 = Some("deepseek".to_string()); |
| 148 | let __cw_config_init_2_1 = |
| 149 | Some(codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL.to_string()); |
| 150 | let mut __cw_config_init_2_value: Config = Config::default(); |
| 151 | __cw_config_init_2_value.provider = __cw_config_init_2_0; |
| 152 | __cw_config_init_2_value.default_text_model = __cw_config_init_2_1; |
| 153 | __cw_config_init_2_value |
| 154 | } |
| 155 | .with_legacy_root(Some(String::new()), None); |
| 156 | let invalid_route = resolve_runtime_route( |
| 157 | &route_config, |
| 158 | ProviderKind::Deepseek, |
| 159 | Some(codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL), |
| 160 | ) |
| 161 | .expect("structurally resolved route"); |
| 162 | assert!( |
| 163 | invalid_route.clone().validate().is_err(), |
| 164 | "fixture must fail at engine route installation" |
| 165 | ); |
| 166 | let (engine, handle) = |
| 167 | Engine::new(deterministic_engine_config(workspace.path()), &route_config); |
| 168 | let task = tokio::spawn(engine.run()); |
| 169 | for submission in [None, Some("sub-route-rejected")] { |
| 170 | let mut op = external_user_message_op("invalid route", AppMode::Agent, &Config::default()); |
| 171 | if let Op::SendMessage(TurnSpec { |
| 172 | route, |
| 173 | provenance, |
| 174 | submission_id, |
| 175 | .. |
| 176 | }) = &mut op |
| 177 | { |
| 178 | **route = invalid_route.clone(); |
| 179 | *submission_id = submission.map(str::to_string); |
| 180 | if submission.is_none() { |
| 181 | *provenance = UserInputProvenance::Runtime; |
| 182 | } |
| 183 | } |
| 184 | handle.send(op).await.expect("queue route rejection"); |
| 185 | } |
| 186 | handle |
| 187 | .send(Op::EditLastTurn { |
| 188 | new_message: "rejected edit".into(), |
| 189 | submission_id: Some("sub-edit-rejected".into()), |
| 190 | }) |
| 191 | .await |
| 192 | .expect("queue rejected edit"); |
| 193 | handle |
| 194 | .send(Op::CompactContext { |
| 195 | id: "compact-after-rejections".into(), |
| 196 | route: Box::new(invalid_route), |
| 197 | compaction: Box::new(CompactionConfig::default()), |
| 198 | }) |
| 199 | .await |
| 200 | .expect("queue compaction rejection"); |
| 201 | let expected = [ |
| 202 | (None, None), |
| 203 | (Some("sub-route-rejected"), None), |
| 204 | (Some("sub-edit-rejected"), None), |
| 205 | (None, Some("compact-after-rejections")), |
| 206 | ]; |
| 207 | let mut terminal_count = 0; |
| 208 | { |
| 209 | let mut rx = handle.rx_event.write().await; |
| 210 | while terminal_count < expected.len() { |
| 211 | let event = tokio::time::timeout(model_turn_event_timeout(), rx.recv()) |
| 212 | .await |
| 213 | .expect("every rejected operation must settle") |
| 214 | .expect("engine event"); |
| 215 | match event { |
| 216 | Event::TurnStarted { .. } => panic!("preflight rejections must not start turns"), |
| 217 | Event::TurnComplete { |
| 218 | turn_id, |
| 219 | submission_id, |
| 220 | compaction_id, |
| 221 | status, |
| 222 | error, |
| 223 | .. |
| 224 | } => { |
| 225 | assert!(turn_id.is_none()); |
| 226 | assert_eq!( |
| 227 | (submission_id.as_deref(), compaction_id.as_deref()), |
| 228 | expected[terminal_count] |
| 229 | ); |
| 230 | assert_eq!(status, TurnOutcomeStatus::Failed); |
| 231 | assert!(error.is_some()); |
| 232 | terminal_count += 1; |
| 233 | } |
| 234 | _ => {} |
| 235 | } |
| 236 | } |
| 237 | } |
| 238 | handle.send(Op::Shutdown).await.expect("shutdown"); |
| 239 | task.await.expect("engine task"); |
| 240 | let mut rx = handle.rx_event.write().await; |
| 241 | assert!( |
| 242 | !std::iter::from_fn(|| rx.try_recv().ok()).any(|event| matches!( |
| 243 | event, |
| 244 | Event::TurnStarted { .. } | Event::TurnComplete { .. } |
| 245 | )), |
| 246 | "each rejected operation has exactly one terminal and no provider turn" |
| 247 | ); |
| 248 | } |
| 249 | |
| 250 | #[tokio::test] |
| 251 | async fn terminal_correlation_started_failure_matches_its_original_submission() { |
| 252 | let workspace = tempdir().expect("isolated workspace"); |
| 253 | let model = std::sync::Arc::new(FailingGoalModelClient { |
| 254 | calls: std::sync::atomic::AtomicUsize::new(0), |
| 255 | message: "deterministic terminal correlation failure".into(), |
| 256 | }); |
| 257 | let client: crate::core::model_client::SharedModelClient = model.clone(); |
| 258 | let (engine, handle) = Engine::new_with_model_client( |
| 259 | deterministic_engine_config(workspace.path()), |
| 260 | &Config::default(), |
| 261 | client, |
| 262 | ); |
| 263 | let task = tokio::spawn(engine.run()); |
| 264 | handle |
| 265 | .send(external_user_message_op_with_submission( |
| 266 | "fail this turn", |
| 267 | AppMode::Agent, |
| 268 | &Config::default(), |
| 269 | Some("sub-started-failure".into()), |
| 270 | )) |
| 271 | .await |
| 272 | .expect("submit"); |
| 273 | let mut started = None; |
| 274 | { |
| 275 | let mut rx = handle.rx_event.write().await; |
| 276 | loop { |
| 277 | let event = tokio::time::timeout(model_turn_event_timeout(), rx.recv()) |
| 278 | .await |
| 279 | .expect("failed model turn must settle") |
| 280 | .expect("engine event"); |
| 281 | match event { |
| 282 | Event::TurnStarted { |
| 283 | turn_id, |
| 284 | submission_id, |
| 285 | .. |
| 286 | } => { |
| 287 | assert!(started.is_none(), "exactly one start"); |
| 288 | assert_eq!(submission_id.as_deref(), Some("sub-started-failure")); |
| 289 | started = Some(turn_id); |
| 290 | } |
| 291 | Event::TurnComplete { |
| 292 | turn_id, |
| 293 | submission_id, |
| 294 | compaction_id, |
| 295 | status, |
| 296 | error, |
| 297 | .. |
| 298 | } => { |
| 299 | assert!(started.is_some()); |
| 300 | assert_eq!(turn_id, started); |
| 301 | assert_eq!(submission_id.as_deref(), Some("sub-started-failure")); |
| 302 | assert!(compaction_id.is_none()); |
| 303 | assert_eq!(status, TurnOutcomeStatus::Failed); |
| 304 | assert!( |
| 305 | error |
| 306 | .as_deref() |
| 307 | .is_some_and(|s| s.contains("terminal correlation failure")) |
| 308 | ); |
| 309 | break; |
| 310 | } |
| 311 | _ => {} |
| 312 | } |
| 313 | } |
| 314 | } |
| 315 | handle.send(Op::Shutdown).await.expect("shutdown"); |
| 316 | task.await.expect("engine task"); |
| 317 | assert_eq!(model.calls.load(std::sync::atomic::Ordering::SeqCst), 1); |
| 318 | let mut rx = handle.rx_event.write().await; |
| 319 | assert!( |
| 320 | !std::iter::from_fn(|| rx.try_recv().ok()).any(|event| matches!( |
| 321 | event, |
| 322 | Event::TurnStarted { .. } | Event::TurnComplete { .. } |
| 323 | )), |
| 324 | "a model failure must not produce a second terminal" |
| 325 | ); |
| 326 | } |
| 327 | |
| 328 | struct BlockingEmergencyCompactionModelClient { |
| 329 | entered: std::sync::Arc<tokio::sync::Notify>, |
| 330 | request_dropped: std::sync::Arc<std::sync::atomic::AtomicBool>, |
| 331 | } |
| 332 | |
| 333 | #[tokio::test] |
| 334 | async fn failed_emergency_compaction_preserves_history_instead_of_trimming() { |
| 335 | use crate::llm_client::mock::MockLlmClient; |
| 336 | let _env_lock = lock_test_env(); |
| 337 | let workspace = tempdir().unwrap(); |
| 338 | // Emergency compaction persists a checkpoint before calling the model. |
| 339 | // Keep that prerequisite away from other tests' shared state fixtures so |
| 340 | // this exercises a summary failure, rather than an unrelated write failure. |
| 341 | let _home = EnvVarGuard::set("CODEWHALE_HOME", workspace.path()); |
| 342 | let (mut engine, handle) = Engine::new( |
| 343 | deterministic_engine_config(workspace.path()), |
| 344 | &Config::default(), |
| 345 | ); |
| 346 | engine.session.messages = (0..12) |
| 347 | .map(|i| Message { |
| 348 | role: if i % 2 == 0 { |
| 349 | Role::User |
| 350 | } else { |
| 351 | Role::Assistant |
| 352 | }, |
| 353 | content: vec![ContentBlock::Text { |
| 354 | text: format!( |
| 355 | "must preserve instruction and evidence {i}: {}", |
| 356 | "x".repeat(20_000) |
| 357 | ), |
| 358 | cache_control: None, |
| 359 | }], |
| 360 | }) |
| 361 | .collect::<Vec<_>>() |
| 362 | .into(); |
| 363 | let before = engine.session.messages.clone(); |
| 364 | let summary = engine.session.compaction_summary_prompt.clone(); |
| 365 | let client = MockLlmClient::new(Vec::new()); |
| 366 | let tools = vec![catalog_tool("read")]; |
| 367 | let mut turn = TurnContext::new(1); |
| 368 | assert!( |
| 369 | !engine |
| 370 | .recover_context_overflow( |
| 371 | &client, |
| 372 | Some(&tools), |
| 373 | "provider rejection fixture", |
| 374 | &mut turn |
| 375 | ) |
| 376 | .await |
| 377 | ); |
| 378 | assert_eq!(engine.session.messages.as_slice(), before.as_slice()); |
| 379 | assert_eq!(engine.session.compaction_summary_prompt, summary); |
| 380 | let mut events = handle.rx_event.write().await; |
| 381 | let drained = std::iter::from_fn(|| events.try_recv().ok()).collect::<Vec<_>>(); |
| 382 | assert_eq!( |
| 383 | client.call_count(), |
| 384 | 1, |
| 385 | "a deterministic summary failure is not retried unchanged: {drained:?}" |
| 386 | ); |
| 387 | let requests = client.captured_requests(); |
| 388 | assert_eq!(requests[0].tools.as_deref(), Some(tools.as_slice())); |
| 389 | assert_eq!(requests[0].tool_choice, Some(default_tool_choice(false))); |
| 390 | assert_eq!(requests[0].system, engine.session.system_prompt); |
| 391 | } |
| 392 | |
| 393 | #[tokio::test] |
| 394 | async fn manual_compaction_accounts_accepted_and_rejected_responses_once() { |
| 395 | use wiremock::matchers::{method, path}; |
| 396 | use wiremock::{Mock, MockServer, ResponseTemplate}; |
| 397 | |
| 398 | let _env_lock = lock_test_env(); |
| 399 | let _cost_scope = crate::cost_status::test_scope(); |
| 400 | let workspace = tempdir().expect("isolated compaction workspace"); |
| 401 | let _home = EnvVarGuard::set("CODEWHALE_HOME", workspace.path()); |
| 402 | for (finish_reason, expected_status) in [ |
| 403 | ("stop", TurnOutcomeStatus::Completed), |
| 404 | ("length", TurnOutcomeStatus::Failed), |
| 405 | ] { |
| 406 | let server = MockServer::start().await; |
| 407 | Mock::given(method("POST")) |
| 408 | .and(path("/v1/chat/completions")) |
| 409 | .respond_with(ResponseTemplate::new(200).set_body_json(json!({ |
| 410 | "id": format!("compaction-{finish_reason}"), |
| 411 | "object": "chat.completion", |
| 412 | "model": codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL, |
| 413 | "choices": [{ |
| 414 | "index": 0, |
| 415 | "message": { "role": "assistant", "content": "Primary request: preserve the session migration. Completed: inspected the existing store. Constraints: keep every user message and failing test. Next: finish the transactional migration and rerun session_store::roundtrip." }, |
| 416 | "finish_reason": finish_reason, |
| 417 | }], |
| 418 | "usage": { "prompt_tokens": 41, "completion_tokens": 7, "total_tokens": 48 }, |
| 419 | }))) |
| 420 | .expect(1) |
| 421 | .mount(&server) |
| 422 | .await; |
| 423 | let route_config = { |
| 424 | let __cw_config_init_3_0 = Some("deepseek".to_string()); |
| 425 | let mut __cw_config_init_3_value: Config = Config::default(); |
| 426 | __cw_config_init_3_value.provider = __cw_config_init_3_0; |
| 427 | __cw_config_init_3_value |
| 428 | } |
| 429 | .with_legacy_root( |
| 430 | Some("fixture-key".to_string()), |
| 431 | Some(format!("{}/v1", server.uri())), |
| 432 | ); |
| 433 | let (mut engine, handle) = Engine::new( |
| 434 | EngineConfig { |
| 435 | workspace: workspace.path().to_path_buf(), |
| 436 | snapshots_enabled: false, |
| 437 | subagents_enabled: false, |
| 438 | ..EngineConfig::default() |
| 439 | }, |
| 440 | &route_config, |
| 441 | ); |
| 442 | engine.session.messages.push(Message { |
| 443 | role: Role::User, |
| 444 | content: vec![ContentBlock::Text { |
| 445 | text: "Preserve the transactional session migration.".to_string(), |
| 446 | cache_control: None, |
| 447 | }], |
| 448 | }); |
| 449 | engine.config.goal_state.lock().unwrap().replace( |
| 450 | "Finish the session migration", |
| 451 | Some(1000), |
| 452 | None, |
| 453 | ); |
| 454 | engine |
| 455 | .handle_manual_compaction("compact-accounting".to_string(), CancellationToken::new()) |
| 456 | .await; |
| 457 | |
| 458 | assert_eq!(engine.session.total_usage.input_tokens, 41); |
| 459 | assert_eq!(engine.session.total_usage.output_tokens, 7); |
| 460 | assert_eq!( |
| 461 | engine |
| 462 | .config |
| 463 | .goal_state |
| 464 | .lock() |
| 465 | .unwrap() |
| 466 | .snapshot() |
| 467 | .tokens_used, |
| 468 | 48 |
| 469 | ); |
| 470 | let mut events = handle.rx_event.write().await; |
| 471 | let mut telemetry_count = 0; |
| 472 | let mut terminal_count = 0; |
| 473 | while let Ok(event) = events.try_recv() { |
| 474 | match event { |
| 475 | Event::RoutedTurnUsage { usage, .. } => { |
| 476 | telemetry_count += 1; |
| 477 | assert_eq!((usage.input_tokens, usage.output_tokens), (41, 7)); |
| 478 | } |
| 479 | Event::TurnComplete { |
| 480 | usage, |
| 481 | parent_route_usage, |
| 482 | status, |
| 483 | .. |
| 484 | } => { |
| 485 | terminal_count += 1; |
| 486 | assert_eq!((usage.input_tokens, usage.output_tokens), (41, 7)); |
| 487 | assert_eq!(parent_route_usage, Usage::default()); |
| 488 | assert_eq!(status, expected_status); |
| 489 | } |
| 490 | _ => {} |
| 491 | } |
| 492 | } |
| 493 | assert_eq!((telemetry_count, terminal_count), (1, 1)); |
| 494 | } |
| 495 | } |
| 496 | |
| 497 | #[async_trait::async_trait] |
| 498 | impl crate::core::model_client::ModelClient for BlockingEmergencyCompactionModelClient { |
| 499 | fn provider_name(&self) -> &str { |
| 500 | "deepseek" |
| 501 | } |
| 502 | |
| 503 | fn model(&self) -> &str { |
| 504 | codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL |
| 505 | } |
| 506 | |
| 507 | async fn create_message( |
| 508 | &self, |
| 509 | _request: codewhale_models::MessageRequest, |
| 510 | ) -> anyhow::Result<codewhale_models::MessageResponse> { |
| 511 | let _drop_signal = DropSignal(std::sync::Arc::clone(&self.request_dropped)); |
| 512 | self.entered.notify_one(); |
| 513 | std::future::pending().await |
| 514 | } |
| 515 | |
| 516 | async fn create_message_stream( |
| 517 | &self, |
| 518 | _request: codewhale_models::MessageRequest, |
| 519 | ) -> anyhow::Result<crate::llm_client::StreamEventBox> { |
| 520 | anyhow::bail!("emergency compaction uses the non-streaming model boundary") |
| 521 | } |
| 522 | |
| 523 | async fn health_check(&self) -> anyhow::Result<bool> { |
| 524 | Ok(true) |
| 525 | } |
| 526 | } |
| 527 | |
| 528 | #[tokio::test] |
| 529 | async fn emergency_compaction_cancellation_drops_provider_and_never_mutates_context() { |
| 530 | let route_config = { |
| 531 | let __cw_config_init_4_0 = Some("deepseek".to_string()); |
| 532 | let __cw_config_init_4_1 = |
| 533 | Some(codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL.to_string()); |
| 534 | let mut __cw_config_init_4_value: Config = Config::default(); |
| 535 | __cw_config_init_4_value.provider = __cw_config_init_4_0; |
| 536 | __cw_config_init_4_value.default_text_model = __cw_config_init_4_1; |
| 537 | __cw_config_init_4_value |
| 538 | }; |
| 539 | let (mut engine, handle) = Engine::new(EngineConfig::default(), &route_config); |
| 540 | engine.session.messages = (0..8) |
| 541 | .map(|index| Message { |
| 542 | role: if index % 2 == 0 { |
| 543 | Role::User |
| 544 | } else { |
| 545 | Role::Assistant |
| 546 | }, |
| 547 | content: vec![ContentBlock::Text { |
| 548 | text: format!("preserve emergency context item {index}"), |
| 549 | cache_control: None, |
| 550 | }], |
| 551 | }) |
| 552 | .collect::<Vec<_>>() |
| 553 | .into(); |
| 554 | let messages_before = engine.session.messages.clone(); |
| 555 | let checkpoint_before = engine.session.compaction_summary_prompt.clone(); |
| 556 | let entered = std::sync::Arc::new(tokio::sync::Notify::new()); |
| 557 | let request_dropped = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); |
| 558 | let client = std::sync::Arc::new(BlockingEmergencyCompactionModelClient { |
| 559 | entered: std::sync::Arc::clone(&entered), |
| 560 | request_dropped: std::sync::Arc::clone(&request_dropped), |
| 561 | }); |
| 562 | |
| 563 | let recovery = tokio::spawn(async move { |
| 564 | let mut turn = TurnContext::new(1); |
| 565 | let recovered = engine |
| 566 | .recover_context_overflow(client.as_ref(), None, "cancellation regression", &mut turn) |
| 567 | .await; |
| 568 | (engine, recovered) |
| 569 | }); |
| 570 | |
| 571 | let started_id = tokio::time::timeout(Duration::from_secs(1), async { |
| 572 | loop { |
| 573 | let event = handle |
| 574 | .rx_event |
| 575 | .write() |
| 576 | .await |
| 577 | .recv() |
| 578 | .await |
| 579 | .expect("emergency compaction start event"); |
| 580 | if let Event::CompactionStarted { id, auto: true, .. } = event { |
| 581 | break id; |
| 582 | } |
| 583 | } |
| 584 | }) |
| 585 | .await |
| 586 | .expect("emergency compaction publishes its stable id"); |
| 587 | tokio::time::timeout(Duration::from_secs(1), entered.notified()) |
| 588 | .await |
| 589 | .expect("emergency provider request starts"); |
| 590 | |
| 591 | handle |
| 592 | .cancel_compaction(started_id.clone()) |
| 593 | .expect("exact emergency cancellation accepted"); |
| 594 | let (engine, recovered) = tokio::time::timeout(Duration::from_secs(1), recovery) |
| 595 | .await |
| 596 | .expect("emergency cancellation settles promptly") |
| 597 | .expect("recovery task"); |
| 598 | |
| 599 | assert!(!recovered); |
| 600 | assert_eq!(&*engine.session.messages, &*messages_before); |
| 601 | assert_eq!(engine.session.compaction_summary_prompt, checkpoint_before); |
| 602 | assert!( |
| 603 | request_dropped.load(std::sync::atomic::Ordering::SeqCst), |
| 604 | "cancellation must drop the in-flight provider future" |
| 605 | ); |
| 606 | |
| 607 | let mut events = handle.rx_event.write().await; |
| 608 | let drained = std::iter::from_fn(|| events.try_recv().ok()).collect::<Vec<_>>(); |
| 609 | assert!(matches!( |
| 610 | drained.as_slice(), |
| 611 | [Event::CompactionCancelled { id, auto: true, .. }] if id == &started_id |
| 612 | )); |
| 613 | assert!( |
| 614 | !drained.iter().any(|event| matches!( |
| 615 | event, |
| 616 | Event::CompactionCompleted { .. } | Event::CompactionFailed { .. } |
| 617 | )), |
| 618 | "a canceled emergency pass must have one canceled terminal event" |
| 619 | ); |
| 620 | } |
| 621 | |
| 622 | /// Experience mark 2: a one-message conversation has nothing to summarize. |
| 623 | /// Emergency recovery must not start a pass (no spinner, no model call) |
| 624 | /// before the failure the caller reports anyway. |
| 625 | #[tokio::test] |
| 626 | async fn emergency_recovery_preserves_history_when_disabled_or_unnecessary() { |
| 627 | use crate::llm_client::mock::MockLlmClient; |
| 628 | let _env_lock = lock_test_env(); |
| 629 | let workspace = tempdir().unwrap(); |
| 630 | let _home = EnvVarGuard::set("CODEWHALE_HOME", workspace.path()); |
| 631 | for automatic in [true, false] { |
| 632 | let mut config = deterministic_engine_config(workspace.path()); |
| 633 | config.compaction.enabled = automatic; |
| 634 | let (mut engine, handle) = Engine::new(config, &Config::default()); |
| 635 | let count = if automatic { 1 } else { 8 }; |
| 636 | engine.session.messages = (0..count) |
| 637 | .map(|index| Message { |
| 638 | role: if index % 2 == 0 { |
| 639 | Role::User |
| 640 | } else { |
| 641 | Role::Assistant |
| 642 | }, |
| 643 | content: vec![ContentBlock::Text { |
| 644 | text: format!("Original conversation step {index}"), |
| 645 | cache_control: None, |
| 646 | }], |
| 647 | }) |
| 648 | .collect::<Vec<_>>() |
| 649 | .into(); |
| 650 | assert_eq!( |
| 651 | crate::compaction::has_compactable_history(&engine.session.messages), |
| 652 | !automatic |
| 653 | ); |
| 654 | let original = engine.session.messages.snapshot(); |
| 655 | let client = MockLlmClient::new(Vec::new()); |
| 656 | let mut turn = TurnContext::new(1); |
| 657 | assert!( |
| 658 | !engine |
| 659 | .recover_context_overflow(&client, None, "preflight token budget", &mut turn) |
| 660 | .await |
| 661 | ); |
| 662 | assert_eq!(client.call_count(), 0); |
| 663 | assert_eq!(turn.stop_diagnostics.emergency_compaction_attempts, 0); |
| 664 | assert_eq!(engine.session.messages.snapshot(), original); |
| 665 | if !automatic { |
| 666 | assert!( |
| 667 | turn.context_recovery_rejection |
| 668 | .as_ref() |
| 669 | .is_some_and(|error| matches!( |
| 670 | error.downcast_ref::<crate::llm_client::LlmError>(), |
| 671 | Some(crate::llm_client::LlmError::ContextLengthError(_)) |
| 672 | )) |
| 673 | ); |
| 674 | let message = engine |
| 675 | .report_context_recovery_failure(&mut turn) |
| 676 | .await |
| 677 | .expect("disabled-setting explanation"); |
| 678 | assert!( |
| 679 | message.contains("Automatic compaction is disabled"), |
| 680 | "{message}" |
| 681 | ); |
| 682 | assert!( |
| 683 | engine |
| 684 | .report_context_recovery_failure(&mut turn) |
| 685 | .await |
| 686 | .is_none() |
| 687 | ); |
| 688 | } else { |
| 689 | assert!(turn.context_recovery_rejection.is_none()); |
| 690 | } |
| 691 | let mut events = handle.rx_event.write().await; |
| 692 | let drained = std::iter::from_fn(|| events.try_recv().ok()).collect::<Vec<_>>(); |
| 693 | assert!( |
| 694 | !drained.iter().any(|event| matches!( |
| 695 | event, |
| 696 | Event::CompactionStarted { .. } | Event::CompactionFailed { .. } |
| 697 | )), |
| 698 | "{drained:?}" |
| 699 | ); |
| 700 | assert_eq!( |
| 701 | drained |
| 702 | .iter() |
| 703 | .filter(|event| matches!(event, Event::Error { .. })) |
| 704 | .count(), |
| 705 | usize::from(!automatic) |
| 706 | ); |
| 707 | } |
| 708 | } |
| 709 | |
| 710 | #[test] |
| 711 | fn recovery_failures_from_the_provider_are_told_apart_from_budget_failures() { |
| 712 | use super::super::compaction::is_provider_rejection; |
| 713 | use crate::llm_client::LlmError; |
| 714 | assert!(is_provider_rejection(&anyhow::Error::new( |
| 715 | LlmError::ModelError("\"nomic-embed-text:latest\" does not support chat".to_string()) |
| 716 | ))); |
| 717 | assert!(is_provider_rejection(&anyhow::anyhow!( |
| 718 | "connection refused while contacting http://localhost:11434" |
| 719 | ))); |
| 720 | assert!(!is_provider_rejection(&anyhow::Error::new( |
| 721 | LlmError::ContextLengthError("prompt is too long".to_string()) |
| 722 | ))); |
| 723 | assert!(!is_provider_rejection(&anyhow::anyhow!( |
| 724 | "Making room did not shrink the context; the original conversation was preserved." |
| 725 | ))); |
| 726 | } |
| 727 | |
| 728 | #[test] |
| 729 | fn a_request_that_cannot_fit_names_the_cause_and_one_next_step() { |
| 730 | use super::super::context::context_does_not_fit_message; |
| 731 | let embed = |
| 732 | context_does_not_fit_message(true, true, "nomic-embed-text:latest", 5_200, 1_500, 5_100); |
| 733 | assert_eq!( |
| 734 | embed, |
| 735 | "nomic-embed-text:latest can't chat. Pick a chat model: /model." |
| 736 | ); |
| 737 | let window = context_does_not_fit_message(true, true, "qwen3:4b", 5_300, 3_000, 5_100); |
| 738 | assert!( |
| 739 | window.contains("qwen3:4b's context window (~3000 tokens usable)"), |
| 740 | "{window}" |
| 741 | ); |
| 742 | assert!( |
| 743 | window.contains("working instructions (~5100 tokens)"), |
| 744 | "{window}" |
| 745 | ); |
| 746 | assert!(window.ends_with("raise num_ctx: /model."), "{window}"); |
| 747 | assert!(!window.contains("compaction"), "{window}"); |
| 748 | let message = context_does_not_fit_message(false, false, "small-model", 9_000, 6_000, 2_000); |
| 749 | assert!( |
| 750 | message.contains("there is not enough earlier conversation to summarize"), |
| 751 | "{message}" |
| 752 | ); |
| 753 | assert!(message.ends_with("choose a larger model."), "{message}"); |
| 754 | assert!( |
| 755 | !message.contains("/model"), |
| 756 | "headless has no command layer: {message}" |
| 757 | ); |
| 758 | } |
| 759 | |
| 760 | #[tokio::test] |
| 761 | async fn manual_compaction_reuses_the_last_turn_request_header() { |
| 762 | use wiremock::matchers::{method, path}; |
| 763 | use wiremock::{Mock, MockServer, Request, ResponseTemplate}; |
| 764 | |
| 765 | let _env_lock = lock_test_env(); |
| 766 | let _cost_scope = crate::cost_status::test_scope(); |
| 767 | let workspace = tempdir().expect("isolated compaction workspace"); |
| 768 | let _home = EnvVarGuard::set("CODEWHALE_HOME", workspace.path()); |
| 769 | let server = MockServer::start().await; |
| 770 | Mock::given(method("POST")) |
| 771 | .and(path("/v1/chat/completions")) |
| 772 | .respond_with(|request: &Request| { |
| 773 | let body: Value = serde_json::from_slice(&request.body).expect("request JSON"); |
| 774 | if body["stream"] == json!(true) { |
| 775 | ResponseTemplate::new(200) |
| 776 | .insert_header("content-type", "text/event-stream") |
| 777 | .set_body_string(concat!( |
| 778 | "data: {\"id\":\"turn\",\"choices\":[{\"index\":0,", |
| 779 | "\"delta\":{\"content\":\"The store migration is transactional now.\"},", |
| 780 | "\"finish_reason\":null}]}\n\n", |
| 781 | "data: {\"id\":\"turn\",\"choices\":[{\"index\":0,", |
| 782 | "\"delta\":{},\"finish_reason\":\"stop\"}]}\n\n", |
| 783 | "data: [DONE]\n\n", |
| 784 | )) |
| 785 | } else { |
| 786 | ResponseTemplate::new(200).set_body_json(json!({ |
| 787 | "id": "summary", |
| 788 | "object": "chat.completion", |
| 789 | "model": codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL, |
| 790 | "choices": [{ |
| 791 | "index": 0, |
| 792 | "message": { "role": "assistant", "content": "Primary request: keep the session store migration transactional. Completed: the migration was made transactional. Next: run session_store::roundtrip and report the result." }, |
| 793 | "finish_reason": "stop", |
| 794 | }], |
| 795 | "usage": { "prompt_tokens": 41, "completion_tokens": 7, "total_tokens": 48 }, |
| 796 | })) |
| 797 | } |
| 798 | }) |
| 799 | .mount(&server) |
| 800 | .await; |
| 801 | let route_config = { |
| 802 | let provider = Some("deepseek".to_string()); |
| 803 | let mut config: Config = Config::default(); |
| 804 | config.provider = provider; |
| 805 | config |
| 806 | } |
| 807 | .with_legacy_root( |
| 808 | Some("fixture-key".to_string()), |
| 809 | Some(format!("{}/v1", server.uri())), |
| 810 | ); |
| 811 | let (engine, handle) = Engine::new( |
| 812 | EngineConfig { |
| 813 | workspace: workspace.path().to_path_buf(), |
| 814 | snapshots_enabled: false, |
| 815 | subagents_enabled: false, |
| 816 | ..EngineConfig::default() |
| 817 | }, |
| 818 | &route_config, |
| 819 | ); |
| 820 | let run_task = tokio::spawn(engine.run()); |
| 821 | let wait_for_terminal = |expect_compaction: bool| { |
| 822 | let handle = &handle; |
| 823 | async move { |
| 824 | let mut rx = handle.rx_event.write().await; |
| 825 | loop { |
| 826 | let event = tokio::time::timeout(Duration::from_secs(30), rx.recv()) |
| 827 | .await |
| 828 | .expect("engine terminal") |
| 829 | .expect("engine event channel"); |
| 830 | if let Event::TurnComplete { |
| 831 | compaction_id, |
| 832 | status, |
| 833 | error, |
| 834 | .. |
| 835 | } = event |
| 836 | { |
| 837 | assert_eq!(compaction_id.is_some(), expect_compaction); |
| 838 | assert_eq!(status, TurnOutcomeStatus::Completed, "{error:?}"); |
| 839 | return; |
| 840 | } |
| 841 | } |
| 842 | } |
| 843 | }; |
| 844 | |
| 845 | handle |
| 846 | .send(external_user_message_op( |
| 847 | "Keep the session store migration transactional.", |
| 848 | AppMode::Agent, |
| 849 | &route_config, |
| 850 | )) |
| 851 | .await |
| 852 | .expect("send turn"); |
| 853 | wait_for_terminal(false).await; |
| 854 | handle |
| 855 | .send(Op::CompactContext { |
| 856 | id: "compact-header-parity".to_string(), |
| 857 | route: resolved_route_for_test( |
| 858 | &route_config, |
| 859 | codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL, |
| 860 | ), |
| 861 | compaction: Box::new(CompactionConfig::default()), |
| 862 | }) |
| 863 | .await |
| 864 | .expect("send manual compaction"); |
| 865 | wait_for_terminal(true).await; |
| 866 | run_task.abort(); |
| 867 | |
| 868 | let bodies = server |
| 869 | .received_requests() |
| 870 | .await |
| 871 | .expect("recorded requests") |
| 872 | .iter() |
| 873 | .map(|request| serde_json::from_slice::<Value>(&request.body).expect("request JSON")) |
| 874 | .collect::<Vec<_>>(); |
| 875 | let turn = bodies |
| 876 | .iter() |
| 877 | .find(|body| body["stream"] == json!(true)) |
| 878 | .expect("turn request"); |
| 879 | let summary = bodies.last().expect("summary request"); |
| 880 | assert_ne!(summary["stream"], json!(true), "{bodies:#?}"); |
| 881 | assert!( |
| 882 | turn["tools"] |
| 883 | .as_array() |
| 884 | .is_some_and(|tools| !tools.is_empty()), |
| 885 | "the turn must carry tools for this check: {turn:#}" |
| 886 | ); |
| 887 | for key in [ |
| 888 | "model", |
| 889 | "tools", |
| 890 | "tool_choice", |
| 891 | "reasoning_effort", |
| 892 | "thinking", |
| 893 | ] { |
| 894 | assert_eq!(turn.get(key), summary.get(key), "summary {key}"); |
| 895 | } |
| 896 | let turn_messages = serde_json::to_string(&turn["messages"]).expect("serialize turn"); |
| 897 | let summary_messages = serde_json::to_string(&summary["messages"]).expect("serialize summary"); |
| 898 | assert!( |
| 899 | summary_messages.starts_with(turn_messages.strip_suffix(']').expect("JSON array")), |
| 900 | "summary history diverges from the turn prefix:\nturn: {turn_messages}\nsummary: {summary_messages}" |
| 901 | ); |
| 902 | } |
| 903 | |
| 904 | #[tokio::test] |
| 905 | async fn session_restore_clears_stale_last_request_tools_and_manual_compact_reconstructs_active_tools() |
| 906 | { |
| 907 | use wiremock::matchers::{method, path}; |
| 908 | use wiremock::{Mock, MockServer, Request, ResponseTemplate}; |
| 909 | |
| 910 | let _env_lock = lock_test_env(); |
| 911 | let _cost_scope = crate::cost_status::test_scope(); |
| 912 | let workspace = tempdir().expect("isolated compaction workspace"); |
| 913 | let _home = EnvVarGuard::set("CODEWHALE_HOME", workspace.path()); |
| 914 | |
| 915 | let (mut unit_engine, _unit_handle) = Engine::new( |
| 916 | deterministic_engine_config(workspace.path()), |
| 917 | &Config::default(), |
| 918 | ); |
| 919 | unit_engine.session.last_request_tools = Some(vec![catalog_tool("stale_tool")]); |
| 920 | unit_engine.restore_session_history(Vec::new(), None, false); |
| 921 | assert!(unit_engine.session.last_request_tools.is_none()); |
| 922 | unit_engine.session.last_request_tools = Some(vec![catalog_tool("stale_tool")]); |
| 923 | assert!( |
| 924 | unit_engine |
| 925 | .install_synced_session_id("session-after-switch".to_string()) |
| 926 | .is_some() |
| 927 | ); |
| 928 | assert!(unit_engine.session.last_request_tools.is_none()); |
| 929 | |
| 930 | let server = MockServer::start().await; |
| 931 | Mock::given(method("POST")) |
| 932 | .and(path("/v1/chat/completions")) |
| 933 | .respond_with(|request: &Request| { |
| 934 | let body: Value = serde_json::from_slice(&request.body).expect("request JSON"); |
| 935 | if body["stream"] == json!(true) { |
| 936 | ResponseTemplate::new(200) |
| 937 | .insert_header("content-type", "text/event-stream") |
| 938 | .set_body_string(concat!( |
| 939 | "data: {\"id\":\"turn\",\"choices\":[{\"index\":0,", |
| 940 | "\"delta\":{\"content\":\"Acknowledged.\"},", |
| 941 | "\"finish_reason\":null}]}\n\n", |
| 942 | "data: {\"id\":\"turn\",\"choices\":[{\"index\":0,", |
| 943 | "\"delta\":{},\"finish_reason\":\"stop\"}]}\n\n", |
| 944 | "data: [DONE]\n\n", |
| 945 | )) |
| 946 | } else { |
| 947 | ResponseTemplate::new(200).set_body_json(json!({ |
| 948 | "id": "summary", |
| 949 | "object": "chat.completion", |
| 950 | "model": codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL, |
| 951 | "choices": [{ |
| 952 | "index": 0, |
| 953 | "message": { "role": "assistant", "content": "Primary request: plan the restored session. Completed: reviewed the prior notes. Next: outline the implementation steps." }, |
| 954 | "finish_reason": "stop", |
| 955 | }], |
| 956 | "usage": { "prompt_tokens": 31, "completion_tokens": 9, "total_tokens": 40 }, |
| 957 | })) |
| 958 | } |
| 959 | }) |
| 960 | .mount(&server) |
| 961 | .await; |
| 962 | let route_config = { |
| 963 | let mut config: Config = Config::default(); |
| 964 | config.provider = Some("deepseek".to_string()); |
| 965 | config |
| 966 | } |
| 967 | .with_legacy_root( |
| 968 | Some("fixture-key".to_string()), |
| 969 | Some(format!("{}/v1", server.uri())), |
| 970 | ); |
| 971 | let (engine, handle) = Engine::new( |
| 972 | EngineConfig { |
| 973 | workspace: workspace.path().to_path_buf(), |
| 974 | snapshots_enabled: false, |
| 975 | subagents_enabled: false, |
| 976 | ..EngineConfig::default() |
| 977 | }, |
| 978 | &route_config, |
| 979 | ); |
| 980 | let run_task = tokio::spawn(engine.run()); |
| 981 | let wait_for_terminal = |expect_compaction: bool| { |
| 982 | let handle = &handle; |
| 983 | async move { |
| 984 | let mut rx = handle.rx_event.write().await; |
| 985 | loop { |
| 986 | let event = tokio::time::timeout(Duration::from_secs(30), rx.recv()) |
| 987 | .await |
| 988 | .expect("engine terminal") |
| 989 | .expect("engine event channel"); |
| 990 | if let Event::TurnComplete { |
| 991 | compaction_id, |
| 992 | status, |
| 993 | error, |
| 994 | .. |
| 995 | } = event |
| 996 | { |
| 997 | assert_eq!(compaction_id.is_some(), expect_compaction); |
| 998 | assert_eq!(status, TurnOutcomeStatus::Completed, "{error:?}"); |
| 999 | return; |
| 1000 | } |
| 1001 | } |
| 1002 | } |
| 1003 | }; |
| 1004 | |
| 1005 | let mut session_a_turn = |
| 1006 | external_user_message_op("Session A work turn.", AppMode::Agent, &route_config); |
| 1007 | if let Op::SendMessage(TurnSpec { allowed_tools, .. }) = &mut session_a_turn { |
| 1008 | *allowed_tools = Some(vec!["read".to_string()]); |
| 1009 | } |
| 1010 | handle.send(session_a_turn).await.expect("send agent turn"); |
| 1011 | wait_for_terminal(false).await; |
| 1012 | |
| 1013 | handle |
| 1014 | .send(Op::SyncSession { |
| 1015 | expected: None, |
| 1016 | control: crate::core::ops::SessionControlId::new(), |
| 1017 | session_id: Some("resumed-plan-session".to_string()), |
| 1018 | messages: vec![ |
| 1019 | Message { |
| 1020 | role: Role::User, |
| 1021 | content: vec![ContentBlock::Text { |
| 1022 | text: "Resumed session prompt.".to_string(), |
| 1023 | cache_control: None, |
| 1024 | }], |
| 1025 | }, |
| 1026 | Message { |
| 1027 | role: Role::Assistant, |
| 1028 | content: vec![ContentBlock::Text { |
| 1029 | text: "Resumed session assistant reply.".to_string(), |
| 1030 | cache_control: None, |
| 1031 | }], |
| 1032 | }, |
| 1033 | ], |
| 1034 | system_prompt: None, |
| 1035 | system_prompt_override: false, |
| 1036 | model: codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL.to_string(), |
| 1037 | workspace: workspace.path().to_path_buf(), |
| 1038 | mode: AppMode::Plan, |
| 1039 | agent_preset: None, |
| 1040 | }) |
| 1041 | .await |
| 1042 | .expect("sync resumed plan session"); |
| 1043 | { |
| 1044 | let mut rx = handle.rx_event.write().await; |
| 1045 | loop { |
| 1046 | let event = tokio::time::timeout(Duration::from_secs(30), rx.recv()) |
| 1047 | .await |
| 1048 | .expect("session sync event") |
| 1049 | .expect("engine event channel"); |
| 1050 | if matches!(event, Event::SessionUpdated { .. }) { |
| 1051 | break; |
| 1052 | } |
| 1053 | } |
| 1054 | } |
| 1055 | |
| 1056 | handle |
| 1057 | .send(Op::CompactContext { |
| 1058 | id: "compact-right-after-resume".to_string(), |
| 1059 | route: resolved_route_for_test( |
| 1060 | &route_config, |
| 1061 | codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL, |
| 1062 | ), |
| 1063 | compaction: Box::new(CompactionConfig::default()), |
| 1064 | }) |
| 1065 | .await |
| 1066 | .expect("send post-resume manual compaction"); |
| 1067 | wait_for_terminal(true).await; |
| 1068 | |
| 1069 | handle |
| 1070 | .send(external_user_message_op( |
| 1071 | "Session B plan turn.", |
| 1072 | AppMode::Plan, |
| 1073 | &route_config, |
| 1074 | )) |
| 1075 | .await |
| 1076 | .expect("send plan turn"); |
| 1077 | wait_for_terminal(false).await; |
| 1078 | run_task.abort(); |
| 1079 | |
| 1080 | let bodies = server |
| 1081 | .received_requests() |
| 1082 | .await |
| 1083 | .expect("recorded requests") |
| 1084 | .iter() |
| 1085 | .map(|request| serde_json::from_slice::<Value>(&request.body).expect("request JSON")) |
| 1086 | .collect::<Vec<_>>(); |
| 1087 | assert_eq!(bodies.len(), 3, "{bodies:#?}"); |
| 1088 | let agent_turn = &bodies[0]; |
| 1089 | let resumed_summary = &bodies[1]; |
| 1090 | let plan_turn = &bodies[2]; |
| 1091 | assert_eq!(agent_turn["stream"], json!(true)); |
| 1092 | assert_ne!(resumed_summary["stream"], json!(true)); |
| 1093 | assert_eq!(plan_turn["stream"], json!(true)); |
| 1094 | assert!( |
| 1095 | resumed_summary["tools"] |
| 1096 | .as_array() |
| 1097 | .is_some_and(|tools| !tools.is_empty()), |
| 1098 | "manual /compact right after /resume must reconstruct active tools: {resumed_summary:#}" |
| 1099 | ); |
| 1100 | assert_ne!( |
| 1101 | agent_turn["tools"], plan_turn["tools"], |
| 1102 | "Session A and restored Session B must have distinct tool catalogs to detect stale leakage" |
| 1103 | ); |
| 1104 | assert_eq!( |
| 1105 | resumed_summary["tools"], plan_turn["tools"], |
| 1106 | "manual /compact after /resume must send the restored session's tools, not stale Agent tools or None" |
| 1107 | ); |
| 1108 | assert_eq!( |
| 1109 | resumed_summary.get("tool_choice"), |
| 1110 | plan_turn.get("tool_choice") |
| 1111 | ); |
| 1112 | } |
| 1113 |