返回 CodeWhale
tests.rs
根目录 / crates / tui / src / tui / infoline / tests.rs
1 //! Golden-buffer contract for the metrics line — the row under the posture
2 //! bar.
3 //!
4 //! Goldens live in `crates/tui/src/tui/goldens/infoline_{screen}_{w}x{h}.txt`
5 //! for the two screens (startup, work) at the blocker sizes. Re-bless by
6 //! deleting the golden and running with `CODEWHALE_BLESS_GOLDENS=1`.
7
8 use ratatui::{Terminal, backend::TestBackend, layout::Rect};
9 use unicode_width::UnicodeWidthStr;
10
11 use super::{InfoLine, InfoSegment, InfoSegmentId, context_meter_hitbox, infoline_hitboxes};
12 use codewhale_palette::{ChromeInk, UI_THEME, UiTheme};
13
14 /// The hint the live shell advertises, from the one binding module that owns
15 /// it — a fixture string here would let chrome and routing drift apart.
16 fn help_hint() -> String {
17 crate::tui::shell_key_routing::info_help_hint(codewhale_localization::Locale::En)
18 }
19
20 const BLOCKER_SIZES: [(u16, u16); 4] = [(80, 24), (100, 30), (120, 32), (160, 40)];
21
22 fn context(pct: u8) -> InfoSegment {
23 InfoSegment::new(
24 InfoSegmentId::Context,
25 "ctx",
26 format!("{pct}%"),
27 if pct >= 80 {
28 ChromeInk::Failure
29 } else {
30 ChromeInk::Info
31 },
32 )
33 }
34
35 /// Approved startup screen: no route yet, no metrics yet.
36 fn startup_segments() -> Vec<InfoSegment> {
37 vec![
38 InfoSegment::new(
39 InfoSegmentId::Model,
40 "",
41 "model not connected",
42 ChromeInk::Waiting,
43 ),
44 context(0),
45 ]
46 }
47
48 /// Approved work screen: model, context, cost, then the session metrics.
49 fn work_segments() -> Vec<InfoSegment> {
50 vec![
51 InfoSegment::new(InfoSegmentId::Model, "", "deepseek-v4", ChromeInk::Identity),
52 context(61),
53 InfoSegment::new(InfoSegmentId::Cost, "", "$0.42", ChromeInk::MetadataValue),
54 InfoSegment::new(
55 InfoSegmentId::Ttft,
56 "ttft",
57 "400ms",
58 ChromeInk::MetadataValue,
59 ),
60 InfoSegment::new(
61 InfoSegmentId::Rate,
62 "",
63 "38 tok/s",
64 ChromeInk::MetadataValue,
65 ),
66 InfoSegment::new(
67 InfoSegmentId::OutputTokens,
68 "↓",
69 "1.2K",
70 ChromeInk::MetadataValue,
71 ),
72 ]
73 }
74
75 fn fixtures() -> Vec<(&'static str, Vec<InfoSegment>)> {
76 vec![("startup", startup_segments()), ("work", work_segments())]
77 }
78
79 fn render_buffer(theme: &UiTheme, width: u16, segments: &[InfoSegment]) -> ratatui::buffer::Buffer {
80 let backend = TestBackend::new(width, 1);
81 let mut terminal = Terminal::new(backend).expect("terminal");
82 let hint = help_hint();
83 terminal
84 .draw(|frame| {
85 let info = InfoLine::new(theme, &hint, segments);
86 use ratatui::widgets::Widget;
87 Widget::render(info, frame.area(), frame.buffer_mut());
88 })
89 .expect("draw");
90 terminal.backend().buffer().clone()
91 }
92
93 fn render_row(theme: &UiTheme, width: u16, segments: &[InfoSegment]) -> String {
94 render_cells(theme, width, segments).concat()
95 }
96
97 /// Per-cell symbols of one rendered row (the golden dump, before joining).
98 fn render_cells(theme: &UiTheme, width: u16, segments: &[InfoSegment]) -> Vec<String> {
99 render_buffer(theme, width, segments)
100 .content()
101 .iter()
102 .map(|cell| cell.symbol().to_string())
103 .collect()
104 }
105
106 fn column_of(row: &str, text: &str) -> u16 {
107 let (prefix, _) = row
108 .split_once(text)
109 .unwrap_or_else(|| panic!("{text:?} missing from {row:?}"));
110 u16::try_from(prefix.width()).unwrap()
111 }
112
113 fn golden_path(name: &str) -> std::path::PathBuf {
114 std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
115 .join("src/tui/goldens")
116 .join(format!("{name}.txt"))
117 }
118
119 fn bless(name: &str, text: &str) {
120 let path = golden_path(name);
121 if let Some(parent) = path.parent() {
122 std::fs::create_dir_all(parent).expect("create goldens dir");
123 }
124 std::fs::write(path, text).expect("write golden");
125 }
126
127 fn golden_text(name: &str) -> Option<String> {
128 // Normalize to LF; a Windows checkout can hand us CRLF while `render_row`
129 // always terminates with LF. Cell symbols never contain CR.
130 std::fs::read_to_string(golden_path(name))
131 .ok()
132 .map(|text| text.replace("\r\n", "\n"))
133 }
134
135 #[test]
136 fn infoline_matches_goldens_at_blocker_sizes() {
137 for (screen, segments) in fixtures() {
138 for (w, h) in BLOCKER_SIZES {
139 let name = format!("infoline_{screen}_{w}x{h}");
140 let rendered = render_row(&UI_THEME, w, &segments);
141 let rendered = format!("{rendered}\n");
142 match golden_text(&name) {
143 Some(expected) => {
144 assert_eq!(
145 rendered, expected,
146 "info-line golden drift at {name}; re-bless only with an approved design change"
147 );
148 }
149 None => {
150 if std::env::var("CODEWHALE_BLESS_GOLDENS").is_ok() {
151 bless(&name, &rendered);
152 } else {
153 panic!(
154 "missing golden {name}; run with CODEWHALE_BLESS_GOLDENS=1 to write it"
155 );
156 }
157 }
158 }
159 }
160 }
161 }
162
163 /// The row states no time of day, carries no wordmark, and no longer names
164 /// the repository or branch: the launch header and the git bottom view own
165 /// those (2026-09-02).
166 #[test]
167 fn infoline_is_model_context_and_metrics_only() {
168 for (_, segments) in fixtures() {
169 for (w, _h) in BLOCKER_SIZES {
170 let row = render_row(&UI_THEME, w, &segments);
171 assert!(
172 !row.contains(':'),
173 "{w}: the metrics line carries no clock: {row:?}"
174 );
175 assert!(
176 !row.contains("CODEWHALE") && !row.contains("codewhale"),
177 "{w}: no wordmark or repository on this row: {row:?}"
178 );
179 assert!(!row.contains('⑂'), "{w}: no branch on this row: {row:?}");
180 }
181 }
182 let work = render_row(&UI_THEME, 160, &work_segments());
183 assert!(
184 work.starts_with("deepseek-v4 │ ctx 61% $0.42 ttft 400ms 38 tok/s ↓ 1.2K "),
185 "{work:?}"
186 );
187 assert!(work.trim_end().ends_with("/help"), "{work:?}");
188 }
189
190 /// Secondary counts and help yield before performance readings and cost. The model and `ctx NN%` are the floor at every width.
191 #[test]
192 fn infoline_sheds_tokens_then_help_then_rate_then_ttft_then_cost() {
193 let segments = work_segments();
194 // The narrowest row that still shows a thing. A thing that sheds earlier
195 // needs a wider row to survive, so these strictly decrease down the
196 // declared order.
197 let narrowest_showing = |needle: &str| -> u16 {
198 (24..=180u16)
199 .filter(|w| render_row(&UI_THEME, *w, &segments).contains(needle))
200 .min()
201 .unwrap_or_else(|| panic!("{needle} never painted at any width"))
202 };
203 let rate = narrowest_showing("tok/s");
204 let ttft = narrowest_showing("ttft");
205 let tokens = narrowest_showing("↓ 1.2K");
206 let help = narrowest_showing("help");
207 let cost = narrowest_showing("$0.42");
208 assert!(
209 tokens > help && help > rate && rate > ttft && ttft > cost,
210 "shed order broke: rate@{rate} ttft@{ttft} tokens@{tokens} help@{help} cost@{cost}"
211 );
212 for w in 24..=180u16 {
213 let row = render_row(&UI_THEME, w, &segments);
214 assert!(
215 row.contains("deepseek-v4") && row.contains("ctx 61%"),
216 "{w}: the model and the context reading never shed: {row:?}"
217 );
218 }
219 }
220
221 /// `tui.metrics_line = "compact"` (#5950) is the row after its first shed
222 /// rungs, at any width: output counts and help are gone before width is
223 /// consulted; selected TTFT/rate survive when they fit. Hitboxes follow the same
224 /// pass so a click still lands on what painted.
225 #[test]
226 fn infoline_compact_keeps_performance_readings_without_extra_rows() {
227 let segments = work_segments();
228 let hint = help_hint();
229 let compact_row = |width: u16| -> (String, Vec<InfoSegmentId>) {
230 let backend = TestBackend::new(width, 1);
231 let mut terminal = Terminal::new(backend).expect("terminal");
232 let mut ids = Vec::new();
233 terminal
234 .draw(|frame| {
235 let info = InfoLine::new(&UI_THEME, &hint, &segments).compact(true);
236 ids = infoline_hitboxes(&info, frame.area())
237 .into_iter()
238 .map(|hitbox| hitbox.id)
239 .collect();
240 use ratatui::widgets::Widget;
241 Widget::render(info, frame.area(), frame.buffer_mut());
242 })
243 .expect("draw");
244 let row = terminal
245 .backend()
246 .buffer()
247 .content()
248 .iter()
249 .map(|cell| cell.symbol().to_string())
250 .collect::<String>();
251 (row, ids)
252 };
253 let (wide, ids) = compact_row(160);
254 assert_eq!(
255 wide.trim_end(),
256 "deepseek-v4 │ ctx 61% $0.42 ttft 400ms 38 tok/s",
257 "compact keeps performance, route, context and price: {wide:?}"
258 );
259 assert_eq!(
260 ids,
261 vec![
262 InfoSegmentId::Model,
263 InfoSegmentId::Context,
264 InfoSegmentId::Cost,
265 InfoSegmentId::Ttft,
266 InfoSegmentId::Rate,
267 ]
268 );
269 for w in 24..=180u16 {
270 let (row, _) = compact_row(w);
271 for gone in ["1.2K", "help"] {
272 assert!(
273 !row.contains(gone),
274 "{w}: compact never paints {gone}: {row:?}"
275 );
276 }
277 assert!(
278 row.contains("deepseek-v4") && row.contains("ctx 61%"),
279 "{w}: the floor still never sheds: {row:?}"
280 );
281 }
282 // The full row at the same width is the row the user had before.
283 assert!(render_row(&UI_THEME, 160, &segments).contains("tok/s"));
284
285 // Cache survives compact and is the first performance reading to shed
286 // when the row is narrow (#6565).
287 let mut with_cache = segments.clone();
288 with_cache.insert(
289 3,
290 InfoSegment::new(
291 InfoSegmentId::Cache,
292 "cache",
293 "85%",
294 ChromeInk::MetadataValue,
295 ),
296 );
297 let wide_cache = render_row_compact(160, &with_cache);
298 assert!(wide_cache.contains("cache 85%"), "{wide_cache:?}");
299 assert!(
300 !wide_cache.contains("1.2K") && !wide_cache.contains("help"),
301 "{wide_cache:?}"
302 );
303 let narrow_cache = render_row_compact(40, &with_cache);
304 assert!(!narrow_cache.contains("cache"), "{narrow_cache:?}");
305 assert!(
306 narrow_cache.contains("deepseek-v4") && narrow_cache.contains("ctx 61%"),
307 "{narrow_cache:?}"
308 );
309 }
310
311 fn render_row_compact(width: u16, segments: &[InfoSegment]) -> String {
312 let backend = TestBackend::new(width, 1);
313 let mut terminal = Terminal::new(backend).expect("terminal");
314 terminal
315 .draw(|frame| {
316 let hint = help_hint();
317 let info = InfoLine::new(&UI_THEME, &hint, segments).compact(true);
318 use ratatui::widgets::Widget;
319 Widget::render(info, frame.area(), frame.buffer_mut());
320 })
321 .expect("draw");
322 terminal
323 .backend()
324 .buffer()
325 .content()
326 .iter()
327 .map(|cell| cell.symbol().to_string())
328 .collect()
329 }
330
331 /// At the 80% cap the context reading takes the error token — the caller
332 /// picks the ink, and the row paints it on both the label and the value.
333 #[test]
334 fn infoline_context_takes_the_error_token_at_eighty() {
335 let theme = &UI_THEME;
336 let failure = codewhale_palette::grammar::chrome_style(theme, ChromeInk::Failure)
337 .fg
338 .expect("failure ink has a colour");
339 for (pct, expect_failure) in [(79u8, false), (80, true), (99, true)] {
340 let segments = vec![
341 InfoSegment::new(InfoSegmentId::Model, "", "deepseek-v4", ChromeInk::Identity),
342 context(pct),
343 ];
344 let buf = render_buffer(theme, 80, &segments);
345 let row = render_row(theme, 80, &segments);
346 let start = column_of(&row, "ctx");
347 let value_fg = buf[(start + 4, 0)].fg;
348 let label_fg = buf[(start, 0)].fg;
349 assert_eq!(value_fg == failure, expect_failure, "{pct}%: value ink");
350 assert_eq!(label_fg == failure, expect_failure, "{pct}%: label ink");
351 }
352 }
353
354 /// The hint must name a route that actually opens help in this shell. `F1`
355 /// is eaten by tmux and several emulators, bare `?` is composer text, and how
356 /// a terminal encodes `Ctrl+/` varies enough that printing it was a promise
357 /// the product could not keep. `/help` reaches the same view through the
358 /// composer in every terminal.
359 #[test]
360 fn infoline_help_hint_names_a_route_that_opens_help() {
361 let hint = help_hint();
362 assert_eq!(hint, "/help", "a slash command names itself: {hint}");
363 assert!(!hint.contains("F1"), "terminals eat F1: {hint}");
364 assert!(!hint.starts_with('?'), "bare ? is composer text: {hint}");
365 // The chord stays accepted for the terminals that do deliver it; it is
366 // only no longer what chrome promises.
367 let key = crossterm::event::KeyEvent::new(
368 crossterm::event::KeyCode::Char('/'),
369 crossterm::event::KeyModifiers::CONTROL,
370 );
371 assert!(crate::tui::shell_key_routing::is_help_shortcut(&key));
372 let row = render_row(&UI_THEME, 120, &work_segments());
373 assert!(row.trim_end().ends_with(&hint), "pinned right: {row:?}");
374 }
375
376 /// Every recorded hitbox covers exactly the cells its segment painted, at
377 /// every width — the hitbox pass and the paint pass share one shed pass.
378 #[test]
379 fn infoline_hitboxes_match_painted_cells() {
380 let segments = work_segments();
381 let hint = help_hint();
382 for w in 24..=180u16 {
383 let area = Rect::new(0, 0, w, 1);
384 let info = InfoLine::new(&UI_THEME, &hint, &segments);
385 let hitboxes = infoline_hitboxes(&info, area);
386 let cells = render_cells(&UI_THEME, w, &segments);
387 for hitbox in &hitboxes {
388 let segment = segments.iter().find(|s| s.id == hitbox.id).unwrap();
389 let painted: String = cells
390 [usize::from(hitbox.area.x)..usize::from(hitbox.area.x + hitbox.area.width)]
391 .concat();
392 let expected = if segment.label.is_empty() {
393 segment.value.clone()
394 } else {
395 format!("{} {}", segment.label, segment.value)
396 };
397 assert!(
398 expected.starts_with(painted.trim_end()),
399 "{w}: {:?} hitbox {:?} covers {painted:?}, expected {expected:?}",
400 hitbox.id,
401 hitbox.area
402 );
403 }
404 // No two hitboxes overlap.
405 for (i, a) in hitboxes.iter().enumerate() {
406 for b in &hitboxes[i + 1..] {
407 assert!(
408 a.area.right() <= b.area.x || b.area.right() <= a.area.x,
409 "{w}: hitboxes overlap: {a:?} {b:?}"
410 );
411 }
412 }
413 }
414 }
415
416 /// The context reading's hitbox is exactly the painted `ctx NN%` span.
417 #[test]
418 fn context_meter_hitbox_covers_exactly_the_painted_reading() {
419 let segments = work_segments();
420 let hint = help_hint();
421 for w in 24..=180u16 {
422 let area = Rect::new(0, 0, w, 1);
423 let info = InfoLine::new(&UI_THEME, &hint, &segments);
424 let hitbox = context_meter_hitbox(&info, area).expect("the reading never sheds");
425 let cells = render_cells(&UI_THEME, w, &segments);
426 let painted: String =
427 cells[usize::from(hitbox.x)..usize::from(hitbox.x + hitbox.width)].concat();
428 assert!(
429 "ctx 61%".starts_with(painted.trim_end()),
430 "{w}: context hitbox {hitbox:?} covers {painted:?}"
431 );
432 }
433 }
434
435 /// ASCII-safe mode projects every glyph to a single-width ASCII cell.
436 #[test]
437 fn infoline_ascii_safe_has_no_wide_or_unsupported_glyphs() {
438 let segments = work_segments();
439 let hint = help_hint();
440 for (w, _) in BLOCKER_SIZES {
441 let area = Rect::new(0, 0, w, 1);
442 let mut buf = ratatui::buffer::Buffer::empty(area);
443 let info = InfoLine::new(&UI_THEME, &hint, &segments).ascii_safe(true);
444 ratatui::widgets::Widget::render(info, area, &mut buf);
445 for x in 0..w {
446 let symbol = buf[(x, 0)].symbol();
447 assert!(symbol.is_ascii(), "{w}: cell {x} {symbol:?} is not ASCII");
448 assert_eq!(
449 symbol.width(),
450 1,
451 "{w}: cell {x} {symbol:?} is not one cell"
452 );
453 }
454 }
455 }
456
457 /// Hover and degenerate sizes never panic, and hover only brightens the
458 /// model — the one segment with an action.
459 #[test]
460 fn infoline_hover_and_narrow_do_not_panic() {
461 let segments = work_segments();
462 let hint = help_hint();
463 for (w, h) in [(0u16, 0u16), (1, 1), (5, 1), (24, 1), (300, 1)] {
464 let area = Rect::new(0, 0, w, h);
465 let mut buf = ratatui::buffer::Buffer::empty(area);
466 let info = InfoLine::new(&UI_THEME, &hint, &segments).hovered(Some(InfoSegmentId::Model));
467 ratatui::widgets::Widget::render(info, area, &mut buf);
468 let info = InfoLine::new(&UI_THEME, &hint, &segments);
469 let _ = infoline_hitboxes(&info, area);
470 let _ = context_meter_hitbox(&info, area);
471 }
472 let area = Rect::new(0, 0, 120, 1);
473 let mut plain = ratatui::buffer::Buffer::empty(area);
474 ratatui::widgets::Widget::render(InfoLine::new(&UI_THEME, &hint, &segments), area, &mut plain);
475 let mut hovered = ratatui::buffer::Buffer::empty(area);
476 ratatui::widgets::Widget::render(
477 InfoLine::new(&UI_THEME, &hint, &segments).hovered(Some(InfoSegmentId::Model)),
478 area,
479 &mut hovered,
480 );
481 assert_ne!(plain[(0, 0)].modifier, hovered[(0, 0)].modifier);
482 let ctx_x = column_of(&render_row(&UI_THEME, 120, &segments), "ctx");
483 assert_eq!(plain[(ctx_x, 0)], hovered[(ctx_x, 0)]);
484 }
485
486 /// Slice G: the context reading owns the inspector click action, so it
487 /// brightens on hover exactly like the model segment; status-only facts
488 /// (cost) never do.
489 #[test]
490 fn infoline_context_hover_brightens_only_the_context_reading() {
491 let segments = work_segments();
492 let hint = help_hint();
493 let area = Rect::new(0, 0, 120, 1);
494 let mut plain = ratatui::buffer::Buffer::empty(area);
495 ratatui::widgets::Widget::render(InfoLine::new(&UI_THEME, &hint, &segments), area, &mut plain);
496 let mut hovered = ratatui::buffer::Buffer::empty(area);
497 ratatui::widgets::Widget::render(
498 InfoLine::new(&UI_THEME, &hint, &segments).hovered(Some(InfoSegmentId::Context)),
499 area,
500 &mut hovered,
501 );
502 let row = render_row(&UI_THEME, 120, &segments);
503 // Hover feedback lands on the value cells (`61%`); the dim label prefix
504 // (`ctx`) keeps its reading ink, mirroring the model segment's probe.
505 let ctx_x = column_of(&row, "61%");
506 assert_ne!(
507 plain[(ctx_x, 0)].modifier,
508 hovered[(ctx_x, 0)].modifier,
509 "hovered context reading must respond visibly"
510 );
511 // Model (actionable but not hovered) and cost (status-only) stay clean.
512 assert_eq!(plain[(0, 0)], hovered[(0, 0)]);
513 let cost_x = column_of(&row, "$0.42");
514 assert_eq!(plain[(cost_x, 0)], hovered[(cost_x, 0)]);
515 }
516
517 #[test]
518 fn infoline_preserves_every_live_chrome_ink_and_untouched_host_style() {
519 use ratatui::style::{Color, Modifier, Style};
520 let theme = UiTheme {
521 status_working: Color::Rgb(1, 2, 3),
522 permission_ask: Color::Rgb(2, 3, 4),
523 permission_auto_review: Color::Rgb(3, 4, 5),
524 permission_full_access: Color::Rgb(4, 5, 6),
525 accent_action: Color::Rgb(5, 6, 7),
526 warning: Color::Rgb(6, 7, 8),
527 accent_primary: Color::Rgb(7, 8, 9),
528 text_soft: Color::Rgb(8, 9, 10),
529 text_muted: Color::Rgb(9, 10, 11),
530 text_hint: Color::Rgb(10, 11, 12),
531 text_dim: Color::Rgb(11, 12, 13),
532 error_fg: Color::Rgb(12, 13, 14),
533 ..UI_THEME
534 };
535 for ink in [
536 ChromeInk::Outcome,
537 ChromeInk::PermissionAsk,
538 ChromeInk::PermissionAutoReview,
539 ChromeInk::PermissionFullAccess,
540 ChromeInk::Waiting,
541 ChromeInk::Attention,
542 ChromeInk::Active,
543 ChromeInk::PolicyAct,
544 ChromeInk::PolicyPlan,
545 ChromeInk::PolicyOperate,
546 ChromeInk::Identity,
547 ChromeInk::Info,
548 ChromeInk::MetadataValue,
549 ChromeInk::Metadata,
550 ChromeInk::MetadataHint,
551 ChromeInk::MetadataDim,
552 ChromeInk::Failure,
553 ] {
554 let segments = [InfoSegment::new(
555 InfoSegmentId::Model,
556 "reading",
557 "value",
558 ink,
559 )];
560 let area = Rect::new(3, 2, 32, 2);
561 let mut buf = ratatui::buffer::Buffer::empty(Rect::new(0, 0, 40, 5));
562 let existing = Style::default()
563 .fg(super::source_theme(false)
564 .color(codewhale_ratatui::Role::Accent)
565 .unwrap())
566 .bg(Color::Rgb(30, 40, 50))
567 .add_modifier(Modifier::ITALIC);
568 buf.set_style(buf.area, existing);
569 let before = buf.clone();
570 let info = InfoLine::new(&theme, "/help", &segments).hovered(Some(InfoSegmentId::Model));
571 ratatui::widgets::Widget::render(info, area, &mut buf);
572 let label_color = if matches!(ink, ChromeInk::Failure | ChromeInk::Attention) {
573 ink.color(&theme)
574 } else {
575 theme.text_soft
576 };
577 let value_color = match ink {
578 ChromeInk::MetadataValue => theme.text_body,
579 ChromeInk::Metadata => theme.text_soft,
580 ChromeInk::MetadataHint => theme.text_muted,
581 _ => ink.color(&theme),
582 };
583 assert_eq!(buf[(3, 2)].fg, label_color, "{ink:?}: label");
584 for x in 11..16 {
585 let cell = &buf[(x, 2)];
586 assert_eq!(cell.fg, value_color, "{ink:?}: value");
587 assert_eq!(cell.bg, Color::Rgb(30, 40, 50), "host owns the ground");
588 assert!(
589 cell.modifier
590 .contains(Modifier::ITALIC | Modifier::BOLD | Modifier::UNDERLINED)
591 );
592 }
593 assert_eq!(
594 buf[(30, 2)].fg,
595 theme.text_muted,
596 "help uses its own live slot"
597 );
598 for position in [(0, 2), (16, 2), (20, 2), (3, 3), (39, 4)] {
599 assert_eq!(
600 buf[position], before[position],
601 "{ink:?}: untouched {position:?}"
602 );
603 }
604 }
605 }
606
607 #[test]
608 fn infoline_cjk_and_combining_text_keep_projected_pointer_geometry_when_clipped() {
609 use ratatui::style::{Color, Style};
610 let segments = [
611 InfoSegment::new(
612 InfoSegmentId::Model,
613 "",
614 "模型-e\u{301}↓",
615 ChromeInk::Identity,
616 ),
617 InfoSegment::new(InfoSegmentId::Context, "上下文", "61%", ChromeInk::Info),
618 ];
619 for ascii in [false, true] {
620 for width in 0..=40 {
621 let area = Rect::new(3, 2, width, 1);
622 let mut buf = ratatui::buffer::Buffer::empty(Rect::new(0, 0, 46, 4));
623 buf.set_style(buf.area, Style::default().bg(Color::Rgb(30, 40, 50)));
624 let before = buf.clone();
625 let info = InfoLine::new(&UI_THEME, "", &segments).ascii_safe(ascii);
626 let hitboxes = infoline_hitboxes(&info, area);
627 let context = context_meter_hitbox(&info, area);
628 ratatui::widgets::Widget::render(info, area, &mut buf);
629 assert_eq!(buf[(2, 2)], before[(2, 2)], "left clipping");
630 assert_eq!(
631 buf[(area.right(), 2)],
632 before[(area.right(), 2)],
633 "right clipping"
634 );
635 assert_eq!(buf[(3, 3)], before[(3, 3)], "the row never wraps");
636 for (index, hitbox) in hitboxes.iter().enumerate() {
637 assert!(hitbox.area.x >= area.x && hitbox.area.right() <= area.right());
638 assert_eq!(hitbox.area.y, area.y);
639 assert_eq!(hitbox.area.height, 1);
640 if index > 0 {
641 assert!(hitboxes[index - 1].area.right() <= hitbox.area.x);
642 }
643 }
644 if width >= 7 {
645 assert_eq!(hitboxes[0].area, Rect::new(3, 2, 7, 1));
646 assert_eq!(buf[(3, 2)].symbol(), "模");
647 assert_eq!(buf[(5, 2)].symbol(), "型");
648 assert_eq!(buf[(8, 2)].symbol(), "e\u{301}");
649 assert_eq!(buf[(9, 2)].symbol(), if ascii { "v" } else { "↓" });
650 }
651 if width >= 20 {
652 assert_eq!(context, Some(Rect::new(13, 2, 10, 1)));
653 assert_eq!(buf[(13, 2)].symbol(), "上");
654 assert_eq!(buf[(15, 2)].symbol(), "下");
655 assert_eq!(buf[(17, 2)].symbol(), "文");
656 assert_eq!(buf[(20, 2)].symbol(), "6");
657 }
658 }
659 }
660 }
661
662 #[test]
663 fn infoline_sanitizes_hidden_controls_before_painting_and_pointer_measurement() {
664 let segments = [
665 InfoSegment::new(
666 InfoSegmentId::Model,
667 "",
668 "model\u{202e}",
669 ChromeInk::Identity,
670 ),
671 InfoSegment::new(
672 InfoSegmentId::Context,
673 "ct\0x",
674 "6\u{1b}1%",
675 ChromeInk::Info,
676 ),
677 InfoSegment::new(
678 InfoSegmentId::OutputTokens,
679 "↓",
680 "1.2K",
681 ChromeInk::MetadataValue,
682 ),
683 ];
684 let area = Rect::new(0, 0, 60, 1);
685 let mut buf = ratatui::buffer::Buffer::empty(area);
686 let info = InfoLine::new(&UI_THEME, "", &segments).ascii_safe(true);
687 let hitboxes = infoline_hitboxes(&info, area);
688 ratatui::widgets::Widget::render(info, area, &mut buf);
689 let row: String = buf.content().iter().map(|cell| cell.symbol()).collect();
690 assert_eq!(row.trim_end(), "model ctx 61% v 1.2K");
691 assert_eq!(
692 hitboxes.iter().map(|hit| hit.area).collect::<Vec<_>>(),
693 [
694 Rect::new(0, 0, 5, 1),
695 Rect::new(8, 0, 7, 1),
696 Rect::new(18, 0, 6, 1),
697 ]
698 );
699 }
700
701 #[test]
702 fn footer_keeps_permission_and_session_state_readable_at_working_sizes() {
703 use super::super::phase_strip::{TidelineFooter, render_tideline_footer};
704 use codewhale_palette::{ThemeId, contrast_ratio};
705 use ratatui::{
706 buffer::Buffer,
707 style::{Modifier, Style},
708 widgets::Widget,
709 };
710
711 let theme = ThemeId::Underwater.ui_theme();
712 let segments = [
713 InfoSegment::new(
714 InfoSegmentId::Model,
715 "",
716 "deepseek-v4 · high effort",
717 ChromeInk::MetadataValue,
718 ),
719 InfoSegment::new(InfoSegmentId::Context, "ctx", "23%", ChromeInk::Info),
720 InfoSegment::new(
721 InfoSegmentId::Ttft,
722 "ttft",
723 "400ms",
724 ChromeInk::MetadataValue,
725 ),
726 InfoSegment::new(
727 InfoSegmentId::Rate,
728 "",
729 "38 tok/s",
730 ChromeInk::MetadataValue,
731 ),
732 InfoSegment::new(
733 InfoSegmentId::Cache,
734 "cache",
735 "88%",
736 ChromeInk::MetadataValue,
737 ),
738 ];
739 for (w, h) in [(106, 39), (120, 35), (64, 20), (40, 12)] {
740 for ascii in [false, true] {
741 let mut buf = Buffer::empty(Rect::new(0, 0, w, h));
742 let posture_area = Rect::new(0, h - 2, w, 1);
743 let info_area = Rect::new(0, h - 1, w, 1);
744 buf.set_style(posture_area, Style::default().bg(theme.footer_bg));
745 buf.set_style(info_area, Style::default().bg(theme.header_bg));
746 let posture =
747 TidelineFooter::new(&theme, ("Full Access", ChromeInk::PermissionFullAccess))
748 .permission_key(Some("Shift+Tab to change"))
749 .ascii_safe(ascii);
750 render_tideline_footer(posture_area, &mut buf, &posture);
751 let info = InfoLine::new(&theme, "/help", &segments).ascii_safe(ascii);
752 let hits = infoline_hitboxes(&info, info_area);
753 info.render(info_area, &mut buf);
754 let row = |y| (0..w).map(|x| buf[(x, y)].symbol()).collect::<String>();
755 let posture_text = row(posture_area.y);
756 let badge_start = column_of(&posture_text, "Full Access");
757 let name = &buf[(badge_start, posture_area.y)];
758 assert!(name.modifier.contains(Modifier::BOLD));
759 assert!(!name.modifier.contains(Modifier::REVERSED));
760 assert_eq!(name.fg, theme.text_body);
761 assert_eq!(name.bg, theme.footer_bg);
762 assert_eq!(
763 buf[(badge_start - 2, posture_area.y)].fg,
764 theme.permission_full_access
765 );
766 if w >= 64 {
767 let key = column_of(&posture_text, "Shift+Tab");
768 assert_eq!(buf[(key, posture_area.y)].fg, theme.text_muted);
769 assert!(
770 !buf[(key, posture_area.y)]
771 .modifier
772 .contains(Modifier::REVERSED)
773 );
774 }
775 for id in [InfoSegmentId::Model, InfoSegmentId::Context] {
776 let hit = hits.iter().find(|hit| hit.id == id).unwrap();
777 let cell = &buf[(hit.area.right() - 1, hit.area.y)];
778 assert!(cell.modifier.contains(Modifier::BOLD));
779 assert!(contrast_ratio(cell.fg, cell.bg).unwrap() >= 4.5);
780 }
781 if w >= 106 {
782 let context = hits
783 .iter()
784 .find(|hit| hit.id == InfoSegmentId::Context)
785 .unwrap();
786 let divider = context.area.left() - 2;
787 assert_eq!(
788 buf[(divider, info_area.y)].symbol(),
789 if ascii { "|" } else { "│" }
790 );
791 assert!(
792 hits.iter()
793 .all(|hit| !hit.area.contains((divider, info_area.y).into()))
794 );
795 let readings = row(info_area.y);
796 for fact in ["ttft 400ms", "38 tok/s", "cache 88%"] {
797 assert!(readings.contains(fact), "{w}x{h} {fact}: {readings}");
798 }
799 }
800 }
801 }
802 }
803
804 #[test]
805 fn narrow_footer_keeps_the_permission_context_reading_and_compact_action() {
806 use super::super::phase_strip::{TidelineFooter, bare_model_reading, render_tideline_footer};
807 use codewhale_localization::{Locale, MessageId, tr};
808 use ratatui::{buffer::Buffer, widgets::Widget};
809 let long = "custom-endpoint-一二三四-five-six-seven-eight-nine-ten-eleven";
810 for locale in [Locale::En, Locale::ZhHans] {
811 let label = tr(locale, MessageId::InfoLineContext);
812 for width in [40, 45, 120] {
813 let area = Rect::new(0, 0, width, 12);
814 for model in ["deepseek-v4", long] {
815 let shown = bare_model_reading(model.to_owned(), width, Some((&label, 84)));
816 let segments = [
817 InfoSegment::new(InfoSegmentId::Model, "", shown, ChromeInk::MetadataValue),
818 InfoSegment::new(
819 InfoSegmentId::Context,
820 label.as_ref(),
821 "84%",
822 ChromeInk::Attention,
823 ),
824 ];
825 let info_area = Rect::new(0, 11, width, 1);
826 let mut buf = Buffer::empty(area);
827 let info = InfoLine::new(&UI_THEME, "/help", &segments);
828 let hit = context_meter_hitbox(&info, info_area).unwrap();
829 let expected = format!("{label} 84%");
830 assert_eq!(usize::from(hit.width), expected.width());
831 info.render(info_area, &mut buf);
832 let footer = TidelineFooter::new(
833 &UI_THEME,
834 ("Full Access", ChromeInk::PermissionFullAccess),
835 )
836 .locale(locale)
837 .context_percent(84)
838 .permission_key(Some("Shift+Tab to change"))
839 .right(Some(("model ready", ChromeInk::Metadata)));
840 render_tideline_footer(Rect::new(0, 10, width, 1), &mut buf, &footer);
841 let row = |y| {
842 let mut text = String::new();
843 let mut x = 0;
844 while x < width {
845 let symbol = buf[(x, y)].symbol();
846 text.push_str(symbol);
847 x += symbol.width().max(1) as u16;
848 }
849 text
850 };
851 let measurements = row(11);
852 let posture = row(10);
853 assert!(measurements.contains(&expected), "{width} {measurements}");
854 assert!(measurements.contains(if width < 120 && model == long {
855 "/model"
856 } else {
857 model
858 }));
859 assert!(
860 posture.contains("Full Access") && posture.contains("/compact"),
861 "{width}: {posture}"
862 );
863 if width == 120 {
864 assert!(posture.contains(tr(locale, MessageId::PostureDepthWarn).as_ref()));
865 assert!(posture.contains("model ready"));
866 }
867 }
868 }
869 }
870 }
871
872 #[test]
873 fn route_emphasis_uses_the_projected_provider_model_and_effort_cells() {
874 use super::super::phase_strip::{RouteFieldKind, RouteIdentityField};
875 use ratatui::{buffer::Buffer, style::Modifier, widgets::Widget};
876
877 for ascii in [false, true] {
878 let fields = [
879 (RouteFieldKind::Provider, "供應🐋"),
880 (RouteFieldKind::Model, "v2 · e\u{301}"),
881 (RouteFieldKind::Effort, "推理 高"),
882 ]
883 .into_iter()
884 .map(|(kind, text)| RouteIdentityField {
885 kind,
886 text: text.to_owned(),
887 })
888 .collect();
889 let segments = [InfoSegment::route(fields, ascii), context(23)];
890 let area = Rect::new(4, 2, 110, 1);
891 let mut buf = Buffer::empty(area);
892 let info = InfoLine::new(&UI_THEME, "", &segments).ascii_safe(ascii);
893 let hits = infoline_hitboxes(&info, area);
894 info.render(area, &mut buf);
895 let widths =
896 super::route_field_cells(&segments[0].route_fields, hits[0].area).collect::<Vec<_>>();
897 assert_eq!(widths[0].1.width, if ascii { 5 } else { 6 });
898 for (kind, rect) in widths {
899 assert_eq!(
900 buf[(rect.x, rect.y)].modifier.contains(Modifier::BOLD),
901 kind == RouteFieldKind::Model
902 );
903 }
904 assert_eq!(
905 buf[(hits[1].area.x - 2, area.y)].symbol(),
906 if ascii { "|" } else { "│" }
907 );
908 assert!(
909 !buf[(hits[1].area.x, area.y)]
910 .modifier
911 .contains(Modifier::BOLD)
912 );
913 assert!(
914 buf[(hits[1].area.right() - 1, area.y)]
915 .modifier
916 .contains(Modifier::BOLD)
917 );
918 }
919 }
920
920 lines RUST