vfa-tui 0.0.18

Enterprise-grade terminal UI for the Vanguard Frontier Agentic marketplace catalog
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
/// Coverage grid widget — renders the coverage matrix as a scrollable,
/// color-coded grid where rows = catalog assets, columns = workspaces.
///
/// Req 3.2: color-coded cells (green=Installed/Current, yellow=Outdated,
///           red=Drifted, gray=NotInstalled).
/// Req 29.2: text glyphs alongside color so the widget is readable without color.
use ratatui::{
    buffer::Buffer,
    layout::Rect,
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Paragraph, Widget},
    Frame,
};

use crate::models::coverage::{AssetType, CellStatus, CoverageMatrix, CoverageRow};
use crate::ui::theme::Theme;

/// Text glyph for each cell status (color-independent, Req 29.2).
pub fn cell_glyph(status: &CellStatus) -> &'static str {
    match status {
        CellStatus::Installed => "[OK]",
        CellStatus::Outdated => "[OLD]",
        CellStatus::Drifted => "[DRF]",
        CellStatus::NotInstalled => "[--]",
    }
}

/// Color for each cell status (falls back gracefully in no-color mode).
fn cell_color(status: &CellStatus, theme: &Theme) -> Style {
    if theme.no_color {
        return Style::default();
    }
    match status {
        CellStatus::Installed => Style::default().fg(Color::Green),
        CellStatus::Outdated => Style::default().fg(Color::Yellow),
        CellStatus::Drifted => Style::default().fg(Color::Red).add_modifier(Modifier::BOLD),
        CellStatus::NotInstalled => Style::default().fg(Color::DarkGray),
    }
}

/// Active filter state for the coverage grid.
#[derive(Debug, Default, Clone)]
pub struct CoverageGridFilter {
    /// Restrict to a specific asset type (`None` = all types).
    pub asset_type: Option<AssetType>,
    /// Restrict to a provider string (`None` = all providers).
    pub provider: Option<String>,
    /// Restrict columns to workspaces whose name contains this substring.
    pub workspace: Option<String>,
}

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

    fn row_passes(&self, row: &CoverageRow) -> bool {
        if let Some(ref at) = self.asset_type {
            if &row.asset_type != at {
                return false;
            }
        }
        if let Some(ref prov) = self.provider {
            let row_prov = serde_json::to_value(row.provider)
                .ok()
                .and_then(|v| v.as_str().map(|s| s.to_string()))
                .unwrap_or_default();
            if !row_prov.contains(prov.as_str()) {
                return false;
            }
        }
        true
    }

    fn col_passes(&self, workspace: &str) -> bool {
        if let Some(ref ws) = self.workspace {
            return workspace.contains(ws.as_str());
        }
        true
    }
}

/// State for the coverage grid viewport (scroll offsets).
#[derive(Debug, Default, Clone)]
pub struct CoverageGridState {
    /// First visible row index (asset dimension).
    pub row_offset: usize,
    /// First visible column index (workspace dimension).
    pub col_offset: usize,
}

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

    pub fn scroll_down(&mut self, n: usize) {
        self.row_offset = self.row_offset.saturating_add(n);
    }

    pub fn scroll_up(&mut self, n: usize) {
        self.row_offset = self.row_offset.saturating_sub(n);
    }

    pub fn scroll_right(&mut self, n: usize) {
        self.col_offset = self.col_offset.saturating_add(n);
    }

    pub fn scroll_left(&mut self, n: usize) {
        self.col_offset = self.col_offset.saturating_sub(n);
    }
}

/// Render the coverage grid into a [`Frame`].
///
/// The grid header shows workspace names (column headers), and each
/// subsequent line shows one asset row with a cell glyph per workspace.
pub fn render_coverage_grid(
    matrix: &CoverageMatrix,
    state: &CoverageGridState,
    filter: &CoverageGridFilter,
    area: Rect,
    frame: &mut Frame,
    theme: &Theme,
) {
    let lines = build_grid_lines(matrix, state, filter, theme, area.width as usize);
    let paragraph = Paragraph::new(lines)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .title("Coverage Matrix  [OK]=Installed [OLD]=Outdated [DRF]=Drifted [--]=Missing")
                .border_style(theme.border_style()),
        )
        .scroll((0, 0));
    frame.render_widget(paragraph, area);
}

/// Pure helper — build the rendered lines for a coverage grid.
///
/// Exposed so tests can call it directly on a `Buffer`.
pub fn build_grid_lines<'a>(
    matrix: &'a CoverageMatrix,
    state: &CoverageGridState,
    filter: &CoverageGridFilter,
    theme: &Theme,
    max_width: usize,
) -> Vec<Line<'a>> {
    // Filtered rows and columns
    let rows: Vec<&CoverageRow> = matrix
        .rows
        .iter()
        .filter(|r| filter.row_passes(r))
        .collect();
    let cols: Vec<&String> = matrix
        .columns
        .iter()
        .filter(|c| filter.col_passes(c))
        .collect();

    // Skip rows/cols before viewport offset
    let visible_rows = rows.into_iter().skip(state.row_offset);
    let visible_cols: Vec<&String> = cols.into_iter().skip(state.col_offset).collect();

    // Cell width: "[DRF]" is 5 chars; we pad to CELL_W chars total
    const CELL_W: usize = 6;
    const NAME_W: usize = 22;

    let mut lines: Vec<Line<'a>> = Vec::new();

    // ── header line ──────────────────────────────────────────────────────────
    let mut header_spans: Vec<Span<'a>> = vec![Span::styled(
        format!("{:<width$}", "Asset", width = NAME_W),
        Style::default().add_modifier(Modifier::BOLD),
    )];
    let mut col_count = 0;
    for ws in &visible_cols {
        let used = NAME_W + col_count * CELL_W;
        if used + CELL_W > max_width {
            break;
        }
        let label = if ws.len() >= CELL_W {
            ws[..CELL_W - 1].to_string()
        } else {
            format!("{:<width$}", &ws[..], width = CELL_W)
        };
        header_spans.push(Span::styled(
            label,
            Style::default().add_modifier(Modifier::BOLD),
        ));
        col_count += 1;
    }
    let visible_cols_truncated = &visible_cols[..col_count.min(visible_cols.len())];
    lines.push(Line::from(header_spans));

    // ── data rows ─────────────────────────────────────────────────────────────
    for row in visible_rows {
        let asset_label = if row.asset_name.len() >= NAME_W {
            format!("{:.width$}", row.asset_name, width = NAME_W - 1)
        } else {
            format!("{:<width$}", row.asset_name, width = NAME_W)
        };

        let mut spans: Vec<Span<'a>> = vec![Span::raw(asset_label)];
        for ws in visible_cols_truncated {
            let key = (row.asset_id.clone(), ws.as_str().to_string());
            let cell = matrix.cells.get(&key);
            let (glyph, style) = match cell {
                Some(c) => (cell_glyph(&c.status), cell_color(&c.status, theme)),
                None => ("[--]", Style::default().fg(Color::DarkGray)),
            };
            spans.push(Span::styled(
                format!("{:<width$}", glyph, width = CELL_W),
                style,
            ));
        }
        lines.push(Line::from(spans));
    }

    if lines.len() == 1 {
        lines.push(Line::from(vec![Span::raw(
            "  (no assets match current filter)",
        )]));
    }

    lines
}

/// Render coverage grid directly into a `Buffer` (useful for testing).
pub fn render_coverage_grid_buffer(
    matrix: &CoverageMatrix,
    state: &CoverageGridState,
    filter: &CoverageGridFilter,
    area: Rect,
    buf: &mut Buffer,
    theme: &Theme,
) {
    let lines = build_grid_lines(matrix, state, filter, theme, area.width as usize);
    let paragraph = Paragraph::new(lines).block(
        Block::default()
            .borders(Borders::ALL)
            .title("Coverage Matrix")
            .border_style(theme.border_style()),
    );
    Widget::render(paragraph, area, buf);
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::models::coverage::{
        AssetType, CellStatus, CoverageCell, CoverageMatrix, CoverageRow,
    };
    use crate::models::provider::Provider;
    use crate::ui::theme::{ColorSupport, Theme};
    use ratatui::backend::TestBackend;
    use ratatui::buffer::Buffer;
    use ratatui::layout::Rect;
    use ratatui::Terminal;
    use std::collections::HashMap;

    fn make_matrix() -> CoverageMatrix {
        let rows = vec![
            CoverageRow {
                asset_id: "agent-alpha".to_string(),
                asset_type: AssetType::Agent,
                asset_name: "Alpha Agent".to_string(),
                provider: Provider::Aws,
            },
            CoverageRow {
                asset_id: "skill-beta".to_string(),
                asset_type: AssetType::Skill,
                asset_name: "Beta Skill".to_string(),
                provider: Provider::Aws,
            },
        ];
        let columns = vec!["prod".to_string(), "staging".to_string()];
        let mut cells = HashMap::new();
        cells.insert(
            ("agent-alpha".to_string(), "prod".to_string()),
            CoverageCell {
                status: CellStatus::Installed,
                installed_version: Some("1.0.0".to_string()),
                canonical_version: "1.0.0".to_string(),
                installed_hash: Some("abc".to_string()),
                canonical_hash: Some("abc".to_string()),
            },
        );
        cells.insert(
            ("agent-alpha".to_string(), "staging".to_string()),
            CoverageCell {
                status: CellStatus::Outdated,
                installed_version: Some("0.9.0".to_string()),
                canonical_version: "1.0.0".to_string(),
                installed_hash: Some("xyz".to_string()),
                canonical_hash: Some("abc".to_string()),
            },
        );
        cells.insert(
            ("skill-beta".to_string(), "prod".to_string()),
            CoverageCell {
                status: CellStatus::Drifted,
                installed_version: Some("1.0.0".to_string()),
                canonical_version: "1.0.0".to_string(),
                installed_hash: Some("WRONG".to_string()),
                canonical_hash: Some("abc".to_string()),
            },
        );
        // skill-beta / staging → not installed (no entry in map)
        let mut workspace_scores = HashMap::new();
        workspace_scores.insert("prod".to_string(), 50.0);
        workspace_scores.insert("staging".to_string(), 0.0);

        CoverageMatrix {
            rows,
            columns,
            cells,
            workspace_scores,
        }
    }

    #[test]
    fn coverage_grid_renders_ok_glyph() {
        let matrix = make_matrix();
        let state = CoverageGridState::new();
        let filter = CoverageGridFilter::new();
        let theme = Theme::with_color_support(ColorSupport::None);
        let area = Rect::new(0, 0, 80, 20);
        let mut buf = Buffer::empty(area);
        render_coverage_grid_buffer(&matrix, &state, &filter, area, &mut buf, &theme);

        let content: String = buf
            .content
            .iter()
            .map(|c| c.symbol().chars().next().unwrap_or(' '))
            .collect();
        assert!(
            content.contains("[OK]"),
            "expected [OK] glyph for Installed"
        );
    }

    #[test]
    fn coverage_grid_renders_old_glyph() {
        let matrix = make_matrix();
        let state = CoverageGridState::new();
        let filter = CoverageGridFilter::new();
        let theme = Theme::with_color_support(ColorSupport::None);
        let area = Rect::new(0, 0, 80, 20);
        let mut buf = Buffer::empty(area);
        render_coverage_grid_buffer(&matrix, &state, &filter, area, &mut buf, &theme);

        let content: String = buf
            .content
            .iter()
            .map(|c| c.symbol().chars().next().unwrap_or(' '))
            .collect();
        assert!(
            content.contains("[OLD]"),
            "expected [OLD] glyph for Outdated"
        );
    }

    #[test]
    fn coverage_grid_renders_drf_glyph() {
        let matrix = make_matrix();
        let state = CoverageGridState::new();
        let filter = CoverageGridFilter::new();
        let theme = Theme::with_color_support(ColorSupport::None);
        let area = Rect::new(0, 0, 80, 20);
        let mut buf = Buffer::empty(area);
        render_coverage_grid_buffer(&matrix, &state, &filter, area, &mut buf, &theme);

        let content: String = buf
            .content
            .iter()
            .map(|c| c.symbol().chars().next().unwrap_or(' '))
            .collect();
        assert!(
            content.contains("[DRF]"),
            "expected [DRF] glyph for Drifted"
        );
    }

    #[test]
    fn coverage_grid_renders_missing_glyph_for_not_installed() {
        let matrix = make_matrix();
        let state = CoverageGridState::new();
        let filter = CoverageGridFilter::new();
        let theme = Theme::with_color_support(ColorSupport::None);
        let area = Rect::new(0, 0, 80, 20);
        let mut buf = Buffer::empty(area);
        render_coverage_grid_buffer(&matrix, &state, &filter, area, &mut buf, &theme);

        let content: String = buf
            .content
            .iter()
            .map(|c| c.symbol().chars().next().unwrap_or(' '))
            .collect();
        assert!(
            content.contains("[--]"),
            "expected [--] glyph for NotInstalled/missing"
        );
    }

    #[test]
    fn coverage_grid_filter_by_asset_type() {
        let matrix = make_matrix();
        let state = CoverageGridState::new();
        let filter = CoverageGridFilter {
            asset_type: Some(AssetType::Skill),
            ..Default::default()
        };
        let theme = Theme::with_color_support(ColorSupport::None);
        let area = Rect::new(0, 0, 80, 20);
        let mut buf = Buffer::empty(area);
        render_coverage_grid_buffer(&matrix, &state, &filter, area, &mut buf, &theme);

        let content: String = buf
            .content
            .iter()
            .map(|c| c.symbol().chars().next().unwrap_or(' '))
            .collect();
        // Only Beta Skill row should appear; Alpha Agent row should be absent
        assert!(
            content.contains("Beta Skill"),
            "skill row should appear when filtering by Skill"
        );
        assert!(
            !content.contains("Alpha Agent"),
            "agent row should be filtered out"
        );
    }

    #[test]
    fn cell_glyph_all_variants_are_nonempty() {
        for status in [
            CellStatus::Installed,
            CellStatus::Outdated,
            CellStatus::Drifted,
            CellStatus::NotInstalled,
        ] {
            let g = cell_glyph(&status);
            assert!(!g.is_empty(), "glyph for {:?} must not be empty", status);
        }
    }

    #[test]
    fn coverage_grid_via_test_backend() {
        let matrix = make_matrix();
        let state = CoverageGridState::new();
        let filter = CoverageGridFilter::new();
        let theme = Theme::with_color_support(ColorSupport::None);

        let backend = TestBackend::new(80, 20);
        let mut terminal = Terminal::new(backend).unwrap();
        terminal
            .draw(|frame| {
                render_coverage_grid(&matrix, &state, &filter, frame.area(), frame, &theme);
            })
            .unwrap();

        let buf = terminal.backend().buffer().clone();
        let content: String = buf
            .content
            .iter()
            .map(|c| c.symbol().chars().next().unwrap_or(' '))
            .collect();
        assert!(content.contains("[OK]"));
    }
}