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 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 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 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 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 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
814fn 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
846pub 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
907const 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
976fn 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
1164fn 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}