Skip to main content

rigspark_cli/
tui_models.rs

1use crate::{
2    accessible_catalog::CatalogPresentation,
3    accessible_installed::{InstalledCommand, InstalledView},
4    accessible_read_only::can_run_screen,
5    accessible_recommend::Recommendation,
6    accessible_text::{identifier, single_line},
7    tui_theme::{self, Theme, Verdict},
8};
9use crossterm::event::{
10    Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseButton, MouseEvent, MouseEventKind,
11};
12use ratatui::{
13    Frame,
14    layout::{Constraint, Layout, Position, Rect},
15    style::Style,
16    text::{Line, Span},
17    widgets::{Cell, Clear, HighlightSpacing, Paragraph, Row, Table, TableState},
18};
19use rigspark_core::reports::strip_control;
20use serde::Deserialize;
21use serde_json::Value;
22use std::io;
23use unicode_segmentation::UnicodeSegmentation;
24
25const MAX_ROWS: usize = 1000;
26const MAX_TEXT: usize = 64 * 1024;
27const MAX_DOCUMENT: usize = 4 * 1024 * 1024;
28const MAX_QUERY: usize = 256;
29const MAX_MARKED: usize = 4;
30
31#[derive(Deserialize)]
32#[serde(rename_all = "camelCase")]
33struct CanRunMetadata<'evidence> {
34    model_id: &'evidence str,
35    runnable: &'evidence str,
36    quant: Option<&'evidence str>,
37    reason: Option<&'evidence str>,
38    throughput_backend: &'evidence str,
39    context: Option<f64>,
40}
41
42fn bound_can_run(value: &Value, depth: usize, budget: &mut usize) -> io::Result<()> {
43    let invalid = || {
44        io::Error::new(
45            io::ErrorKind::InvalidInput,
46            "can-run view input limit exceeded",
47        )
48    };
49    if depth > 16 {
50        return Err(invalid());
51    }
52    *budget = budget.checked_sub(64).ok_or_else(invalid)?;
53    match value {
54        Value::String(text) => {
55            if text.len() > MAX_TEXT {
56                return Err(invalid());
57            }
58            *budget = budget.checked_sub(text.len()).ok_or_else(invalid)?;
59        }
60        Value::Array(values) => {
61            if values.len() > MAX_ROWS {
62                return Err(invalid());
63            }
64            for value in values {
65                bound_can_run(value, depth + 1, budget)?;
66            }
67        }
68        Value::Object(values) => {
69            if values.len() > MAX_ROWS {
70                return Err(invalid());
71            }
72            for (key, value) in values {
73                if key.len() > MAX_TEXT {
74                    return Err(invalid());
75                }
76                *budget = budget.checked_sub(key.len()).ok_or_else(invalid)?;
77                bound_can_run(value, depth + 1, budget)?;
78            }
79        }
80        _ => (),
81    }
82    Ok(())
83}
84
85#[derive(Debug)]
86pub struct ModelRow {
87    label: String,
88    summary: String,
89    search: String,
90    evidence: String,
91    need_bytes: Option<f64>,
92    /// Release date, else auto-admission date (YYYY-MM-DD), for the month filter.
93    recency: Option<String>,
94}
95
96fn bounded_text(value: &str, limit: usize) -> io::Result<String> {
97    if value.len() > limit {
98        return Err(io::Error::new(
99            io::ErrorKind::InvalidInput,
100            "model view text limit exceeded",
101        ));
102    }
103    Ok(strip_control(value)
104        .chars()
105        .filter(|character| !character.is_control())
106        .collect())
107}
108
109impl ModelRow {
110    pub fn new(label: &str, search: &str, evidence: &str) -> io::Result<Self> {
111        Ok(Self {
112            label: bounded_text(label, 1024)?,
113            summary: String::new(),
114            search: bounded_text(search, MAX_TEXT)?.to_lowercase(),
115            evidence: bounded_evidence(evidence)?,
116            need_bytes: None,
117            recency: None,
118        })
119    }
120
121    pub fn label(&self) -> &str {
122        &self.label
123    }
124
125    fn cells(&self) -> Vec<&str> {
126        if self.summary.is_empty() {
127            Vec::new()
128        } else {
129            self.summary.split(" | ").collect()
130        }
131    }
132
133    fn verdict(&self) -> Option<Verdict> {
134        self.cells().into_iter().find_map(tui_theme::verdict_kind)
135    }
136}
137
138fn bounded_evidence(value: &str) -> io::Result<String> {
139    if value.len() > MAX_TEXT {
140        return Err(io::Error::new(
141            io::ErrorKind::InvalidInput,
142            "model view text limit exceeded",
143        ));
144    }
145    value
146        .lines()
147        .map(|line| bounded_text(line, MAX_TEXT))
148        .collect::<io::Result<Vec<_>>>()
149        .map(|lines| lines.join("\n"))
150}
151
152#[derive(Debug, PartialEq, Eq)]
153pub enum ModelOutcome {
154    Exit { code: u8 },
155    PrintCommand { command: String },
156}
157
158#[derive(Clone, Copy, PartialEq, Eq)]
159enum Focus {
160    List,
161    Detail,
162    Overview,
163    Help,
164    Compare,
165}
166
167#[derive(Default)]
168struct HitAreas {
169    rows: Rect,
170    header: Vec<(Rect, usize)>,
171    detail: Rect,
172}
173
174pub struct ModelView {
175    title: String,
176    overview: Vec<String>,
177    rows: Vec<ModelRow>,
178    visible: Vec<usize>,
179    matches: Vec<Vec<usize>>,
180    list: TableState,
181    query: String,
182    searching: bool,
183    focus: Focus,
184    help_return: Option<(Focus, usize, usize)>,
185    marked: Vec<usize>,
186    notice: Option<&'static str>,
187    toast: Option<String>,
188    clipboard: Option<String>,
189    scroll: usize,
190    scroll_max: usize,
191    page: usize,
192    detail_page: usize,
193    color: bool,
194    command: Option<String>,
195    comparison: bool,
196    columns: Vec<&'static str>,
197    priority: Vec<usize>,
198    sort: Option<(usize, bool)>,
199    verdict_filter: Option<Verdict>,
200    /// Earliest recency date shown for the 1, 2 and 3 month windows.
201    month_cutoffs: Option<[String; 3]>,
202    month_filter: Option<u8>,
203    usable_bytes: Option<f64>,
204    areas: HitAreas,
205}
206
207impl ModelView {
208    pub fn new(
209        title: &str,
210        overview: Vec<String>,
211        rows: Vec<ModelRow>,
212        color: bool,
213    ) -> io::Result<Self> {
214        if rows.len() > MAX_ROWS || overview.len() > MAX_ROWS + 8 {
215            return Err(io::Error::new(
216                io::ErrorKind::InvalidInput,
217                "model view row limit exceeded",
218            ));
219        }
220        let bytes = rows
221            .iter()
222            .map(|row| row.label.len() + row.summary.len() + row.search.len() + row.evidence.len())
223            .sum::<usize>()
224            + overview.iter().map(String::len).sum::<usize>();
225        if bytes > MAX_DOCUMENT {
226            return Err(io::Error::new(
227                io::ErrorKind::InvalidInput,
228                "model view document limit exceeded",
229            ));
230        }
231        let overview = overview
232            .iter()
233            .map(|line| bounded_text(line, MAX_TEXT))
234            .collect::<io::Result<_>>()?;
235        let selection = if rows.is_empty() { None } else { Some(0) };
236        Ok(Self {
237            title: bounded_text(title, 256)?,
238            overview,
239            visible: (0..rows.len()).collect(),
240            matches: vec![Vec::new(); rows.len()],
241            rows,
242            list: TableState::default().with_selected(selection),
243            query: String::new(),
244            searching: false,
245            focus: Focus::List,
246            help_return: None,
247            marked: Vec::new(),
248            notice: None,
249            toast: None,
250            clipboard: None,
251            scroll: 0,
252            scroll_max: 0,
253            page: 1,
254            detail_page: 1,
255            color,
256            command: None,
257            comparison: true,
258            columns: Vec::new(),
259            priority: Vec::new(),
260            sort: None,
261            verdict_filter: None,
262            month_cutoffs: None,
263            month_filter: None,
264            usable_bytes: None,
265            areas: HitAreas::default(),
266        })
267    }
268
269    fn with_columns(mut self, columns: &[&'static str], priority: &[usize]) -> Self {
270        self.columns = columns.to_vec();
271        self.priority = priority.to_vec();
272        self
273    }
274
275    fn with_memory(mut self, usable: f64, needs: impl Iterator<Item = f64>) -> Self {
276        self.usable_bytes = (usable.is_finite() && usable > 0.0).then_some(usable);
277        for (row, need) in self.rows.iter_mut().zip(needs) {
278            row.need_bytes = (need.is_finite() && need >= 0.0).then_some(need);
279        }
280        self
281    }
282
283    /// Enables the `m` month filter using each model's release or auto-admission date.
284    pub fn with_recency(
285        mut self,
286        dates: &std::collections::BTreeMap<String, String>,
287        today: &str,
288    ) -> io::Result<Self> {
289        let cutoff = |months| {
290            rigspark_core::catalog::months_before(today, months)
291                .map(|day| day.to_string())
292                .map_err(io::Error::other)
293        };
294        self.month_cutoffs = Some([cutoff(1)?, cutoff(2)?, cutoff(3)?]);
295        for row in &mut self.rows {
296            row.recency = dates.get(&row.label).cloned();
297        }
298        Ok(self)
299    }
300
301    pub fn from_catalog(presentation: &CatalogPresentation, color: bool) -> io::Result<Self> {
302        Ok(Self::new(
303            "Catalog",
304            presentation.visual_overview(),
305            adapt_rows(presentation.visual_rows())?,
306            color,
307        )?
308        .with_columns(&["Quant", "Need", "Fit", "Release"], &[2, 1, 0, 3])
309        .with_memory(presentation.usable_bytes(), presentation.need_bytes()))
310    }
311
312    pub fn from_recommendation(presentation: &Recommendation, color: bool) -> io::Result<Self> {
313        let mut view = Self::new(
314            "Recommend",
315            presentation.visual_overview(),
316            adapt_rows(presentation.visual_rows())?,
317            color,
318        )?
319        .with_columns(
320            &["Rank", "Quant", "Need", "Verdict", "Tok/s", "Score"],
321            &[3, 4, 2, 0, 5, 1],
322        )
323        .with_memory(presentation.usable_bytes(), presentation.need_bytes());
324        view.command = presentation.print_command().map(str::to_owned);
325        Ok(view)
326    }
327
328    pub fn from_installed(presentation: &InstalledView, color: bool) -> io::Result<Self> {
329        let title = match presentation.command() {
330            InstalledCommand::Recommend => "Recommend / Installed",
331            InstalledCommand::CanRun => "Can Run / Installed",
332        };
333        let rows = presentation
334            .visual_rows()
335            .map(|(label, fit, search, evidence)| {
336                let mut row = ModelRow::new(label, search, evidence)?;
337                row.summary = bounded_text(fit, 64)?;
338                Ok(row)
339            })
340            .collect::<io::Result<Vec<_>>>()?;
341        let mut view = Self::new(title, presentation.visual_overview(), rows, color)?
342            .with_columns(&["Fit"], &[0]);
343        view.comparison =
344            presentation.command() == InstalledCommand::Recommend && view.rows.len() >= 2;
345        if view.rows.is_empty() {
346            view.focus(Focus::Overview);
347        } else if presentation.command() == InstalledCommand::CanRun {
348            view.focus(Focus::Detail);
349        }
350        Ok(view)
351    }
352
353    pub fn from_can_run(evidence: &Value, color: bool) -> io::Result<Self> {
354        let mut budget = MAX_DOCUMENT;
355        bound_can_run(evidence, 0, &mut budget)?;
356        let screen = can_run_screen(evidence)?;
357        let metadata = CanRunMetadata::deserialize(evidence).map_err(io::Error::other)?;
358        if metadata.model_id.len() > 1024 {
359            return Err(io::Error::new(
360                io::ErrorKind::InvalidInput,
361                "model view text limit exceeded",
362            ));
363        }
364        let label = identifier(metadata.model_id)?;
365        let summary = single_line(&format!(
366            "Verdict: {}; quant {}; reason {}",
367            metadata.runnable,
368            metadata.quant.unwrap_or("unknown"),
369            metadata.reason.unwrap_or("none"),
370        ))?;
371        let search = single_line(&format!(
372            "{} {} {}",
373            metadata.model_id, summary, metadata.throughput_backend,
374        ))?;
375        let mut row = ModelRow::new(&label, &search, &screen)?;
376        row.summary = bounded_text(&summary, 2048)?;
377        let context = metadata.context.map_or_else(
378            || "Requested context: not specified".into(),
379            |context| format!("Requested context: {context} tokens"),
380        );
381        let mut view = Self::new(
382            "Can Run",
383            vec![
384                format!("Verdict: {} / offline evidence", metadata.runnable),
385                context,
386            ],
387            vec![row],
388            color,
389        )?;
390        view.comparison = false;
391        view.focus(Focus::Detail);
392        Ok(view)
393    }
394
395    pub fn selected(&self) -> Option<&ModelRow> {
396        self.list
397            .selected()
398            .and_then(|index| self.visible.get(index))
399            .map(|index| &self.rows[*index])
400    }
401
402    pub fn visible_count(&self) -> usize {
403        self.visible.len()
404    }
405
406    pub fn detail_focused(&self) -> bool {
407        self.focus == Focus::Detail
408    }
409
410    fn filter(&mut self) {
411        let selected = self
412            .list
413            .selected()
414            .and_then(|index| self.visible.get(index))
415            .copied();
416        let needle = self.query.to_lowercase();
417        let mut found: Vec<(usize, usize, Vec<usize>)> = self
418            .rows
419            .iter()
420            .enumerate()
421            .filter(|(_, row)| {
422                self.verdict_filter
423                    .is_none_or(|wanted| row.verdict() == Some(wanted))
424            })
425            .filter(|(_, row)| {
426                let cutoff = self
427                    .month_filter
428                    .zip(self.month_cutoffs.as_ref())
429                    .map(|(months, cutoffs)| cutoffs[usize::from(months) - 1].as_str());
430                cutoff.is_none_or(|cutoff| row.recency.as_deref().is_some_and(|day| day >= cutoff))
431            })
432            .filter_map(|(index, row)| {
433                if let Some(positions) = tui_theme::fuzzy(&row.label, &needle) {
434                    Some((index, tui_theme::fuzzy_rank(&positions), positions))
435                } else {
436                    row.search
437                        .contains(&needle)
438                        .then_some((index, usize::MAX, Vec::new()))
439                }
440            })
441            .collect();
442        if let Some((column, descending)) = self.sort {
443            found.sort_by(|left, right| {
444                let order = sort_key(&self.rows[left.0], column)
445                    .partial_cmp(&sort_key(&self.rows[right.0], column))
446                    .unwrap_or(std::cmp::Ordering::Equal);
447                let unknown = |row: usize| sort_key(&self.rows[row], column).0;
448                match (unknown(left.0), unknown(right.0)) {
449                    (0, 0) if descending => order.reverse(),
450                    _ => order,
451                }
452                .then(left.0.cmp(&right.0))
453            });
454        } else if !needle.is_empty() {
455            found.sort_by_key(|(index, rank, _)| (*rank, *index));
456        }
457        self.visible = found.iter().map(|(index, _, _)| *index).collect();
458        self.matches = found
459            .into_iter()
460            .map(|(_, _, positions)| positions)
461            .collect();
462        let position = selected
463            .and_then(|selected| self.visible.iter().position(|index| *index == selected))
464            .or_else(|| (!self.visible.is_empty()).then_some(0));
465        self.list.select(position);
466        *self.list.offset_mut() = 0;
467        self.scroll = 0;
468    }
469
470    fn cycle_sort(&mut self, column: Option<usize>) {
471        let columns = self.columns.len() + 1;
472        self.sort = match (column, self.sort) {
473            (Some(column), Some((current, descending))) if column == current => {
474                Some((column, !descending))
475            }
476            (Some(column), _) => Some((column, false)),
477            (None, None) => Some((0, false)),
478            (None, Some((current, _))) if current + 1 < columns => Some((current + 1, false)),
479            (None, Some(_)) => None,
480        };
481        self.filter();
482    }
483
484    fn selected_index(&self) -> Option<usize> {
485        self.list
486            .selected()
487            .and_then(|index| self.visible.get(index))
488            .copied()
489    }
490
491    /// Text queued for the terminal clipboard by `y`, `Y`, `e`, or chat copy.
492    pub fn take_clipboard(&mut self) -> Option<String> {
493        self.clipboard.take()
494    }
495
496    pub fn toast(&self) -> Option<&str> {
497        self.toast.as_deref()
498    }
499
500    fn copy(&mut self, text: String, what: &str) {
501        self.toast = Some(format!("Copied {what} to clipboard"));
502        self.clipboard = Some(text);
503    }
504
505    /// Paste-ready 72-column ASCII summary of the selected model.
506    fn card(&self, row: &ModelRow) -> String {
507        const WIDTH: usize = 72;
508        let mut card = format!(
509            "rigspark / {} / {}\n{}\n",
510            self.title,
511            row.label,
512            "=".repeat(WIDTH)
513        );
514        let mut field = |key: &str, value: &str| {
515            for (index, line) in tui_theme::wrap(value, WIDTH - 10).into_iter().enumerate() {
516                let key = if index == 0 { key } else { "" };
517                card.push_str(&format!("{key:<9} {line}\n"));
518            }
519        };
520        for (header, cell) in self.columns.iter().zip(row.cells()) {
521            field(&header.to_uppercase(), cell);
522        }
523        if let Some(usable) = self.usable_bytes {
524            field(
525                "MEMORY",
526                &row.need_bytes.map_or_else(
527                    || "need unknown".into(),
528                    |need| {
529                        format!(
530                            "{:.1} / {:.1} GiB ({:.0}%)",
531                            need / 1_073_741_824.0,
532                            usable / 1_073_741_824.0,
533                            need / usable * 100.0
534                        )
535                    },
536                ),
537            );
538        }
539        for line in self.overview.iter().take(2) {
540            field("MACHINE", line);
541        }
542        let mut entries = Vec::new();
543        evidence_entries(row, &mut entries);
544        for entry in entries.iter().take(24) {
545            if let Entry::Field { key, value } = entry {
546                field(
547                    &key.to_uppercase().chars().take(9).collect::<String>(),
548                    value,
549                );
550            }
551        }
552        card.push_str(&format!(
553            "{}\nrigspark: offline, cited estimate\n",
554            "-".repeat(WIDTH)
555        ));
556        card
557    }
558
559    fn move_to(&mut self, position: usize) {
560        if self.focus != Focus::List {
561            self.scroll = position.min(self.scroll_max);
562        } else if !self.visible.is_empty() {
563            self.list.select(Some(position.min(self.visible.len() - 1)));
564            self.scroll = 0;
565        }
566    }
567
568    fn focus(&mut self, focus: Focus) {
569        self.focus = focus;
570        self.scroll = 0;
571        self.scroll_max = 0;
572    }
573
574    fn append_query(&mut self, text: &str) {
575        let available = MAX_QUERY.saturating_sub(self.query.len());
576        let mut bytes = 0;
577        let prefix: String = text
578            .chars()
579            .take_while(|character| {
580                bytes += character.len_utf8();
581                bytes <= available
582            })
583            .collect();
584        let clean = strip_control(&prefix);
585        self.query
586            .extend(clean.chars().filter(|character| !character.is_control()));
587        self.filter();
588    }
589
590    fn toggle_help(&mut self) {
591        if let Some((focus, scroll, scroll_max)) = self.help_return.take() {
592            self.focus = focus;
593            self.scroll = scroll;
594            self.scroll_max = scroll_max;
595        } else {
596            self.help_return = Some((self.focus, self.scroll, self.scroll_max));
597            self.focus(Focus::Help);
598        }
599    }
600
601    fn toggle_mark(&mut self) {
602        let Some(index) = self
603            .list
604            .selected()
605            .and_then(|index| self.visible.get(index))
606            .copied()
607        else {
608            self.notice = Some("No model selected to mark");
609            return;
610        };
611        if let Some(position) = self.marked.iter().position(|marked| *marked == index) {
612            self.marked.remove(position);
613            self.notice = None;
614        } else if self.marked.len() == MAX_MARKED {
615            self.notice = Some("Mark limit 4: unmark a model with Space");
616        } else {
617            self.marked.push(index);
618            self.notice = None;
619        }
620    }
621}
622
623fn adapt_rows<'row>(
624    rows: impl Iterator<Item = (&'row str, &'row str, &'row str, &'row str)>,
625) -> io::Result<Vec<ModelRow>> {
626    rows.map(|(label, summary, search, evidence)| {
627        let mut row = ModelRow::new(label, search, evidence)?;
628        row.summary = bounded_text(summary, 2048)?;
629        Ok(row)
630    })
631    .collect()
632}
633
634pub fn handle_key(view: &mut ModelView, key: KeyEvent) -> Option<ModelOutcome> {
635    if key.kind == KeyEventKind::Release {
636        return None;
637    }
638    view.toast = None;
639    if key.modifiers.contains(KeyModifiers::CONTROL) {
640        match key.code {
641            KeyCode::Char('c') => return Some(ModelOutcome::Exit { code: 130 }),
642            KeyCode::Char('u') if view.focus != Focus::Help => {
643                view.query.clear();
644                view.verdict_filter = None;
645                view.month_filter = None;
646                view.filter();
647            }
648            _ => (),
649        }
650        return None;
651    }
652    if key
653        .modifiers
654        .intersects(KeyModifiers::ALT | KeyModifiers::SUPER)
655    {
656        return None;
657    }
658    if view.searching {
659        match key.code {
660            KeyCode::Esc | KeyCode::Enter => view.searching = false,
661            KeyCode::Backspace | KeyCode::Delete => {
662                if let Some((index, _)) = view.query.grapheme_indices(true).next_back() {
663                    view.query.truncate(index);
664                }
665                view.filter();
666            }
667            KeyCode::Char(character) if !character.is_control() => {
668                view.append_query(&character.to_string())
669            }
670            _ => (),
671        }
672        return None;
673    }
674    if view.focus == Focus::Help {
675        match key.code {
676            KeyCode::Esc | KeyCode::Left | KeyCode::Backspace => {
677                view.toggle_help();
678                return None;
679            }
680            KeyCode::Char('?' | 'q' | 'j' | 'k' | 'p')
681            | KeyCode::Up
682            | KeyCode::Down
683            | KeyCode::PageUp
684            | KeyCode::PageDown
685            | KeyCode::Home
686            | KeyCode::End => (),
687            _ => return None,
688        }
689    }
690    let position = if view.focus == Focus::List {
691        view.list.selected().unwrap_or(0)
692    } else {
693        view.scroll
694    };
695    let page = if view.focus == Focus::List {
696        view.page
697    } else {
698        view.detail_page
699    };
700    match key.code {
701        KeyCode::Char('q') => return Some(ModelOutcome::Exit { code: 0 }),
702        KeyCode::Char('?') if key.kind == KeyEventKind::Press => view.toggle_help(),
703        KeyCode::Char(' ')
704            if key.kind == KeyEventKind::Press
705                && view.comparison
706                && matches!(view.focus, Focus::List | Focus::Detail) =>
707        {
708            view.toggle_mark()
709        }
710        KeyCode::Char('c') if key.kind == KeyEventKind::Press && view.comparison => {
711            if view.focus == Focus::Compare {
712                view.focus(Focus::List);
713            } else if view.marked.len() < 2 {
714                view.notice = Some("Mark at least 2 models with Space to compare (max 4)");
715            } else {
716                view.notice = None;
717                view.focus(Focus::Compare);
718            }
719        }
720        KeyCode::Esc if view.focus == Focus::List => return Some(ModelOutcome::Exit { code: 0 }),
721        KeyCode::Esc | KeyCode::Left | KeyCode::Backspace => view.focus(Focus::List),
722        KeyCode::Enter | KeyCode::Tab | KeyCode::BackTab => {
723            if view.focus == Focus::List && view.selected().is_some() {
724                view.focus(Focus::Detail);
725            } else {
726                view.focus(Focus::List);
727            }
728        }
729        KeyCode::Right if view.selected().is_some() => view.focus(Focus::Detail),
730        KeyCode::Char('i') => view.focus(if view.focus == Focus::Overview {
731            Focus::List
732        } else {
733            Focus::Overview
734        }),
735        KeyCode::Char('/') => {
736            view.searching = true;
737            view.focus(Focus::List);
738        }
739        KeyCode::Down | KeyCode::Char('j') => view.move_to(position.saturating_add(1)),
740        KeyCode::Up | KeyCode::Char('k') => view.move_to(position.saturating_sub(1)),
741        KeyCode::PageDown => view.move_to(position.saturating_add(page)),
742        KeyCode::PageUp => view.move_to(position.saturating_sub(page)),
743        KeyCode::Home => view.move_to(0),
744        KeyCode::End => view.move_to(usize::MAX),
745        KeyCode::Char('p') if key.kind == KeyEventKind::Press => {
746            return view
747                .command
748                .as_ref()
749                .map(|command| ModelOutcome::PrintCommand {
750                    command: command.clone(),
751                });
752        }
753        KeyCode::Char('s') if view.focus == Focus::List => view.cycle_sort(None),
754        KeyCode::Char('S') if view.focus == Focus::List => {
755            if let Some((column, descending)) = view.sort {
756                view.sort = Some((column, !descending));
757                view.filter();
758            }
759        }
760        KeyCode::Char('m') if view.focus == Focus::List && view.month_cutoffs.is_some() => {
761            view.month_filter = match view.month_filter {
762                None => Some(1),
763                Some(months) if months < 3 => Some(months + 1),
764                Some(_) => None,
765            };
766            view.filter();
767        }
768        KeyCode::Char('v') if view.focus == Focus::List && !view.columns.is_empty() => {
769            view.verdict_filter = match view.verdict_filter {
770                None => Some(Verdict::Yes),
771                Some(Verdict::Yes) => Some(Verdict::Slow),
772                Some(Verdict::Slow) => Some(Verdict::No),
773                Some(Verdict::No) => Some(Verdict::Unknown),
774                Some(Verdict::Unknown) => None,
775            };
776            view.filter();
777        }
778        KeyCode::Char('y') => {
779            if let Some(index) = view.selected_index() {
780                let label = view.rows[index].label.clone();
781                view.copy(label, "model id");
782            }
783        }
784        KeyCode::Char('Y') => {
785            if let Some(index) = view.selected_index() {
786                let label = view.rows[index].label.clone();
787                if command_safe(&label) {
788                    view.copy(format!("rigspark up {label}"), "up command");
789                } else {
790                    view.notice = Some("Model id is not safe to copy as a command");
791                }
792            }
793        }
794        KeyCode::Char('e') => {
795            if let Some(index) = view.selected_index() {
796                let card = view.card(&view.rows[index]);
797                view.copy(card, "shareable card");
798            }
799        }
800        _ => (),
801    }
802    None
803}
804
805fn command_safe(id: &str) -> bool {
806    !id.is_empty()
807        && !id.starts_with('-')
808        && !id.split('/').any(|part| part == "..")
809        && id.bytes().all(|byte| {
810            byte.is_ascii_lowercase() || byte.is_ascii_digit() || b"._:/-".contains(&byte)
811        })
812}
813
814/// Unknowns sort last in both directions; numbers compare numerically, then text.
815fn sort_key(row: &ModelRow, column: usize) -> (u8, f64, String) {
816    let cells = row.cells();
817    let text = if column == 0 {
818        row.label.as_str()
819    } else {
820        cells.get(column - 1).copied().unwrap_or("")
821    };
822    if column > 0 {
823        match tui_theme::verdict_kind(text) {
824            Some(Verdict::Unknown) => return (1, 0.0, String::new()),
825            Some(verdict) => return (0, f64::from(verdict as u8), String::new()),
826            None => (),
827        }
828    }
829    let lower = text.to_lowercase();
830    if text.is_empty() || lower.starts_with("unknown") {
831        return (1, 0.0, lower);
832    }
833    let number = if column == 0 {
834        0.0
835    } else {
836        let digits: String = text
837            .chars()
838            .skip_while(|character| !character.is_ascii_digit())
839            .take_while(|character| character.is_ascii_digit() || *character == '.')
840            .collect();
841        digits.parse().unwrap_or(0.0)
842    };
843    (0, number, lower)
844}
845
846/// Wheel scrolls the pane under the pointer; clicks select rows, open the selected row, or sort by a header.
847pub fn handle_mouse(view: &mut ModelView, mouse: MouseEvent) {
848    let point = Position::new(mouse.column, mouse.row);
849    view.toast = None;
850    match mouse.kind {
851        MouseEventKind::ScrollDown | MouseEventKind::ScrollUp => {
852            let down = mouse.kind == MouseEventKind::ScrollDown;
853            if view.focus == Focus::List && !view.areas.detail.contains(point) {
854                let position = view.list.selected().unwrap_or(0);
855                view.move_to(if down {
856                    position.saturating_add(1)
857                } else {
858                    position.saturating_sub(1)
859                });
860            } else if view.focus != Focus::List {
861                view.scroll = if down {
862                    view.scroll.saturating_add(3).min(view.scroll_max)
863                } else {
864                    view.scroll.saturating_sub(3)
865                };
866            }
867        }
868        MouseEventKind::Down(MouseButton::Left) if view.focus == Focus::List => {
869            if let Some((_, column)) = view
870                .areas
871                .header
872                .iter()
873                .find(|(area, _)| area.contains(point))
874            {
875                let column = *column;
876                view.cycle_sort(Some(column));
877            } else if view.areas.rows.contains(point) {
878                let row = view.list.offset() + usize::from(point.y - view.areas.rows.y);
879                if row < view.visible.len() {
880                    if view.list.selected() == Some(row) {
881                        view.focus(Focus::Detail);
882                    } else {
883                        view.list.select(Some(row));
884                    }
885                }
886            }
887        }
888        _ => (),
889    }
890}
891
892pub fn handle_event(view: &mut ModelView, event: Event) -> Option<ModelOutcome> {
893    match event {
894        Event::Key(key) => handle_key(view, key),
895        Event::Mouse(mouse) => {
896            handle_mouse(view, mouse);
897            None
898        }
899        Event::Paste(text) if view.searching => {
900            view.append_query(&text);
901            None
902        }
903        _ => None,
904    }
905}
906
907/// Evidence labels emitted by the presentation builders, longest prefixes first.
908const EVIDENCE_KEYS: [&str; 24] = [
909    "throughput backend",
910    "unknown reason",
911    "KV bytes/token",
912    "selected quant",
913    "quantizations",
914    "capabilities",
915    "architecture",
916    "open weight",
917    "throughput",
918    "benchmark",
919    "backends",
920    "release",
921    "license",
922    "context",
923    "verdict",
924    "sources",
925    "family",
926    "params",
927    "scores",
928    "source",
929    "score",
930    "rank",
931    "need",
932    "fit",
933];
934
935enum Entry {
936    Heading(String),
937    Note(String),
938    Plain(String),
939    Field { key: String, value: String },
940    Blank,
941}
942
943fn split_key(segment: &str) -> Entry {
944    EVIDENCE_KEYS
945        .iter()
946        .find_map(|key| {
947            segment
948                .strip_prefix(key)
949                .and_then(|rest| rest.strip_prefix(' '))
950                .map(|value| Entry::Field {
951                    key: (*key).to_owned(),
952                    value: value.to_owned(),
953                })
954        })
955        .unwrap_or_else(|| Entry::Field {
956            key: String::new(),
957            value: segment.to_owned(),
958        })
959}
960
961fn evidence_entries(row: &ModelRow, entries: &mut Vec<Entry>) {
962    for (index, segment) in row
963        .evidence
964        .lines()
965        .flat_map(|line| line.split("; "))
966        .enumerate()
967    {
968        entries.push(if index == 0 && segment == row.label {
969            Entry::Heading(segment.to_owned())
970        } else {
971            split_key(segment)
972        });
973    }
974}
975
976/// Lays out entries with right-aligned keys so every `key value` stays contiguous.
977fn layout(entries: &[Entry], width: u16, theme: Theme, key_style: Style) -> Vec<Line<'static>> {
978    let width = usize::from(width.max(1));
979    let key_width = entries
980        .iter()
981        .filter_map(|entry| match entry {
982            Entry::Field { key, .. } => Some(tui_theme::width(key)),
983            _ => None,
984        })
985        .max()
986        .unwrap_or(0)
987        .min(width / 3);
988    let aligned = width >= 30;
989    let mut lines = Vec::new();
990    for entry in entries {
991        match entry {
992            Entry::Heading(text) => lines.extend(
993                tui_theme::wrap(text, width)
994                    .into_iter()
995                    .map(|line| Line::styled(line, theme.title())),
996            ),
997            Entry::Note(text) => lines.extend(
998                tui_theme::wrap(text, width)
999                    .into_iter()
1000                    .map(|line| Line::styled(line, theme.muted())),
1001            ),
1002            Entry::Plain(text) => {
1003                lines.extend(tui_theme::wrap(text, width).into_iter().map(Line::from))
1004            }
1005            Entry::Blank => lines.push(Line::default()),
1006            Entry::Field { key, value } if !aligned => {
1007                let text = if key.is_empty() {
1008                    value.clone()
1009                } else {
1010                    format!("{key} {value}")
1011                };
1012                lines.extend(tui_theme::wrap(&text, width).into_iter().map(Line::from));
1013            }
1014            Entry::Field { key, value } => {
1015                let key_cells = tui_theme::width(key);
1016                let indent = key_width.max(key_cells) + 1;
1017                let value_style = match key.as_str() {
1018                    "verdict" | "fit" => theme.verdict(value),
1019                    _ => Style::default(),
1020                };
1021                let items: Vec<&str> = if matches!(key.as_str(), "sources" | "quantizations") {
1022                    value.split(", ").collect()
1023                } else {
1024                    vec![value.as_str()]
1025                };
1026                let mut first = true;
1027                for item in items {
1028                    for piece in tui_theme::wrap(item, width.saturating_sub(indent)) {
1029                        let mut spans = Vec::with_capacity(4);
1030                        if first && !key.is_empty() {
1031                            spans.push(Span::raw(" ".repeat(key_width.saturating_sub(key_cells))));
1032                            spans.push(Span::styled(key.clone(), key_style));
1033                            spans.push(Span::raw(" "));
1034                        } else {
1035                            spans.push(Span::raw(" ".repeat(indent)));
1036                        }
1037                        spans.push(Span::styled(piece, value_style));
1038                        lines.push(Line::from(spans));
1039                        first = false;
1040                    }
1041                }
1042            }
1043        }
1044    }
1045    lines
1046}
1047
1048fn render_detail(frame: &mut Frame<'_>, view: &mut ModelView, area: Rect, theme: Theme) {
1049    let title = match view.focus {
1050        Focus::Overview => "Machine / scope".to_owned(),
1051        Focus::Help => "Keyboard help".to_owned(),
1052        Focus::Compare => format!("Compare {} models", view.marked.len()),
1053        _ => "Evidence".to_owned(),
1054    };
1055    let inner = theme.panel(frame, area, &title);
1056    let lines = if view.focus == Focus::Help {
1057        let mut help = vec![
1058            "Up/Down or j/k: navigate list or scroll screen",
1059            "PageUp/PageDown: page; Home/End: first/last",
1060            "/: search; Enter/Esc: close search; Ctrl+U: reset filter",
1061            "Enter/Right/Tab: details; Left/Backspace/Esc: back",
1062            "i: machine/scope; ?: toggle help",
1063            "s: sort by next column (Model, then each column, then original); S: reverse",
1064            "y: copy model id; Y: copy `rigspark up` command; e: copy shareable card",
1065            "Mouse: wheel scrolls; click selects, click again opens; click a header sorts",
1066            "Esc: back from screen; Esc on list or q: quit",
1067            "Ctrl+C: interrupt (exit 130)",
1068            "Read-only: stored evidence only; no actions execute",
1069        ];
1070        if view.comparison {
1071            help.extend([
1072                "Space: mark/unmark selected model (max 4)",
1073                "c: compare 2-4 marked models / return to list",
1074                "Marks survive filtering; * identifies a marked model",
1075            ]);
1076        }
1077        if !view.columns.is_empty() {
1078            help.push("v: cycle verdict filter (yes, slow, no, unknown, all)");
1079        }
1080        if view.month_cutoffs.is_some() {
1081            help.push("m: cycle recency filter (released or added in 1, 2, 3 months, all)");
1082        }
1083        if view.command.is_some() {
1084            help.push("p: finish and print existing top-pick command; never execute");
1085        }
1086        let entries: Vec<_> = help
1087            .into_iter()
1088            .map(|line| match line.split_once(": ") {
1089                Some((key, value)) => Entry::Field {
1090                    key: format!("{key}:"),
1091                    value: value.to_owned(),
1092                },
1093                None => Entry::Plain(line.to_owned()),
1094            })
1095            .collect();
1096        layout(&entries, inner.width, theme, theme.title())
1097    } else if view.focus == Focus::Compare {
1098        compare_lines(view, inner.width, theme).unwrap_or_else(|| {
1099            let mut entries = Vec::new();
1100            for index in &view.marked {
1101                let row = &view.rows[*index];
1102                if !entries.is_empty() {
1103                    entries.push(Entry::Blank);
1104                }
1105                entries.push(Entry::Heading(row.label.clone()));
1106                if !row.summary.is_empty() {
1107                    entries.push(Entry::Note(row.summary.clone()));
1108                }
1109                let mut evidence = Vec::new();
1110                evidence_entries(row, &mut evidence);
1111                if matches!(evidence.first(), Some(Entry::Heading(_))) {
1112                    evidence.remove(0);
1113                }
1114                entries.extend(evidence);
1115            }
1116            layout(&entries, inner.width, theme, theme.muted())
1117        })
1118    } else if view.focus == Focus::Overview {
1119        let entries: Vec<_> = view
1120            .overview
1121            .iter()
1122            .map(|line| Entry::Plain(line.clone()))
1123            .collect();
1124        layout(&entries, inner.width, theme, theme.muted())
1125    } else if let Some(row) = view.selected() {
1126        let mut entries = Vec::new();
1127        evidence_entries(row, &mut entries);
1128        let heading = matches!(entries.first(), Some(Entry::Heading(_)));
1129        if heading {
1130            entries.insert(1, Entry::Blank);
1131        }
1132        let mut lines = layout(&entries, inner.width, theme, theme.muted());
1133        if let Some(usable) = view.usable_bytes {
1134            let gauge = match row.need_bytes {
1135                Some(need) => tui_theme::gauge(
1136                    theme,
1137                    need,
1138                    usable,
1139                    usize::from(inner.width).saturating_sub(8),
1140                ),
1141                None => Line::styled("need unknown", theme.muted()),
1142            };
1143            let mut spans = vec![Span::styled("Memory  ", theme.muted())];
1144            spans.extend(gauge.spans);
1145            lines.insert(usize::from(heading), Line::from(spans));
1146        }
1147        lines
1148    } else {
1149        vec![Line::styled("No model selected", theme.muted())]
1150    };
1151    view.detail_page = usize::from(inner.height.max(1));
1152    view.scroll_max = lines.len().saturating_sub(view.detail_page);
1153    view.scroll = view.scroll.min(view.scroll_max);
1154    let total = lines.len();
1155    let visible: Vec<_> = lines
1156        .into_iter()
1157        .skip(view.scroll)
1158        .take(view.detail_page)
1159        .collect();
1160    frame.render_widget(Paragraph::new(visible), inner);
1161    tui_theme::scrollbar(frame, area, total, view.scroll, view.detail_page, theme);
1162}
1163
1164/// Side-by-side comparison aligned by evidence key; `None` when columns would be too narrow.
1165fn compare_lines(view: &ModelView, width: u16, theme: Theme) -> Option<Vec<Line<'static>>> {
1166    let width = usize::from(width);
1167    let count = view.marked.len();
1168    if count == 0 {
1169        return None;
1170    }
1171    let mut order: Vec<String> = Vec::new();
1172    let mut tables: Vec<Vec<(String, String)>> = Vec::new();
1173    for index in &view.marked {
1174        let row = &view.rows[*index];
1175        let mut entries = Vec::new();
1176        evidence_entries(row, &mut entries);
1177        let mut unkeyed = 0;
1178        let mut fields = Vec::new();
1179        for entry in entries {
1180            if let Entry::Field { key, value } = entry {
1181                let id = if key.is_empty() {
1182                    unkeyed += 1;
1183                    format!("\u{0}{unkeyed}")
1184                } else {
1185                    key
1186                };
1187                if !order.contains(&id) {
1188                    order.push(id.clone());
1189                }
1190                fields.push((id, value));
1191            }
1192        }
1193        tables.push(fields);
1194    }
1195    let display = |id: &str| {
1196        if id.starts_with('\u{0}') {
1197            String::new()
1198        } else {
1199            id.to_owned()
1200        }
1201    };
1202    let key_width = order
1203        .iter()
1204        .map(|id| tui_theme::width(&display(id)))
1205        .max()
1206        .unwrap_or(0)
1207        .min(18);
1208    let cell = width.checked_sub(key_width + 3 * count)? / count;
1209    if cell < 14 {
1210        return None;
1211    }
1212    let pad = |text: &str, width: usize| {
1213        format!(
1214            "{text}{}",
1215            " ".repeat(width.saturating_sub(tui_theme::width(text)))
1216        )
1217    };
1218    let mut lines = Vec::new();
1219    let mut header = vec![Span::raw(" ".repeat(key_width))];
1220    for index in &view.marked {
1221        header.push(Span::styled(" │ ", theme.border()));
1222        let label = tui_theme::truncate(vec![Span::raw(view.rows[*index].label.clone())], cell);
1223        let text: String = label.iter().map(|span| span.content.as_ref()).collect();
1224        header.push(Span::styled(pad(&text, cell), theme.title()));
1225    }
1226    lines.push(Line::from(header));
1227    lines.push(Line::styled("─".repeat(width), theme.border()));
1228    let mut rows: Vec<(String, Vec<String>)> = vec![(
1229        "summary".into(),
1230        view.marked
1231            .iter()
1232            .map(|index| view.rows[*index].cells().join(" · "))
1233            .collect(),
1234    )];
1235    for id in &order {
1236        rows.push((
1237            display(id),
1238            tables
1239                .iter()
1240                .map(|fields| {
1241                    fields
1242                        .iter()
1243                        .find(|(key, _)| key == id)
1244                        .map_or_else(|| "—".into(), |(_, value)| value.clone())
1245                })
1246                .collect(),
1247        ));
1248    }
1249    for (key, values) in rows {
1250        let wrapped: Vec<Vec<String>> = values
1251            .iter()
1252            .map(|value| tui_theme::wrap(value, cell))
1253            .collect();
1254        let height = wrapped.iter().map(Vec::len).max().unwrap_or(1);
1255        for line in 0..height {
1256            let key_text = if line == 0 { key.as_str() } else { "" };
1257            let mut spans = vec![Span::styled(
1258                pad(
1259                    &key_text.chars().take(key_width).collect::<String>(),
1260                    key_width,
1261                ),
1262                theme.muted(),
1263            )];
1264            for (column, cells) in wrapped.iter().enumerate() {
1265                spans.push(Span::styled(" │ ", theme.border()));
1266                let text = cells.get(line).cloned().unwrap_or_default();
1267                let style = match key.as_str() {
1268                    "verdict" | "fit" => theme.verdict(&values[column]),
1269                    "summary" => theme.muted(),
1270                    _ => Style::default(),
1271                };
1272                spans.push(Span::styled(pad(&text, cell), style));
1273            }
1274            lines.push(Line::from(spans));
1275        }
1276    }
1277    Some(lines)
1278}
1279
1280fn render_table(frame: &mut Frame<'_>, view: &mut ModelView, area: Rect, theme: Theme) {
1281    let inner = theme.panel(
1282        frame,
1283        area,
1284        &format!("Models {}/{}", view.visible_count(), view.rows.len()),
1285    );
1286    view.areas.header.clear();
1287    view.areas.rows = Rect::default();
1288    if view.visible.is_empty() {
1289        let mut lines = vec![Line::styled("No results", theme.muted())];
1290        if !view.query.is_empty() || view.verdict_filter.is_some() || view.month_filter.is_some() {
1291            lines.push(Line::styled("Ctrl+U resets the filter", theme.muted()));
1292        }
1293        frame.render_widget(Paragraph::new(lines), inner);
1294        return;
1295    }
1296    let header_row = inner.height >= 3;
1297    let available = usize::from(inner.width).saturating_sub(2);
1298    let widths: Vec<usize> = (0..view.columns.len())
1299        .map(|column| {
1300            view.visible
1301                .iter()
1302                .map(|index| {
1303                    view.rows[*index]
1304                        .cells()
1305                        .get(column)
1306                        .map_or(0, |text| tui_theme::width(text))
1307                })
1308                .max()
1309                .unwrap_or(0)
1310                .max(tui_theme::width(view.columns[column]) + 2)
1311                .min(18)
1312        })
1313        .collect();
1314    let model_width = view
1315        .visible
1316        .iter()
1317        .map(|index| tui_theme::width(&view.rows[*index].label) + 2)
1318        .max()
1319        .unwrap_or(12)
1320        .clamp(12, 28);
1321    let mut shown: Vec<usize> = (0..view.columns.len()).collect();
1322    let mut droppable = view.priority.clone();
1323    while shown
1324        .iter()
1325        .map(|column| widths[*column] + 1)
1326        .sum::<usize>()
1327        + model_width
1328        > available
1329    {
1330        let Some(victim) = droppable.pop() else {
1331            shown.clear();
1332            break;
1333        };
1334        shown.retain(|column| *column != victim);
1335    }
1336    let arrow = |column: usize| match view.sort {
1337        Some((sorted, descending)) if sorted == column => {
1338            if descending {
1339                " ▼"
1340            } else {
1341                " ▲"
1342            }
1343        }
1344        _ => "",
1345    };
1346    let mut constraints = vec![Constraint::Min(u16::try_from(model_width).unwrap_or(12))];
1347    constraints.extend(
1348        shown
1349            .iter()
1350            .map(|column| Constraint::Length(u16::try_from(widths[*column]).unwrap_or(18))),
1351    );
1352    let rows: Vec<Row> = view
1353        .visible
1354        .iter()
1355        .enumerate()
1356        .map(|(position, index)| {
1357            let row = &view.rows[*index];
1358            let mut label = vec![if view.marked.contains(index) {
1359                Span::styled("* ", theme.title())
1360            } else {
1361                Span::raw("  ")
1362            }];
1363            label.extend(tui_theme::highlighted(
1364                &row.label,
1365                view.matches.get(position).map_or(&[], Vec::as_slice),
1366                theme.strong(),
1367                theme,
1368            ));
1369            let cells = row.cells();
1370            let mut columns = vec![Cell::from(Line::from(label))];
1371            for column in &shown {
1372                let text = cells.get(*column).copied().unwrap_or("");
1373                let style = if tui_theme::verdict_kind(text).is_some() {
1374                    theme.verdict(text)
1375                } else {
1376                    Style::default()
1377                };
1378                columns.push(Cell::from(Span::styled(text.to_owned(), style)));
1379            }
1380            Row::new(columns)
1381        })
1382        .collect();
1383    let mut table = Table::new(rows, constraints.clone())
1384        .column_spacing(1)
1385        .highlight_symbol("▸ ")
1386        .highlight_spacing(HighlightSpacing::Always)
1387        .row_highlight_style(theme.selection());
1388    if header_row {
1389        let mut header = vec![Cell::from(format!("Model{}", arrow(0)))];
1390        header.extend(
1391            shown.iter().map(|column| {
1392                Cell::from(format!("{}{}", view.columns[*column], arrow(column + 1)))
1393            }),
1394        );
1395        table = table.header(Row::new(header).style(theme.title()));
1396    }
1397    frame.render_stateful_widget(table, inner, &mut view.list);
1398    let body_offset = u16::from(header_row);
1399    view.page = usize::from(inner.height.saturating_sub(body_offset)).max(1);
1400    view.areas.rows = Rect {
1401        y: inner.y + body_offset,
1402        height: inner.height.saturating_sub(body_offset),
1403        ..inner
1404    };
1405    if header_row {
1406        let header_area = Rect {
1407            x: inner.x + 2,
1408            width: inner.width.saturating_sub(2),
1409            height: 1,
1410            ..inner
1411        };
1412        let cells = Layout::horizontal(constraints)
1413            .spacing(1)
1414            .split(header_area);
1415        view.areas.header = cells
1416            .iter()
1417            .enumerate()
1418            .map(|(position, area)| {
1419                (
1420                    *area,
1421                    if position == 0 {
1422                        0
1423                    } else {
1424                        shown[position - 1] + 1
1425                    },
1426                )
1427            })
1428            .collect();
1429    }
1430    tui_theme::scrollbar(
1431        frame,
1432        area,
1433        view.visible.len(),
1434        view.list.offset(),
1435        view.page,
1436        theme,
1437    );
1438}
1439
1440pub fn render(frame: &mut Frame<'_>, view: &mut ModelView) {
1441    let area = frame.area();
1442    if area.is_empty() {
1443        return;
1444    }
1445    let theme = Theme::new(view.color);
1446    let compact_overview = area.height >= 12 && !view.overview.is_empty();
1447    let overview: Vec<String> = view
1448        .overview
1449        .iter()
1450        .take(2)
1451        .flat_map(|line| tui_theme::wrap(line, usize::from(area.width.saturating_sub(4))))
1452        .take(3)
1453        .collect();
1454    let context_height = if area.height >= 28 && !overview.is_empty() {
1455        overview.len() + 2
1456    } else if compact_overview {
1457        view.overview.len().min(2)
1458    } else {
1459        0
1460    };
1461    let [header, context, body, status, footer] = Layout::vertical([
1462        Constraint::Length(1),
1463        Constraint::Length(u16::try_from(context_height).unwrap_or(0)),
1464        Constraint::Min(0),
1465        Constraint::Length(if area.height >= 3 { 1 } else { 0 }),
1466        Constraint::Length(if area.height >= 2 { 1 } else { 0 }),
1467    ])
1468    .areas(area);
1469    theme.header(
1470        frame,
1471        header,
1472        &format!("rigspark / {}", view.title),
1473        "Read-only",
1474    );
1475    if context.height > 2 {
1476        let inner = theme.panel(frame, context, "Machine / scope");
1477        let lines: Vec<_> = overview
1478            .into_iter()
1479            .enumerate()
1480            .map(|(index, line)| {
1481                if index == 0 {
1482                    Line::from(line)
1483                } else {
1484                    Line::styled(line, theme.muted())
1485                }
1486            })
1487            .collect();
1488        frame.render_widget(Paragraph::new(lines), inner);
1489    } else {
1490        let lines: Vec<_> = view
1491            .overview
1492            .iter()
1493            .take(2)
1494            .map(|line| Line::styled(format!(" {line}"), theme.muted()))
1495            .collect();
1496        frame.render_widget(Paragraph::new(lines), context);
1497    }
1498    if view.focus != Focus::List {
1499        view.areas = HitAreas::default();
1500        render_detail(frame, view, body, theme);
1501    } else {
1502        let (list_area, detail_area) = if body.width >= 110 {
1503            let [list, detail] =
1504                Layout::horizontal([Constraint::Percentage(55), Constraint::Percentage(45)])
1505                    .areas(body);
1506            (list, Some(detail))
1507        } else if body.height >= 14 {
1508            let [list, detail] =
1509                Layout::vertical([Constraint::Percentage(50), Constraint::Percentage(50)])
1510                    .areas(body);
1511            (list, Some(detail))
1512        } else {
1513            (body, None)
1514        };
1515        render_table(frame, view, list_area, theme);
1516        if let Some(detail) = detail_area {
1517            render_detail(frame, view, detail, theme);
1518            view.areas.detail = detail;
1519        } else {
1520            view.areas.detail = Rect::default();
1521        }
1522    }
1523    if let Some(toast) = &view.toast {
1524        let width = u16::try_from(tui_theme::width(toast) + 4)
1525            .unwrap_or(u16::MAX)
1526            .min(body.width);
1527        if body.height >= 3 && width >= 8 {
1528            let area = Rect {
1529                x: body.right() - width,
1530                y: body.bottom() - 3,
1531                width,
1532                height: 3,
1533            };
1534            frame.render_widget(Clear, area);
1535            let inner = theme.panel(frame, area, "");
1536            frame.render_widget(
1537                Paragraph::new(Line::styled(toast.clone(), theme.success())),
1538                inner,
1539            );
1540        }
1541    }
1542    let left = if view.searching {
1543        Line::from(vec![
1544            Span::styled(" /", theme.title()),
1545            Span::raw(view.query.clone()),
1546            Span::styled("▌", theme.accent()),
1547        ])
1548    } else if let Some(notice) = view.notice {
1549        Line::styled(format!(" {notice}"), theme.warning())
1550    } else if !view.query.is_empty() {
1551        Line::from(vec![
1552            Span::styled(" Filter ", theme.muted()),
1553            Span::styled(view.query.clone(), theme.accent()),
1554        ])
1555    } else {
1556        Line::default()
1557    };
1558    let mut position = if view.focus == Focus::List {
1559        format!(
1560            "{}/{}",
1561            view.list.selected().map_or(0, |index| index + 1),
1562            view.visible_count()
1563        )
1564    } else {
1565        format!("Line {}/{}", view.scroll + 1, view.scroll_max + 1)
1566    };
1567    if view.comparison {
1568        position.push_str(&format!(" · Marked {}/{MAX_MARKED}", view.marked.len()));
1569    }
1570    if let Some(months) = view.month_filter {
1571        position.insert_str(0, &format!("last {months} mo · "));
1572    }
1573    if let Some(verdict) = view.verdict_filter {
1574        position.insert_str(
1575            0,
1576            &format!("verdict {} · ", format!("{verdict:?}").to_lowercase()),
1577        );
1578    }
1579    if let Some((column, descending)) = view.sort {
1580        let name = if column == 0 {
1581            "model"
1582        } else {
1583            view.columns.get(column - 1).copied().unwrap_or("?")
1584        };
1585        position.insert_str(
1586            0,
1587            &format!(
1588                "sort {} {} · ",
1589                name.to_lowercase(),
1590                if descending { "▼" } else { "▲" }
1591            ),
1592        );
1593    }
1594    theme.bar(
1595        frame,
1596        status,
1597        left,
1598        Line::styled(format!("{position} "), theme.muted()),
1599    );
1600    let mut hints: Vec<(&str, &str)> = if view.searching {
1601        vec![("Enter", "apply"), ("Esc", "close"), ("Ctrl+U", "reset")]
1602    } else if view.focus == Focus::Help {
1603        vec![("Esc", "back"), ("↑↓", "scroll"), ("q", "quit")]
1604    } else if view.focus != Focus::List {
1605        vec![
1606            ("Esc", "back"),
1607            ("↑↓", "scroll"),
1608            ("Home/End", "jump"),
1609            ("?", "help"),
1610            ("q", "quit"),
1611        ]
1612    } else {
1613        vec![
1614            ("q", "quit"),
1615            ("?", "help"),
1616            ("/", "search"),
1617            ("Enter", "detail"),
1618            ("s", "sort"),
1619        ]
1620    };
1621    if !view.searching && view.focus == Focus::List {
1622        if !view.columns.is_empty() {
1623            hints.push(("v", "verdict"));
1624        }
1625        if view.month_cutoffs.is_some() {
1626            hints.push(("m", "recent"));
1627        }
1628        hints.push(("y", "copy"));
1629        if view.comparison {
1630            hints.extend([("Space", "mark"), ("c", "compare")]);
1631        } else {
1632            hints.push(("i", "overview"));
1633        }
1634        if view.command.is_some() {
1635            hints.push(("p", "finish/print"));
1636        }
1637    }
1638    frame.render_widget(Paragraph::new(theme.hints(&hints, footer.width)), footer);
1639}
1640
1641pub async fn show_models(mut view: ModelView) -> io::Result<ModelOutcome> {
1642    let mut signals = crate::cancellation::TerminalSignals::new()?;
1643    let (mut terminal, _restore) = crate::tui_view::enter_terminal()?;
1644    let mut events = crate::terminal_events::terminal_events();
1645    loop {
1646        terminal.draw(|frame| render(frame, &mut view))?;
1647        let expiry = tokio::time::sleep(std::time::Duration::from_millis(2500));
1648        let event = tokio::select! {
1649            code = signals.recv() => return Ok(ModelOutcome::Exit { code: code? }),
1650            event = crate::tui_view::next_navigation_event(&mut events) => event?,
1651            () = expiry, if view.toast.is_some() => {
1652                view.toast = None;
1653                continue;
1654            }
1655        };
1656        if let Some(outcome) = handle_event(&mut view, event) {
1657            return Ok(outcome);
1658        }
1659        if let Some(text) = view.take_clipboard() {
1660            tui_theme::copy_to_clipboard(&text)?;
1661        }
1662    }
1663}
1664
1665#[cfg(test)]
1666mod recency_tests {
1667    use super::*;
1668
1669    #[test]
1670    fn m_cycles_month_windows_over_release_or_added_dates() {
1671        let rows = ["new:8b", "older:8b", "undated:8b"]
1672            .iter()
1673            .map(|id| ModelRow::new(id, id, "evidence"))
1674            .collect::<io::Result<Vec<_>>>()
1675            .unwrap();
1676        let dates = [("new:8b", "2026-09-30"), ("older:8b", "2026-08-01")]
1677            .into_iter()
1678            .map(|(id, day)| (id.to_string(), day.to_string()))
1679            .collect();
1680        let mut view = ModelView::new("Catalog", Vec::new(), rows, false)
1681            .unwrap()
1682            .with_recency(&dates, "2026-10-07")
1683            .unwrap();
1684        let key = KeyEvent::new(KeyCode::Char('m'), KeyModifiers::NONE);
1685        let shown = |view: &ModelView| {
1686            view.visible
1687                .iter()
1688                .map(|index| view.rows[*index].label.clone())
1689                .collect::<Vec<_>>()
1690        };
1691        assert_eq!(shown(&view).len(), 3);
1692        handle_key(&mut view, key);
1693        assert_eq!(shown(&view), ["new:8b"], "1 month");
1694        handle_key(&mut view, key);
1695        handle_key(&mut view, key);
1696        assert_eq!(
1697            shown(&view),
1698            ["new:8b", "older:8b"],
1699            "3 months; undated is never assumed recent"
1700        );
1701        handle_key(&mut view, key);
1702        assert_eq!(shown(&view).len(), 3, "back to all");
1703    }
1704}
1705
1706#[cfg(test)]
1707mod boundary_tests {
1708    use super::*;
1709    use serde_json::json;
1710
1711    fn row(label: &str, summary: &str, evidence: &str) -> ModelRow {
1712        let mut row = ModelRow::new(label, label, evidence).unwrap();
1713        row.summary = summary.into();
1714        row
1715    }
1716    fn view(rows: Vec<ModelRow>) -> ModelView {
1717        ModelView::new("Recommend", vec!["Machine: test".into()], rows, false)
1718            .unwrap()
1719            .with_columns(&["Rank", "Need", "Verdict"], &[0, 1, 2])
1720    }
1721    fn three() -> ModelView {
1722        view(vec![
1723            row(
1724                "alpha:8b",
1725                "1 | 5.2 GiB | yes",
1726                "alpha:8b; verdict yes; note",
1727            ),
1728            row("beta:8b", "2 | 9.1 GiB | slow", "beta:8b; verdict slow"),
1729            row("gamma:8b", "3 | unknown | no", "gamma:8b; verdict no"),
1730        ])
1731    }
1732    fn press(code: KeyCode) -> KeyEvent {
1733        KeyEvent::new(code, KeyModifiers::NONE)
1734    }
1735    fn key(view: &mut ModelView, code: KeyCode) -> Option<ModelOutcome> {
1736        handle_key(view, press(code))
1737    }
1738    fn labels(view: &ModelView) -> Vec<&str> {
1739        view.visible
1740            .iter()
1741            .map(|index| view.rows[*index].label.as_str())
1742            .collect()
1743    }
1744    fn bound(value: &Value) -> bool {
1745        bound_can_run(value, 0, &mut MAX_DOCUMENT.clone()).is_ok()
1746    }
1747    fn nested(depth: usize, wrap: fn(Value) -> Value) -> Value {
1748        (0..depth).fold(json!("x"), |inner, _| wrap(inner))
1749    }
1750
1751    #[test]
1752    fn can_run_evidence_bounds_depth_text_rows_and_keys() {
1753        assert!(bound(&nested(16, |inner| json!([inner]))));
1754        assert!(!bound(&nested(17, |inner| json!([inner]))));
1755        assert!(bound(&nested(16, |inner| json!({ "k": inner }))));
1756        assert!(!bound(&nested(17, |inner| json!({ "k": inner }))));
1757        assert!(bound(&json!("x".repeat(MAX_TEXT))));
1758        assert!(!bound(&json!("x".repeat(MAX_TEXT + 1))));
1759        assert!(bound(&json!(vec![0; MAX_ROWS])));
1760        assert!(!bound(&json!(vec![0; MAX_ROWS + 1])));
1761        let object = |count: usize| {
1762            Value::Object(
1763                (0..count)
1764                    .map(|index| (index.to_string(), json!(0)))
1765                    .collect(),
1766            )
1767        };
1768        assert!(bound(&object(MAX_ROWS)));
1769        assert!(!bound(&object(MAX_ROWS + 1)));
1770        let keyed =
1771            |length: usize| Value::Object([("k".repeat(length), json!(0))].into_iter().collect());
1772        assert!(bound(&keyed(MAX_TEXT)));
1773        assert!(!bound(&keyed(MAX_TEXT + 1)));
1774        // The shared budget is spent by text, so a large document fails even when each part fits.
1775        let mut budget = 1000;
1776        assert!(bound_can_run(&json!("x".repeat(900)), 0, &mut budget).is_ok());
1777        assert_eq!(budget, 1000 - 64 - 900);
1778        assert!(bound_can_run(&json!("x".repeat(100)), 0, &mut budget).is_err());
1779    }
1780
1781    #[test]
1782    fn documents_may_fill_exactly_four_mib() {
1783        let rows = || {
1784            (0..64)
1785                .map(|_| ModelRow::new("", &"a".repeat(65_536), "").unwrap())
1786                .collect::<Vec<_>>()
1787        };
1788        assert!(ModelView::new("Catalog", Vec::new(), rows(), false).is_ok());
1789        assert!(ModelView::new("Catalog", vec!["x".into()], rows(), false).is_err());
1790    }
1791
1792    #[test]
1793    fn memory_figures_must_be_finite_and_usable_must_be_positive() {
1794        for (usable, kept) in [
1795            (8.0, true),
1796            (0.0, false),
1797            (-1.0, false),
1798            (f64::INFINITY, false),
1799            (f64::NAN, false),
1800        ] {
1801            let view = three().with_memory(usable, std::iter::empty());
1802            assert_eq!(view.usable_bytes.is_some(), kept, "{usable}");
1803        }
1804        let needs = [0.0, -1.0, f64::INFINITY];
1805        let view = three().with_memory(8.0, needs.into_iter());
1806        let kept: Vec<_> = view.rows.iter().map(|row| row.need_bytes).collect();
1807        assert_eq!(kept, [Some(0.0), None, None]);
1808    }
1809
1810    #[test]
1811    fn search_ranks_closer_matches_first() {
1812        let mut view = view(vec![row("q-x-w-e-n:8b", "", ""), row("qwen:8b", "", "")]);
1813        view.append_query("qwen");
1814        assert_eq!(labels(&view), ["qwen:8b", "q-x-w-e-n:8b"]);
1815    }
1816
1817    #[test]
1818    fn sort_cycles_through_every_column_then_off() {
1819        let mut view = three();
1820        let mut seen = Vec::new();
1821        for _ in 0..5 {
1822            key(&mut view, KeyCode::Char('s'));
1823            seen.push(view.sort);
1824        }
1825        assert_eq!(
1826            seen,
1827            [
1828                Some((0, false)),
1829                Some((1, false)),
1830                Some((2, false)),
1831                Some((3, false)),
1832                None
1833            ]
1834        );
1835        view.cycle_sort(Some(2));
1836        view.cycle_sort(Some(2));
1837        assert_eq!(view.sort, Some((2, true)));
1838        view.cycle_sort(Some(1));
1839        assert_eq!(view.sort, Some((1, false)));
1840        // Outside the list, sort keys do nothing.
1841        view.focus(Focus::Detail);
1842        key(&mut view, KeyCode::Char('s'));
1843        key(&mut view, KeyCode::Char('S'));
1844        assert_eq!(view.sort, Some((1, false)));
1845        view.focus(Focus::List);
1846        key(&mut view, KeyCode::Char('S'));
1847        assert_eq!(view.sort, Some((1, true)));
1848    }
1849
1850    #[test]
1851    fn sort_keys_compare_verdicts_numbers_and_unknowns() {
1852        let model = row("7b-yes", "~12.5 tok/s | unknown | slow | ", "");
1853        assert_eq!(sort_key(&model, 0), (0, 0.0, "7b-yes".into()));
1854        assert_eq!(sort_key(&model, 1), (0, 12.5, "~12.5 tok/s".into()));
1855        assert_eq!(sort_key(&model, 2), (1, 0.0, String::new()));
1856        assert_eq!(
1857            sort_key(&model, 3),
1858            (0, f64::from(Verdict::Slow as u8), String::new())
1859        );
1860        assert_eq!(sort_key(&model, 4), (1, 0.0, String::new()));
1861        assert_eq!(sort_key(&model, 9), (1, 0.0, String::new()));
1862        let named = row("yes", "Unknown size", "");
1863        assert_eq!(sort_key(&named, 0), (0, 0.0, "yes".into()));
1864        assert_eq!(sort_key(&named, 1), (1, 0.0, "unknown size".into()));
1865    }
1866
1867    #[test]
1868    fn commands_are_copied_only_for_plain_model_ids() {
1869        for id in ["qwen3:8b", "hf.co/org/model-q4_k_m", "a_b"] {
1870            assert!(command_safe(id), "{id}");
1871        }
1872        for id in ["", "-rf", "../x", "org/../x", "Qwen3", "qwen 3", "qwen;rm"] {
1873            assert!(!command_safe(id), "{id}");
1874        }
1875    }
1876
1877    #[test]
1878    fn modifier_release_and_repeat_keys_are_ignored() {
1879        let mut view = three();
1880        view.command = Some("rigspark up alpha:8b".into());
1881        for modifiers in [KeyModifiers::ALT, KeyModifiers::SUPER] {
1882            assert_eq!(
1883                handle_key(&mut view, KeyEvent::new(KeyCode::Char('q'), modifiers)),
1884                None
1885            );
1886        }
1887        let mut repeat = press(KeyCode::Char('p'));
1888        repeat.kind = KeyEventKind::Repeat;
1889        assert_eq!(handle_key(&mut view, repeat), None);
1890        assert_eq!(
1891            key(&mut view, KeyCode::Char('p')),
1892            Some(ModelOutcome::PrintCommand {
1893                command: "rigspark up alpha:8b".into()
1894            })
1895        );
1896        // Ctrl-U clears filters, except while help is open.
1897        view.append_query("beta");
1898        view.toggle_help();
1899        handle_key(
1900            &mut view,
1901            KeyEvent::new(KeyCode::Char('u'), KeyModifiers::CONTROL),
1902        );
1903        assert_eq!(view.query, "beta");
1904        view.toggle_help();
1905        handle_key(
1906            &mut view,
1907            KeyEvent::new(KeyCode::Char('u'), KeyModifiers::CONTROL),
1908        );
1909        assert_eq!(view.query, "");
1910    }
1911
1912    #[test]
1913    fn navigation_keys_use_the_focused_pane() {
1914        let mut view = three();
1915        view.page = 2;
1916        view.detail_page = 1;
1917        key(&mut view, KeyCode::PageDown);
1918        assert_eq!(view.list.selected(), Some(2));
1919        key(&mut view, KeyCode::Up);
1920        assert_eq!(view.list.selected(), Some(1));
1921        key(&mut view, KeyCode::Char('i'));
1922        assert!(view.focus == Focus::Overview);
1923        key(&mut view, KeyCode::Char('i'));
1924        assert!(view.focus == Focus::List);
1925        view.focus(Focus::Detail);
1926        view.scroll_max = 10;
1927        key(&mut view, KeyCode::PageDown);
1928        assert_eq!(view.scroll, 1);
1929        // Right opens details only when something is selected.
1930        let mut empty = view_with_no_rows();
1931        key(&mut empty, KeyCode::Right);
1932        assert!(empty.focus == Focus::List);
1933    }
1934
1935    fn view_with_no_rows() -> ModelView {
1936        view(Vec::new())
1937    }
1938
1939    #[test]
1940    fn month_and_verdict_filters_apply_only_in_the_list() {
1941        let mut view = three();
1942        key(&mut view, KeyCode::Char('m'));
1943        assert_eq!(view.month_filter, None, "no recency data");
1944        let dates = std::collections::BTreeMap::new();
1945        let mut view = three().with_recency(&dates, "2026-10-07").unwrap();
1946        view.focus(Focus::Detail);
1947        key(&mut view, KeyCode::Char('m'));
1948        key(&mut view, KeyCode::Char('v'));
1949        assert_eq!((view.month_filter, view.verdict_filter), (None, None));
1950        view.focus(Focus::List);
1951        key(&mut view, KeyCode::Char('v'));
1952        assert_eq!(labels(&view), ["alpha:8b"]);
1953        let mut bare =
1954            ModelView::new("Catalog", Vec::new(), vec![row("a", "yes", "")], false).unwrap();
1955        key(&mut bare, KeyCode::Char('v'));
1956        assert_eq!(bare.verdict_filter, None, "no columns to filter on");
1957    }
1958
1959    #[test]
1960    fn cards_wrap_within_72_columns() {
1961        let view = three();
1962        let long = row(
1963            "alpha:8b",
1964            &format!("1 | {} | yes", "word ".repeat(30)),
1965            "alpha:8b",
1966        );
1967        let card = view.card(&long);
1968        assert!(card.lines().count() > 6);
1969        assert!(
1970            card.lines().all(|line| line.chars().count() <= 72),
1971            "{card}"
1972        );
1973    }
1974
1975    fn mouse(kind: MouseEventKind, column: u16, row: u16) -> MouseEvent {
1976        MouseEvent {
1977            kind,
1978            column,
1979            row,
1980            modifiers: KeyModifiers::NONE,
1981        }
1982    }
1983    fn clickable() -> ModelView {
1984        let mut view = three();
1985        view.areas = HitAreas {
1986            rows: Rect::new(0, 5, 40, 10),
1987            header: vec![(Rect::new(0, 4, 10, 1), 2)],
1988            detail: Rect::new(40, 0, 40, 20),
1989        };
1990        view
1991    }
1992
1993    #[test]
1994    fn wheel_scrolls_the_pane_under_the_pointer() {
1995        let mut view = clickable();
1996        handle_mouse(&mut view, mouse(MouseEventKind::ScrollDown, 5, 6));
1997        assert_eq!(view.list.selected(), Some(1));
1998        handle_mouse(&mut view, mouse(MouseEventKind::ScrollUp, 5, 6));
1999        assert_eq!(view.list.selected(), Some(0));
2000        // Over the detail pane while the list has focus: nothing scrolls.
2001        view.scroll_max = 10;
2002        handle_mouse(&mut view, mouse(MouseEventKind::ScrollDown, 50, 6));
2003        assert_eq!((view.list.selected(), view.scroll), (Some(0), 0));
2004        view.focus = Focus::Detail;
2005        view.scroll_max = 10;
2006        handle_mouse(&mut view, mouse(MouseEventKind::ScrollDown, 50, 6));
2007        assert_eq!((view.list.selected(), view.scroll), (Some(0), 3));
2008        handle_event(
2009            &mut view,
2010            Event::Mouse(mouse(MouseEventKind::ScrollUp, 50, 6)),
2011        );
2012        assert_eq!(view.scroll, 0);
2013    }
2014
2015    #[test]
2016    fn clicks_select_open_and_sort_only_in_the_list() {
2017        let mut view = clickable();
2018        let click = |column, row| mouse(MouseEventKind::Down(MouseButton::Left), column, row);
2019        handle_mouse(&mut view, click(3, 7));
2020        assert_eq!(view.list.selected(), Some(2));
2021        handle_mouse(&mut view, click(3, 8));
2022        assert_eq!(view.list.selected(), Some(2), "past the last row");
2023        handle_mouse(&mut view, click(3, 7));
2024        assert!(
2025            view.focus == Focus::Detail,
2026            "clicking the selection opens it"
2027        );
2028        handle_mouse(&mut view, click(3, 5));
2029        assert_eq!(view.list.selected(), Some(2), "ignored outside the list");
2030        view.focus(Focus::List);
2031        handle_mouse(&mut view, click(3, 4));
2032        assert_eq!(view.sort, Some((2, false)));
2033    }
2034
2035    #[test]
2036    fn comparison_aligns_keys_and_needs_fourteen_column_cells() {
2037        let mut view = three();
2038        assert!(compare_lines(&view, 120, Theme::new(false)).is_none());
2039        view.marked = vec![0, 1];
2040        let theme = Theme::new(true);
2041        let text = |line: &Line| {
2042            line.spans
2043                .iter()
2044                .map(|span| span.content.as_ref())
2045                .collect::<String>()
2046        };
2047        let wide = compare_lines(&view, 80, theme).unwrap();
2048        // The header opens with the key column's padding.
2049        let key_width = wide[0].spans[0].content.chars().count();
2050        assert_eq!(key_width, "verdict".len());
2051        let cell = (80 - key_width - 6) / 2;
2052        assert_eq!(text(&wide[0]).chars().count(), key_width + 2 * (3 + cell));
2053        // Exactly 14-column cells still fit; one column less does not.
2054        let fits = u16::try_from(key_width + 6 + 28).unwrap();
2055        let lines = compare_lines(&view, fits, theme).unwrap();
2056        assert_eq!(text(&lines[0]).chars().count(), key_width + 2 * (3 + 14));
2057        assert!(compare_lines(&view, fits - 1, theme).is_none());
2058        let row_for = |key: &str| {
2059            wide.iter()
2060                .find(|line| text(line).starts_with(key))
2061                .unwrap_or_else(|| panic!("{key} row"))
2062                .clone()
2063        };
2064        assert_eq!(row_for("summary").spans[2].style, theme.muted());
2065        assert_eq!(row_for("verdict").spans[2].style, theme.verdict("yes"));
2066        assert_eq!(row_for("verdict").spans[4].style, theme.verdict("slow"));
2067        // An unkeyed note keeps its own row, blank where the other model has none.
2068        assert!(wide.iter().any(|line| text(line).contains("note")));
2069    }
2070
2071    #[test]
2072    fn can_run_model_ids_are_capped_at_1024_bytes() {
2073        let evidence = |id: &str| {
2074            json!({
2075                "modelId": id, "runnable": "slow", "quant": "Q4_K_M",
2076                "reason": null, "requiredBytes": 1024, "usableBytes": 4096,
2077                "throughput": {"known": false, "lowTokPerSec": 0, "highTokPerSec": 0},
2078                "throughputEvidence": {"source": "offline-estimate", "unknownReason": "no-sourced-performance-profile"},
2079                "backends": ["ollama"], "throughputBackend": "ollama",
2080                "context": 8192, "contextFitKnown": false
2081            })
2082        };
2083        // Identifiers are truncated for display, so exactly 1024 bytes is still accepted.
2084        assert!(ModelView::from_can_run(&evidence(&"a".repeat(1024)), false).is_ok());
2085        let error = ModelView::from_can_run(&evidence(&"a".repeat(1025)), false)
2086            .err()
2087            .unwrap();
2088        assert_eq!(error.to_string(), "model view text limit exceeded");
2089        assert!(ModelView::from_can_run(&evidence("custom:local"), false).is_ok());
2090    }
2091
2092    #[test]
2093    fn choosing_another_column_sorts_it_ascending() {
2094        let mut view = three();
2095        view.cycle_sort(Some(2));
2096        assert_eq!(view.sort, Some((2, false)));
2097        view.cycle_sort(Some(1));
2098        assert_eq!(view.sort, Some((1, false)));
2099    }
2100
2101    #[test]
2102    fn copies_use_the_selected_visible_row_and_confirm_with_a_toast() {
2103        let mut view = three();
2104        assert_eq!(view.toast(), None);
2105        // Filtering leaves gamma first in the visible list but third in the rows.
2106        view.append_query("gamma");
2107        assert_eq!(labels(&view), ["gamma:8b"]);
2108        key(&mut view, KeyCode::Char('y'));
2109        assert_eq!(view.take_clipboard().as_deref(), Some("gamma:8b"));
2110        assert_eq!(view.toast(), Some("Copied model id to clipboard"));
2111        key(&mut view, KeyCode::Char('Y'));
2112        assert_eq!(
2113            view.take_clipboard().as_deref(),
2114            Some("rigspark up gamma:8b")
2115        );
2116        assert_eq!(view.toast(), Some("Copied up command to clipboard"));
2117        key(&mut view, KeyCode::Char('e'));
2118        assert!(view.take_clipboard().unwrap().contains("/ gamma:8b\n"));
2119        // Nothing visible: nothing is copied.
2120        view.append_query("zzz");
2121        key(&mut view, KeyCode::Char('y'));
2122        assert_eq!(view.take_clipboard(), None);
2123    }
2124
2125    #[test]
2126    fn card_fields_wrap_at_62_columns() {
2127        let view = three();
2128        let words = "abcd ".repeat(12);
2129        let card = view.card(&row("alpha:8b", &format!("1 | {} | yes", words.trim()), ""));
2130        let need = card.lines().find(|line| line.starts_with("NEED")).unwrap();
2131        assert_eq!(need, format!("{:<9} {}", "NEED", words.trim()));
2132    }
2133
2134    #[test]
2135    fn search_accepts_printable_characters_only() {
2136        let mut view = three();
2137        key(&mut view, KeyCode::Char('/'));
2138        assert!(view.searching);
2139        key(&mut view, KeyCode::Char('\u{7}'));
2140        key(&mut view, KeyCode::Char('b'));
2141        assert_eq!(view.query, "b");
2142        key(&mut view, KeyCode::Backspace);
2143        assert_eq!(view.query, "");
2144    }
2145
2146    #[test]
2147    fn enter_opens_the_selected_model() {
2148        let mut view = three();
2149        key(&mut view, KeyCode::Enter);
2150        assert!(view.focus == Focus::Detail);
2151        key(&mut view, KeyCode::Enter);
2152        assert!(view.focus == Focus::List);
2153        key(&mut view, KeyCode::Right);
2154        assert!(view.focus == Focus::Detail);
2155        let mut empty = view_with_no_rows();
2156        key(&mut empty, KeyCode::Enter);
2157        assert!(empty.focus == Focus::List);
2158    }
2159
2160    fn describe(entry: &Entry) -> String {
2161        match entry {
2162            Entry::Heading(text) => format!("heading {text}"),
2163            Entry::Field { key, value } => format!("field {key}={value}"),
2164            Entry::Note(text) => format!("note {text}"),
2165            Entry::Plain(text) => format!("plain {text}"),
2166            Entry::Blank => "blank".into(),
2167        }
2168    }
2169    fn line_text(line: &Line) -> String {
2170        line.spans
2171            .iter()
2172            .map(|span| span.content.as_ref())
2173            .collect()
2174    }
2175    fn field(key: &str, value: &str) -> Entry {
2176        Entry::Field {
2177            key: key.into(),
2178            value: value.into(),
2179        }
2180    }
2181
2182    #[test]
2183    fn only_a_leading_label_becomes_the_evidence_heading() {
2184        let entries = |label: &str, evidence: &str| {
2185            let mut entries = Vec::new();
2186            evidence_entries(&row(label, "", evidence), &mut entries);
2187            entries.iter().map(describe).collect::<Vec<_>>()
2188        };
2189        assert_eq!(
2190            entries("a:1b", "a:1b; verdict yes; a:1b"),
2191            ["heading a:1b", "field verdict=yes", "field =a:1b"]
2192        );
2193        assert_eq!(
2194            entries("a:1b", "b:1b; verdict no"),
2195            ["field =b:1b", "field verdict=no"]
2196        );
2197    }
2198
2199    #[test]
2200    fn detail_keys_align_to_a_third_of_the_width_from_30_columns() {
2201        let theme = Theme::new(true);
2202        let key_style = theme.muted();
2203        let entries = [field("fit", "yes"), field("throughput backend", "ollama")];
2204        let lines = layout(&entries, 30, theme, key_style);
2205        let texts: Vec<_> = lines.iter().map(line_text).collect();
2206        // The longest key (18 cells) is capped at 30 / 3 = 10, so short keys pad to 10.
2207        assert_eq!(texts[0], format!("{}fit yes", " ".repeat(7)));
2208        assert_eq!(texts[1], "throughput backend ollama");
2209        assert_eq!(lines[0].spans[3].style, theme.verdict("yes"));
2210        assert_eq!(lines[1].spans[3].style, Style::default());
2211        // Below 30 columns keys and values simply run together.
2212        let narrow: Vec<_> = layout(&entries, 29, theme, key_style)
2213            .iter()
2214            .map(line_text)
2215            .collect();
2216        assert_eq!(narrow, ["fit yes", "throughput backend ollama"]);
2217    }
2218
2219    #[test]
2220    fn detail_values_wrap_after_the_key_indent() {
2221        let theme = Theme::new(false);
2222        let wrapped = |value: &str| {
2223            layout(&[field("fit", value)], 30, theme, Style::default())
2224                .iter()
2225                .map(line_text)
2226                .collect::<Vec<_>>()
2227        };
2228        // "fit" plus one space leaves 26 columns for the value.
2229        let fits = "abcde ".repeat(4) + "ab";
2230        assert_eq!(wrapped(&fits), [format!("fit {fits}")]);
2231        let over = fits.clone() + "c";
2232        assert_eq!(wrapped(&over).len(), 2);
2233        // An unkeyed value is indented as a single raw span.
2234        let lines = layout(
2235            &[field("fit", "yes"), field("", "loose")],
2236            30,
2237            theme,
2238            Style::default(),
2239        );
2240        assert_eq!(line_text(&lines[1]), "    loose");
2241        assert_eq!(lines[1].spans.len(), 2);
2242    }
2243
2244    #[test]
2245    fn comparison_keeps_every_unkeyed_note() {
2246        let mut view = view(vec![
2247            row("a:1b", "", "a:1b; first note; second note"),
2248            row("b:1b", "", "b:1b; verdict yes"),
2249        ]);
2250        view.marked = vec![0, 1];
2251        let lines = compare_lines(&view, 120, Theme::new(false)).unwrap();
2252        let text: Vec<_> = lines.iter().map(line_text).collect();
2253        assert!(
2254            text.iter().any(|line| line.contains("first note")),
2255            "{text:?}"
2256        );
2257        assert!(
2258            text.iter().any(|line| line.contains("second note")),
2259            "{text:?}"
2260        );
2261    }
2262
2263    fn draw(view: &mut ModelView, width: u16, height: u16) -> ratatui::buffer::Buffer {
2264        let backend = ratatui::backend::TestBackend::new(width, height);
2265        let mut terminal = ratatui::Terminal::new(backend).unwrap();
2266        terminal.draw(|frame| render(frame, view)).unwrap();
2267        terminal.backend().buffer().clone()
2268    }
2269    fn screen(buffer: &ratatui::buffer::Buffer) -> Vec<String> {
2270        buffer
2271            .content
2272            .chunks(usize::from(buffer.area.width))
2273            .map(|row| row.iter().map(|cell| cell.symbol()).collect())
2274            .collect()
2275    }
2276    fn wide_labels() -> ModelView {
2277        let mut view = three();
2278        view.rows[0].label = "alphabet-model:8b".into();
2279        view
2280    }
2281
2282    #[test]
2283    fn rendering_records_where_rows_and_header_cells_are() {
2284        let mut view = three();
2285        view.sort = Some((1, true));
2286        let text = screen(&draw(&mut view, 120, 30)).join("\n");
2287        assert!(text.contains("Rank ▼"), "{text}");
2288        assert!(
2289            !text.contains("Model ▼") && !text.contains("Need ▼"),
2290            "{text}"
2291        );
2292        let rows = view.areas.rows;
2293        let header: Vec<_> = view
2294            .areas
2295            .header
2296            .iter()
2297            .map(|(_, column)| *column)
2298            .collect();
2299        assert_eq!(header, [0, 1, 2, 3]);
2300        let first = view.areas.header[0].0;
2301        let last = view.areas.header.last().unwrap().0;
2302        assert_eq!(
2303            (first.x, first.y, first.height),
2304            (rows.x + 2, rows.y - 1, 1)
2305        );
2306        assert!(last.right() <= rows.right(), "{last:?} within {rows:?}");
2307        assert_eq!(usize::from(rows.height), view.page);
2308        // At 120 columns the detail pane sits to the right of the list.
2309        assert!(view.areas.detail.x >= rows.right());
2310        draw(&mut view, 109, 30);
2311        assert_eq!(view.areas.detail.x, 0);
2312        assert!(view.areas.detail.y > view.areas.rows.y);
2313    }
2314
2315    #[test]
2316    fn columns_drop_by_priority_when_the_table_is_narrow() {
2317        // Model 19 cells; Rank, Need, Verdict 6, 7 and 9, each plus one space.
2318        for width in 30..110 {
2319            let mut view = wide_labels();
2320            draw(&mut view, width, 12);
2321            let available = usize::from(view.areas.rows.width) - 2;
2322            let shown = view.areas.header.len() - 1;
2323            let expected = match available {
2324                44.. => 3,
2325                34..44 => 2,
2326                26..34 => 1,
2327                _ => 0,
2328            };
2329            assert_eq!(shown, expected, "width {width}, available {available}");
2330        }
2331    }
2332
2333    #[test]
2334    fn empty_results_offer_a_reset_only_when_filtered() {
2335        let hint = |view: &mut ModelView| {
2336            screen(&draw(view, 80, 20))
2337                .join("\n")
2338                .contains("Ctrl+U resets the filter")
2339        };
2340        let mut view = three();
2341        view.append_query("zzz");
2342        assert!(hint(&mut view));
2343        let mut view = three();
2344        view.rows.retain(|row| row.label != "alpha:8b");
2345        view.filter();
2346        view.verdict_filter = Some(Verdict::Yes);
2347        view.filter();
2348        assert!(hint(&mut view));
2349        assert!(!hint(&mut view_with_no_rows()));
2350    }
2351
2352    #[test]
2353    fn machine_context_grows_with_the_terminal() {
2354        let shown = |lines: Vec<String>, height: u16| {
2355            let mut view = ModelView::new("Recommend", lines, Vec::new(), true).unwrap();
2356            let buffer = draw(&mut view, 80, height);
2357            (screen(&buffer).join("\n"), buffer)
2358        };
2359        let one = || vec!["Machine: test".to_owned()];
2360        let (text, _) = shown(one(), 28);
2361        assert!(text.contains("Machine / scope"), "{text}");
2362        let (text, _) = shown(one(), 27);
2363        assert!(!text.contains("Machine / scope") && text.contains("Machine: test"));
2364        let (text, _) = shown(one(), 12);
2365        assert!(text.contains("Machine: test"));
2366        let (text, _) = shown(one(), 11);
2367        assert!(!text.contains("Machine: test"));
2368        // Two compact lines do not earn a panel.
2369        let two = || vec!["Machine: test".to_owned(), "Scope: all".to_owned()];
2370        let (text, _) = shown(two(), 20);
2371        assert!(!text.contains("Machine / scope") && text.contains("Scope: all"));
2372        // Compact lines are indented one column, under the header.
2373        assert!(
2374            text.lines().nth(1).unwrap().starts_with(" Machine: test"),
2375            "{text}"
2376        );
2377        // In the panel only the first line is emphasised.
2378        let (text, buffer) = shown(two(), 28);
2379        let theme = Theme::new(true);
2380        let cell = |needle: &str| {
2381            let (row, line) = screen(&buffer)
2382                .into_iter()
2383                .enumerate()
2384                .find(|(_, line)| line.contains(needle))
2385                .unwrap_or_else(|| panic!("{needle}: {text}"));
2386            let start = line.find(needle).unwrap();
2387            let column = line[..start].chars().count();
2388            buffer[(u16::try_from(column).unwrap(), u16::try_from(row).unwrap())].fg
2389        };
2390        assert_ne!(Some(cell("Machine: test")), theme.muted().fg);
2391        assert_eq!(Some(cell("Scope: all")), theme.muted().fg);
2392    }
2393
2394    #[test]
2395    fn toasts_sit_in_the_bottom_right_of_the_body() {
2396        let mut view = three();
2397        key(&mut view, KeyCode::Char('y'));
2398        let lines = screen(&draw(&mut view, 80, 20));
2399        let (row, line) = lines
2400            .iter()
2401            .enumerate()
2402            .find(|(_, line)| line.contains("Copied model id"))
2403            .unwrap();
2404        // The body ends above the status and footer lines; the toast's text is its middle row.
2405        assert_eq!(row, 20 - 2 - 2);
2406        let end = line.find("clipboard").unwrap() + "clipboard".len();
2407        assert_eq!(line[end..].chars().count(), 2, "{line:?}");
2408    }
2409
2410    #[test]
2411    fn detail_pane_titles_help_and_narrow_comparisons() {
2412        let text = |view: &mut ModelView, width: u16| screen(&draw(view, width, 40));
2413        let mut view = three();
2414        view.focus(Focus::Overview);
2415        assert!(text(&mut view, 80).join("\n").contains("Machine / scope"));
2416        // Help lists the verdict filter only when there are columns to filter on.
2417        let mut view = three();
2418        view.toggle_help();
2419        assert!(
2420            text(&mut view, 120)
2421                .join("\n")
2422                .contains("v: cycle verdict filter")
2423        );
2424        let mut bare =
2425            ModelView::new("Catalog", Vec::new(), vec![row("a", "", "")], false).unwrap();
2426        bare.toggle_help();
2427        assert!(!text(&mut bare, 120).join("\n").contains("verdict filter"));
2428        // Too narrow for columns: models are listed one after another, a blank line apart.
2429        let mut view = three();
2430        view.rows[1].summary.clear();
2431        view.marked = vec![0, 1];
2432        view.focus(Focus::Compare);
2433        let lines = text(&mut view, 30);
2434        let at = |needle: &str| {
2435            lines
2436                .iter()
2437                .position(|line| line.contains(needle))
2438                .unwrap_or_else(|| panic!("{needle}: {lines:#?}"))
2439        };
2440        let alpha = at("alpha:8b");
2441        let beta = at("beta:8b");
2442        assert!(alpha < beta);
2443        assert!(
2444            lines[beta - 1]
2445                .trim_matches(|c: char| c == '│' || c == ' ')
2446                .is_empty()
2447        );
2448        assert!(!lines[alpha - 1].contains("alpha"));
2449        assert!(lines[alpha + 1].contains("1 | 5.2 GiB"), "{lines:#?}");
2450        assert!(lines[beta + 1].contains("verdict"), "{lines:#?}");
2451    }
2452
2453    #[test]
2454    fn overview_focus_titles_the_body_even_without_a_context_panel() {
2455        let mut view = three();
2456        view.focus(Focus::Overview);
2457        // At 11 rows there is no machine context above the body.
2458        let text = screen(&draw(&mut view, 80, 11)).join("\n");
2459        assert!(text.contains("Machine / scope"), "{text}");
2460        assert!(!text.contains("Evidence"), "{text}");
2461    }
2462
2463    #[test]
2464    fn header_cells_follow_the_table_wherever_it_is_placed() {
2465        let mut view = three();
2466        let backend = ratatui::backend::TestBackend::new(120, 20);
2467        let mut terminal = ratatui::Terminal::new(backend).unwrap();
2468        terminal
2469            .draw(|frame| {
2470                render_table(
2471                    frame,
2472                    &mut view,
2473                    Rect::new(10, 0, 100, 20),
2474                    Theme::new(true),
2475                );
2476            })
2477            .unwrap();
2478        let first = view.areas.header[0].0;
2479        assert_eq!(first.x, view.areas.rows.x + 2);
2480        assert!(view.areas.rows.x > 10);
2481    }
2482
2483    #[test]
2484    fn toasts_need_three_body_rows() {
2485        let mut view = three();
2486        key(&mut view, KeyCode::Char('y'));
2487        for height in 1..6 {
2488            let text = screen(&draw(&mut view, 80, height)).join("\n");
2489            assert!(!text.contains("Copied"), "{height}: {text}");
2490        }
2491        // Header, status and footer take a row each: six rows leave a three-row body.
2492        let text = screen(&draw(&mut view, 80, 6)).join("\n");
2493        assert!(text.contains("Copied"), "{text}");
2494    }
2495
2496    #[test]
2497    fn status_bar_reports_filter_position_and_sort() {
2498        let status = |view: &mut ModelView| screen(&draw(view, 120, 20))[18].clone();
2499        let mut view = three();
2500        assert!(status(&mut view).contains("1/3"), "{}", status(&mut view));
2501        assert!(!status(&mut view).contains("Filter"));
2502        view.append_query("a");
2503        view.searching = false;
2504        assert!(
2505            status(&mut view).contains(" Filter a"),
2506            "{}",
2507            status(&mut view)
2508        );
2509        let mut view = three();
2510        view.sort = Some((1, false));
2511        assert!(
2512            status(&mut view).contains("sort rank ▲"),
2513            "{}",
2514            status(&mut view)
2515        );
2516        view.sort = Some((2, true));
2517        assert!(
2518            status(&mut view).contains("sort need ▼"),
2519            "{}",
2520            status(&mut view)
2521        );
2522        view.sort = None;
2523        view.focus(Focus::Detail);
2524        let line = status(&mut view);
2525        assert!(line.contains("Line 1/") && !line.contains("1/3"), "{line}");
2526    }
2527
2528    #[test]
2529    fn footer_hints_match_the_focus() {
2530        let footer = |view: &mut ModelView| screen(&draw(view, 120, 20))[19].clone();
2531        let mut view = three();
2532        let list = footer(&mut view);
2533        assert!(
2534            list.contains("v verdict") && list.contains("y copy"),
2535            "{list}"
2536        );
2537        let mut bare =
2538            ModelView::new("Catalog", Vec::new(), vec![row("a", "", "")], false).unwrap();
2539        assert!(
2540            !footer(&mut bare).contains("verdict"),
2541            "{}",
2542            footer(&mut bare)
2543        );
2544        view.searching = true;
2545        let searching = footer(&mut view);
2546        assert!(
2547            searching.contains("Enter apply") && !searching.contains("verdict"),
2548            "{searching}"
2549        );
2550        view.searching = false;
2551        view.focus(Focus::Detail);
2552        let detail = footer(&mut view);
2553        assert!(
2554            detail.contains("Esc back") && detail.contains("Home/End jump"),
2555            "{detail}"
2556        );
2557        assert!(!detail.contains("verdict"), "{detail}");
2558        view.focus(Focus::Help);
2559        let help = footer(&mut view);
2560        assert!(
2561            help.contains("Esc back") && !help.contains("jump"),
2562            "{help}"
2563        );
2564        assert!(!help.contains("verdict"), "{help}");
2565    }
2566}