sbom-tools 0.2.0

Semantic SBOM diff and analysis tool
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
//! Hierarchical tree widget for component navigation.

use crate::tui::theme::colors;
use ratatui::{
    prelude::*,
    widgets::{Block, Scrollbar, ScrollbarOrientation, ScrollbarState, StatefulWidget, Widget},
};
use std::collections::HashSet;
use unicode_width::UnicodeWidthStr;

/// A node in the component tree.
#[derive(Debug, Clone)]
pub enum TreeNode {
    /// A group node (ecosystem, namespace, etc.)
    Group {
        id: String,
        label: String,
        children: Vec<Self>,
        item_count: usize,
        vuln_count: usize,
    },
    /// A leaf component node
    Component {
        id: String,
        name: String,
        version: Option<String>,
        vuln_count: usize,
        /// Maximum severity level of vulnerabilities (critical/high/medium/low)
        max_severity: Option<String>,
        /// Component type indicator (library, binary, file, etc.)
        component_type: Option<String>,
        /// Ecosystem (npm, pypi, etc.) for display tag
        ecosystem: Option<String>,
        /// Whether this component is bookmarked by the user
        is_bookmarked: bool,
    },
}

impl TreeNode {
    pub(crate) fn id(&self) -> &str {
        match self {
            Self::Group { id, .. } | Self::Component { id, .. } => id,
        }
    }

    pub(crate) fn label(&self) -> String {
        match self {
            Self::Group {
                label, item_count, ..
            } => format!("{label} ({item_count})"),
            Self::Component {
                name,
                version,
                ecosystem,
                is_bookmarked,
                ..
            } => {
                let display_name = extract_display_name(name);
                let mut result = if let Some(v) = version {
                    format!("{display_name}@{v}")
                } else {
                    display_name
                };
                // Append ecosystem tag if present and not "Unknown"
                if let Some(eco) = ecosystem
                    && eco != "Unknown"
                {
                    use std::fmt::Write;
                    let _ = write!(result, " [{eco}]");
                }
                // Prepend bookmark star
                if *is_bookmarked {
                    result = format!("\u{2605} {result}");
                }
                result
            }
        }
    }

    pub(crate) const fn vuln_count(&self) -> usize {
        match self {
            Self::Group { vuln_count, .. } | Self::Component { vuln_count, .. } => *vuln_count,
        }
    }

    pub(crate) fn max_severity(&self) -> Option<&str> {
        match self {
            Self::Component { max_severity, .. } => max_severity.as_deref(),
            Self::Group { .. } => None,
        }
    }

    pub(crate) const fn is_group(&self) -> bool {
        matches!(self, Self::Group { .. })
    }

    pub(crate) fn children(&self) -> Option<&[Self]> {
        match self {
            Self::Group { children, .. } => Some(children),
            Self::Component { .. } => None,
        }
    }
}

/// Extract a meaningful display name from a component path
pub fn extract_display_name(name: &str) -> String {
    // If it's a clean package name (no path separators, reasonable length), use it as-is
    if !name.contains('/') && !name.starts_with('.') && name.len() <= 40 {
        return name.to_string();
    }

    // Extract the meaningful part from a path
    if let Some(filename) = name.rsplit('/').next() {
        // Clean up common suffixes
        let clean = filename
            .trim_end_matches(".squashfs")
            .trim_end_matches(".squ")
            .trim_end_matches(".img")
            .trim_end_matches(".bin")
            .trim_end_matches(".unknown")
            .trim_end_matches(".crt")
            .trim_end_matches(".so")
            .trim_end_matches(".a")
            .trim_end_matches(".elf32");

        // If the remaining name is a hash-like string, try to get parent directory context
        if is_hash_like(clean) {
            // Try to find a meaningful parent directory
            let parts: Vec<&str> = name.split('/').collect();
            if parts.len() >= 2 {
                for part in parts.iter().rev().skip(1) {
                    if !part.is_empty()
                        && !part.starts_with('.')
                        && !is_hash_like(part)
                        && part.len() > 2
                    {
                        return format!("{part}/{filename}");
                    }
                }
            }
            return filename.to_string();
        }

        return clean.to_string();
    }

    name.to_string()
}

/// Check if a name looks like a hash (hex digits and dashes)
fn is_hash_like(name: &str) -> bool {
    if name.len() < 8 {
        return false;
    }
    let clean = name.replace(['-', '_'], "");
    clean.chars().all(|c| c.is_ascii_hexdigit())
        || (clean.chars().filter(char::is_ascii_digit).count() > clean.len() / 2)
}

/// Get component type from path/name
pub fn detect_component_type(name: &str) -> &'static str {
    let lower = name.to_lowercase();
    let ext = std::path::Path::new(&lower)
        .extension()
        .and_then(|e| e.to_str())
        .unwrap_or("");

    if matches!(ext, "so") || lower.contains(".so.") {
        return "lib";
    }
    if matches!(ext, "a") {
        return "lib";
    }
    if matches!(ext, "crt" | "pem" | "key") {
        return "cert";
    }
    if matches!(ext, "img" | "bin" | "elf" | "elf32") {
        return "bin";
    }
    if matches!(ext, "squashfs" | "squ") {
        return "fs";
    }
    if matches!(ext, "unknown") {
        return "unk";
    }
    if lower.contains("lib") {
        return "lib";
    }

    "file"
}

/// Get a human-readable label for a detected component type code.
///
/// Returns `None` for generic types ("file") where the label adds no value
/// over the SBOM `ComponentType`.
pub fn detect_component_label(name: &str) -> Option<&'static str> {
    match detect_component_type(name) {
        "lib" => Some("Shared library"),
        "bin" => Some("Binary / ELF"),
        "cert" => Some("Certificate"),
        "fs" => Some("Filesystem image"),
        "unk" => Some("Unknown format"),
        _ => None,
    }
}

/// State for the tree widget.
#[derive(Debug, Clone, Default)]
pub struct TreeState {
    /// Currently selected node index in flattened view
    pub selected: usize,
    /// Set of expanded node IDs
    pub expanded: HashSet<String>,
    /// Scroll offset
    pub offset: usize,
    /// Total visible items
    pub visible_count: usize,
}

impl TreeState {
    pub(crate) fn new() -> Self {
        Self::default()
    }

    pub(crate) fn toggle_expand(&mut self, node_id: &str) {
        if self.expanded.contains(node_id) {
            self.expanded.remove(node_id);
        } else {
            self.expanded.insert(node_id.to_string());
        }
    }

    pub(crate) fn expand(&mut self, node_id: &str) {
        self.expanded.insert(node_id.to_string());
    }

    pub(crate) fn collapse(&mut self, node_id: &str) {
        self.expanded.remove(node_id);
    }

    pub(crate) fn is_expanded(&self, node_id: &str) -> bool {
        self.expanded.contains(node_id)
    }

    pub(crate) const fn select_next(&mut self) {
        if self.visible_count > 0 && self.selected < self.visible_count - 1 {
            self.selected += 1;
        }
    }

    pub(crate) const fn select_prev(&mut self) {
        if self.selected > 0 {
            self.selected -= 1;
        }
    }

    pub(crate) const fn select_first(&mut self) {
        self.selected = 0;
    }

    pub(crate) const fn select_last(&mut self) {
        if self.visible_count > 0 {
            self.selected = self.visible_count - 1;
        }
    }
}

/// A flattened tree item for rendering.
#[derive(Debug, Clone)]
pub struct FlattenedItem {
    pub label: String,
    pub depth: usize,
    pub is_group: bool,
    pub is_expanded: bool,
    pub is_last_sibling: bool,
    pub vuln_count: usize,
    pub ancestors_last: Vec<bool>,
    /// Maximum severity for components with vulnerabilities
    pub max_severity: Option<String>,
}

/// The tree widget.
pub struct Tree<'a> {
    roots: &'a [TreeNode],
    block: Option<Block<'a>>,
    highlight_style: Style,
    highlight_symbol: &'a str,
    group_style: Style,
    search_query: String,
}

impl<'a> Tree<'a> {
    pub(crate) fn new(roots: &'a [TreeNode]) -> Self {
        let scheme = colors();
        Self {
            roots,
            block: None,
            highlight_style: Style::default()
                .bg(scheme.selection)
                .add_modifier(Modifier::BOLD),
            highlight_symbol: "",
            group_style: Style::default().fg(scheme.primary).bold(),
            search_query: String::new(),
        }
    }

    pub(crate) fn block(mut self, block: Block<'a>) -> Self {
        self.block = Some(block);
        self
    }

    pub(crate) const fn highlight_style(mut self, style: Style) -> Self {
        self.highlight_style = style;
        self
    }

    pub(crate) fn search_query(mut self, query: &str) -> Self {
        self.search_query = query.to_lowercase();
        self
    }

    /// Flatten the tree into a list of items for rendering.
    fn flatten(&self, state: &TreeState) -> Vec<FlattenedItem> {
        let mut items = Vec::new();
        self.flatten_nodes(self.roots, 0, state, &mut items, &[]);
        items
    }

    #[allow(clippy::only_used_in_recursion)]
    fn flatten_nodes(
        &self,
        nodes: &[TreeNode],
        depth: usize,
        state: &TreeState,
        items: &mut Vec<FlattenedItem>,
        ancestors_last: &[bool],
    ) {
        for (i, node) in nodes.iter().enumerate() {
            let is_last = i == nodes.len() - 1;
            let is_expanded = state.is_expanded(node.id());

            let mut current_ancestors = ancestors_last.to_vec();
            current_ancestors.push(is_last);

            items.push(FlattenedItem {
                label: node.label(),
                depth,
                is_group: node.is_group(),
                is_expanded,
                is_last_sibling: is_last,
                vuln_count: node.vuln_count(),
                ancestors_last: current_ancestors.clone(),
                max_severity: node.max_severity().map(std::string::ToString::to_string),
            });

            // Recursively add children if expanded
            if is_expanded && let Some(children) = node.children() {
                self.flatten_nodes(children, depth + 1, state, items, &current_ancestors);
            }
        }
    }
}

impl StatefulWidget for Tree<'_> {
    type State = TreeState;

    fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
        // Handle block separately to avoid borrow issues
        let inner_area = self.block.as_ref().map_or(area, |b| {
            let inner = b.inner(area);
            b.clone().render(area, buf);
            inner
        });

        if inner_area.width < 4 || inner_area.height < 1 {
            return;
        }

        let items = self.flatten(state);
        let area = inner_area;
        state.visible_count = items.len();

        // Calculate scroll offset to keep selected item visible
        let visible_height = area.height as usize;
        if state.selected >= state.offset + visible_height {
            state.offset = state.selected - visible_height + 1;
        } else if state.selected < state.offset {
            state.offset = state.selected;
        }

        // Render visible items
        for (i, item) in items
            .iter()
            .skip(state.offset)
            .take(visible_height)
            .enumerate()
        {
            let y = area.y + i as u16;
            let is_selected = state.offset + i == state.selected;

            // Build the tree prefix with box-drawing characters
            let mut prefix = String::new();
            for (depth, is_last) in item.ancestors_last.iter().take(item.depth).enumerate() {
                if depth < item.depth {
                    if *is_last {
                        prefix.push_str("   ");
                    } else {
                        prefix.push_str("");
                    }
                }
            }

            // Add the branch character for this node
            if item.depth > 0 {
                if item.is_last_sibling {
                    prefix.push_str("└─ ");
                } else {
                    prefix.push_str("├─ ");
                }
            }

            // Add expand/collapse indicator for groups, leaf dot for components
            let expand_indicator = if item.is_group {
                if item.is_expanded { "" } else { "" }
            } else {
                "· "
            };

            // Build the line
            let mut x = area.x;

            // Selection indicator
            let scheme = colors();
            if is_selected {
                let symbol = self.highlight_symbol;
                for ch in symbol.chars() {
                    if x < area.x + area.width {
                        if let Some(cell) = buf.cell_mut((x, y)) {
                            cell.set_char(ch)
                                .set_style(Style::default().fg(scheme.accent));
                        }
                        x += 1;
                    }
                }
            } else {
                // Advance by display width, not byte length: the default
                // "▶ " symbol is 4 bytes but 2 columns, so byte-length
                // indenting shifted every non-selected row 2 columns right
                // of the selected one (visible jitter when moving the cursor).
                x += UnicodeWidthStr::width(self.highlight_symbol) as u16;
            }

            // Tree prefix
            for ch in prefix.chars() {
                if x < area.x + area.width {
                    if let Some(cell) = buf.cell_mut((x, y)) {
                        cell.set_char(ch)
                            .set_style(Style::default().fg(scheme.text_muted));
                    }
                    x += 1;
                }
            }

            // Expand indicator
            let indicator_style = if item.is_group {
                Style::default().fg(scheme.accent)
            } else {
                Style::default().fg(scheme.muted)
            };
            for ch in expand_indicator.chars() {
                if x < area.x + area.width {
                    if let Some(cell) = buf.cell_mut((x, y)) {
                        cell.set_char(ch).set_style(indicator_style);
                    }
                    x += 1;
                }
            }

            // Label — truncate to fit with room for vuln badge
            // Search match highlighting (accent+bold when query matches)
            let is_search_match = !self.search_query.is_empty()
                && item.label.to_lowercase().contains(&self.search_query);

            // Depth-based color gradient for component names
            let depth_color = if item.is_group {
                scheme.primary
            } else {
                // Depth 2+ merges into text_muted: a dedicated light-gray RGB
                // step was near-invisible on the light theme's background.
                match item.depth {
                    0 | 1 => scheme.text,
                    _ => scheme.text_muted,
                }
            };

            let label_style = if is_selected {
                self.highlight_style
            } else if is_search_match {
                Style::default().fg(scheme.accent).bold()
            } else if item.is_group {
                self.group_style
            } else if item.depth == 0 {
                Style::default().fg(depth_color).bold()
            } else {
                Style::default().fg(depth_color)
            };

            let vuln_badge_width: u16 = if item.vuln_count > 0 {
                3 + item.vuln_count.to_string().len() as u16 // space + sev_char + space + count
            } else {
                0
            };
            let remaining = (area.x + area.width).saturating_sub(x + vuln_badge_width) as usize;

            // Width-aware truncation + placement: set_stringn caps at `remaining`
            // display cells and correctly advances past double-width glyphs, so the
            // vuln badge can no longer be overrun by CJK/emoji labels.
            let display_label = super::truncate_str(&item.label, remaining);
            let (new_x, _) = buf.set_stringn(x, y, &display_label, remaining, label_style);
            x = new_x;

            // Vulnerability indicator with severity badge
            if item.vuln_count > 0 {
                // Get severity color
                let (sev_char, sev_color) =
                    item.max_severity
                        .as_ref()
                        .map_or(('!', scheme.warning), |sev| {
                            match sev.to_lowercase().as_str() {
                                "critical" => ('C', scheme.critical),
                                "high" => ('H', scheme.high),
                                "medium" => ('M', scheme.medium),
                                "low" => ('L', scheme.low),
                                _ => ('!', scheme.warning),
                            }
                        });

                // Space before indicator
                if x < area.x + area.width {
                    if let Some(cell) = buf.cell_mut((x, y)) {
                        cell.set_char(' ');
                    }
                    x += 1;
                }

                // Severity badge [C], [H], [M], [L]
                let badge_style = Style::default()
                    .fg(scheme.badge_fg_dark)
                    .bg(sev_color)
                    .bold();

                if x < area.x + area.width {
                    if let Some(cell) = buf.cell_mut((x, y)) {
                        cell.set_char(sev_char).set_style(badge_style);
                    }
                    x += 1;
                }

                // Space between badge and count
                if x < area.x + area.width {
                    x += 1;
                }

                // Vuln count
                let count_text = format!("{}", item.vuln_count);
                let count_style = Style::default().fg(sev_color).bold();
                for ch in count_text.chars() {
                    if x < area.x + area.width {
                        if let Some(cell) = buf.cell_mut((x, y)) {
                            cell.set_char(ch).set_style(count_style);
                        }
                        x += 1;
                    }
                }
            }

            // Fill rest with background if selected
            if is_selected {
                while x < area.x + area.width {
                    if let Some(cell) = buf.cell_mut((x, y)) {
                        cell.set_style(self.highlight_style);
                    }
                    x += 1;
                }
            }
        }

        // Render scrollbar if needed
        if items.len() > visible_height {
            let scheme = colors();
            let scrollbar = Scrollbar::new(ScrollbarOrientation::VerticalRight)
                .thumb_style(Style::default().fg(scheme.accent))
                .track_style(Style::default().fg(scheme.muted));
            let mut scrollbar_state = ScrollbarState::new(items.len()).position(state.selected);
            scrollbar.render(area, buf, &mut scrollbar_state);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_tree_state() {
        let mut state = TreeState::new();
        assert!(!state.is_expanded("test"));

        state.toggle_expand("test");
        assert!(state.is_expanded("test"));

        state.toggle_expand("test");
        assert!(!state.is_expanded("test"));
    }

    #[test]
    fn test_tree_node() {
        let node = TreeNode::Component {
            id: "comp-1".to_string(),
            name: "lodash".to_string(),
            version: Some("4.17.21".to_string()),
            vuln_count: 2,
            max_severity: Some("high".to_string()),
            component_type: Some("lib".to_string()),
            ecosystem: Some("npm".to_string()),
            is_bookmarked: false,
        };

        assert_eq!(node.label(), "lodash@4.17.21 [npm]");
        assert_eq!(node.vuln_count(), 2);
        assert_eq!(node.max_severity(), Some("high"));
        assert!(!node.is_group());
    }

    #[test]
    fn test_tree_node_bookmarked() {
        let node = TreeNode::Component {
            id: "comp-1".to_string(),
            name: "lodash".to_string(),
            version: Some("4.17.21".to_string()),
            vuln_count: 0,
            max_severity: None,
            component_type: None,
            ecosystem: None,
            is_bookmarked: true,
        };

        assert_eq!(node.label(), "\u{2605} lodash@4.17.21");
    }

    #[test]
    fn test_tree_node_unknown_ecosystem_hidden() {
        let node = TreeNode::Component {
            id: "comp-1".to_string(),
            name: "lodash".to_string(),
            version: Some("4.17.21".to_string()),
            vuln_count: 0,
            max_severity: None,
            component_type: None,
            ecosystem: Some("Unknown".to_string()),
            is_bookmarked: false,
        };

        assert_eq!(node.label(), "lodash@4.17.21");
    }

    #[test]
    fn test_extract_display_name() {
        // Path-like names - extracts the filename
        assert_eq!(
            extract_display_name("./6488064-48136192.squashfs_v4_le_extract/SMASH/ShowProperty"),
            "ShowProperty"
        );

        // Clean package names should pass through
        assert_eq!(extract_display_name("lodash"), "lodash");
        assert_eq!(extract_display_name("openssl-1.1.1"), "openssl-1.1.1");

        // Hash-like filenames with meaningful parent get parent/file format
        let hash_result = extract_display_name("./6488064-48136192.squashfs");
        assert!(hash_result.len() <= 30);
    }

    #[test]
    fn test_detect_component_type() {
        assert_eq!(detect_component_type("libssl.so"), "lib");
        assert_eq!(detect_component_type("libcrypto.so.1.1"), "lib");
        assert_eq!(detect_component_type("server.crt"), "cert");
        assert_eq!(detect_component_type("firmware.img"), "bin");
        assert_eq!(detect_component_type("rootfs.squashfs"), "fs");
        assert_eq!(detect_component_type("random.unknown"), "unk");
    }
}

#[cfg(test)]
mod indent_tests {
    use super::*;
    use ratatui::buffer::Buffer;
    use ratatui::layout::Rect;
    use ratatui::widgets::StatefulWidget;

    /// Regression for the byte-length indent bug: the expand indicator must
    /// sit in the same column on selected and non-selected rows ("▶ " is
    /// 4 bytes but 2 display columns, so non-selected rows drifted 2 right).
    #[test]
    fn unselected_rows_align_with_selected_row() {
        crate::tui::test_support::pin_theme();
        let group = |id: &str| TreeNode::Group {
            id: id.to_string(),
            label: id.to_string(),
            children: Vec::new(),
            item_count: 1,
            vuln_count: 0,
        };
        let roots = [group("alpha"), group("beta")];
        let mut state = TreeState::new();
        state.selected = 0;

        let area = Rect::new(0, 0, 40, 4);
        let mut buf = Buffer::empty(area);
        Tree::new(&roots).render(area, &mut buf, &mut state);

        // Compare the column where each row's LABEL starts (the selected row
        // also paints the highlight arrow at column 0, so scanning for the
        // first arrow glyph would find the highlight, not the tree content).
        let row_text = |y: u16| -> String {
            (0..area.width)
                .map(|x| buf.cell((x, y)).map(|c| c.symbol()).unwrap_or(" "))
                .collect()
        };
        let label_col = |y: u16, label: &str| -> usize {
            let text = row_text(y);
            let byte_idx = text
                .find(label)
                .unwrap_or_else(|| panic!("label {label:?} not on row {y}: {text:?}"));
            // Convert the byte offset to a display column ("▶" is 3 bytes but
            // 1 column — the same trap the render fix closes).
            text[..byte_idx].chars().count()
        };
        assert_eq!(
            label_col(0, "alpha"),
            label_col(1, "beta"),
            "selected (row 0) and non-selected (row 1) labels must align"
        );
    }

    /// Depth>=2 component labels must take scheme.text_muted while depth 0|1 keep
    /// scheme.text (the depth cue the theme backbone moved off the hardcoded
    /// Rgb(180,180,180)); flattening the depth match to one slot loses the cue
    /// with no snapshot noticing, because text snapshots strip styles.
    #[test]
    fn depth_two_labels_use_muted_theme_text() {
        crate::tui::test_support::pin_theme();
        let leaf = |name: &str| TreeNode::Component {
            id: format!("id-{name}"),
            name: name.to_string(),
            version: None,
            vuln_count: 0,
            max_severity: None,
            component_type: None,
            ecosystem: None,
            is_bookmarked: false,
        };
        let roots = [TreeNode::Group {
            id: "g1".to_string(),
            label: "outer".to_string(),
            children: vec![
                TreeNode::Group {
                    id: "g2".to_string(),
                    label: "inner".to_string(),
                    children: vec![leaf("deep-leaf")],
                    item_count: 1,
                    vuln_count: 0,
                },
                leaf("mid-leaf"),
            ],
            item_count: 2,
            vuln_count: 0,
        }];
        let mut state = TreeState::new();
        state.expand("g1");
        state.expand("g2");
        // Selection stays on the root group header so neither leaf takes the
        // selection style.
        state.selected = 0;

        let area = Rect::new(0, 0, 40, 6);
        let mut buf = Buffer::empty(area);
        Tree::new(&roots).render(area, &mut buf, &mut state);

        // Find a label's first cell and return its fg (byte offset converted to a
        // display column: the tree prefix glyphs are multi-byte, single-column).
        let label_fg = |label: &str| {
            for y in 0..area.height {
                let text: String = (0..area.width)
                    .map(|x| buf.cell((x, y)).map(|c| c.symbol()).unwrap_or(" "))
                    .collect();
                if let Some(byte_idx) = text.find(label) {
                    let col = text[..byte_idx].chars().count() as u16;
                    return buf.cell((col, y)).and_then(|c| c.style().fg);
                }
            }
            panic!("label {label:?} not rendered in the tree buffer");
        };
        let scheme = colors();
        assert_ne!(
            scheme.text, scheme.text_muted,
            "precondition: the pinned theme must distinguish text from text_muted"
        );
        assert_eq!(
            label_fg("deep-leaf"),
            Some(scheme.text_muted),
            "depth-2 component labels must use the themed text_muted fg (depth cue lost or re-slotted)"
        );
        assert_eq!(
            label_fg("mid-leaf"),
            Some(scheme.text),
            "depth-1 component labels must keep the full text fg (the muted boundary sits at depth 2)"
        );
    }
}