| 1 | //! Scripted-provider fixture for the one context-pressure number (0.10.1 |
| 2 | //! item 9). |
| 3 | //! |
| 4 | //! A tool-heavy turn crosses the auto-compaction threshold mid-turn, compacts, |
| 5 | //! then the next turn switches route and endpoint and continues. At every |
| 6 | //! model request the engine actually sent, the context meter, the |
| 7 | //! auto-compaction gate, the compaction preflight, and the `/context` headline |
| 8 | //! must read the same number — and it must be the pressure estimate, not the |
| 9 | //! 1.5x-inflated overflow guard, which `/context` shows only as a labeled |
| 10 | //! secondary line. |
| 11 | |
| 12 | use std::time::Duration; |
| 13 | |
| 14 | use codewhale_models::MessageRequest; |
| 15 | use serde_json::json; |
| 16 | use tempfile::tempdir; |
| 17 | |
| 18 | use super::{build_context_report, format_context_report, format_context_summary}; |
| 19 | use crate::test_support::{EnvVarGuard, lock_test_env}; |
| 20 | use crate::tui::app::App; |
| 21 | use codewhale_engine::compaction::{ |
| 22 | CompactionConfig, compaction_pressure_reached_with_billed, estimate_input_tokens_conservative, |
| 23 | estimate_input_tokens_for_pressure, |
| 24 | }; |
| 25 | use codewhale_engine::core::engine::{Engine, EngineConfig}; |
| 26 | use codewhale_engine::core::events::{Event, TurnOutcomeStatus}; |
| 27 | use codewhale_engine::core::ops::{Op, TurnSpec, UserInputProvenance}; |
| 28 | use codewhale_engine::llm_client::mock::{MockLlmClient, canned}; |
| 29 | use codewhale_engine::route_runtime::{ResolvedRuntimeRoute, resolve_runtime_route}; |
| 30 | use codewhale_runtime::config::Config; |
| 31 | |
| 32 | const THRESHOLD: usize = 40_000; |
| 33 | const PRIVATE_BASE_URL: &str = "https://private-fixture.test/v1"; |
| 34 | const PRIVATE_MODEL: &str = "private-fixture-deployment"; |
| 35 | const PRIVATE_WINDOW: u32 = 200_000; |
| 36 | |
| 37 | fn private_route_config() -> Config { |
| 38 | { |
| 39 | let __cw_config_init_0_0 = Some("custom".to_string()); |
| 40 | let __cw_config_init_0_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 41 | custom: std::collections::HashMap::from([( |
| 42 | "custom".to_string(), |
| 43 | codewhale_runtime::config::ProviderConfig { |
| 44 | kind: Some("openai-compatible".to_string()), |
| 45 | api_key: Some("test-private-key".to_string()), |
| 46 | base_url: Some(PRIVATE_BASE_URL.to_string()), |
| 47 | model: Some(PRIVATE_MODEL.to_string()), |
| 48 | context_window: Some(PRIVATE_WINDOW), |
| 49 | ..Default::default() |
| 50 | }, |
| 51 | )]), |
| 52 | ..Default::default() |
| 53 | }); |
| 54 | let mut __cw_config_init_0_value: Config = Default::default(); |
| 55 | __cw_config_init_0_value.provider = __cw_config_init_0_0; |
| 56 | __cw_config_init_0_value.providers = __cw_config_init_0_1; |
| 57 | __cw_config_init_0_value |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | fn resolve(config: &Config, model: &str) -> ResolvedRuntimeRoute { |
| 62 | resolve_runtime_route( |
| 63 | config, |
| 64 | config.active_provider_identity().unwrap().provider, |
| 65 | Some(model), |
| 66 | ) |
| 67 | .expect("resolve route") |
| 68 | } |
| 69 | |
| 70 | fn fixture_compaction() -> CompactionConfig { |
| 71 | CompactionConfig { |
| 72 | token_threshold: THRESHOLD, |
| 73 | ..CompactionConfig::default() |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | fn turn_op(content: &str, route: &ResolvedRuntimeRoute) -> Op { |
| 78 | let compaction = fixture_compaction(); |
| 79 | Op::SendMessage(TurnSpec { |
| 80 | profile_constitution: None, |
| 81 | max_output_tokens: None, |
| 82 | content: content.to_string(), |
| 83 | images: Vec::new(), |
| 84 | mode: codewhale_config::AppMode::Agent, |
| 85 | route: Box::new(route.clone()), |
| 86 | compaction: Box::new(compaction), |
| 87 | initial_routed_usage: Box::default(), |
| 88 | goal_objective: None, |
| 89 | goal_token_budget: None, |
| 90 | goal_status: codewhale_engine::tools::goal::GoalStatus::Active, |
| 91 | reasoning_effort: None, |
| 92 | reasoning_effort_auto: false, |
| 93 | auto_model: false, |
| 94 | allow_shell: true, |
| 95 | trust_mode: false, |
| 96 | auto_approve: true, |
| 97 | approval_mode: codewhale_execpolicy::ApprovalMode::Suggest, |
| 98 | translation_enabled: false, |
| 99 | allowed_tools: None, |
| 100 | dynamic_tools: Vec::new(), |
| 101 | hook_executor: None, |
| 102 | verbosity: None, |
| 103 | provenance: UserInputProvenance::ExternalUser, |
| 104 | input_authorship: codewhale_engine::core::ops::TurnInputAuthorship::NotPerson, |
| 105 | submission_id: None, |
| 106 | }) |
| 107 | } |
| 108 | |
| 109 | fn tool_step(step: usize, payload_chars: usize) -> Vec<codewhale_models::StreamEvent> { |
| 110 | vec![ |
| 111 | canned::message_start(&format!("response-{step}")), |
| 112 | canned::text_block_start(0), |
| 113 | canned::text_delta(0, &format!("Step {step}: {}", "x".repeat(payload_chars))), |
| 114 | canned::block_stop(0), |
| 115 | canned::tool_use_block_start(1, &format!("read-{step}"), "read"), |
| 116 | canned::tool_input_delta(1, r#"{"path":"README.md"}"#), |
| 117 | canned::block_stop(1), |
| 118 | canned::message_delta("tool_use", None), |
| 119 | canned::message_stop(), |
| 120 | ] |
| 121 | } |
| 122 | |
| 123 | #[derive(Debug, Default)] |
| 124 | struct TurnEvents { |
| 125 | auto_compactions: usize, |
| 126 | receipts: Vec<(String, Option<u64>)>, |
| 127 | } |
| 128 | |
| 129 | async fn run_turn(handle: &codewhale_engine::core::engine::EngineHandle, op: Op) -> TurnEvents { |
| 130 | handle.send(op).await.expect("send turn"); |
| 131 | let mut events = TurnEvents::default(); |
| 132 | let mut rx = handle.rx_event.write().await; |
| 133 | loop { |
| 134 | match tokio::time::timeout(Duration::from_secs(30), rx.recv()) |
| 135 | .await |
| 136 | .expect("engine event before timeout") |
| 137 | .expect("engine event channel open") |
| 138 | { |
| 139 | Event::CompactionCompleted { |
| 140 | auto: true, |
| 141 | message, |
| 142 | post_input_tokens, |
| 143 | .. |
| 144 | } => { |
| 145 | events.auto_compactions += 1; |
| 146 | events.receipts.push((message, post_input_tokens)); |
| 147 | } |
| 148 | Event::CompactionFailed { message, .. } => { |
| 149 | panic!("fixture compaction must succeed: {message}") |
| 150 | } |
| 151 | Event::TurnComplete { status, error, .. } => { |
| 152 | assert_eq!(status, TurnOutcomeStatus::Completed, "{error:?}"); |
| 153 | return events; |
| 154 | } |
| 155 | _ => {} |
| 156 | } |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | /// Mirror the engine's installed route and the exact request it sent into a |
| 161 | /// TUI `App`, then read every surface. Returns the one agreed number. |
| 162 | fn assert_one_pressure_number( |
| 163 | app: &mut App, |
| 164 | label: &str, |
| 165 | request: &MessageRequest, |
| 166 | route: &ResolvedRuntimeRoute, |
| 167 | ) -> usize { |
| 168 | app.api_provider = route.identity.provider; |
| 169 | app.model = route.model.clone(); |
| 170 | app.active_route_limits = |
| 171 | codewhale_engine::route_budget::known_route_limits(route.candidate.limits()); |
| 172 | app.active_context_window_source = route.context_window.source; |
| 173 | app.active_context_window = Some(route.context_window); |
| 174 | // Install the transcript the way the host applies an engine session |
| 175 | // projection (`apply_engine_session_projection`): the meter's per-message |
| 176 | // cache is dropped before the rewritten history lands, so a compaction |
| 177 | // cannot leave stale per-index counts behind. |
| 178 | app.context_token_cache.borrow_mut().clear(); |
| 179 | app.set_api_messages(std::sync::Arc::new(request.messages.clone())); |
| 180 | app.system_prompt = request.system.clone(); |
| 181 | // Mock usage bills no prompt tokens; the number is the estimate alone. |
| 182 | app.last_billed_input_tokens = None; |
| 183 | |
| 184 | let messages = &request.messages; |
| 185 | let system = request.system.as_ref(); |
| 186 | |
| 187 | // Auto-compaction gate. |
| 188 | let gate = estimate_input_tokens_for_pressure(messages, system); |
| 189 | let compaction = fixture_compaction(); |
| 190 | assert_eq!( |
| 191 | compaction_pressure_reached_with_billed(messages, system, &compaction, None), |
| 192 | gate >= THRESHOLD, |
| 193 | "{label}: gate decision must follow the gate number {gate}" |
| 194 | ); |
| 195 | |
| 196 | // Compaction preflight (live input the turn loop measures). |
| 197 | let preflight = codewhale_engine::core::turn::TurnContext::new(8) |
| 198 | .live_input_tokens_for_compaction(messages, system, None) |
| 199 | .expect("non-empty request"); |
| 200 | |
| 201 | // Context meter (footer). |
| 202 | let (meter, meter_window, meter_percent) = |
| 203 | crate::tui::ui::context_usage_snapshot(app).expect("meter reading"); |
| 204 | |
| 205 | // `/context` headline. |
| 206 | let report = build_context_report(app); |
| 207 | |
| 208 | assert_eq!(preflight, gate as u64, "{label}: preflight vs gate"); |
| 209 | assert_eq!(meter, gate as i64, "{label}: meter vs gate"); |
| 210 | assert_eq!( |
| 211 | report.active_context_estimated_tokens, gate, |
| 212 | "{label}: /context headline vs gate" |
| 213 | ); |
| 214 | assert_eq!( |
| 215 | report.context_window_tokens, |
| 216 | Some(meter_window), |
| 217 | "{label}: /context window vs meter window" |
| 218 | ); |
| 219 | let report_percent = report.budget_used_percent.expect("window known"); |
| 220 | assert!( |
| 221 | (report_percent - meter_percent).abs() < 1e-9, |
| 222 | "{label}: /context {report_percent}% vs meter {meter_percent}%" |
| 223 | ); |
| 224 | |
| 225 | // The inflated figure is only the labeled secondary overflow-guard line. |
| 226 | let guard = estimate_input_tokens_conservative(messages, system); |
| 227 | assert!( |
| 228 | guard > gate, |
| 229 | "{label}: fixture must separate the estimators" |
| 230 | ); |
| 231 | assert_eq!(report.overflow_guard_estimated_tokens, Some(guard)); |
| 232 | for text in [ |
| 233 | format_context_report(&report), |
| 234 | format_context_summary(&report), |
| 235 | ] { |
| 236 | assert!( |
| 237 | text.contains(&format!("Estimated active context: {gate} tokens")), |
| 238 | "{label}: {text}" |
| 239 | ); |
| 240 | assert!( |
| 241 | text.contains(&format!("Overflow guard: {guard} tokens")), |
| 242 | "{label}: {text}" |
| 243 | ); |
| 244 | } |
| 245 | |
| 246 | // Once the provider bills a prompt above the local estimate, every |
| 247 | // surface lifts to the bill together — the footer meter included. |
| 248 | let billed = gate + 7_000; |
| 249 | app.last_billed_input_tokens = Some(u32::try_from(billed).expect("fixture bill")); |
| 250 | let billed_u64 = billed as u64; |
| 251 | assert_eq!( |
| 252 | compaction_pressure_reached_with_billed(messages, system, &compaction, Some(billed_u64)), |
| 253 | billed >= THRESHOLD, |
| 254 | "{label}: billed gate decision" |
| 255 | ); |
| 256 | let billed_preflight = codewhale_engine::core::turn::TurnContext::new(8) |
| 257 | .live_input_tokens_for_compaction( |
| 258 | messages, |
| 259 | system, |
| 260 | Some(u32::try_from(billed).expect("fixture bill")), |
| 261 | ) |
| 262 | .expect("non-empty request"); |
| 263 | let (billed_meter, _, _) = crate::tui::ui::context_usage_snapshot(app).expect("meter reading"); |
| 264 | let billed_report = build_context_report(app); |
| 265 | assert_eq!(billed_preflight, billed_u64, "{label}: billed preflight"); |
| 266 | assert_eq!(billed_meter, billed as i64, "{label}: billed meter"); |
| 267 | assert_eq!( |
| 268 | billed_report.active_context_estimated_tokens, billed, |
| 269 | "{label}: billed /context headline" |
| 270 | ); |
| 271 | app.last_billed_input_tokens = None; |
| 272 | gate |
| 273 | } |
| 274 | |
| 275 | /// The `~before → ~after tokens` pair a compaction receipt prints. |
| 276 | fn receipt_token_pair(message: &str) -> (usize, usize) { |
| 277 | let (_, tail) = message.split_once("), ~").expect("receipt token clause"); |
| 278 | let (before, rest) = tail.split_once(" → ~").expect("receipt arrow"); |
| 279 | let (after, _) = rest.split_once(" tokens").expect("receipt tokens"); |
| 280 | ( |
| 281 | before.parse().expect("before tokens"), |
| 282 | after.parse().expect("after tokens"), |
| 283 | ) |
| 284 | } |
| 285 | |
| 286 | fn streaming(requests: &[MessageRequest]) -> Vec<MessageRequest> { |
| 287 | requests |
| 288 | .iter() |
| 289 | .filter(|request| request.stream == Some(true)) |
| 290 | .cloned() |
| 291 | .collect() |
| 292 | } |
| 293 | |
| 294 | #[test] |
| 295 | fn one_pressure_number_across_mid_turn_compaction_and_route_switch() { |
| 296 | let _env = lock_test_env(); |
| 297 | let home = tempdir().expect("home"); |
| 298 | let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 299 | let _user_home = EnvVarGuard::set("HOME", home.path()); |
| 300 | let _user_profile = EnvVarGuard::set("USERPROFILE", home.path()); |
| 301 | let runtime = tokio::runtime::Builder::new_current_thread() |
| 302 | .enable_all() |
| 303 | .build() |
| 304 | .expect("runtime"); |
| 305 | runtime.block_on(async { |
| 306 | let workspace = tempdir().expect("workspace"); |
| 307 | std::fs::write(workspace.path().join("README.md"), "verified fixture evidence") |
| 308 | .expect("write fixture"); |
| 309 | |
| 310 | let default_config = Config::default(); |
| 311 | let route_a = resolve(&default_config, codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL); |
| 312 | let private_config = private_route_config(); |
| 313 | let route_b = resolve(&private_config, PRIVATE_MODEL); |
| 314 | assert_ne!( |
| 315 | route_a.candidate.endpoint().base_url, |
| 316 | route_b.candidate.endpoint().base_url, |
| 317 | "the second turn must switch endpoint" |
| 318 | ); |
| 319 | assert_ne!(route_a.model, route_b.model, "and route"); |
| 320 | |
| 321 | // Turn 1: tool-heavy, crosses the threshold mid-turn. |
| 322 | let mock = std::sync::Arc::new(MockLlmClient::new(Vec::new())); |
| 323 | for step in 0..8 { |
| 324 | mock.push_turn(tool_step(step, 32_000)); |
| 325 | } |
| 326 | mock.push_turn(canned::simple_text_turn("All reads verified on route A.")); |
| 327 | // Turn 2: continues on the new route and endpoint. |
| 328 | mock.push_turn(tool_step(100, 400)); |
| 329 | mock.push_turn(canned::simple_text_turn("Continued on route B.")); |
| 330 | for checkpoint in 0..6 { |
| 331 | mock.push_message_response( |
| 332 | serde_json::from_value(json!({ |
| 333 | "id": format!("summary-{checkpoint}"), |
| 334 | "type": "message", |
| 335 | "role": "assistant", |
| 336 | "content": [{"type": "text", "text": format!( |
| 337 | "Current objective: finish the README reads. Checkpoint {checkpoint}: earlier reads verified; continue the remaining reads, then report." |
| 338 | )}], |
| 339 | "model": "mock-model", |
| 340 | "usage": {"input_tokens": 0, "output_tokens": 0} |
| 341 | })) |
| 342 | .expect("summary response"), |
| 343 | ); |
| 344 | } |
| 345 | |
| 346 | let engine_config = EngineConfig { |
| 347 | workspace: workspace.path().to_path_buf(), |
| 348 | snapshots_enabled: false, |
| 349 | subagents_enabled: false, |
| 350 | ..EngineConfig::default() |
| 351 | }; |
| 352 | let (engine, handle) = |
| 353 | Engine::new_with_model_client(engine_config, &default_config, mock.clone()); |
| 354 | let task = tokio::spawn(engine.run()); |
| 355 | |
| 356 | let turn_one = run_turn( |
| 357 | &handle, |
| 358 | turn_op("Read README.md repeatedly and verify it.", &route_a), |
| 359 | ) |
| 360 | .await; |
| 361 | let after_turn_one = mock.captured_requests().len(); |
| 362 | let turn_two = run_turn(&handle, turn_op("Continue on the new route.", &route_b)).await; |
| 363 | handle.send(Op::Shutdown).await.expect("shutdown"); |
| 364 | task.await.expect("engine task"); |
| 365 | |
| 366 | let requests = mock.captured_requests(); |
| 367 | let turn_one_requests = streaming(&requests[..after_turn_one]); |
| 368 | let turn_two_requests = streaming(&requests[after_turn_one..]); |
| 369 | assert_eq!(turn_one_requests.len(), 9, "one request per scripted step"); |
| 370 | assert_eq!(turn_two_requests.len(), 2, "turn two continues"); |
| 371 | assert!( |
| 372 | turn_one.auto_compactions >= 1, |
| 373 | "turn one must compact mid-turn: {turn_one:?}" |
| 374 | ); |
| 375 | assert_eq!( |
| 376 | turn_two.auto_compactions, 0, |
| 377 | "turn two stays under the threshold: {turn_two:?}" |
| 378 | ); |
| 379 | for request in &turn_two_requests { |
| 380 | assert_eq!(request.model, PRIVATE_MODEL, "turn two uses route B"); |
| 381 | } |
| 382 | |
| 383 | let mut app = crate::tui::test_support::test_app_with_options( |
| 384 | crate::tui::test_support::test_tui_options(workspace.path()), |
| 385 | ); |
| 386 | let mut readings = Vec::new(); |
| 387 | for (index, request) in turn_one_requests.iter().enumerate() { |
| 388 | readings.push(assert_one_pressure_number( |
| 389 | &mut app, |
| 390 | &format!("turn 1 request {index}"), |
| 391 | request, |
| 392 | &route_a, |
| 393 | )); |
| 394 | } |
| 395 | // The compaction happened mid-turn: the transcript shrank between two |
| 396 | // requests of the same turn, and the pressure number fell with it. |
| 397 | let shrink = turn_one_requests |
| 398 | .windows(2) |
| 399 | .position(|pair| pair[1].messages.len() < pair[0].messages.len()) |
| 400 | .expect("a mid-turn compaction shrinks the next request"); |
| 401 | assert!( |
| 402 | readings[shrink + 1] < readings[shrink], |
| 403 | "pressure falls across the compaction: {readings:?}" |
| 404 | ); |
| 405 | assert!( |
| 406 | readings[..=shrink].iter().any(|tokens| *tokens + 16_000 >= THRESHOLD), |
| 407 | "the turn approached the threshold before compacting: {readings:?}" |
| 408 | ); |
| 409 | |
| 410 | let (_, window_a, _) = crate::tui::ui::context_usage_snapshot(&app).expect("meter"); |
| 411 | for (index, request) in turn_two_requests.iter().enumerate() { |
| 412 | assert_one_pressure_number( |
| 413 | &mut app, |
| 414 | &format!("turn 2 request {index}"), |
| 415 | request, |
| 416 | &route_b, |
| 417 | ); |
| 418 | } |
| 419 | let (_, window_b, _) = crate::tui::ui::context_usage_snapshot(&app).expect("meter"); |
| 420 | assert_eq!(window_b, PRIVATE_WINDOW, "meter follows the switched route"); |
| 421 | assert_ne!(window_a, window_b, "the route switch changes the window"); |
| 422 | |
| 423 | // Compaction receipts report the same pressure number: the printed |
| 424 | // `after` equals `post_input_tokens`, which is the reading of the |
| 425 | // first request sent after that compaction. The printed `before` |
| 426 | // crossed the gate's threshold. |
| 427 | let shrinks: Vec<usize> = turn_one_requests |
| 428 | .windows(2) |
| 429 | .enumerate() |
| 430 | .filter(|(_, pair)| pair[1].messages.len() < pair[0].messages.len()) |
| 431 | .map(|(index, _)| index + 1) |
| 432 | .collect(); |
| 433 | assert_eq!( |
| 434 | shrinks.len(), |
| 435 | turn_one.receipts.len(), |
| 436 | "one shrink per receipt: {:?}", |
| 437 | turn_one.receipts |
| 438 | ); |
| 439 | for ((message, post_input_tokens), next) in turn_one.receipts.iter().zip(&shrinks) { |
| 440 | let (before, after) = receipt_token_pair(message); |
| 441 | assert_eq!(Some(after as u64), *post_input_tokens, "{message}"); |
| 442 | assert_eq!(after, readings[*next], "receipt vs next request: {message}"); |
| 443 | assert!(before >= THRESHOLD, "receipt before crossed the gate: {message}"); |
| 444 | } |
| 445 | }); |
| 446 | } |
| 447 |