| 1 | const REPRESENTATIVE_HANDOFF_RELAY: &str = "REPRESENTATIVE_HANDOFF_RELAY"; |
| 2 | |
| 3 | #[test] |
| 4 | fn ordinary_engine_default_does_not_install_a_step_budget() { |
| 5 | assert_eq!( |
| 6 | DEFAULT_MODEL_STEPS, |
| 7 | codewhale_runtime::turn_budget::DEFAULT_MAX_MODEL_STEPS |
| 8 | ); |
| 9 | assert_eq!(EngineConfig::default().max_steps, DEFAULT_MODEL_STEPS); |
| 10 | let mut turn = TurnContext::new(EngineConfig::default().max_steps); |
| 11 | assert_eq!(turn.step_limit(), None); |
| 12 | assert_eq!(turn.stop_diagnostics.effective_max_steps, None); |
| 13 | // No substitute ceiling or overflow may stop an uncapped turn. |
| 14 | turn.step = u32::MAX - 1; |
| 15 | assert!(turn.next_step()); |
| 16 | assert!(turn.next_step()); |
| 17 | assert!(!turn.at_max_steps()); |
| 18 | assert_eq!(turn.steps_used(), u32::MAX); |
| 19 | } |
| 20 | |
| 21 | #[test] |
| 22 | fn registry_guidance_stays_out_of_the_initial_prompt() { |
| 23 | for mcp_enabled in [true, false] { |
| 24 | let mut config = EngineConfig::default(); |
| 25 | if !mcp_enabled { |
| 26 | config.features.disable(Feature::Mcp); |
| 27 | } |
| 28 | let (engine, _handle) = Engine::new(config, &Config::default()); |
| 29 | let prompt = crate::prompts::system_prompt_flat_text( |
| 30 | engine |
| 31 | .session |
| 32 | .system_prompt |
| 33 | .as_ref() |
| 34 | .expect("system prompt"), |
| 35 | ); |
| 36 | assert!(!prompt.contains("## MCP Registry")); |
| 37 | assert!(!prompt.contains("runtime:mcp-registry-first")); |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | /// The engine hands every agent the live posture cell, not a copy: a |
| 42 | /// posture the person publishes after the agent's context was built is what |
| 43 | /// the agent's next call runs under: approval, shell, sandbox. |
| 44 | #[test] |
| 45 | fn agent_tool_contexts_follow_the_published_posture() { |
| 46 | let (engine, handle) = Engine::new(EngineConfig::default(), &Config::default()); |
| 47 | let context = engine.build_tool_context(AppMode::Agent, false); |
| 48 | let mut before = context.clone(); |
| 49 | before |
| 50 | .refresh_live_posture() |
| 51 | .expect("engine contexts carry the live cell"); |
| 52 | assert!(!before.auto_approve); |
| 53 | assert_ne!( |
| 54 | before.elevated_sandbox_policy, |
| 55 | Some(codewhale_sandbox::SandboxPolicy::DangerFullAccess) |
| 56 | ); |
| 57 | handle.publish_turn_authority( |
| 58 | AppMode::Agent, |
| 59 | true, |
| 60 | false, |
| 61 | true, |
| 62 | ApprovalMode::Bypass, |
| 63 | None, |
| 64 | ); |
| 65 | let mut after = context; |
| 66 | after.refresh_live_posture(); |
| 67 | assert!(after.auto_approve); |
| 68 | assert_eq!(after.approval_mode, ApprovalMode::Bypass); |
| 69 | assert_eq!( |
| 70 | after.elevated_sandbox_policy, |
| 71 | Some(codewhale_sandbox::SandboxPolicy::DangerFullAccess) |
| 72 | ); |
| 73 | // Narrowing reaches it too: Plan drops shell and makes the sandbox read-only. |
| 74 | handle.publish_turn_authority( |
| 75 | AppMode::Plan, |
| 76 | true, |
| 77 | false, |
| 78 | false, |
| 79 | ApprovalMode::Suggest, |
| 80 | None, |
| 81 | ); |
| 82 | after.refresh_live_posture(); |
| 83 | assert!(!after.auto_approve); |
| 84 | assert_eq!( |
| 85 | after.shell_policy, |
| 86 | codewhale_agent_contract::worker_profile::ShellPolicy::None |
| 87 | ); |
| 88 | assert_eq!( |
| 89 | after.elevated_sandbox_policy, |
| 90 | Some(codewhale_sandbox::SandboxPolicy::read_only()) |
| 91 | ); |
| 92 | } |
| 93 | |
| 94 | /// "Gets stuck": an agent's approval answer only reached the agent when the |
| 95 | /// engine was idle or itself awaiting approval. While the parent turn |
| 96 | /// streamed or ran tools nobody read it, and the agent waited on. The handle |
| 97 | /// now hands it to the agent directly — here with no engine running at all. |
| 98 | #[tokio::test] |
| 99 | async fn an_agent_approval_answer_reaches_the_agent_while_the_engine_is_busy() { |
| 100 | let mock = mock_engine_handle(); |
| 101 | let id = format!("agent:agent_busy:approval:{}", uuid::Uuid::new_v4()); |
| 102 | let (_, waiting) = mock |
| 103 | .handle |
| 104 | .subagent_manager |
| 105 | .write() |
| 106 | .await |
| 107 | .register_child_approval("agent_busy", &id, "bash", "held", None) |
| 108 | .expect("register"); |
| 109 | mock.handle.approve_tool_call(id).await.expect("send"); |
| 110 | let outcome = tokio::time::timeout(std::time::Duration::from_secs(2), waiting) |
| 111 | .await |
| 112 | .expect("the waiting agent is answered without the engine") |
| 113 | .expect("answer"); |
| 114 | assert_eq!( |
| 115 | outcome.outcome, |
| 116 | crate::tools::subagent::ChildApprovalOutcome::Approved { |
| 117 | by: crate::approval_log::ApprovalDecider::User |
| 118 | } |
| 119 | ); |
| 120 | } |
| 121 | |
| 122 | /// The regression this test exists for. A real DeepSeek turn — "build a |
| 123 | /// self-contained HTML focus timer, read a local fixture, verify it" — spent |
| 124 | /// its steps on five `tool_search` calls for `registry_sync`, a deferred-schema |
| 125 | /// retry, and reasoning about starting a browser MCP server, because the |
| 126 | /// always-visible instruction ordered Registry discovery *before* code |
| 127 | /// execution or a manual implementation and named two tools that are not in the |
| 128 | /// catalog head. |
| 129 | /// |
| 130 | /// Two properties keep that from coming back, and both are about this prompt, |
| 131 | /// not about a second policy surface: discovery is never ordered ahead of |
| 132 | /// ordinary local work, and the deferred-tool cost of reaching the Registry |
| 133 | /// tools is stated where the model reads about them. |
| 134 | #[test] |
| 135 | fn registry_instruction_does_not_gate_ordinary_local_work() { |
| 136 | let (engine, _handle) = Engine::new(EngineConfig::default(), &Config::default()); |
| 137 | let prompt = crate::prompts::system_prompt_flat_text( |
| 138 | engine |
| 139 | .session |
| 140 | .system_prompt |
| 141 | .as_ref() |
| 142 | .expect("system prompt"), |
| 143 | ); |
| 144 | assert!(!prompt.contains("## MCP Registry")); |
| 145 | assert!(!prompt.contains("registry_sync")); |
| 146 | |
| 147 | for ordered in [ |
| 148 | "must call `registry_sync`", |
| 149 | "before `exec_shell`", |
| 150 | "you must call `start_registry_mcp_server`", |
| 151 | "not a reason to skip Registry discovery", |
| 152 | ] { |
| 153 | assert!( |
| 154 | !prompt.contains(ordered), |
| 155 | "Registry guidance must not order discovery ahead of ordinary work: {ordered:?}" |
| 156 | ); |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | /// A provider's input bill describes one route's tokenization of one prompt. |
| 161 | /// The compaction gate and the preflight guard lift the honest estimate to |
| 162 | /// it, so a bill carried across a route switch would measure the next |
| 163 | /// request with the previous route's tokenizer and prefix. Re-installing the |
| 164 | /// same route keeps the carry-over #5577 relies on; a different route drops |
| 165 | /// it. |
| 166 | /// A named custom provider keeps its name, model string, and (absent) limits |
| 167 | /// across a config reload that points it at a different server. A different |
| 168 | /// server is a different tokenizer, so the bill from the old one must not |
| 169 | /// measure the first request to the new one (post-merge finding on #6380). |
| 170 | #[test] |
| 171 | fn custom_route_endpoint_change_forgets_the_previous_bill() { |
| 172 | let mut custom = HashMap::new(); |
| 173 | custom.insert( |
| 174 | "lm-studio".to_string(), |
| 175 | codewhale_runtime::config::ProviderConfig { |
| 176 | kind: Some("openai-compatible".to_string()), |
| 177 | base_url: Some("http://127.0.0.1:18181/v1".to_string()), |
| 178 | model: Some("local-model".to_string()), |
| 179 | api_key: Some("local-test-key".to_string()), |
| 180 | ..codewhale_runtime::config::ProviderConfig::default() |
| 181 | }, |
| 182 | ); |
| 183 | let config = { |
| 184 | let __cw_config_init_0_0 = Some("lm-studio".to_string()); |
| 185 | let __cw_config_init_0_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 186 | custom, |
| 187 | ..codewhale_runtime::config::ProvidersConfig::default() |
| 188 | }); |
| 189 | let mut __cw_config_init_0_value: Config = Config::default(); |
| 190 | __cw_config_init_0_value.provider = __cw_config_init_0_0; |
| 191 | __cw_config_init_0_value.providers = __cw_config_init_0_1; |
| 192 | __cw_config_init_0_value |
| 193 | }; |
| 194 | let (mut engine, _handle) = Engine::new(EngineConfig::default(), &config); |
| 195 | let install = |engine: &mut Engine, config: &Config| { |
| 196 | let route = resolve_runtime_route(config, ProviderKind::Custom, Some("local-model")) |
| 197 | .expect("resolve lm-studio") |
| 198 | .validate() |
| 199 | .expect("preflight lm-studio"); |
| 200 | let context_window = route.context_window; |
| 201 | engine.install_validated_runtime_route(route); |
| 202 | assert_eq!(engine.active_context_window, Some(context_window)); |
| 203 | }; |
| 204 | install(&mut engine, &config); |
| 205 | engine.session.latest_parent_input_tokens = Some(150_000); |
| 206 | |
| 207 | install(&mut engine, &config); |
| 208 | assert_eq!( |
| 209 | engine.session.latest_parent_input_tokens, |
| 210 | Some(150_000), |
| 211 | "the same endpoint keeps the last bill" |
| 212 | ); |
| 213 | |
| 214 | let mut reloaded = config; |
| 215 | reloaded |
| 216 | .providers |
| 217 | .as_mut() |
| 218 | .and_then(|providers| providers.custom.get_mut("lm-studio")) |
| 219 | .expect("named custom provider") |
| 220 | .base_url = Some("http://127.0.0.1:18182/v1".to_string()); |
| 221 | install(&mut engine, &reloaded); |
| 222 | assert_eq!( |
| 223 | engine.api_provider_identity.as_ref().unwrap().key.as_str(), |
| 224 | "lm-studio" |
| 225 | ); |
| 226 | assert_eq!( |
| 227 | engine.session.latest_parent_input_tokens, None, |
| 228 | "a new endpoint under the same name drops the old server's bill" |
| 229 | ); |
| 230 | } |
| 231 | |
| 232 | /// A catalog refresh can keep a route's name, base URL, model, and limits and |
| 233 | /// still move it to another endpoint key or wire protocol. Chat Completions |
| 234 | /// and Responses serialize a prompt differently, so the bill from one must |
| 235 | /// not measure the first request on the other (post-merge finding on #6381). |
| 236 | #[test] |
| 237 | fn route_protocol_change_forgets_the_previous_bill() { |
| 238 | use codewhale_config::route::{RequestProtocol, ResolvedEndpoint}; |
| 239 | let (mut engine, _handle) = Engine::new(EngineConfig::default(), &Config::default()); |
| 240 | let chat = ResolvedEndpoint { |
| 241 | catalog_connection: None, |
| 242 | base_url: "https://gateway.example/v1".to_string(), |
| 243 | endpoint_key: "chat".to_string(), |
| 244 | protocol: RequestProtocol::ChatCompletions, |
| 245 | }; |
| 246 | engine.active_route_endpoint = Some(chat.clone()); |
| 247 | let identity = engine.api_provider_identity.clone().unwrap(); |
| 248 | let model = engine.session.model.clone(); |
| 249 | let limits = engine.active_route_limits; |
| 250 | |
| 251 | engine.session.latest_parent_input_tokens = Some(150_000); |
| 252 | engine.forget_input_bill_if_route_changes( |
| 253 | identity.key.as_str(), |
| 254 | identity.persisted_id(), |
| 255 | Some(&chat), |
| 256 | &model, |
| 257 | limits, |
| 258 | ); |
| 259 | assert_eq!( |
| 260 | engine.session.latest_parent_input_tokens, |
| 261 | Some(150_000), |
| 262 | "the same endpoint keeps the last bill" |
| 263 | ); |
| 264 | |
| 265 | let responses = ResolvedEndpoint { |
| 266 | endpoint_key: "responses".to_string(), |
| 267 | protocol: RequestProtocol::Responses, |
| 268 | ..chat |
| 269 | }; |
| 270 | engine.forget_input_bill_if_route_changes( |
| 271 | identity.key.as_str(), |
| 272 | identity.persisted_id(), |
| 273 | Some(&responses), |
| 274 | &model, |
| 275 | limits, |
| 276 | ); |
| 277 | assert_eq!( |
| 278 | engine.session.latest_parent_input_tokens, None, |
| 279 | "a new endpoint key or protocol at the same URL drops the bill" |
| 280 | ); |
| 281 | } |
| 282 | |
| 283 | #[test] |
| 284 | fn route_switch_forgets_the_previous_routes_input_bill() { |
| 285 | let mut custom = HashMap::new(); |
| 286 | for (name, base_url, model) in [ |
| 287 | ("custom-a", "http://127.0.0.1:18181/v1", "model-a"), |
| 288 | ("custom-b", "http://127.0.0.1:18182/v1", "model-b"), |
| 289 | ] { |
| 290 | custom.insert( |
| 291 | name.to_string(), |
| 292 | codewhale_runtime::config::ProviderConfig { |
| 293 | kind: Some("openai-compatible".to_string()), |
| 294 | base_url: Some(base_url.to_string()), |
| 295 | model: Some(model.to_string()), |
| 296 | api_key: Some("local-test-key".to_string()), |
| 297 | ..codewhale_runtime::config::ProviderConfig::default() |
| 298 | }, |
| 299 | ); |
| 300 | } |
| 301 | let config = { |
| 302 | let __cw_config_init_1_0 = Some("custom-a".to_string()); |
| 303 | let __cw_config_init_1_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 304 | custom, |
| 305 | ..codewhale_runtime::config::ProvidersConfig::default() |
| 306 | }); |
| 307 | let mut __cw_config_init_1_value: Config = Config::default(); |
| 308 | __cw_config_init_1_value.provider = __cw_config_init_1_0; |
| 309 | __cw_config_init_1_value.providers = __cw_config_init_1_1; |
| 310 | __cw_config_init_1_value |
| 311 | }; |
| 312 | let (mut engine, _handle) = Engine::new(EngineConfig::default(), &config); |
| 313 | let route_a = || { |
| 314 | resolve_runtime_route(&config, ProviderKind::Custom, Some("model-a")) |
| 315 | .expect("resolve custom A") |
| 316 | .validate() |
| 317 | .expect("preflight custom A") |
| 318 | }; |
| 319 | engine.install_validated_runtime_route(route_a()); |
| 320 | engine.session.latest_parent_input_tokens = Some(150_000); |
| 321 | |
| 322 | engine.install_validated_runtime_route(route_a()); |
| 323 | assert_eq!( |
| 324 | engine.session.latest_parent_input_tokens, |
| 325 | Some(150_000), |
| 326 | "re-installing the same route keeps the last bill" |
| 327 | ); |
| 328 | |
| 329 | let mut target = config.clone(); |
| 330 | target.provider = Some("custom-b".to_string()); |
| 331 | let route_b = resolve_runtime_route(&target, ProviderKind::Custom, Some("model-b")) |
| 332 | .expect("resolve custom B") |
| 333 | .validate() |
| 334 | .expect("preflight custom B"); |
| 335 | engine.install_validated_runtime_route(route_b); |
| 336 | assert_eq!( |
| 337 | engine.session.latest_parent_input_tokens, None, |
| 338 | "a different route drops the previous route's bill" |
| 339 | ); |
| 340 | } |
| 341 | |
| 342 | #[test] |
| 343 | fn custom_route_identity_change_rebuilds_client_for_new_named_endpoint() { |
| 344 | let mut custom = HashMap::new(); |
| 345 | for (name, base_url, model) in [ |
| 346 | ("custom-a", "http://127.0.0.1:18181/v1", "model-a"), |
| 347 | ("custom-b", "http://127.0.0.1:18182/v1", "model-b"), |
| 348 | ] { |
| 349 | custom.insert( |
| 350 | name.to_string(), |
| 351 | codewhale_runtime::config::ProviderConfig { |
| 352 | kind: Some("openai-compatible".to_string()), |
| 353 | base_url: Some(base_url.to_string()), |
| 354 | model: Some(model.to_string()), |
| 355 | api_key: Some("local-test-key".to_string()), |
| 356 | ..codewhale_runtime::config::ProviderConfig::default() |
| 357 | }, |
| 358 | ); |
| 359 | } |
| 360 | let config = { |
| 361 | let __cw_config_init_2_0 = Some("custom-a".to_string()); |
| 362 | let __cw_config_init_2_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 363 | custom, |
| 364 | ..codewhale_runtime::config::ProvidersConfig::default() |
| 365 | }); |
| 366 | let mut __cw_config_init_2_value: Config = Config::default(); |
| 367 | __cw_config_init_2_value.provider = __cw_config_init_2_0; |
| 368 | __cw_config_init_2_value.providers = __cw_config_init_2_1; |
| 369 | __cw_config_init_2_value |
| 370 | }; |
| 371 | let (mut engine, _handle) = Engine::new(EngineConfig::default(), &config); |
| 372 | assert_eq!( |
| 373 | engine.api_provider_identity.as_ref().unwrap().key.as_str(), |
| 374 | "custom-a" |
| 375 | ); |
| 376 | assert_eq!( |
| 377 | engine |
| 378 | .codewhale_client |
| 379 | .as_ref() |
| 380 | .expect("custom A client") |
| 381 | .base_url(), |
| 382 | "http://127.0.0.1:18181/v1" |
| 383 | ); |
| 384 | |
| 385 | let mut target = config.clone(); |
| 386 | target.provider = Some("custom-b".to_string()); |
| 387 | let route = resolve_runtime_route(&target, ProviderKind::Custom, Some("model-b")) |
| 388 | .expect("resolve custom B") |
| 389 | .validate() |
| 390 | .expect("preflight custom B"); |
| 391 | engine.install_validated_runtime_route(route); |
| 392 | |
| 393 | assert_eq!( |
| 394 | engine.api_provider_identity.as_ref().unwrap().key.as_str(), |
| 395 | "custom-b" |
| 396 | ); |
| 397 | assert_eq!( |
| 398 | engine |
| 399 | .codewhale_client |
| 400 | .as_ref() |
| 401 | .expect("custom B client") |
| 402 | .base_url(), |
| 403 | "http://127.0.0.1:18182/v1" |
| 404 | ); |
| 405 | } |
| 406 | |
| 407 | #[test] |
| 408 | fn custom_route_config_reload_rebuilds_client_when_identity_is_unchanged() { |
| 409 | let mut custom = HashMap::new(); |
| 410 | custom.insert( |
| 411 | "lm-studio".to_string(), |
| 412 | codewhale_runtime::config::ProviderConfig { |
| 413 | kind: Some("openai-compatible".to_string()), |
| 414 | base_url: Some("http://127.0.0.1:18181/v1".to_string()), |
| 415 | model: Some("local-model".to_string()), |
| 416 | api_key: Some("old-local-test-key".to_string()), |
| 417 | ..codewhale_runtime::config::ProviderConfig::default() |
| 418 | }, |
| 419 | ); |
| 420 | let config = { |
| 421 | let __cw_config_init_3_0 = Some("lm-studio".to_string()); |
| 422 | let __cw_config_init_3_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 423 | custom, |
| 424 | ..codewhale_runtime::config::ProvidersConfig::default() |
| 425 | }); |
| 426 | let mut __cw_config_init_3_value: Config = Config::default(); |
| 427 | __cw_config_init_3_value.provider = __cw_config_init_3_0; |
| 428 | __cw_config_init_3_value.providers = __cw_config_init_3_1; |
| 429 | __cw_config_init_3_value |
| 430 | }; |
| 431 | let (mut engine, _handle) = Engine::new(EngineConfig::default(), &config); |
| 432 | |
| 433 | let mut reloaded = config; |
| 434 | let provider = reloaded |
| 435 | .providers |
| 436 | .as_mut() |
| 437 | .and_then(|providers| providers.custom.get_mut("lm-studio")) |
| 438 | .expect("named custom provider"); |
| 439 | provider.base_url = Some("http://127.0.0.1:18182/v1".to_string()); |
| 440 | provider.api_key = Some("new-local-test-key".to_string()); |
| 441 | |
| 442 | let route = resolve_runtime_route(&reloaded, ProviderKind::Custom, Some("local-model")) |
| 443 | .expect("resolve reloaded route") |
| 444 | .validate() |
| 445 | .expect("preflight reloaded route"); |
| 446 | engine.install_validated_runtime_route(route); |
| 447 | |
| 448 | assert_eq!( |
| 449 | engine.api_provider_identity.as_ref().unwrap().key.as_str(), |
| 450 | "lm-studio" |
| 451 | ); |
| 452 | assert_eq!( |
| 453 | engine |
| 454 | .codewhale_client |
| 455 | .as_ref() |
| 456 | .expect("reloaded custom client") |
| 457 | .base_url(), |
| 458 | "http://127.0.0.1:18182/v1" |
| 459 | ); |
| 460 | assert_eq!( |
| 461 | engine.api_config.active_route_base_url(), |
| 462 | "http://127.0.0.1:18182/v1" |
| 463 | ); |
| 464 | } |
| 465 | |
| 466 | #[test] |
| 467 | fn failed_same_identity_route_preflight_leaves_old_client_untouched() { |
| 468 | let mut custom = HashMap::new(); |
| 469 | custom.insert( |
| 470 | "lm-studio".to_string(), |
| 471 | codewhale_runtime::config::ProviderConfig { |
| 472 | kind: Some("openai-compatible".to_string()), |
| 473 | base_url: Some("http://127.0.0.1:18181/v1".to_string()), |
| 474 | model: Some("local-model".to_string()), |
| 475 | api_key: Some("old-local-test-key".to_string()), |
| 476 | ..codewhale_runtime::config::ProviderConfig::default() |
| 477 | }, |
| 478 | ); |
| 479 | let config = { |
| 480 | let __cw_config_init_4_0 = Some("lm-studio".to_string()); |
| 481 | let __cw_config_init_4_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 482 | custom, |
| 483 | ..codewhale_runtime::config::ProvidersConfig::default() |
| 484 | }); |
| 485 | let mut __cw_config_init_4_value: Config = Config::default(); |
| 486 | __cw_config_init_4_value.provider = __cw_config_init_4_0; |
| 487 | __cw_config_init_4_value.providers = __cw_config_init_4_1; |
| 488 | __cw_config_init_4_value |
| 489 | }; |
| 490 | let (engine, _handle) = Engine::new(EngineConfig::default(), &config); |
| 491 | assert!(engine.codewhale_client.is_some()); |
| 492 | |
| 493 | let mut invalid = config; |
| 494 | invalid |
| 495 | .providers |
| 496 | .as_mut() |
| 497 | .and_then(|providers| providers.custom.get_mut("lm-studio")) |
| 498 | .expect("named custom provider") |
| 499 | .base_url = Some("ftp://invalid.example/v1".to_string()); |
| 500 | let err = crate::route_runtime::resolve_runtime_route_for_identity( |
| 501 | &invalid, |
| 502 | engine |
| 503 | .api_provider_identity |
| 504 | .as_ref() |
| 505 | .expect("captured named identity"), |
| 506 | Some("local-model"), |
| 507 | ) |
| 508 | .expect_err("invalid route must fail before installation"); |
| 509 | |
| 510 | assert!(err.contains("must be an http(s) URL with a host"), "{err}"); |
| 511 | assert_eq!( |
| 512 | engine.api_provider_identity.as_ref().unwrap().key.as_str(), |
| 513 | "lm-studio" |
| 514 | ); |
| 515 | assert!(engine.codewhale_client.is_some()); |
| 516 | assert!(engine.model_client.is_some()); |
| 517 | assert!(engine.codewhale_client_error.is_none()); |
| 518 | } |
| 519 | |
| 520 | #[tokio::test] |
| 521 | async fn exact_turn_snapshot_restores_custom_endpoint_and_turn_receipt_after_builtin_route() { |
| 522 | use wiremock::matchers::{method, path}; |
| 523 | use wiremock::{Mock, MockServer, ResponseTemplate}; |
| 524 | |
| 525 | let custom_server = MockServer::start().await; |
| 526 | let custom_base_url = format!("{}/v1", custom_server.uri()); |
| 527 | let done_sse = concat!( |
| 528 | "data: {\"id\":\"chatcmpl-exact-route\",\"choices\":[{\"index\":0,", |
| 529 | "\"delta\":{\"content\":\"exact route\"},\"finish_reason\":null}]}\n\n", |
| 530 | "data: {\"id\":\"chatcmpl-exact-route\",\"choices\":[{\"index\":0,", |
| 531 | "\"delta\":{},\"finish_reason\":\"stop\"}]}\n\n", |
| 532 | "data: [DONE]\n\n", |
| 533 | ); |
| 534 | Mock::given(method("POST")) |
| 535 | .and(path("/v1/chat/completions")) |
| 536 | .respond_with( |
| 537 | ResponseTemplate::new(200) |
| 538 | .insert_header("content-type", "text/event-stream") |
| 539 | .set_body_string(done_sse), |
| 540 | ) |
| 541 | .expect(1) |
| 542 | .mount(&custom_server) |
| 543 | .await; |
| 544 | |
| 545 | let mut custom = HashMap::new(); |
| 546 | custom.insert( |
| 547 | "custom-a".to_string(), |
| 548 | codewhale_runtime::config::ProviderConfig { |
| 549 | kind: Some("openai-compatible".to_string()), |
| 550 | base_url: Some(custom_base_url.clone()), |
| 551 | model: Some("local-model".to_string()), |
| 552 | api_key: Some("local-test-key".to_string()), |
| 553 | ..codewhale_runtime::config::ProviderConfig::default() |
| 554 | }, |
| 555 | ); |
| 556 | let config = { |
| 557 | let __cw_config_init_5_0 = Some("custom-a".to_string()); |
| 558 | let __cw_config_init_5_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 559 | openai: codewhale_runtime::config::ProviderConfig { |
| 560 | base_url: Some("http://127.0.0.1:18182/v1".to_string()), |
| 561 | model: Some("gpt-5.5".to_string()), |
| 562 | api_key: Some("builtin-test-key".to_string()), |
| 563 | ..codewhale_runtime::config::ProviderConfig::default() |
| 564 | }, |
| 565 | custom, |
| 566 | ..codewhale_runtime::config::ProvidersConfig::default() |
| 567 | }); |
| 568 | let mut __cw_config_init_5_value: Config = Config::default(); |
| 569 | __cw_config_init_5_value.provider = __cw_config_init_5_0; |
| 570 | __cw_config_init_5_value.providers = __cw_config_init_5_1; |
| 571 | __cw_config_init_5_value |
| 572 | }; |
| 573 | let engine_config = EngineConfig { |
| 574 | max_steps: 1, |
| 575 | snapshots_enabled: false, |
| 576 | ..EngineConfig::default() |
| 577 | }; |
| 578 | let (mut engine, handle) = Engine::new(engine_config, &config); |
| 579 | |
| 580 | let mut builtin_config = config.clone(); |
| 581 | builtin_config.provider = Some("openai".to_string()); |
| 582 | let builtin_route = |
| 583 | resolve_runtime_route(&builtin_config, ProviderKind::Openai, Some("gpt-5.5")) |
| 584 | .expect("resolve intervening builtin route") |
| 585 | .validate() |
| 586 | .expect("preflight intervening builtin route"); |
| 587 | engine.install_validated_runtime_route(builtin_route); |
| 588 | assert_eq!(engine.api_provider, ProviderKind::Openai); |
| 589 | assert_eq!( |
| 590 | engine |
| 591 | .codewhale_client |
| 592 | .as_ref() |
| 593 | .expect("builtin client") |
| 594 | .base_url(), |
| 595 | "http://127.0.0.1:18182/v1" |
| 596 | ); |
| 597 | |
| 598 | let run_task = tokio::spawn(engine.run()); |
| 599 | handle |
| 600 | .send(Op::SendMessage(TurnSpec { |
| 601 | profile_constitution: None, |
| 602 | max_output_tokens: None, |
| 603 | content: "verify exact route".to_string(), |
| 604 | images: Vec::new(), |
| 605 | mode: AppMode::Agent, |
| 606 | route: Box::new( |
| 607 | resolve_runtime_route(&config, ProviderKind::Custom, Some("local-model")) |
| 608 | .expect("resolve exact custom route"), |
| 609 | ), |
| 610 | compaction: Box::new(CompactionConfig::default()), |
| 611 | initial_routed_usage: Box::default(), |
| 612 | goal_objective: None, |
| 613 | goal_token_budget: None, |
| 614 | goal_status: crate::tools::goal::GoalStatus::Active, |
| 615 | reasoning_effort: None, |
| 616 | reasoning_effort_auto: false, |
| 617 | auto_model: true, |
| 618 | allow_shell: false, |
| 619 | trust_mode: false, |
| 620 | auto_approve: false, |
| 621 | approval_mode: ApprovalMode::Suggest, |
| 622 | translation_enabled: false, |
| 623 | allowed_tools: None, |
| 624 | dynamic_tools: Vec::new(), |
| 625 | hook_executor: None, |
| 626 | verbosity: None, |
| 627 | provenance: UserInputProvenance::ExternalUser, |
| 628 | input_authorship: crate::core::ops::TurnInputAuthorship::NotPerson, |
| 629 | submission_id: None, |
| 630 | })) |
| 631 | .await |
| 632 | .expect("send exact custom turn"); |
| 633 | |
| 634 | // This test runs alongside more than ten thousand TUI tests in the release |
| 635 | // parity job. Keep the assertion bounded, but leave enough headroom for a |
| 636 | // saturated shared runner to schedule the loopback SSE response. |
| 637 | let deadline = tokio::time::Instant::now() + Duration::from_secs(15); |
| 638 | let mut lifecycle_stage = 0u8; |
| 639 | let mut diagnostics = Vec::new(); |
| 640 | let mut rx = handle.rx_event.write().await; |
| 641 | loop { |
| 642 | let event = tokio::time::timeout_at(deadline, rx.recv()) |
| 643 | .await |
| 644 | .unwrap_or_else(|_| { |
| 645 | panic!("timed out waiting for semantic route sequence: {diagnostics:?}") |
| 646 | }) |
| 647 | .expect("engine event channel closed before terminal route receipt"); |
| 648 | diagnostics.push(match &event { |
| 649 | Event::TurnStarted { .. } => "turn_started", |
| 650 | Event::RouteDispatched { .. } => "route_dispatched", |
| 651 | Event::TurnComplete { .. } => "turn_complete", |
| 652 | Event::SessionUpdated { .. } => "session_updated", |
| 653 | Event::PrefixCacheChange { .. } => "prefix_cache", |
| 654 | Event::Status { .. } => "status", |
| 655 | _ => "other", |
| 656 | }); |
| 657 | match event { |
| 658 | Event::TurnStarted { route, .. } => { |
| 659 | assert_eq!( |
| 660 | lifecycle_stage, 0, |
| 661 | "duplicate/reordered start: {diagnostics:?}" |
| 662 | ); |
| 663 | // Lifecycle start still carries the installed-route receipt |
| 664 | // hosts authorize follow-up work against, but it must carry no |
| 665 | // billing envelope: nothing has been dispatched yet, and an |
| 666 | // undispatched route has no metering surface or billing time. |
| 667 | assert!( |
| 668 | route.as_ref().is_none_or(|route| route.billing.is_none()), |
| 669 | "billing route must not be stamped at lifecycle start" |
| 670 | ); |
| 671 | lifecycle_stage = 1; |
| 672 | } |
| 673 | Event::RouteDispatched { route, .. } => { |
| 674 | assert_eq!( |
| 675 | lifecycle_stage, 1, |
| 676 | "dispatch missing, duplicated, or reordered: {diagnostics:?}" |
| 677 | ); |
| 678 | assert_eq!(route.provider, ProviderKind::Custom); |
| 679 | assert_eq!(route.provider_identity, "custom-a"); |
| 680 | assert_eq!(route.model, "local-model"); |
| 681 | assert_eq!( |
| 682 | route |
| 683 | .billing |
| 684 | .as_ref() |
| 685 | .and_then(|billing| billing.endpoint_fingerprint.clone()), |
| 686 | crate::cost_status::endpoint_fingerprint(&custom_base_url), |
| 687 | "dispatch receipt borrowed the later ambient route" |
| 688 | ); |
| 689 | lifecycle_stage = 2; |
| 690 | } |
| 691 | Event::TurnComplete { base_url, .. } => { |
| 692 | assert_eq!( |
| 693 | lifecycle_stage, 2, |
| 694 | "terminal arrived without an ordered dispatch receipt: {diagnostics:?}" |
| 695 | ); |
| 696 | assert_eq!(base_url.as_deref(), Some(custom_base_url.as_str())); |
| 697 | lifecycle_stage = 3; |
| 698 | break; |
| 699 | } |
| 700 | _ => {} |
| 701 | } |
| 702 | } |
| 703 | drop(rx); |
| 704 | assert_eq!(lifecycle_stage, 3); |
| 705 | assert_eq!( |
| 706 | custom_server |
| 707 | .received_requests() |
| 708 | .await |
| 709 | .expect("recorded custom-route request") |
| 710 | .len(), |
| 711 | 1, |
| 712 | "semantic dispatch sequence must bracket one real provider request" |
| 713 | ); |
| 714 | handle.send(Op::Shutdown).await.expect("shutdown engine"); |
| 715 | run_task.await.expect("engine task"); |
| 716 | } |
| 717 | |
| 718 | /// #6690: the main interactive turn froze its dispatch quote only from the |
| 719 | /// provider lake, so an operator's `[[custom_models]]` rate never priced it |
| 720 | /// even though background/review envelopes honored the same row. |
| 721 | #[tokio::test] |
| 722 | async fn main_turn_dispatch_freezes_declared_custom_model_rate() { |
| 723 | use wiremock::matchers::{method, path}; |
| 724 | use wiremock::{Mock, MockServer, ResponseTemplate}; |
| 725 | |
| 726 | let custom_server = MockServer::start().await; |
| 727 | let custom_base_url = format!("{}/v1", custom_server.uri()); |
| 728 | let done_sse = concat!( |
| 729 | "data: {\"id\":\"chatcmpl-declared-rate\",\"choices\":[{\"index\":0,", |
| 730 | "\"delta\":{\"content\":\"priced\"},\"finish_reason\":null}]}\n\n", |
| 731 | "data: {\"id\":\"chatcmpl-declared-rate\",\"choices\":[{\"index\":0,", |
| 732 | "\"delta\":{},\"finish_reason\":\"stop\"}]}\n\n", |
| 733 | "data: [DONE]\n\n", |
| 734 | ); |
| 735 | Mock::given(method("POST")) |
| 736 | .and(path("/v1/chat/completions")) |
| 737 | .respond_with( |
| 738 | ResponseTemplate::new(200) |
| 739 | .insert_header("content-type", "text/event-stream") |
| 740 | .set_body_string(done_sse), |
| 741 | ) |
| 742 | .mount(&custom_server) |
| 743 | .await; |
| 744 | |
| 745 | let mut custom = HashMap::new(); |
| 746 | custom.insert( |
| 747 | "custom-a".to_string(), |
| 748 | codewhale_runtime::config::ProviderConfig { |
| 749 | kind: Some("openai-compatible".to_string()), |
| 750 | base_url: Some(custom_base_url.clone()), |
| 751 | model: Some("local-model".to_string()), |
| 752 | api_key: Some("local-test-key".to_string()), |
| 753 | ..codewhale_runtime::config::ProviderConfig::default() |
| 754 | }, |
| 755 | ); |
| 756 | let declared: codewhale_config::catalog::configured::ConfiguredModel = |
| 757 | toml::from_str(&format!( |
| 758 | "provider = \"custom-a\"\nbase_url = \"{custom_base_url}\"\n\ |
| 759 | id = \"local-model\"\ncost = {{ input = 1.0, output = 2.0 }}\n" |
| 760 | )) |
| 761 | .expect("declared model row"); |
| 762 | let config = { |
| 763 | let __cw_config_init_6_0 = Some("custom-a".to_string()); |
| 764 | let __cw_config_init_6_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 765 | custom, |
| 766 | ..codewhale_runtime::config::ProvidersConfig::default() |
| 767 | }); |
| 768 | let __cw_config_init_6_2 = Some(vec![declared]); |
| 769 | let mut __cw_config_init_6_value: Config = Config::default(); |
| 770 | __cw_config_init_6_value.provider = __cw_config_init_6_0; |
| 771 | __cw_config_init_6_value.providers = __cw_config_init_6_1; |
| 772 | __cw_config_init_6_value.custom_models = __cw_config_init_6_2; |
| 773 | __cw_config_init_6_value |
| 774 | }; |
| 775 | let engine_config = EngineConfig { |
| 776 | max_steps: 1, |
| 777 | snapshots_enabled: false, |
| 778 | ..EngineConfig::default() |
| 779 | }; |
| 780 | let (engine, handle) = Engine::new(engine_config, &config); |
| 781 | let run_task = tokio::spawn(engine.run()); |
| 782 | handle |
| 783 | .send(Op::SendMessage(TurnSpec { |
| 784 | profile_constitution: None, |
| 785 | max_output_tokens: None, |
| 786 | content: "price this turn".to_string(), |
| 787 | images: Vec::new(), |
| 788 | mode: AppMode::Agent, |
| 789 | route: Box::new( |
| 790 | resolve_runtime_route(&config, ProviderKind::Custom, Some("local-model")) |
| 791 | .expect("resolve declared custom route"), |
| 792 | ), |
| 793 | compaction: Box::new(CompactionConfig::default()), |
| 794 | initial_routed_usage: Box::default(), |
| 795 | goal_objective: None, |
| 796 | goal_token_budget: None, |
| 797 | goal_status: crate::tools::goal::GoalStatus::Active, |
| 798 | reasoning_effort: None, |
| 799 | reasoning_effort_auto: false, |
| 800 | auto_model: false, |
| 801 | allow_shell: false, |
| 802 | trust_mode: false, |
| 803 | auto_approve: false, |
| 804 | approval_mode: ApprovalMode::Suggest, |
| 805 | translation_enabled: false, |
| 806 | allowed_tools: None, |
| 807 | dynamic_tools: Vec::new(), |
| 808 | hook_executor: None, |
| 809 | verbosity: None, |
| 810 | provenance: UserInputProvenance::ExternalUser, |
| 811 | input_authorship: crate::core::ops::TurnInputAuthorship::NotPerson, |
| 812 | submission_id: None, |
| 813 | })) |
| 814 | .await |
| 815 | .expect("send declared custom turn"); |
| 816 | |
| 817 | let deadline = tokio::time::Instant::now() + Duration::from_secs(15); |
| 818 | let mut rx = handle.rx_event.write().await; |
| 819 | let quote = loop { |
| 820 | let event = tokio::time::timeout_at(deadline, rx.recv()) |
| 821 | .await |
| 822 | .expect("timed out waiting for route dispatch") |
| 823 | .expect("engine event channel closed before dispatch"); |
| 824 | if let Event::RouteDispatched { route, .. } = event { |
| 825 | break route |
| 826 | .billing |
| 827 | .and_then(|billing| billing.provider_live_pricing) |
| 828 | .expect("declared custom_models rate must be frozen at main-turn dispatch"); |
| 829 | } |
| 830 | }; |
| 831 | drop(rx); |
| 832 | assert_eq!( |
| 833 | quote.provenance, |
| 834 | codewhale_config::pricing::PricingProvenance::UserOverride |
| 835 | ); |
| 836 | assert_eq!(quote.input_per_million.as_deref(), Some("1")); |
| 837 | assert_eq!(quote.output_per_million.as_deref(), Some("2")); |
| 838 | assert_eq!(quote.cache_read_per_million, None); |
| 839 | handle.send(Op::Shutdown).await.expect("shutdown engine"); |
| 840 | run_task.await.expect("engine task"); |
| 841 | } |
| 842 | |
| 843 | struct GatedGoalModelClient { |
| 844 | calls: std::sync::atomic::AtomicUsize, |
| 845 | requests: std::sync::Mutex<Vec<codewhale_models::MessageRequest>>, |
| 846 | second_request_entered: std::sync::Arc<tokio::sync::Notify>, |
| 847 | release_second_request: std::sync::Arc<tokio::sync::Notify>, |
| 848 | first_usage: Option<Usage>, |
| 849 | } |
| 850 | |
| 851 | struct FirstRequestGatedGoalModelClient { |
| 852 | calls: std::sync::atomic::AtomicUsize, |
| 853 | request_entered: std::sync::Arc<tokio::sync::Notify>, |
| 854 | release_request: std::sync::Arc<tokio::sync::Notify>, |
| 855 | } |
| 856 | |
| 857 | struct IndexedGatedGoalModelClient { |
| 858 | calls: std::sync::atomic::AtomicUsize, |
| 859 | gates: HashMap< |
| 860 | usize, |
| 861 | ( |
| 862 | std::sync::Arc<tokio::sync::Notify>, |
| 863 | std::sync::Arc<tokio::sync::Notify>, |
| 864 | ), |
| 865 | >, |
| 866 | max_calls: usize, |
| 867 | } |
| 868 | |
| 869 | #[async_trait::async_trait] |
| 870 | impl crate::core::model_client::ModelClient for IndexedGatedGoalModelClient { |
| 871 | fn provider_name(&self) -> &str { |
| 872 | "deterministic-goal" |
| 873 | } |
| 874 | |
| 875 | fn model(&self) -> &str { |
| 876 | "local-model" |
| 877 | } |
| 878 | |
| 879 | async fn create_message( |
| 880 | &self, |
| 881 | _request: codewhale_models::MessageRequest, |
| 882 | ) -> anyhow::Result<codewhale_models::MessageResponse> { |
| 883 | anyhow::bail!("indexed gate regression uses the streaming model boundary") |
| 884 | } |
| 885 | |
| 886 | async fn create_message_stream( |
| 887 | &self, |
| 888 | _request: codewhale_models::MessageRequest, |
| 889 | ) -> anyhow::Result<crate::llm_client::StreamEventBox> { |
| 890 | let call = self |
| 891 | .calls |
| 892 | .fetch_add(1, std::sync::atomic::Ordering::SeqCst) |
| 893 | .saturating_add(1); |
| 894 | if call > self.max_calls { |
| 895 | anyhow::bail!("unexpected indexed goal model request #{call}"); |
| 896 | } |
| 897 | if let Some((entered, release)) = self.gates.get(&call).cloned() { |
| 898 | entered.notify_one(); |
| 899 | release.notified().await; |
| 900 | } |
| 901 | |
| 902 | let events = crate::llm_client::mock::canned::simple_text_turn("still working") |
| 903 | .into_iter() |
| 904 | .map(Ok); |
| 905 | Ok(Box::pin(futures_util::stream::iter(events))) |
| 906 | } |
| 907 | |
| 908 | async fn health_check(&self) -> anyhow::Result<bool> { |
| 909 | Ok(true) |
| 910 | } |
| 911 | } |
| 912 | |
| 913 | #[async_trait::async_trait] |
| 914 | impl crate::core::model_client::ModelClient for FirstRequestGatedGoalModelClient { |
| 915 | fn provider_name(&self) -> &str { |
| 916 | "deterministic-goal" |
| 917 | } |
| 918 | |
| 919 | fn model(&self) -> &str { |
| 920 | "local-model" |
| 921 | } |
| 922 | |
| 923 | async fn create_message( |
| 924 | &self, |
| 925 | _request: codewhale_models::MessageRequest, |
| 926 | ) -> anyhow::Result<codewhale_models::MessageResponse> { |
| 927 | anyhow::bail!("mailbox regression uses the streaming model boundary") |
| 928 | } |
| 929 | |
| 930 | async fn create_message_stream( |
| 931 | &self, |
| 932 | _request: codewhale_models::MessageRequest, |
| 933 | ) -> anyhow::Result<crate::llm_client::StreamEventBox> { |
| 934 | let call = self |
| 935 | .calls |
| 936 | .fetch_add(1, std::sync::atomic::Ordering::SeqCst) |
| 937 | .saturating_add(1); |
| 938 | if call > 1 { |
| 939 | anyhow::bail!("unexpected mailbox regression model request #{call}"); |
| 940 | } |
| 941 | self.request_entered.notify_one(); |
| 942 | self.release_request.notified().await; |
| 943 | |
| 944 | let events = crate::llm_client::mock::canned::simple_text_turn("still working") |
| 945 | .into_iter() |
| 946 | .map(Ok); |
| 947 | Ok(Box::pin(futures_util::stream::iter(events))) |
| 948 | } |
| 949 | |
| 950 | async fn health_check(&self) -> anyhow::Result<bool> { |
| 951 | Ok(true) |
| 952 | } |
| 953 | } |
| 954 | |
| 955 | struct FailingGoalModelClient { |
| 956 | calls: std::sync::atomic::AtomicUsize, |
| 957 | message: String, |
| 958 | } |
| 959 | |
| 960 | #[async_trait::async_trait] |
| 961 | impl crate::core::model_client::ModelClient for FailingGoalModelClient { |
| 962 | fn provider_name(&self) -> &str { |
| 963 | "deterministic-goal" |
| 964 | } |
| 965 | |
| 966 | fn model(&self) -> &str { |
| 967 | "local-model" |
| 968 | } |
| 969 | |
| 970 | async fn create_message( |
| 971 | &self, |
| 972 | _request: codewhale_models::MessageRequest, |
| 973 | ) -> anyhow::Result<codewhale_models::MessageResponse> { |
| 974 | anyhow::bail!("failure regression uses the streaming model boundary") |
| 975 | } |
| 976 | |
| 977 | async fn create_message_stream( |
| 978 | &self, |
| 979 | _request: codewhale_models::MessageRequest, |
| 980 | ) -> anyhow::Result<crate::llm_client::StreamEventBox> { |
| 981 | self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst); |
| 982 | anyhow::bail!(self.message.clone()) |
| 983 | } |
| 984 | |
| 985 | async fn health_check(&self) -> anyhow::Result<bool> { |
| 986 | Ok(true) |
| 987 | } |
| 988 | } |
| 989 | |
| 990 | impl GatedGoalModelClient { |
| 991 | fn captured_requests(&self) -> Vec<codewhale_models::MessageRequest> { |
| 992 | self.requests |
| 993 | .lock() |
| 994 | .expect("goal model request lock") |
| 995 | .clone() |
| 996 | } |
| 997 | } |
| 998 | |
| 999 | #[async_trait::async_trait] |
| 1000 | impl crate::core::model_client::ModelClient for GatedGoalModelClient { |
| 1001 | fn provider_name(&self) -> &str { |
| 1002 | "deterministic-goal" |
| 1003 | } |
| 1004 | |
| 1005 | fn model(&self) -> &str { |
| 1006 | "local-model" |
| 1007 | } |
| 1008 | |
| 1009 | async fn create_message( |
| 1010 | &self, |
| 1011 | _request: codewhale_models::MessageRequest, |
| 1012 | ) -> anyhow::Result<codewhale_models::MessageResponse> { |
| 1013 | anyhow::bail!("goal regression uses the streaming model boundary") |
| 1014 | } |
| 1015 | |
| 1016 | async fn create_message_stream( |
| 1017 | &self, |
| 1018 | request: codewhale_models::MessageRequest, |
| 1019 | ) -> anyhow::Result<crate::llm_client::StreamEventBox> { |
| 1020 | let call = self |
| 1021 | .calls |
| 1022 | .fetch_add(1, std::sync::atomic::Ordering::SeqCst) |
| 1023 | .saturating_add(1); |
| 1024 | self.requests |
| 1025 | .lock() |
| 1026 | .expect("goal model request lock") |
| 1027 | .push(request); |
| 1028 | if call == 2 { |
| 1029 | self.second_request_entered.notify_one(); |
| 1030 | self.release_second_request.notified().await; |
| 1031 | } else if call > 2 { |
| 1032 | anyhow::bail!("unexpected goal model request #{call}"); |
| 1033 | } |
| 1034 | |
| 1035 | let mut events = crate::llm_client::mock::canned::simple_text_turn("still working"); |
| 1036 | if call == 1 |
| 1037 | && let Some(usage) = self.first_usage.clone() |
| 1038 | && let Some(codewhale_models::StreamEvent::MessageDelta { usage: slot, .. }) = events |
| 1039 | .iter_mut() |
| 1040 | .find(|event| matches!(event, codewhale_models::StreamEvent::MessageDelta { .. })) |
| 1041 | { |
| 1042 | *slot = Some(usage); |
| 1043 | } |
| 1044 | let events = events.into_iter().map(Ok); |
| 1045 | Ok(Box::pin(futures_util::stream::iter(events))) |
| 1046 | } |
| 1047 | |
| 1048 | async fn health_check(&self) -> anyhow::Result<bool> { |
| 1049 | Ok(true) |
| 1050 | } |
| 1051 | } |
| 1052 | |
| 1053 | #[tokio::test] |
| 1054 | async fn goal_continuation_preserves_goal_and_resolves_updated_authoritative_route() { |
| 1055 | let first_base_url = "http://127.0.0.1:18181/v1".to_string(); |
| 1056 | let second_base_url = "http://127.0.0.1:18182/v1".to_string(); |
| 1057 | let second_request_entered = std::sync::Arc::new(tokio::sync::Notify::new()); |
| 1058 | let release_second_request = std::sync::Arc::new(tokio::sync::Notify::new()); |
| 1059 | let model = std::sync::Arc::new(GatedGoalModelClient { |
| 1060 | calls: std::sync::atomic::AtomicUsize::new(0), |
| 1061 | requests: std::sync::Mutex::new(Vec::new()), |
| 1062 | second_request_entered: std::sync::Arc::clone(&second_request_entered), |
| 1063 | release_second_request: std::sync::Arc::clone(&release_second_request), |
| 1064 | first_usage: Some(Usage { |
| 1065 | input_tokens: 3, |
| 1066 | output_tokens: 2, |
| 1067 | ..Usage::default() |
| 1068 | }), |
| 1069 | }); |
| 1070 | let mut custom = HashMap::new(); |
| 1071 | custom.insert( |
| 1072 | "custom-a".to_string(), |
| 1073 | codewhale_runtime::config::ProviderConfig { |
| 1074 | kind: Some("openai-compatible".to_string()), |
| 1075 | base_url: Some(first_base_url.clone()), |
| 1076 | model: Some("local-model".to_string()), |
| 1077 | api_key: Some("local-test-key".to_string()), |
| 1078 | ..codewhale_runtime::config::ProviderConfig::default() |
| 1079 | }, |
| 1080 | ); |
| 1081 | let config = { |
| 1082 | let __cw_config_init_7_0 = Some("custom-a".to_string()); |
| 1083 | let __cw_config_init_7_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 1084 | custom, |
| 1085 | ..codewhale_runtime::config::ProvidersConfig::default() |
| 1086 | }); |
| 1087 | let mut __cw_config_init_7_value: Config = Config::default(); |
| 1088 | __cw_config_init_7_value.provider = __cw_config_init_7_0; |
| 1089 | __cw_config_init_7_value.providers = __cw_config_init_7_1; |
| 1090 | __cw_config_init_7_value |
| 1091 | }; |
| 1092 | let engine_config = EngineConfig { |
| 1093 | max_steps: 1, |
| 1094 | snapshots_enabled: false, |
| 1095 | terminal_chrome_enabled: false, |
| 1096 | goal_objective: Some("keep going".to_string()), |
| 1097 | goal_token_budget: Some(50_000), |
| 1098 | ..EngineConfig::default() |
| 1099 | }; |
| 1100 | let authoritative = Arc::new(parking_lot::RwLock::new(config.clone())); |
| 1101 | let client: crate::core::model_client::SharedModelClient = model.clone(); |
| 1102 | let (mut engine, handle) = Engine::new_with_model_client(engine_config, &config, client); |
| 1103 | engine.authoritative_route_config = Some(Arc::clone(&authoritative)); |
| 1104 | let goal_state = engine.config.goal_state.clone(); |
| 1105 | |
| 1106 | handle |
| 1107 | .send(Op::SendMessage(TurnSpec { |
| 1108 | profile_constitution: None, |
| 1109 | max_output_tokens: None, |
| 1110 | content: "first turn".to_string(), |
| 1111 | images: Vec::new(), |
| 1112 | mode: AppMode::Agent, |
| 1113 | route: resolved_route_for_test(&config, "local-model"), |
| 1114 | compaction: Box::new(CompactionConfig::default()), |
| 1115 | initial_routed_usage: Box::default(), |
| 1116 | goal_objective: Some("keep going".to_string()), |
| 1117 | goal_token_budget: Some(50_000), |
| 1118 | goal_status: crate::tools::goal::GoalStatus::Active, |
| 1119 | reasoning_effort: None, |
| 1120 | reasoning_effort_auto: false, |
| 1121 | auto_model: false, |
| 1122 | allow_shell: false, |
| 1123 | trust_mode: false, |
| 1124 | auto_approve: false, |
| 1125 | approval_mode: ApprovalMode::Suggest, |
| 1126 | translation_enabled: false, |
| 1127 | allowed_tools: None, |
| 1128 | dynamic_tools: Vec::new(), |
| 1129 | hook_executor: None, |
| 1130 | verbosity: None, |
| 1131 | provenance: UserInputProvenance::ExternalUser, |
| 1132 | input_authorship: crate::core::ops::TurnInputAuthorship::NotPerson, |
| 1133 | submission_id: None, |
| 1134 | })) |
| 1135 | .await |
| 1136 | .expect("send first goal turn"); |
| 1137 | |
| 1138 | let mut reloaded = config; |
| 1139 | reloaded |
| 1140 | .providers |
| 1141 | .as_mut() |
| 1142 | .and_then(|providers| providers.custom.get_mut("custom-a")) |
| 1143 | .expect("custom route") |
| 1144 | .base_url = Some(second_base_url.clone()); |
| 1145 | *authoritative.write() = reloaded; |
| 1146 | let refreshed_route = engine |
| 1147 | .current_runtime_route() |
| 1148 | .expect("resolve the updated authoritative route"); |
| 1149 | assert_eq!( |
| 1150 | refreshed_route.candidate.endpoint().base_url, |
| 1151 | second_base_url, |
| 1152 | "the synthetic continuation must resolve the latest authoritative endpoint" |
| 1153 | ); |
| 1154 | let run_task = tokio::spawn(engine.run()); |
| 1155 | |
| 1156 | let mut lifecycle_starts = 0; |
| 1157 | let mut dispatches = 0; |
| 1158 | let mut completes = 0; |
| 1159 | let mut awaiting_second_sync = false; |
| 1160 | let mut verified_synthetic_goal = false; |
| 1161 | while completes < 2 { |
| 1162 | let event = tokio::time::timeout(Duration::from_secs(3), async { |
| 1163 | handle.rx_event.write().await.recv().await |
| 1164 | }) |
| 1165 | .await |
| 1166 | .expect("goal engine event timeout") |
| 1167 | .expect("goal engine event"); |
| 1168 | match event { |
| 1169 | Event::TurnStarted { route, .. } => { |
| 1170 | assert!( |
| 1171 | route.as_ref().is_none_or(|route| route.billing.is_none()), |
| 1172 | "lifecycle start must not carry billing time" |
| 1173 | ); |
| 1174 | lifecycle_starts += 1; |
| 1175 | if lifecycle_starts == 2 { |
| 1176 | awaiting_second_sync = true; |
| 1177 | } |
| 1178 | } |
| 1179 | Event::RouteDispatched { route, .. } => { |
| 1180 | dispatches += 1; |
| 1181 | assert_eq!(route.provider_identity, "custom-a"); |
| 1182 | let expected_base_url = if dispatches == 1 { |
| 1183 | first_base_url.as_str() |
| 1184 | } else { |
| 1185 | second_base_url.as_str() |
| 1186 | }; |
| 1187 | assert_eq!( |
| 1188 | route |
| 1189 | .billing |
| 1190 | .as_ref() |
| 1191 | .and_then(|billing| billing.endpoint_fingerprint.clone()), |
| 1192 | crate::cost_status::endpoint_fingerprint(expected_base_url), |
| 1193 | "goal continuation dispatch borrowed the wrong authoritative route" |
| 1194 | ); |
| 1195 | } |
| 1196 | Event::SessionUpdated { |
| 1197 | messages, |
| 1198 | system_prompt, |
| 1199 | .. |
| 1200 | } if awaiting_second_sync => { |
| 1201 | awaiting_second_sync = false; |
| 1202 | let snapshot = goal_state.lock().expect("goal lock").snapshot(); |
| 1203 | assert_eq!(snapshot.objective.as_deref(), Some("keep going")); |
| 1204 | assert_eq!(snapshot.token_budget, Some(50_000)); |
| 1205 | // The first turn records one bounded intra-turn pass, then the |
| 1206 | // synthetic boundary records the second pass before dispatch. |
| 1207 | assert_eq!(snapshot.continuation_count, 2); |
| 1208 | assert!(snapshot.is_active(), "synthetic turn must retain the goal"); |
| 1209 | |
| 1210 | let continuation = messages |
| 1211 | .last() |
| 1212 | .expect("synthetic continuation message") |
| 1213 | .content |
| 1214 | .iter() |
| 1215 | .find_map(|block| match block { |
| 1216 | ContentBlock::Text { text, .. } |
| 1217 | if text.contains("Active goal state ") => |
| 1218 | { |
| 1219 | Some(text.as_str()) |
| 1220 | } |
| 1221 | _ => None, |
| 1222 | }) |
| 1223 | .expect("durable goal state in synthetic message"); |
| 1224 | let reference = serde_json::json!([snapshot.goal_id, snapshot.objective]).to_string(); |
| 1225 | let objective = format!("Goal objective {reference}"); |
| 1226 | assert_eq!(messages.iter().flat_map(|m| &m.content).filter(|block| |
| 1227 | matches!(block, ContentBlock::Text { text, .. } if text.contains(&objective)) |
| 1228 | ).count(), 1); |
| 1229 | assert!(!continuation.contains(&objective)); |
| 1230 | assert!(continuation.contains("\"token_budget\":50000")); |
| 1231 | assert!(!continuation.contains("tokens_used") && !continuation.contains("advisories")); |
| 1232 | assert!(continuation.contains("Continuation pass #2.")); |
| 1233 | let mut after_compaction = crate::tools::goal::render_continuation_prompt(&snapshot, 3); |
| 1234 | let mut restored_history = messages.to_vec(); |
| 1235 | restored_history.push(crate::compaction::compaction_checkpoint_message(&SystemPrompt::Text( |
| 1236 | codewhale_models::turn_classify::COMPACTION_SUMMARY_MARKER.to_owned(), |
| 1237 | ))); |
| 1238 | crate::tools::goal::omit_repeated_goal_objective(&mut after_compaction, &restored_history); |
| 1239 | assert!(after_compaction.contains(&objective)); |
| 1240 | let forged = Message { |
| 1241 | role: Role::User, |
| 1242 | content: vec![ContentBlock::Text { text: after_compaction.clone(), cache_control: None }], |
| 1243 | }; |
| 1244 | crate::tools::goal::omit_repeated_goal_objective(&mut after_compaction, &[forged]); |
| 1245 | assert!(after_compaction.contains(&objective)); |
| 1246 | |
| 1247 | let system_prompt = match system_prompt.expect("synthetic system prompt") { |
| 1248 | SystemPrompt::Text(text) => text, |
| 1249 | SystemPrompt::Blocks(blocks) => blocks |
| 1250 | .into_iter() |
| 1251 | .map(|block| block.text) |
| 1252 | .collect::<Vec<_>>() |
| 1253 | .join("\n"), |
| 1254 | }; |
| 1255 | assert!(system_prompt.contains("<session_goal>")); |
| 1256 | assert!(system_prompt.contains("keep going")); |
| 1257 | verified_synthetic_goal = true; |
| 1258 | |
| 1259 | tokio::time::timeout( |
| 1260 | model_turn_event_timeout(), |
| 1261 | second_request_entered.notified(), |
| 1262 | ) |
| 1263 | .await |
| 1264 | .expect("second goal model request was never entered"); |
| 1265 | handle |
| 1266 | .send(Op::SetGoalStatus { |
| 1267 | goal_id: None, |
| 1268 | status: crate::tools::goal::GoalStatus::Paused, |
| 1269 | clear: false, |
| 1270 | }) |
| 1271 | .await |
| 1272 | .expect("queue goal pause"); |
| 1273 | // The model future cannot finish until the pause operation is |
| 1274 | // already in the engine mailbox, making the queue-order proof |
| 1275 | // deterministic under arbitrarily loaded CI runners. |
| 1276 | release_second_request.notify_one(); |
| 1277 | } |
| 1278 | Event::TurnComplete { base_url, .. } => { |
| 1279 | completes += 1; |
| 1280 | assert!( |
| 1281 | base_url.is_none(), |
| 1282 | "an injected provider-neutral transport must not claim the auxiliary route's endpoint" |
| 1283 | ); |
| 1284 | } |
| 1285 | _ => {} |
| 1286 | } |
| 1287 | } |
| 1288 | assert_eq!(lifecycle_starts, 2); |
| 1289 | assert_eq!(dispatches, 2); |
| 1290 | assert!(verified_synthetic_goal); |
| 1291 | let requests = model.captured_requests(); |
| 1292 | assert_eq!(requests.len(), 2); |
| 1293 | let first_intra_turn_prompt = requests[1] |
| 1294 | .messages |
| 1295 | .iter() |
| 1296 | .flat_map(|message| &message.content) |
| 1297 | .find_map(|block| match block { |
| 1298 | ContentBlock::Text { text, .. } if text.contains("Continuation pass #1.") => { |
| 1299 | Some(text.as_str()) |
| 1300 | } |
| 1301 | _ => None, |
| 1302 | }) |
| 1303 | .expect("first intra-turn goal snapshot must survive into the next request"); |
| 1304 | assert!( |
| 1305 | first_intra_turn_prompt.contains("\"goal_budget_remaining_tokens\":49995"), |
| 1306 | "remaining goal budget must include current-turn usage: {first_intra_turn_prompt}" |
| 1307 | ); |
| 1308 | |
| 1309 | // The pause was queued while the second turn was still running. Wait for |
| 1310 | // that control operation, then put a snapshot receipt behind the already |
| 1311 | // queued continuation. Receiving the receipt proves the continuation was |
| 1312 | // consumed; no third TurnStarted may have been emitted. |
| 1313 | let mut saw_paused_prompt = false; |
| 1314 | let mut saw_paused_goal = false; |
| 1315 | loop { |
| 1316 | let event = tokio::time::timeout(Duration::from_secs(3), async { |
| 1317 | handle.rx_event.write().await.recv().await |
| 1318 | }) |
| 1319 | .await |
| 1320 | .expect("goal pause event timeout") |
| 1321 | .expect("goal pause event"); |
| 1322 | match event { |
| 1323 | Event::SessionUpdated { |
| 1324 | system_prompt: Some(system_prompt), |
| 1325 | .. |
| 1326 | } => { |
| 1327 | let prompt = match system_prompt { |
| 1328 | SystemPrompt::Text(text) => text, |
| 1329 | SystemPrompt::Blocks(blocks) => blocks |
| 1330 | .into_iter() |
| 1331 | .map(|block| block.text) |
| 1332 | .collect::<Vec<_>>() |
| 1333 | .join("\n"), |
| 1334 | }; |
| 1335 | if !prompt.contains("<session_goal>") { |
| 1336 | saw_paused_prompt = true; |
| 1337 | } |
| 1338 | } |
| 1339 | Event::GoalUpdated { snapshot } if snapshot.status == "paused" => { |
| 1340 | assert_eq!(snapshot.objective.as_deref(), Some("keep going")); |
| 1341 | saw_paused_goal = true; |
| 1342 | } |
| 1343 | Event::Status { ref message } if message == "Goal paused." => { |
| 1344 | assert!( |
| 1345 | saw_paused_prompt, |
| 1346 | "pause status must follow the persisted prompt refresh" |
| 1347 | ); |
| 1348 | assert!( |
| 1349 | saw_paused_goal, |
| 1350 | "pause status must follow the visible goal snapshot" |
| 1351 | ); |
| 1352 | break; |
| 1353 | } |
| 1354 | Event::TurnStarted { .. } => { |
| 1355 | panic!("queued pause must prevent an additional goal turn") |
| 1356 | } |
| 1357 | _ => {} |
| 1358 | } |
| 1359 | } |
| 1360 | |
| 1361 | let (snapshot_tx, snapshot_rx) = tokio::sync::oneshot::channel(); |
| 1362 | handle |
| 1363 | .send(Op::GetSessionSnapshot { |
| 1364 | tx: std::sync::Arc::new(std::sync::Mutex::new(Some(snapshot_tx))), |
| 1365 | }) |
| 1366 | .await |
| 1367 | .expect("queue post-continuation receipt"); |
| 1368 | tokio::time::timeout(Duration::from_secs(3), snapshot_rx) |
| 1369 | .await |
| 1370 | .expect("post-continuation receipt timeout") |
| 1371 | .expect("post-continuation receipt"); |
| 1372 | { |
| 1373 | let mut events = handle.rx_event.write().await; |
| 1374 | while let Ok(event) = events.try_recv() { |
| 1375 | assert!( |
| 1376 | !matches!(event, Event::TurnStarted { .. }), |
| 1377 | "paused goal continuation started a stale turn" |
| 1378 | ); |
| 1379 | } |
| 1380 | } |
| 1381 | |
| 1382 | handle.send(Op::Shutdown).await.expect("queue shutdown"); |
| 1383 | run_task.await.expect("engine task"); |
| 1384 | } |
| 1385 | |
| 1386 | #[tokio::test] |
| 1387 | async fn saturated_mailbox_does_not_deadlock_goal_continuation_self_dispatch() { |
| 1388 | let request_entered = std::sync::Arc::new(tokio::sync::Notify::new()); |
| 1389 | let release_request = std::sync::Arc::new(tokio::sync::Notify::new()); |
| 1390 | let model = std::sync::Arc::new(FirstRequestGatedGoalModelClient { |
| 1391 | calls: std::sync::atomic::AtomicUsize::new(0), |
| 1392 | request_entered: std::sync::Arc::clone(&request_entered), |
| 1393 | release_request: std::sync::Arc::clone(&release_request), |
| 1394 | }); |
| 1395 | let config = goal_custom_route_config(); |
| 1396 | let engine_config = EngineConfig { |
| 1397 | model: "local-model".to_string(), |
| 1398 | max_steps: 1, |
| 1399 | snapshots_enabled: false, |
| 1400 | terminal_chrome_enabled: false, |
| 1401 | goal_objective: Some("survive a saturated mailbox".to_string()), |
| 1402 | ..EngineConfig::default() |
| 1403 | }; |
| 1404 | let client: crate::core::model_client::SharedModelClient = model.clone(); |
| 1405 | let (engine, handle) = Engine::new_with_model_client(engine_config, &config, client); |
| 1406 | let goal_state = engine.config.goal_state.clone(); |
| 1407 | let run_task = tokio::spawn(engine.run()); |
| 1408 | |
| 1409 | handle |
| 1410 | .send(Op::SendMessage(TurnSpec { |
| 1411 | profile_constitution: None, |
| 1412 | max_output_tokens: None, |
| 1413 | content: "start the saturated goal turn".to_string(), |
| 1414 | images: Vec::new(), |
| 1415 | mode: AppMode::Agent, |
| 1416 | route: resolved_route_for_test(&config, "local-model"), |
| 1417 | compaction: Box::new(CompactionConfig::default()), |
| 1418 | initial_routed_usage: Box::default(), |
| 1419 | goal_objective: Some("survive a saturated mailbox".to_string()), |
| 1420 | goal_token_budget: None, |
| 1421 | goal_status: crate::tools::goal::GoalStatus::Active, |
| 1422 | reasoning_effort: None, |
| 1423 | reasoning_effort_auto: false, |
| 1424 | auto_model: false, |
| 1425 | allow_shell: false, |
| 1426 | trust_mode: false, |
| 1427 | auto_approve: false, |
| 1428 | approval_mode: ApprovalMode::Suggest, |
| 1429 | translation_enabled: false, |
| 1430 | allowed_tools: None, |
| 1431 | dynamic_tools: Vec::new(), |
| 1432 | hook_executor: None, |
| 1433 | verbosity: None, |
| 1434 | provenance: UserInputProvenance::ExternalUser, |
| 1435 | input_authorship: crate::core::ops::TurnInputAuthorship::NotPerson, |
| 1436 | submission_id: None, |
| 1437 | })) |
| 1438 | .await |
| 1439 | .expect("send saturated goal turn"); |
| 1440 | tokio::time::timeout(model_turn_event_timeout(), request_entered.notified()) |
| 1441 | .await |
| 1442 | .expect("first goal request was never entered"); |
| 1443 | |
| 1444 | // The engine has consumed the SendMessage and is gated inside the model |
| 1445 | // request, so every slot below belongs to a queued control operation. The |
| 1446 | // final pause must remain ahead of the synthetic continuation. |
| 1447 | for index in 0..ENGINE_OP_CHANNEL_CAPACITY { |
| 1448 | let status = if index + 1 == ENGINE_OP_CHANNEL_CAPACITY { |
| 1449 | crate::tools::goal::GoalStatus::Paused |
| 1450 | } else { |
| 1451 | crate::tools::goal::GoalStatus::Active |
| 1452 | }; |
| 1453 | handle |
| 1454 | .tx_op |
| 1455 | .try_send(Op::SetGoalStatus { |
| 1456 | goal_id: None, |
| 1457 | status, |
| 1458 | clear: false, |
| 1459 | }) |
| 1460 | .unwrap_or_else(|error| panic!("fill op mailbox slot {index}: {error}")); |
| 1461 | } |
| 1462 | assert_eq!(handle.tx_op.capacity(), 0, "fixture must saturate mailbox"); |
| 1463 | |
| 1464 | release_request.notify_one(); |
| 1465 | let session = tokio::time::timeout(model_turn_event_timeout(), handle.get_session_snapshot()) |
| 1466 | .await |
| 1467 | .expect("saturated mailbox deadlocked the engine") |
| 1468 | .expect("post-saturation session snapshot"); |
| 1469 | |
| 1470 | let prompt = match session.system_prompt.expect("paused system prompt") { |
| 1471 | SystemPrompt::Text(text) => text, |
| 1472 | SystemPrompt::Blocks(blocks) => blocks |
| 1473 | .into_iter() |
| 1474 | .map(|block| block.text) |
| 1475 | .collect::<Vec<_>>() |
| 1476 | .join("\n"), |
| 1477 | }; |
| 1478 | assert!(!prompt.contains("<session_goal>"), "{prompt}"); |
| 1479 | let goal = goal_state.lock().expect("goal lock").snapshot(); |
| 1480 | assert_eq!(goal.status, "paused"); |
| 1481 | assert_eq!( |
| 1482 | model.calls.load(std::sync::atomic::Ordering::SeqCst), |
| 1483 | 1, |
| 1484 | "the queued pause must suppress the stale continuation" |
| 1485 | ); |
| 1486 | |
| 1487 | let mut starts = 0; |
| 1488 | { |
| 1489 | let mut events = handle.rx_event.write().await; |
| 1490 | while let Ok(event) = events.try_recv() { |
| 1491 | if matches!(event, Event::TurnStarted { .. }) { |
| 1492 | starts += 1; |
| 1493 | } |
| 1494 | } |
| 1495 | } |
| 1496 | assert_eq!(starts, 1, "only the original goal turn may start"); |
| 1497 | |
| 1498 | handle.send(Op::Shutdown).await.expect("shutdown engine"); |
| 1499 | tokio::time::timeout(model_turn_event_timeout(), run_task) |
| 1500 | .await |
| 1501 | .expect("engine did not shut down after mailbox saturation") |
| 1502 | .expect("engine task"); |
| 1503 | } |
| 1504 | |
| 1505 | #[tokio::test] |
| 1506 | async fn queued_ordinary_turn_does_not_multiply_engine_goal_continuations() { |
| 1507 | let first_entered = std::sync::Arc::new(tokio::sync::Notify::new()); |
| 1508 | let release_first = std::sync::Arc::new(tokio::sync::Notify::new()); |
| 1509 | let third_entered = std::sync::Arc::new(tokio::sync::Notify::new()); |
| 1510 | let release_third = std::sync::Arc::new(tokio::sync::Notify::new()); |
| 1511 | let model = std::sync::Arc::new(IndexedGatedGoalModelClient { |
| 1512 | calls: std::sync::atomic::AtomicUsize::new(0), |
| 1513 | gates: HashMap::from([ |
| 1514 | ( |
| 1515 | 1, |
| 1516 | ( |
| 1517 | std::sync::Arc::clone(&first_entered), |
| 1518 | std::sync::Arc::clone(&release_first), |
| 1519 | ), |
| 1520 | ), |
| 1521 | ( |
| 1522 | 3, |
| 1523 | ( |
| 1524 | std::sync::Arc::clone(&third_entered), |
| 1525 | std::sync::Arc::clone(&release_third), |
| 1526 | ), |
| 1527 | ), |
| 1528 | ]), |
| 1529 | max_calls: 3, |
| 1530 | }); |
| 1531 | let config = goal_custom_route_config(); |
| 1532 | let engine_config = EngineConfig { |
| 1533 | model: "local-model".to_string(), |
| 1534 | max_steps: 1, |
| 1535 | snapshots_enabled: false, |
| 1536 | terminal_chrome_enabled: false, |
| 1537 | goal_objective: Some("coalesce queued goal turns".to_string()), |
| 1538 | ..EngineConfig::default() |
| 1539 | }; |
| 1540 | let client: crate::core::model_client::SharedModelClient = model.clone(); |
| 1541 | let (engine, handle) = Engine::new_with_model_client(engine_config, &config, client); |
| 1542 | let goal_state = engine.config.goal_state.clone(); |
| 1543 | let run_task = tokio::spawn(engine.run()); |
| 1544 | let send_message = |content: &str| { |
| 1545 | Op::SendMessage(TurnSpec { |
| 1546 | profile_constitution: None, |
| 1547 | max_output_tokens: None, |
| 1548 | content: content.to_string(), |
| 1549 | images: Vec::new(), |
| 1550 | mode: AppMode::Agent, |
| 1551 | route: resolved_route_for_test(&config, "local-model"), |
| 1552 | compaction: Box::new(CompactionConfig::default()), |
| 1553 | initial_routed_usage: Box::default(), |
| 1554 | goal_objective: Some("coalesce queued goal turns".to_string()), |
| 1555 | goal_token_budget: None, |
| 1556 | goal_status: crate::tools::goal::GoalStatus::Active, |
| 1557 | reasoning_effort: None, |
| 1558 | reasoning_effort_auto: false, |
| 1559 | auto_model: false, |
| 1560 | allow_shell: false, |
| 1561 | trust_mode: false, |
| 1562 | auto_approve: false, |
| 1563 | approval_mode: ApprovalMode::Suggest, |
| 1564 | translation_enabled: false, |
| 1565 | allowed_tools: None, |
| 1566 | dynamic_tools: Vec::new(), |
| 1567 | hook_executor: None, |
| 1568 | verbosity: None, |
| 1569 | provenance: UserInputProvenance::ExternalUser, |
| 1570 | input_authorship: crate::core::ops::TurnInputAuthorship::NotPerson, |
| 1571 | submission_id: None, |
| 1572 | }) |
| 1573 | }; |
| 1574 | |
| 1575 | handle |
| 1576 | .send(send_message("start the goal turn")) |
| 1577 | .await |
| 1578 | .expect("send first goal turn"); |
| 1579 | tokio::time::timeout(model_turn_event_timeout(), first_entered.notified()) |
| 1580 | .await |
| 1581 | .expect("first goal request was never entered"); |
| 1582 | |
| 1583 | // This ordinary user turn is already ahead of the first synthetic token |
| 1584 | // when the gated turn completes. It may refresh that token's tools, but it |
| 1585 | // must not create a second autonomous continuation. |
| 1586 | handle |
| 1587 | .send(send_message("queued ordinary follow-up")) |
| 1588 | .await |
| 1589 | .expect("queue ordinary follow-up"); |
| 1590 | release_first.notify_one(); |
| 1591 | |
| 1592 | tokio::time::timeout(model_turn_event_timeout(), third_entered.notified()) |
| 1593 | .await |
| 1594 | .expect("coalesced synthetic continuation was never entered"); |
| 1595 | handle |
| 1596 | .send(Op::SetGoalStatus { |
| 1597 | goal_id: None, |
| 1598 | status: crate::tools::goal::GoalStatus::Paused, |
| 1599 | clear: false, |
| 1600 | }) |
| 1601 | .await |
| 1602 | .expect("queue goal pause behind synthetic turn"); |
| 1603 | release_third.notify_one(); |
| 1604 | |
| 1605 | let _session = tokio::time::timeout(model_turn_event_timeout(), handle.get_session_snapshot()) |
| 1606 | .await |
| 1607 | .expect("queued-turn coalescing did not settle") |
| 1608 | .expect("post-coalescing session snapshot"); |
| 1609 | assert_eq!( |
| 1610 | model.calls.load(std::sync::atomic::Ordering::SeqCst), |
| 1611 | 3, |
| 1612 | "one initial turn, one queued user turn, and one synthetic continuation are expected" |
| 1613 | ); |
| 1614 | assert_eq!( |
| 1615 | goal_state.lock().expect("goal lock").snapshot().status, |
| 1616 | "paused" |
| 1617 | ); |
| 1618 | |
| 1619 | handle.send(Op::Shutdown).await.expect("shutdown engine"); |
| 1620 | tokio::time::timeout(model_turn_event_timeout(), run_task) |
| 1621 | .await |
| 1622 | .expect("engine did not shut down after queued-turn coalescing") |
| 1623 | .expect("engine task"); |
| 1624 | } |
| 1625 |