返回 CodeWhale
debug_diagnostics_host_tests.rs
根目录 / crates / tui / src / commands / debug_diagnostics_host_tests.rs
1 //! Host-bound diagnostics regressions relocated outside the future movable
2 //! `groups/debug` source closure. Selected by CW-SLICE's
3 //! `commands::debug_diagnostics` filter; mutation-only tests stay in the group.
4
5 use super::debug_mutation_host_tests::{create_test_app, test_tool};
6 use crate::tui::app::{App, AppAction, TurnCacheRecord};
7 use crate::tui::history::HistoryCell;
8 use codewhale_commands::debug::cache_format::format_tokens;
9 use codewhale_engine::client::CacheWarmupKey;
10 use codewhale_models::Role;
11 use codewhale_models::{ContentBlock, Message, SystemBlock, SystemPrompt};
12 use std::time::Instant;
13
14 // Exercise the real registry/dispatcher, not the legacy debug group's
15 // mutation-only dispatch. The caller-supplied argument is unchanged after
16 // the one separator inserted by the public slash-command parser.
17 fn dispatch(
18 app: &mut App,
19 name: &str,
20 arg: Option<&str>,
21 ) -> Option<crate::commands::CommandResult> {
22 let input = match arg {
23 Some(arg) => format!("/{name} {arg}"),
24 None => format!("/{name}"),
25 };
26 Some(super::execute(&input, app))
27 }
28
29 fn system_prompt(app: &mut App) -> crate::commands::CommandResult {
30 dispatch(app, "system", None).expect("registered system command")
31 }
32
33 fn context(app: &mut App, arg: Option<&str>) -> crate::commands::CommandResult {
34 dispatch(app, "context", arg).expect("registered context command")
35 }
36
37 fn cost(app: &mut App) -> crate::commands::CommandResult {
38 dispatch(app, "cost", None).expect("registered cost command")
39 }
40
41 fn tokens(app: &mut App) -> crate::commands::CommandResult {
42 dispatch(app, "tokens", None).expect("registered tokens command")
43 }
44
45 fn cache(app: &mut App, arg: Option<&str>) -> crate::commands::CommandResult {
46 dispatch(app, "cache", arg).expect("registered cache command")
47 }
48
49 fn format_warmup_status(last: Option<&CacheWarmupKey>, current: &CacheWarmupKey) -> String {
50 let previous = last.cloned().map(super::contract::project_debug_warmup_key);
51 let projected = super::contract::project_debug_warmup_key(current.clone());
52 codewhale_commands::debug::cache_format::format_warmup_status(
53 previous.as_ref(),
54 &projected,
55 last.map(CacheWarmupKey::hash_short).as_deref(),
56 &current.hash_short(),
57 )
58 }
59
60 #[test]
61 fn test_tokens_shows_usage_info() {
62 let mut app = create_test_app();
63 app.session.total_tokens = 1234;
64 app.session.session_cost = 0.05;
65 app.session.last_prompt_tokens = Some(100);
66 app.session.last_completion_tokens = Some(25);
67 app.session.last_prompt_cache_hit_tokens = Some(70);
68 app.session.last_prompt_cache_miss_tokens = Some(30);
69 app.api_messages_mut().push(Message {
70 role: Role::User,
71 content: vec![ContentBlock::Text {
72 text: "test".to_string(),
73 cache_control: None,
74 }],
75 });
76 app.history.push(HistoryCell::User {
77 content: "test".to_string(),
78 });
79
80 let result = tokens(&mut app);
81 assert!(result.message.is_some());
82 let msg = result.message.unwrap();
83 assert!(msg.contains("Token Usage"));
84 assert!(msg.contains("Active context:"));
85 assert!(msg.contains("Last API input:"));
86 assert!(msg.contains("Last API output:"));
87 assert!(msg.contains("Cache hit/miss:"));
88 assert!(msg.contains("70 hit / 30 miss"));
89 assert!(msg.contains("Cumulative tokens:"));
90 // Not "approx session cost": the figure is the priced subtotal, and a
91 // session with no priced turn reports `unknown` rather than the raw
92 // accumulator (#4318).
93 assert!(msg.contains("Priced amount:"));
94 assert!(msg.contains("Priced amount: unknown"), "{msg}");
95 assert!(msg.contains("API messages:"));
96 assert!(msg.contains("Chat messages:"));
97 assert!(msg.contains("Model:"));
98 }
99
100 #[test]
101 fn tokens_report_uses_codex_oauth_route_context() {
102 let mut app = create_test_app();
103 app.api_provider = codewhale_config::ProviderKind::OpenaiCodex;
104 app.set_model_selection("gpt-5.5".to_string());
105 app.active_route_limits = Some(codewhale_config::route::RouteLimits {
106 context_tokens: Some(272_000),
107 input_tokens: None,
108 output_tokens: None,
109 output_declared: false,
110 });
111
112 let message = tokens(&mut app).message.expect("tokens report");
113
114 assert!(message.contains("/ 272000"), "{message}");
115 assert!(!message.contains("1050000"), "{message}");
116 }
117
118 #[test]
119 fn test_cost_shows_spending_info() {
120 let mut app = create_test_app();
121 // A total is only reportable with the coverage that qualifies it. Setting
122 // the accumulator alone is the legacy shape, checked separately below.
123 app.session.cost_priced_turns = 1;
124 app.session.session_cost = 0.1234;
125 let result = cost(&mut app);
126 assert!(result.message.is_some());
127 let msg = result.message.unwrap();
128 assert!(msg.contains("Session Cost"), "{msg}");
129 assert!(msg.contains("Estimated total:"), "{msg}");
130 assert!(msg.contains("$0.1234"), "{msg}");
131 // The old copy hedged with "approximate" and then printed a static
132 // "Provider API Pricing" rate card that was not what the number was
133 // computed from. Both are gone: the report now names its own basis and
134 // its coverage instead of gesturing at a price list (#4318).
135 assert!(msg.contains("estimate, not a bill"), "{msg}");
136 assert!(msg.contains("Covered: 1 of 1"), "{msg}");
137 assert!(!msg.contains("Provider API Pricing"), "{msg}");
138 assert!(!msg.contains("DeepSeek API Pricing"), "{msg}");
139
140 let mut subscription = create_test_app();
141 subscription.session.cost_route_receipts.insert(
142 "provider=example identity=- model=example surface=api endpoint_fp=- billing_mode=subscription currency=USD".to_string(),
143 );
144 let summary = cost(&mut subscription)
145 .message
146 .expect("subscription summary");
147 assert!(summary.contains("subscription billing"), "{summary}");
148 assert!(
149 summary.contains("does not know the amount charged"),
150 "{summary}"
151 );
152 let details = dispatch(&mut subscription, "cost", Some("details"))
153 .expect("cost details")
154 .message
155 .expect("details message");
156 assert!(details.contains("billing_mode=subscription"), "{details}");
157 subscription.session.session_cost = 0.5;
158 let unknown = cost(&mut subscription)
159 .message
160 .expect("unknown cost report");
161 assert!(
162 !unknown.contains("These routes use subscription billing"),
163 "{unknown}"
164 );
165 subscription.session.session_cost = 0.0;
166 subscription.session.cost_route_receipts.insert(
167 "provider=example identity=- model=example surface=api endpoint_fp=- billing_mode=metered currency=USD".to_string(),
168 );
169 let mixed = cost(&mut subscription).message.expect("mixed cost report");
170 assert!(
171 !mixed.contains("These routes use subscription billing"),
172 "{mixed}"
173 );
174 }
175
176 /// The same accumulator with no coverage behind it is not a total. It is the
177 /// exact state a pre-coverage session restores into, and reporting it as
178 /// "Estimated total: $0.1234" would claim the figure is complete.
179 #[test]
180 fn cost_report_will_not_promote_an_unqualified_accumulator_to_a_total() {
181 let mut app = create_test_app();
182 app.session.session_cost = 0.1234;
183
184 let msg = cost(&mut app).message.expect("cost report");
185 assert!(msg.contains("Estimated total: unknown"), "{msg}");
186 assert!(!msg.contains("$0.1234"), "{msg}");
187 }
188
189 #[test]
190 fn cost_report_states_its_coverage_and_names_what_it_excludes() {
191 use codewhale_engine::pricing::audit_turn_cost_for_provider_at;
192
193 let mut app = create_test_app();
194 let write_heavy = codewhale_models::Usage {
195 input_tokens: 1_000_000,
196 output_tokens: 100_000,
197 prompt_cache_hit_tokens: Some(200_000),
198 prompt_cache_write_tokens: Some(100_000),
199 ..Default::default()
200 };
201 let now = chrono::Utc::now();
202
203 // One priced turn, one turn whose route publishes no cache-write rate, and
204 // one subscription turn that is not money-metered at all.
205 let priced = audit_turn_cost_for_provider_at(
206 codewhale_config::ProviderKind::Anthropic,
207 "claude-haiku-4-5",
208 &write_heavy,
209 now,
210 );
211 assert!(priced.is_priced(), "fixture must be priced");
212 app.record_turn_cost_audit(&priced);
213 app.accrue_session_cost_estimate(priced.estimate.expect("priced"));
214
215 let unpriced = audit_turn_cost_for_provider_at(
216 codewhale_config::ProviderKind::Moonshot,
217 "kimi-k2.7-code",
218 &write_heavy,
219 now,
220 );
221 assert!(!unpriced.is_priced(), "fixture must fail closed");
222 app.record_turn_cost_audit(&unpriced);
223
224 let billing = codewhale_engine::route_billing::for_dispatched_receipt(
225 codewhale_engine::route_billing::DispatchedReceipt {
226 provider: codewhale_config::ProviderKind::OpenaiCodex,
227 identity: Some("openai_codex"),
228 base_url: "https://api.openai.com/v1",
229 product: codewhale_engine::route_billing::RouteProduct::Subscription(
230 "ChatGPT plan allowance",
231 ),
232 },
233 );
234 let oauth = codewhale_engine::pricing::audit_turn_cost_for_route(
235 codewhale_config::ProviderKind::OpenaiCodex,
236 "gpt-5.5",
237 None,
238 &write_heavy,
239 now,
240 billing,
241 );
242 app.record_turn_cost_audit(&oauth);
243 assert!(
244 !app.session
245 .cost_unpriced_reasons
246 .contains("not_money_metered")
247 );
248
249 let msg = cost(&mut app).message.expect("cost report");
250
251 // Non-metered routes are not counted as "incomplete dollars".
252 assert!(msg.contains("Covered: 1 of 2"), "{msg}");
253 assert!(msg.contains("estimate, not a bill"), "{msg}");
254 assert!(msg.contains("Excluded: 1"), "{msg}");
255 assert!(msg.contains("Priced subtotal:"), "{msg}");
256 assert!(msg.contains("token class rate unavailable"), "{msg}");
257 assert!(msg.contains("cache_write"), "{msg}");
258
259 // A run with no unpriced turns says so without an exclusion note.
260 let mut clean = create_test_app();
261 clean.record_turn_cost_audit(&priced);
262 let clean_msg = cost(&mut clean).message.expect("cost report");
263 assert!(clean_msg.contains("Covered: 1 of 1"), "{clean_msg}");
264 assert!(clean_msg.contains("Estimated total:"), "{clean_msg}");
265 assert!(!clean_msg.contains("Excluded:"), "{clean_msg}");
266 assert!(clean_msg.contains("estimate, not a bill"), "{clean_msg}");
267 // Provenance of the row the total was built from is part of explaining it.
268 assert!(clean_msg.contains("Pricing sources used:"), "{clean_msg}");
269 }
270
271 #[test]
272 fn cost_coverage_is_currency_specific_for_mixed_deepseek_openai() {
273 let mut app = create_test_app();
274 let usage = codewhale_models::Usage {
275 input_tokens: 10_000,
276 output_tokens: 1_000,
277 ..Default::default()
278 };
279 let deepseek = codewhale_engine::pricing::audit_turn_cost_for_provider_at(
280 codewhale_config::ProviderKind::Deepseek,
281 "deepseek-v4-flash",
282 &usage,
283 chrono::Utc::now(),
284 );
285 let openai = codewhale_engine::pricing::audit_turn_cost_for_provider_at(
286 codewhale_config::ProviderKind::Openai,
287 "gpt-5.5",
288 &usage,
289 chrono::Utc::now(),
290 );
291 app.record_turn_cost_audit(&deepseek);
292 app.record_turn_cost_audit(&openai);
293 app.accrue_session_cost_estimate(deepseek.estimate.expect("DeepSeek priced"));
294 app.accrue_session_cost_estimate(openai.estimate.expect("OpenAI priced"));
295
296 app.cost_currency = codewhale_config::pricing::CostCurrency::Usd;
297 let usd = cost(&mut app).message.expect("USD report");
298 assert!(usd.contains("Covered: 2 of 2"), "{usd}");
299 assert!(usd.contains("Estimated total:"), "{usd}");
300
301 app.cost_currency = codewhale_config::pricing::CostCurrency::Cny;
302 let cny = cost(&mut app).message.expect("CNY report");
303 assert!(cny.contains("Covered: 1 of 2"), "{cny}");
304 assert!(cny.contains("Priced subtotal:"), "{cny}");
305 }
306
307 /// A session restored from a pre-coverage save has real money and no evidence of
308 /// what it covers. `/cost` must say the coverage is unknown rather than render a
309 /// fabricated "0 of 0 priced", which would assert the total is complete (#4318).
310 #[test]
311 fn cost_report_shows_unknown_coverage_for_a_legacy_session_instead_of_zero_of_zero() {
312 let mut app = create_test_app();
313 app.session.session_cost = 1.25;
314 app.session.cost_coverage_unknown_legacy = true;
315
316 let msg = cost(&mut app).message.expect("cost report");
317 assert!(msg.contains("Coverage: unknown"), "{msg}");
318 assert!(
319 !msg.contains("Covered: 0 of 0"),
320 "a legacy session must never claim a complete zero-turn total: {msg}"
321 );
322 assert!(msg.contains("estimate, not a bill"), "{msg}");
323 }
324
325 #[test]
326 fn cost_report_distinguishes_unknown_from_authoritatively_priced_zero() {
327 let mut unknown = create_test_app();
328 let unknown_msg = cost(&mut unknown).message.expect("unknown report");
329 assert!(
330 unknown_msg.contains("Estimated total: unknown"),
331 "{unknown_msg}"
332 );
333 assert!(!unknown_msg.contains("$0.0000"), "{unknown_msg}");
334
335 let mut priced_zero = create_test_app();
336 priced_zero.session.cost_priced_turns = 1;
337 let zero_msg = cost(&mut priced_zero).message.expect("priced zero report");
338 assert!(zero_msg.contains("$0.0000"), "{zero_msg}");
339 assert!(!zero_msg.contains("<$0.0001"), "{zero_msg}");
340 }
341
342 #[test]
343 fn cost_report_distinguishes_bundled_fallback_from_no_usable_fallback() {
344 let mut app = create_test_app();
345 app.session.cost_priced_turns = 1;
346 app.session
347 .cost_live_pricing_defects
348 .insert("live_pricing_stale".to_string());
349 app.session
350 .cost_live_pricing_unusable_defects
351 .insert("live_pricing_scope_mismatch".to_string());
352
353 let msg = cost(&mut app).message.expect("cost report");
354 assert!(msg.contains("bundled published rates were used"), "{msg}");
355 assert!(
356 msg.contains("no usable bundled rate was available"),
357 "{msg}"
358 );
359 assert!(msg.contains("this spend is unknown"), "{msg}");
360 }
361
362 #[test]
363 fn all_zero_legacy_coverage_stays_unknown_when_rendered_and_resaved() {
364 let mut app = create_test_app();
365 let legacy: codewhale_engine::session_manager::SessionCostSnapshot =
366 serde_json::from_value(serde_json::json!({
367 "session_cost_usd": 0.0,
368 "session_cost_cny": 0.0
369 }))
370 .expect("legacy zero snapshot");
371 assert!(legacy.coverage_is_legacy_unknown());
372 app.session.cost_coverage_unknown_legacy = true;
373
374 let msg = cost(&mut app).message.expect("cost report");
375 assert!(msg.contains("Coverage: unknown"), "{msg}");
376 assert!(!msg.contains("Covered: 0 of 0"), "{msg}");
377
378 let mut metadata = codewhale_engine::session_manager::create_saved_session_with_id_and_mode(
379 "legacy-zero".to_string(),
380 &[],
381 "deepseek-v4-flash",
382 std::path::Path::new("/tmp"),
383 0,
384 None,
385 None,
386 )
387 .metadata;
388 app.sync_cost_to_metadata(&mut metadata);
389 assert!(!metadata.cost.coverage_recorded);
390 assert!(metadata.cost.coverage_is_legacy_unknown());
391 }
392
393 /// Loading a session must not leave the previous session's coverage counters
394 /// attached to a total that no longer contains those turns.
395 #[test]
396 fn reset_cost_coverage_clears_every_counter() {
397 use codewhale_engine::pricing::audit_turn_cost_for_provider_at;
398
399 let mut app = create_test_app();
400 let usage = codewhale_models::Usage {
401 input_tokens: 1_000_000,
402 output_tokens: 100_000,
403 prompt_cache_write_tokens: Some(100_000),
404 ..Default::default()
405 };
406 let now = chrono::Utc::now();
407 app.record_turn_cost_audit(&audit_turn_cost_for_provider_at(
408 codewhale_config::ProviderKind::Anthropic,
409 "claude-haiku-4-5",
410 &usage,
411 now,
412 ));
413 app.record_turn_cost_audit(&audit_turn_cost_for_provider_at(
414 codewhale_config::ProviderKind::Moonshot,
415 "kimi-k2.7-code",
416 &usage,
417 now,
418 ));
419 app.record_turn_cost_route_receipt("provider=anthropic model=x".to_string());
420 app.session.cost_coverage_unknown_legacy = true;
421 assert_ne!(app.session.cost_priced_turns, 0);
422 assert_ne!(app.session.cost_unpriced_turns, 0);
423 assert!(!app.session.cost_unpriced_reasons.is_empty());
424 assert!(!app.session.cost_unpriced_classes.is_empty());
425 assert!(!app.session.cost_pricing_provenances.is_empty());
426 assert!(!app.session.cost_route_receipts.is_empty());
427
428 app.reset_cost_coverage();
429
430 assert_eq!(app.session.cost_priced_turns, 0);
431 assert_eq!(app.session.cost_unpriced_turns, 0);
432 assert!(app.session.cost_unpriced_reasons.is_empty());
433 assert!(app.session.cost_cny_unpriced_reasons.is_empty());
434 assert!(app.session.cost_unpriced_classes.is_empty());
435 assert!(app.session.cost_pricing_provenances.is_empty());
436 assert!(app.session.cost_live_pricing_defects.is_empty());
437 assert!(app.session.cost_live_pricing_unusable_defects.is_empty());
438 assert!(app.session.cost_route_receipts.is_empty());
439 assert!(!app.session.cost_coverage_unknown_legacy);
440 // With nothing recorded, `/cost` reports an honest empty coverage rather
441 // than the legacy-unknown state.
442 let msg = cost(&mut app).message.expect("cost report");
443 assert!(msg.contains("Covered: 0 of 0"), "{msg}");
444 assert!(!msg.contains("Coverage: unknown"), "{msg}");
445 }
446
447 /// `/tokens` quotes the same total as `/cost`, so it carries the same estimate
448 /// disclaimer and the same coverage state, and reports cache-write with a
449 /// pointer to `/cache` for the per-turn detail.
450 #[test]
451 fn tokens_report_says_estimate_and_exposes_coverage_and_cache_write() {
452 let mut app = create_test_app();
453 app.session.total_cache_write_tokens = 250_000;
454 app.record_turn_cost_audit(&codewhale_engine::pricing::audit_turn_cost_for_provider_at(
455 codewhale_config::ProviderKind::Moonshot,
456 "kimi-k2.7-code",
457 &codewhale_models::Usage {
458 input_tokens: 1_000_000,
459 output_tokens: 100_000,
460 prompt_cache_write_tokens: Some(100_000),
461 ..Default::default()
462 },
463 chrono::Utc::now(),
464 ));
465
466 let msg = tokens(&mut app).message.expect("tokens report");
467 assert!(msg.contains("estimate, not a bill"), "{msg}");
468 assert!(msg.contains("Covered: 0 of 1"), "{msg}");
469 assert!(msg.contains("Excluded: 1"), "{msg}");
470 assert!(msg.contains("250000"), "{msg}");
471 // The cache-write line links to /cache rather than duplicating the table.
472 assert!(msg.contains("/cache"), "{msg}");
473 }
474
475 #[test]
476 fn test_system_prompt_displays_text() {
477 let mut app = create_test_app();
478 app.system_prompt = Some(SystemPrompt::Text("Test system prompt".to_string()));
479 let result = system_prompt(&mut app);
480 assert!(result.message.is_some());
481 let msg = result.message.unwrap();
482 assert!(msg.contains("System Prompt"));
483 assert!(msg.contains("Test system prompt"));
484 }
485
486 #[test]
487 fn test_system_prompt_displays_blocks() {
488 let mut app = create_test_app();
489 app.system_prompt = Some(SystemPrompt::Blocks(vec![
490 SystemBlock {
491 block_type: "text".to_string(),
492 text: "Block 1".to_string(),
493 cache_control: None,
494 },
495 SystemBlock {
496 block_type: "text".to_string(),
497 text: "Block 2".to_string(),
498 cache_control: None,
499 },
500 ]));
501 let result = system_prompt(&mut app);
502 assert!(result.message.is_some());
503 let msg = result.message.unwrap();
504 assert!(msg.contains("System Prompt"));
505 assert!(msg.contains("Block 1"));
506 assert!(msg.contains("Block 2"));
507 }
508
509 #[test]
510 fn test_system_prompt_none() {
511 let mut app = create_test_app();
512 app.system_prompt = None;
513 let result = system_prompt(&mut app);
514 assert!(result.message.is_some());
515 let msg = result.message.unwrap();
516 assert!(msg.contains("(no system prompt)"));
517 }
518
519 #[test]
520 fn test_system_prompt_truncates_long_text() {
521 let mut app = create_test_app();
522 let long_text = "x".repeat(600);
523 app.system_prompt = Some(SystemPrompt::Text(long_text));
524 let result = system_prompt(&mut app);
525 assert!(result.message.is_some());
526 let msg = result.message.unwrap();
527 assert!(msg.contains("..."));
528 assert!(msg.contains("chars total"));
529 }
530
531 #[test]
532 fn cache_command_reports_no_data_before_first_turn() {
533 let mut app = create_test_app();
534 let result = cache(&mut app, None);
535 let msg = result.message.expect("cache produces a message");
536 assert!(msg.contains("no turns recorded yet"), "got: {msg}");
537 }
538
539 #[test]
540 fn cache_inspect_reports_hashes_without_prompt_text() {
541 let mut app = create_test_app();
542 app.system_prompt = Some(SystemPrompt::Text(
543 "Base policy\n\n<project_instructions source=\"AGENTS.md\">\nSECRET_PROJECT_RULE\n</project_instructions>"
544 .to_string(),
545 ));
546 app.api_messages_mut().push(Message {
547 role: Role::User,
548 content: vec![ContentBlock::Text {
549 text: "SECRET_USER_TASK".to_string(),
550 cache_control: None,
551 }],
552 });
553
554 let result = cache(&mut app, Some("inspect"));
555 let msg = result.message.expect("inspect output");
556
557 assert!(msg.contains("Cache Inspect"));
558 assert!(msg.contains("Base static prefix hash:"));
559 assert!(msg.contains("Full request prefix hash:"));
560 assert!(msg.contains("Static base prefix stability: no previous request"));
561 assert!(msg.contains("First divergence from previous request: unavailable"));
562 assert!(msg.contains("Global system prefix: static"));
563 assert!(msg.contains("Project context: static"));
564 assert!(msg.contains("User task: dynamic"));
565 assert!(!msg.contains("SECRET_PROJECT_RULE"));
566 assert!(!msg.contains("SECRET_USER_TASK"));
567 }
568
569 #[test]
570 fn cache_inspect_uses_last_request_tool_catalog() {
571 let mut app = create_test_app();
572 app.system_prompt = Some(SystemPrompt::Text("Base policy".to_string()));
573 app.session.last_tool_catalog = Some(vec![test_tool("read_file")]);
574 app.api_messages_mut().push(Message {
575 role: Role::User,
576 content: vec![ContentBlock::Text {
577 text: "Current task".to_string(),
578 cache_control: None,
579 }],
580 });
581
582 let msg = cache(&mut app, Some("inspect"))
583 .message
584 .expect("inspect output");
585
586 assert!(msg.contains("Tool catalog hash: "), "got: {msg}");
587 assert!(!msg.contains("(no tools registered)"), "got: {msg}");
588 assert!(msg.contains("Tool catalog: static"), "got: {msg}");
589 assert!(msg.contains("bytes="), "got: {msg}");
590 assert!(msg.contains("~"), "got: {msg}");
591 }
592
593 #[test]
594 fn cache_inspect_json_reports_tool_catalog_hash_and_layer_sizes() {
595 let mut app = create_test_app();
596 app.system_prompt = Some(SystemPrompt::Text("Base policy".to_string()));
597 app.session.last_tool_catalog = Some(vec![test_tool("read_file")]);
598 app.api_messages_mut().push(Message {
599 role: Role::User,
600 content: vec![ContentBlock::Text {
601 text: "Current task".to_string(),
602 cache_control: None,
603 }],
604 });
605
606 let msg = cache(&mut app, Some("inspect --json"))
607 .message
608 .expect("inspect json output");
609 let parsed: serde_json::Value = serde_json::from_str(&msg).expect("valid json");
610
611 assert_eq!(parsed["tool_catalog_hash"].as_str().unwrap().len(), 64);
612 assert!(
613 parsed["warmup_status"]
614 .as_str()
615 .is_some_and(|status| status.starts_with("Warmup status: no previous warmup"))
616 );
617 assert!(parsed["current_warmup_key"].is_object());
618 let tool_layer = parsed["layers"]
619 .as_array()
620 .unwrap()
621 .iter()
622 .find(|layer| layer["name"] == "Tool catalog")
623 .expect("tool catalog layer");
624 assert!(tool_layer["byte_len"].as_u64().unwrap() > 0);
625 assert!(tool_layer["token_estimate"].as_u64().unwrap() > 0);
626 }
627
628 #[test]
629 fn cache_inspect_json_keys_auto_replay_to_the_last_concrete_route() {
630 let mut app = create_test_app();
631 app.model = "auto".to_string();
632 app.auto_model = true;
633 app.reasoning_effort = codewhale_engine::reasoning_preference::ReasoningEffort::Off;
634 app.last_effective_provider = Some(codewhale_config::ProviderKind::OpenaiCodex);
635 app.last_effective_provider_identity = Some(
636 codewhale_config::ProviderKind::OpenaiCodex
637 .as_str()
638 .to_string(),
639 );
640 app.last_effective_model =
641 Some(codewhale_config::descriptors::defaults::DEFAULT_OPENAI_CODEX_MODEL.to_string());
642 app.session.last_base_url =
643 Some(codewhale_config::descriptors::defaults::DEFAULT_OPENAI_CODEX_BASE_URL.to_string());
644 app.push_turn_cache_record(TurnCacheRecord {
645 provider: Some(codewhale_config::ProviderKind::OpenaiCodex),
646 provider_identity: Some(
647 codewhale_config::ProviderKind::OpenaiCodex
648 .as_str()
649 .to_string(),
650 ),
651 model: Some(
652 codewhale_config::descriptors::defaults::DEFAULT_OPENAI_CODEX_MODEL.to_string(),
653 ),
654 auto_model: true,
655 input_tokens: 1,
656 output_tokens: 1,
657 cache_hit_tokens: None,
658 cache_miss_tokens: None,
659 cache_write_tokens: None,
660 reasoning_tokens: None,
661 cost_audit: None,
662 reasoning_replay_tokens: None,
663 recorded_at: Instant::now(),
664 });
665
666 let message = cache(&mut app, Some("inspect --json"))
667 .message
668 .expect("inspect json output");
669 let parsed: serde_json::Value = serde_json::from_str(&message).expect("valid json");
670 let key = &parsed["current_warmup_key"];
671
672 assert_eq!(
673 key["provider"],
674 codewhale_config::ProviderKind::OpenaiCodex.as_str()
675 );
676 assert_eq!(
677 key["model"],
678 codewhale_config::descriptors::defaults::DEFAULT_OPENAI_CODEX_MODEL
679 );
680 assert_eq!(
681 key["base_url"],
682 codewhale_config::descriptors::defaults::DEFAULT_OPENAI_CODEX_BASE_URL
683 );
684 }
685
686 fn warmup_key(model: &str, static_hash: &str) -> CacheWarmupKey {
687 CacheWarmupKey {
688 provider: "Deepseek".to_string(),
689 model: model.to_string(),
690 base_url: "https://api.deepseek.com".to_string(),
691 static_prefix_hash: static_hash.to_string(),
692 tool_catalog_hash: "tool".to_string(),
693 project_pack_hash: "project".to_string(),
694 skills_hash: "skills".to_string(),
695 }
696 }
697
698 #[test]
699 fn warmup_status_reports_valid_matching_key() {
700 let key = warmup_key("deepseek-v4-pro", "static-a");
701 let result = format_warmup_status(Some(&key), &key);
702 assert!(result.contains("Warmup status: valid"), "got: {result}");
703 }
704
705 #[test]
706 fn warmup_status_reports_invalidation_reason() {
707 let previous = warmup_key("deepseek-v4-pro", "static-a");
708 let current = warmup_key("deepseek-v4-flash", "static-b");
709 let result = format_warmup_status(Some(&previous), &current);
710 assert!(result.contains("Warmup status: invalid"), "got: {result}");
711 assert!(result.contains("model changed"), "got: {result}");
712 assert!(result.contains("static prefix changed"), "got: {result}");
713 }
714
715 #[test]
716 fn warmup_status_reports_project_and_skills_reasons() {
717 let previous = warmup_key("deepseek-v4-pro", "static-a");
718 let mut current = previous.clone();
719 current.project_pack_hash = "project-b".to_string();
720 current.skills_hash = "skills-b".to_string();
721
722 let result = format_warmup_status(Some(&previous), &current);
723
724 assert!(result.contains("project pack changed"), "got: {result}");
725 assert!(result.contains("skills changed"), "got: {result}");
726 assert!(!result.contains("; )"), "got: {result}");
727 }
728
729 #[test]
730 fn cache_inspect_rejects_json_verbose_combo() {
731 let mut app = create_test_app();
732 let msg = cache(&mut app, Some("inspect --json --verbose"))
733 .message
734 .expect("inspect output");
735
736 assert_eq!(
737 msg,
738 "cache inspect: --json and --verbose cannot be combined"
739 );
740 }
741
742 #[test]
743 fn cache_inspect_json_uses_cjk_aware_token_estimate() {
744 let mut app = create_test_app();
745 app.system_prompt = Some(SystemPrompt::Text("缓存命中测试".to_string()));
746
747 let msg = cache(&mut app, Some("inspect --json"))
748 .message
749 .expect("inspect json output");
750 let parsed: serde_json::Value = serde_json::from_str(&msg).expect("valid json");
751 let system_layer = parsed["layers"]
752 .as_array()
753 .unwrap()
754 .iter()
755 .find(|layer| layer["name"] == "Global system prefix")
756 .expect("system layer");
757
758 assert_eq!(
759 system_layer["token_estimate"].as_u64(),
760 system_layer["char_len"].as_u64()
761 );
762 }
763
764 #[test]
765 fn cache_inspect_reports_divergence_from_previous_request() {
766 let mut app = create_test_app();
767 app.system_prompt = Some(SystemPrompt::Text(
768 "Base policy\n\n## Environment\n\n- shell: powershell".to_string(),
769 ));
770 app.api_messages_mut().push(Message {
771 role: Role::Assistant,
772 content: vec![codewhale_models::ContentBlock::Text {
773 text: "Prior answer".to_string(),
774 cache_control: None,
775 }],
776 });
777 app.api_messages_mut().push(Message {
778 role: Role::User,
779 content: vec![codewhale_models::ContentBlock::Text {
780 text: "First task".to_string(),
781 cache_control: None,
782 }],
783 });
784
785 let first = cache(&mut app, Some("inspect"))
786 .message
787 .expect("first inspect output");
788 assert!(first.contains("Static base prefix stability: no previous request"));
789
790 if let Some(last) = app.api_messages_mut().last_mut()
791 && let Some(codewhale_models::ContentBlock::Text { text, .. }) = last.content.first_mut()
792 {
793 *text = "Second task".to_string();
794 }
795
796 let second = cache(&mut app, Some("inspect"))
797 .message
798 .expect("second inspect output");
799 assert!(second.contains("Static base prefix stability: OK"));
800 assert!(second.contains("First divergence from previous request: User task"));
801 assert!(second.contains("Message #1 assistant: history"));
802 }
803
804 fn push_repeated_shell_results(app: &mut App, output: &str) {
805 for id in ["tool-1", "tool-2"] {
806 app.api_messages_mut().push(Message {
807 role: Role::Assistant,
808 content: vec![ContentBlock::ToolUse {
809 execution_id: None,
810 id: id.to_string(),
811 name: "shell_command".to_string(),
812 input: serde_json::json!({"command": "cargo test"}),
813 caller: None,
814 thought_signature: None,
815 }],
816 });
817 app.api_messages_mut().push(Message {
818 role: Role::User,
819 content: vec![ContentBlock::ToolResult {
820 execution_id: None,
821 tool_use_id: id.to_string(),
822 content: output.to_string(),
823 is_error: None,
824 content_blocks: None,
825 }],
826 });
827 }
828 }
829
830 #[test]
831 fn cache_inspect_displays_tool_result_budget_metadata() {
832 // Past the 100,000-char wire backstop (#6508), so each sighting is
833 // excerpted rather than sent whole or deduplicated.
834 let mut app = create_test_app();
835 let long_output = format!("{}{}", "A".repeat(60_000), "Z".repeat(60_000));
836 push_repeated_shell_results(&mut app, &long_output);
837
838 let result = cache(&mut app, Some("inspect"));
839 let msg = result.message.expect("inspect output");
840
841 let tool_budget_lines: Vec<_> = msg
842 .lines()
843 .filter(|line| line.contains("original_chars=120000"))
844 .collect();
845 assert_eq!(tool_budget_lines.len(), 2, "got: {msg}");
846
847 for sighting in tool_budget_lines {
848 assert!(sighting.contains("sent_chars="), "got: {msg}");
849 assert!(!sighting.contains("sent_chars=120000"), "got: {msg}");
850 assert!(sighting.contains("truncated=true"), "got: {msg}");
851 assert!(sighting.contains("deduplicated=false"), "got: {msg}");
852 }
853 }
854
855 #[test]
856 fn cache_inspect_shows_repeated_in_budget_tool_result_sent_whole_then_deduplicated() {
857 // Under the wire backstop (#6508), a repeated result is sent whole the
858 // first time and replaced by a reference to that copy the second time.
859 let mut app = create_test_app();
860 let output = format!("{}{}", "A".repeat(7_000), "Z".repeat(7_000));
861 push_repeated_shell_results(&mut app, &output);
862
863 let result = cache(&mut app, Some("inspect"));
864 let msg = result.message.expect("inspect output");
865
866 let lines: Vec<_> = msg
867 .lines()
868 .filter(|line| line.contains("original_chars=14000"))
869 .collect();
870 assert_eq!(lines.len(), 2, "got: {msg}");
871 assert!(lines[0].contains("sent_chars=14000"), "got: {msg}");
872 assert!(lines[0].contains("truncated=false"), "got: {msg}");
873 assert!(lines[0].contains("deduplicated=false"), "got: {msg}");
874 assert!(lines[1].contains("truncated=false"), "got: {msg}");
875 assert!(lines[1].contains("deduplicated=true"), "got: {msg}");
876 assert!(!lines[1].contains("sent_chars=14000"), "got: {msg}");
877 }
878
879 #[test]
880 fn cache_inspect_displays_turn_meta_dedup_metadata() {
881 let mut app = create_test_app();
882 let turn_meta = format!(
883 "<turn_meta>\nCurrent local date: 2026-05-09\n{}\n</turn_meta>",
884 "Working set: src/lib.rs\n".repeat(20)
885 );
886 app.api_messages_mut().push(Message {
887 role: Role::User,
888 content: vec![
889 ContentBlock::Text {
890 text: turn_meta.clone(),
891 cache_control: None,
892 },
893 ContentBlock::Text {
894 text: "first task".to_string(),
895 cache_control: None,
896 },
897 ],
898 });
899 app.api_messages_mut().push(Message {
900 role: Role::User,
901 content: vec![
902 ContentBlock::Text {
903 text: turn_meta,
904 cache_control: None,
905 },
906 ContentBlock::Text {
907 text: "second task".to_string(),
908 cache_control: None,
909 },
910 ],
911 });
912
913 let result = cache(&mut app, Some("inspect"));
914 let msg = result.message.expect("inspect output");
915
916 assert!(msg.contains("turn_meta_original_chars="), "got: {msg}");
917 assert!(msg.contains("turn_meta_sent_chars="), "got: {msg}");
918 assert!(msg.contains("turn_meta_deduplicated=false"), "got: {msg}");
919 assert!(msg.contains("turn_meta_deduplicated=true"), "got: {msg}");
920 assert!(msg.contains("turn_meta_sha256="), "got: {msg}");
921 assert!(!msg.contains("Working set: src/lib.rs"), "got: {msg}");
922 }
923
924 #[test]
925 fn cache_command_renders_recorded_turns_with_ratio() {
926 let mut app = create_test_app();
927 let now = Instant::now();
928 // Three turns: 75% hit, 50% hit, miss-only (provider didn't report hit).
929 app.push_turn_cache_record(TurnCacheRecord {
930 provider: Some(codewhale_config::ProviderKind::Deepseek),
931 provider_identity: Some("deepseek".to_string()),
932 model: Some("deepseek-v4-pro".to_string()),
933 auto_model: true,
934 input_tokens: 4_000,
935 output_tokens: 200,
936 cache_hit_tokens: Some(3_000),
937 cache_miss_tokens: Some(1_000),
938 reasoning_replay_tokens: None,
939 cache_write_tokens: None,
940 reasoning_tokens: None,
941 cost_audit: None,
942 recorded_at: now,
943 });
944 app.push_turn_cache_record(TurnCacheRecord {
945 provider: None,
946 provider_identity: None,
947 model: None,
948 auto_model: false,
949 input_tokens: 6_000,
950 output_tokens: 250,
951 cache_hit_tokens: Some(3_000),
952 cache_miss_tokens: Some(3_000),
953 reasoning_replay_tokens: Some(150),
954 cache_write_tokens: None,
955 reasoning_tokens: None,
956 cost_audit: None,
957 recorded_at: now,
958 });
959 // Turn 3: hit reported but provider didn't report miss separately —
960 // infer miss = input − hit and mark with `*`.
961 app.push_turn_cache_record(TurnCacheRecord {
962 provider: None,
963 provider_identity: None,
964 model: None,
965 auto_model: false,
966 input_tokens: 5_000,
967 output_tokens: 100,
968 cache_hit_tokens: Some(2_500),
969 cache_miss_tokens: None,
970 reasoning_replay_tokens: None,
971 cache_write_tokens: None,
972 reasoning_tokens: None,
973 cost_audit: None,
974 recorded_at: now,
975 });
976 // Turn 4: no telemetry at all — must not pollute aggregate ratios.
977 app.push_turn_cache_record(TurnCacheRecord {
978 provider: None,
979 provider_identity: None,
980 model: None,
981 auto_model: false,
982 input_tokens: 1_000,
983 output_tokens: 50,
984 cache_hit_tokens: None,
985 cache_miss_tokens: None,
986 reasoning_replay_tokens: None,
987 cache_write_tokens: None,
988 reasoning_tokens: None,
989 cost_audit: None,
990 recorded_at: now,
991 });
992
993 let result = cache(&mut app, None);
994 let msg = result.message.expect("cache produces a message");
995
996 // Header reflects total rows and model.
997 assert!(msg.contains("last 4 of 4 turn(s)"), "got: {msg}");
998 // Per-turn ratios are rendered.
999 assert!(msg.contains("75.0%"), "got: {msg}");
1000 assert!(msg.contains("50.0%"), "got: {msg}");
1001 assert!(msg.contains("auto:deepseek/deepsee..."), "got: {msg}");
1002 // Turn 3: hit=2500, inferred miss=2500 → 50.0% with `*`-marked miss.
1003 assert!(msg.contains("2500*"), "got: {msg}");
1004 // Turn 4 (no telemetry) shows em-dashes and is excluded from totals.
1005 // Aggregate over turns 1-3: hit=8500, miss=6500 → 56.7%.
1006 assert!(msg.contains("avg hit ratio: 56.7%"), "got: {msg}");
1007 // Footer guidance is present.
1008 assert!(msg.contains("70%"), "got: {msg}");
1009 }
1010
1011 #[test]
1012 fn cache_history_shows_cache_write_tokens_and_explains_unpriced_turns() {
1013 use codewhale_engine::pricing::audit_turn_cost_for_provider_at;
1014
1015 let mut app = create_test_app();
1016 let write_heavy = codewhale_models::Usage {
1017 input_tokens: 1_000_000,
1018 output_tokens: 100_000,
1019 prompt_cache_hit_tokens: Some(200_000),
1020 prompt_cache_write_tokens: Some(100_000),
1021 ..Default::default()
1022 };
1023 let now = chrono::Utc::now();
1024
1025 app.push_turn_cache_record(TurnCacheRecord {
1026 provider: Some(codewhale_config::ProviderKind::Anthropic),
1027 provider_identity: None,
1028 model: Some("claude-haiku-4-5".to_string()),
1029 auto_model: false,
1030 input_tokens: 1_000_000,
1031 output_tokens: 100_000,
1032 cache_hit_tokens: Some(200_000),
1033 cache_miss_tokens: Some(700_000),
1034 reasoning_replay_tokens: None,
1035 cache_write_tokens: Some(100_000),
1036 reasoning_tokens: Some(40_000),
1037 cost_audit: Some(audit_turn_cost_for_provider_at(
1038 codewhale_config::ProviderKind::Anthropic,
1039 "claude-haiku-4-5",
1040 &write_heavy,
1041 now,
1042 )),
1043 recorded_at: Instant::now(),
1044 });
1045 app.push_turn_cache_record(TurnCacheRecord {
1046 provider: Some(codewhale_config::ProviderKind::Moonshot),
1047 provider_identity: None,
1048 model: Some("kimi-k2.7-code".to_string()),
1049 auto_model: false,
1050 input_tokens: 1_000_000,
1051 output_tokens: 100_000,
1052 cache_hit_tokens: Some(200_000),
1053 cache_miss_tokens: Some(700_000),
1054 reasoning_replay_tokens: None,
1055 cache_write_tokens: Some(100_000),
1056 reasoning_tokens: Some(10_000),
1057 cost_audit: Some(audit_turn_cost_for_provider_at(
1058 codewhale_config::ProviderKind::Moonshot,
1059 "kimi-k2.7-code",
1060 &write_heavy,
1061 now,
1062 )),
1063 recorded_at: Instant::now(),
1064 });
1065
1066 let msg = cache(&mut app, None).message.expect("cache message");
1067
1068 assert!(msg.contains("write"), "{msg}");
1069 assert!(msg.contains("sum_write: 200000"), "{msg}");
1070 assert!(msg.contains("sum_reasoning: 50000"), "{msg}");
1071 // The priced turn shows money; the unpriced one shows why it does not.
1072 assert!(msg.contains("$1.3450"), "{msg}");
1073 assert!(msg.contains("token class rate unavailable"), "{msg}");
1074 assert!(msg.contains("cache_write"), "{msg}");
1075 }
1076
1077 #[test]
1078 fn cache_command_replays_reported_1177_low_hit_fixture() {
1079 let mut app = create_test_app();
1080 let now = Instant::now();
1081 // Fixture from #1177 / douglarek's 2026-05-10 `/cache` report.
1082 // It captures a real low-hit sequence with one 56.8% tail turn.
1083 for (input, output, hit, miss) in [
1084 (25_839, 12, 4_608, 21_231),
1085 (25_906, 288, 25_728, 178),
1086 (264_500, 2_528, 235_648, 28_852),
1087 (202_230, 3_191, 193_536, 8_694),
1088 (45_982, 294, 26_112, 19_870),
1089 ] {
1090 app.push_turn_cache_record(TurnCacheRecord {
1091 provider: None,
1092 provider_identity: None,
1093 model: None,
1094 auto_model: false,
1095 input_tokens: input,
1096 output_tokens: output,
1097 cache_hit_tokens: Some(hit),
1098 cache_miss_tokens: Some(miss),
1099 reasoning_replay_tokens: None,
1100 cache_write_tokens: None,
1101 reasoning_tokens: None,
1102 cost_audit: None,
1103 recorded_at: now,
1104 });
1105 }
1106
1107 let result = cache(&mut app, None);
1108 let msg = result.message.expect("cache produces a message");
1109
1110 assert!(msg.contains("last 5 of 5 turn(s)"), "got: {msg}");
1111 assert!(msg.contains("56.8%"), "got: {msg}");
1112 assert!(msg.contains("Σ in: 564457"), "got: {msg}");
1113 assert!(msg.contains("Σ hit: 485632"), "got: {msg}");
1114 assert!(msg.contains("Σ miss: 78825"), "got: {msg}");
1115 assert!(msg.contains("avg hit ratio: 86.0%"), "got: {msg}");
1116 }
1117
1118 #[test]
1119 fn cache_command_count_argument_clamps_to_history() {
1120 let mut app = create_test_app();
1121 for _ in 0..3 {
1122 app.push_turn_cache_record(TurnCacheRecord {
1123 provider: None,
1124 provider_identity: None,
1125 model: None,
1126 auto_model: false,
1127 input_tokens: 1_000,
1128 output_tokens: 100,
1129 cache_hit_tokens: Some(500),
1130 cache_miss_tokens: Some(500),
1131 reasoning_replay_tokens: None,
1132 cache_write_tokens: None,
1133 reasoning_tokens: None,
1134 cost_audit: None,
1135 recorded_at: Instant::now(),
1136 });
1137 }
1138 let result = cache(&mut app, Some("100"));
1139 let msg = result.message.expect("cache produces a message");
1140 // Asked for 100 turns, only 3 exist — should report "last 3 of 3".
1141 assert!(msg.contains("last 3 of 3 turn(s)"), "got: {msg}");
1142 }
1143
1144 #[test]
1145 fn turn_cache_history_is_capped_at_50() {
1146 let mut app = create_test_app();
1147 for i in 0..(crate::tui::app::App::TURN_CACHE_HISTORY_CAP + 12) {
1148 app.push_turn_cache_record(TurnCacheRecord {
1149 provider: None,
1150 provider_identity: None,
1151 model: None,
1152 auto_model: false,
1153 input_tokens: i as u32,
1154 output_tokens: 1,
1155 cache_hit_tokens: Some(i as u32),
1156 cache_miss_tokens: Some(0),
1157 reasoning_replay_tokens: None,
1158 cache_write_tokens: None,
1159 reasoning_tokens: None,
1160 cost_audit: None,
1161 recorded_at: Instant::now(),
1162 });
1163 }
1164 assert_eq!(
1165 app.session.turn_cache_history.len(),
1166 crate::tui::app::App::TURN_CACHE_HISTORY_CAP
1167 );
1168 // Oldest record was evicted; newest record is still at the back.
1169 assert_eq!(
1170 app.session.turn_cache_history.back().unwrap().input_tokens,
1171 (crate::tui::app::App::TURN_CACHE_HISTORY_CAP + 11) as u32
1172 );
1173 }
1174
1175 #[test]
1176 fn test_context_shows_usage_stats() {
1177 let mut app = create_test_app();
1178 app.api_messages_mut().push(Message {
1179 role: Role::User,
1180 content: vec![ContentBlock::Text {
1181 text: "Hello".to_string(),
1182 cache_control: None,
1183 }],
1184 });
1185 app.history.push(HistoryCell::User {
1186 content: "Hello".to_string(),
1187 });
1188
1189 let result = context(&mut app, None);
1190 assert!(matches!(
1191 result.action,
1192 Some(AppAction::OpenContextInspector)
1193 ));
1194 assert!(result.message.is_none());
1195 }
1196
1197 #[test]
1198 fn test_context_report_subcommands_return_source_map() {
1199 // The source map reads the user's global instructions and skills: seal the
1200 // home so the report does not change with whoever runs the suite.
1201 let _home = crate::test_support::SealedHome::new();
1202 let mut app = create_test_app();
1203 app.api_messages_mut().push(Message {
1204 role: Role::User,
1205 content: vec![ContentBlock::Text {
1206 text: "Hello".to_string(),
1207 cache_control: None,
1208 }],
1209 });
1210 app.session.last_tool_catalog = Some(vec![test_tool("read_file")]);
1211
1212 let report = context(&mut app, Some("report"))
1213 .message
1214 .expect("report text");
1215 assert!(report.contains("Context Source Map"));
1216 assert!(report.contains("Tool schemas"));
1217
1218 let summary = context(&mut app, Some("summary"))
1219 .message
1220 .expect("summary text");
1221 assert!(summary.contains("Context Summary"));
1222
1223 let json = context(&mut app, Some("json")).message.expect("json text");
1224 let parsed: serde_json::Value = serde_json::from_str(&json).expect("valid context json");
1225 assert!(!parsed["entries"].as_array().unwrap().is_empty());
1226
1227 let prompt_json = context(&mut app, Some("prompt-json"))
1228 .message
1229 .expect("prompt context json");
1230 let prompt: serde_json::Value =
1231 serde_json::from_str(&prompt_json).expect("valid prompt context json");
1232 assert_eq!(prompt["schema_version"], 1);
1233 assert_eq!(prompt["model"], app.model);
1234 assert_eq!(prompt["system_prompt_state"], "current_session");
1235 assert_eq!(prompt["tool_catalog_state"], "last_sent");
1236 assert_eq!(prompt["tools"][0]["name"], "read_file");
1237 assert!(prompt["sections"].is_array());
1238 assert!(
1239 !prompt["source_map"]["entries"]
1240 .as_array()
1241 .expect("source entries")
1242 .is_empty()
1243 );
1244 }
1245
1246 #[test]
1247 fn cache_stats_no_data_before_first_turn() {
1248 let mut app = create_test_app();
1249 let result = cache(&mut app, Some("stats"));
1250 let msg = result.message.expect("cache stats produces a message");
1251 assert!(msg.contains("Cache Stats"), "got: {msg}");
1252 assert!(
1253 msg.contains("unknown (no checks recorded yet)"),
1254 "got: {msg}"
1255 );
1256 assert!(msg.contains("Pinned hash: unavailable"), "got: {msg}");
1257 assert!(msg.contains("No turn telemetry recorded yet"), "got: {msg}");
1258 }
1259
1260 #[test]
1261 fn cache_stats_shows_stable_prefix_with_hash() {
1262 let mut app = create_test_app();
1263 app.prefix_stability_pct = Some(100);
1264 app.prefix_checks_total = 5;
1265 app.prefix_change_count = 0;
1266 app.last_pinned_prefix_hash =
1267 Some("a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2".to_string());
1268
1269 let result = cache(&mut app, Some("stats"));
1270 let msg = result.message.expect("cache stats produces a message");
1271
1272 assert!(msg.contains("Stability: 100%"), "got: {msg}");
1273 assert!(msg.contains("stable (no prefix changes"), "got: {msg}");
1274 assert!(msg.contains("Pinned hash: a1b2c3d4e5f6"), "got: {msg}");
1275 assert!(
1276 msg.contains("Drift: none (hash stable)"),
1277 "got: {msg}"
1278 );
1279 }
1280
1281 #[test]
1282 fn cache_stats_warns_on_prefix_change() {
1283 let mut app = create_test_app();
1284 app.prefix_stability_pct = Some(67);
1285 app.prefix_checks_total = 3;
1286 app.prefix_change_count = 1;
1287 // The one change was an undeclared drift — the case worth warning about.
1288 app.prefix_drift_count = 1;
1289 app.prefix_pin_reason = Some("initial".to_string());
1290 app.prefix_last_miss_reason = Some("drift:sys".to_string());
1291 app.last_prefix_change_desc =
1292 Some("drift — prefix cache invalidated: system prompt changed".to_string());
1293 app.last_pinned_prefix_hash =
1294 Some("deadbeef0000deadbeef0000deadbeef0000deadbeef0000deadbeef0000deadbeef".to_string());
1295
1296 let result = cache(&mut app, Some("stats"));
1297 let msg = result.message.expect("cache stats produces a message");
1298
1299 assert!(msg.contains("Stability: 67%"), "got: {msg}");
1300 assert!(msg.contains("WARNING — 1 undeclared drift"), "got: {msg}");
1301 assert!(msg.contains("Last miss: drift:sys"), "got: {msg}");
1302 assert!(msg.contains("system prompt changed"), "got: {msg}");
1303 assert!(msg.contains("1 change detected"), "got: {msg}");
1304 }
1305
1306 #[test]
1307 fn cache_stats_does_not_warn_on_declared_header_change() {
1308 let mut app = create_test_app();
1309 app.prefix_stability_pct = Some(67);
1310 app.prefix_checks_total = 3;
1311 app.prefix_change_count = 1;
1312 // A declared header change (e.g. /model): expected, not drift.
1313 app.prefix_drift_count = 0;
1314 app.prefix_pin_reason = Some("change:model".to_string());
1315 app.prefix_last_miss_reason = Some("change:model".to_string());
1316 app.last_prefix_change_desc = Some("change:model — tool set changed".to_string());
1317 app.last_pinned_prefix_hash =
1318 Some("deadbeef0000deadbeef0000deadbeef0000deadbeef0000deadbeef0000deadbeef".to_string());
1319
1320 let result = cache(&mut app, Some("stats"));
1321 let msg = result.message.expect("cache stats produces a message");
1322
1323 assert!(
1324 msg.contains("stable (all changes were declared header changes)"),
1325 "got: {msg}"
1326 );
1327 assert!(!msg.contains("WARNING — "), "got: {msg}");
1328 assert!(msg.contains("Pin reason: change:model"), "got: {msg}");
1329 }
1330
1331 #[test]
1332 fn cache_stats_shows_cache_hit_summary() {
1333 let mut app = create_test_app();
1334 app.prefix_stability_pct = Some(100);
1335 app.prefix_checks_total = 1;
1336 app.last_pinned_prefix_hash =
1337 Some("abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234".to_string());
1338
1339 app.push_turn_cache_record(TurnCacheRecord {
1340 provider: None,
1341 provider_identity: None,
1342 model: None,
1343 auto_model: false,
1344 input_tokens: 10_000,
1345 output_tokens: 1_000,
1346 cache_hit_tokens: Some(8_000),
1347 cache_miss_tokens: Some(2_000),
1348 reasoning_replay_tokens: None,
1349 cache_write_tokens: None,
1350 reasoning_tokens: None,
1351 cost_audit: None,
1352 recorded_at: Instant::now(),
1353 });
1354 app.push_turn_cache_record(TurnCacheRecord {
1355 provider: None,
1356 provider_identity: None,
1357 model: None,
1358 auto_model: false,
1359 input_tokens: 5_000,
1360 output_tokens: 500,
1361 cache_hit_tokens: Some(4_500),
1362 cache_miss_tokens: Some(500),
1363 reasoning_replay_tokens: None,
1364 cache_write_tokens: None,
1365 reasoning_tokens: None,
1366 cost_audit: None,
1367 recorded_at: Instant::now(),
1368 });
1369
1370 let result = cache(&mut app, Some("stats"));
1371 let msg = result.message.expect("cache stats produces a message");
1372
1373 assert!(msg.contains("Turns recorded: 2"), "got: {msg}");
1374 // Total: 12,500 hit out of 15,000 cache-aware = 83.3%
1375 assert!(msg.contains("83.3%"), "got: {msg}");
1376 }
1377
1378 #[test]
1379 fn cache_stats_low_hit_rate_shows_note() {
1380 let mut app = create_test_app();
1381 app.prefix_stability_pct = Some(100);
1382 app.prefix_checks_total = 1;
1383 app.last_pinned_prefix_hash =
1384 Some("abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234".to_string());
1385
1386 app.push_turn_cache_record(TurnCacheRecord {
1387 provider: None,
1388 provider_identity: None,
1389 model: None,
1390 auto_model: false,
1391 input_tokens: 10_000,
1392 output_tokens: 1_000,
1393 cache_hit_tokens: Some(1_000),
1394 cache_miss_tokens: Some(9_000),
1395 reasoning_replay_tokens: None,
1396 cache_write_tokens: None,
1397 reasoning_tokens: None,
1398 cost_audit: None,
1399 recorded_at: Instant::now(),
1400 });
1401
1402 let result = cache(&mut app, Some("stats"));
1403 let msg = result.message.expect("cache stats produces a message");
1404
1405 // 10% hit rate → below 80% threshold
1406 assert!(msg.contains("10.0%"), "got: {msg}");
1407 assert!(
1408 msg.contains("cache hit rate is low"),
1409 "should show low-hit-rate advisory, got: {msg}"
1410 );
1411 }
1412
1413 #[test]
1414 fn cache_stats_flags_reported_1747_low_hit_fixture() {
1415 let mut app = create_test_app();
1416 app.prefix_stability_pct = Some(100);
1417 app.prefix_checks_total = 1;
1418 app.last_pinned_prefix_hash =
1419 Some("abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234".to_string());
1420
1421 // Fixture from #1747 / Amund's DeepSeek-TUI session aggregate:
1422 // hit=21,356,928, miss=8,470,281, output=165,624.
1423 app.push_turn_cache_record(TurnCacheRecord {
1424 provider: None,
1425 provider_identity: None,
1426 model: None,
1427 auto_model: false,
1428 input_tokens: 29_827_209,
1429 output_tokens: 165_624,
1430 cache_hit_tokens: Some(21_356_928),
1431 cache_miss_tokens: Some(8_470_281),
1432 reasoning_replay_tokens: None,
1433 cache_write_tokens: None,
1434 reasoning_tokens: None,
1435 cost_audit: None,
1436 recorded_at: Instant::now(),
1437 });
1438
1439 let result = cache(&mut app, Some("stats"));
1440 let msg = result.message.expect("cache stats produces a message");
1441
1442 assert!(msg.contains("71.6%"), "got: {msg}");
1443 assert!(msg.contains("Cache hit tokens: 21.4M"), "got: {msg}");
1444 assert!(msg.contains("Cache miss tokens: 8.5M"), "got: {msg}");
1445 assert!(
1446 msg.contains("cache hit rate is low"),
1447 "reported #1747 fixture should remain below the advisory threshold: {msg}"
1448 );
1449 }
1450
1451 #[test]
1452 fn format_tokens_handles_all_scales() {
1453 assert_eq!(format_tokens(0), "0");
1454 assert_eq!(format_tokens(999), "999");
1455 assert_eq!(format_tokens(1_000), "1.0K");
1456 assert_eq!(format_tokens(15_500), "15.5K");
1457 assert_eq!(format_tokens(1_000_000), "1.0M");
1458 assert_eq!(format_tokens(2_500_000), "2.5M");
1459 }
1460
1461 #[test]
1462 fn tools_command_is_truthful_before_any_request_snapshot() {
1463 let mut app = create_test_app();
1464 let result = dispatch(&mut app, "tools", None).expect("registered tools command");
1465
1466 assert!(!result.is_error);
1467 assert!(
1468 result
1469 .message
1470 .expect("message")
1471 .contains("snapshot unavailable — no model request has been captured")
1472 );
1473 }
1474
1475 #[test]
1476 fn tools_command_and_compatibility_alias_render_same_exact_snapshot() {
1477 let mut app = create_test_app();
1478 app.session.last_tool_request_snapshot = Some(
1479 codewhale_engine::tool_inspection::ToolInspectionSnapshot::from_prepared_request(
1480 "turn-1",
1481 2,
1482 Some(&[test_tool("read_file")]),
1483 ),
1484 );
1485
1486 let primary = dispatch(&mut app, "tools", Some("json")).expect("primary command");
1487 let alias = dispatch(&mut app, "tool-studio", Some("json")).expect("compatibility alias");
1488 let primary = match primary.action.expect("primary pager") {
1489 AppAction::OpenTextPager { content, .. } => content,
1490 other => panic!("unexpected primary action: {other:?}"),
1491 };
1492 let alias = match alias.action.expect("alias pager") {
1493 AppAction::OpenTextPager { content, .. } => content,
1494 other => panic!("unexpected alias action: {other:?}"),
1495 };
1496
1497 assert_eq!(primary, alias);
1498 let parsed: serde_json::Value = serde_json::from_str(&primary).expect("valid JSON output");
1499 assert_eq!(parsed["turn_id"]["value"], "turn-1");
1500 assert_eq!(parsed["step"], 2);
1501 assert_eq!(parsed["tool_count"], 1);
1502 assert_eq!(parsed["tools"][0]["name"]["value"], "read_file");
1503 }
1504
1505 #[test]
1506 fn tools_command_rejects_unknown_formats_without_mutating_state() {
1507 let mut app = create_test_app();
1508 app.session.last_tool_request_snapshot = Some(
1509 codewhale_engine::tool_inspection::ToolInspectionSnapshot::from_prepared_request(
1510 "turn-1",
1511 1,
1512 Some(&[]),
1513 ),
1514 );
1515 let before = app.session.last_tool_request_snapshot.clone();
1516
1517 let result = dispatch(&mut app, "tools", Some("yaml")).expect("tools command");
1518
1519 assert!(result.is_error);
1520 assert_eq!(app.session.last_tool_request_snapshot, before);
1521 }
1522
1523 #[cfg(test)]
1524 mod cost_breakdown_tests {
1525 use super::*;
1526 use crate::commands::contract::DebugCostComponents as CostComponents;
1527 use crate::tui::app::App;
1528 use crate::tui::app::{TuiOptions, TurnCacheRecord};
1529 use codewhale_config::pricing::CostCurrency;
1530 use codewhale_engine::pricing::{CostEstimate, TurnCostAudit};
1531 use codewhale_runtime::config::Config;
1532 use std::path::PathBuf;
1533 use std::time::Instant;
1534
1535 fn test_app() -> App {
1536 let options = TuiOptions {
1537 skills_dir: PathBuf::from("/tmp/test-skills"),
1538 ..crate::tui::test_support::test_tui_options(PathBuf::from("/tmp/test-workspace"))
1539 };
1540 let mut app = App::new(options, &Config::default());
1541 app.ui_locale = codewhale_localization::Locale::En;
1542 app.cost_currency = CostCurrency::Usd;
1543 app.api_provider = codewhale_config::ProviderKind::Deepseek;
1544 app
1545 }
1546
1547 fn priced_audit(estimate: CostEstimate) -> TurnCostAudit {
1548 TurnCostAudit {
1549 estimate: Some(estimate),
1550 provenance: None,
1551 unpriced_classes: Vec::new(),
1552 unpriced_reason: None,
1553 live_pricing_defect: None,
1554 usd_priced: true,
1555 cny_priced: estimate.cny > 0.0,
1556 exact_usd: None,
1557 exact_cny: None,
1558 }
1559 }
1560
1561 fn turn_record(model: &str, audit: TurnCostAudit) -> TurnCacheRecord {
1562 TurnCacheRecord {
1563 provider: Some(codewhale_config::ProviderKind::Deepseek),
1564 provider_identity: None,
1565 model: Some(model.to_string()),
1566 auto_model: false,
1567 input_tokens: 100,
1568 output_tokens: 10,
1569 cache_hit_tokens: None,
1570 cache_miss_tokens: None,
1571 cache_write_tokens: None,
1572 reasoning_tokens: None,
1573 cost_audit: Some(audit),
1574 reasoning_replay_tokens: None,
1575 recorded_at: Instant::now(),
1576 }
1577 }
1578
1579 #[test]
1580 fn configured_model_cost_copy_does_not_claim_published_rates() {
1581 let _env = crate::test_support::lock_test_env();
1582 let mut app = test_app();
1583 app.session
1584 .cost_pricing_provenances
1585 .insert("user_override".into());
1586 app.session.cost_priced_turns = 1;
1587 let report = cost(&mut app).message.expect("cost report");
1588 assert!(report.contains("user-declared, unverified price estimates"));
1589 assert!(!report.contains("published rates"));
1590 assert!(!report.contains("money-metered"));
1591 }
1592
1593 /// The decomposition's terms are exactly the headline's inputs, so their
1594 /// sum reproduces the headline — including when the #244 monotonic floor,
1595 /// not the live accumulators, is the number on display (#4939).
1596 #[test]
1597 fn cost_breakdown_components_sum_to_headline() {
1598 let mut app = test_app();
1599 app.session.cost_priced_turns = 2;
1600 app.accrue_session_cost_estimate(CostEstimate {
1601 usd: 0.05,
1602 cny: 0.0,
1603 });
1604 app.accrue_subagent_cost_estimate(CostEstimate {
1605 usd: 0.02,
1606 cny: 0.0,
1607 });
1608
1609 // Live sum is the headline: no floor component.
1610 let components = CostComponents::compute(&app);
1611 assert_eq!(components.parent_turns, 0.05);
1612 assert_eq!(components.subagents, 0.02);
1613 assert_eq!(components.display_floor, 0.0);
1614 assert_eq!(
1615 components.sum(),
1616 app.displayed_session_cost_for_currency(CostCurrency::Usd),
1617 "components must sum to the /cost headline"
1618 );
1619
1620 // After a downward reconciliation the high-water is the headline; the
1621 // difference surfaces as an explicit floor component, and the sum still
1622 // reproduces the headline exactly.
1623 app.session.displayed_cost_high_water = 0.10;
1624 let components = CostComponents::compute(&app);
1625 assert!(components.display_floor > 0.0);
1626 assert_eq!(
1627 components.sum(),
1628 app.displayed_session_cost_for_currency(CostCurrency::Usd),
1629 "floor component must absorb exactly the high-water excess"
1630 );
1631
1632 let msg = cost(&mut app).message.expect("cost report");
1633 assert!(msg.contains("Breakdown"), "{msg}");
1634 assert!(msg.contains("Parent turns: $0.0500"), "{msg}");
1635 assert!(msg.contains("Sub-agents: $0.0200"), "{msg}");
1636 assert!(msg.contains("Reconciliation floor:"), "{msg}");
1637 }
1638
1639 /// Per-route attribution comes from the same `TurnCostAudit`s that fed the
1640 /// total, in the display currency; with every priced turn itemized, the
1641 /// route amounts account for the whole parent component. CNY amounts are
1642 /// the audits' provider-published CNY figures — never an FX projection of
1643 /// the USD column (#4939).
1644 #[test]
1645 fn cost_breakdown_itemizes_routes_from_turn_audits() {
1646 let mut app = test_app();
1647 app.cost_currency = CostCurrency::Cny;
1648 let turns = [
1649 CostEstimate {
1650 usd: 0.01,
1651 cny: 0.07,
1652 },
1653 CostEstimate {
1654 usd: 0.02,
1655 cny: 0.14,
1656 },
1657 ];
1658 for estimate in turns {
1659 let audit = priced_audit(estimate);
1660 app.record_turn_cost_audit(&audit);
1661 app.accrue_session_cost_estimate(estimate);
1662 app.push_turn_cache_record(turn_record("deepseek-chat", audit));
1663 }
1664
1665 let components = CostComponents::compute(&app);
1666 assert_eq!(
1667 components.sum(),
1668 app.displayed_session_cost_for_currency(CostCurrency::Cny),
1669 "CNY components must sum to the CNY headline"
1670 );
1671
1672 let msg = cost(&mut app).message.expect("cost report");
1673 assert!(
1674 msg.contains("Parent-turn spend by route (2 of 2 priced turns itemized):"),
1675 "{msg}"
1676 );
1677 // 0.07 + 0.14 accumulated in ring order equals the parent component's
1678 // accumulation, so the route line shows the whole parent spend.
1679 let route_amount = codewhale_commands::diagnostics_reports::format_cost_amount_precise(
1680 components.parent_turns,
1681 crate::commands::contract::to_command_currency(
1682 app.cost_display_currency(app.cost_currency),
1683 ),
1684 );
1685 assert!(
1686 msg.contains(&format!("deepseek/deepseek-chat: {route_amount}")),
1687 "{msg}"
1688 );
1689 assert!(msg.contains("¥"), "CNY display must use CNY symbol: {msg}");
1690 }
1691
1692 /// An unpriced headline renders no breakdown: decomposing a number that is
1693 /// not being shown would fabricate amounts the report just declined to
1694 /// claim.
1695 #[test]
1696 fn cost_breakdown_absent_when_headline_unknown() {
1697 let mut app = test_app();
1698 let msg = cost(&mut app).message.expect("cost report");
1699 assert!(!msg.contains("Breakdown"), "{msg}");
1700 assert!(!msg.contains("Parent turns:"), "{msg}");
1701 }
1702 }
1703
1704 #[cfg(test)]
1705 mod route_tests {
1706 use super::*;
1707
1708 #[test]
1709 fn cache_route_keeps_exact_named_custom_identity() {
1710 let record = TurnCacheRecord {
1711 provider: Some(codewhale_config::ProviderKind::Custom),
1712 provider_identity: Some("lm-studio".to_string()),
1713 model: Some("local-code-model".to_string()),
1714 auto_model: false,
1715 input_tokens: 1,
1716 output_tokens: 1,
1717 cache_hit_tokens: None,
1718 cache_miss_tokens: None,
1719 reasoning_replay_tokens: None,
1720 cache_write_tokens: None,
1721 reasoning_tokens: None,
1722 cost_audit: None,
1723 recorded_at: Instant::now(),
1724 };
1725
1726 let mut app = create_test_app();
1727 app.push_turn_cache_record(record);
1728 let mut bundle = app.command_contexts();
1729 let mut parts = bundle
1730 .contexts(codewhale_command_contract::handler::CommandCapabilities::DEBUG_DIAGNOSTICS)
1731 .into_parts();
1732 let turn = parts
1733 .debug_diagnostics
1734 .as_deref_mut()
1735 .unwrap()
1736 .cache_telemetry()
1737 .history
1738 .pop()
1739 .unwrap();
1740 assert_eq!(
1741 codewhale_commands::debug::cache_format::format_turn_cache_route(&turn),
1742 "lm-studio/local-code-..."
1743 );
1744 }
1745 }
1746
1747 #[cfg(test)]
1748 mod zones_tests {
1749 use super::*;
1750 use codewhale_runtime::config::Config;
1751 use std::path::PathBuf;
1752
1753 #[test]
1754 fn cache_zones_output_reports_real_wiring() {
1755 let mut app = App::new(
1756 crate::tui::test_support::test_tui_options(PathBuf::from(".")),
1757 &Config::default(),
1758 );
1759 app.api_messages = std::sync::Arc::new(Vec::new());
1760 app.last_pinned_prefix_hash = None;
1761 app.prefix_change_count = 0;
1762
1763 let expected = "\
1764 Cache Zones (#2264 three-zone contract)
1765
1766 ── PinnedPrefix (system + tools, frozen baseline)
1767 Status: unavailable (not yet frozen)
1768 Run a turn first to freeze the baseline.
1769
1770 ── AppendLog (conversation history, append-only)
1771 Status: wired — backs the engine session history
1772 Messages: 0
1773 History msgs: 0
1774
1775 ── TurnScratch (per-turn ephemeral data)
1776 Status: not wired — type scaffolding, unused by requests
1777
1778 ── Contract Status
1779 PinnedPrefix: not frozen
1780 AppendLog: wired (session history)
1781 TurnScratch: not wired
1782 ";
1783 assert_eq!(
1784 cache(&mut app, Some("zones")).message.as_deref(),
1785 Some(expected)
1786 );
1787 }
1788 }
1789
1790 #[cfg(test)]
1791 mod arg_tests {
1792 use super::*;
1793 use codewhale_runtime::config::Config;
1794 use std::path::PathBuf;
1795
1796 fn app() -> App {
1797 App::new(
1798 crate::tui::test_support::test_tui_options(PathBuf::from(".")),
1799 &Config::default(),
1800 )
1801 }
1802
1803 #[test]
1804 fn cache_rejects_unknown_word_args() {
1805 let mut app = app();
1806 for arg in ["stat", "inspector", "inspect--json"] {
1807 let result = cache(&mut app, Some(arg));
1808 assert!(result.is_error, "/cache {arg} must be a usage error");
1809 let text = result.message.as_deref().unwrap_or_default();
1810 assert!(
1811 text.contains(arg) && text.contains("Usage: /cache"),
1812 "{text}"
1813 );
1814 }
1815 }
1816
1817 #[test]
1818 fn cache_inspect_matches_whole_word_with_optional_flags() {
1819 let mut app = app();
1820 for arg in ["inspect", "inspect --json", "inspect --verbose"] {
1821 let result = cache(&mut app, Some(arg));
1822 let text = result.message.as_deref().unwrap_or_default();
1823 assert!(!result.is_error, "/cache {arg}: {text}");
1824 assert!(
1825 !text.contains("Unknown /cache argument"),
1826 "/cache {arg}: {text}"
1827 );
1828 }
1829 }
1830
1831 #[test]
1832 fn cache_numeric_arg_still_selects_count() {
1833 let mut app = app();
1834 let result = cache(&mut app, Some("5"));
1835 assert!(!result.is_error);
1836 }
1837 }
1838
1839 mod preview_host_tests {
1840 use super::*;
1841 use codewhale_models::Role;
1842 use codewhale_runtime::config::Config;
1843
1844 #[test]
1845 fn unknown_argument_is_rejected_without_touching_state() {
1846 let options = crate::tui::test_support::test_tui_options(std::path::PathBuf::from(
1847 "/tmp/test-workspace-preview-request",
1848 ));
1849 let mut app = App::new(options, &Config::default());
1850 let messages_before = app.api_messages.len();
1851 let history_before = app.history.len();
1852
1853 let result = dispatch(&mut app, "preview-request", Some("nope"))
1854 .expect("registered preview command");
1855
1856 assert!(!result.is_error);
1857 assert!(
1858 result
1859 .message
1860 .as_deref()
1861 .is_some_and(|message| message.contains("/preview-request")),
1862 "{result:?}"
1863 );
1864 assert!(result.action.is_none());
1865 assert_eq!(app.api_messages.len(), messages_before);
1866 assert_eq!(app.history.len(), history_before);
1867 }
1868
1869 #[test]
1870 fn command_delegates_to_the_engine_and_mutates_nothing() {
1871 let options = crate::tui::test_support::test_tui_options(std::path::PathBuf::from(
1872 "/tmp/test-workspace-preview-request-pure",
1873 ));
1874 let mut app = App::new(options, &Config::default());
1875 app.api_messages_mut().push(codewhale_models::Message {
1876 role: Role::User,
1877 content: vec![codewhale_models::ContentBlock::Text {
1878 text: "hello".to_string(),
1879 cache_control: None,
1880 }],
1881 });
1882
1883 let result = dispatch(&mut app, "preview-request", Some("json"))
1884 .expect("registered preview command");
1885
1886 // The command itself renders nothing: the engine is the authority.
1887 assert!(result.message.is_none(), "{result:?}");
1888 assert!(matches!(
1889 result.action,
1890 Some(AppAction::PreviewOutboundRequest { json: true, .. })
1891 ));
1892 assert_eq!(app.api_messages.len(), 1);
1893 assert!(app.history.is_empty());
1894 }
1895
1896 #[test]
1897 fn base_prompt_provenance_is_runtime_not_a_source_path() {
1898 let label = codewhale_engine::prompts::base_prompt_origin().label();
1899 assert!(!label.contains("crates/"), "{label}");
1900 assert!(!label.contains(".rs"), "{label}");
1901 assert!(
1902 label.contains("bundled") || label.contains("override"),
1903 "{label}"
1904 );
1905 }
1906 }
1907
1908 /// FEAT-029 must retain main's newer per-scope cache display when moving
1909 /// formatting behind the facet. Parent writes (including in-flight writes)
1910 /// and agent writes belong in their own denominators, never as invented hits.
1911 #[test]
1912 fn cache_report_preserves_upstream_scoped_session_rates() {
1913 for with_history in [false, true] {
1914 let mut harness = super::debug_diagnostics_test_support::DiagnosticsHarness::new();
1915 let app = &mut harness.app;
1916 app.ui_locale = codewhale_localization::Locale::En;
1917 if with_history {
1918 app.push_turn_cache_record(TurnCacheRecord {
1919 provider: None,
1920 provider_identity: None,
1921 model: None,
1922 auto_model: false,
1923 input_tokens: 1000,
1924 output_tokens: 10,
1925 cache_hit_tokens: Some(800),
1926 cache_miss_tokens: Some(200),
1927 reasoning_replay_tokens: None,
1928 cache_write_tokens: None,
1929 reasoning_tokens: None,
1930 cost_audit: None,
1931 recorded_at: Instant::now(),
1932 });
1933 }
1934 app.session.total_cache_hit_tokens = 800;
1935 app.session.total_cache_miss_tokens = 200;
1936 let parent_only = cache(app, None).message.expect("cache report");
1937 assert!(
1938 !parent_only.contains("Session cache hit rate:"),
1939 "{parent_only}"
1940 );
1941
1942 app.session.subagent_cache_hit_tokens = Some(600);
1943 app.session.subagent_cache_miss_tokens = Some(0);
1944 app.session.subagent_cache_write_tokens = Some(400);
1945 let scopes = cache(app, None).message.expect("cache report");
1946 assert!(
1947 scopes.ends_with("\n\nSession cache hit rate: parent 80% · agents 60% · combined 70%"),
1948 "{scopes}"
1949 );
1950
1951 app.session.total_cache_write_tokens = 200;
1952 app.session.pending_turn_cache_write_tokens = 400;
1953 let writes = cache(app, None).message.expect("cache report");
1954 assert!(
1955 writes.ends_with("\n\nSession cache hit rate: parent 50% · agents 60% · combined 54%"),
1956 "{writes}"
1957 );
1958
1959 app.session.reset_token_breakdown();
1960 app.session.subagent_cache_hit_tokens = Some(0);
1961 app.session.subagent_cache_miss_tokens = Some(0);
1962 app.session.subagent_cache_write_tokens = Some(400);
1963 let no_parent = cache(app, None).message.expect("cache report");
1964 assert!(
1965 no_parent.ends_with("\n\nSession cache hit rate: agents 0% · combined 0%"),
1966 "{no_parent}"
1967 );
1968 }
1969 }
1970
1970 lines RUST