返回 CodeWhale
context_inspector.rs
根目录 / crates / tui / src / tui / context_inspector.rs
1 //! Compact session context inspector.
2
3 use std::borrow::Cow;
4 use std::cell::RefCell;
5 use std::collections::HashSet;
6 use std::fmt::Write;
7
8 use crossterm::event::{KeyCode, KeyEvent, MouseButton, MouseEvent, MouseEventKind};
9 use ratatui::{
10 buffer::Buffer,
11 layout::Rect,
12 style::{Modifier, Style},
13 text::{Line, Span},
14 widgets::{Paragraph, Widget},
15 };
16
17 use crate::tui::app::{App, ToolDetailRecord};
18 use crate::tui::views::rounded::{
19 pad_selected_line, render_rounded_footer, render_rounded_surface,
20 };
21 use crate::tui::views::{ActionHint, ModalKind, ModalView, ViewAction, ViewEvent};
22 use codewhale_core::ContextReferenceSource;
23 use codewhale_engine::compaction::{
24 CompactionPath, estimate_input_tokens_for_pressure, inspect_compaction_keep,
25 last_round_kept_count, last_round_start, pinned_anchors_text,
26 };
27 use codewhale_engine::session_manager::SessionContextReference;
28 use codewhale_localization::{Locale, MessageId, tr};
29 use codewhale_models::{SystemPrompt, Tool};
30 use codewhale_palette as palette;
31 use codewhale_runtime::context_budget::{
32 CONTEXT_CRITICAL_THRESHOLD_PERCENT, CONTEXT_WARNING_THRESHOLD_PERCENT,
33 };
34 use codewhale_tui_kit::menu_style;
35
36 /// Marker used by per-turn working-set metadata. Replicated here so the
37 /// context inspector can distinguish stable prompt blocks from volatile
38 /// working-set context without importing engine internals.
39 const WORKING_SET_MARKER: &str = "## Repo Working Set";
40
41 const MAX_REFERENCE_ROWS: usize = 12;
42 const MAX_TOOL_ROWS: usize = 8;
43 const MAX_SCHEMA_COST_ROWS: usize = 24;
44 const SCHEMA_TOKEN_DIVISOR: usize = 4;
45
46 const SYSTEM_LAYER_MARKERS: &[(&str, &str, PromptLayerKind)] = &[
47 (
48 "Bundled constitution",
49 "## Codewhale",
50 PromptLayerKind::Static,
51 ),
52 ("Language policy", "## Language", PromptLayerKind::Static),
53 (
54 "Output formatting",
55 "## Output Formatting",
56 PromptLayerKind::Static,
57 ),
58 (
59 "Repository constitution",
60 "<codewhale_repo_constitution",
61 PromptLayerKind::Static,
62 ),
63 (
64 "Project context",
65 "<project_instructions",
66 PromptLayerKind::Static,
67 ),
68 (
69 "Project context pack",
70 "## Project Context Pack",
71 PromptLayerKind::Static,
72 ),
73 ("Environment", "## Environment", PromptLayerKind::Static),
74 ("Skills", "## Skills", PromptLayerKind::Static),
75 (
76 "Core execution",
77 "## Core Execution",
78 PromptLayerKind::Static,
79 ),
80 ("Compact template", "## Compact", PromptLayerKind::Static),
81 (
82 "Configured instructions",
83 "<instructions ",
84 PromptLayerKind::Dynamic,
85 ),
86 ("User memory", "## User Memory", PromptLayerKind::Dynamic),
87 (
88 "Current session goal",
89 "## Current Session Goal",
90 PromptLayerKind::Dynamic,
91 ),
92 (
93 "Previous session relay",
94 "## Previous Session Relay",
95 PromptLayerKind::Dynamic,
96 ),
97 (
98 "Volatile working set",
99 WORKING_SET_MARKER,
100 PromptLayerKind::Dynamic,
101 ),
102 ];
103
104 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
105 enum PromptLayerKind {
106 Static,
107 Dynamic,
108 }
109
110 impl PromptLayerKind {
111 fn label(self, locale: Locale) -> Cow<'static, str> {
112 match self {
113 Self::Static => tr(locale, MessageId::CtxInspCacheFriendly),
114 Self::Dynamic => tr(locale, MessageId::CtxInspChangesByTurn),
115 }
116 }
117 }
118
119 /// Localize well-known layer labels that already have inspector MessageIds.
120 /// Other layer names stay as English product identifiers.
121 fn layer_display_name(name: &'static str, locale: Locale) -> Cow<'static, str> {
122 match name {
123 "Volatile working set" => tr(locale, MessageId::CtxInspVolatileWorkingSet),
124 other => Cow::Borrowed(other),
125 }
126 }
127
128 #[derive(Debug)]
129 struct PromptTextLayer<'a> {
130 name: &'static str,
131 kind: PromptLayerKind,
132 body: &'a str,
133 }
134
135 fn context_window_source_label(
136 source: codewhale_engine::route_runtime::ContextWindowSource,
137 locale: Locale,
138 ) -> Cow<'static, str> {
139 use codewhale_engine::route_runtime::ContextWindowSource;
140 if locale == Locale::En {
141 return Cow::Owned(source.display_label());
142 }
143 let id = match source {
144 ContextWindowSource::Configured | ContextWindowSource::UserDeclared => {
145 MessageId::StatusContextSourceConfigured
146 }
147 ContextWindowSource::ConfiguredModel => MessageId::StatusContextSourceConfiguredModel,
148 ContextWindowSource::ProviderReported => MessageId::StatusContextSourceProviderReported,
149 ContextWindowSource::StaticKimiCodeSafeFloor => MessageId::StatusContextSourceKimiSafeFloor,
150 ContextWindowSource::Catalog => MessageId::StatusContextSourceCatalog,
151 ContextWindowSource::NameSuffixHint => MessageId::StatusContextSourceModelHint,
152 ContextWindowSource::Fallback => MessageId::StatusContextSourceFallback,
153 };
154 tr(locale, id)
155 }
156
157 fn restored_window_label(app: &App, locale: Locale) -> Option<String> {
158 let budget = app
159 .matching_auto_budget()
160 .filter(|budget| budget.restored)?;
161 let route = tr(locale, MessageId::ModelPickerAutoLastRoute)
162 .replace("{provider}", &budget.provider_identity)
163 .replace("{model}", &budget.model);
164 Some(format!(
165 "{route} · {} {} ({})",
166 budget.window.tokens,
167 tr(locale, MessageId::CtxInspTokens),
168 budget.window.source.display_label()
169 ))
170 }
171
172 #[must_use]
173 pub fn build_context_inspector_text(app: &App, locale: Locale) -> String {
174 let mut out = String::new();
175 let usage = context_usage(app);
176 let (used, max, percent) = usage;
177
178 let _ = writeln!(out, "{}", tr(locale, MessageId::CtxInspSessionContext));
179 let _ = writeln!(out, "---------------");
180 let _ = writeln!(
181 out,
182 "{}: {}",
183 tr(locale, MessageId::CtxInspModel),
184 app.model
185 );
186 if let Some(previous) = restored_window_label(app, locale) {
187 let _ = writeln!(out, "{previous}");
188 }
189 let _ = writeln!(
190 out,
191 "{}: {}",
192 tr(locale, MessageId::CtxInspWorkspace),
193 codewhale_util::utils::display_path(&app.workspace)
194 );
195 if let Some(session_id) = app.current_session_id.as_deref() {
196 let _ = writeln!(
197 out,
198 "{}: {}",
199 tr(locale, MessageId::CtxInspSession),
200 codewhale_engine::session_manager::truncate_id(session_id)
201 );
202 }
203 // Real provider-token cache hit rate from the same records /cache
204 // aggregates (C3): only provider-reported cache telemetry counts, so the
205 // number is what the user actually paid to keep, not a predicted guess.
206 let mut cache_turns = 0u64;
207 let (cache_hit, cache_miss) =
208 app.session
209 .turn_cache_history
210 .iter()
211 .fold((0u64, 0u64), |(hit, miss), record| {
212 let Some(hit_tokens_u32) = record.cache_hit_tokens else {
213 return (hit, miss);
214 };
215 let hit_tokens = u64::from(hit_tokens_u32);
216 let miss_tokens = u64::from(
217 record
218 .cache_miss_tokens
219 .unwrap_or(record.input_tokens.saturating_sub(hit_tokens_u32)),
220 );
221 cache_turns += 1;
222 (hit + hit_tokens, miss + miss_tokens)
223 });
224 let cache_total = cache_hit + cache_miss;
225 if cache_turns > 0 && cache_total > 0 {
226 let cache_percent = (cache_hit as f64 / cache_total as f64 * 100.0).clamp(0.0, 100.0);
227 let _ = writeln!(
228 out,
229 "Provider cache hit rate: {cache_percent:.1}% over {cache_turns} cache-aware turn{}",
230 if cache_turns == 1 { "" } else { "s" },
231 );
232 } else {
233 let _ = writeln!(out, "Provider cache hit rate: no cache telemetry yet");
234 }
235 let status_label = match context_status(percent) {
236 ContextPressure::Critical => tr(locale, MessageId::CtxInspCritical),
237 ContextPressure::High => tr(locale, MessageId::CtxInspHigh),
238 ContextPressure::Ok => tr(locale, MessageId::CtxInspOk),
239 };
240 let tokens_unit = tr(locale, MessageId::CtxInspTokens);
241 let source_label = context_window_source_label(app.effective_context_window_source(), locale);
242 let _ = writeln!(
243 out,
244 "{ctx_label}: {status_label} - ~{used}/{max} {tokens_unit} ({percent:.1}% · {source_label})",
245 ctx_label = tr(locale, MessageId::CtxInspContext),
246 );
247 let cells = tr(locale, MessageId::CtxInspCells);
248 let api_msgs = tr(locale, MessageId::CtxInspApiMessages);
249 let _ = writeln!(
250 out,
251 "{label}: {} {cells}, {} {api_msgs}",
252 app.history.len(),
253 app.api_messages.len(),
254 label = tr(locale, MessageId::CtxInspTranscript),
255 );
256 if let Some(kept) = last_round_kept_count(&app.api_messages) {
257 let _ = writeln!(
258 out,
259 "Last compaction: kept last round verbatim ({kept} messages); earlier turns summarized."
260 );
261 }
262 let _ = writeln!(
263 out,
264 "{}: {}",
265 tr(locale, MessageId::CtxInspWorkspaceStatus),
266 app.workspace_context
267 .as_deref()
268 .unwrap_or(&*tr(locale, MessageId::CtxInspNotSampledYet))
269 );
270
271 let _ = writeln!(out);
272 push_compaction_and_anchors(&mut out, app, locale);
273 let _ = writeln!(out);
274 push_system_prompt_structure(&mut out, app, locale);
275 if let Some(record) = app
276 .api_messages
277 .iter()
278 .rev()
279 .find_map(codewhale_engine::runtime_handoff::constitution_display)
280 {
281 let source = match record
282 .split_once("\n\n")
283 .map(|(_, guidance)| guidance.lines().next().unwrap_or_default())
284 {
285 Some(line) if line.starts_with("Account profile constitution, settings revision ") => {
286 tr(locale, MessageId::CtxInspConstitutionAccount).replace(
287 "{revision}",
288 line.trim_start_matches("Account profile constitution, settings revision ")
289 .trim_end_matches('.'),
290 )
291 }
292 Some(_) => tr(locale, MessageId::CtxInspConstitutionLocal).into_owned(),
293 None => tr(locale, MessageId::CtxInspConstitutionWithdrawn).into_owned(),
294 };
295 let label = tr(locale, MessageId::CtxInspPersonalConstitution);
296 let tokens = record.chars().count().div_ceil(3);
297 let unit = tr(locale, MessageId::CtxInspTokens);
298 let cadence = tr(locale, MessageId::CtxInspChangesByTurn);
299 let _ = writeln!(out, "\n{label} ({source}): ~{tokens} {unit} [{cadence}]");
300 }
301 let _ = writeln!(out);
302 push_references(&mut out, &app.session_context_references, locale);
303 let _ = writeln!(out);
304 push_tools(&mut out, app, locale);
305 push_tool_schema_costs(&mut out, app, locale);
306
307 out
308 }
309
310 fn context_usage(app: &App) -> (usize, u32, f64) {
311 let max = app.effective_context_window();
312 // The meter must show the SAME pressure signal the auto-compaction trigger
313 // decides on (compaction::estimate_input_tokens_for_pressure, the
314 // non-inflated estimate with framing overhead). The old conservative
315 // overflow estimator was ~1.5x larger, so the meter showed the trigger
316 // point as "free" while compaction was still far away (ops T1) — and vice
317 // versa the meter read "free" as negative when the engine was only halfway.
318 let estimated =
319 estimate_input_tokens_for_pressure(&app.api_messages, app.system_prompt.as_ref());
320 // The trigger decides on max(estimate, provider-billed prompt); the meter
321 // must too, or a provider billing above the local estimate (non-ASCII
322 // text, server-side framing) makes the meter under-show real pressure
323 // (#5577). The billed receipt is per model call, so it goes stale only
324 // until the next step or compaction updates it.
325 let used = estimated.max(
326 app.last_billed_input_tokens
327 .map(|tokens| tokens as usize)
328 .unwrap_or(0),
329 );
330 let percent = ((used as f64 / f64::from(max)) * 100.0).clamp(0.0, 100.0);
331 (used, max, percent)
332 }
333
334 enum ContextPressure {
335 Ok,
336 High,
337 Critical,
338 }
339
340 fn context_status(percent: f64) -> ContextPressure {
341 if percent >= CONTEXT_CRITICAL_THRESHOLD_PERCENT {
342 ContextPressure::Critical
343 } else if percent >= CONTEXT_WARNING_THRESHOLD_PERCENT {
344 ContextPressure::High
345 } else {
346 ContextPressure::Ok
347 }
348 }
349
350 fn compaction_path_label(path: CompactionPath, locale: Locale) -> Cow<'static, str> {
351 match path {
352 CompactionPath::Summary => tr(locale, MessageId::CtxInspCompactionPathSummary),
353 CompactionPath::PruneOnly => tr(locale, MessageId::CtxInspCompactionPathPrune),
354 }
355 }
356
357 fn compaction_assistant_clause(kept: bool, locale: Locale) -> Cow<'static, str> {
358 if kept {
359 tr(locale, MessageId::CtxInspCompactionAssistantKept)
360 } else {
361 Cow::Borrowed("")
362 }
363 }
364
365 fn last_round_messages(messages: &[codewhale_models::Message]) -> &[codewhale_models::Message] {
366 let start = last_round_start(messages).min(messages.len());
367 &messages[start..]
368 }
369
370 fn compaction_detail_for_app(app: &App, locale: Locale) -> (String, usize) {
371 let keep = inspect_compaction_keep(&app.api_messages);
372 let assistant = compaction_assistant_clause(keep.last_round_assistant, locale);
373 let last_round_tokens =
374 estimate_input_tokens_for_pressure(last_round_messages(&app.api_messages), None);
375 let detail = if let Some(snapshot) = app.last_compaction.as_ref() {
376 tr(locale, MessageId::CtxInspCompactionDetail)
377 .replace(
378 "{path}",
379 &compaction_path_label(snapshot.coverage.path, locale),
380 )
381 .replace("{before}", &snapshot.messages_before.to_string())
382 .replace("{after}", &snapshot.messages_after.to_string())
383 .replace(
384 "{round}",
385 &snapshot.coverage.last_round_messages.to_string(),
386 )
387 .replace(
388 "{tools}",
389 &snapshot.coverage.last_round_tool_results.to_string(),
390 )
391 .replace("{assistant}", &assistant)
392 } else if keep.has_checkpoint {
393 tr(locale, MessageId::CtxInspCompactionRestored)
394 .replace("{round}", &keep.last_round_messages.to_string())
395 .replace("{tools}", &keep.last_round_tool_results.to_string())
396 .replace("{assistant}", &assistant)
397 } else {
398 tr(locale, MessageId::CtxInspCompactionNever).into_owned()
399 };
400 (detail, last_round_tokens)
401 }
402
403 fn anchors_detail_for_app(app: &App, locale: Locale) -> (String, usize) {
404 match pinned_anchors_text(Some(&app.workspace)) {
405 Some(text) => {
406 let chars = text.chars().count();
407 (
408 tr(locale, MessageId::CtxInspAnchorsPresent).replace("{chars}", &chars.to_string()),
409 chars.div_ceil(3),
410 )
411 }
412 None => (tr(locale, MessageId::CtxInspAnchorsNone).into_owned(), 0),
413 }
414 }
415
416 fn push_compaction_and_anchors(out: &mut String, app: &App, locale: Locale) {
417 let (compaction_detail, _) = compaction_detail_for_app(app, locale);
418 let (anchors_detail, _) = anchors_detail_for_app(app, locale);
419 let _ = writeln!(out, "{}", tr(locale, MessageId::CtxInspRowCompaction));
420 let _ = writeln!(out, "----------");
421 let _ = writeln!(out, "{compaction_detail}");
422 let _ = writeln!(out);
423 let _ = writeln!(out, "{}", tr(locale, MessageId::CtxInspRowAnchors));
424 let _ = writeln!(out, "-------");
425 let _ = writeln!(out, "{anchors_detail}");
426 }
427
428 /// Inspect the system prompt structure, split into cache-friendly stable
429 /// prefix blocks and the volatile working-set tail block.
430 fn push_system_prompt_structure(out: &mut String, app: &App, locale: Locale) {
431 let _ = writeln!(out, "{}", tr(locale, MessageId::CtxInspSystemPrompt));
432 let _ = writeln!(out, "-----------------------");
433
434 // Conservative token estimate: ~3 chars per token (consistent with
435 // compaction.rs internal helpers — replicated here to avoid depending
436 // on a private function).
437 let text_tokens = |text: &str| text.chars().count().div_ceil(3);
438
439 let total_est = match &app.system_prompt {
440 Some(SystemPrompt::Text(t)) => text_tokens(t),
441 Some(SystemPrompt::Blocks(blocks)) => blocks.iter().map(|b| text_tokens(&b.text)).sum(),
442 None => 0,
443 };
444
445 let stable_lbl = tr(locale, MessageId::CtxInspStablePrefix);
446 let volatile_lbl = tr(locale, MessageId::CtxInspVolatileWorkingSet);
447 let first_line_lbl = tr(locale, MessageId::CtxInspFirstLine);
448 let total_lbl = tr(locale, MessageId::CtxInspTotal);
449 let text_prompt_lbl = tr(locale, MessageId::CtxInspTextPromptLayers);
450 let single_blob_lbl = tr(locale, MessageId::CtxInspSingleTextBlob);
451 let blocks_unit = tr(locale, MessageId::CtxInspBlocks);
452 let block_unit = tr(locale, MessageId::CtxInspBlock);
453 let tokens_unit = tr(locale, MessageId::CtxInspTokens);
454 let layers_unit = tr(locale, MessageId::CtxInspLayers);
455 let none_lbl = tr(locale, MessageId::CtxInspNone);
456 let empty_lbl = tr(locale, MessageId::CtxInspEmpty);
457 let cache_friendly = tr(locale, MessageId::CtxInspCacheFriendly);
458 let changes_by_turn = tr(locale, MessageId::CtxInspChangesByTurn);
459 let stable_only = tr(locale, MessageId::CtxInspStablePrefixOnly);
460 let no_system_prompt = tr(locale, MessageId::CtxInspNoSystemPrompt);
461 match &app.system_prompt {
462 Some(SystemPrompt::Blocks(blocks)) => {
463 let working_set_idx = blocks
464 .iter()
465 .position(|b| b.text.contains(WORKING_SET_MARKER));
466 let (stable_count, working_block) = match working_set_idx {
467 Some(idx) => (idx, Some(&blocks[idx])),
468 None => (blocks.len(), None),
469 };
470
471 let stable_tokens: usize = blocks
472 .iter()
473 .take(stable_count)
474 .map(|b| text_tokens(&b.text))
475 .sum();
476 let working_tokens = working_block.map(|b| text_tokens(&b.text)).unwrap_or(0);
477
478 let _ = writeln!(
479 out,
480 " {stable_lbl}: {stable_count} {blocks_unit}, ~{stable_tokens} {tokens_unit} [{cache_friendly}]"
481 );
482 if let Some(block) = working_block {
483 let _ = writeln!(
484 out,
485 " {volatile_lbl}: 1 {block_unit}, ~{working_tokens} {tokens_unit} [{changes_by_turn}]"
486 );
487 let _ = writeln!(
488 out,
489 " {first_line_lbl}: {}",
490 block.text.lines().next().unwrap_or(&*empty_lbl)
491 );
492 } else {
493 let _ = writeln!(out, " {volatile_lbl}: {none_lbl}");
494 }
495 let _ = writeln!(
496 out,
497 " {total_lbl}: {} {blocks_unit}, ~{total_est} {tokens_unit}",
498 blocks.len()
499 );
500 let layers = blocks
501 .iter()
502 .flat_map(|block| split_text_prompt_layers(&block.text))
503 .filter(|layer| !layer.body.is_empty())
504 .collect::<Vec<_>>();
505 if layers.iter().any(|layer| layer.name != "System prompt") {
506 let _ = writeln!(out, " {text_prompt_lbl}:");
507 for layer in layers {
508 let tokens = text_tokens(layer.body);
509 let kind_lbl = layer.kind.label(locale);
510 let layer_name = layer_display_name(layer.name, locale);
511 let _ = writeln!(
512 out,
513 " - {layer_name}: ~{tokens} {tokens_unit} [{kind_lbl}]",
514 );
515 }
516 }
517 }
518 Some(SystemPrompt::Text(text)) => {
519 let layers = split_text_prompt_layers(text);
520 if layers.len() > 1
521 || layers
522 .first()
523 .is_some_and(|layer| layer.name != "System prompt")
524 {
525 let _ = writeln!(
526 out,
527 " {text_prompt_lbl}: {} {layers_unit}, ~{total_est} {tokens_unit}",
528 layers.len()
529 );
530 for layer in layers {
531 let tokens = text_tokens(layer.body);
532 let kind_lbl = layer.kind.label(locale);
533 let layer_name = layer_display_name(layer.name, locale);
534 let _ = writeln!(
535 out,
536 " - {layer_name}: ~{tokens} {tokens_unit} [{kind_lbl}]",
537 );
538 }
539 } else {
540 let _ = writeln!(
541 out,
542 " {single_blob_lbl} (~{total_est} {tokens_unit}) [{stable_only}]"
543 );
544 }
545 }
546 None => {
547 let _ = writeln!(out, " {no_system_prompt}");
548 }
549 }
550
551 // Cache-economics hint
552 let _ = writeln!(out, " {}", tr(locale, MessageId::CtxInspCacheTip));
553 }
554
555 fn split_text_prompt_layers(text: &str) -> Vec<PromptTextLayer<'_>> {
556 let mut starts = SYSTEM_LAYER_MARKERS
557 .iter()
558 .filter_map(|(name, marker, kind)| text.find(marker).map(|idx| (idx, *name, *kind)))
559 .collect::<Vec<_>>();
560 starts.sort_by_key(|(idx, _, _)| *idx);
561
562 let Some((first_idx, _, _)) = starts.first().copied() else {
563 return vec![PromptTextLayer {
564 name: "System prompt",
565 kind: PromptLayerKind::Static,
566 body: text.trim(),
567 }];
568 };
569
570 let mut layers = Vec::new();
571 if first_idx > 0 {
572 layers.push(PromptTextLayer {
573 name: "Global system prefix",
574 kind: PromptLayerKind::Static,
575 body: text[..first_idx].trim(),
576 });
577 }
578
579 for (i, (start, name, kind)) in starts.iter().enumerate() {
580 let end = starts.get(i + 1).map_or(text.len(), |(idx, _, _)| *idx);
581 layers.push(PromptTextLayer {
582 name,
583 kind: *kind,
584 body: text[*start..end].trim(),
585 });
586 }
587
588 layers
589 }
590
591 fn push_references(out: &mut String, references: &[SessionContextReference], locale: Locale) {
592 let _ = writeln!(out, "{}", tr(locale, MessageId::CtxInspReferences));
593 let _ = writeln!(out, "----------");
594
595 let reference_key = |reference: &codewhale_core::ContextReference| {
596 format!(
597 "{:?}:{:?}:{}:{}",
598 reference.source, reference.kind, reference.target, reference.label
599 )
600 };
601 let unique_total = references
602 .iter()
603 .map(|record| reference_key(&record.reference))
604 .collect::<HashSet<_>>()
605 .len();
606 let mut seen = HashSet::new();
607 let mut rendered = 0usize;
608 for record in references {
609 let reference = &record.reference;
610 if !seen.insert(reference_key(reference)) {
611 continue;
612 }
613 if rendered >= MAX_REFERENCE_ROWS {
614 let remaining = unique_total.saturating_sub(rendered);
615 if remaining > 0 {
616 let _ = writeln!(
617 out,
618 "- ... {remaining} {}",
619 tr(locale, MessageId::CtxInspMoreReferences)
620 );
621 }
622 break;
623 }
624
625 let prefix = match reference.source {
626 ContextReferenceSource::AtMention => "@",
627 ContextReferenceSource::Attachment => "/attach ",
628 };
629 let state = if reference.included {
630 if reference.expanded {
631 tr(locale, MessageId::CtxInspIncluded)
632 } else {
633 tr(locale, MessageId::CtxInspAttached)
634 }
635 } else {
636 tr(locale, MessageId::CtxInspNotIncluded)
637 };
638 let detail = reference
639 .detail
640 .as_deref()
641 .filter(|detail| !detail.trim().is_empty())
642 .map(|detail| format!(" - {detail}"))
643 .unwrap_or_default();
644 let _ = writeln!(
645 out,
646 "- [{}] {prefix}{} -> {} ({state}{detail})",
647 reference.badge, reference.label, reference.target
648 );
649 rendered += 1;
650 }
651
652 if rendered == 0 {
653 let _ = writeln!(out, "- {}", tr(locale, MessageId::CtxInspNoReferences));
654 }
655 }
656
657 fn push_tools(out: &mut String, app: &App, locale: Locale) {
658 let _ = writeln!(out, "{}", tr(locale, MessageId::CtxInspRecentTools));
659 let _ = writeln!(out, "------------");
660
661 let mut rows: Vec<(usize, &ToolDetailRecord)> = app
662 .tool_details_by_cell
663 .iter()
664 .map(|(idx, detail)| (*idx, detail))
665 .collect();
666 rows.sort_by_key(|(idx, _)| std::cmp::Reverse(*idx));
667
668 let mut rendered = 0usize;
669 for detail in app.active_tool_details.values() {
670 let location = tr(locale, MessageId::CtxInspActive);
671 push_tool_row(out, locale, &location, detail);
672 rendered += 1;
673 if rendered >= MAX_TOOL_ROWS {
674 break;
675 }
676 }
677 for (cell_idx, detail) in rows
678 .into_iter()
679 .take(MAX_TOOL_ROWS.saturating_sub(rendered))
680 {
681 let location = format!("{} {cell_idx}", tr(locale, MessageId::CtxInspCell));
682 push_tool_row(out, locale, &location, detail);
683 rendered += 1;
684 }
685
686 if rendered == 0 {
687 let _ = writeln!(out, "- {}", tr(locale, MessageId::CtxInspNoToolActivity));
688 } else {
689 let details = crate::tui::shell_key_routing::display_chord(
690 crate::tui::shell_key_routing::binding(
691 crate::tui::shell_key_routing::ShellBindingId::ToolDetails,
692 )
693 .footer_chord,
694 );
695 let _ = writeln!(
696 out,
697 "- {}",
698 tr(locale, MessageId::CtxInspVHint).replace("{details}", details.as_ref())
699 );
700 }
701 }
702
703 fn push_tool_row(out: &mut String, locale: Locale, location: &str, detail: &ToolDetailRecord) {
704 let output_state = if detail.output.as_deref().is_some_and(|out| !out.is_empty()) {
705 tr(locale, MessageId::CtxInspOutputCaptured)
706 } else {
707 tr(locale, MessageId::CtxInspNoOutputYet)
708 };
709 let _ = writeln!(
710 out,
711 "- [{}] {} {} ({output_state})",
712 location,
713 detail.tool_name,
714 short_tool_id(&detail.tool_id)
715 );
716 }
717
718 fn tool_schema_tokens(tool: &Tool) -> usize {
719 serde_json::to_string(tool)
720 .map(|schema| schema.chars().count().div_ceil(SCHEMA_TOKEN_DIVISOR))
721 .unwrap_or_default()
722 }
723
724 fn push_tool_schema_costs(out: &mut String, app: &App, locale: Locale) {
725 let Some(catalog) = app.session.last_tool_catalog.as_ref() else {
726 return;
727 };
728
729 let _ = writeln!(out);
730 let tokens = tr(locale, MessageId::CtxInspTokens);
731 let schema_costs_label = tr(locale, MessageId::CtxInspToolSchemaCosts);
732 let _ = writeln!(out, "{} ({})", schema_costs_label, tokens);
733 let _ = writeln!(out, "------------");
734
735 let mut built_in: Vec<(String, usize)> = catalog
736 .iter()
737 .filter(|tool| !codewhale_engine::mcp::McpPool::is_mcp_tool(&tool.name))
738 .map(|tool| (tool.name.clone(), tool_schema_tokens(tool)))
739 .collect();
740 built_in.sort_by(|left, right| right.1.cmp(&left.1).then_with(|| left.0.cmp(&right.0)));
741 let built_in_total: usize = built_in.iter().map(|(_, cost)| cost).sum();
742 let _ = writeln!(
743 out,
744 "- [catalog] ~{built_in_total} {tokens} ({} tools)",
745 built_in.len()
746 );
747 for (name, cost) in built_in.iter().take(MAX_SCHEMA_COST_ROWS) {
748 let _ = writeln!(out, " - {name}: ~{cost} {tokens}");
749 }
750 if built_in.len() > MAX_SCHEMA_COST_ROWS {
751 let _ = writeln!(
752 out,
753 " - ... {} more catalog tools",
754 built_in.len() - MAX_SCHEMA_COST_ROWS
755 );
756 }
757
758 let Some(snapshot) = app.mcp_snapshot.as_ref() else {
759 return;
760 };
761 for server in &snapshot.servers {
762 let mut server_tokens = 0usize;
763 let mut catalog_tools = 0usize;
764 for announced in &server.tools {
765 if let Some(tool) = catalog
766 .iter()
767 .find(|tool| tool.name == announced.model_name)
768 {
769 server_tokens += tool_schema_tokens(tool);
770 catalog_tools += 1;
771 }
772 }
773 let _ = writeln!(
774 out,
775 "- [mcp:{}] ~{server_tokens} {tokens} ({catalog_tools}/{} announced tools)",
776 server.name,
777 server.tools.len()
778 );
779 }
780 }
781
782 fn short_tool_id(id: &str) -> String {
783 // Slice by characters, not bytes: a tool id from a gateway can contain
784 // multibyte characters, and `&id[..8]` panics on a byte index that lands
785 // mid-codepoint (2026-08-04 review).
786 let mut chars = id.chars();
787 let head: String = chars.by_ref().take(8).collect();
788 if chars.next().is_some() {
789 format!("{head}...")
790 } else {
791 head
792 }
793 }
794
795 #[derive(Debug, Clone)]
796 struct ContextBucket {
797 label: String,
798 tokens: usize,
799 percent: f64,
800 detail: String,
801 }
802
803 /// Live context surface. The host refreshes its snapshot immediately before
804 /// every render, so opening it never freezes the underlying session facts.
805 pub(crate) struct ContextInspectorView {
806 used: usize,
807 max: u32,
808 percent: f64,
809 window_source: codewhale_engine::route_runtime::ContextWindowSource,
810 model: String,
811 workspace: String,
812 restored_window: Option<String>,
813 auto_compact: bool,
814 threshold: f64,
815 compact_threshold_tokens: usize,
816 rows: Vec<ContextBucket>,
817 selected: usize,
818 hitboxes: RefCell<Vec<(u16, usize)>>,
819 locale: Locale,
820 }
821
822 impl ContextInspectorView {
823 #[must_use]
824 pub(crate) fn new(app: &App) -> Self {
825 let mut view = Self {
826 used: 0,
827 max: 0,
828 percent: 0.0,
829 window_source: app.effective_context_window_source(),
830 model: String::new(),
831 workspace: String::new(),
832 restored_window: None,
833 auto_compact: app.auto_compact,
834 threshold: 0.0,
835 compact_threshold_tokens: 0,
836 rows: Vec::new(),
837 selected: 0,
838 hitboxes: RefCell::new(Vec::new()),
839 locale: app.ui_locale,
840 };
841 view.refresh_from_app(app);
842 view
843 }
844
845 pub(crate) fn refresh_from_app(&mut self, app: &App) {
846 let (used, max, percent) = context_usage(app);
847 let system_tokens = estimate_input_tokens_for_pressure(&[], app.system_prompt.as_ref());
848 let message_tokens = used.saturating_sub(system_tokens);
849 let free_tokens = usize::try_from(max)
850 .unwrap_or(usize::MAX)
851 .saturating_sub(used);
852 let full_detail = build_context_inspector_text(app, app.ui_locale);
853 self.used = used;
854 self.max = max;
855 self.percent = percent;
856 self.window_source = app.effective_context_window_source();
857 self.model = app.model_display_label();
858 self.restored_window = restored_window_label(app, app.ui_locale);
859 self.workspace = codewhale_util::utils::display_path(&app.workspace);
860 self.auto_compact = app.auto_compact;
861 self.compact_threshold_tokens = app.compact_threshold;
862 self.threshold = if app.auto_compact && max > 0 {
863 (app.compact_threshold as f64 * 100.0 / f64::from(max)).clamp(0.0, 100.0)
864 } else {
865 app.auto_compact_threshold_percent
866 };
867 self.locale = app.ui_locale;
868 let max_f = f64::from(max.max(1));
869 let (compaction_detail, compaction_tokens) = compaction_detail_for_app(app, self.locale);
870 let (anchors_detail, anchors_tokens) = anchors_detail_for_app(app, self.locale);
871 self.rows = vec![
872 ContextBucket {
873 label: tr(self.locale, MessageId::CtxInspRowSystemPrompt).into_owned(),
874 tokens: system_tokens,
875 percent: (system_tokens as f64 / max_f) * 100.0,
876 detail: full_detail.clone(),
877 },
878 ContextBucket {
879 label: tr(self.locale, MessageId::CtxInspRowMessages).into_owned(),
880 tokens: message_tokens,
881 percent: (message_tokens as f64 / max_f) * 100.0,
882 detail: full_detail,
883 },
884 ContextBucket {
885 label: tr(self.locale, MessageId::CtxInspRowFree).into_owned(),
886 tokens: free_tokens,
887 percent: (free_tokens as f64 / max_f) * 100.0,
888 detail: if self.auto_compact {
889 tr(self.locale, MessageId::CtxInspFreeTokensDetail)
890 .replace("{free}", &free_tokens.to_string())
891 .replace("{threshold}", &format!("{:.0}", self.threshold))
892 } else {
893 format!(
894 "{}: {free_tokens} {} · {}: {}",
895 tr(self.locale, MessageId::CtxInspRowFree),
896 tr(self.locale, MessageId::CtxInspTokens),
897 tr(self.locale, MessageId::ConfigLabelAutoCompact),
898 tr(self.locale, MessageId::SubagentsValueOff),
899 )
900 },
901 },
902 ContextBucket {
903 label: tr(self.locale, MessageId::CtxInspRowCompaction).into_owned(),
904 tokens: compaction_tokens,
905 percent: (compaction_tokens as f64 / max_f) * 100.0,
906 detail: compaction_detail,
907 },
908 ContextBucket {
909 label: tr(self.locale, MessageId::CtxInspRowAnchors).into_owned(),
910 tokens: anchors_tokens,
911 percent: (anchors_tokens as f64 / max_f) * 100.0,
912 detail: anchors_detail,
913 },
914 ];
915 self.selected = self.selected.min(self.rows.len().saturating_sub(1));
916 }
917
918 #[cfg(test)]
919 fn row_labels(&self) -> Vec<String> {
920 self.rows.iter().map(|row| row.label.clone()).collect()
921 }
922
923 fn move_selection(&mut self, delta: isize) {
924 if self.rows.is_empty() {
925 return;
926 }
927 self.selected = if delta.is_negative() {
928 self.selected.saturating_sub(delta.unsigned_abs())
929 } else {
930 (self.selected + delta as usize).min(self.rows.len() - 1)
931 };
932 }
933
934 fn open_selected(&self) -> ViewAction {
935 let Some(row) = self.rows.get(self.selected) else {
936 return ViewAction::None;
937 };
938 ViewAction::Emit(ViewEvent::OpenTextPager {
939 title: tr(self.locale, MessageId::CtxInspDrillTitle).replace("{row}", &row.label),
940 content: row.detail.clone(),
941 })
942 }
943 }
944
945 impl ModalView for ContextInspectorView {
946 fn kind(&self) -> ModalKind {
947 ModalKind::ContextInspector
948 }
949
950 fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
951 self
952 }
953
954 fn handle_key(&mut self, key: KeyEvent) -> ViewAction {
955 match key.code {
956 KeyCode::Esc | KeyCode::Char('q') => ViewAction::Close,
957 KeyCode::Up | KeyCode::Char('k') => {
958 self.move_selection(-1);
959 ViewAction::None
960 }
961 KeyCode::Down | KeyCode::Char('j') => {
962 self.move_selection(1);
963 ViewAction::None
964 }
965 KeyCode::Enter => self.open_selected(),
966 _ => ViewAction::None,
967 }
968 }
969
970 fn handle_mouse(&mut self, mouse: MouseEvent) -> ViewAction {
971 match mouse.kind {
972 MouseEventKind::ScrollUp => {
973 self.move_selection(-1);
974 ViewAction::None
975 }
976 MouseEventKind::ScrollDown => {
977 self.move_selection(1);
978 ViewAction::None
979 }
980 MouseEventKind::Down(MouseButton::Left) => {
981 let hit = self
982 .hitboxes
983 .borrow()
984 .iter()
985 .find_map(|(y, idx)| (*y == mouse.row).then_some(*idx));
986 let Some(idx) = hit else {
987 return ViewAction::None;
988 };
989 if idx == self.selected {
990 self.open_selected()
991 } else {
992 self.selected = idx;
993 ViewAction::None
994 }
995 }
996 _ => ViewAction::None,
997 }
998 }
999
1000 fn render(&self, area: Rect, buf: &mut Buffer) {
1001 let inner = render_rounded_surface(
1002 area,
1003 buf,
1004 tr(self.locale, MessageId::CtxInspSurfaceTitle),
1005 Some(format!("{:.1}%", self.percent)),
1006 false,
1007 );
1008 let content = render_rounded_footer(
1009 inner,
1010 buf,
1011 &[
1012 ActionHint::new("↑/↓", tr(self.locale, MessageId::CtxInspActionSelect)),
1013 ActionHint::new("Enter", tr(self.locale, MessageId::CtxInspActionDrillDown)),
1014 ActionHint::new("Esc", tr(self.locale, MessageId::CtxInspActionClose)),
1015 ],
1016 );
1017 let width = usize::from(content.width);
1018 let ascii = crate::tui::color_compat::ascii_safe_enabled();
1019 let source_label = context_window_source_label(self.window_source, self.locale);
1020 let source_style = if self.window_source.is_verified() {
1021 Style::default().fg(palette::TEXT_MUTED)
1022 } else {
1023 Style::default().fg(palette::STATUS_WARNING)
1024 };
1025 let mut lines = vec![
1026 Line::from(vec![
1027 Span::styled(
1028 tr(self.locale, MessageId::CtxInspUsedTokens)
1029 .replace("{used}", &self.used.to_string())
1030 .replace("{max}", &self.max.to_string()),
1031 Style::default()
1032 .fg(palette::WHALE_ACTION)
1033 .add_modifier(Modifier::BOLD),
1034 ),
1035 Span::styled(
1036 format!(" · {:.1}% · {} · ", self.percent, self.model),
1037 Style::default().fg(palette::TEXT_MUTED),
1038 ),
1039 Span::styled(source_label.into_owned(), source_style),
1040 ]),
1041 Line::from(Span::styled(
1042 crate::tui::workspace_context::truncate_left(&self.workspace, width),
1043 Style::default().fg(palette::TEXT_MUTED),
1044 )),
1045 Line::from(Span::styled(
1046 self.restored_window.as_deref().unwrap_or_default(),
1047 Style::default().fg(palette::TEXT_MUTED),
1048 )),
1049 ];
1050
1051 let mut meter_row_y: Option<u16> = None;
1052 if content.height >= 11 && content.width >= 24 {
1053 meter_row_y = Some(
1054 content
1055 .y
1056 .saturating_add(u16::try_from(lines.len()).unwrap_or(u16::MAX)),
1057 );
1058 lines.push(Line::default());
1059 lines.push(if self.auto_compact {
1060 let base = tr(self.locale, MessageId::CtxInspAutoCompactAt)
1061 .replace("{threshold}", &format!("{:.0}", self.threshold));
1062 if self.used >= self.compact_threshold_tokens {
1063 Line::from(vec![
1064 Span::styled(base, Style::default().fg(palette::TEXT_MUTED)),
1065 Span::styled(
1066 " · threshold reached",
1067 Style::default().fg(palette::STATUS_WARNING),
1068 ),
1069 ])
1070 } else {
1071 let headroom = self.compact_threshold_tokens.saturating_sub(self.used);
1072 Line::from(Span::styled(
1073 format!("{base} · {headroom} tokens headroom"),
1074 Style::default().fg(palette::TEXT_MUTED),
1075 ))
1076 }
1077 } else {
1078 Line::from(Span::styled(
1079 format!(
1080 "{}: {}",
1081 tr(self.locale, MessageId::ConfigLabelAutoCompact),
1082 tr(self.locale, MessageId::SubagentsValueOff),
1083 ),
1084 Style::default().fg(palette::TEXT_MUTED),
1085 ))
1086 });
1087 lines.push(Line::from(Span::styled(
1088 if ascii { "-" } else { "─" }.repeat(width),
1089 Style::default().fg(palette::BORDER_COLOR),
1090 )));
1091 }
1092
1093 self.hitboxes.borrow_mut().clear();
1094 for (idx, row) in self.rows.iter().enumerate() {
1095 let selected = idx == self.selected;
1096 let marker = codewhale_tui_kit::glyphs::selection_marker(selected);
1097 let value = tr(self.locale, MessageId::CtxInspRowTokens)
1098 .replace("{tokens}", &row.tokens.to_string())
1099 .replace("{percent}", &format!("{:.1}", row.percent));
1100 let value_width = codewhale_tui_kit::ui_text::text_display_width(&value);
1101 let label_width = width.saturating_sub(value_width + 5);
1102 let label = codewhale_tui_kit::ui_text::semantic_truncate(&row.label, label_width);
1103 let gap = width.saturating_sub(
1104 codewhale_tui_kit::ui_text::text_display_width(&label) + value_width + 3,
1105 );
1106 let y = content
1107 .y
1108 .saturating_add(u16::try_from(lines.len()).unwrap_or(u16::MAX));
1109 self.hitboxes.borrow_mut().push((y, idx));
1110 if selected {
1111 let sel = menu_style::selected_row_style();
1112 lines.push(pad_selected_line(
1113 Line::from(Span::styled(
1114 format!("{marker} {label}{}{value}", " ".repeat(gap)),
1115 sel,
1116 )),
1117 width,
1118 sel,
1119 ));
1120 } else {
1121 lines.push(Line::from(vec![
1122 Span::styled(
1123 format!("{marker} {label}"),
1124 Style::default().fg(palette::TEXT_PRIMARY),
1125 ),
1126 Span::raw(" ".repeat(gap)),
1127 Span::styled(value, Style::default().fg(palette::TEXT_MUTED)),
1128 ]));
1129 }
1130 }
1131 Paragraph::new(lines).render(content, buf);
1132
1133 if let Some(y) = meter_row_y
1134 && self.rows.len() >= 2
1135 {
1136 use codewhale_ratatui::{
1137 Caps, MeterSegment, Paint, Role, SegmentedMeter, Theme, color::ColorDepth,
1138 detect::Appearance,
1139 };
1140 let no_color = std::env::var_os("NO_COLOR").is_some_and(|v| !v.is_empty());
1141 let meter_ascii = ascii || no_color;
1142 let caps = Caps {
1143 depth: if no_color {
1144 ColorDepth::Monochrome
1145 } else if meter_ascii {
1146 ColorDepth::Ansi16
1147 } else {
1148 ColorDepth::TrueColor
1149 },
1150 ascii: meter_ascii,
1151 appearance: Appearance::Dark,
1152 };
1153 let theme = Theme::new(caps);
1154 let segments = [
1155 MeterSegment::new(
1156 self.rows[0].label.as_str(),
1157 self.rows[0].percent,
1158 Role::Accent,
1159 ),
1160 MeterSegment::new(
1161 self.rows[1].label.as_str(),
1162 self.rows[1].percent,
1163 Role::Live,
1164 ),
1165 ];
1166 let mut meter = SegmentedMeter::new(&segments, 100.0);
1167 if self.auto_compact {
1168 meter = meter.threshold((self.threshold / 100.0) as f32);
1169 }
1170 let meter_rect = Rect::new(content.x, y, content.width.min(68), 1);
1171 meter.paint(meter_rect, buf, &theme);
1172 }
1173 }
1174 }
1175
1176 #[cfg(test)]
1177 mod tests {
1178 use super::*;
1179 use codewhale_models::Role;
1180 use codewhale_runtime::config::Config;
1181
1182 #[test]
1183 fn short_tool_id_never_panics_on_multibyte() {
1184 // ASCII short/long behave as before.
1185 assert_eq!(short_tool_id("abc"), "abc");
1186 assert_eq!(short_tool_id("0123456789"), "01234567...");
1187 // A multibyte id must truncate on a char boundary, not panic.
1188 // 10 chars → first 8 kept, then the ellipsis.
1189 assert_eq!(short_tool_id("日本語のツールid名"), "日本語のツールi...");
1190 assert_eq!(short_tool_id("café"), "café");
1191 }
1192
1193 use crate::tui::app::TuiOptions;
1194 use crate::tui::history::HistoryCell;
1195 use codewhale_core::{ContextReference, ContextReferenceKind, ContextReferenceSource};
1196 use codewhale_engine::mcp::{McpDiscoveredItem, McpManagerSnapshot, McpServerSnapshot};
1197 use codewhale_engine::session_manager::SessionContextReference;
1198 use codewhale_models::{ContentBlock, Message, Tool};
1199 use std::path::PathBuf;
1200
1201 use codewhale_localization::Locale;
1202
1203 #[test]
1204 fn reference_overflow_counts_only_distinct_references() {
1205 let reference = |label: String| SessionContextReference {
1206 message_index: 0,
1207 reference: ContextReference {
1208 kind: ContextReferenceKind::File,
1209 source: ContextReferenceSource::AtMention,
1210 badge: "file".to_string(),
1211 target: format!("/tmp/project/{label}"),
1212 label,
1213 included: true,
1214 expanded: true,
1215 detail: None,
1216 },
1217 };
1218 let mut references: Vec<_> = (0..MAX_REFERENCE_ROWS + 1)
1219 .map(|index| reference(format!("f{index}.rs")))
1220 .collect();
1221 references.insert(1, reference("f0.rs".to_string()));
1222 let mut out = String::new();
1223 push_references(&mut out, &references, Locale::En);
1224 assert!(out.contains("- ... 1 "), "{out}");
1225 }
1226
1227 fn test_app() -> App {
1228 let mut app = App::new(
1229 TuiOptions {
1230 model: "unknown-model".to_string(),
1231 skills_dir: PathBuf::from("/tmp/skills"),
1232 ..crate::tui::test_support::test_tui_options(PathBuf::from("/tmp/project"))
1233 },
1234 &Config::default(),
1235 );
1236 // Pin the route identity: App::new consults the developer's real
1237 // saved settings, so on a machine with customized provider/model
1238 // the context-window assertions computed against a different route.
1239 app.api_provider = codewhale_config::ProviderKind::Deepseek;
1240 app.auto_model = false;
1241 app.last_effective_model = None;
1242 app.active_route_limits = None;
1243 app.active_context_window_override = None;
1244 app
1245 }
1246
1247 #[test]
1248 fn inspector_reports_the_provider_cache_hit_rate() {
1249 let mut app = test_app();
1250 for (input, hit) in [(1_000u32, 800u32), (1_000, 500)] {
1251 app.session
1252 .turn_cache_history
1253 .push_back(crate::tui::app::TurnCacheRecord {
1254 provider: None,
1255 provider_identity: None,
1256 model: None,
1257 auto_model: false,
1258 input_tokens: input,
1259 output_tokens: 0,
1260 cache_hit_tokens: Some(hit),
1261 cache_miss_tokens: None,
1262 reasoning_replay_tokens: None,
1263 cache_write_tokens: None,
1264 reasoning_tokens: None,
1265 cost_audit: None,
1266 recorded_at: std::time::Instant::now(),
1267 });
1268 }
1269 let text = build_context_inspector_text(&app, Locale::En);
1270 assert!(
1271 text.contains("Provider cache hit rate: 65.0% over 2 cache-aware turns"),
1272 "{text}"
1273 );
1274
1275 let empty = build_context_inspector_text(&test_app(), Locale::En);
1276 assert!(empty.contains("no cache telemetry yet"), "{empty}");
1277 }
1278
1279 #[test]
1280 fn inspector_formats_empty_state() {
1281 let app = test_app();
1282 let text = build_context_inspector_text(&app, Locale::En);
1283 assert!(text.contains("Session Context"));
1284 assert!(text.contains("No file, folder, or media references yet."));
1285 assert!(text.contains("No tool activity yet."));
1286 }
1287
1288 fn schema_tool(name: &str, property_count: usize) -> Tool {
1289 let properties = (0..property_count)
1290 .map(|index| {
1291 (
1292 format!("field_{index}"),
1293 serde_json::json!({"type": "string"}),
1294 )
1295 })
1296 .collect::<serde_json::Map<_, _>>();
1297 Tool {
1298 tool_type: Some("function".to_string()),
1299 name: name.to_string(),
1300 description: format!("schema for {name}"),
1301 input_schema: serde_json::json!({
1302 "type": "object",
1303 "properties": properties,
1304 }),
1305 allowed_callers: None,
1306 defer_loading: None,
1307 input_examples: None,
1308 strict: None,
1309 cache_control: None,
1310 }
1311 }
1312
1313 #[test]
1314 fn inspector_reports_catalog_and_mcp_schema_costs_with_bounded_rows() {
1315 let mut app = test_app();
1316 let mut catalog = (0..(MAX_SCHEMA_COST_ROWS + 2))
1317 .map(|index| schema_tool(&format!("tool_{index}"), index + 1))
1318 .collect::<Vec<_>>();
1319 catalog.push(schema_tool("mcp_local_echo", 3));
1320 app.session.last_tool_catalog = Some(catalog);
1321 app.mcp_snapshot = Some(McpManagerSnapshot {
1322 config_path: PathBuf::from("/tmp/mcp.json"),
1323 config_exists: true,
1324 reload_required: false,
1325 servers: vec![
1326 McpServerSnapshot {
1327 name: "local".to_string(),
1328 enabled: true,
1329 required: false,
1330 transport: "stdio".to_string(),
1331 command_or_url: "echo".to_string(),
1332 connect_timeout: 1,
1333 execute_timeout: 1,
1334 read_timeout: 1,
1335 connected: true,
1336 error: None,
1337 auth_required: false,
1338 capability_metadata: Default::default(),
1339 tools: vec![McpDiscoveredItem {
1340 name: "echo".to_string(),
1341 model_name: "mcp_local_echo".to_string(),
1342 description: Some("echoes input".to_string()),
1343 }],
1344 resources: Vec::new(),
1345 prompts: Vec::new(),
1346 },
1347 McpServerSnapshot {
1348 name: "empty".to_string(),
1349 enabled: true,
1350 required: false,
1351 transport: "stdio".to_string(),
1352 command_or_url: "empty".to_string(),
1353 connect_timeout: 1,
1354 execute_timeout: 1,
1355 read_timeout: 1,
1356 connected: true,
1357 error: None,
1358 auth_required: false,
1359 capability_metadata: Default::default(),
1360 tools: Vec::new(),
1361 resources: Vec::new(),
1362 prompts: Vec::new(),
1363 },
1364 ],
1365 });
1366
1367 let text = build_context_inspector_text(&app, Locale::En);
1368 assert_eq!(
1369 text.matches("Recent Tools").count(),
1370 1,
1371 "schema costs need a distinct section heading: {text}"
1372 );
1373 assert!(
1374 text.contains("\n\nTool schema costs (tokens)\n------------"),
1375 "schema costs need a separated localized section: {text}"
1376 );
1377 assert!(text.contains("[catalog]"), "catalog total missing: {text}");
1378 assert!(text.contains("tool_25"), "catalog row missing: {text}");
1379 assert!(
1380 text.contains("more catalog tools"),
1381 "catalog bound missing: {text}"
1382 );
1383 assert!(
1384 text.contains("[mcp:local]"),
1385 "MCP server row missing: {text}"
1386 );
1387 assert!(
1388 text.contains("1/1 announced tools"),
1389 "MCP tool cost missing: {text}"
1390 );
1391 assert!(
1392 text.contains("[mcp:empty] ~0"),
1393 "empty MCP row missing: {text}"
1394 );
1395 }
1396
1397 #[test]
1398 fn inspector_uses_compact_session_id() {
1399 let mut app = test_app();
1400 app.current_session_id = Some("1234567890abcdef".to_string());
1401
1402 let text = build_context_inspector_text(&app, Locale::En);
1403
1404 assert!(text.contains("Session: 12345678"), "{text}");
1405 assert!(!text.contains("1234567890abcdef"), "{text}");
1406 }
1407
1408 #[test]
1409 fn inspector_lists_context_references() {
1410 let mut app = test_app();
1411 app.history.push(HistoryCell::User {
1412 content: "read @src/main.rs".to_string(),
1413 });
1414 app.session_context_references
1415 .push(SessionContextReference {
1416 message_index: 0,
1417 reference: ContextReference {
1418 kind: ContextReferenceKind::File,
1419 source: ContextReferenceSource::AtMention,
1420 badge: "file".to_string(),
1421 label: "src/main.rs".to_string(),
1422 target: "/tmp/project/src/main.rs".to_string(),
1423 included: true,
1424 expanded: true,
1425 detail: Some("included".to_string()),
1426 },
1427 });
1428
1429 let text = build_context_inspector_text(&app, Locale::En);
1430 assert!(text.contains("[file] @src/main.rs -> /tmp/project/src/main.rs"));
1431 }
1432
1433 #[test]
1434 fn inspector_marks_high_context_pressure() {
1435 let mut app = test_app();
1436 app.api_messages_mut().push(Message {
1437 role: Role::User,
1438 content: vec![ContentBlock::Text {
1439 text: "x".repeat(4_000_000),
1440 cache_control: None,
1441 }],
1442 });
1443
1444 let text = build_context_inspector_text(&app, Locale::En);
1445 assert!(text.contains("Context: critical"), "{text}");
1446 }
1447
1448 #[test]
1449 fn inspector_uses_effective_auto_model_context_window() {
1450 let mut app = test_app();
1451 app.model = "auto".to_string();
1452 app.auto_model = true;
1453 app.last_effective_model = Some("deepseek-v4-pro".to_string());
1454 app.last_effective_provider = Some(codewhale_config::ProviderKind::Deepseek);
1455 app.last_effective_provider_identity = Some("deepseek".into());
1456 app.last_effective_budget = Some(crate::tui::app::AutoRouteBudget {
1457 provider: codewhale_config::ProviderKind::Deepseek,
1458 provider_identity: "deepseek".into(),
1459 model: "deepseek-v4-pro".into(),
1460 limits: None,
1461 window: codewhale_engine::route_runtime::ContextWindowResolution {
1462 tokens: 1_000_000,
1463 source: codewhale_engine::route_runtime::ContextWindowSource::Catalog,
1464 },
1465 restored: false,
1466 });
1467
1468 let text = build_context_inspector_text(&app, Locale::En);
1469 assert!(text.contains("Model: auto"), "{text}");
1470 assert!(text.contains("/1000000 tokens"), "{text}");
1471 }
1472
1473 #[test]
1474 fn inspector_no_system_prompt_shows_section() {
1475 let app = test_app();
1476 let text = build_context_inspector_text(&app, Locale::En);
1477 assert!(text.contains("System Prompt Structure"));
1478 assert!(text.contains("No system prompt set."));
1479 }
1480
1481 #[test]
1482 fn inspector_blocks_format_shows_stable_prefix_and_working_set() {
1483 let mut app = test_app();
1484 use codewhale_models::SystemBlock;
1485 app.system_prompt = Some(SystemPrompt::Blocks(vec![
1486 SystemBlock {
1487 block_type: "text".to_string(),
1488 text: "## Stable Base\n\nYou are CodeWhale.".to_string(),
1489 cache_control: None,
1490 },
1491 SystemBlock {
1492 block_type: "text".to_string(),
1493 text: format!("{WORKING_SET_MARKER}\nsrc/main.rs changed"),
1494 cache_control: None,
1495 },
1496 ]));
1497
1498 let text = build_context_inspector_text(&app, Locale::En);
1499 assert!(text.contains("System Prompt Structure"));
1500 assert!(
1501 text.contains("Stable prefix: 1 block"),
1502 "stable prefix count: {text}"
1503 );
1504 assert!(
1505 text.contains("Volatile working set: 1 block"),
1506 "working set section: {text}"
1507 );
1508 assert!(
1509 text.contains("[cache-friendly]"),
1510 "cache hint for stable: {text}"
1511 );
1512 assert!(
1513 text.contains("[changes by session/turn]"),
1514 "volatile marker: {text}"
1515 );
1516 assert!(
1517 text.contains("First line: ## Repo Working Set"),
1518 "first line of working set: {text}"
1519 );
1520 }
1521
1522 #[test]
1523 fn inspector_blocks_without_working_set_shows_stable_only() {
1524 let mut app = test_app();
1525 use codewhale_models::SystemBlock;
1526 app.system_prompt = Some(SystemPrompt::Blocks(vec![
1527 SystemBlock {
1528 block_type: "text".to_string(),
1529 text: "## Stable Base".to_string(),
1530 cache_control: None,
1531 },
1532 SystemBlock {
1533 block_type: "text".to_string(),
1534 text: "## Personality\nCalm".to_string(),
1535 cache_control: None,
1536 },
1537 ]));
1538
1539 let text = build_context_inspector_text(&app, Locale::En);
1540 assert!(text.contains("Stable prefix: 2 block(s)"));
1541 assert!(text.contains("Volatile working set: none"));
1542 }
1543
1544 #[test]
1545 fn inspector_text_prompt_shows_layer_map() {
1546 let mut app = test_app();
1547 app.system_prompt = Some(SystemPrompt::Text(
1548 "## Codewhale\nBundled base law.\n\n## Language\nUse English.\n\n## Output Formatting\nBe clear.\n\n<codewhale_repo_constitution>\nRepo law\n</codewhale_repo_constitution>\n\n<project_instructions source=\"AGENTS.md\">\nRules\n</project_instructions>\n\n## Project Context Pack\n{}\n\n## Environment\n- lang: en\n\n## Skills\n- rust\n\n## Core Execution\nInspect, edit, verify.\n\n## Compact\nTemplate\n\n## Repo Working Set\nsrc/".to_string(),
1549 ));
1550
1551 let text = build_context_inspector_text(&app, Locale::En);
1552 assert!(text.contains("System Prompt Structure"));
1553 assert!(text.contains("Text prompt layers"));
1554 assert!(text.contains("Bundled constitution"));
1555 assert!(text.contains("Language policy"));
1556 assert!(text.contains("Output formatting"));
1557 assert!(text.contains("Repository constitution"));
1558 assert!(text.contains("Project context"));
1559 assert!(text.contains("Project context pack"));
1560 assert!(text.contains("Environment"));
1561 assert!(text.contains("Skills"));
1562 assert!(text.contains("Core execution"));
1563 assert!(text.contains("Compact template"));
1564 assert!(text.contains("Volatile working set"));
1565 assert!(text.contains("changes by session/turn"));
1566 }
1567
1568 #[test]
1569 fn inspector_text_prompt_without_markers_shows_single_blob() {
1570 let mut app = test_app();
1571 app.system_prompt = Some(SystemPrompt::Text("You are CodeWhale.".to_string()));
1572
1573 let text = build_context_inspector_text(&app, Locale::En);
1574 assert!(text.contains("Single text blob"));
1575 assert!(text.contains("stable prefix only"));
1576 }
1577
1578 #[test]
1579 fn inspector_localizes_to_zh_hans() {
1580 use codewhale_models::SystemBlock;
1581 let mut app = test_app();
1582 app.system_prompt = Some(SystemPrompt::Blocks(vec![
1583 SystemBlock {
1584 block_type: "text".to_string(),
1585 text: "## Base\nYou are CodeWhale.".to_string(),
1586 cache_control: None,
1587 },
1588 SystemBlock {
1589 block_type: "text".to_string(),
1590 text: format!("{WORKING_SET_MARKER}\nsrc/main.rs changed"),
1591 cache_control: None,
1592 },
1593 ]));
1594 let text = build_context_inspector_text(&app, Locale::ZhHans);
1595
1596 // Positive: key ZhHans labels present
1597 assert!(text.contains("会话上下文"), "session header: {text}");
1598 assert!(text.contains("模型"), "model label: {text}");
1599 assert!(text.contains("工作区"), "workspace: {text}");
1600 assert!(text.contains("系统提示结构"), "sysprompt section: {text}");
1601 assert!(text.contains("稳定前缀"), "stable prefix: {text}");
1602 assert!(text.contains("易变工作集"), "volatile ws: {text}");
1603 assert!(text.contains("第一行"), "first line: {text}");
1604 assert!(text.contains("总计"), "total line: {text}");
1605 assert!(text.contains("引用"), "references: {text}");
1606 assert!(text.contains("最近使用的工具"), "tools: {text}");
1607 assert!(text.contains("个区块"), "blocks unit: {text}");
1608 assert!(text.contains("个 token"), "tokens unit: {text}");
1609 assert!(text.contains("缓存友好"), "cache-friendly: {text}");
1610 assert!(text.contains("提示"), "cache tip: {text}");
1611
1612 // Negative: no English labels leak
1613 assert!(!text.contains("Session Context"), "EN session leaked");
1614 assert!(!text.contains("Model:"), "EN model leaked");
1615 assert!(!text.contains("cells"), "EN cells leaked");
1616 assert!(!text.contains("API messages"), "EN API msgs leaked");
1617 assert!(!text.contains("Stable prefix"), "EN stable prefix leaked");
1618 assert!(
1619 !text.contains("Volatile working set"),
1620 "EN volatile ws leaked"
1621 );
1622 assert!(!text.contains("First line"), "EN first line leaked");
1623 assert!(!text.contains("Total:"), "EN total leaked");
1624 assert!(!text.contains("Text prompt layers"), "EN layers leaked");
1625 assert!(!text.contains("cache-friendly"), "EN cache-friendly leaked");
1626 assert!(!text.contains("more reference"), "EN more refs leaked");
1627 assert!(!text.contains("no output yet"), "EN no output leaked");
1628 assert!(text.contains("压缩"), "compaction row: {text}");
1629 assert!(text.contains("锚点"), "anchors row: {text}");
1630 }
1631
1632 #[test]
1633 fn inspector_meter_matches_compaction_pressure_signal() {
1634 let mut app = test_app();
1635 app.api_messages_mut().push(Message {
1636 role: Role::User,
1637 content: vec![ContentBlock::Text {
1638 text: "x".repeat(4_000),
1639 cache_control: None,
1640 }],
1641 });
1642 app.last_billed_input_tokens = Some(12_000);
1643 let estimated =
1644 estimate_input_tokens_for_pressure(&app.api_messages, app.system_prompt.as_ref());
1645 let (used, _, _) = context_usage(&app);
1646 assert_eq!(used, estimated.max(12_000));
1647 app.last_billed_input_tokens = None;
1648 let (estimated_only, _, _) = context_usage(&app);
1649 assert_eq!(estimated_only, estimated);
1650 assert_ne!(
1651 estimated_only,
1652 codewhale_engine::compaction::estimate_input_tokens_conservative(
1653 &app.api_messages,
1654 app.system_prompt.as_ref()
1655 )
1656 );
1657 }
1658
1659 #[test]
1660 fn inspector_rows_name_compaction_and_anchors() {
1661 let mut app = test_app();
1662 app.last_compaction = Some(codewhale_engine::compaction::LastCompactionSnapshot {
1663 auto: true,
1664 coverage: codewhale_engine::compaction::CompactionCoverage {
1665 path: codewhale_engine::compaction::CompactionPath::Summary,
1666 last_round_messages: 4,
1667 last_round_tool_results: 1,
1668 last_round_assistant: true,
1669 dropped_messages: 12,
1670 anchors_chars: 0,
1671 retained_user_message_tokens: 20_000,
1672 operator_instructions_applied: false,
1673 },
1674 messages_before: 16,
1675 messages_after: 4,
1676 });
1677 let text = build_context_inspector_text(&app, Locale::En);
1678 assert!(text.contains("making room"), "{text}");
1679 assert!(text.contains("16 → 4 messages"), "{text}");
1680 let view = ContextInspectorView::new(&app);
1681 assert!(view.row_labels().iter().any(|label| label == "making room"));
1682 assert!(view.row_labels().iter().any(|label| label == "anchors"));
1683 let (_, max, _) = context_usage(&app);
1684 app.auto_compact = true;
1685 app.auto_compact_threshold_percent = 80.0;
1686 app.compact_threshold = (max / 2) as usize;
1687 let mut view = ContextInspectorView::new(&app);
1688 assert!((view.threshold - 50.0).abs() < 0.01);
1689 assert!(view.rows[2].detail.contains("Makes room at 50%"));
1690 let area = Rect::new(0, 0, 100, 24);
1691 let mut buffer = Buffer::empty(area);
1692 view.render(area, &mut buffer);
1693 let rendered: String = buffer.content().iter().map(|cell| cell.symbol()).collect();
1694 assert!(rendered.contains("makes room at 50%"), "{rendered}");
1695 app.compact_threshold = 0;
1696 view.refresh_from_app(&app);
1697 assert_eq!(view.threshold, 0.0);
1698 assert!(view.rows[2].detail.contains("Makes room at 0%"));
1699 app.auto_compact = false;
1700 view.refresh_from_app(&app);
1701 assert!(view.rows[2].detail.contains("Auto compact: off"));
1702 assert!(!view.rows[2].detail.contains("Makes room at"));
1703 let mut buffer = Buffer::empty(area);
1704 view.render(area, &mut buffer);
1705 let rendered: String = buffer.content().iter().map(|cell| cell.symbol()).collect();
1706 assert!(rendered.contains("Auto compact: off"), "{rendered}");
1707 assert!(!rendered.contains("makes room at"), "{rendered}");
1708 }
1709
1710 #[test]
1711 fn push_tools_keeps_details_hint_when_active_tools_fill_cap() {
1712 let mut app = test_app();
1713 for index in 0..=MAX_TOOL_ROWS {
1714 let tool_id = format!("tool-{index}");
1715 app.active_tool_details.insert(
1716 tool_id.clone(),
1717 ToolDetailRecord {
1718 tool_id,
1719 tool_name: format!("read_file_{index}"),
1720 input: serde_json::json!({}),
1721 output: None,
1722 },
1723 );
1724 }
1725 let mut out = String::new();
1726 push_tools(&mut out, &app, Locale::En);
1727 let details = crate::tui::shell_key_routing::display_chord(
1728 crate::tui::shell_key_routing::binding(
1729 crate::tui::shell_key_routing::ShellBindingId::ToolDetails,
1730 )
1731 .footer_chord,
1732 );
1733 let expected_hint =
1734 tr(Locale::En, MessageId::CtxInspVHint).replace("{details}", details.as_ref());
1735 assert!(out.contains(&expected_hint), "{out}");
1736 }
1737
1738 #[test]
1739 fn chatgpt_models_contract_propagates_verified_context_and_surfaces_unverified_fallback() {
1740 let _lock = codewhale_engine::test_support::lock_test_env();
1741 let home = tempfile::tempdir().expect("tempdir");
1742 let root = home.path().canonicalize().expect("canonical tempdir");
1743 let _home = codewhale_engine::test_support::EnvVarGuard::set("CODEWHALE_HOME", &root);
1744
1745 let parsed = codewhale_engine::client::parse_models_response_for_provider(
1746 r#"{"models":[
1747 {
1748 "slug":"gpt-6.2-sol",
1749 "display_name":"GPT-6.2-Sol",
1750 "visibility":"list",
1751 "context_window":500000,
1752 "max_context_window":872000,
1753 "effective_context_window_percent":95,
1754 "supported_reasoning_levels":[
1755 {"effort":"low","description":"Fast"},
1756 {"effort":"medium","description":"Balanced"},
1757 {"effort":"high","description":"Deep"},
1758 {"effort":"xhigh","description":"Extra"},
1759 {"effort":"max","description":"Max"},
1760 {"effort":"ultra","description":"Ultra"}
1761 ]
1762 },
1763 {
1764 "slug":"gpt-missing-window",
1765 "display_name":"GPT Missing Window",
1766 "visibility":"list"
1767 },
1768 {
1769 "slug":"gpt-zero-window",
1770 "display_name":"GPT Zero Window",
1771 "visibility":"list",
1772 "context_window":0
1773 },
1774 {
1775 "slug":"gpt-oversize-window",
1776 "display_name":"GPT Oversize Window",
1777 "visibility":"list",
1778 "context_window":99000000
1779 }
1780 ]}"#,
1781 codewhale_config::ProviderKind::OpenaiCodex,
1782 )
1783 .expect("parse ChatGPT models");
1784
1785 let metadata: Vec<_> = parsed
1786 .into_iter()
1787 .map(
1788 |model| codewhale_runtime::codex_model_roster::CodexModelMetadata {
1789 id: model.id,
1790 display_name: model.display_name,
1791 context_window: model.context_window,
1792 reasoning: model.reasoning,
1793 efforts: model.efforts,
1794 },
1795 )
1796 .collect();
1797 assert_eq!(metadata[0].context_window, Some(500_000));
1798 assert_eq!(
1799 metadata[0].efforts,
1800 vec!["low", "medium", "high", "xhigh", "max", "ultra"]
1801 );
1802 assert_eq!(metadata[1].context_window, None);
1803 assert_eq!(metadata[2].context_window, None);
1804 assert_eq!(metadata[3].context_window, None);
1805
1806 let mut config = Config::default();
1807 config.provider = Some(codewhale_config::ProviderKind::OpenaiCodex.as_str().into());
1808 codewhale_runtime::oauth::install_test_chatgpt_registration(&mut config)
1809 .expect("test ChatGPT grant");
1810 codewhale_runtime::codex_model_roster::install_test_chatgpt_roster_with_metadata(
1811 &config, metadata,
1812 )
1813 .expect("install roster");
1814
1815 let roster = codewhale_engine::codex_model_cache::model_roster_for(&config);
1816 assert_eq!(
1817 roster.metadata_for("gpt-6.2-sol").unwrap().efforts,
1818 vec!["low", "medium", "high", "xhigh", "max", "ultra"]
1819 );
1820
1821 let sol_route = codewhale_engine::route_runtime::resolve_runtime_route(
1822 &config,
1823 codewhale_config::ProviderKind::OpenaiCodex,
1824 Some("gpt-6.2-sol"),
1825 )
1826 .expect("resolve gpt-6.2-sol");
1827 assert_eq!(sol_route.context_window.tokens, 500_000);
1828 assert_eq!(
1829 sol_route.context_window.source,
1830 codewhale_engine::route_runtime::ContextWindowSource::ProviderReported
1831 );
1832 assert!(sol_route.context_window.source.is_verified());
1833
1834 let inventory =
1835 codewhale_engine::model_inventory::ModelInventory::from_config(&config).unwrap();
1836 let sol_candidate = inventory
1837 .candidates
1838 .iter()
1839 .find(|c| c.model == "gpt-6.2-sol")
1840 .unwrap();
1841 assert_eq!(sol_candidate.context_window, 500_000);
1842 assert!(!sol_candidate.context_window_unverified);
1843
1844 let mut app = test_app();
1845 app.api_provider = codewhale_config::ProviderKind::OpenaiCodex;
1846 app.model = "gpt-6.2-sol".to_string();
1847 app.last_billed_input_tokens = Some(20_546);
1848 app.set_active_route_resolution(
1849 sol_route.candidate.endpoint().base_url.clone(),
1850 sol_route.candidate.limits(),
1851 sol_route.context_window,
1852 );
1853 let sol_text = build_context_inspector_text(&app, Locale::En);
1854 assert!(
1855 sol_text.contains("~20546/500000 tokens (4.1% · provider-reported)"),
1856 "{sol_text}"
1857 );
1858 assert!(!sol_text.contains("unverified"), "{sol_text}");
1859 let sol_view = ContextInspectorView::new(&app);
1860 let area = Rect::new(0, 0, 100, 24);
1861 let mut buffer = Buffer::empty(area);
1862 sol_view.render(area, &mut buffer);
1863 let sol_rendered: String = buffer.content().iter().map(|cell| cell.symbol()).collect();
1864 assert!(
1865 sol_rendered.contains("~20546/500000 tokens"),
1866 "{sol_rendered}"
1867 );
1868 assert!(sol_rendered.contains("provider-reported"), "{sol_rendered}");
1869 assert!(!sol_rendered.contains("unverified"), "{sol_rendered}");
1870
1871 for fallback_id in [
1872 "gpt-missing-window",
1873 "gpt-zero-window",
1874 "gpt-oversize-window",
1875 ] {
1876 let fallback_route = codewhale_engine::route_runtime::resolve_runtime_route(
1877 &config,
1878 codewhale_config::ProviderKind::OpenaiCodex,
1879 Some(fallback_id),
1880 )
1881 .expect("resolve fallback ChatGPT route");
1882 assert_eq!(fallback_route.context_window.tokens, 128_000);
1883 assert_eq!(
1884 fallback_route.context_window.source,
1885 codewhale_engine::route_runtime::ContextWindowSource::Fallback
1886 );
1887 assert!(!fallback_route.context_window.source.is_verified());
1888
1889 let candidate = inventory
1890 .candidates
1891 .iter()
1892 .find(|c| c.model == fallback_id)
1893 .unwrap();
1894 assert_eq!(candidate.context_window, 128_000);
1895 assert!(candidate.context_window_unverified);
1896
1897 app.model = fallback_id.to_string();
1898 app.set_active_route_resolution(
1899 fallback_route.candidate.endpoint().base_url.clone(),
1900 fallback_route.candidate.limits(),
1901 fallback_route.context_window,
1902 );
1903 let fb_text = build_context_inspector_text(&app, Locale::En);
1904 assert!(
1905 fb_text.contains("~20546/128000 tokens (16.1% · fallback (unverified))"),
1906 "{fb_text}"
1907 );
1908 let fb_view = ContextInspectorView::new(&app);
1909 let mut fb_buf = Buffer::empty(area);
1910 fb_view.render(area, &mut fb_buf);
1911 let fb_rendered: String = fb_buf.content().iter().map(|cell| cell.symbol()).collect();
1912 assert!(
1913 fb_rendered.contains("~20546/128000 tokens"),
1914 "{fb_rendered}"
1915 );
1916 assert!(
1917 fb_rendered.contains("fallback (unverified)"),
1918 "{fb_rendered}"
1919 );
1920 }
1921 }
1922
1923 #[test]
1924 fn auto_compact_line_shows_exact_headroom_and_threshold_reached() {
1925 let mut app = test_app();
1926 app.auto_compact = true;
1927 app.last_billed_input_tokens = Some(20_000);
1928 app.compact_threshold = 50_000;
1929 let mut view = ContextInspectorView::new(&app);
1930 let area = Rect::new(0, 0, 100, 24);
1931 let mut buffer = Buffer::empty(area);
1932 view.render(area, &mut buffer);
1933 let rendered: String = buffer.content().iter().map(|cell| cell.symbol()).collect();
1934 assert!(rendered.contains("30000 tokens headroom"), "{rendered}");
1935 assert!(!rendered.contains("threshold reached"), "{rendered}");
1936
1937 app.last_billed_input_tokens = Some(50_000);
1938 view.refresh_from_app(&app);
1939 let mut buffer = Buffer::empty(area);
1940 view.render(area, &mut buffer);
1941 let rendered: String = buffer.content().iter().map(|cell| cell.symbol()).collect();
1942 assert!(rendered.contains("threshold reached"), "{rendered}");
1943 assert!(!rendered.contains("tokens headroom"), "{rendered}");
1944 }
1945
1946 #[test]
1947 fn context_inspector_segmented_meter_renders_unicode_eighths_and_threshold_tick() {
1948 let _lock = codewhale_engine::test_support::lock_test_env();
1949 let _no_color = codewhale_engine::test_support::EnvVarGuard::remove("NO_COLOR");
1950 let _ascii = codewhale_engine::test_support::EnvVarGuard::remove("CODEWHALE_ASCII_SAFE");
1951
1952 let mut app = test_app();
1953 app.auto_compact = true;
1954 app.last_billed_input_tokens = Some(37_500);
1955 app.compact_threshold = 80_000;
1956 let view = ContextInspectorView::new(&app);
1957 let area = Rect::new(0, 0, 100, 24);
1958 let mut buffer = Buffer::empty(area);
1959 view.render(area, &mut buffer);
1960 let rendered: String = buffer.content().iter().map(|cell| cell.symbol()).collect();
1961 let has_eighth_block = ['▏', '▎', '▍', '▌', '▋', '▊', '▉', '█']
1962 .into_iter()
1963 .any(|ch| rendered.contains(ch));
1964 assert!(has_eighth_block, "expected eighth-cell meter:\n{rendered}");
1965 assert!(
1966 rendered.contains('▕'),
1967 "expected Unicode threshold tick:\n{rendered}"
1968 );
1969
1970 app.auto_compact = false;
1971 let view_off = ContextInspectorView::new(&app);
1972 let mut buf_off = Buffer::empty(area);
1973 view_off.render(area, &mut buf_off);
1974 let rendered_off: String = buf_off.content().iter().map(|cell| cell.symbol()).collect();
1975 assert!(
1976 !rendered_off.contains('▕'),
1977 "threshold tick should be hidden when auto_compact is off:\n{rendered_off}"
1978 );
1979 }
1980
1981 #[test]
1982 fn context_inspector_segmented_meter_falls_back_to_ascii_under_no_color() {
1983 let _lock = codewhale_engine::test_support::lock_test_env();
1984 let _no_color = codewhale_engine::test_support::EnvVarGuard::set("NO_COLOR", "1");
1985
1986 let mut app = test_app();
1987 app.auto_compact = true;
1988 app.last_billed_input_tokens = Some(45_000);
1989 app.compact_threshold = 80_000;
1990 let view = ContextInspectorView::new(&app);
1991 let area = Rect::new(0, 0, 100, 24);
1992 let mut buffer = Buffer::empty(area);
1993 view.render(area, &mut buffer);
1994 let rendered: String = buffer.content().iter().map(|cell| cell.symbol()).collect();
1995 assert!(
1996 rendered.contains('[') && rendered.contains(']'),
1997 "expected bracketed ASCII meter under NO_COLOR:\n{rendered}"
1998 );
1999 assert!(
2000 rendered.contains('#') || rendered.contains('='),
2001 "expected ASCII fill marks under NO_COLOR:\n{rendered}"
2002 );
2003 assert!(
2004 rendered.contains('|'),
2005 "expected ASCII threshold tick under NO_COLOR:\n{rendered}"
2006 );
2007 assert!(
2008 !rendered.contains('█') && !rendered.contains('▕'),
2009 "ASCII fallback should not emit Unicode meter glyphs:\n{rendered}"
2010 );
2011 }
2012 }
2013
2013 lines RUST