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}
93
94fn bounded_text(value: &str, limit: usize) -> io::Result<String> {
95    if value.len() > limit {
96        return Err(io::Error::new(
97            io::ErrorKind::InvalidInput,
98            "model view text limit exceeded",
99        ));
100    }
101    Ok(strip_control(value)
102        .chars()
103        .filter(|character| !character.is_control())
104        .collect())
105}
106
107impl ModelRow {
108    pub fn new(label: &str, search: &str, evidence: &str) -> io::Result<Self> {
109        Ok(Self {
110            label: bounded_text(label, 1024)?,
111            summary: String::new(),
112            search: bounded_text(search, MAX_TEXT)?.to_lowercase(),
113            evidence: bounded_evidence(evidence)?,
114            need_bytes: None,
115        })
116    }
117
118    pub fn label(&self) -> &str {
119        &self.label
120    }
121
122    fn cells(&self) -> Vec<&str> {
123        if self.summary.is_empty() {
124            Vec::new()
125        } else {
126            self.summary.split(" | ").collect()
127        }
128    }
129
130    fn verdict(&self) -> Option<Verdict> {
131        self.cells().into_iter().find_map(tui_theme::verdict_kind)
132    }
133}
134
135fn bounded_evidence(value: &str) -> io::Result<String> {
136    if value.len() > MAX_TEXT {
137        return Err(io::Error::new(
138            io::ErrorKind::InvalidInput,
139            "model view text limit exceeded",
140        ));
141    }
142    value
143        .lines()
144        .map(|line| bounded_text(line, MAX_TEXT))
145        .collect::<io::Result<Vec<_>>>()
146        .map(|lines| lines.join("\n"))
147}
148
149#[derive(Debug, PartialEq, Eq)]
150pub enum ModelOutcome {
151    Exit { code: u8 },
152    PrintCommand { command: String },
153}
154
155#[derive(Clone, Copy, PartialEq, Eq)]
156enum Focus {
157    List,
158    Detail,
159    Overview,
160    Help,
161    Compare,
162}
163
164#[derive(Default)]
165struct HitAreas {
166    rows: Rect,
167    header: Vec<(Rect, usize)>,
168    detail: Rect,
169}
170
171pub struct ModelView {
172    title: String,
173    overview: Vec<String>,
174    rows: Vec<ModelRow>,
175    visible: Vec<usize>,
176    matches: Vec<Vec<usize>>,
177    list: TableState,
178    query: String,
179    searching: bool,
180    focus: Focus,
181    help_return: Option<(Focus, usize, usize)>,
182    marked: Vec<usize>,
183    notice: Option<&'static str>,
184    toast: Option<String>,
185    clipboard: Option<String>,
186    scroll: usize,
187    scroll_max: usize,
188    page: usize,
189    detail_page: usize,
190    color: bool,
191    command: Option<String>,
192    comparison: bool,
193    columns: Vec<&'static str>,
194    priority: Vec<usize>,
195    sort: Option<(usize, bool)>,
196    verdict_filter: Option<Verdict>,
197    usable_bytes: Option<f64>,
198    areas: HitAreas,
199}
200
201impl ModelView {
202    pub fn new(
203        title: &str,
204        overview: Vec<String>,
205        rows: Vec<ModelRow>,
206        color: bool,
207    ) -> io::Result<Self> {
208        if rows.len() > MAX_ROWS || overview.len() > MAX_ROWS + 8 {
209            return Err(io::Error::new(
210                io::ErrorKind::InvalidInput,
211                "model view row limit exceeded",
212            ));
213        }
214        let bytes = rows
215            .iter()
216            .map(|row| row.label.len() + row.summary.len() + row.search.len() + row.evidence.len())
217            .sum::<usize>()
218            + overview.iter().map(String::len).sum::<usize>();
219        if bytes > MAX_DOCUMENT {
220            return Err(io::Error::new(
221                io::ErrorKind::InvalidInput,
222                "model view document limit exceeded",
223            ));
224        }
225        let overview = overview
226            .iter()
227            .map(|line| bounded_text(line, MAX_TEXT))
228            .collect::<io::Result<_>>()?;
229        let selection = if rows.is_empty() { None } else { Some(0) };
230        Ok(Self {
231            title: bounded_text(title, 256)?,
232            overview,
233            visible: (0..rows.len()).collect(),
234            matches: vec![Vec::new(); rows.len()],
235            rows,
236            list: TableState::default().with_selected(selection),
237            query: String::new(),
238            searching: false,
239            focus: Focus::List,
240            help_return: None,
241            marked: Vec::new(),
242            notice: None,
243            toast: None,
244            clipboard: None,
245            scroll: 0,
246            scroll_max: 0,
247            page: 1,
248            detail_page: 1,
249            color,
250            command: None,
251            comparison: true,
252            columns: Vec::new(),
253            priority: Vec::new(),
254            sort: None,
255            verdict_filter: None,
256            usable_bytes: None,
257            areas: HitAreas::default(),
258        })
259    }
260
261    fn with_columns(mut self, columns: &[&'static str], priority: &[usize]) -> Self {
262        self.columns = columns.to_vec();
263        self.priority = priority.to_vec();
264        self
265    }
266
267    fn with_memory(mut self, usable: f64, needs: impl Iterator<Item = f64>) -> Self {
268        self.usable_bytes = (usable.is_finite() && usable > 0.0).then_some(usable);
269        for (row, need) in self.rows.iter_mut().zip(needs) {
270            row.need_bytes = (need.is_finite() && need >= 0.0).then_some(need);
271        }
272        self
273    }
274
275    pub fn from_catalog(presentation: &CatalogPresentation, color: bool) -> io::Result<Self> {
276        Ok(Self::new(
277            "Catalog",
278            presentation.visual_overview(),
279            adapt_rows(presentation.visual_rows())?,
280            color,
281        )?
282        .with_columns(&["Quant", "Need", "Fit", "Release"], &[2, 1, 0, 3])
283        .with_memory(presentation.usable_bytes(), presentation.need_bytes()))
284    }
285
286    pub fn from_recommendation(presentation: &Recommendation, color: bool) -> io::Result<Self> {
287        let mut view = Self::new(
288            "Recommend",
289            presentation.visual_overview(),
290            adapt_rows(presentation.visual_rows())?,
291            color,
292        )?
293        .with_columns(
294            &["Rank", "Quant", "Need", "Verdict", "Tok/s", "Score"],
295            &[3, 4, 2, 0, 5, 1],
296        )
297        .with_memory(presentation.usable_bytes(), presentation.need_bytes());
298        view.command = presentation.print_command().map(str::to_owned);
299        Ok(view)
300    }
301
302    pub fn from_installed(presentation: &InstalledView, color: bool) -> io::Result<Self> {
303        let title = match presentation.command() {
304            InstalledCommand::Recommend => "Recommend / Installed",
305            InstalledCommand::CanRun => "Can Run / Installed",
306        };
307        let rows = presentation
308            .visual_rows()
309            .map(|(label, fit, search, evidence)| {
310                let mut row = ModelRow::new(label, search, evidence)?;
311                row.summary = bounded_text(fit, 64)?;
312                Ok(row)
313            })
314            .collect::<io::Result<Vec<_>>>()?;
315        let mut view = Self::new(title, presentation.visual_overview(), rows, color)?
316            .with_columns(&["Fit"], &[0]);
317        view.comparison =
318            presentation.command() == InstalledCommand::Recommend && view.rows.len() >= 2;
319        if view.rows.is_empty() {
320            view.focus(Focus::Overview);
321        } else if presentation.command() == InstalledCommand::CanRun {
322            view.focus(Focus::Detail);
323        }
324        Ok(view)
325    }
326
327    pub fn from_can_run(evidence: &Value, color: bool) -> io::Result<Self> {
328        let mut budget = MAX_DOCUMENT;
329        bound_can_run(evidence, 0, &mut budget)?;
330        let screen = can_run_screen(evidence)?;
331        let metadata = CanRunMetadata::deserialize(evidence).map_err(io::Error::other)?;
332        if metadata.model_id.len() > 1024 {
333            return Err(io::Error::new(
334                io::ErrorKind::InvalidInput,
335                "model view text limit exceeded",
336            ));
337        }
338        let label = identifier(metadata.model_id)?;
339        let summary = single_line(&format!(
340            "Verdict: {}; quant {}; reason {}",
341            metadata.runnable,
342            metadata.quant.unwrap_or("unknown"),
343            metadata.reason.unwrap_or("none"),
344        ))?;
345        let search = single_line(&format!(
346            "{} {} {}",
347            metadata.model_id, summary, metadata.throughput_backend,
348        ))?;
349        let mut row = ModelRow::new(&label, &search, &screen)?;
350        row.summary = bounded_text(&summary, 2048)?;
351        let context = metadata.context.map_or_else(
352            || "Requested context: not specified".into(),
353            |context| format!("Requested context: {context} tokens"),
354        );
355        let mut view = Self::new(
356            "Can Run",
357            vec![
358                format!("Verdict: {} / offline evidence", metadata.runnable),
359                context,
360            ],
361            vec![row],
362            color,
363        )?;
364        view.comparison = false;
365        view.focus(Focus::Detail);
366        Ok(view)
367    }
368
369    pub fn selected(&self) -> Option<&ModelRow> {
370        self.list
371            .selected()
372            .and_then(|index| self.visible.get(index))
373            .map(|index| &self.rows[*index])
374    }
375
376    pub fn visible_count(&self) -> usize {
377        self.visible.len()
378    }
379
380    pub fn detail_focused(&self) -> bool {
381        self.focus == Focus::Detail
382    }
383
384    fn filter(&mut self) {
385        let selected = self
386            .list
387            .selected()
388            .and_then(|index| self.visible.get(index))
389            .copied();
390        let needle = self.query.to_lowercase();
391        let mut found: Vec<(usize, usize, Vec<usize>)> = self
392            .rows
393            .iter()
394            .enumerate()
395            .filter(|(_, row)| {
396                self.verdict_filter
397                    .is_none_or(|wanted| row.verdict() == Some(wanted))
398            })
399            .filter_map(|(index, row)| {
400                if let Some(positions) = tui_theme::fuzzy(&row.label, &needle) {
401                    Some((index, tui_theme::fuzzy_rank(&positions), positions))
402                } else {
403                    row.search
404                        .contains(&needle)
405                        .then_some((index, usize::MAX, Vec::new()))
406                }
407            })
408            .collect();
409        if let Some((column, descending)) = self.sort {
410            found.sort_by(|left, right| {
411                let order = sort_key(&self.rows[left.0], column)
412                    .partial_cmp(&sort_key(&self.rows[right.0], column))
413                    .unwrap_or(std::cmp::Ordering::Equal);
414                let unknown = |row: usize| sort_key(&self.rows[row], column).0;
415                match (unknown(left.0), unknown(right.0)) {
416                    (0, 0) if descending => order.reverse(),
417                    _ => order,
418                }
419                .then(left.0.cmp(&right.0))
420            });
421        } else if !needle.is_empty() {
422            found.sort_by_key(|(index, rank, _)| (*rank, *index));
423        }
424        self.visible = found.iter().map(|(index, _, _)| *index).collect();
425        self.matches = found
426            .into_iter()
427            .map(|(_, _, positions)| positions)
428            .collect();
429        let position = selected
430            .and_then(|selected| self.visible.iter().position(|index| *index == selected))
431            .or_else(|| (!self.visible.is_empty()).then_some(0));
432        self.list.select(position);
433        *self.list.offset_mut() = 0;
434        self.scroll = 0;
435    }
436
437    fn cycle_sort(&mut self, column: Option<usize>) {
438        let columns = self.columns.len() + 1;
439        self.sort = match (column, self.sort) {
440            (Some(column), Some((current, descending))) if column == current => {
441                Some((column, !descending))
442            }
443            (Some(column), _) => Some((column, false)),
444            (None, None) => Some((0, false)),
445            (None, Some((current, _))) if current + 1 < columns => Some((current + 1, false)),
446            (None, Some(_)) => None,
447        };
448        self.filter();
449    }
450
451    fn selected_index(&self) -> Option<usize> {
452        self.list
453            .selected()
454            .and_then(|index| self.visible.get(index))
455            .copied()
456    }
457
458    /// Text queued for the terminal clipboard by `y`, `Y`, `e`, or chat copy.
459    pub fn take_clipboard(&mut self) -> Option<String> {
460        self.clipboard.take()
461    }
462
463    pub fn toast(&self) -> Option<&str> {
464        self.toast.as_deref()
465    }
466
467    fn copy(&mut self, text: String, what: &str) {
468        self.toast = Some(format!("Copied {what} to clipboard"));
469        self.clipboard = Some(text);
470    }
471
472    /// Paste-ready 72-column ASCII summary of the selected model.
473    fn card(&self, row: &ModelRow) -> String {
474        const WIDTH: usize = 72;
475        let mut card = format!(
476            "rigspark / {} / {}\n{}\n",
477            self.title,
478            row.label,
479            "=".repeat(WIDTH)
480        );
481        let mut field = |key: &str, value: &str| {
482            for (index, line) in tui_theme::wrap(value, WIDTH - 10).into_iter().enumerate() {
483                let key = if index == 0 { key } else { "" };
484                card.push_str(&format!("{key:<9} {line}\n"));
485            }
486        };
487        for (header, cell) in self.columns.iter().zip(row.cells()) {
488            field(&header.to_uppercase(), cell);
489        }
490        if let Some(usable) = self.usable_bytes {
491            field(
492                "MEMORY",
493                &row.need_bytes.map_or_else(
494                    || "need unknown".into(),
495                    |need| {
496                        format!(
497                            "{:.1} / {:.1} GiB ({:.0}%)",
498                            need / 1_073_741_824.0,
499                            usable / 1_073_741_824.0,
500                            need / usable * 100.0
501                        )
502                    },
503                ),
504            );
505        }
506        for line in self.overview.iter().take(2) {
507            field("MACHINE", line);
508        }
509        let mut entries = Vec::new();
510        evidence_entries(row, &mut entries);
511        for entry in entries.iter().take(24) {
512            if let Entry::Field { key, value } = entry {
513                field(
514                    &key.to_uppercase().chars().take(9).collect::<String>(),
515                    value,
516                );
517            }
518        }
519        card.push_str(&format!(
520            "{}\nrigspark: offline, cited estimate\n",
521            "-".repeat(WIDTH)
522        ));
523        card
524    }
525
526    fn move_to(&mut self, position: usize) {
527        if self.focus != Focus::List {
528            self.scroll = position.min(self.scroll_max);
529        } else if !self.visible.is_empty() {
530            self.list.select(Some(position.min(self.visible.len() - 1)));
531            self.scroll = 0;
532        }
533    }
534
535    fn focus(&mut self, focus: Focus) {
536        self.focus = focus;
537        self.scroll = 0;
538        self.scroll_max = 0;
539    }
540
541    fn append_query(&mut self, text: &str) {
542        let available = MAX_QUERY.saturating_sub(self.query.len());
543        let mut bytes = 0;
544        let prefix: String = text
545            .chars()
546            .take_while(|character| {
547                bytes += character.len_utf8();
548                bytes <= available
549            })
550            .collect();
551        let clean = strip_control(&prefix);
552        self.query
553            .extend(clean.chars().filter(|character| !character.is_control()));
554        self.filter();
555    }
556
557    fn toggle_help(&mut self) {
558        if let Some((focus, scroll, scroll_max)) = self.help_return.take() {
559            self.focus = focus;
560            self.scroll = scroll;
561            self.scroll_max = scroll_max;
562        } else {
563            self.help_return = Some((self.focus, self.scroll, self.scroll_max));
564            self.focus(Focus::Help);
565        }
566    }
567
568    fn toggle_mark(&mut self) {
569        let Some(index) = self
570            .list
571            .selected()
572            .and_then(|index| self.visible.get(index))
573            .copied()
574        else {
575            self.notice = Some("No model selected to mark");
576            return;
577        };
578        if let Some(position) = self.marked.iter().position(|marked| *marked == index) {
579            self.marked.remove(position);
580            self.notice = None;
581        } else if self.marked.len() == MAX_MARKED {
582            self.notice = Some("Mark limit 4: unmark a model with Space");
583        } else {
584            self.marked.push(index);
585            self.notice = None;
586        }
587    }
588}
589
590fn adapt_rows<'row>(
591    rows: impl Iterator<Item = (&'row str, &'row str, &'row str, &'row str)>,
592) -> io::Result<Vec<ModelRow>> {
593    rows.map(|(label, summary, search, evidence)| {
594        let mut row = ModelRow::new(label, search, evidence)?;
595        row.summary = bounded_text(summary, 2048)?;
596        Ok(row)
597    })
598    .collect()
599}
600
601pub fn handle_key(view: &mut ModelView, key: KeyEvent) -> Option<ModelOutcome> {
602    if key.kind == KeyEventKind::Release {
603        return None;
604    }
605    view.toast = None;
606    if key.modifiers.contains(KeyModifiers::CONTROL) {
607        match key.code {
608            KeyCode::Char('c') => return Some(ModelOutcome::Exit { code: 130 }),
609            KeyCode::Char('u') if view.focus != Focus::Help => {
610                view.query.clear();
611                view.verdict_filter = None;
612                view.filter();
613            }
614            _ => (),
615        }
616        return None;
617    }
618    if key
619        .modifiers
620        .intersects(KeyModifiers::ALT | KeyModifiers::SUPER)
621    {
622        return None;
623    }
624    if view.searching {
625        match key.code {
626            KeyCode::Esc | KeyCode::Enter => view.searching = false,
627            KeyCode::Backspace | KeyCode::Delete => {
628                if let Some((index, _)) = view.query.grapheme_indices(true).next_back() {
629                    view.query.truncate(index);
630                }
631                view.filter();
632            }
633            KeyCode::Char(character) if !character.is_control() => {
634                view.append_query(&character.to_string())
635            }
636            _ => (),
637        }
638        return None;
639    }
640    if view.focus == Focus::Help {
641        match key.code {
642            KeyCode::Esc | KeyCode::Left | KeyCode::Backspace => {
643                view.toggle_help();
644                return None;
645            }
646            KeyCode::Char('?' | 'q' | 'j' | 'k' | 'p')
647            | KeyCode::Up
648            | KeyCode::Down
649            | KeyCode::PageUp
650            | KeyCode::PageDown
651            | KeyCode::Home
652            | KeyCode::End => (),
653            _ => return None,
654        }
655    }
656    let position = if view.focus == Focus::List {
657        view.list.selected().unwrap_or(0)
658    } else {
659        view.scroll
660    };
661    let page = if view.focus == Focus::List {
662        view.page
663    } else {
664        view.detail_page
665    };
666    match key.code {
667        KeyCode::Char('q') => return Some(ModelOutcome::Exit { code: 0 }),
668        KeyCode::Char('?') if key.kind == KeyEventKind::Press => view.toggle_help(),
669        KeyCode::Char(' ')
670            if key.kind == KeyEventKind::Press
671                && view.comparison
672                && matches!(view.focus, Focus::List | Focus::Detail) =>
673        {
674            view.toggle_mark()
675        }
676        KeyCode::Char('c') if key.kind == KeyEventKind::Press && view.comparison => {
677            if view.focus == Focus::Compare {
678                view.focus(Focus::List);
679            } else if view.marked.len() < 2 {
680                view.notice = Some("Mark at least 2 models with Space to compare (max 4)");
681            } else {
682                view.notice = None;
683                view.focus(Focus::Compare);
684            }
685        }
686        KeyCode::Esc if view.focus == Focus::List => return Some(ModelOutcome::Exit { code: 0 }),
687        KeyCode::Esc | KeyCode::Left | KeyCode::Backspace => view.focus(Focus::List),
688        KeyCode::Enter | KeyCode::Tab | KeyCode::BackTab => {
689            if view.focus == Focus::List && view.selected().is_some() {
690                view.focus(Focus::Detail);
691            } else {
692                view.focus(Focus::List);
693            }
694        }
695        KeyCode::Right if view.selected().is_some() => view.focus(Focus::Detail),
696        KeyCode::Char('i') => view.focus(if view.focus == Focus::Overview {
697            Focus::List
698        } else {
699            Focus::Overview
700        }),
701        KeyCode::Char('/') => {
702            view.searching = true;
703            view.focus(Focus::List);
704        }
705        KeyCode::Down | KeyCode::Char('j') => view.move_to(position.saturating_add(1)),
706        KeyCode::Up | KeyCode::Char('k') => view.move_to(position.saturating_sub(1)),
707        KeyCode::PageDown => view.move_to(position.saturating_add(page)),
708        KeyCode::PageUp => view.move_to(position.saturating_sub(page)),
709        KeyCode::Home => view.move_to(0),
710        KeyCode::End => view.move_to(usize::MAX),
711        KeyCode::Char('p') if key.kind == KeyEventKind::Press => {
712            return view
713                .command
714                .as_ref()
715                .map(|command| ModelOutcome::PrintCommand {
716                    command: command.clone(),
717                });
718        }
719        KeyCode::Char('s') if view.focus == Focus::List => view.cycle_sort(None),
720        KeyCode::Char('S') if view.focus == Focus::List => {
721            if let Some((column, descending)) = view.sort {
722                view.sort = Some((column, !descending));
723                view.filter();
724            }
725        }
726        KeyCode::Char('v') if view.focus == Focus::List && !view.columns.is_empty() => {
727            view.verdict_filter = match view.verdict_filter {
728                None => Some(Verdict::Yes),
729                Some(Verdict::Yes) => Some(Verdict::Slow),
730                Some(Verdict::Slow) => Some(Verdict::No),
731                Some(Verdict::No) => Some(Verdict::Unknown),
732                Some(Verdict::Unknown) => None,
733            };
734            view.filter();
735        }
736        KeyCode::Char('y') => {
737            if let Some(index) = view.selected_index() {
738                let label = view.rows[index].label.clone();
739                view.copy(label, "model id");
740            }
741        }
742        KeyCode::Char('Y') => {
743            if let Some(index) = view.selected_index() {
744                let label = view.rows[index].label.clone();
745                if command_safe(&label) {
746                    view.copy(format!("rigspark up {label}"), "up command");
747                } else {
748                    view.notice = Some("Model id is not safe to copy as a command");
749                }
750            }
751        }
752        KeyCode::Char('e') => {
753            if let Some(index) = view.selected_index() {
754                let card = view.card(&view.rows[index]);
755                view.copy(card, "shareable card");
756            }
757        }
758        _ => (),
759    }
760    None
761}
762
763fn command_safe(id: &str) -> bool {
764    !id.is_empty()
765        && !id.starts_with('-')
766        && !id.split('/').any(|part| part == "..")
767        && id.bytes().all(|byte| {
768            byte.is_ascii_lowercase() || byte.is_ascii_digit() || b"._:/-".contains(&byte)
769        })
770}
771
772/// Unknowns sort last in both directions; numbers compare numerically, then text.
773fn sort_key(row: &ModelRow, column: usize) -> (u8, f64, String) {
774    let cells = row.cells();
775    let text = if column == 0 {
776        row.label.as_str()
777    } else {
778        cells.get(column - 1).copied().unwrap_or("")
779    };
780    if column > 0 {
781        match tui_theme::verdict_kind(text) {
782            Some(Verdict::Unknown) => return (1, 0.0, String::new()),
783            Some(verdict) => return (0, f64::from(verdict as u8), String::new()),
784            None => (),
785        }
786    }
787    let lower = text.to_lowercase();
788    if text.is_empty() || lower.starts_with("unknown") {
789        return (1, 0.0, lower);
790    }
791    let number = if column == 0 {
792        0.0
793    } else {
794        let digits: String = text
795            .chars()
796            .skip_while(|character| !character.is_ascii_digit())
797            .take_while(|character| character.is_ascii_digit() || *character == '.')
798            .collect();
799        digits.parse().unwrap_or(0.0)
800    };
801    (0, number, lower)
802}
803
804/// Wheel scrolls the pane under the pointer; clicks select rows, open the selected row, or sort by a header.
805pub fn handle_mouse(view: &mut ModelView, mouse: MouseEvent) {
806    let point = Position::new(mouse.column, mouse.row);
807    view.toast = None;
808    match mouse.kind {
809        MouseEventKind::ScrollDown | MouseEventKind::ScrollUp => {
810            let down = mouse.kind == MouseEventKind::ScrollDown;
811            if view.focus == Focus::List && !view.areas.detail.contains(point) {
812                let position = view.list.selected().unwrap_or(0);
813                view.move_to(if down {
814                    position.saturating_add(1)
815                } else {
816                    position.saturating_sub(1)
817                });
818            } else if view.focus != Focus::List {
819                view.scroll = if down {
820                    view.scroll.saturating_add(3).min(view.scroll_max)
821                } else {
822                    view.scroll.saturating_sub(3)
823                };
824            }
825        }
826        MouseEventKind::Down(MouseButton::Left) if view.focus == Focus::List => {
827            if let Some((_, column)) = view
828                .areas
829                .header
830                .iter()
831                .find(|(area, _)| area.contains(point))
832            {
833                let column = *column;
834                view.cycle_sort(Some(column));
835            } else if view.areas.rows.contains(point) {
836                let row = view.list.offset() + usize::from(point.y - view.areas.rows.y);
837                if row < view.visible.len() {
838                    if view.list.selected() == Some(row) {
839                        view.focus(Focus::Detail);
840                    } else {
841                        view.list.select(Some(row));
842                    }
843                }
844            }
845        }
846        _ => (),
847    }
848}
849
850pub fn handle_event(view: &mut ModelView, event: Event) -> Option<ModelOutcome> {
851    match event {
852        Event::Key(key) => handle_key(view, key),
853        Event::Mouse(mouse) => {
854            handle_mouse(view, mouse);
855            None
856        }
857        Event::Paste(text) if view.searching => {
858            view.append_query(&text);
859            None
860        }
861        _ => None,
862    }
863}
864
865/// Evidence labels emitted by the presentation builders, longest prefixes first.
866const EVIDENCE_KEYS: [&str; 24] = [
867    "throughput backend",
868    "unknown reason",
869    "KV bytes/token",
870    "selected quant",
871    "quantizations",
872    "capabilities",
873    "architecture",
874    "open weight",
875    "throughput",
876    "benchmark",
877    "backends",
878    "release",
879    "license",
880    "context",
881    "verdict",
882    "sources",
883    "family",
884    "params",
885    "scores",
886    "source",
887    "score",
888    "rank",
889    "need",
890    "fit",
891];
892
893enum Entry {
894    Heading(String),
895    Note(String),
896    Plain(String),
897    Field { key: String, value: String },
898    Blank,
899}
900
901fn split_key(segment: &str) -> Entry {
902    EVIDENCE_KEYS
903        .iter()
904        .find_map(|key| {
905            segment
906                .strip_prefix(key)
907                .and_then(|rest| rest.strip_prefix(' '))
908                .map(|value| Entry::Field {
909                    key: (*key).to_owned(),
910                    value: value.to_owned(),
911                })
912        })
913        .unwrap_or_else(|| Entry::Field {
914            key: String::new(),
915            value: segment.to_owned(),
916        })
917}
918
919fn evidence_entries(row: &ModelRow, entries: &mut Vec<Entry>) {
920    for (index, segment) in row
921        .evidence
922        .lines()
923        .flat_map(|line| line.split("; "))
924        .enumerate()
925    {
926        entries.push(if index == 0 && segment == row.label {
927            Entry::Heading(segment.to_owned())
928        } else {
929            split_key(segment)
930        });
931    }
932}
933
934/// Lays out entries with right-aligned keys so every `key value` stays contiguous.
935fn layout(entries: &[Entry], width: u16, theme: Theme, key_style: Style) -> Vec<Line<'static>> {
936    let width = usize::from(width.max(1));
937    let key_width = entries
938        .iter()
939        .filter_map(|entry| match entry {
940            Entry::Field { key, .. } => Some(tui_theme::width(key)),
941            _ => None,
942        })
943        .max()
944        .unwrap_or(0)
945        .min(width / 3);
946    let aligned = width >= 30;
947    let mut lines = Vec::new();
948    for entry in entries {
949        match entry {
950            Entry::Heading(text) => lines.extend(
951                tui_theme::wrap(text, width)
952                    .into_iter()
953                    .map(|line| Line::styled(line, theme.title())),
954            ),
955            Entry::Note(text) => lines.extend(
956                tui_theme::wrap(text, width)
957                    .into_iter()
958                    .map(|line| Line::styled(line, theme.muted())),
959            ),
960            Entry::Plain(text) => {
961                lines.extend(tui_theme::wrap(text, width).into_iter().map(Line::from))
962            }
963            Entry::Blank => lines.push(Line::default()),
964            Entry::Field { key, value } if !aligned => {
965                let text = if key.is_empty() {
966                    value.clone()
967                } else {
968                    format!("{key} {value}")
969                };
970                lines.extend(tui_theme::wrap(&text, width).into_iter().map(Line::from));
971            }
972            Entry::Field { key, value } => {
973                let key_cells = tui_theme::width(key);
974                let indent = key_width.max(key_cells) + 1;
975                let value_style = match key.as_str() {
976                    "verdict" | "fit" => theme.verdict(value),
977                    _ => Style::default(),
978                };
979                let items: Vec<&str> = if matches!(key.as_str(), "sources" | "quantizations") {
980                    value.split(", ").collect()
981                } else {
982                    vec![value.as_str()]
983                };
984                let mut first = true;
985                for item in items {
986                    for piece in tui_theme::wrap(item, width.saturating_sub(indent)) {
987                        let mut spans = Vec::with_capacity(4);
988                        if first && !key.is_empty() {
989                            spans.push(Span::raw(" ".repeat(key_width.saturating_sub(key_cells))));
990                            spans.push(Span::styled(key.clone(), key_style));
991                            spans.push(Span::raw(" "));
992                        } else {
993                            spans.push(Span::raw(" ".repeat(indent)));
994                        }
995                        spans.push(Span::styled(piece, value_style));
996                        lines.push(Line::from(spans));
997                        first = false;
998                    }
999                }
1000            }
1001        }
1002    }
1003    lines
1004}
1005
1006fn render_detail(frame: &mut Frame<'_>, view: &mut ModelView, area: Rect, theme: Theme) {
1007    let title = match view.focus {
1008        Focus::Overview => "Machine / scope".to_owned(),
1009        Focus::Help => "Keyboard help".to_owned(),
1010        Focus::Compare => format!("Compare {} models", view.marked.len()),
1011        _ => "Evidence".to_owned(),
1012    };
1013    let inner = theme.panel(frame, area, &title);
1014    let lines = if view.focus == Focus::Help {
1015        let mut help = vec![
1016            "Up/Down or j/k: navigate list or scroll screen",
1017            "PageUp/PageDown: page; Home/End: first/last",
1018            "/: search; Enter/Esc: close search; Ctrl+U: reset filter",
1019            "Enter/Right/Tab: details; Left/Backspace/Esc: back",
1020            "i: machine/scope; ?: toggle help",
1021            "s: sort by next column (Model, then each column, then original); S: reverse",
1022            "y: copy model id; Y: copy `rigspark up` command; e: copy shareable card",
1023            "Mouse: wheel scrolls; click selects, click again opens; click a header sorts",
1024            "Esc: back from screen; Esc on list or q: quit",
1025            "Ctrl+C: interrupt (exit 130)",
1026            "Read-only: stored evidence only; no actions execute",
1027        ];
1028        if view.comparison {
1029            help.extend([
1030                "Space: mark/unmark selected model (max 4)",
1031                "c: compare 2-4 marked models / return to list",
1032                "Marks survive filtering; * identifies a marked model",
1033            ]);
1034        }
1035        if !view.columns.is_empty() {
1036            help.push("v: cycle verdict filter (yes, slow, no, unknown, all)");
1037        }
1038        if view.command.is_some() {
1039            help.push("p: finish and print existing top-pick command; never execute");
1040        }
1041        let entries: Vec<_> = help
1042            .into_iter()
1043            .map(|line| match line.split_once(": ") {
1044                Some((key, value)) => Entry::Field {
1045                    key: format!("{key}:"),
1046                    value: value.to_owned(),
1047                },
1048                None => Entry::Plain(line.to_owned()),
1049            })
1050            .collect();
1051        layout(&entries, inner.width, theme, theme.title())
1052    } else if view.focus == Focus::Compare {
1053        compare_lines(view, inner.width, theme).unwrap_or_else(|| {
1054            let mut entries = Vec::new();
1055            for index in &view.marked {
1056                let row = &view.rows[*index];
1057                if !entries.is_empty() {
1058                    entries.push(Entry::Blank);
1059                }
1060                entries.push(Entry::Heading(row.label.clone()));
1061                if !row.summary.is_empty() {
1062                    entries.push(Entry::Note(row.summary.clone()));
1063                }
1064                let mut evidence = Vec::new();
1065                evidence_entries(row, &mut evidence);
1066                if matches!(evidence.first(), Some(Entry::Heading(_))) {
1067                    evidence.remove(0);
1068                }
1069                entries.extend(evidence);
1070            }
1071            layout(&entries, inner.width, theme, theme.muted())
1072        })
1073    } else if view.focus == Focus::Overview {
1074        let entries: Vec<_> = view
1075            .overview
1076            .iter()
1077            .map(|line| Entry::Plain(line.clone()))
1078            .collect();
1079        layout(&entries, inner.width, theme, theme.muted())
1080    } else if let Some(row) = view.selected() {
1081        let mut entries = Vec::new();
1082        evidence_entries(row, &mut entries);
1083        let heading = matches!(entries.first(), Some(Entry::Heading(_)));
1084        if heading {
1085            entries.insert(1, Entry::Blank);
1086        }
1087        let mut lines = layout(&entries, inner.width, theme, theme.muted());
1088        if let Some(usable) = view.usable_bytes {
1089            let gauge = match row.need_bytes {
1090                Some(need) => tui_theme::gauge(
1091                    theme,
1092                    need,
1093                    usable,
1094                    usize::from(inner.width).saturating_sub(8),
1095                ),
1096                None => Line::styled("need unknown", theme.muted()),
1097            };
1098            let mut spans = vec![Span::styled("Memory  ", theme.muted())];
1099            spans.extend(gauge.spans);
1100            lines.insert(usize::from(heading), Line::from(spans));
1101        }
1102        lines
1103    } else {
1104        vec![Line::styled("No model selected", theme.muted())]
1105    };
1106    view.detail_page = usize::from(inner.height.max(1));
1107    view.scroll_max = lines.len().saturating_sub(view.detail_page);
1108    view.scroll = view.scroll.min(view.scroll_max);
1109    let total = lines.len();
1110    let visible: Vec<_> = lines
1111        .into_iter()
1112        .skip(view.scroll)
1113        .take(view.detail_page)
1114        .collect();
1115    frame.render_widget(Paragraph::new(visible), inner);
1116    tui_theme::scrollbar(frame, area, total, view.scroll, view.detail_page, theme);
1117}
1118
1119/// Side-by-side comparison aligned by evidence key; `None` when columns would be too narrow.
1120fn compare_lines(view: &ModelView, width: u16, theme: Theme) -> Option<Vec<Line<'static>>> {
1121    let width = usize::from(width);
1122    let count = view.marked.len();
1123    if count == 0 {
1124        return None;
1125    }
1126    let mut order: Vec<String> = Vec::new();
1127    let mut tables: Vec<Vec<(String, String)>> = Vec::new();
1128    for index in &view.marked {
1129        let row = &view.rows[*index];
1130        let mut entries = Vec::new();
1131        evidence_entries(row, &mut entries);
1132        let mut unkeyed = 0;
1133        let mut fields = Vec::new();
1134        for entry in entries {
1135            if let Entry::Field { key, value } = entry {
1136                let id = if key.is_empty() {
1137                    unkeyed += 1;
1138                    format!("\u{0}{unkeyed}")
1139                } else {
1140                    key
1141                };
1142                if !order.contains(&id) {
1143                    order.push(id.clone());
1144                }
1145                fields.push((id, value));
1146            }
1147        }
1148        tables.push(fields);
1149    }
1150    let display = |id: &str| {
1151        if id.starts_with('\u{0}') {
1152            String::new()
1153        } else {
1154            id.to_owned()
1155        }
1156    };
1157    let key_width = order
1158        .iter()
1159        .map(|id| tui_theme::width(&display(id)))
1160        .max()
1161        .unwrap_or(0)
1162        .min(18);
1163    let cell = width.checked_sub(key_width + 3 * count)? / count;
1164    if cell < 14 {
1165        return None;
1166    }
1167    let pad = |text: &str, width: usize| {
1168        format!(
1169            "{text}{}",
1170            " ".repeat(width.saturating_sub(tui_theme::width(text)))
1171        )
1172    };
1173    let mut lines = Vec::new();
1174    let mut header = vec![Span::raw(" ".repeat(key_width))];
1175    for index in &view.marked {
1176        header.push(Span::styled(" │ ", theme.border()));
1177        let label = tui_theme::truncate(vec![Span::raw(view.rows[*index].label.clone())], cell);
1178        let text: String = label.iter().map(|span| span.content.as_ref()).collect();
1179        header.push(Span::styled(pad(&text, cell), theme.title()));
1180    }
1181    lines.push(Line::from(header));
1182    lines.push(Line::styled("─".repeat(width), theme.border()));
1183    let mut rows: Vec<(String, Vec<String>)> = vec![(
1184        "summary".into(),
1185        view.marked
1186            .iter()
1187            .map(|index| view.rows[*index].cells().join(" · "))
1188            .collect(),
1189    )];
1190    for id in &order {
1191        rows.push((
1192            display(id),
1193            tables
1194                .iter()
1195                .map(|fields| {
1196                    fields
1197                        .iter()
1198                        .find(|(key, _)| key == id)
1199                        .map_or_else(|| "—".into(), |(_, value)| value.clone())
1200                })
1201                .collect(),
1202        ));
1203    }
1204    for (key, values) in rows {
1205        let wrapped: Vec<Vec<String>> = values
1206            .iter()
1207            .map(|value| tui_theme::wrap(value, cell))
1208            .collect();
1209        let height = wrapped.iter().map(Vec::len).max().unwrap_or(1);
1210        for line in 0..height {
1211            let key_text = if line == 0 { key.as_str() } else { "" };
1212            let mut spans = vec![Span::styled(
1213                pad(
1214                    &key_text.chars().take(key_width).collect::<String>(),
1215                    key_width,
1216                ),
1217                theme.muted(),
1218            )];
1219            for (column, cells) in wrapped.iter().enumerate() {
1220                spans.push(Span::styled(" │ ", theme.border()));
1221                let text = cells.get(line).cloned().unwrap_or_default();
1222                let style = match key.as_str() {
1223                    "verdict" | "fit" => theme.verdict(&values[column]),
1224                    "summary" => theme.muted(),
1225                    _ => Style::default(),
1226                };
1227                spans.push(Span::styled(pad(&text, cell), style));
1228            }
1229            lines.push(Line::from(spans));
1230        }
1231    }
1232    Some(lines)
1233}
1234
1235fn render_table(frame: &mut Frame<'_>, view: &mut ModelView, area: Rect, theme: Theme) {
1236    let inner = theme.panel(
1237        frame,
1238        area,
1239        &format!("Models {}/{}", view.visible_count(), view.rows.len()),
1240    );
1241    view.areas.header.clear();
1242    view.areas.rows = Rect::default();
1243    if view.visible.is_empty() {
1244        let mut lines = vec![Line::styled("No results", theme.muted())];
1245        if !view.query.is_empty() || view.verdict_filter.is_some() {
1246            lines.push(Line::styled("Ctrl+U resets the filter", theme.muted()));
1247        }
1248        frame.render_widget(Paragraph::new(lines), inner);
1249        return;
1250    }
1251    let header_row = inner.height >= 3;
1252    let available = usize::from(inner.width).saturating_sub(2);
1253    let widths: Vec<usize> = (0..view.columns.len())
1254        .map(|column| {
1255            view.visible
1256                .iter()
1257                .map(|index| {
1258                    view.rows[*index]
1259                        .cells()
1260                        .get(column)
1261                        .map_or(0, |text| tui_theme::width(text))
1262                })
1263                .max()
1264                .unwrap_or(0)
1265                .max(tui_theme::width(view.columns[column]) + 2)
1266                .min(18)
1267        })
1268        .collect();
1269    let model_width = view
1270        .visible
1271        .iter()
1272        .map(|index| tui_theme::width(&view.rows[*index].label) + 2)
1273        .max()
1274        .unwrap_or(12)
1275        .clamp(12, 28);
1276    let mut shown: Vec<usize> = (0..view.columns.len()).collect();
1277    let mut droppable = view.priority.clone();
1278    while shown
1279        .iter()
1280        .map(|column| widths[*column] + 1)
1281        .sum::<usize>()
1282        + model_width
1283        > available
1284    {
1285        let Some(victim) = droppable.pop() else {
1286            shown.clear();
1287            break;
1288        };
1289        shown.retain(|column| *column != victim);
1290    }
1291    let arrow = |column: usize| match view.sort {
1292        Some((sorted, descending)) if sorted == column => {
1293            if descending {
1294                " ▼"
1295            } else {
1296                " ▲"
1297            }
1298        }
1299        _ => "",
1300    };
1301    let mut constraints = vec![Constraint::Min(u16::try_from(model_width).unwrap_or(12))];
1302    constraints.extend(
1303        shown
1304            .iter()
1305            .map(|column| Constraint::Length(u16::try_from(widths[*column]).unwrap_or(18))),
1306    );
1307    let rows: Vec<Row> = view
1308        .visible
1309        .iter()
1310        .enumerate()
1311        .map(|(position, index)| {
1312            let row = &view.rows[*index];
1313            let mut label = vec![if view.marked.contains(index) {
1314                Span::styled("* ", theme.title())
1315            } else {
1316                Span::raw("  ")
1317            }];
1318            label.extend(tui_theme::highlighted(
1319                &row.label,
1320                view.matches.get(position).map_or(&[], Vec::as_slice),
1321                theme.strong(),
1322                theme,
1323            ));
1324            let cells = row.cells();
1325            let mut columns = vec![Cell::from(Line::from(label))];
1326            for column in &shown {
1327                let text = cells.get(*column).copied().unwrap_or("");
1328                let style = if tui_theme::verdict_kind(text).is_some() {
1329                    theme.verdict(text)
1330                } else {
1331                    Style::default()
1332                };
1333                columns.push(Cell::from(Span::styled(text.to_owned(), style)));
1334            }
1335            Row::new(columns)
1336        })
1337        .collect();
1338    let mut table = Table::new(rows, constraints.clone())
1339        .column_spacing(1)
1340        .highlight_symbol("▸ ")
1341        .highlight_spacing(HighlightSpacing::Always)
1342        .row_highlight_style(theme.selection());
1343    if header_row {
1344        let mut header = vec![Cell::from(format!("Model{}", arrow(0)))];
1345        header.extend(
1346            shown.iter().map(|column| {
1347                Cell::from(format!("{}{}", view.columns[*column], arrow(column + 1)))
1348            }),
1349        );
1350        table = table.header(Row::new(header).style(theme.title()));
1351    }
1352    frame.render_stateful_widget(table, inner, &mut view.list);
1353    let body_offset = u16::from(header_row);
1354    view.page = usize::from(inner.height.saturating_sub(body_offset)).max(1);
1355    view.areas.rows = Rect {
1356        y: inner.y + body_offset,
1357        height: inner.height.saturating_sub(body_offset),
1358        ..inner
1359    };
1360    if header_row {
1361        let header_area = Rect {
1362            x: inner.x + 2,
1363            width: inner.width.saturating_sub(2),
1364            height: 1,
1365            ..inner
1366        };
1367        let cells = Layout::horizontal(constraints)
1368            .spacing(1)
1369            .split(header_area);
1370        view.areas.header = cells
1371            .iter()
1372            .enumerate()
1373            .map(|(position, area)| {
1374                (
1375                    *area,
1376                    if position == 0 {
1377                        0
1378                    } else {
1379                        shown[position - 1] + 1
1380                    },
1381                )
1382            })
1383            .collect();
1384    }
1385    tui_theme::scrollbar(
1386        frame,
1387        area,
1388        view.visible.len(),
1389        view.list.offset(),
1390        view.page,
1391        theme,
1392    );
1393}
1394
1395pub fn render(frame: &mut Frame<'_>, view: &mut ModelView) {
1396    let area = frame.area();
1397    if area.is_empty() {
1398        return;
1399    }
1400    let theme = Theme::new(view.color);
1401    let compact_overview = area.height >= 12 && !view.overview.is_empty();
1402    let overview: Vec<String> = view
1403        .overview
1404        .iter()
1405        .take(2)
1406        .flat_map(|line| tui_theme::wrap(line, usize::from(area.width.saturating_sub(4))))
1407        .take(3)
1408        .collect();
1409    let context_height = if area.height >= 28 && !overview.is_empty() {
1410        overview.len() + 2
1411    } else if compact_overview {
1412        view.overview.len().min(2)
1413    } else {
1414        0
1415    };
1416    let [header, context, body, status, footer] = Layout::vertical([
1417        Constraint::Length(1),
1418        Constraint::Length(u16::try_from(context_height).unwrap_or(0)),
1419        Constraint::Min(0),
1420        Constraint::Length(if area.height >= 3 { 1 } else { 0 }),
1421        Constraint::Length(if area.height >= 2 { 1 } else { 0 }),
1422    ])
1423    .areas(area);
1424    theme.header(
1425        frame,
1426        header,
1427        &format!("rigspark / {}", view.title),
1428        "Read-only",
1429    );
1430    if context.height > 2 {
1431        let inner = theme.panel(frame, context, "Machine / scope");
1432        let lines: Vec<_> = overview
1433            .into_iter()
1434            .enumerate()
1435            .map(|(index, line)| {
1436                if index == 0 {
1437                    Line::from(line)
1438                } else {
1439                    Line::styled(line, theme.muted())
1440                }
1441            })
1442            .collect();
1443        frame.render_widget(Paragraph::new(lines), inner);
1444    } else {
1445        let lines: Vec<_> = view
1446            .overview
1447            .iter()
1448            .take(2)
1449            .map(|line| Line::styled(format!(" {line}"), theme.muted()))
1450            .collect();
1451        frame.render_widget(Paragraph::new(lines), context);
1452    }
1453    if view.focus != Focus::List {
1454        view.areas = HitAreas::default();
1455        render_detail(frame, view, body, theme);
1456    } else {
1457        let (list_area, detail_area) = if body.width >= 110 {
1458            let [list, detail] =
1459                Layout::horizontal([Constraint::Percentage(55), Constraint::Percentage(45)])
1460                    .areas(body);
1461            (list, Some(detail))
1462        } else if body.height >= 14 {
1463            let [list, detail] =
1464                Layout::vertical([Constraint::Percentage(50), Constraint::Percentage(50)])
1465                    .areas(body);
1466            (list, Some(detail))
1467        } else {
1468            (body, None)
1469        };
1470        render_table(frame, view, list_area, theme);
1471        if let Some(detail) = detail_area {
1472            render_detail(frame, view, detail, theme);
1473            view.areas.detail = detail;
1474        } else {
1475            view.areas.detail = Rect::default();
1476        }
1477    }
1478    if let Some(toast) = &view.toast {
1479        let width = u16::try_from(tui_theme::width(toast) + 4)
1480            .unwrap_or(u16::MAX)
1481            .min(body.width);
1482        if body.height >= 3 && width >= 8 {
1483            let area = Rect {
1484                x: body.right() - width,
1485                y: body.bottom() - 3,
1486                width,
1487                height: 3,
1488            };
1489            frame.render_widget(Clear, area);
1490            let inner = theme.panel(frame, area, "");
1491            frame.render_widget(
1492                Paragraph::new(Line::styled(toast.clone(), theme.success())),
1493                inner,
1494            );
1495        }
1496    }
1497    let left = if view.searching {
1498        Line::from(vec![
1499            Span::styled(" /", theme.title()),
1500            Span::raw(view.query.clone()),
1501            Span::styled("▌", theme.accent()),
1502        ])
1503    } else if let Some(notice) = view.notice {
1504        Line::styled(format!(" {notice}"), theme.warning())
1505    } else if !view.query.is_empty() {
1506        Line::from(vec![
1507            Span::styled(" Filter ", theme.muted()),
1508            Span::styled(view.query.clone(), theme.accent()),
1509        ])
1510    } else {
1511        Line::default()
1512    };
1513    let mut position = if view.focus == Focus::List {
1514        format!(
1515            "{}/{}",
1516            view.list.selected().map_or(0, |index| index + 1),
1517            view.visible_count()
1518        )
1519    } else {
1520        format!("Line {}/{}", view.scroll + 1, view.scroll_max + 1)
1521    };
1522    if view.comparison {
1523        position.push_str(&format!(" · Marked {}/{MAX_MARKED}", view.marked.len()));
1524    }
1525    if let Some(verdict) = view.verdict_filter {
1526        position.insert_str(
1527            0,
1528            &format!("verdict {} · ", format!("{verdict:?}").to_lowercase()),
1529        );
1530    }
1531    if let Some((column, descending)) = view.sort {
1532        let name = if column == 0 {
1533            "model"
1534        } else {
1535            view.columns.get(column - 1).copied().unwrap_or("?")
1536        };
1537        position.insert_str(
1538            0,
1539            &format!(
1540                "sort {} {} · ",
1541                name.to_lowercase(),
1542                if descending { "▼" } else { "▲" }
1543            ),
1544        );
1545    }
1546    theme.bar(
1547        frame,
1548        status,
1549        left,
1550        Line::styled(format!("{position} "), theme.muted()),
1551    );
1552    let mut hints: Vec<(&str, &str)> = if view.searching {
1553        vec![("Enter", "apply"), ("Esc", "close"), ("Ctrl+U", "reset")]
1554    } else if view.focus == Focus::Help {
1555        vec![("Esc", "back"), ("↑↓", "scroll"), ("q", "quit")]
1556    } else if view.focus != Focus::List {
1557        vec![
1558            ("Esc", "back"),
1559            ("↑↓", "scroll"),
1560            ("Home/End", "jump"),
1561            ("?", "help"),
1562            ("q", "quit"),
1563        ]
1564    } else {
1565        vec![
1566            ("q", "quit"),
1567            ("?", "help"),
1568            ("/", "search"),
1569            ("Enter", "detail"),
1570            ("s", "sort"),
1571        ]
1572    };
1573    if !view.searching && view.focus == Focus::List {
1574        if !view.columns.is_empty() {
1575            hints.push(("v", "verdict"));
1576        }
1577        hints.push(("y", "copy"));
1578        if view.comparison {
1579            hints.extend([("Space", "mark"), ("c", "compare")]);
1580        } else {
1581            hints.push(("i", "overview"));
1582        }
1583        if view.command.is_some() {
1584            hints.push(("p", "finish/print"));
1585        }
1586    }
1587    frame.render_widget(Paragraph::new(theme.hints(&hints, footer.width)), footer);
1588}
1589
1590pub async fn show_models(mut view: ModelView) -> io::Result<ModelOutcome> {
1591    let mut signals = crate::cancellation::TerminalSignals::new()?;
1592    let (mut terminal, _restore) = crate::tui_view::enter_terminal()?;
1593    let mut events = crate::terminal_events::terminal_events();
1594    loop {
1595        terminal.draw(|frame| render(frame, &mut view))?;
1596        let expiry = tokio::time::sleep(std::time::Duration::from_millis(2500));
1597        let event = tokio::select! {
1598            code = signals.recv() => return Ok(ModelOutcome::Exit { code: code? }),
1599            event = crate::tui_view::next_navigation_event(&mut events) => event?,
1600            () = expiry, if view.toast.is_some() => {
1601                view.toast = None;
1602                continue;
1603            }
1604        };
1605        if let Some(outcome) = handle_event(&mut view, event) {
1606            return Ok(outcome);
1607        }
1608        if let Some(text) = view.take_clipboard() {
1609            tui_theme::copy_to_clipboard(&text)?;
1610        }
1611    }
1612}