rho-coding-agent 1.40.0

A lightweight agent harness inspired by Pi
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
use std::collections::HashMap;
use std::sync::{Mutex, OnceLock};

use ratatui::{
    style::{Color, Modifier, Style},
    text::Line,
};

use super::{
    markdown::HeadingLevel,
    theme_scheme::{
        self, is_terminal_theme_id, normalize_theme_id, resolve_fixed_scheme, ColorScheme, Rgb,
        TERMINAL_THEME_ID,
    },
    theme_terminal::{query_terminal_palette, AnsiColor, TerminalPalette},
};

#[path = "theme_diff.rs"]
mod theme_diff;

const USER_BACKGROUND_ALPHA: f32 = 0.10;
const NEUTRAL_TOOL_BACKGROUND_ALPHA: f32 = 0.10;
// Light/dark split for palette-derived chrome. Matches the existing block
// contrast threshold used by block_foreground.
const LIGHT_BACKGROUND_LUMINANCE: f32 = 0.55;
// Dim candidate band: stay muted and readable against the terminal background.
// 0.75 ≈ #c0c0c0 (above this, dark-bg dim collapses into body white).
const DIM_MAX_LUMINANCE_ON_DARK: f32 = 0.75;
// 0.12 ≈ #383838 (below this, dark-bg dim vanishes into the background).
const DIM_MIN_LUMINANCE_ON_DARK: f32 = 0.12;
// 0.45 rejects mid/light bright-black samples on light backgrounds.
const DIM_MAX_LUMINANCE_ON_LIGHT: f32 = 0.45;
// Minimum luminance gap so muted text neither matches the wash nor the body.
const DIM_CONTRAST_MARGIN: f32 = 0.08;
// Status/role ink (warning, success, ...) vs surface. Bright yellow on light
// surfaces is the usual failure; require a clear darker/lighter separation.
const ROLE_INK_MARGIN: f32 = 0.22;

/// Host terminal sample captured once at startup.
static TERMINAL_SAMPLE: OnceLock<TerminalPalette> = OnceLock::new();

/// Active theme selection (terminal-matched or a fixed scheme).
static THEME_STATE: Mutex<ThemeState> = Mutex::new(ThemeState::new());

/// Serializes tests that change or read the process-wide active theme.
///
/// The selection is global, so a test that switches themes rewrites the styles
/// another test is comparing against. Tests on either side of that hazard hold
/// this: the ones that call `Theme::apply_committed` or `Theme::preview`, and
/// the ones that build styled lines and later re-derive a style from the theme
/// to match them.
#[cfg(test)]
pub(super) fn theme_test_lock() -> std::sync::MutexGuard<'static, ()> {
    static LOCK: Mutex<()> = Mutex::new(());
    LOCK.lock().unwrap_or_else(|error| error.into_inner())
}

#[derive(Clone, Debug)]
struct ThemeState {
    /// Configured / committed theme id (`terminal`, `one-half-dark`, ...).
    committed_id: String,
    /// Id currently driving colors (may be a live picker preview).
    active_id: String,
    /// Fixed scheme when `active_id` is not terminal.
    active_scheme: Option<ColorScheme>,
    /// Bumps when active colors change so history cache rebuilds.
    generation: u64,
    /// Derived palette for the active colors. Style accessors run per span on
    /// render hot paths, so the blend/luminance work happens once per theme
    /// change instead of once per call.
    palette: Option<Palette>,
    /// Schemes retained from the open theme picker so preview/apply do not
    /// re-read custom theme files while browsing.
    picker_catalog: Option<HashMap<String, ColorScheme>>,
}

impl ThemeState {
    const fn new() -> Self {
        Self {
            committed_id: String::new(),
            active_id: String::new(),
            active_scheme: None,
            generation: 0,
            palette: None,
            picker_catalog: None,
        }
    }
}

impl Rgb {
    fn color(self) -> Color {
        Color::Rgb(self.red, self.green, self.blue)
    }

    /// True when this sample can serve as muted chrome against `background_luminance`.
    fn is_usable_dim(self, background_luminance: f32) -> bool {
        let luminance = self.luminance();
        if is_light_background(background_luminance) {
            luminance + DIM_CONTRAST_MARGIN < background_luminance
                && luminance < DIM_MAX_LUMINANCE_ON_LIGHT
        } else {
            (DIM_MIN_LUMINANCE_ON_DARK..=DIM_MAX_LUMINANCE_ON_DARK).contains(&luminance)
                && luminance >= background_luminance + DIM_CONTRAST_MARGIN
        }
    }
}

impl TerminalPalette {
    fn blended_background(&self, color: AnsiColor, alpha: f32) -> Option<BlockColor> {
        self.ansi.get(&color).map(|ansi| {
            let rgb = self.background.blend_toward(*ansi, alpha);
            BlockColor::from_rgb(rgb)
        })
    }

    fn dim_foreground(&self) -> Color {
        // Dim chrome comes from ANSI bright black (index 8), never white (index 7).
        // Terminal mode keeps named ANSI fallbacks so the host palette paints them.
        let background_luminance = self.background.luminance();
        let fallback = if is_light_background(background_luminance) {
            Color::Black
        } else {
            Color::DarkGray
        };
        self.ansi
            .get(&AnsiColor::BrightBlack)
            .copied()
            .filter(|rgb| rgb.is_usable_dim(background_luminance))
            .map_or(fallback, Rgb::color)
    }
}

/// Dim ink for a fixed RGB scheme. Never returns named ANSI fallbacks.
fn scheme_dim_foreground(scheme: &ColorScheme) -> Color {
    let background = scheme.background;
    let background_luminance = background.luminance();
    let candidates = [
        scheme_ansi(scheme, AnsiColor::BrightBlack),
        scheme.ansi[0], // black (ANSI 0 has no AnsiColor variant)
        scheme.foreground,
    ];
    for candidate in candidates {
        if candidate.is_usable_dim(background_luminance) {
            return candidate.color();
        }
    }
    // Last resort: pull foreground toward the surface so chrome stays muted.
    background.blend_toward(scheme.foreground, 0.55).color()
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct BlockColor {
    color: Color,
    rgb: Option<Rgb>,
}

impl BlockColor {
    fn from_rgb(rgb: Rgb) -> Self {
        Self {
            color: rgb.color(),
            rgb: Some(rgb),
        }
    }

    const fn from_color(color: Color) -> Self {
        Self { color, rgb: None }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Palette {
    /// Body text. `None` keeps the host default foreground (terminal theme).
    text: Option<Color>,
    /// Full-screen surface. `None` keeps the host default background.
    surface: Option<Color>,
    dim: Color,
    accent: Color,
    success: Color,
    warning: Color,
    error: Color,
    skill: Color,
    user_background: BlockColor,
    neutral_tool_background: BlockColor,
    /// Add-side row wash. Absent without sampled RGB.
    diff_add_wash: Option<BlockColor>,
    /// Delete-side row wash. Absent without sampled RGB.
    diff_del_wash: Option<BlockColor>,
}

impl Palette {
    fn current() -> Self {
        let mut state = THEME_STATE
            .lock()
            .unwrap_or_else(|error| error.into_inner());
        if let Some(palette) = state.palette {
            return palette;
        }
        let palette = match state.active_scheme.as_ref() {
            Some(scheme) => Self::from_scheme(scheme),
            None => Self::from_terminal(TERMINAL_SAMPLE.get()),
        };
        state.palette = Some(palette);
        palette
    }

    fn from_terminal(terminal: Option<&TerminalPalette>) -> Self {
        let surface = terminal.map(|palette| palette.background);
        let (diff_add_wash, diff_del_wash) = theme_diff::terminal_diff_washes(terminal);
        Self {
            text: None,
            surface: None,
            dim: terminal.map_or(Color::DarkGray, TerminalPalette::dim_foreground),
            // Prefer sampled RGB when the host answered palette queries so brand,
            // version, and status colors track the real terminal theme instead of
            // generic named ANSI (which often looks "hardcoded").
            accent: role_ink(sampled_or_named(terminal, AnsiColor::Cyan), surface),
            success: role_ink(sampled_or_named(terminal, AnsiColor::Green), surface),
            warning: role_ink(sampled_or_named(terminal, AnsiColor::Yellow), surface),
            error: role_ink(sampled_or_named(terminal, AnsiColor::Red), surface),
            skill: role_ink(sampled_or_named(terminal, AnsiColor::Magenta), surface),
            user_background: blended_or_fallback(
                terminal,
                AnsiColor::White,
                USER_BACKGROUND_ALPHA,
                BlockColor::from_color(Color::DarkGray),
            ),
            // Same blend recipe as user prompts today; keep a dedicated field so
            // tool chrome can diverge later without rewriting call sites.
            neutral_tool_background: blended_or_fallback(
                terminal,
                AnsiColor::White,
                NEUTRAL_TOOL_BACKGROUND_ALPHA,
                BlockColor::from_color(Color::DarkGray),
            ),
            diff_add_wash,
            diff_del_wash,
        }
    }

    fn from_scheme(scheme: &ColorScheme) -> Self {
        let panel = scheme_panel_background(scheme);
        let surface = scheme.background;
        let (diff_add_wash, diff_del_wash) = theme_diff::scheme_diff_washes(scheme);
        Self {
            text: Some(scheme.foreground.color()),
            surface: Some(scheme.background.color()),
            dim: scheme_dim_foreground(scheme),
            accent: role_ink(scheme_ansi(scheme, AnsiColor::Cyan).color(), Some(surface)),
            success: role_ink(scheme_ansi(scheme, AnsiColor::Green).color(), Some(surface)),
            warning: role_ink(
                scheme_ansi(scheme, AnsiColor::Yellow).color(),
                Some(surface),
            ),
            error: role_ink(scheme_ansi(scheme, AnsiColor::Red).color(), Some(surface)),
            skill: role_ink(
                scheme_ansi(scheme, AnsiColor::Magenta).color(),
                Some(surface),
            ),
            user_background: panel,
            neutral_tool_background: panel,
            diff_add_wash,
            diff_del_wash,
        }
    }
}

/// Soft panel wash: blend dark ink into light surfaces, light ink into dark ones.
fn scheme_panel_background(scheme: &ColorScheme) -> BlockColor {
    let background = scheme.background;
    let wash = if is_light_background(background.luminance()) {
        scheme.ansi[0] // black
    } else {
        scheme_ansi(scheme, AnsiColor::White)
    };
    BlockColor::from_rgb(background.blend_toward(wash, USER_BACKGROUND_ALPHA))
}

fn scheme_ansi(scheme: &ColorScheme, color: AnsiColor) -> Rgb {
    scheme.ansi[color.index() as usize]
}

/// Sampled host RGB when available, else the named ANSI fallback.
fn sampled_or_named(terminal: Option<&TerminalPalette>, color: AnsiColor) -> Color {
    terminal
        .and_then(|palette| palette.ansi.get(&color).copied())
        .map(Rgb::color)
        .unwrap_or_else(|| color.color())
}

/// Make role ink readable as text on the UI surface.
///
/// Keeps the hue family (yellow stays warm, red stays red) but pulls bright
/// inks darker on light surfaces and invisible dark inks lighter on dark ones.
/// Named ANSI colors pass through unchanged so the host can still paint them.
fn role_ink(ink: Color, surface: Option<Rgb>) -> Color {
    let Color::Rgb(red, green, blue) = ink else {
        return ink;
    };
    let Some(surface) = surface else {
        return ink;
    };
    let ink = Rgb::new(red, green, blue);
    let surface_luminance = surface.luminance();
    let ink_luminance = ink.luminance();

    if is_light_background(surface_luminance) {
        // Light UI: role text must sit clearly below the surface luminance.
        if ink_luminance + ROLE_INK_MARGIN <= surface_luminance {
            return ink.color();
        }
        return pull_ink_until(ink, Rgb::new(0, 0, 0), |candidate| {
            candidate.luminance() + ROLE_INK_MARGIN <= surface_luminance
        });
    }

    // Dark UI: keep any ink already brighter than the surface; only lift
    // colors that disappear into the background.
    if ink_luminance > surface_luminance {
        return ink.color();
    }
    pull_ink_until(ink, Rgb::new(255, 255, 255), |candidate| {
        candidate.luminance() > surface_luminance
    })
}

fn pull_ink_until(start: Rgb, target: Rgb, acceptable: impl Fn(Rgb) -> bool) -> Color {
    if acceptable(start) {
        return start.color();
    }
    let mut best = start.blend_toward(target, 0.95);
    for alpha in [0.25_f32, 0.4, 0.55, 0.7, 0.85, 0.95] {
        let candidate = start.blend_toward(target, alpha);
        if acceptable(candidate) {
            return candidate.color();
        }
        best = candidate;
    }
    best.color()
}

/// Color for an ANSI role under the active theme.
fn active_ansi_color(color: AnsiColor) -> Color {
    let state = THEME_STATE
        .lock()
        .unwrap_or_else(|error| error.into_inner());
    if let Some(scheme) = state.active_scheme.as_ref() {
        return scheme_ansi(scheme, color).color();
    }
    sampled_or_named(TERMINAL_SAMPLE.get(), color)
}

/// Syntax-highlighting roles for code fences and diff bodies. The highlighter
/// maps syntect scopes onto these; the theme maps them onto the palette.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum SyntaxRole {
    Comment,
    String,
    Constant,
    Keyword,
    Function,
    Type,
}

pub(super) struct Theme;

impl Theme {
    pub(super) fn initialize_from_terminal() {
        if let Some(palette) = query_terminal_palette() {
            let _ = TERMINAL_SAMPLE.set(palette);
            // The sample feeds the terminal-mode palette; drop any derived
            // palette computed before the sample landed.
            THEME_STATE
                .lock()
                .unwrap_or_else(|error| error.into_inner())
                .palette = None;
        }
    }

    /// Retain fixed schemes from the open theme picker so preview uses them
    /// directly instead of re-resolving custom files on each row change.
    pub(super) fn set_picker_catalog(entries: &[theme_scheme::ThemeEntry]) {
        let mut catalog = HashMap::new();
        for entry in entries {
            if let theme_scheme::ThemeEntry::Fixed(scheme) = entry {
                catalog.insert(scheme.id.clone(), scheme.clone());
            }
        }
        THEME_STATE
            .lock()
            .unwrap_or_else(|error| error.into_inner())
            .picker_catalog = Some(catalog);
    }

    pub(super) fn clear_picker_catalog() {
        THEME_STATE
            .lock()
            .unwrap_or_else(|error| error.into_inner())
            .picker_catalog = None;
    }

    /// Apply the committed config theme (startup and after successful apply).
    pub(super) fn apply_committed(id: &str) {
        apply_theme_id(id, /*commit*/ true);
    }

    /// Live preview while browsing the theme picker. Does not change commit.
    /// Prefers schemes retained in the picker catalog.
    pub(super) fn preview(id: &str) {
        apply_theme_id(id, /*commit*/ false);
    }

    /// Abandon a live preview and restore the last committed theme.
    pub(super) fn cancel_preview() {
        let id = {
            let state = THEME_STATE
                .lock()
                .unwrap_or_else(|error| error.into_inner());
            if state.active_id == state.committed_id {
                return;
            }
            normalize_theme_id(&state.committed_id)
        };
        apply_theme_id(&id, /*commit*/ false);
    }

    pub(super) fn committed_id() -> String {
        let id = THEME_STATE
            .lock()
            .unwrap_or_else(|error| error.into_inner())
            .committed_id
            .clone();
        normalize_theme_id(&id)
    }

    pub(super) fn active_id() -> String {
        let id = THEME_STATE
            .lock()
            .unwrap_or_else(|error| error.into_inner())
            .active_id
            .clone();
        normalize_theme_id(&id)
    }

    /// Cache key: changes when the active palette changes.
    pub(super) fn generation() -> u64 {
        THEME_STATE
            .lock()
            .unwrap_or_else(|error| error.into_inner())
            .generation
    }

    /// Full-frame / popup base style. Fixed schemes set fg+bg; terminal leaves host defaults.
    pub(super) fn surface() -> Style {
        let palette = Palette::current();
        let mut style = Style::default().remove_modifier(Modifier::UNDERLINED);
        if let Some(fg) = palette.text {
            style = style.fg(fg);
        }
        if let Some(bg) = palette.surface {
            style = style.bg(bg);
        }
        style
    }

    /// Ink that contrasts with a solid fill (RGB under fixed themes).
    pub(super) fn contrasting_ink_on(background: Color) -> Color {
        match background {
            Color::Rgb(red, green, blue) => block_foreground(Some(Rgb::new(red, green, blue))),
            Color::White | Color::Gray | Color::Yellow => Color::Black,
            _ => Color::White,
        }
    }

    pub(super) fn text() -> Style {
        let mut style = Style::default().remove_modifier(Modifier::UNDERLINED);
        if let Some(fg) = Palette::current().text {
            style = style.fg(fg);
        }
        style
    }

    pub(super) fn text_strong() -> Style {
        Self::text().add_modifier(Modifier::BOLD)
    }

    pub(super) fn dim() -> Style {
        Style::default().fg(Palette::current().dim)
    }

    pub(super) fn dim_italic() -> Style {
        Self::dim().add_modifier(Modifier::ITALIC)
    }

    pub(super) fn accent() -> Style {
        Style::default().fg(Palette::current().accent)
    }

    pub(super) fn brand() -> Style {
        Self::accent().add_modifier(Modifier::BOLD)
    }

    pub(super) fn activity_rail() -> Style {
        let background = Palette::current().neutral_tool_background;
        Style::reset()
            .fg(block_foreground(background.rgb))
            .bg(background.color)
    }

    pub(super) fn jump_to_bottom() -> Style {
        Self::activity_rail().fg(Palette::current().accent)
    }

    pub(super) fn jump_to_bottom_shortcut() -> Style {
        Self::activity_rail().fg(Palette::current().dim)
    }

    pub(super) fn subagent_row(state: super::subagent_panel::SubagentRowState) -> Style {
        use super::subagent_panel::SubagentRowState;
        match state {
            SubagentRowState::Idle => Self::activity_rail(),
            SubagentRowState::Hovered => Self::activity_rail().fg(Palette::current().accent),
            SubagentRowState::Pressed => {
                let accent = Palette::current().accent;
                Style::default()
                    .fg(Self::contrasting_ink_on(accent))
                    .bg(accent)
                    .add_modifier(Modifier::BOLD)
            }
        }
    }

    pub(super) fn success() -> Style {
        Style::default()
            .fg(Palette::current().success)
            .add_modifier(Modifier::BOLD)
    }

    pub(super) fn warning() -> Style {
        Style::default()
            .fg(Palette::current().warning)
            .add_modifier(Modifier::BOLD)
    }

    pub(super) fn error() -> Style {
        Style::default()
            .fg(Palette::current().error)
            .add_modifier(Modifier::BOLD)
    }

    pub(super) fn input_prompt() -> Style {
        Style::default()
            .fg(Palette::current().accent)
            .add_modifier(Modifier::BOLD)
    }

    pub(super) fn user_message() -> Style {
        Self::dim_block(Palette::current().user_background)
    }

    pub(super) fn reasoning_output(lines: &mut [Line<'static>]) {
        let reasoning_style = Self::dim();
        for line in lines {
            line.style = reasoning_style
                .patch(line.style)
                .remove_modifier(Modifier::DIM);
            for span in &mut line.spans {
                span.style = reasoning_style
                    .patch(span.style)
                    .remove_modifier(Modifier::DIM);
            }
        }
    }

    pub(super) fn reasoning_input_border(level: rho_providers::reasoning::ReasoningLevel) -> Style {
        let color = match level {
            rho_providers::reasoning::ReasoningLevel::Off => return Theme::dim(),
            rho_providers::reasoning::ReasoningLevel::Minimal => active_ansi_color(AnsiColor::Blue),
            rho_providers::reasoning::ReasoningLevel::Low => active_ansi_color(AnsiColor::Cyan),
            rho_providers::reasoning::ReasoningLevel::Medium => active_ansi_color(AnsiColor::Green),
            rho_providers::reasoning::ReasoningLevel::High => active_ansi_color(AnsiColor::Yellow),
            rho_providers::reasoning::ReasoningLevel::Xhigh => {
                active_ansi_color(AnsiColor::Magenta)
            }
            rho_providers::reasoning::ReasoningLevel::Max => active_ansi_color(AnsiColor::Red),
        };
        Style::default().fg(color)
    }

    pub(super) fn markdown_heading(level: HeadingLevel) -> Style {
        let color = match level {
            HeadingLevel::H1 => active_ansi_color(AnsiColor::Magenta),
            HeadingLevel::H2 => active_ansi_color(AnsiColor::Blue),
            HeadingLevel::H3 => active_ansi_color(AnsiColor::Cyan),
            HeadingLevel::H4 => active_ansi_color(AnsiColor::Green),
            HeadingLevel::H5 => active_ansi_color(AnsiColor::Yellow),
            HeadingLevel::H6 => active_ansi_color(AnsiColor::BrightBlack),
        };
        let style = Style::default()
            .fg(color)
            .remove_modifier(Modifier::UNDERLINED);
        match level {
            HeadingLevel::H1 | HeadingLevel::H2 | HeadingLevel::H3 => {
                style.add_modifier(Modifier::BOLD)
            }
            HeadingLevel::H4 | HeadingLevel::H5 | HeadingLevel::H6 => style,
        }
    }

    pub(super) fn markdown_inline_code() -> Style {
        Style::default()
            .fg(Palette::current().warning)
            .remove_modifier(Modifier::UNDERLINED)
    }

    /// Plain style for code, Mermaid, and math content (not chrome).
    pub(super) fn code_text() -> Style {
        // Match assistant body text so source reads as content rather than
        // accent-colored chrome.
        Self::text()
    }

    /// Style for one syntax-highlighting role.
    /// Colors track the active ANSI palette so every theme, including
    /// terminal-sampled ones, keeps highlighted code readable.
    pub(super) fn syntax(role: SyntaxRole) -> Style {
        let color = match role {
            SyntaxRole::Comment => active_ansi_color(AnsiColor::BrightBlack),
            SyntaxRole::String => active_ansi_color(AnsiColor::Green),
            SyntaxRole::Constant => active_ansi_color(AnsiColor::Magenta),
            SyntaxRole::Keyword => active_ansi_color(AnsiColor::Blue),
            SyntaxRole::Function => active_ansi_color(AnsiColor::Yellow),
            SyntaxRole::Type => active_ansi_color(AnsiColor::Cyan),
        };
        Style::default()
            .fg(color)
            .remove_modifier(Modifier::UNDERLINED)
    }

    /// Grep/search match overlay on top of plain or syntax-colored text.
    ///
    /// Keeps the underlying foreground when present, adds a warning-tinted
    /// background and bold so hits stay visible without erasing language roles.
    pub(super) fn search_match(base: Style) -> Style {
        let palette = Palette::current();
        let bg = palette.warning;
        base.bg(bg)
            .fg(Self::contrasting_ink_on(bg))
            .add_modifier(Modifier::BOLD)
            .remove_modifier(Modifier::UNDERLINED)
    }

    pub(super) fn markdown_code_copy_button(hovered: bool) -> Style {
        let palette = Palette::current();
        if hovered {
            Style::default()
                .fg(Self::contrasting_ink_on(palette.accent))
                .bg(palette.accent)
                .add_modifier(Modifier::BOLD)
        } else {
            Self::dim_block(palette.neutral_tool_background).add_modifier(Modifier::BOLD)
        }
    }

    pub(super) fn markdown_bold() -> Style {
        Self::text()
            .add_modifier(Modifier::BOLD)
            .remove_modifier(Modifier::UNDERLINED)
    }

    pub(super) fn markdown_italic() -> Style {
        Self::text()
            .add_modifier(Modifier::ITALIC)
            .remove_modifier(Modifier::UNDERLINED)
    }

    pub(super) fn markdown_link() -> Style {
        Style::default()
            .fg(Palette::current().accent)
            .add_modifier(Modifier::UNDERLINED)
    }

    pub(super) fn command_block() -> Style {
        Self::dim_block(Palette::current().neutral_tool_background)
    }

    /// Status marker color for Call + Children tool cards.
    pub(super) fn tool_marker(status: rho_tools::tool_card::ToolStatus) -> Style {
        use rho_tools::tool_card::ToolStatus;
        match status {
            ToolStatus::Running => Self::accent(),
            ToolStatus::Ok => Self::success(),
            ToolStatus::Error => Self::error(),
            ToolStatus::Interrupted => Self::warning(),
        }
    }

    /// Family color for the tool verb / shell prompt.
    pub(super) fn tool_verb(family: rho_tools::tool_card::ToolFamily) -> Style {
        use rho_tools::tool_card::ToolFamily;
        let palette = Palette::current();
        match family {
            ToolFamily::FileCommand | ToolFamily::FileDiff => Style::default().fg(palette.success),
            ToolFamily::Web => Style::default().fg(active_ansi_color(AnsiColor::Blue)),
            ToolFamily::Skill => Style::default().fg(palette.skill),
            ToolFamily::Form => Style::default().fg(palette.warning),
            ToolFamily::Agent => Self::text(),
            ToolFamily::Default => Self::dim(),
        }
    }

    /// Primary argument style in the header.
    pub(super) fn tool_primary() -> Style {
        Self::text()
    }

    pub(super) fn tool_tree() -> Style {
        Self::dim()
    }

    pub(super) fn tool_meta() -> Style {
        Self::dim()
    }

    pub(super) fn tool_path() -> Style {
        Self::dim()
    }

    pub(super) fn tool_stat_add() -> Style {
        Style::default().fg(Palette::current().success)
    }

    pub(super) fn tool_stat_del() -> Style {
        Style::default().fg(Palette::current().error)
    }

    /// Line-number gutter. The sign carries the change, so numbers stay chrome.
    pub(super) fn tool_diff_gutter() -> Style {
        Self::dim()
    }

    pub(super) fn tool_exit(status: rho_tools::tool_card::ToolStatus) -> Style {
        use rho_tools::tool_card::ToolStatus;
        match status {
            ToolStatus::Ok | ToolStatus::Running => Self::success(),
            ToolStatus::Error | ToolStatus::Interrupted => Self::error(),
        }
    }

    pub(super) fn tool_error_text() -> Style {
        Self::error()
    }

    /// Explicit padding style for tool cards (never sample the marker span).
    pub(super) fn tool_card_padding() -> Style {
        Self::text()
    }

    fn dim_block(background: BlockColor) -> Style {
        Style::default()
            .fg(block_foreground(background.rgb))
            .bg(background.color)
    }
}

fn apply_theme_id(id: &str, commit: bool) {
    let id = normalize_theme_id(id);
    let mut state = THEME_STATE
        .lock()
        .unwrap_or_else(|error| error.into_inner());
    let scheme = if is_terminal_theme_id(&id) {
        None
    } else if let Some(scheme) = state
        .picker_catalog
        .as_ref()
        .and_then(|catalog| catalog.get(&id).cloned())
    {
        // Prefer the scheme already loaded into the open picker catalog.
        Some(scheme)
    } else {
        // Unknown id falls back to terminal so a bad config never blanks the UI.
        // Drop the lock while resolving from disk.
        drop(state);
        let scheme = resolve_fixed_scheme(&id);
        state = THEME_STATE
            .lock()
            .unwrap_or_else(|error| error.into_inner());
        scheme
    };
    let resolved_id = if scheme.is_none() {
        TERMINAL_THEME_ID.to_string()
    } else {
        id
    };

    let changed = state.active_id != resolved_id
        || state.active_scheme.as_ref().map(|s| s.id.as_str())
            != scheme.as_ref().map(|s| s.id.as_str());
    if commit {
        state.committed_id = resolved_id.clone();
    }
    if changed {
        state.active_id = resolved_id;
        state.active_scheme = scheme;
        state.generation = state.generation.saturating_add(1);
        state.palette = None;
    }
}

// Re-export catalog helpers used by the picker and config layers.
pub(super) use theme_scheme::{
    list_themes, theme_display_name, ThemeEntry, TERMINAL_THEME_ID as THEME_TERMINAL_ID,
};

fn block_foreground(background: Option<Rgb>) -> Color {
    let on_light = background.is_some_and(|rgb| is_light_background(rgb.luminance()));
    let state = THEME_STATE
        .lock()
        .unwrap_or_else(|error| error.into_inner());
    if let Some(scheme) = state.active_scheme.as_ref() {
        let fg = scheme.foreground;
        let bg = scheme.background;
        // Prefer the scheme ink that actually contrasts with the panel wash.
        return if on_light {
            if fg.luminance() <= bg.luminance() {
                fg.color()
            } else {
                bg.color()
            }
        } else if fg.luminance() >= bg.luminance() {
            fg.color()
        } else {
            bg.color()
        };
    }
    if on_light {
        Color::Black
    } else {
        Color::White
    }
}

fn is_light_background(luminance: f32) -> bool {
    luminance > LIGHT_BACKGROUND_LUMINANCE
}

fn blended_or_fallback(
    terminal: Option<&TerminalPalette>,
    color: AnsiColor,
    alpha: f32,
    fallback: BlockColor,
) -> BlockColor {
    optional_blended(terminal, color, alpha).unwrap_or(fallback)
}

fn optional_blended(
    terminal: Option<&TerminalPalette>,
    color: AnsiColor,
    alpha: f32,
) -> Option<BlockColor> {
    terminal.and_then(|palette| palette.blended_background(color, alpha))
}

#[cfg(test)]
#[path = "theme_tests.rs"]
mod tests;