返回 CodeWhale
tests.rs
根目录 / crates / palette / src / tests.rs
1 use super::adapt::{
2 ColorDepth, adapt_bg, adapt_bg_for_palette_mode, adapt_bg_for_theme, adapt_color,
3 adapt_fg_for_depth, adapt_fg_for_palette_mode, adapt_fg_for_theme, blend, luma, nearest_ansi16,
4 pulse_brightness, reasoning_surface_tint, rgb_to_ansi256,
5 };
6 use super::detect::{
7 BackgroundSource, PaletteMode, palette_mode_for_background,
8 palette_mode_from_apple_interface_style, resolve_terminal_background,
9 };
10 use super::ids::{SELECTABLE_THEMES, ThemeId, normalize_hex_rgb_color, normalize_theme_name};
11 use super::rgb::*;
12 use super::themes::{
13 CATPPUCCIN_MOCHA_UI_THEME, GRAYSCALE_UI_THEME, LIGHT_UI_THEME, MATRIX_UI_THEME,
14 SOLARIZED_LIGHT_UI_THEME, TERMINAL_UI_THEME, TOKYO_NIGHT_UI_THEME, UI_THEME, UiTheme,
15 parse_hex_rgb_color, theme_label_for_mode, ui_theme_from_settings,
16 };
17 use super::tokens::{
18 ACCENT_REASONING_LIVE, DIFF_ADDED, DIFF_ADDED_BG, DIFF_DELETED_BG, GRAYSCALE_BORDER,
19 GRAYSCALE_ELEVATED, GRAYSCALE_PANEL, GRAYSCALE_REASONING, GRAYSCALE_SURFACE,
20 GRAYSCALE_TEXT_BODY, GRAYSCALE_TEXT_HINT, GRAYSCALE_TEXT_SOFT, LIGHT_ACTION, LIGHT_BORDER,
21 LIGHT_DANGER, LIGHT_ELEVATED, LIGHT_ERROR, LIGHT_HUMAN, LIGHT_LIVE, LIGHT_PANEL,
22 LIGHT_REASONING, LIGHT_SELECTION_BG, LIGHT_SUCCESS, LIGHT_SUCCESS_FG, LIGHT_SURFACE,
23 LIGHT_TEXT_BODY, LIGHT_TEXT_HINT, LIGHT_WARNING, MODE_AGENT, MODE_PLAN, MODE_YOLO,
24 SELECTION_BG, SOLARIZED_PANEL, SOLARIZED_SURFACE, SOLARIZED_TEXT_BODY, SOLARIZED_TEXT_HINT,
25 STATUS_ERROR, STATUS_WARNING, SURFACE_ERROR, SURFACE_REASONING, SURFACE_REASONING_TINT,
26 SURFACE_TOOL_ACTIVE, TEXT_BODY, TEXT_HINT, TEXT_REASONING, TEXT_TOOL_OUTPUT, WHALE_ACTION,
27 WHALE_BG, WHALE_ERROR, WHALE_HUMAN, WHALE_LIVE, WHALE_PANEL,
28 };
29 use ratatui::style::Color;
30
31 #[test]
32 fn palette_mode_parses_colorfgbg_background_slot() {
33 assert_eq!(
34 PaletteMode::from_colorfgbg("0;15"),
35 Some(PaletteMode::Light)
36 );
37 assert_eq!(PaletteMode::from_colorfgbg("15;0"), Some(PaletteMode::Dark));
38 assert_eq!(
39 PaletteMode::from_colorfgbg("7;default;15"),
40 Some(PaletteMode::Light)
41 );
42 assert_eq!(PaletteMode::from_colorfgbg("not-a-color"), None);
43 }
44
45 #[test]
46 fn palette_mode_detect_prefers_colorfgbg_over_macos_fallback() {
47 assert_eq!(
48 resolve_terminal_background(None, Some("0;15"), Some(PaletteMode::Dark)).mode(),
49 PaletteMode::Light
50 );
51 assert_eq!(
52 resolve_terminal_background(None, Some("15;0"), Some(PaletteMode::Light)).mode(),
53 PaletteMode::Dark
54 );
55 }
56
57 #[test]
58 fn palette_mode_detect_uses_macos_fallback_when_colorfgbg_missing_or_invalid() {
59 assert_eq!(
60 resolve_terminal_background(None, None, Some(PaletteMode::Light)).mode(),
61 PaletteMode::Light
62 );
63 assert_eq!(
64 resolve_terminal_background(None, Some("not-a-color"), Some(PaletteMode::Light)).mode(),
65 PaletteMode::Light
66 );
67 assert_eq!(
68 resolve_terminal_background(None, None, None).mode(),
69 PaletteMode::Dark
70 );
71 }
72
73 #[test]
74 fn apple_interface_style_maps_dark_and_missing_key_to_expected_modes() {
75 assert_eq!(
76 palette_mode_from_apple_interface_style("Dark\n"),
77 PaletteMode::Dark
78 );
79 assert_eq!(
80 palette_mode_from_apple_interface_style("Light\n"),
81 PaletteMode::Light
82 );
83 assert_eq!(
84 palette_mode_from_apple_interface_style(""),
85 PaletteMode::Light
86 );
87 }
88
89 #[test]
90 fn ui_theme_selects_light_variant() {
91 let theme = UiTheme::for_mode(PaletteMode::Light);
92 assert_eq!(theme, LIGHT_UI_THEME);
93 assert_eq!(theme.surface_bg, Color::Reset);
94 assert_eq!(theme.text_body, LIGHT_TEXT_BODY);
95 }
96
97 #[test]
98 fn whale_pair_flat_shells_are_terminal_native_without_erasing_semantic_surfaces() {
99 for theme in [UI_THEME, LIGHT_UI_THEME] {
100 for shell_surface in [
101 theme.surface_bg,
102 theme.panel_bg,
103 theme.composer_bg,
104 theme.header_bg,
105 theme.footer_bg,
106 ] {
107 assert_eq!(shell_surface, Color::Reset, "{} shell", theme.name);
108 }
109
110 for semantic_surface in [
111 theme.elevated_bg,
112 theme.selection_bg,
113 theme.error_surface,
114 theme.diff_added_bg,
115 theme.diff_deleted_bg,
116 ] {
117 assert_ne!(semantic_surface, Color::Reset, "{} semantics", theme.name);
118 }
119 }
120 }
121
122 #[test]
123 fn ui_theme_selects_grayscale_variant() {
124 let theme = UiTheme::for_mode(PaletteMode::Grayscale);
125 assert_eq!(theme, GRAYSCALE_UI_THEME);
126 assert_eq!(theme.surface_bg, GRAYSCALE_SURFACE);
127 assert_eq!(theme.panel_bg, GRAYSCALE_PANEL);
128 assert_eq!(theme.text_body, GRAYSCALE_TEXT_BODY);
129 }
130
131 #[test]
132 fn ui_theme_selects_solarized_light_variant() {
133 let theme = UiTheme::for_mode(PaletteMode::SolarizedLight);
134 assert_eq!(theme, SOLARIZED_LIGHT_UI_THEME);
135 assert_eq!(theme.surface_bg, SOLARIZED_SURFACE);
136 assert_eq!(theme.panel_bg, SOLARIZED_PANEL);
137 assert_eq!(theme.text_body, SOLARIZED_TEXT_BODY);
138 }
139
140 #[test]
141 fn theme_names_normalize_common_grayscale_aliases() {
142 assert_eq!(normalize_theme_name("system"), Some("system"));
143 assert_eq!(normalize_theme_name("default"), Some("system"));
144 assert_eq!(normalize_theme_name("whale"), Some("dark"));
145 assert_eq!(normalize_theme_name("transparent"), Some("terminal"));
146 assert_eq!(normalize_theme_name("inherit"), Some("terminal"));
147 assert_eq!(normalize_theme_name("black-white"), Some("grayscale"));
148 assert_eq!(normalize_theme_name("mono"), Some("grayscale"));
149 assert_eq!(normalize_theme_name("solarized"), Some("solarized-light"));
150 assert_eq!(theme_label_for_mode(PaletteMode::Grayscale), "grayscale");
151 }
152
153 #[test]
154 fn terminal_theme_resets_surfaces_and_remaps_direct_palette_constants() {
155 assert_eq!(ThemeId::from_name("terminal"), Some(ThemeId::Terminal));
156 assert_eq!(TERMINAL_UI_THEME.surface_bg, Color::Reset);
157 assert_eq!(TERMINAL_UI_THEME.footer_bg, Color::Reset);
158 assert_eq!(TERMINAL_UI_THEME.text_body, Color::Reset);
159
160 assert_eq!(
161 adapt_bg_for_theme(WHALE_BG, ThemeId::Terminal, &TERMINAL_UI_THEME),
162 Color::Reset
163 );
164 assert_eq!(
165 adapt_bg_for_theme(DIFF_ADDED_BG, ThemeId::Terminal, &TERMINAL_UI_THEME),
166 Color::Reset
167 );
168 assert_eq!(
169 adapt_fg_for_theme(TEXT_BODY, ThemeId::Terminal, &TERMINAL_UI_THEME),
170 Color::Reset
171 );
172 assert_eq!(
173 adapt_fg_for_theme(DIFF_ADDED, ThemeId::Terminal, &TERMINAL_UI_THEME),
174 Color::Green
175 );
176 }
177
178 #[test]
179 fn terminal_and_matrix_preserve_agent_plan_and_full_access_mode_slots() {
180 for (theme_id, theme) in [
181 (ThemeId::Terminal, TERMINAL_UI_THEME),
182 (ThemeId::Matrix, MATRIX_UI_THEME),
183 ] {
184 for (source, expected, role) in [
185 (MODE_AGENT, theme.mode_agent, "agent"),
186 (MODE_PLAN, theme.mode_plan, "plan"),
187 (MODE_YOLO, theme.mode_yolo, "full access"),
188 ] {
189 assert_eq!(
190 adapt_fg_for_theme(source, theme_id, &theme),
191 expected,
192 "theme '{}' must map the raw {role} token to its mode slot",
193 theme_id.name(),
194 );
195 }
196 }
197 }
198
199 #[test]
200 fn community_remap_keeps_selection_tool_and_error_background_domains() {
201 let mut theme = TOKYO_NIGHT_UI_THEME;
202 theme.selection_bg = Color::Rgb(1, 2, 3);
203 theme.elevated_bg = Color::Rgb(4, 5, 6);
204 theme.error_surface = Color::Rgb(7, 8, 9);
205 theme.diff_deleted_bg = Color::Rgb(10, 11, 12);
206
207 assert_eq!(
208 adapt_bg_for_theme(SELECTION_BG, ThemeId::TokyoNight, &theme),
209 theme.selection_bg
210 );
211 assert_eq!(
212 adapt_bg_for_theme(SURFACE_TOOL_ACTIVE, ThemeId::TokyoNight, &theme),
213 theme.elevated_bg
214 );
215 assert_eq!(
216 adapt_bg_for_theme(SURFACE_ERROR, ThemeId::TokyoNight, &theme),
217 theme.error_surface
218 );
219 assert_eq!(
220 adapt_bg_for_theme(DIFF_DELETED_BG, ThemeId::TokyoNight, &theme),
221 theme.diff_deleted_bg
222 );
223 }
224
225 #[test]
226 fn light_palette_has_quiet_layer_separation() {
227 assert_eq!(LIGHT_SURFACE, Color::Rgb(244, 247, 251));
228 assert_eq!(LIGHT_PANEL, Color::Rgb(255, 253, 248));
229 assert_eq!(LIGHT_ELEVATED, Color::Rgb(232, 238, 248));
230 assert_eq!(LIGHT_BORDER, Color::Rgb(169, 184, 207));
231 assert_eq!(LIGHT_SELECTION_BG, Color::Rgb(238, 246, 255));
232 assert_ne!(LIGHT_SURFACE, LIGHT_PANEL);
233 assert_ne!(LIGHT_PANEL, LIGHT_ELEVATED);
234 }
235
236 #[test]
237 fn solarized_light_does_not_mutate_whale_light_text() {
238 assert_eq!(
239 LIGHT_TEXT_BODY,
240 Color::Rgb(
241 LIGHT_TEXT_BODY_RGB.0,
242 LIGHT_TEXT_BODY_RGB.1,
243 LIGHT_TEXT_BODY_RGB.2
244 )
245 );
246 assert_ne!(LIGHT_TEXT_BODY, SOLARIZED_TEXT_BODY);
247 }
248
249 #[test]
250 fn dark_palette_uses_soft_body_text_and_warm_reasoning() {
251 assert_eq!(
252 TEXT_BODY,
253 Color::Rgb(
254 WHALE_TEXT_BODY_RGB.0,
255 WHALE_TEXT_BODY_RGB.1,
256 WHALE_TEXT_BODY_RGB.2
257 )
258 );
259 assert_eq!(
260 TEXT_REASONING,
261 Color::Rgb(
262 WHALE_REASONING_TEXT_RGB.0,
263 WHALE_REASONING_TEXT_RGB.1,
264 WHALE_REASONING_TEXT_RGB.2
265 )
266 );
267 assert_eq!(
268 ACCENT_REASONING_LIVE,
269 Color::Rgb(
270 WHALE_REASONING_TEXT_RGB.0,
271 WHALE_REASONING_TEXT_RGB.1,
272 WHALE_REASONING_TEXT_RGB.2
273 )
274 );
275 assert_ne!(TEXT_REASONING, TEXT_TOOL_OUTPUT);
276 assert_ne!(TEXT_BODY, Color::White);
277 }
278
279 #[test]
280 fn ui_theme_applies_custom_background_to_base_surfaces() {
281 let custom = Color::Rgb(26, 27, 38);
282 let theme = UiTheme::for_mode(PaletteMode::Dark).with_background_color(custom);
283
284 assert_eq!(theme.surface_bg, custom);
285 assert_eq!(theme.header_bg, custom);
286 assert_eq!(theme.footer_bg, custom);
287 assert_eq!(
288 theme.composer_bg, UI_THEME.composer_bg,
289 "custom background must not erase panel contrast"
290 );
291 }
292
293 #[test]
294 fn hex_rgb_color_parser_accepts_hashless_and_normalizes() {
295 assert_eq!(parse_hex_rgb_color("#1a1B26"), Some(Color::Rgb(26, 27, 38)));
296 assert_eq!(parse_hex_rgb_color("1a1b26"), Some(Color::Rgb(26, 27, 38)));
297 assert_eq!(
298 normalize_hex_rgb_color("#1A1B26").as_deref(),
299 Some("#1a1b26")
300 );
301 assert_eq!(parse_hex_rgb_color("#123"), None);
302 assert_eq!(parse_hex_rgb_color("#zzzzzz"), None);
303 }
304
305 #[test]
306 fn light_palette_maps_dark_surfaces_and_text() {
307 assert_eq!(
308 adapt_bg_for_palette_mode(WHALE_BG, PaletteMode::Light),
309 LIGHT_SURFACE
310 );
311 assert_eq!(
312 adapt_bg_for_palette_mode(WHALE_PANEL, PaletteMode::Light),
313 LIGHT_PANEL
314 );
315 assert_eq!(
316 adapt_fg_for_palette_mode(Color::White, LIGHT_SURFACE, PaletteMode::Light),
317 LIGHT_TEXT_BODY
318 );
319 assert_eq!(
320 adapt_fg_for_palette_mode(TEXT_HINT, LIGHT_SURFACE, PaletteMode::Light),
321 LIGHT_TEXT_HINT
322 );
323 assert_eq!(
324 adapt_fg_for_palette_mode(WHALE_ACTION, LIGHT_SURFACE, PaletteMode::Light),
325 LIGHT_ACTION
326 );
327 assert_eq!(
328 adapt_fg_for_palette_mode(WHALE_LIVE, LIGHT_SURFACE, PaletteMode::Light),
329 LIGHT_LIVE
330 );
331 assert_eq!(
332 adapt_fg_for_palette_mode(WHALE_HUMAN, LIGHT_SURFACE, PaletteMode::Light),
333 LIGHT_HUMAN
334 );
335 assert_eq!(
336 adapt_fg_for_palette_mode(STATUS_WARNING, LIGHT_SURFACE, PaletteMode::Light),
337 LIGHT_WARNING
338 );
339 assert_eq!(
340 adapt_fg_for_palette_mode(STATUS_ERROR, LIGHT_SURFACE, PaletteMode::Light),
341 LIGHT_DANGER
342 );
343 assert_ne!(LIGHT_LIVE, LIGHT_SUCCESS_FG);
344 }
345
346 #[test]
347 fn solarized_light_palette_maps_dark_surfaces_and_text_to_solarized_roles() {
348 assert_eq!(
349 adapt_bg_for_palette_mode(WHALE_BG, PaletteMode::SolarizedLight),
350 SOLARIZED_SURFACE
351 );
352 assert_eq!(
353 adapt_bg_for_palette_mode(WHALE_PANEL, PaletteMode::SolarizedLight),
354 SOLARIZED_PANEL
355 );
356 assert_eq!(
357 adapt_fg_for_palette_mode(Color::White, SOLARIZED_SURFACE, PaletteMode::SolarizedLight),
358 SOLARIZED_TEXT_BODY
359 );
360 assert_eq!(
361 adapt_fg_for_palette_mode(TEXT_HINT, SOLARIZED_SURFACE, PaletteMode::SolarizedLight),
362 SOLARIZED_TEXT_HINT
363 );
364 }
365
366 #[test]
367 fn grayscale_palette_maps_brand_hues_to_neutral_roles() {
368 assert_eq!(
369 adapt_bg_for_palette_mode(WHALE_BG, PaletteMode::Grayscale),
370 GRAYSCALE_SURFACE
371 );
372 assert_eq!(
373 adapt_bg_for_palette_mode(WHALE_PANEL, PaletteMode::Grayscale),
374 GRAYSCALE_PANEL
375 );
376 assert_eq!(
377 adapt_bg_for_palette_mode(SURFACE_REASONING, PaletteMode::Grayscale),
378 GRAYSCALE_REASONING
379 );
380 assert_eq!(
381 adapt_fg_for_palette_mode(WHALE_ACTION, GRAYSCALE_SURFACE, PaletteMode::Grayscale),
382 GRAYSCALE_TEXT_SOFT
383 );
384 assert_eq!(
385 adapt_fg_for_palette_mode(WHALE_ERROR, GRAYSCALE_SURFACE, PaletteMode::Grayscale),
386 GRAYSCALE_TEXT_BODY
387 );
388 assert_eq!(
389 adapt_fg_for_palette_mode(TEXT_HINT, GRAYSCALE_SURFACE, PaletteMode::Grayscale),
390 GRAYSCALE_TEXT_HINT
391 );
392 }
393
394 #[test]
395 fn grayscale_luma_handles_bright_rgb_without_overflow() {
396 assert_eq!(luma(255, 255, 255), 255);
397 assert_eq!(
398 adapt_fg_for_palette_mode(
399 Color::Rgb(255, 255, 255),
400 GRAYSCALE_SURFACE,
401 PaletteMode::Grayscale
402 ),
403 GRAYSCALE_TEXT_BODY
404 );
405 }
406
407 #[test]
408 fn ui_theme_from_settings_applies_theme_and_background() {
409 let theme = ui_theme_from_settings("grayscale", Some("#111111"));
410 assert_eq!(theme.mode, PaletteMode::Grayscale);
411 assert_eq!(theme.surface_bg, Color::Rgb(17, 17, 17));
412 assert_eq!(theme.header_bg, Color::Rgb(17, 17, 17));
413 assert_eq!(theme.footer_bg, Color::Rgb(17, 17, 17));
414 assert_eq!(theme.panel_bg, GRAYSCALE_PANEL);
415 assert_eq!(theme.elevated_bg, GRAYSCALE_ELEVATED);
416 assert_eq!(theme.border, GRAYSCALE_BORDER);
417 }
418
419 #[test]
420 fn adapt_color_passes_through_truecolor() {
421 let c = Color::Rgb(53, 120, 229);
422 assert_eq!(adapt_color(c, ColorDepth::TrueColor), c);
423 }
424
425 #[test]
426 fn adapt_color_maps_rgb_to_indexed_on_ansi256() {
427 let c = Color::Rgb(53, 120, 229);
428 assert!(matches!(
429 adapt_color(c, ColorDepth::Ansi256),
430 Color::Indexed(_)
431 ));
432 }
433
434 #[test]
435 fn adapt_bg_maps_rgb_to_indexed_on_ansi256() {
436 assert!(matches!(
437 adapt_bg(SURFACE_REASONING, ColorDepth::Ansi256),
438 Color::Indexed(_)
439 ));
440 }
441
442 #[test]
443 fn adapt_color_drops_to_named_on_ansi16() {
444 // Sky: blue-dominant and bright → LightBlue, not terminal cyan.
445 assert_eq!(
446 adapt_color(WHALE_ACTION, ColorDepth::Ansi16),
447 Color::LightBlue
448 );
449 // Rose Red is intentionally bright enough to use the terminal's
450 // bright red slot.
451 assert_eq!(
452 adapt_color(WHALE_ERROR, ColorDepth::Ansi16),
453 Color::LightRed
454 );
455 }
456
457 #[test]
458 fn action_blue_is_not_human_gold() {
459 assert_ne!(WHALE_ACTION, WHALE_HUMAN);
460 }
461
462 #[test]
463 fn stable_dark_and_light_ids_expose_blue_stage_product_names() {
464 assert_eq!(ThemeId::from_name("dark"), Some(ThemeId::Whale));
465 assert_eq!(ThemeId::Whale.display_name(), "Blue Stage");
466 assert_eq!(ThemeId::from_name("light"), Some(ThemeId::WhaleLight));
467 assert_eq!(ThemeId::WhaleLight.display_name(), "Blue Stage Light");
468 }
469
470 #[test]
471 fn community_theme_info_keeps_the_sky_live_role_on_ansi16() {
472 assert_eq!(
473 adapt_fg_for_depth(
474 CATPPUCCIN_MOCHA_UI_THEME.info,
475 CATPPUCCIN_MOCHA_UI_THEME.info,
476 ColorDepth::Ansi16,
477 &CATPPUCCIN_MOCHA_UI_THEME,
478 ),
479 Color::LightCyan,
480 );
481 assert_eq!(
482 adapt_fg_for_depth(
483 CATPPUCCIN_MOCHA_UI_THEME.status_working,
484 CATPPUCCIN_MOCHA_UI_THEME.status_working,
485 ColorDepth::Ansi16,
486 &CATPPUCCIN_MOCHA_UI_THEME,
487 ),
488 Color::LightCyan,
489 );
490 }
491
492 #[test]
493 fn every_selectable_theme_keeps_action_and_working_roles_distinct_on_ansi16() {
494 for theme_id in SELECTABLE_THEMES {
495 // Grayscale deliberately collapses colored semantic lanes to neutral
496 // luminance tiers before terminal-depth adaptation.
497 if *theme_id == ThemeId::Grayscale {
498 continue;
499 }
500 let ui = theme_id.ui_theme();
501 let is_light = matches!(ui.mode, PaletteMode::Light | PaletteMode::SolarizedLight);
502 assert_eq!(
503 adapt_fg_for_depth(
504 ui.accent_primary,
505 ui.accent_primary,
506 ColorDepth::Ansi16,
507 &ui,
508 ),
509 if is_light {
510 Color::Blue
511 } else {
512 Color::LightBlue
513 },
514 "theme '{}' lost the action lane",
515 theme_id.name(),
516 );
517 assert_eq!(
518 adapt_fg_for_depth(
519 ui.status_working,
520 ui.status_working,
521 ColorDepth::Ansi16,
522 &ui,
523 ),
524 if is_light {
525 Color::Cyan
526 } else {
527 Color::LightCyan
528 },
529 "theme '{}' lost the live working lane",
530 theme_id.name(),
531 );
532 }
533 }
534
535 #[test]
536 fn adapt_bg_preserves_diff_hues_on_ansi256() {
537 assert_eq!(
538 adapt_bg(DIFF_ADDED_BG, ColorDepth::Ansi256),
539 Color::Indexed(22)
540 );
541 assert_eq!(
542 adapt_bg(DIFF_DELETED_BG, ColorDepth::Ansi256),
543 Color::Indexed(52)
544 );
545 assert_eq!(
546 adapt_bg(LIGHT_SUCCESS, ColorDepth::Ansi256),
547 Color::Indexed(158)
548 );
549 assert_eq!(
550 adapt_bg(LIGHT_ERROR, ColorDepth::Ansi256),
551 Color::Indexed(224)
552 );
553 }
554
555 #[test]
556 fn adapt_bg_disables_tints_on_ansi16() {
557 assert_eq!(
558 adapt_bg(SURFACE_REASONING, ColorDepth::Ansi16),
559 Color::Reset
560 );
561 assert_eq!(
562 adapt_bg(SURFACE_REASONING, ColorDepth::TrueColor),
563 SURFACE_REASONING
564 );
565 }
566
567 #[test]
568 fn reasoning_tint_is_none_on_ansi16() {
569 assert!(reasoning_surface_tint(ColorDepth::Ansi16).is_none());
570 assert!(reasoning_surface_tint(ColorDepth::TrueColor).is_some());
571 assert!(matches!(
572 reasoning_surface_tint(ColorDepth::Ansi256),
573 Some(Color::Indexed(_))
574 ));
575 }
576
577 #[test]
578 fn light_palette_maps_reasoning_tint_to_light_surface() {
579 assert_eq!(
580 SURFACE_REASONING_TINT,
581 Color::Rgb(
582 WHALE_REASONING_TINT_RGB.0,
583 WHALE_REASONING_TINT_RGB.1,
584 WHALE_REASONING_TINT_RGB.2
585 )
586 );
587 assert_eq!(
588 adapt_bg_for_palette_mode(SURFACE_REASONING_TINT, PaletteMode::Light),
589 LIGHT_REASONING
590 );
591 assert_eq!(
592 adapt_bg_for_palette_mode(
593 reasoning_surface_tint(ColorDepth::TrueColor).expect("truecolor tint"),
594 PaletteMode::Light,
595 ),
596 LIGHT_REASONING
597 );
598 }
599
600 #[test]
601 fn blend_at_zero_returns_bg_at_one_returns_fg() {
602 let fg = Color::Rgb(200, 100, 50);
603 let bg = Color::Rgb(0, 0, 0);
604 assert_eq!(blend(fg, bg, 0.0), bg);
605 assert_eq!(blend(fg, bg, 1.0), fg);
606 }
607
608 #[test]
609 fn blend_at_half_is_midpoint() {
610 let mid = blend(Color::Rgb(200, 100, 0), Color::Rgb(0, 0, 0), 0.5);
611 assert_eq!(mid, Color::Rgb(100, 50, 0));
612 }
613
614 #[test]
615 fn pulse_brightness_swings_within_envelope() {
616 // The pulse rides between 30%..100% — never below 30% of the source.
617 let src = ACCENT_REASONING_LIVE;
618 let mut min_r = u8::MAX;
619 let mut max_r = 0u8;
620 for ms in (0u64..2000).step_by(50) {
621 if let Color::Rgb(r, _, _) = pulse_brightness(src, ms) {
622 min_r = min_r.min(r);
623 max_r = max_r.max(r);
624 }
625 }
626 let Color::Rgb(src_r, _, _) = src else {
627 panic!("expected RGB");
628 };
629 // Trough should land near 30% of source; crest near source itself.
630 let lower = (f32::from(src_r) * 0.30).round() as u8;
631 assert!(min_r <= lower + 2, "trough too high: {min_r}");
632 assert!(max_r + 2 >= src_r, "crest too low: {max_r}");
633 }
634
635 #[test]
636 fn pulse_passes_named_colors_unchanged() {
637 // Named palette entries don't blend meaningfully — leave them alone.
638 assert_eq!(pulse_brightness(Color::Reset, 0), Color::Reset);
639 assert_eq!(pulse_brightness(Color::Cyan, 1234), Color::Cyan);
640 }
641
642 #[test]
643 fn nearest_ansi16_routes_known_brand_colors() {
644 // Codewhale keeps action, live, human, and danger distinct where ANSI-16 allows it.
645 assert_eq!(nearest_ansi16(106, 174, 242), Color::LightBlue); // Cobalt action
646 assert_eq!(nearest_ansi16(246, 196, 83), Color::LightYellow); // Signal Gold
647 assert_eq!(nearest_ansi16(79, 209, 197), Color::LightCyan); // Seafoam
648 assert_eq!(nearest_ansi16(38, 62, 92), Color::Blue); // Border
649 assert_eq!(nearest_ansi16(54, 187, 212), Color::LightCyan); // Aqua
650 assert_eq!(nearest_ansi16(255, 134, 178), Color::LightRed); // Rose danger
651 assert_eq!(nearest_ansi16(3, 7, 13), Color::Black); // Deep field
652 }
653
654 #[test]
655 fn rgb_to_ansi256_uses_stable_extended_palette() {
656 assert!(rgb_to_ansi256(53, 120, 229) >= 16);
657 assert!(rgb_to_ansi256(11, 21, 38) >= 16);
658 }
659
660 #[test]
661 fn color_depth_detect_is_safe_without_env() {
662 // Don't try to pin the result — env may be anything in CI. Just
663 // exercise the path so a panic would surface.
664 let _ = ColorDepth::detect();
665 let _ = adapt_color(WHALE_BG, ColorDepth::detect());
666 }
667
668 /// no-color.org contract (spec TIDELINE §5d gap): `NO_COLOR` present and
669 /// non-empty suppresses colors even on a truecolor terminal;
670 /// an empty value does not count.
671 #[test]
672 fn no_color_forces_the_mono_depth_even_on_truecolor() {
673 fn read(pairs: &[(&'static str, &'static str)]) -> impl Fn(&str) -> Option<std::ffi::OsString> {
674 move |key: &str| {
675 pairs
676 .iter()
677 .find(|(k, _)| *k == key)
678 .map(|(_, v)| std::ffi::OsString::from(v))
679 }
680 }
681 let depth = ColorDepth::detect_with(read(&[("NO_COLOR", "1"), ("COLORTERM", "truecolor")]));
682 assert_eq!(
683 depth,
684 ColorDepth::Monochrome,
685 "NO_COLOR wins over COLORTERM"
686 );
687 for color in [
688 Color::Reset,
689 Color::Red,
690 Color::Indexed(9),
691 Color::Rgb(103, 184, 214),
692 ] {
693 assert_eq!(adapt_color(color, depth), Color::Reset);
694 assert_eq!(adapt_bg(color, depth), Color::Reset);
695 }
696 assert!(reasoning_surface_tint(depth).is_none());
697 let depth = ColorDepth::detect_with(read(&[("NO_COLOR", ""), ("COLORTERM", "truecolor")]));
698 assert_eq!(
699 depth,
700 ColorDepth::TrueColor,
701 "empty NO_COLOR does not count (no-color.org)"
702 );
703 let depth = ColorDepth::detect_with(read(&[("COLORTERM", "truecolor")]));
704 assert_eq!(depth, ColorDepth::TrueColor, "no NO_COLOR: normal detect");
705 }
706
707 // === #4833: contrast floor ===
708
709 use super::contrast::{
710 AA_BODY_CONTRAST, contrast_ratio, effective_surface, enforce_contrast, meets_contrast,
711 relative_luminance, symbol_needs_text_contrast, theme_contrast_violations,
712 theme_uses_terminal_owned_surfaces,
713 };
714 use super::detect::TerminalBackground;
715 use super::osc11::{ProbeSplit, ProbeStep, parse_osc11_reply};
716 use super::tokens::{
717 MODE_OPERATE, STATUS_SUCCESS, TEXT_MUTED, TEXT_SECONDARY, TEXT_SOFT, USER_BODY,
718 };
719
720 const WHITE: Color = Color::Rgb(0xFF, 0xFF, 0xFF);
721 const BLACK: Color = Color::Rgb(0x00, 0x00, 0x00);
722
723 /// Every dark-palette token that renders *text*. Frame chrome (`BORDER_COLOR`)
724 /// is deliberately absent — see `symbol_needs_text_contrast`.
725 const DARK_TEXT_TOKENS: &[Color] = &[
726 TEXT_BODY,
727 TEXT_SOFT,
728 TEXT_SECONDARY,
729 TEXT_MUTED,
730 TEXT_HINT,
731 TEXT_REASONING,
732 TEXT_TOOL_OUTPUT,
733 USER_BODY,
734 WHALE_ACTION,
735 WHALE_LIVE,
736 WHALE_HUMAN,
737 WHALE_ERROR,
738 MODE_AGENT,
739 MODE_PLAN,
740 MODE_OPERATE,
741 MODE_YOLO,
742 STATUS_ERROR,
743 STATUS_WARNING,
744 STATUS_SUCCESS,
745 DIFF_ADDED,
746 ];
747
748 fn approx(actual: f32, expected: f32, tolerance: f32) {
749 assert!(
750 (actual - expected).abs() <= tolerance,
751 "expected {expected} ± {tolerance}, got {actual}"
752 );
753 }
754
755 #[test]
756 fn relative_luminance_matches_wcag_reference_values() {
757 approx(relative_luminance(WHITE).unwrap(), 1.0, 1e-4);
758 approx(relative_luminance(BLACK).unwrap(), 0.0, 1e-4);
759 // WCAG worked example: #808080 has relative luminance 0.2159.
760 approx(
761 relative_luminance(Color::Rgb(0x80, 0x80, 0x80)).unwrap(),
762 0.2159,
763 1e-3,
764 );
765 // Terminal-defined colors have no knowable RGB, so no luminance.
766 assert_eq!(relative_luminance(Color::Reset), None);
767 assert_eq!(relative_luminance(Color::White), None);
768 assert_eq!(relative_luminance(Color::Indexed(7)), None);
769 // The xterm cube and gray ramp are fixed by spec, so they are knowable.
770 assert!(relative_luminance(Color::Indexed(231)).is_some());
771 }
772
773 #[test]
774 fn contrast_ratio_matches_known_pairs() {
775 approx(contrast_ratio(BLACK, WHITE).unwrap(), 21.0, 1e-3);
776 approx(contrast_ratio(WHITE, WHITE).unwrap(), 1.0, 1e-4);
777 // #767676 on white is the canonical "smallest AA-passing gray".
778 approx(
779 contrast_ratio(Color::Rgb(0x76, 0x76, 0x76), WHITE).unwrap(),
780 4.54,
781 0.01,
782 );
783 // Symmetric in its arguments.
784 assert_eq!(
785 contrast_ratio(TEXT_BODY, WHALE_BG),
786 contrast_ratio(WHALE_BG, TEXT_BODY)
787 );
788 // An unknowable side yields no ratio, and `meets_contrast` refuses to call
789 // that a pass.
790 assert_eq!(contrast_ratio(TEXT_BODY, Color::Reset), None);
791 assert!(!meets_contrast(TEXT_BODY, Color::Reset, AA_BODY_CONTRAST));
792 }
793
794 #[test]
795 fn light_surface_lifts_body_text_that_no_whitelist_adapted() {
796 // The #4833 shape: dark-tuned ivory body text reaching a near-white
797 // terminal with no light adaptation applied, because detection said Dark.
798 let before = contrast_ratio(TEXT_BODY, WHITE).unwrap();
799 assert!(
800 before < AA_BODY_CONTRAST,
801 "precondition: unadapted body text is illegible on white ({before})"
802 );
803
804 let lifted = enforce_contrast(TEXT_BODY, WHITE, AA_BODY_CONTRAST);
805 let after = contrast_ratio(lifted, WHITE).unwrap();
806 assert!(
807 after >= AA_BODY_CONTRAST,
808 "body text must clear AA on a light surface, got {after}"
809 );
810
811 // The same holds for the reporter's paler surface and for the secondary
812 // tiers that collapsed alongside body text.
813 let reported_surface = Color::Rgb(0xF7, 0xF7, 0xF5);
814 for token in [TEXT_BODY, TEXT_SOFT, TEXT_SECONDARY, TEXT_HINT] {
815 let lifted = enforce_contrast(token, reported_surface, AA_BODY_CONTRAST);
816 let ratio = contrast_ratio(lifted, reported_surface).unwrap();
817 assert!(
818 ratio >= AA_BODY_CONTRAST,
819 "{token:?} still below floor on light surface: {ratio}"
820 );
821 }
822 }
823
824 #[test]
825 fn enforce_contrast_lifts_by_the_smallest_amount_that_clears_the_floor() {
826 let lifted = enforce_contrast(TEXT_BODY, WHITE, AA_BODY_CONTRAST);
827 let ratio = contrast_ratio(lifted, WHITE).unwrap();
828 assert!(
829 (AA_BODY_CONTRAST..AA_BODY_CONTRAST + 0.1).contains(&ratio),
830 "expected a minimal lift to ~{AA_BODY_CONTRAST}, got {ratio}"
831 );
832 // Already-compliant colors are returned byte-identical.
833 assert_eq!(
834 enforce_contrast(LIGHT_TEXT_BODY, WHITE, AA_BODY_CONTRAST),
835 LIGHT_TEXT_BODY
836 );
837 }
838
839 #[test]
840 fn dark_surface_leaves_every_text_token_untouched() {
841 // The no-regression guarantee for today's users: on the surfaces a dark
842 // terminal actually presents, no shipped text token is rewritten.
843 for surface in [
844 WHALE_BG,
845 WHALE_PANEL,
846 BLACK,
847 Color::Rgb(0x1E, 0x1E, 0x1E), // VS Code dark
848 Color::Rgb(0x0C, 0x0C, 0x0C), // Windows Terminal default
849 ] {
850 for token in DARK_TEXT_TOKENS {
851 assert_eq!(
852 enforce_contrast(*token, surface, AA_BODY_CONTRAST),
853 *token,
854 "{token:?} was rewritten on dark surface {surface:?}"
855 );
856 }
857 }
858 }
859
860 #[test]
861 fn light_theme_tokens_already_clear_the_floor_on_their_own_surfaces() {
862 for surface in [LIGHT_SURFACE, LIGHT_PANEL, LIGHT_ELEVATED] {
863 for token in [
864 LIGHT_TEXT_BODY,
865 LIGHT_TEXT_HINT,
866 LIGHT_ACTION,
867 LIGHT_LIVE,
868 LIGHT_HUMAN,
869 LIGHT_WARNING,
870 LIGHT_DANGER,
871 LIGHT_SUCCESS_FG,
872 ] {
873 let ratio = contrast_ratio(token, surface).unwrap();
874 assert!(
875 ratio >= AA_BODY_CONTRAST,
876 "{token:?} on {surface:?} is {ratio}, below the floor"
877 );
878 assert_eq!(enforce_contrast(token, surface, AA_BODY_CONTRAST), token);
879 }
880 }
881 }
882
883 #[test]
884 fn enforce_contrast_declines_when_it_cannot_know_the_colors() {
885 // Named/indexed colors are remapped by the user's terminal profile, and
886 // `Reset` is the terminal's own choice. Rewriting either would be a guess.
887 assert_eq!(
888 enforce_contrast(Color::White, WHITE, AA_BODY_CONTRAST),
889 Color::White
890 );
891 assert_eq!(
892 enforce_contrast(Color::Indexed(250), WHITE, AA_BODY_CONTRAST),
893 Color::Indexed(250)
894 );
895 assert_eq!(
896 enforce_contrast(TEXT_BODY, Color::Reset, AA_BODY_CONTRAST),
897 TEXT_BODY
898 );
899 // 4.5:1 is reachable from *every* surface — the worst case is the
900 // luminance where black and white tie, and even there the better pole
901 // clears 4.58:1. So the floor never silently gives up.
902 for gray in (0u8..=255).step_by(5) {
903 let surface = Color::Rgb(gray, gray, gray);
904 let lifted = enforce_contrast(TEXT_BODY, surface, AA_BODY_CONTRAST);
905 let ratio = contrast_ratio(lifted, surface).unwrap();
906 assert!(
907 ratio >= AA_BODY_CONTRAST,
908 "gray {gray:#04x} left body text at {ratio}:1"
909 );
910 }
911
912 // An unreachable floor (AAA on a mid-gray) returns the better pole rather
913 // than pretending it succeeded.
914 let mid = Color::Rgb(0x80, 0x80, 0x80);
915 assert_eq!(enforce_contrast(TEXT_BODY, mid, 7.0), BLACK);
916 }
917
918 #[test]
919 fn effective_surface_prefers_painted_background_then_measurement() {
920 // A painted cell knows its own surface.
921 assert_eq!(
922 effective_surface(WHALE_PANEL, Some(WHITE)),
923 Some(WHALE_PANEL)
924 );
925 // An unpainted cell falls through to what detection measured.
926 assert_eq!(effective_surface(Color::Reset, Some(WHITE)), Some(WHITE));
927 // With no measurement there is no surface — the floor stands down.
928 assert_eq!(effective_surface(Color::Reset, None), None);
929 // A measurement we cannot resolve is not a measurement.
930 assert_eq!(effective_surface(Color::Reset, Some(Color::Reset)), None);
931 }
932
933 #[test]
934 fn text_contrast_floor_applies_to_glyphs_not_frame_chrome() {
935 assert!(symbol_needs_text_contrast("a"));
936 assert!(symbol_needs_text_contrast("字"));
937 assert!(symbol_needs_text_contrast("→"));
938 assert!(!symbol_needs_text_contrast(" "));
939 assert!(!symbol_needs_text_contrast(""));
940 assert!(!symbol_needs_text_contrast("─"));
941 assert!(!symbol_needs_text_contrast("│"));
942 assert!(!symbol_needs_text_contrast("█"));
943 assert!(!symbol_needs_text_contrast("▏"));
944 assert!(!symbol_needs_text_contrast("●"));
945 }
946
947 #[test]
948 fn background_luminance_decides_polarity_without_a_color_list() {
949 assert_eq!(palette_mode_for_background(WHITE), Some(PaletteMode::Light));
950 assert_eq!(palette_mode_for_background(BLACK), Some(PaletteMode::Dark));
951 assert_eq!(
952 palette_mode_for_background(LIGHT_SURFACE),
953 Some(PaletteMode::Light)
954 );
955 assert_eq!(
956 palette_mode_for_background(SOLARIZED_SURFACE),
957 Some(PaletteMode::Light)
958 );
959 assert_eq!(
960 palette_mode_for_background(WHALE_BG),
961 Some(PaletteMode::Dark)
962 );
963 assert_eq!(
964 palette_mode_for_background(Color::Rgb(0x28, 0x2C, 0x34)),
965 Some(PaletteMode::Dark)
966 );
967 assert_eq!(palette_mode_for_background(Color::Reset), None);
968 }
969
970 #[test]
971 fn unknown_background_keeps_the_dark_default_and_offers_no_surface() {
972 let unknown = TerminalBackground::unknown();
973 assert_eq!(unknown.mode(), PaletteMode::Dark);
974 assert_eq!(unknown.color(), None);
975 assert_eq!(unknown.source(), BackgroundSource::Unknown);
976 // This is the #4833 trigger environment: a terminal that sets no
977 // COLORFGBG and is not macOS. Detection still answers Dark — but it says
978 // so with `Unknown` provenance and no color, so nothing downstream
979 // mistakes the guess for a measurement.
980 let resolved = resolve_terminal_background(None, None, None);
981 assert_eq!(resolved, unknown);
982 assert_eq!(effective_surface(Color::Reset, resolved.color()), None);
983 }
984
985 #[test]
986 fn measured_background_outranks_env_hints_and_records_provenance() {
987 // A white terminal that also exports a dark-looking COLORFGBG: the
988 // measurement wins, and it carries the color the floor needs.
989 let measured = resolve_terminal_background(Some((0xFF, 0xFF, 0xFF)), Some("15;0"), None);
990 assert_eq!(measured.mode(), PaletteMode::Light);
991 assert_eq!(measured.color(), Some(WHITE));
992 assert_eq!(measured.source(), BackgroundSource::Osc11);
993
994 // COLORFGBG with a resolvable xterm index yields a real color too.
995 let indexed = resolve_terminal_background(None, Some("0;231"), None);
996 assert_eq!(indexed.mode(), PaletteMode::Light);
997 assert_eq!(indexed.color(), Some(Color::Indexed(231)));
998 assert_eq!(indexed.source(), BackgroundSource::ColorFgBg);
999
1000 // Indices 0..=15 are terminal-profile defined: mode only, no color.
1001 let ansi = resolve_terminal_background(None, Some("0;15"), None);
1002 assert_eq!(ansi.mode(), PaletteMode::Light);
1003 assert_eq!(ansi.color(), None);
1004 assert_eq!(ansi.source(), BackgroundSource::ColorFgBg);
1005
1006 // macOS appearance describes the OS, not the terminal — no color.
1007 let macos = resolve_terminal_background(None, None, Some(PaletteMode::Light));
1008 assert_eq!(macos.mode(), PaletteMode::Light);
1009 assert_eq!(macos.color(), None);
1010 assert_eq!(macos.source(), BackgroundSource::MacOsAppearance);
1011 }
1012
1013 #[test]
1014 fn osc11_replies_parse_across_the_shapes_terminals_emit() {
1015 assert_eq!(
1016 parse_osc11_reply("\u{1b}]11;rgb:ffff/ffff/ffff"),
1017 Some((255, 255, 255))
1018 );
1019 assert_eq!(
1020 parse_osc11_reply("]11;rgb:0000/0000/0000\u{7}"),
1021 Some((0, 0, 0))
1022 );
1023 // 8-bit channels, and a mid value that must scale rather than truncate.
1024 assert_eq!(parse_osc11_reply("rgb:1e/1e/1e"), Some((30, 30, 30)));
1025 assert_eq!(
1026 parse_osc11_reply("rgb:8000/8000/8000"),
1027 Some((128, 128, 128))
1028 );
1029 assert_eq!(parse_osc11_reply("rgb:f/f/f"), Some((255, 255, 255)));
1030 // Hash forms.
1031 assert_eq!(parse_osc11_reply("]11;#282c34"), Some((0x28, 0x2C, 0x34)));
1032 assert_eq!(parse_osc11_reply("#fff"), Some((255, 255, 255)));
1033 // Anything we cannot read is `None`, never a fabricated color.
1034 assert_eq!(parse_osc11_reply(""), None);
1035 assert_eq!(parse_osc11_reply("\u{1b}]11;"), None);
1036 assert_eq!(parse_osc11_reply("rgb:ff/ff"), None);
1037 assert_eq!(parse_osc11_reply("rgb:ff/ff/ff/ff"), None);
1038 assert_eq!(parse_osc11_reply("rgb:zz/zz/zz"), None);
1039 assert_eq!(parse_osc11_reply("#ff00"), None);
1040 }
1041
1042 /// Drive a whole byte stream through the split the way the reader does,
1043 /// including the one-byte lookahead after an `ESC \` terminator.
1044 fn split_probe_stream(query: &[u8], stream: &[u8], csi: bool) -> (Vec<u8>, Vec<u8>) {
1045 let mut split = ProbeSplit::for_query(query, csi);
1046 let mut index = 0;
1047 while index < stream.len() {
1048 let byte = stream[index];
1049 index += 1;
1050 match split.feed(byte) {
1051 ProbeStep::Continue => {}
1052 ProbeStep::Done | ProbeStep::Overflow => break,
1053 ProbeStep::AwaitStringTerminator => {
1054 if let Some(next) = stream.get(index) {
1055 split.finish_string_terminator(*next);
1056 }
1057 break;
1058 }
1059 }
1060 }
1061 split.finish()
1062 }
1063
1064 #[test]
1065 fn a_probe_reply_never_swallows_the_line_typed_before_it() {
1066 // #5925: `/plugin install …` typed at launch arrived before the terminal
1067 // answered the OSC 11 query. The reply is ours; every other byte is the
1068 // user's and must come back out, in order.
1069 let (reply, carried) = split_probe_stream(
1070 b"\x1b]11;?\x1b\\",
1071 b"/plugin install /tmp/bundle\r\x1b]11;rgb:ffff/ffff/ffff\x1b\\",
1072 false,
1073 );
1074 assert_eq!(
1075 parse_osc11_reply(&String::from_utf8_lossy(&reply)),
1076 Some((255, 255, 255)),
1077 "the reply still parses"
1078 );
1079 assert_eq!(
1080 carried,
1081 b"/plugin install /tmp/bundle\r".to_vec(),
1082 "not one typed byte is consumed or reordered"
1083 );
1084 }
1085
1086 #[test]
1087 fn a_probe_that_is_never_answered_still_hands_back_what_was_typed() {
1088 let (reply, carried) = split_probe_stream(b"\x1b]11;?\x1b\\", b"/plugin list\r", false);
1089 assert!(reply.is_empty(), "no reply arrived");
1090 assert_eq!(carried, b"/plugin list\r".to_vec());
1091 }
1092
1093 #[test]
1094 fn an_escape_that_is_not_the_reply_is_the_users_keystroke() {
1095 // A bare `Esc`, then typing, then the real reply.
1096 let (reply, carried) = split_probe_stream(
1097 b"\x1b_Gi=31,s=1,v=1,a=q,t=d,f=24;AAAA\x1b\\",
1098 b"\x1bhi\x1b_Gi=31;OK\x1b\\",
1099 false,
1100 );
1101 assert_eq!(reply, b"\x1b_Gi=31;OK".to_vec());
1102 assert_eq!(carried, b"\x1bhi".to_vec());
1103 }
1104
1105 #[test]
1106 fn a_keystroke_after_the_string_terminator_escape_is_kept() {
1107 // The reply ends `ESC \`; if the byte after `ESC` is not `\` it belongs
1108 // to the user and must not vanish with the terminator.
1109 let (reply, carried) = split_probe_stream(b"\x1b]11;?\x1b\\", b"\x1b]11;rgb:0/0/0\x1bx", false);
1110 assert_eq!(reply, b"\x1b]11;rgb:0/0/0".to_vec());
1111 assert_eq!(carried, b"x".to_vec());
1112 }
1113
1114 #[test]
1115 fn a_da_reply_stops_at_its_final_byte_and_keeps_the_rest_of_the_line() {
1116 let (reply, carried) = split_probe_stream(b"\x1b[c", b"\x1b[?62;4c/plugin list\r", true);
1117 assert_eq!(reply, b"\x1b[?62;4c".to_vec());
1118 // Bytes after the DA reply were never read by the split; the reader
1119 // leaves them in the tty for the input pump.
1120 assert!(carried.is_empty(), "{carried:?}");
1121 }
1122
1123 #[test]
1124 fn measured_light_background_selects_the_light_theme_end_to_end() {
1125 // Detection → mode → theme: an OSC 11 answer of white must reach the
1126 // light UiTheme, which is what actually repaints the frame.
1127 let measured = resolve_terminal_background(Some((0xFA, 0xFA, 0xFA)), None, None);
1128 assert_eq!(UiTheme::for_mode(measured.mode()), LIGHT_UI_THEME);
1129 let dark = resolve_terminal_background(Some((0x1E, 0x1E, 0x1E)), None, None);
1130 assert_eq!(UiTheme::for_mode(dark.mode()), UI_THEME);
1131 }
1132
1133 // === #4813: cross-theme contrast audit ===
1134
1135 #[test]
1136 fn grayscale_background_roles_survive_direct_and_token_render_paths() {
1137 let theme = GRAYSCALE_UI_THEME;
1138 for (token, expected) in [
1139 (WHALE_BG, theme.surface_bg),
1140 (WHALE_PANEL, theme.panel_bg),
1141 (SURFACE_TOOL_ACTIVE, theme.elevated_bg),
1142 (SELECTION_BG, theme.selection_bg),
1143 (LIGHT_SELECTION_BG, theme.selection_bg),
1144 (SURFACE_REASONING, GRAYSCALE_REASONING),
1145 (DIFF_ADDED_BG, theme.diff_added_bg),
1146 (DIFF_DELETED_BG, theme.diff_deleted_bg),
1147 ] {
1148 let resolved = adapt_bg_for_palette_mode(token, PaletteMode::Grayscale);
1149 assert_eq!(resolved, expected, "token {token:?}");
1150 assert_eq!(
1151 adapt_bg_for_palette_mode(expected, PaletteMode::Grayscale),
1152 expected,
1153 "direct theme role {expected:?} must not be bucketed twice",
1154 );
1155 }
1156 }
1157
1158 #[test]
1159 fn rendered_workbench_selection_tracks_every_selectable_theme() {
1160 use ratatui::{
1161 buffer::Buffer,
1162 layout::Rect,
1163 style::{Modifier, Style},
1164 widgets::{Block, Paragraph, Widget},
1165 };
1166
1167 // Menus and Config paint legacy semantic tokens; the home/composer use
1168 // direct UiTheme roles. The final cell remap must make those surfaces
1169 // agree, including the selected row's padding, on every picker choice.
1170 for theme_id in SELECTABLE_THEMES {
1171 let theme = theme_id.ui_theme();
1172 for width in [40, 80] {
1173 let area = Rect::new(0, 0, width, 3);
1174 let mut buffer = Buffer::empty(area);
1175 Block::default()
1176 .style(Style::default().bg(WHALE_BG))
1177 .render(area, &mut buffer);
1178 Paragraph::new("Current workspace")
1179 .style(Style::default().fg(TEXT_BODY))
1180 .render(Rect::new(0, 0, width, 1), &mut buffer);
1181 Paragraph::new("> Recent session")
1182 .style(
1183 Style::default()
1184 .fg(super::tokens::SELECTION_TEXT)
1185 .bg(SELECTION_BG)
1186 .add_modifier(Modifier::BOLD),
1187 )
1188 .render(Rect::new(0, 1, width, 1), &mut buffer);
1189
1190 // The same two semantic adaptation stages as ColorCompatBackend,
1191 // before terminal-depth quantization or any contrast correction.
1192 for cell in &mut buffer.content {
1193 cell.fg = adapt_fg_for_theme(cell.fg, *theme_id, &theme);
1194 cell.bg = adapt_bg_for_theme(cell.bg, *theme_id, &theme);
1195 cell.fg = adapt_fg_for_palette_mode(cell.fg, cell.bg, theme.mode);
1196 cell.bg = adapt_bg_for_palette_mode(cell.bg, theme.mode);
1197 }
1198 assert_eq!(buffer[(0, 0)].fg, theme.text_body, "{} body", theme.name);
1199 assert_eq!(buffer[(0, 0)].bg, theme.surface_bg, "{} field", theme.name);
1200 for x in 0..width {
1201 let selected = &buffer[(x, 1)];
1202 assert_eq!(selected.fg, theme.text_body, "{} selected ink", theme.name);
1203 assert_eq!(selected.bg, theme.selection_bg, "{} selection", theme.name);
1204 assert!(selected.modifier.contains(Modifier::BOLD));
1205 }
1206 if let Some(ratio) =
1207 super::contrast::contrast_ratio(buffer[(0, 1)].fg, buffer[(0, 1)].bg)
1208 {
1209 assert!(ratio >= 4.5, "{} selected text: {ratio}", theme.name);
1210 }
1211 }
1212 }
1213 }
1214
1215 #[test]
1216 fn every_selectable_theme_clears_the_text_floor() {
1217 let mut terminal_owned = Vec::new();
1218 for theme_id in SELECTABLE_THEMES {
1219 let theme = theme_id.ui_theme();
1220 if theme_uses_terminal_owned_surfaces(&theme) {
1221 terminal_owned.push(theme_id.name());
1222 continue;
1223 }
1224 let violations = theme_contrast_violations(&theme);
1225 assert!(
1226 violations.is_empty(),
1227 "theme '{}' fails the contrast audit: {violations:?}",
1228 theme_id.name(),
1229 );
1230 }
1231 // System resolves to one member of the built-in Whale pair. Those Flat
1232 // shells and Terminal are intentionally host-owned; community themes stay
1233 // painted and therefore remain fully auditable here.
1234 assert_eq!(terminal_owned, ["system", "terminal", "dark", "light"]);
1235 }
1236
1237 #[test]
1238 fn terminal_native_theme_exemptions_are_explicit() {
1239 // Reset surfaces are terminal-defined, so the audit records zero
1240 // violations for those pairs. That is *not* a pass — unresolvable pairs
1241 // are skipped, never counted as clearing the floor. Deepsea's authored
1242 // RGB ramp is audited separately by the ocean tests.
1243 for theme in [TERMINAL_UI_THEME, UI_THEME, LIGHT_UI_THEME] {
1244 assert!(theme_uses_terminal_owned_surfaces(&theme));
1245 assert_eq!(theme.surface_bg, Color::Reset);
1246 assert!(theme_contrast_violations(&theme).is_empty());
1247 }
1248 // A painted community theme never gets the exemption.
1249 assert!(!theme_uses_terminal_owned_surfaces(&TOKYO_NIGHT_UI_THEME));
1250 }
1251
1252 #[test]
1253 fn high_contrast_grayscale_theme_clears_body_floor_on_every_surface() {
1254 // The picker tagline claims "Color-minimal high contrast" — hold the
1255 // grayscale theme to the full body-text floor on every surface, not the
1256 // 3:1 secondary-chrome floor.
1257 let theme = GRAYSCALE_UI_THEME;
1258 for fg in [theme.text_body, theme.text_soft, theme.text_muted] {
1259 for bg in [
1260 theme.surface_bg,
1261 theme.panel_bg,
1262 theme.composer_bg,
1263 theme.elevated_bg,
1264 ] {
1265 let ratio = contrast_ratio(fg, bg).expect("grayscale colors are all resolvable RGB");
1266 assert!(
1267 ratio >= AA_BODY_CONTRAST,
1268 "grayscale {fg:?} on {bg:?} is {ratio}:1, below the {AA_BODY_CONTRAST}:1 floor",
1269 );
1270 }
1271 }
1272 }
1273
1274 #[test]
1275 fn violation_report_names_pair_and_ratio() {
1276 let mut bad = TOKYO_NIGHT_UI_THEME;
1277 bad.text_muted = bad.surface_bg;
1278 let violations = theme_contrast_violations(&bad);
1279 // The muted-on-surface color fails against all four text surfaces.
1280 let muted_pairs: Vec<_> = violations
1281 .iter()
1282 .filter(|violation| violation.pair.starts_with("text_muted on "))
1283 .collect();
1284 assert_eq!(muted_pairs.len(), 4);
1285 let violation = violations
1286 .iter()
1287 .find(|violation| violation.pair == "text_muted on surface_bg")
1288 .expect("the report must name the failing pair");
1289 assert_eq!(violation.fg, bad.text_muted);
1290 assert_eq!(violation.bg, bad.surface_bg);
1291 // Identical colors sit at 1:1 — far under the floor the report carries.
1292 assert!(violation.ratio < 1.1);
1293 assert!(violation.ratio < violation.floor);
1294 assert_eq!(violation.floor, AA_BODY_CONTRAST);
1295 }
1296
1297 #[test]
1298 fn direct_field_paint_follows_the_terminal_owned_shell() {
1299 // Widgets that paint `bg(WHALE_BG)` directly follow the theme's shell
1300 // instead of laying a navy patch over the terminal's own ground.
1301 assert_eq!(
1302 adapt_bg_for_theme(WHALE_BG, ThemeId::Whale, &UI_THEME),
1303 Color::Reset
1304 );
1305 assert_eq!(
1306 adapt_bg_for_theme(WHALE_BG, ThemeId::WhaleLight, &LIGHT_UI_THEME),
1307 Color::Reset
1308 );
1309 // A user `background_color` override is the field for direct paints too.
1310 let custom = UI_THEME.with_background_color(Color::Rgb(1, 2, 3));
1311 assert_eq!(
1312 adapt_bg_for_theme(WHALE_BG, ThemeId::Whale, &custom),
1313 Color::Rgb(1, 2, 3)
1314 );
1315 // Semantic surfaces keep their paint on the whale pair.
1316 assert_eq!(
1317 adapt_bg_for_theme(SELECTION_BG, ThemeId::Whale, &UI_THEME),
1318 SELECTION_BG
1319 );
1320 }
1321
1321 lines RUST