| 1 | #[tokio::test] |
| 2 | async fn queued_failed_turn_cancels_older_goal_continuation_without_third_call() { |
| 3 | let objective = "stop after the intervening failure"; |
| 4 | let model = std::sync::Arc::new(FailingGoalModelClient { |
| 5 | calls: std::sync::atomic::AtomicUsize::new(0), |
| 6 | message: "deterministic queued turn failure".to_string(), |
| 7 | }); |
| 8 | let config = goal_custom_route_config(); |
| 9 | let client: crate::core::model_client::SharedModelClient = model.clone(); |
| 10 | let (mut engine, handle) = Engine::new_with_model_client( |
| 11 | EngineConfig { |
| 12 | model: "local-model".to_string(), |
| 13 | snapshots_enabled: false, |
| 14 | terminal_chrome_enabled: false, |
| 15 | goal_objective: Some(objective.to_string()), |
| 16 | ..EngineConfig::default() |
| 17 | }, |
| 18 | &config, |
| 19 | client, |
| 20 | ); |
| 21 | let goal_state = engine.config.goal_state.clone(); |
| 22 | |
| 23 | handle |
| 24 | .send(active_goal_message_op( |
| 25 | &config, |
| 26 | "queued turn that will fail", |
| 27 | objective, |
| 28 | None, |
| 29 | )) |
| 30 | .await |
| 31 | .expect("queue failing ordinary turn"); |
| 32 | engine.schedule_goal_continuation(Vec::new()).await; |
| 33 | assert!(engine.has_scheduled_goal_continuation()); |
| 34 | let run_task = tokio::spawn(engine.run()); |
| 35 | |
| 36 | let session = tokio::time::timeout(model_turn_event_timeout(), handle.get_session_snapshot()) |
| 37 | .await |
| 38 | .expect("queued failure did not settle") |
| 39 | .expect("post-failure session snapshot"); |
| 40 | assert_eq!( |
| 41 | model.calls.load(std::sync::atomic::Ordering::SeqCst), |
| 42 | 1, |
| 43 | "the stale synthetic token must not make a third provider call" |
| 44 | ); |
| 45 | let goal = goal_state.lock().expect("goal lock").snapshot(); |
| 46 | assert_eq!(goal.status, "blocked"); |
| 47 | assert!( |
| 48 | goal.blocker |
| 49 | .as_deref() |
| 50 | .is_some_and(|blocker| blocker.contains("deterministic queued turn failure")), |
| 51 | "{goal:?}" |
| 52 | ); |
| 53 | let prompt = system_prompt_text(session.system_prompt.expect("blocked system prompt")); |
| 54 | assert!(!prompt.contains("<session_goal>"), "{prompt}"); |
| 55 | |
| 56 | handle.send(Op::Shutdown).await.expect("shutdown engine"); |
| 57 | run_task.await.expect("engine task"); |
| 58 | } |
| 59 | |
| 60 | #[tokio::test] |
| 61 | async fn configured_goal_delay_is_cancellable_without_starting_another_turn() { |
| 62 | let model = std::sync::Arc::new(FailingGoalModelClient { |
| 63 | calls: std::sync::atomic::AtomicUsize::new(0), |
| 64 | message: "the delayed provider turn must not start".to_string(), |
| 65 | }); |
| 66 | let config = goal_custom_route_config(); |
| 67 | let client: crate::core::model_client::SharedModelClient = model.clone(); |
| 68 | let (mut engine, handle) = Engine::new_with_model_client( |
| 69 | EngineConfig { |
| 70 | model: "local-model".to_string(), |
| 71 | snapshots_enabled: false, |
| 72 | terminal_chrome_enabled: false, |
| 73 | goal_continuation_delay_seconds: 300, |
| 74 | ..EngineConfig::default() |
| 75 | }, |
| 76 | &config, |
| 77 | client, |
| 78 | ); |
| 79 | |
| 80 | engine.schedule_goal_continuation(Vec::new()).await; |
| 81 | let run_task = tokio::spawn(engine.run()); |
| 82 | |
| 83 | { |
| 84 | let mut events = handle.rx_event.write().await; |
| 85 | let waiting = tokio::time::timeout(model_turn_event_timeout(), events.recv()) |
| 86 | .await |
| 87 | .expect("missing continuation wait event") |
| 88 | .expect("engine event channel closed"); |
| 89 | assert!(matches!( |
| 90 | waiting, |
| 91 | Event::GoalContinuationWaiting { delay_seconds: 300 } |
| 92 | )); |
| 93 | } |
| 94 | |
| 95 | handle.cancel(); |
| 96 | { |
| 97 | let mut events = handle.rx_event.write().await; |
| 98 | let ended = tokio::time::timeout(model_turn_event_timeout(), async { |
| 99 | loop { |
| 100 | if let Some(Event::GoalContinuationWaitEnded { interrupted }) = events.recv().await |
| 101 | { |
| 102 | break interrupted; |
| 103 | } |
| 104 | } |
| 105 | }) |
| 106 | .await |
| 107 | .expect("cancel did not end the continuation delay"); |
| 108 | assert!( |
| 109 | ended, |
| 110 | "the wait receipt must identify an explicit interrupt" |
| 111 | ); |
| 112 | } |
| 113 | |
| 114 | let _ = tokio::time::timeout(model_turn_event_timeout(), handle.get_session_snapshot()) |
| 115 | .await |
| 116 | .expect("engine did not accept controls after cancelling the delay") |
| 117 | .expect("session snapshot after cancelled delay"); |
| 118 | assert_eq!( |
| 119 | model.calls.load(std::sync::atomic::Ordering::SeqCst), |
| 120 | 0, |
| 121 | "cancelling the quiet period must happen before provider dispatch" |
| 122 | ); |
| 123 | |
| 124 | handle.send(Op::Shutdown).await.expect("shutdown engine"); |
| 125 | tokio::time::timeout(model_turn_event_timeout(), run_task) |
| 126 | .await |
| 127 | .expect("engine did not shut down after delay cancellation") |
| 128 | .expect("engine task"); |
| 129 | } |
| 130 | |
| 131 | #[tokio::test] |
| 132 | async fn sync_session_boundary_discards_delayed_goal_and_runtime_mcp_capabilities() { |
| 133 | let (mut engine, _handle) = Engine::new( |
| 134 | EngineConfig { |
| 135 | goal_continuation_delay_seconds: 300, |
| 136 | ..EngineConfig::default() |
| 137 | }, |
| 138 | &Config::default(), |
| 139 | ); |
| 140 | engine.session.id = "session-a".to_string(); |
| 141 | engine.schedule_goal_continuation(Vec::new()).await; |
| 142 | assert!(engine.has_scheduled_goal_continuation()); |
| 143 | engine.ensure_mcp_pool().await.expect("initialize MCP pool"); |
| 144 | assert!(engine.mcp_pool.is_some()); |
| 145 | |
| 146 | assert_eq!( |
| 147 | engine.install_synced_session_id("session-a".to_string()), |
| 148 | None |
| 149 | ); |
| 150 | assert!(engine.has_scheduled_goal_continuation()); |
| 151 | assert!( |
| 152 | engine.mcp_pool.is_some(), |
| 153 | "same-id reload keeps runtime state" |
| 154 | ); |
| 155 | |
| 156 | assert_eq!( |
| 157 | engine.install_synced_session_id("session-b".to_string()), |
| 158 | Some("session-a".to_string()) |
| 159 | ); |
| 160 | assert!(!engine.has_scheduled_goal_continuation()); |
| 161 | assert!( |
| 162 | engine.mcp_pool.is_none(), |
| 163 | "same-workspace B must not inherit A's runtime-added MCP servers" |
| 164 | ); |
| 165 | assert_eq!( |
| 166 | engine.install_synced_session_id("session-a".to_string()), |
| 167 | Some("session-b".to_string()) |
| 168 | ); |
| 169 | assert!( |
| 170 | !engine.has_scheduled_goal_continuation() && engine.mcp_pool.is_none(), |
| 171 | "A -> B -> A must not resurrect process-local state from the first A" |
| 172 | ); |
| 173 | } |
| 174 | |
| 175 | #[tokio::test] |
| 176 | async fn sync_session_boundary_rejects_an_already_enqueued_goal_token() { |
| 177 | let (mut engine, _handle) = Engine::new( |
| 178 | EngineConfig { |
| 179 | goal_continuation_delay_seconds: 0, |
| 180 | ..EngineConfig::default() |
| 181 | }, |
| 182 | &Config::default(), |
| 183 | ); |
| 184 | engine.session.id = "session-a".to_string(); |
| 185 | engine.schedule_goal_continuation(Vec::new()).await; |
| 186 | assert!( |
| 187 | engine |
| 188 | .scheduled_goal_continuation |
| 189 | .as_ref() |
| 190 | .is_some_and(|scheduled| scheduled.enqueued), |
| 191 | "fixture must place A's token in the engine mailbox" |
| 192 | ); |
| 193 | |
| 194 | engine.install_synced_session_id("session-b".to_string()); |
| 195 | let input = engine |
| 196 | .next_run_input(false) |
| 197 | .await |
| 198 | .expect("queued continuation token"); |
| 199 | let EngineRunInput::Operation(op) = input else { |
| 200 | panic!("expected queued continuation operation"); |
| 201 | }; |
| 202 | let Op::ContinueGoal { |
| 203 | dynamic_tools, |
| 204 | engine_schedule_id, |
| 205 | } = *op |
| 206 | else { |
| 207 | panic!("expected queued continuation token"); |
| 208 | }; |
| 209 | assert!( |
| 210 | engine |
| 211 | .take_scheduled_goal_continuation(engine_schedule_id, dynamic_tools) |
| 212 | .is_none(), |
| 213 | "B must reject A's already-enqueued synthetic turn token" |
| 214 | ); |
| 215 | } |
| 216 | |
| 217 | #[tokio::test] |
| 218 | async fn cancellation_after_delay_expiry_beats_queued_continuation_dispatch() { |
| 219 | let model = std::sync::Arc::new(FailingGoalModelClient { |
| 220 | calls: std::sync::atomic::AtomicUsize::new(0), |
| 221 | message: "the raced provider turn must not start".to_string(), |
| 222 | }); |
| 223 | let config = goal_custom_route_config(); |
| 224 | let client: crate::core::model_client::SharedModelClient = model.clone(); |
| 225 | let (mut engine, handle) = Engine::new_with_model_client( |
| 226 | EngineConfig { |
| 227 | model: "local-model".to_string(), |
| 228 | snapshots_enabled: false, |
| 229 | terminal_chrome_enabled: false, |
| 230 | goal_continuation_delay_seconds: 300, |
| 231 | ..EngineConfig::default() |
| 232 | }, |
| 233 | &config, |
| 234 | client, |
| 235 | ); |
| 236 | |
| 237 | engine.schedule_goal_continuation(Vec::new()).await; |
| 238 | // Deterministically place the fixture at the timer/mailbox boundary: the |
| 239 | // quiet period expired and its one coalesced token is already queued, but |
| 240 | // the engine has not consumed it yet. |
| 241 | engine |
| 242 | .scheduled_goal_continuation |
| 243 | .as_mut() |
| 244 | .expect("scheduled continuation") |
| 245 | .ready_at = None; |
| 246 | engine.try_flush_pending_goal_continuation(); |
| 247 | assert!( |
| 248 | engine |
| 249 | .scheduled_goal_continuation |
| 250 | .as_ref() |
| 251 | .is_some_and(|scheduled| scheduled.enqueued) |
| 252 | ); |
| 253 | handle.cancel(); |
| 254 | let run_task = tokio::spawn(engine.run()); |
| 255 | |
| 256 | let _ = tokio::time::timeout(model_turn_event_timeout(), handle.get_session_snapshot()) |
| 257 | .await |
| 258 | .expect("engine did not settle the delay-expiry cancellation race") |
| 259 | .expect("session snapshot after expiry race"); |
| 260 | assert_eq!( |
| 261 | model.calls.load(std::sync::atomic::Ordering::SeqCst), |
| 262 | 0, |
| 263 | "cancelled delayed token must be discarded before provider dispatch" |
| 264 | ); |
| 265 | |
| 266 | handle.send(Op::Shutdown).await.expect("shutdown engine"); |
| 267 | tokio::time::timeout(model_turn_event_timeout(), run_task) |
| 268 | .await |
| 269 | .expect("engine did not shut down after expiry race") |
| 270 | .expect("engine task"); |
| 271 | } |
| 272 | |
| 273 | #[tokio::test] |
| 274 | async fn configured_goal_delay_expires_into_exactly_one_continuation() { |
| 275 | let model = std::sync::Arc::new(FailingGoalModelClient { |
| 276 | calls: std::sync::atomic::AtomicUsize::new(0), |
| 277 | message: "stop after proving delayed dispatch".to_string(), |
| 278 | }); |
| 279 | let config = goal_custom_route_config(); |
| 280 | let client: crate::core::model_client::SharedModelClient = model.clone(); |
| 281 | let (mut engine, handle) = Engine::new_with_model_client( |
| 282 | EngineConfig { |
| 283 | model: "local-model".to_string(), |
| 284 | snapshots_enabled: false, |
| 285 | terminal_chrome_enabled: false, |
| 286 | goal_objective: Some("dispatch once after the cadence".to_string()), |
| 287 | goal_continuation_delay_seconds: 1, |
| 288 | ..EngineConfig::default() |
| 289 | }, |
| 290 | &config, |
| 291 | client, |
| 292 | ); |
| 293 | engine |
| 294 | .config |
| 295 | .goal_state |
| 296 | .lock() |
| 297 | .expect("goal lock") |
| 298 | .sync_from_host_status( |
| 299 | Some("dispatch once after the cadence"), |
| 300 | None, |
| 301 | crate::tools::goal::GoalStatus::Active, |
| 302 | ); |
| 303 | engine.schedule_goal_continuation(Vec::new()).await; |
| 304 | let run_task = tokio::spawn(engine.run()); |
| 305 | |
| 306 | let (mut saw_waiting, mut saw_ready, mut saw_started) = (false, false, false); |
| 307 | { |
| 308 | let mut events = handle.rx_event.write().await; |
| 309 | tokio::time::timeout(Duration::from_secs(3), async { |
| 310 | while let Some(event) = events.recv().await { |
| 311 | match event { |
| 312 | Event::GoalContinuationWaiting { delay_seconds: 1 } => saw_waiting = true, |
| 313 | Event::GoalContinuationWaitEnded { interrupted: false } => saw_ready = true, |
| 314 | Event::TurnStarted { .. } => { |
| 315 | saw_started = true; |
| 316 | break; |
| 317 | } |
| 318 | _ => {} |
| 319 | } |
| 320 | } |
| 321 | }) |
| 322 | .await |
| 323 | .expect("configured delay did not dispatch its continuation"); |
| 324 | } |
| 325 | assert!(saw_waiting && saw_ready && saw_started); |
| 326 | |
| 327 | let _ = tokio::time::timeout(model_turn_event_timeout(), handle.get_session_snapshot()) |
| 328 | .await |
| 329 | .expect("delayed failing turn did not settle") |
| 330 | .expect("session snapshot after delayed dispatch"); |
| 331 | assert_eq!( |
| 332 | model.calls.load(std::sync::atomic::Ordering::SeqCst), |
| 333 | 1, |
| 334 | "one delayed schedule must create exactly one provider request" |
| 335 | ); |
| 336 | |
| 337 | handle.send(Op::Shutdown).await.expect("shutdown engine"); |
| 338 | tokio::time::timeout(model_turn_event_timeout(), run_task) |
| 339 | .await |
| 340 | .expect("engine did not shut down after delayed dispatch") |
| 341 | .expect("engine task"); |
| 342 | } |
| 343 | |
| 344 | #[tokio::test] |
| 345 | async fn goal_pause_during_configured_delay_cancels_pending_continuation() { |
| 346 | let model = std::sync::Arc::new(FailingGoalModelClient { |
| 347 | calls: std::sync::atomic::AtomicUsize::new(0), |
| 348 | message: "the paused provider turn must not start".to_string(), |
| 349 | }); |
| 350 | let config = goal_custom_route_config(); |
| 351 | let client: crate::core::model_client::SharedModelClient = model.clone(); |
| 352 | let (mut engine, handle) = Engine::new_with_model_client( |
| 353 | EngineConfig { |
| 354 | model: "local-model".to_string(), |
| 355 | snapshots_enabled: false, |
| 356 | terminal_chrome_enabled: false, |
| 357 | goal_objective: Some("coordinate until paused".to_string()), |
| 358 | goal_continuation_delay_seconds: 300, |
| 359 | ..EngineConfig::default() |
| 360 | }, |
| 361 | &config, |
| 362 | client, |
| 363 | ); |
| 364 | let goal_state = engine.config.goal_state.clone(); |
| 365 | goal_state.lock().expect("goal lock").sync_from_host_status( |
| 366 | Some("coordinate until paused"), |
| 367 | None, |
| 368 | crate::tools::goal::GoalStatus::Active, |
| 369 | ); |
| 370 | engine.schedule_goal_continuation(Vec::new()).await; |
| 371 | let run_task = tokio::spawn(engine.run()); |
| 372 | |
| 373 | handle |
| 374 | .send(Op::SetGoalStatus { |
| 375 | goal_id: None, |
| 376 | status: crate::tools::goal::GoalStatus::Paused, |
| 377 | clear: false, |
| 378 | }) |
| 379 | .await |
| 380 | .expect("pause delayed goal"); |
| 381 | { |
| 382 | let mut events = handle.rx_event.write().await; |
| 383 | let interrupted = tokio::time::timeout(model_turn_event_timeout(), async { |
| 384 | loop { |
| 385 | if let Some(Event::GoalContinuationWaitEnded { interrupted }) = events.recv().await |
| 386 | { |
| 387 | break interrupted; |
| 388 | } |
| 389 | } |
| 390 | }) |
| 391 | .await |
| 392 | .expect("goal pause did not end the continuation delay"); |
| 393 | assert!( |
| 394 | interrupted, |
| 395 | "a pause is an explicit interruption, not a ready-to-run receipt" |
| 396 | ); |
| 397 | } |
| 398 | let _ = tokio::time::timeout(model_turn_event_timeout(), handle.get_session_snapshot()) |
| 399 | .await |
| 400 | .expect("goal pause did not settle during delay") |
| 401 | .expect("session snapshot after goal pause"); |
| 402 | |
| 403 | assert_eq!( |
| 404 | goal_state.lock().expect("goal lock").snapshot().status, |
| 405 | "paused" |
| 406 | ); |
| 407 | assert_eq!( |
| 408 | model.calls.load(std::sync::atomic::Ordering::SeqCst), |
| 409 | 0, |
| 410 | "a goal status control must beat the delayed continuation" |
| 411 | ); |
| 412 | |
| 413 | handle.send(Op::Shutdown).await.expect("shutdown engine"); |
| 414 | tokio::time::timeout(model_turn_event_timeout(), run_task) |
| 415 | .await |
| 416 | .expect("engine did not shut down after pausing delayed goal") |
| 417 | .expect("engine task"); |
| 418 | } |
| 419 | |
| 420 | #[tokio::test] |
| 421 | async fn host_injected_goal_continuation_waits_out_the_quiet_period() { |
| 422 | // Host-managed sessions never run the engine-owned scheduler |
| 423 | // (schedule_goal_continuation is gated on !host_managed_turns), so the |
| 424 | // host injects ContinueGoal with engine_schedule_id None and this arm is |
| 425 | // the only dispatch site. A positive configured delay must be awaited |
| 426 | // before the provider request starts. |
| 427 | let model = std::sync::Arc::new(FailingGoalModelClient { |
| 428 | calls: std::sync::atomic::AtomicUsize::new(0), |
| 429 | message: "the host-injected continuation must wait first".to_string(), |
| 430 | }); |
| 431 | let config = goal_custom_route_config(); |
| 432 | let client: crate::core::model_client::SharedModelClient = model.clone(); |
| 433 | let (engine, handle) = Engine::new_with_model_client( |
| 434 | EngineConfig { |
| 435 | model: "local-model".to_string(), |
| 436 | snapshots_enabled: false, |
| 437 | terminal_chrome_enabled: false, |
| 438 | goal_objective: Some("wait out the cadence".to_string()), |
| 439 | goal_continuation_delay_seconds: 1, |
| 440 | ..EngineConfig::default() |
| 441 | }, |
| 442 | &config, |
| 443 | client, |
| 444 | ); |
| 445 | engine |
| 446 | .config |
| 447 | .goal_state |
| 448 | .lock() |
| 449 | .expect("goal lock") |
| 450 | .sync_from_host_status( |
| 451 | Some("wait out the cadence"), |
| 452 | None, |
| 453 | crate::tools::goal::GoalStatus::Active, |
| 454 | ); |
| 455 | let run_task = tokio::spawn(engine.run()); |
| 456 | |
| 457 | let queued_at = Instant::now(); |
| 458 | handle |
| 459 | .send(Op::ContinueGoal { |
| 460 | dynamic_tools: Vec::new(), |
| 461 | engine_schedule_id: None, |
| 462 | }) |
| 463 | .await |
| 464 | .expect("queue host-injected continuation"); |
| 465 | { |
| 466 | let mut events = handle.rx_event.write().await; |
| 467 | tokio::time::timeout(Duration::from_secs(3), async { |
| 468 | while let Some(event) = events.recv().await { |
| 469 | if matches!(event, Event::TurnStarted { .. }) { |
| 470 | break; |
| 471 | } |
| 472 | } |
| 473 | }) |
| 474 | .await |
| 475 | .expect("host-injected continuation did not dispatch after the quiet period"); |
| 476 | } |
| 477 | let elapsed = queued_at.elapsed(); |
| 478 | assert!( |
| 479 | elapsed >= Duration::from_millis(900), |
| 480 | "dispatch must wait out the configured quiet period, dispatched after {elapsed:?}" |
| 481 | ); |
| 482 | |
| 483 | let _ = tokio::time::timeout(model_turn_event_timeout(), handle.get_session_snapshot()) |
| 484 | .await |
| 485 | .expect("host-injected delayed turn did not settle") |
| 486 | .expect("session snapshot after delayed host-injected dispatch"); |
| 487 | assert_eq!( |
| 488 | model.calls.load(std::sync::atomic::Ordering::SeqCst), |
| 489 | 1, |
| 490 | "the host-injected token must dispatch exactly one provider request" |
| 491 | ); |
| 492 | |
| 493 | handle.send(Op::Shutdown).await.expect("shutdown engine"); |
| 494 | tokio::time::timeout(model_turn_event_timeout(), run_task) |
| 495 | .await |
| 496 | .expect("engine did not shut down after host-injected delay") |
| 497 | .expect("engine task"); |
| 498 | } |
| 499 | |
| 500 | #[tokio::test] |
| 501 | async fn host_injected_goal_continuation_with_zero_delay_dispatches_immediately() { |
| 502 | let model = std::sync::Arc::new(FailingGoalModelClient { |
| 503 | calls: std::sync::atomic::AtomicUsize::new(0), |
| 504 | message: "zero-delay host-injected dispatch proof".to_string(), |
| 505 | }); |
| 506 | let config = goal_custom_route_config(); |
| 507 | let client: crate::core::model_client::SharedModelClient = model.clone(); |
| 508 | let (engine, handle) = Engine::new_with_model_client( |
| 509 | EngineConfig { |
| 510 | model: "local-model".to_string(), |
| 511 | snapshots_enabled: false, |
| 512 | terminal_chrome_enabled: false, |
| 513 | goal_objective: Some("dispatch without a cadence".to_string()), |
| 514 | goal_continuation_delay_seconds: 0, |
| 515 | ..EngineConfig::default() |
| 516 | }, |
| 517 | &config, |
| 518 | client, |
| 519 | ); |
| 520 | engine |
| 521 | .config |
| 522 | .goal_state |
| 523 | .lock() |
| 524 | .expect("goal lock") |
| 525 | .sync_from_host_status( |
| 526 | Some("dispatch without a cadence"), |
| 527 | None, |
| 528 | crate::tools::goal::GoalStatus::Active, |
| 529 | ); |
| 530 | let run_task = tokio::spawn(engine.run()); |
| 531 | |
| 532 | handle |
| 533 | .send(Op::ContinueGoal { |
| 534 | dynamic_tools: Vec::new(), |
| 535 | engine_schedule_id: None, |
| 536 | }) |
| 537 | .await |
| 538 | .expect("queue zero-delay host-injected continuation"); |
| 539 | { |
| 540 | let mut events = handle.rx_event.write().await; |
| 541 | tokio::time::timeout(Duration::from_secs(1), async { |
| 542 | while let Some(event) = events.recv().await { |
| 543 | if matches!(event, Event::TurnStarted { .. }) { |
| 544 | break; |
| 545 | } |
| 546 | } |
| 547 | }) |
| 548 | .await |
| 549 | .expect("a zero-delay host-injected continuation must dispatch immediately"); |
| 550 | } |
| 551 | |
| 552 | let _ = tokio::time::timeout(model_turn_event_timeout(), handle.get_session_snapshot()) |
| 553 | .await |
| 554 | .expect("zero-delay host-injected turn did not settle") |
| 555 | .expect("session snapshot after zero-delay dispatch"); |
| 556 | assert_eq!( |
| 557 | model.calls.load(std::sync::atomic::Ordering::SeqCst), |
| 558 | 1, |
| 559 | "zero delay must not suppress the host-injected dispatch" |
| 560 | ); |
| 561 | |
| 562 | handle.send(Op::Shutdown).await.expect("shutdown engine"); |
| 563 | tokio::time::timeout(model_turn_event_timeout(), run_task) |
| 564 | .await |
| 565 | .expect("engine did not shut down after zero-delay dispatch") |
| 566 | .expect("engine task"); |
| 567 | } |
| 568 | |
| 569 | #[tokio::test] |
| 570 | async fn cancellation_during_host_injected_continuation_wait_never_dispatches() { |
| 571 | let model = std::sync::Arc::new(FailingGoalModelClient { |
| 572 | calls: std::sync::atomic::AtomicUsize::new(0), |
| 573 | message: "a cancelled host-injected wait must never start".to_string(), |
| 574 | }); |
| 575 | let config = goal_custom_route_config(); |
| 576 | let client: crate::core::model_client::SharedModelClient = model.clone(); |
| 577 | let (engine, handle) = Engine::new_with_model_client( |
| 578 | EngineConfig { |
| 579 | model: "local-model".to_string(), |
| 580 | snapshots_enabled: false, |
| 581 | terminal_chrome_enabled: false, |
| 582 | goal_objective: Some("cancel mid-cadence".to_string()), |
| 583 | goal_continuation_delay_seconds: 1, |
| 584 | ..EngineConfig::default() |
| 585 | }, |
| 586 | &config, |
| 587 | client, |
| 588 | ); |
| 589 | engine |
| 590 | .config |
| 591 | .goal_state |
| 592 | .lock() |
| 593 | .expect("goal lock") |
| 594 | .sync_from_host_status( |
| 595 | Some("cancel mid-cadence"), |
| 596 | None, |
| 597 | crate::tools::goal::GoalStatus::Active, |
| 598 | ); |
| 599 | let run_task = tokio::spawn(engine.run()); |
| 600 | |
| 601 | handle |
| 602 | .send(Op::ContinueGoal { |
| 603 | dynamic_tools: Vec::new(), |
| 604 | engine_schedule_id: None, |
| 605 | }) |
| 606 | .await |
| 607 | .expect("queue host-injected continuation"); |
| 608 | // Enter the quiet period, then cancel: the biased wait must drop the |
| 609 | // pending pass instead of dispatching when the period would have elapsed. |
| 610 | tokio::time::sleep(Duration::from_millis(100)).await; |
| 611 | handle.cancel(); |
| 612 | |
| 613 | // A dispatch bug would surface a TurnStarted once the 1s period expires; |
| 614 | // a correct cancellation settles back into the mailbox loop silently. |
| 615 | let dispatched = { |
| 616 | let mut events = handle.rx_event.write().await; |
| 617 | tokio::time::timeout(Duration::from_secs(2), async { |
| 618 | loop { |
| 619 | let Some(event) = events.recv().await else { |
| 620 | break false; |
| 621 | }; |
| 622 | if matches!(event, Event::TurnStarted { .. }) { |
| 623 | break true; |
| 624 | } |
| 625 | } |
| 626 | }) |
| 627 | .await |
| 628 | .unwrap_or(false) |
| 629 | }; |
| 630 | assert!( |
| 631 | !dispatched, |
| 632 | "cancellation during the host-injected quiet period must never dispatch" |
| 633 | ); |
| 634 | |
| 635 | // The engine must keep accepting controls after the cancelled wait. |
| 636 | let _ = tokio::time::timeout(model_turn_event_timeout(), handle.get_session_snapshot()) |
| 637 | .await |
| 638 | .expect("engine did not accept controls after the cancelled wait") |
| 639 | .expect("session snapshot after cancelled wait"); |
| 640 | assert_eq!( |
| 641 | model.calls.load(std::sync::atomic::Ordering::SeqCst), |
| 642 | 0, |
| 643 | "the cancelled host-injected token must never reach the provider" |
| 644 | ); |
| 645 | |
| 646 | handle.send(Op::Shutdown).await.expect("shutdown engine"); |
| 647 | tokio::time::timeout(model_turn_event_timeout(), run_task) |
| 648 | .await |
| 649 | .expect("engine did not shut down after cancelled wait") |
| 650 | .expect("engine task"); |
| 651 | } |
| 652 | |
| 653 | #[tokio::test] |
| 654 | async fn queued_not_started_turn_cancels_older_goal_continuation() { |
| 655 | let objective = "stop when the queued turn cannot start"; |
| 656 | let model = std::sync::Arc::new(FailingGoalModelClient { |
| 657 | calls: std::sync::atomic::AtomicUsize::new(0), |
| 658 | message: "model must never be called".to_string(), |
| 659 | }); |
| 660 | let config = goal_custom_route_config(); |
| 661 | let client: crate::core::model_client::SharedModelClient = model.clone(); |
| 662 | let (mut engine, handle) = Engine::new_with_model_client( |
| 663 | EngineConfig { |
| 664 | model: "local-model".to_string(), |
| 665 | snapshots_enabled: false, |
| 666 | terminal_chrome_enabled: false, |
| 667 | goal_objective: Some(objective.to_string()), |
| 668 | ..EngineConfig::default() |
| 669 | }, |
| 670 | &config, |
| 671 | client, |
| 672 | ); |
| 673 | let goal_state = engine.config.goal_state.clone(); |
| 674 | engine.model_client = None; |
| 675 | engine.codewhale_client_error = Some("deterministic missing model client".to_string()); |
| 676 | |
| 677 | handle |
| 678 | .send(active_goal_message_op( |
| 679 | &config, |
| 680 | "queued turn that cannot start", |
| 681 | objective, |
| 682 | None, |
| 683 | )) |
| 684 | .await |
| 685 | .expect("queue not-started ordinary turn"); |
| 686 | engine.schedule_goal_continuation(Vec::new()).await; |
| 687 | let run_task = tokio::spawn(engine.run()); |
| 688 | |
| 689 | let session = tokio::time::timeout(model_turn_event_timeout(), handle.get_session_snapshot()) |
| 690 | .await |
| 691 | .expect("not-started turn did not settle") |
| 692 | .expect("post-rejection session snapshot"); |
| 693 | assert_eq!( |
| 694 | model.calls.load(std::sync::atomic::Ordering::SeqCst), |
| 695 | 0, |
| 696 | "neither the rejected turn nor its stale token may call the provider" |
| 697 | ); |
| 698 | let goal = goal_state.lock().expect("goal lock").snapshot(); |
| 699 | assert_eq!(goal.status, "blocked"); |
| 700 | assert!( |
| 701 | goal.blocker |
| 702 | .as_deref() |
| 703 | .is_some_and(|blocker| blocker.contains("could not be started")), |
| 704 | "{goal:?}" |
| 705 | ); |
| 706 | let prompt = system_prompt_text(session.system_prompt.expect("blocked system prompt")); |
| 707 | assert!(!prompt.contains("<session_goal>"), "{prompt}"); |
| 708 | |
| 709 | handle.send(Op::Shutdown).await.expect("shutdown engine"); |
| 710 | run_task.await.expect("engine task"); |
| 711 | } |
| 712 | |
| 713 | #[tokio::test] |
| 714 | async fn queued_interrupted_turn_cancels_older_goal_continuation_without_third_call() { |
| 715 | let objective = "pause after the intervening cancellation"; |
| 716 | let request_entered = std::sync::Arc::new(tokio::sync::Notify::new()); |
| 717 | let release_request = std::sync::Arc::new(tokio::sync::Notify::new()); |
| 718 | let model = std::sync::Arc::new(FirstRequestGatedGoalModelClient { |
| 719 | calls: std::sync::atomic::AtomicUsize::new(0), |
| 720 | request_entered: std::sync::Arc::clone(&request_entered), |
| 721 | release_request, |
| 722 | }); |
| 723 | let config = goal_custom_route_config(); |
| 724 | let client: crate::core::model_client::SharedModelClient = model.clone(); |
| 725 | let (mut engine, handle) = Engine::new_with_model_client( |
| 726 | EngineConfig { |
| 727 | model: "local-model".to_string(), |
| 728 | snapshots_enabled: false, |
| 729 | terminal_chrome_enabled: false, |
| 730 | goal_objective: Some(objective.to_string()), |
| 731 | ..EngineConfig::default() |
| 732 | }, |
| 733 | &config, |
| 734 | client, |
| 735 | ); |
| 736 | let goal_state = engine.config.goal_state.clone(); |
| 737 | |
| 738 | handle |
| 739 | .send(active_goal_message_op( |
| 740 | &config, |
| 741 | "queued turn that will be cancelled", |
| 742 | objective, |
| 743 | None, |
| 744 | )) |
| 745 | .await |
| 746 | .expect("queue interruptible ordinary turn"); |
| 747 | engine.schedule_goal_continuation(Vec::new()).await; |
| 748 | let run_task = tokio::spawn(engine.run()); |
| 749 | tokio::time::timeout(model_turn_event_timeout(), request_entered.notified()) |
| 750 | .await |
| 751 | .expect("queued request was never entered"); |
| 752 | handle.cancel(); |
| 753 | |
| 754 | let session = tokio::time::timeout(model_turn_event_timeout(), handle.get_session_snapshot()) |
| 755 | .await |
| 756 | .expect("interrupted turn did not settle") |
| 757 | .expect("post-interruption session snapshot"); |
| 758 | assert_eq!( |
| 759 | model.calls.load(std::sync::atomic::Ordering::SeqCst), |
| 760 | 1, |
| 761 | "the stale synthetic token must not make a third provider call" |
| 762 | ); |
| 763 | let goal = goal_state.lock().expect("goal lock").snapshot(); |
| 764 | // Interrupted ordinary turns cancel stale auto-continuation only; the goal |
| 765 | // stays Active so the next user message continues without /goal resume. |
| 766 | assert_eq!(goal.status, "active"); |
| 767 | assert_eq!(goal.blocker, None); |
| 768 | assert_eq!(goal.pause_reason, None); |
| 769 | let prompt = system_prompt_text(session.system_prompt.expect("active system prompt")); |
| 770 | assert!(prompt.contains("<session_goal>"), "{prompt}"); |
| 771 | |
| 772 | handle.send(Op::Shutdown).await.expect("shutdown engine"); |
| 773 | run_task.await.expect("engine task"); |
| 774 | } |
| 775 | |
| 776 | #[tokio::test] |
| 777 | async fn initial_goal_failure_projects_blocked_state() { |
| 778 | let objective = "block the initial failed goal turn"; |
| 779 | let leaked_secret = "sk-initial-goal-secret-123456"; |
| 780 | let model = std::sync::Arc::new(FailingGoalModelClient { |
| 781 | calls: std::sync::atomic::AtomicUsize::new(0), |
| 782 | message: format!("initial provider failure: {leaked_secret}"), |
| 783 | }); |
| 784 | let config = goal_custom_route_config(); |
| 785 | let client: crate::core::model_client::SharedModelClient = model.clone(); |
| 786 | let (engine, handle) = Engine::new_with_model_client( |
| 787 | EngineConfig { |
| 788 | model: "local-model".to_string(), |
| 789 | snapshots_enabled: false, |
| 790 | terminal_chrome_enabled: false, |
| 791 | ..EngineConfig::default() |
| 792 | }, |
| 793 | &config, |
| 794 | client, |
| 795 | ); |
| 796 | let goal_state = engine.config.goal_state.clone(); |
| 797 | let run_task = tokio::spawn(engine.run()); |
| 798 | |
| 799 | handle |
| 800 | .send(active_goal_message_op( |
| 801 | &config, |
| 802 | "start a goal whose first turn fails", |
| 803 | objective, |
| 804 | None, |
| 805 | )) |
| 806 | .await |
| 807 | .expect("send initial goal turn"); |
| 808 | let session = tokio::time::timeout(model_turn_event_timeout(), handle.get_session_snapshot()) |
| 809 | .await |
| 810 | .expect("initial goal failure did not settle") |
| 811 | .expect("post-failure session snapshot"); |
| 812 | |
| 813 | assert_eq!(model.calls.load(std::sync::atomic::Ordering::SeqCst), 1); |
| 814 | let goal = goal_state.lock().expect("goal lock").snapshot(); |
| 815 | assert_eq!(goal.objective.as_deref(), Some(objective)); |
| 816 | assert_eq!(goal.status, "blocked"); |
| 817 | let blocker = goal.blocker.as_deref().expect("failure blocker"); |
| 818 | assert!(blocker.contains("initial provider failure"), "{blocker}"); |
| 819 | assert!(!blocker.contains(leaked_secret), "{blocker}"); |
| 820 | let prompt = system_prompt_text(session.system_prompt.expect("blocked system prompt")); |
| 821 | assert!(!prompt.contains("<session_goal>"), "{prompt}"); |
| 822 | |
| 823 | handle.send(Op::Shutdown).await.expect("shutdown engine"); |
| 824 | run_task.await.expect("engine task"); |
| 825 | } |
| 826 | |
| 827 | /// A goal the runtime stopped (its turn failed) resumes when the person |
| 828 | /// writes again; the host still reports Blocked because it only learns of |
| 829 | /// the resume from this turn's GoalUpdated. |
| 830 | #[tokio::test] |
| 831 | async fn user_message_resumes_a_goal_only_the_runtime_blocked() { |
| 832 | let objective = "resume after a runtime stop"; |
| 833 | let model = std::sync::Arc::new(FailingGoalModelClient { |
| 834 | calls: std::sync::atomic::AtomicUsize::new(0), |
| 835 | message: "turn deadline elapsed".to_string(), |
| 836 | }); |
| 837 | let config = goal_custom_route_config(); |
| 838 | let client: crate::core::model_client::SharedModelClient = model.clone(); |
| 839 | let (engine, handle) = Engine::new_with_model_client( |
| 840 | EngineConfig { |
| 841 | model: "local-model".to_string(), |
| 842 | snapshots_enabled: false, |
| 843 | terminal_chrome_enabled: false, |
| 844 | ..EngineConfig::default() |
| 845 | }, |
| 846 | &config, |
| 847 | client, |
| 848 | ); |
| 849 | let goal_state = engine.config.goal_state.clone(); |
| 850 | let run_task = tokio::spawn(engine.run()); |
| 851 | let settle = || async { |
| 852 | tokio::time::timeout(model_turn_event_timeout(), handle.get_session_snapshot()) |
| 853 | .await |
| 854 | .expect("turn did not settle") |
| 855 | .expect("session snapshot") |
| 856 | }; |
| 857 | |
| 858 | handle |
| 859 | .send(active_goal_message_op(&config, "start", objective, None)) |
| 860 | .await |
| 861 | .expect("send goal turn"); |
| 862 | settle().await; |
| 863 | let blocked = goal_state.lock().expect("goal lock").snapshot(); |
| 864 | assert_eq!(blocked.status, "blocked"); |
| 865 | |
| 866 | let Op::SendMessage(mut automatic) = |
| 867 | active_goal_message_op(&config, "watch event", objective, None) |
| 868 | else { |
| 869 | unreachable!() |
| 870 | }; |
| 871 | automatic.goal_status = crate::tools::goal::GoalStatus::Blocked; |
| 872 | automatic.provenance = crate::core::ops::UserInputProvenance::Runtime; |
| 873 | handle |
| 874 | .send(Op::SendMessage(automatic)) |
| 875 | .await |
| 876 | .expect("send non-person input"); |
| 877 | settle().await; |
| 878 | let retained = goal_state.lock().expect("goal lock").snapshot(); |
| 879 | assert_eq!(retained.status, "blocked"); |
| 880 | assert_eq!(retained.goal_id, blocked.goal_id); |
| 881 | |
| 882 | let Op::SendMessage(mut spec) = active_goal_message_op(&config, "continue", objective, None) |
| 883 | else { |
| 884 | unreachable!() |
| 885 | }; |
| 886 | spec.goal_status = crate::tools::goal::GoalStatus::Blocked; |
| 887 | handle |
| 888 | .send(Op::SendMessage(spec)) |
| 889 | .await |
| 890 | .expect("send continue"); |
| 891 | settle().await; |
| 892 | assert_eq!(model.calls.load(std::sync::atomic::Ordering::SeqCst), 3); |
| 893 | let resumed = goal_state.lock().expect("goal lock").snapshot(); |
| 894 | assert_ne!( |
| 895 | resumed.goal_id, blocked.goal_id, |
| 896 | "the continue turn ran as a resumed goal revision" |
| 897 | ); |
| 898 | |
| 899 | // A blocker the model reported is a judgement: the next message is an |
| 900 | // ordinary turn and the goal stays blocked on that report. |
| 901 | goal_state |
| 902 | .lock() |
| 903 | .expect("goal lock") |
| 904 | .mark_blocked("needs the staging credentials".to_string()) |
| 905 | .unwrap(); |
| 906 | let reported = goal_state.lock().expect("goal lock").snapshot(); |
| 907 | let Op::SendMessage(mut spec) = active_goal_message_op(&config, "continue", objective, None) |
| 908 | else { |
| 909 | unreachable!() |
| 910 | }; |
| 911 | spec.goal_status = crate::tools::goal::GoalStatus::Blocked; |
| 912 | handle |
| 913 | .send(Op::SendMessage(spec)) |
| 914 | .await |
| 915 | .expect("send ordinary turn"); |
| 916 | settle().await; |
| 917 | let after = goal_state.lock().expect("goal lock").snapshot(); |
| 918 | assert_eq!(after.status, "blocked"); |
| 919 | assert_eq!(after.goal_id, reported.goal_id); |
| 920 | assert_eq!( |
| 921 | after.blocker.as_deref(), |
| 922 | Some("needs the staging credentials") |
| 923 | ); |
| 924 | |
| 925 | handle.send(Op::Shutdown).await.expect("shutdown engine"); |
| 926 | run_task.await.expect("engine task"); |
| 927 | } |
| 928 | |
| 929 | #[tokio::test] |
| 930 | async fn initial_goal_interruption_keeps_goal_active() { |
| 931 | let objective = "keep goal active after interrupted turn"; |
| 932 | let request_entered = std::sync::Arc::new(tokio::sync::Notify::new()); |
| 933 | let release_request = std::sync::Arc::new(tokio::sync::Notify::new()); |
| 934 | let model = std::sync::Arc::new(FirstRequestGatedGoalModelClient { |
| 935 | calls: std::sync::atomic::AtomicUsize::new(0), |
| 936 | request_entered: std::sync::Arc::clone(&request_entered), |
| 937 | release_request, |
| 938 | }); |
| 939 | let config = goal_custom_route_config(); |
| 940 | let client: crate::core::model_client::SharedModelClient = model.clone(); |
| 941 | let (engine, handle) = Engine::new_with_model_client( |
| 942 | EngineConfig { |
| 943 | model: "local-model".to_string(), |
| 944 | snapshots_enabled: false, |
| 945 | terminal_chrome_enabled: false, |
| 946 | ..EngineConfig::default() |
| 947 | }, |
| 948 | &config, |
| 949 | client, |
| 950 | ); |
| 951 | let goal_state = engine.config.goal_state.clone(); |
| 952 | let run_task = tokio::spawn(engine.run()); |
| 953 | |
| 954 | handle |
| 955 | .send(active_goal_message_op( |
| 956 | &config, |
| 957 | "start a goal whose first turn is cancelled", |
| 958 | objective, |
| 959 | None, |
| 960 | )) |
| 961 | .await |
| 962 | .expect("send initial goal turn"); |
| 963 | tokio::time::timeout(model_turn_event_timeout(), request_entered.notified()) |
| 964 | .await |
| 965 | .expect("initial request was never entered"); |
| 966 | handle.cancel(); |
| 967 | |
| 968 | let session = tokio::time::timeout(model_turn_event_timeout(), handle.get_session_snapshot()) |
| 969 | .await |
| 970 | .expect("initial interruption did not settle") |
| 971 | .expect("post-interruption session snapshot"); |
| 972 | assert_eq!(model.calls.load(std::sync::atomic::Ordering::SeqCst), 1); |
| 973 | let goal = goal_state.lock().expect("goal lock").snapshot(); |
| 974 | assert_eq!(goal.objective.as_deref(), Some(objective)); |
| 975 | assert_eq!(goal.status, "active"); |
| 976 | assert_eq!(goal.blocker, None); |
| 977 | assert_eq!(goal.pause_reason, None); |
| 978 | let prompt = system_prompt_text(session.system_prompt.expect("active system prompt")); |
| 979 | // Durable goals stay in the prompt after interrupt so the next turn continues. |
| 980 | assert!(prompt.contains("<session_goal>"), "{prompt}"); |
| 981 | assert!(prompt.contains(objective), "{prompt}"); |
| 982 | |
| 983 | handle.send(Op::Shutdown).await.expect("shutdown engine"); |
| 984 | run_task.await.expect("engine task"); |
| 985 | } |
| 986 | |
| 987 | #[tokio::test] |
| 988 | async fn saturated_goal_controls_run_before_ready_idle_child_completion() { |
| 989 | use crate::tools::subagent::SubAgentCompletion; |
| 990 | |
| 991 | let stale_tool = DynamicToolSpec { |
| 992 | namespace: Some("goal-regression".to_string()), |
| 993 | name: "stale".to_string(), |
| 994 | description: "stale tool catalog".to_string(), |
| 995 | input_schema: json!({"type": "object"}), |
| 996 | defer_loading: false, |
| 997 | }; |
| 998 | let fresh_tool = DynamicToolSpec { |
| 999 | name: "fresh".to_string(), |
| 1000 | description: "fresh tool catalog".to_string(), |
| 1001 | ..stale_tool.clone() |
| 1002 | }; |
| 1003 | let config = goal_custom_route_config(); |
| 1004 | let (mut engine, handle) = Engine::new( |
| 1005 | EngineConfig { |
| 1006 | snapshots_enabled: false, |
| 1007 | terminal_chrome_enabled: false, |
| 1008 | ..EngineConfig::default() |
| 1009 | }, |
| 1010 | &config, |
| 1011 | ); |
| 1012 | |
| 1013 | for index in 0..ENGINE_OP_CHANNEL_CAPACITY { |
| 1014 | let status = if index + 1 == ENGINE_OP_CHANNEL_CAPACITY { |
| 1015 | crate::tools::goal::GoalStatus::Paused |
| 1016 | } else { |
| 1017 | crate::tools::goal::GoalStatus::Active |
| 1018 | }; |
| 1019 | handle |
| 1020 | .tx_op |
| 1021 | .try_send(Op::SetGoalStatus { |
| 1022 | goal_id: None, |
| 1023 | status, |
| 1024 | clear: false, |
| 1025 | }) |
| 1026 | .unwrap_or_else(|error| panic!("fill ordering mailbox slot {index}: {error}")); |
| 1027 | } |
| 1028 | assert_eq!(handle.tx_op.capacity(), 0, "fixture must saturate mailbox"); |
| 1029 | engine |
| 1030 | .tx_subagent_completion |
| 1031 | .try_send(SubAgentCompletion { |
| 1032 | owner_session_id: engine.session.id.clone(), |
| 1033 | agent_id: "agent_ready_during_backpressure".to_string(), |
| 1034 | payload: "ready child completion".to_string(), |
| 1035 | }) |
| 1036 | .expect("queue ready idle child completion"); |
| 1037 | engine.schedule_goal_continuation(vec![stale_tool]).await; |
| 1038 | assert!( |
| 1039 | engine.has_scheduled_goal_continuation(), |
| 1040 | "a live schedule must activate temporary op priority" |
| 1041 | ); |
| 1042 | |
| 1043 | // Inspect the exact production receive helper without running handlers: |
| 1044 | // all controls that filled the mailbox, including the final pause, must be |
| 1045 | // selected before the already-ready idle child completion. |
| 1046 | for index in 0..ENGINE_OP_CHANNEL_CAPACITY { |
| 1047 | let input = tokio::time::timeout(model_turn_event_timeout(), engine.next_run_input(false)) |
| 1048 | .await |
| 1049 | .expect("backpressured operation receive timed out") |
| 1050 | .expect("engine input"); |
| 1051 | let EngineRunInput::Operation(op) = input else { |
| 1052 | panic!("idle child completion beat queued control {index}"); |
| 1053 | }; |
| 1054 | let Op::SetGoalStatus { status, clear, .. } = *op else { |
| 1055 | panic!("unexpected operation before queued control {index}"); |
| 1056 | }; |
| 1057 | assert!(!clear); |
| 1058 | let expected = if index + 1 == ENGINE_OP_CHANNEL_CAPACITY { |
| 1059 | crate::tools::goal::GoalStatus::Paused |
| 1060 | } else { |
| 1061 | crate::tools::goal::GoalStatus::Active |
| 1062 | }; |
| 1063 | assert_eq!(status, expected); |
| 1064 | if index == 0 { |
| 1065 | // Refresh after capacity opens. The existing token must retain its |
| 1066 | // FIFO position behind the remaining controls while carrying the |
| 1067 | // newest runtime tool catalog when it is eventually consumed. |
| 1068 | engine |
| 1069 | .schedule_goal_continuation(vec![fresh_tool.clone()]) |
| 1070 | .await; |
| 1071 | } |
| 1072 | } |
| 1073 | |
| 1074 | let token = engine |
| 1075 | .next_run_input(false) |
| 1076 | .await |
| 1077 | .expect("backpressured continuation token"); |
| 1078 | let EngineRunInput::Operation(token) = token else { |
| 1079 | panic!("idle child completion beat the backpressured continuation token"); |
| 1080 | }; |
| 1081 | let Op::ContinueGoal { |
| 1082 | dynamic_tools, |
| 1083 | engine_schedule_id, |
| 1084 | } = *token |
| 1085 | else { |
| 1086 | panic!("expected engine-owned continuation token"); |
| 1087 | }; |
| 1088 | assert!(dynamic_tools.is_empty()); |
| 1089 | let continued_tools = engine |
| 1090 | .take_scheduled_goal_continuation(engine_schedule_id, dynamic_tools) |
| 1091 | .expect("engine-owned continuation token must consume its schedule marker"); |
| 1092 | assert_eq!(continued_tools, vec![fresh_tool]); |
| 1093 | assert!(!engine.has_scheduled_goal_continuation()); |
| 1094 | |
| 1095 | let child = engine |
| 1096 | .next_run_input(false) |
| 1097 | .await |
| 1098 | .expect("ready idle child completion"); |
| 1099 | let EngineRunInput::SubAgentCompletion(child) = child else { |
| 1100 | panic!("unexpected operation after backpressure drain"); |
| 1101 | }; |
| 1102 | assert_eq!(child.agent_id, "agent_ready_during_backpressure"); |
| 1103 | } |
| 1104 | |
| 1105 | #[tokio::test] |
| 1106 | async fn unsaturated_goal_control_runs_before_ready_idle_child_completion() { |
| 1107 | use crate::tools::subagent::SubAgentCompletion; |
| 1108 | |
| 1109 | let config = goal_custom_route_config(); |
| 1110 | let (mut engine, handle) = Engine::new( |
| 1111 | EngineConfig { |
| 1112 | snapshots_enabled: false, |
| 1113 | terminal_chrome_enabled: false, |
| 1114 | ..EngineConfig::default() |
| 1115 | }, |
| 1116 | &config, |
| 1117 | ); |
| 1118 | |
| 1119 | handle |
| 1120 | .tx_op |
| 1121 | .try_send(Op::SetGoalStatus { |
| 1122 | goal_id: None, |
| 1123 | status: crate::tools::goal::GoalStatus::Paused, |
| 1124 | clear: false, |
| 1125 | }) |
| 1126 | .expect("queue unsaturated pause"); |
| 1127 | engine |
| 1128 | .tx_subagent_completion |
| 1129 | .try_send(SubAgentCompletion { |
| 1130 | owner_session_id: engine.session.id.clone(), |
| 1131 | agent_id: "agent_ready_without_backpressure".to_string(), |
| 1132 | payload: "ready child completion".to_string(), |
| 1133 | }) |
| 1134 | .expect("queue ready idle child completion"); |
| 1135 | engine.schedule_goal_continuation(Vec::new()).await; |
| 1136 | assert!(engine.has_scheduled_goal_continuation()); |
| 1137 | assert!( |
| 1138 | handle.tx_op.capacity() > 0, |
| 1139 | "fixture must leave the mailbox unsaturated" |
| 1140 | ); |
| 1141 | |
| 1142 | let first = engine |
| 1143 | .next_run_input(false) |
| 1144 | .await |
| 1145 | .expect("queued pause must be selected"); |
| 1146 | let EngineRunInput::Operation(first) = first else { |
| 1147 | panic!("ready child completion beat an unsaturated queued pause"); |
| 1148 | }; |
| 1149 | assert!(matches!( |
| 1150 | *first, |
| 1151 | Op::SetGoalStatus { |
| 1152 | goal_id: None, |
| 1153 | status: crate::tools::goal::GoalStatus::Paused, |
| 1154 | clear: false |
| 1155 | } |
| 1156 | )); |
| 1157 | |
| 1158 | let token = engine |
| 1159 | .next_run_input(false) |
| 1160 | .await |
| 1161 | .expect("scheduled continuation token"); |
| 1162 | let EngineRunInput::Operation(token) = token else { |
| 1163 | panic!("ready child completion beat the live continuation token"); |
| 1164 | }; |
| 1165 | let Op::ContinueGoal { |
| 1166 | dynamic_tools, |
| 1167 | engine_schedule_id, |
| 1168 | } = *token |
| 1169 | else { |
| 1170 | panic!("expected continuation token behind pause"); |
| 1171 | }; |
| 1172 | engine |
| 1173 | .take_scheduled_goal_continuation(engine_schedule_id, dynamic_tools) |
| 1174 | .expect("consume live continuation schedule"); |
| 1175 | assert!(!engine.has_scheduled_goal_continuation()); |
| 1176 | |
| 1177 | let child = engine |
| 1178 | .next_run_input(false) |
| 1179 | .await |
| 1180 | .expect("idle child completion after schedule consumption"); |
| 1181 | let EngineRunInput::SubAgentCompletion(child) = child else { |
| 1182 | panic!("normal child fairness did not resume after schedule consumption"); |
| 1183 | }; |
| 1184 | assert_eq!(child.agent_id, "agent_ready_without_backpressure"); |
| 1185 | |
| 1186 | engine.config.goal_state.lock().expect("goal").replace( |
| 1187 | "finish the existing goal", |
| 1188 | None, |
| 1189 | Some("same-goal".to_string()), |
| 1190 | ); |
| 1191 | engine |
| 1192 | .handle_set_goal_status(GoalStatus::Active, false, Some("unused-new-id".to_string())) |
| 1193 | .await; |
| 1194 | let scheduled_id = engine |
| 1195 | .scheduled_goal_continuation |
| 1196 | .as_ref() |
| 1197 | .expect("idle kick") |
| 1198 | .id; |
| 1199 | engine |
| 1200 | .handle_set_goal_status(GoalStatus::Active, false, None) |
| 1201 | .await; |
| 1202 | assert_eq!( |
| 1203 | engine.scheduled_goal_continuation.as_ref().unwrap().id, |
| 1204 | scheduled_id |
| 1205 | ); |
| 1206 | assert_eq!( |
| 1207 | engine |
| 1208 | .config |
| 1209 | .goal_state |
| 1210 | .lock() |
| 1211 | .unwrap() |
| 1212 | .snapshot() |
| 1213 | .goal_id |
| 1214 | .as_deref(), |
| 1215 | Some("same-goal") |
| 1216 | ); |
| 1217 | engine.cancel_scheduled_goal_continuation(true).await; |
| 1218 | engine.cancel_token.cancel(); |
| 1219 | engine |
| 1220 | .handle_set_goal_status(GoalStatus::Active, false, None) |
| 1221 | .await; |
| 1222 | assert!(!engine.has_scheduled_goal_continuation()); |
| 1223 | } |
| 1224 | |
| 1225 | #[tokio::test] |
| 1226 | async fn cross_turn_token_budget_exhaustion_does_not_pause_goal() { |
| 1227 | use crate::llm_client::mock::{MockLlmClient, canned}; |
| 1228 | |
| 1229 | let budget_turn = vec![ |
| 1230 | canned::message_start("mock_goal_budget"), |
| 1231 | canned::text_block_start(0), |
| 1232 | canned::text_delta(0, "budget spent"), |
| 1233 | canned::block_stop(0), |
| 1234 | canned::message_delta( |
| 1235 | "end_turn", |
| 1236 | Some(Usage { |
| 1237 | input_tokens: 8, |
| 1238 | output_tokens: 3, |
| 1239 | ..Usage::default() |
| 1240 | }), |
| 1241 | ), |
| 1242 | canned::message_stop(), |
| 1243 | ]; |
| 1244 | let model = std::sync::Arc::new(MockLlmClient::new(vec![ |
| 1245 | budget_turn, |
| 1246 | canned::simple_text_turn("the cross-turn continuation runs past the exhausted budget"), |
| 1247 | ])); |
| 1248 | let client: crate::core::model_client::SharedModelClient = model.clone(); |
| 1249 | let config = Config::default(); |
| 1250 | let engine_config = EngineConfig { |
| 1251 | max_steps: 1, |
| 1252 | snapshots_enabled: false, |
| 1253 | subagents_enabled: false, |
| 1254 | terminal_chrome_enabled: false, |
| 1255 | goal_objective: Some("finish within budget".to_string()), |
| 1256 | goal_token_budget: Some(10), |
| 1257 | ..EngineConfig::default() |
| 1258 | }; |
| 1259 | let (engine, handle) = Engine::new_with_model_client(engine_config, &config, client); |
| 1260 | let goal_state = engine.config.goal_state.clone(); |
| 1261 | let run_task = tokio::spawn(engine.run()); |
| 1262 | |
| 1263 | handle |
| 1264 | .send(Op::SendMessage(TurnSpec { |
| 1265 | profile_constitution: None, |
| 1266 | max_output_tokens: None, |
| 1267 | content: "start budgeted goal".to_string(), |
| 1268 | images: Vec::new(), |
| 1269 | mode: AppMode::Agent, |
| 1270 | route: resolved_route_for_test( |
| 1271 | &config, |
| 1272 | codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL, |
| 1273 | ), |
| 1274 | compaction: Box::new(CompactionConfig::default()), |
| 1275 | initial_routed_usage: Box::default(), |
| 1276 | goal_objective: Some("finish within budget".to_string()), |
| 1277 | goal_token_budget: Some(10), |
| 1278 | goal_status: crate::tools::goal::GoalStatus::Active, |
| 1279 | reasoning_effort: None, |
| 1280 | reasoning_effort_auto: false, |
| 1281 | auto_model: false, |
| 1282 | allow_shell: false, |
| 1283 | trust_mode: false, |
| 1284 | auto_approve: false, |
| 1285 | approval_mode: ApprovalMode::Suggest, |
| 1286 | translation_enabled: false, |
| 1287 | allowed_tools: None, |
| 1288 | dynamic_tools: Vec::new(), |
| 1289 | hook_executor: None, |
| 1290 | verbosity: None, |
| 1291 | provenance: UserInputProvenance::ExternalUser, |
| 1292 | input_authorship: crate::core::ops::TurnInputAuthorship::NotPerson, |
| 1293 | submission_id: None, |
| 1294 | })) |
| 1295 | .await |
| 1296 | .expect("send budgeted goal turn"); |
| 1297 | |
| 1298 | let mut starts = 0; |
| 1299 | let mut completed_turns = 0; |
| 1300 | let mut saw_blocked_goal = false; |
| 1301 | while completed_turns < 2 || !saw_blocked_goal { |
| 1302 | let event = tokio::time::timeout(model_turn_event_timeout(), async { |
| 1303 | handle.rx_event.write().await.recv().await |
| 1304 | }) |
| 1305 | .await |
| 1306 | .expect("budget goal event timeout") |
| 1307 | .expect("budget goal event"); |
| 1308 | match event { |
| 1309 | Event::TurnStarted { .. } => starts += 1, |
| 1310 | Event::TurnComplete { status, error, .. } => { |
| 1311 | if status == TurnOutcomeStatus::Completed { |
| 1312 | completed_turns += 1; |
| 1313 | } else { |
| 1314 | // The fixture mock is exhausted after the continuation |
| 1315 | // turns; that provider failure blocks the goal (a |
| 1316 | // legitimate terminal) — it is not a budget pause. |
| 1317 | assert!( |
| 1318 | error |
| 1319 | .as_deref() |
| 1320 | .is_some_and(|e| e.contains("no canned turn queued")), |
| 1321 | "unexpected non-completed turn: {status:?} {error:?}" |
| 1322 | ); |
| 1323 | } |
| 1324 | } |
| 1325 | Event::GoalUpdated { snapshot } if snapshot.status == "paused" => { |
| 1326 | panic!( |
| 1327 | "budgets are telemetry-only in unbounded goal mode; the goal must not \ |
| 1328 | pause on budget (pause_reason={:?})", |
| 1329 | snapshot.pause_reason |
| 1330 | ); |
| 1331 | } |
| 1332 | Event::GoalUpdated { snapshot } if snapshot.status == "blocked" => { |
| 1333 | saw_blocked_goal = true; |
| 1334 | } |
| 1335 | _ => {} |
| 1336 | } |
| 1337 | } |
| 1338 | |
| 1339 | let snapshot = goal_state.lock().expect("goal lock").snapshot(); |
| 1340 | assert_eq!(snapshot.status, "blocked"); |
| 1341 | assert_eq!( |
| 1342 | snapshot.pause_reason, None, |
| 1343 | "budget must never be the pause reason in unbounded goal mode" |
| 1344 | ); |
| 1345 | assert_eq!(snapshot.tokens_used, 11); |
| 1346 | assert_eq!(snapshot.token_budget, Some(10)); |
| 1347 | assert!( |
| 1348 | starts >= 2, |
| 1349 | "budget exhaustion must not stop the cross-turn continuation (starts={starts})" |
| 1350 | ); |
| 1351 | assert!( |
| 1352 | model.call_count() >= 2, |
| 1353 | "the continuation must issue a second provider call (calls={})", |
| 1354 | model.call_count() |
| 1355 | ); |
| 1356 | |
| 1357 | handle.send(Op::Shutdown).await.expect("shutdown engine"); |
| 1358 | run_task.await.expect("engine task"); |
| 1359 | } |
| 1360 | |
| 1361 | #[tokio::test] |
| 1362 | async fn current_turn_usage_does_not_stop_budgeted_goal_after_one_provider_call() { |
| 1363 | use crate::llm_client::mock::{MockLlmClient, canned}; |
| 1364 | |
| 1365 | let objective = "stop before an intra-turn budget overspend"; |
| 1366 | let budget_turn = vec![ |
| 1367 | canned::message_start("mock_goal_current_turn_budget"), |
| 1368 | canned::text_block_start(0), |
| 1369 | canned::text_delta(0, "budget spent"), |
| 1370 | canned::block_stop(0), |
| 1371 | canned::message_delta( |
| 1372 | "end_turn", |
| 1373 | Some(Usage { |
| 1374 | input_tokens: 8, |
| 1375 | output_tokens: 3, |
| 1376 | ..Usage::default() |
| 1377 | }), |
| 1378 | ), |
| 1379 | canned::message_stop(), |
| 1380 | ]; |
| 1381 | let model = std::sync::Arc::new(MockLlmClient::new(vec![ |
| 1382 | budget_turn, |
| 1383 | canned::simple_text_turn("the continuation runs past the exhausted budget"), |
| 1384 | ])); |
| 1385 | let client: crate::core::model_client::SharedModelClient = model.clone(); |
| 1386 | let config = goal_custom_route_config(); |
| 1387 | let (engine, handle) = Engine::new_with_model_client( |
| 1388 | EngineConfig { |
| 1389 | model: "local-model".to_string(), |
| 1390 | snapshots_enabled: false, |
| 1391 | subagents_enabled: false, |
| 1392 | terminal_chrome_enabled: false, |
| 1393 | goal_objective: Some(objective.to_string()), |
| 1394 | goal_token_budget: Some(10), |
| 1395 | ..EngineConfig::default() |
| 1396 | }, |
| 1397 | &config, |
| 1398 | client, |
| 1399 | ); |
| 1400 | let goal_state = engine.config.goal_state.clone(); |
| 1401 | let run_task = tokio::spawn(engine.run()); |
| 1402 | |
| 1403 | handle |
| 1404 | .send(active_goal_message_op( |
| 1405 | &config, |
| 1406 | "start the budgeted goal", |
| 1407 | objective, |
| 1408 | Some(10), |
| 1409 | )) |
| 1410 | .await |
| 1411 | .expect("send budgeted goal turn"); |
| 1412 | let mut starts = 0; |
| 1413 | let mut saw_blocked_goal = false; |
| 1414 | while !saw_blocked_goal { |
| 1415 | let event = tokio::time::timeout(model_turn_event_timeout(), async { |
| 1416 | handle.rx_event.write().await.recv().await |
| 1417 | }) |
| 1418 | .await |
| 1419 | .expect("current-turn budget continuation did not settle") |
| 1420 | .expect("current-turn budget event"); |
| 1421 | match event { |
| 1422 | Event::TurnStarted { .. } => starts += 1, |
| 1423 | Event::TurnComplete { status, error, .. } => { |
| 1424 | if status != TurnOutcomeStatus::Completed { |
| 1425 | assert!( |
| 1426 | error |
| 1427 | .as_deref() |
| 1428 | .is_some_and(|e| e.contains("no canned turn queued")), |
| 1429 | "unexpected non-completed turn: {status:?} {error:?}" |
| 1430 | ); |
| 1431 | } |
| 1432 | } |
| 1433 | Event::GoalUpdated { snapshot } if snapshot.status == "paused" => { |
| 1434 | panic!( |
| 1435 | "budgets are telemetry-only in unbounded goal mode; the goal must not \ |
| 1436 | pause on budget (pause_reason={:?})", |
| 1437 | snapshot.pause_reason |
| 1438 | ); |
| 1439 | } |
| 1440 | Event::GoalUpdated { snapshot } if snapshot.status == "blocked" => { |
| 1441 | saw_blocked_goal = true; |
| 1442 | } |
| 1443 | _ => {} |
| 1444 | } |
| 1445 | } |
| 1446 | assert!( |
| 1447 | model.call_count() >= 2, |
| 1448 | "current-turn usage must not stop additional provider calls (calls={})", |
| 1449 | model.call_count() |
| 1450 | ); |
| 1451 | assert_eq!(model.remaining_turns(), 0); |
| 1452 | let goal = goal_state.lock().expect("goal lock").snapshot(); |
| 1453 | assert_eq!(goal.status, "blocked"); |
| 1454 | assert_eq!( |
| 1455 | goal.pause_reason, None, |
| 1456 | "budget must never be the pause reason in unbounded goal mode" |
| 1457 | ); |
| 1458 | assert_eq!(goal.tokens_used, 11); |
| 1459 | assert_eq!(goal.token_budget, Some(10)); |
| 1460 | assert!( |
| 1461 | starts >= 1, |
| 1462 | "the initial goal turn must start before its intra-turn continuation (starts={starts})" |
| 1463 | ); |
| 1464 | |
| 1465 | handle.send(Op::Shutdown).await.expect("shutdown engine"); |
| 1466 | run_task.await.expect("engine task"); |
| 1467 | } |
| 1468 | |
| 1469 | #[tokio::test] |
| 1470 | async fn tool_response_crossing_goal_budget_issues_second_provider_request() { |
| 1471 | use crate::llm_client::mock::{MockLlmClient, canned}; |
| 1472 | |
| 1473 | let objective = "stop after a budget-crossing goal tool response"; |
| 1474 | let budget_tool_turn = vec![ |
| 1475 | canned::message_start("mock_goal_tool_budget"), |
| 1476 | canned::tool_use_block_start(0, "call-get-goal", "get_goal"), |
| 1477 | canned::tool_input_delta(0, "{}"), |
| 1478 | canned::block_stop(0), |
| 1479 | canned::message_delta( |
| 1480 | "tool_use", |
| 1481 | Some(Usage { |
| 1482 | input_tokens: 8, |
| 1483 | output_tokens: 3, |
| 1484 | ..Usage::default() |
| 1485 | }), |
| 1486 | ), |
| 1487 | canned::message_stop(), |
| 1488 | ]; |
| 1489 | let model = std::sync::Arc::new(MockLlmClient::new(vec![ |
| 1490 | budget_tool_turn, |
| 1491 | canned::simple_text_turn( |
| 1492 | "this second provider response is issued past the exhausted budget", |
| 1493 | ), |
| 1494 | ])); |
| 1495 | let client: crate::core::model_client::SharedModelClient = model.clone(); |
| 1496 | let config = goal_custom_route_config(); |
| 1497 | let (engine, handle) = Engine::new_with_model_client( |
| 1498 | EngineConfig { |
| 1499 | model: "local-model".to_string(), |
| 1500 | snapshots_enabled: false, |
| 1501 | subagents_enabled: false, |
| 1502 | terminal_chrome_enabled: false, |
| 1503 | goal_objective: Some(objective.to_string()), |
| 1504 | goal_token_budget: Some(10), |
| 1505 | ..EngineConfig::default() |
| 1506 | }, |
| 1507 | &config, |
| 1508 | client, |
| 1509 | ); |
| 1510 | let goal_state = engine.config.goal_state.clone(); |
| 1511 | let run_task = tokio::spawn(engine.run()); |
| 1512 | |
| 1513 | handle |
| 1514 | .send(active_goal_message_op( |
| 1515 | &config, |
| 1516 | "inspect the goal without overspending", |
| 1517 | objective, |
| 1518 | Some(10), |
| 1519 | )) |
| 1520 | .await |
| 1521 | .expect("send budgeted goal tool turn"); |
| 1522 | |
| 1523 | let mut saw_get_goal = false; |
| 1524 | let mut saw_blocked_goal = false; |
| 1525 | while !saw_blocked_goal { |
| 1526 | let event = tokio::time::timeout(model_turn_event_timeout(), async { |
| 1527 | handle.rx_event.write().await.recv().await |
| 1528 | }) |
| 1529 | .await |
| 1530 | .expect("budget-crossing goal tool turn did not settle") |
| 1531 | .expect("budget-crossing goal tool event"); |
| 1532 | match event { |
| 1533 | Event::ToolCallComplete { name, result, .. } if name == "get_goal" => { |
| 1534 | assert!(result.expect("get_goal result").success); |
| 1535 | saw_get_goal = true; |
| 1536 | } |
| 1537 | Event::TurnComplete { status, error, .. } => { |
| 1538 | if status != TurnOutcomeStatus::Completed { |
| 1539 | assert!( |
| 1540 | error |
| 1541 | .as_deref() |
| 1542 | .is_some_and(|e| e.contains("no canned turn queued")), |
| 1543 | "unexpected non-completed turn: {status:?} {error:?}" |
| 1544 | ); |
| 1545 | } |
| 1546 | } |
| 1547 | Event::GoalUpdated { snapshot } if snapshot.status == "paused" => { |
| 1548 | panic!( |
| 1549 | "budgets are telemetry-only in unbounded goal mode; the goal must not \ |
| 1550 | pause on budget (pause_reason={:?})", |
| 1551 | snapshot.pause_reason |
| 1552 | ); |
| 1553 | } |
| 1554 | Event::GoalUpdated { snapshot } if snapshot.status == "blocked" => { |
| 1555 | saw_blocked_goal = true; |
| 1556 | } |
| 1557 | _ => {} |
| 1558 | } |
| 1559 | } |
| 1560 | |
| 1561 | assert!(saw_get_goal, "the first response's goal tool must execute"); |
| 1562 | assert!( |
| 1563 | model.call_count() >= 2, |
| 1564 | "the provider-request boundary must not stop the second model call (calls={})", |
| 1565 | model.call_count() |
| 1566 | ); |
| 1567 | assert_eq!(model.remaining_turns(), 0); |
| 1568 | let goal = goal_state.lock().expect("goal lock").snapshot(); |
| 1569 | assert_eq!(goal.status, "blocked"); |
| 1570 | assert_eq!(goal.tokens_used, 11, "usage must be durably recorded once"); |
| 1571 | assert_eq!(goal.token_budget, Some(10)); |
| 1572 | assert_eq!( |
| 1573 | goal.pause_reason, None, |
| 1574 | "budget must never be the pause reason in unbounded goal mode" |
| 1575 | ); |
| 1576 | |
| 1577 | handle.send(Op::Shutdown).await.expect("shutdown engine"); |
| 1578 | run_task.await.expect("engine task"); |
| 1579 | } |
| 1580 |