Switchyard lets LLM applications route traffic across models and providers while preserving native OpenAI and Anthropic API compatibility - enabling flexible model selection, benchmarking, and cost/performance optimization.
Rust
feat(desktop): add Overview usage cards, the hourly chart, and the help window (#1088)
Elyas Mehtabuddin324f01164d81
diff --git a/crates/switchyard-desktop/src/controller.rs b/crates/switchyard-desktop/src/controller.rsindex 5cf09c55d..70da3fc92 100644--- a/crates/switchyard-desktop/src/controller.rs+++ b/crates/switchyard-desktop/src/controller.rs@@ -4,16 +4,21 @@//! The terminal controller reloads settings and combines usage and server health into snapshots.//! It retains the log reader and health probe across refreshes.-use crate::{config::Config, rollup};+use crate::{config::Config, history, pricing, rollup};use serde::Serialize;use serde_json::{Value, json};-use std::path::PathBuf;+use std::{collections::BTreeMap, path::PathBuf};/// Snapshot holds the terminal app's usage, server health, errors, and refresh interval.#[derive(Clone, Default, Serialize)]pub struct Snapshot {pub data_state: DataState,pub metrics: Metrics,+ pub today: chrono::NaiveDate,+ /// The keys are `today`, `week`, and `all`. A value is null when usage could not be read.+ pub estimates: BTreeMap<&'static str, Option<pricing::Estimate>>,+ pub activity: [u64; 24],+ pub limited: bool,pub errors: Vec<String>,pub refresh_seconds: u64,}@@ -89,6 +94,23 @@ impl Controller {errors.push(format!("Could not read usage: {error}"));rollup::Usage::default()});+ // Invalid overrides leave baseline rates unknown and add an error to the snapshot.+ let rates = pricing::load(self.config.prices_file.as_deref()).unwrap_or_else(|error| {+ errors.push(format!("Could not read model prices: {error}"));+ Default::default()+ });+ let estimates = [+ ("today", &usage.today),+ ("week", &usage.week),+ ("all", &usage.all),+ ]+ .into_iter()+ .map(|(period, totals)| {+ let estimate = (usage_state == Availability::Available)+ .then(|| pricing::Estimate::new(totals, &rates, &self.config.baseline_model));+ (period, estimate)+ })+ .collect();let checked_at = chrono::Utc::now().to_rfc3339();let mut health = self.health_probe.details(&self.config.server_url);health["checked_at"] = json!(checked_at);@@ -98,6 +120,11 @@ impl Controller {} else {crate::health::ServerStatus::Stopped};+ let history = history::load(&self.config.routing_log).unwrap_or_else(|error| {+ errors.push(format!("Could not read recent calls: {error}"));+ history::History::default()+ });+ let activity = history::hourly_calls(&history.entries, chrono::Utc::now());let server_url = self.config.server_url.clone();let routing_log = self.config.routing_log.clone();let refresh_seconds = self.config.refresh_seconds;@@ -122,8 +149,44 @@ impl Controller {tokens: usage.week.tokens(),},},+ today,+ estimates,+ activity,+ limited: history.limited,errors,refresh_seconds: refresh_seconds.max(1),})}}++#[cfg(test)]+mod tests {+ use super::{Config, Controller};++ #[test]+ fn recent_call_read_errors_name_the_source_and_keep_the_io_details() {+ let directory = tempfile::tempdir().expect("directory");+ let settings = directory.path().join("desktop.toml");+ let path = directory.path().to_str().expect("UTF-8 path");+ std::fs::write(+ &settings,+ format!("routing_log = {path:?}\nserver_url = 'http://127.0.0.1:9'\n"),+ )+ .expect("settings");+ let config = Config::load(&settings).expect("config");+ let expected = crate::history::load(directory.path())+ .err()+ .expect("directory read fails");+ let snapshot = Controller::new(config, settings)+ .snapshot()+ .expect("snapshot");+ assert!(+ snapshot+ .errors+ .contains(&format!("Could not read recent calls: {expected}")),+ "{:?}",+ snapshot.errors+ );+ assert_eq!(snapshot.activity, [0; 24]);+ }+}diff --git a/crates/switchyard-desktop/src/history.rs b/crates/switchyard-desktop/src/history.rsindex feebe6295..697ec6367 100644--- a/crates/switchyard-desktop/src/history.rs+++ b/crates/switchyard-desktop/src/history.rs@@ -1,11 +1,17 @@// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.// SPDX-License-Identifier: Apache-2.0-//! This module describes one completed model call in the routing log.+//! This module reads recent completed model calls and counts them by hour.use serde::Deserialize;+use std::collections::VecDeque;+use std::io::{Read, Seek, SeekFrom};+use std::path::Path;-#[derive(Debug, Deserialize, serde::Serialize)]+const MAX_BYTES: u64 = 8 * 1024 * 1024;+const MAX_RECORDS: usize = 5000;++#[derive(Clone, Debug, Deserialize, serde::Serialize)]pub struct Entry {pub ts: String,pub model: String,@@ -31,3 +37,119 @@ pub struct Entry {#[serde(default)]pub cost: Option<switchyard_costs::RecordedCost>,}++#[derive(Default)]+pub struct History {+ pub entries: Vec<Entry>,+ pub limited: bool,+}++// `hourly_calls` uses bounded recent history, so its buckets may omit calls from a busy day.+pub fn hourly_calls(entries: &[Entry], now: chrono::DateTime<chrono::Utc>) -> [u64; 24] {+ let mut buckets = [0; 24];+ for entry in entries {+ if let Ok(time) = chrono::DateTime::parse_from_rfc3339(&entry.ts) {+ let age = now.signed_duration_since(time);+ if (chrono::Duration::zero()..chrono::Duration::hours(24)).contains(&age) {+ buckets[23 - age.num_seconds() as usize / 3600] += 1;+ }+ }+ }+ buckets+}++pub fn load(path: &Path) -> Result<History, String> {+ let mut file = match std::fs::File::open(path) {+ Ok(f) => f,+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(History::default()),+ Err(e) => return Err(e.to_string()),+ };+ let size = file.metadata().map_err(|e| e.to_string())?.len();+ let offset = size.saturating_sub(MAX_BYTES);+ // The preceding byte distinguishes a partial record from a complete first+ // record when the byte limit starts immediately after a newline.+ let mut previous = *b"\n";+ if offset > 0 {+ file.seek(SeekFrom::Start(offset - 1))+ .map_err(|e| e.to_string())?;+ file.read_exact(&mut previous).map_err(|e| e.to_string())?;+ }+ file.seek(SeekFrom::Start(offset))+ .map_err(|e| e.to_string())?;+ let mut bytes = Vec::new();+ file.take(MAX_BYTES)+ .read_to_end(&mut bytes)+ .map_err(|e| e.to_string())?;+ let mut history = parse(&bytes, offset > 0 && previous[0] != b'\n');+ history.limited |= offset > 0;+ Ok(history)+}++fn parse(bytes: &[u8], truncated: bool) -> History {+ let mut result = History {+ limited: truncated,+ ..History::default()+ };+ let mut lines = bytes.split_inclusive(|b| *b == b'\n');+ if truncated {+ lines.next();+ }+ let mut entries = VecDeque::new();+ for line in lines {+ if !line.ends_with(b"\n") {+ break;+ }+ match serde_json::from_slice::<Entry>(line) {+ Ok(entry)+ if !entry.model.trim().is_empty()+ && chrono::DateTime::parse_from_rfc3339(&entry.ts).is_ok() =>+ {+ if entries.len() == MAX_RECORDS {+ entries.pop_front();+ result.limited = true;+ }+ entries.push_back(entry);+ }+ _ => {}+ }+ }+ result.entries = entries.into();+ result+}++#[cfg(test)]+mod tests {+ use super::{MAX_BYTES, MAX_RECORDS, load};++ #[test]+ fn retains_recent_records_and_complete_byte_limited_records() {+ let directory = tempfile::tempdir().expect("directory");+ let path = directory.path().join("log");+ let line = b"{\"ts\":\"2026-10-08T12:00:00Z\",\"model\":\"recent\"}\n";+ let mut contents = b"{\"ts\":\"2026-10-08T11:00:00Z\",\"model\":\"old\"}\n".to_vec();+ contents.extend(line.repeat(MAX_RECORDS));+ std::fs::write(&path, contents).expect("record-limited log");+ let history = load(&path).expect("record-limited history");+ assert_eq!(history.entries.len(), MAX_RECORDS);+ assert!(history.entries.iter().all(|entry| entry.model == "recent"));+ assert!(history.limited);++ for prefix in [+ b"discarded prefix\n".as_slice(),+ b"partial prefix".as_slice(),+ ] {+ let mut contents = prefix.to_vec();+ contents.extend_from_slice(line);+ contents.resize(prefix.len() + MAX_BYTES as usize, b' ');+ std::fs::write(&path, contents).expect("byte-limited log");+ let history = load(&path).expect("byte-limited history");+ assert!(history.limited);+ if prefix.ends_with(b"\n") {+ assert_eq!(history.entries.len(), 1);+ assert_eq!(history.entries[0].model, "recent");+ } else {+ assert!(history.entries.is_empty());+ }+ }+ }+}diff --git a/crates/switchyard-desktop/src/main.rs b/crates/switchyard-desktop/src/main.rsindex b4e46e9e0..4c3e7cbc8 100644--- a/crates/switchyard-desktop/src/main.rs+++ b/crates/switchyard-desktop/src/main.rs@@ -7,7 +7,7 @@#![cfg_attr(windows, windows_subsystem = "windows")]-use switchyard_desktop::{config, health, rollup};+use switchyard_desktop::{config, health, history, rollup};mod controller;#[cfg(any(target_os = "macos", windows))]mod gui;diff --git a/crates/switchyard-desktop/src/tui.rs b/crates/switchyard-desktop/src/tui.rsindex 22abf1264..71c5f392f 100644--- a/crates/switchyard-desktop/src/tui.rs+++ b/crates/switchyard-desktop/src/tui.rs@@ -7,13 +7,15 @@//! draws and reads input.use crate::controller::{Availability, Controller, Snapshot};+use crate::pricing::Estimate;+use crate::summary::{money, tokens};use ratatui::{Frame,crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers},layout::{Constraint, Layout, Rect},- style::{Color, Modifier, Style},+ style::{Color, Modifier, Style, Stylize},text::{Line, Span},- widgets::{Block, BorderType, Padding, Paragraph, Tabs, Wrap},+ widgets::{Bar, BarChart, Block, BorderType, Clear, Padding, Paragraph, Tabs, Wrap},};use std::{sync::mpsc,@@ -40,12 +42,14 @@ const GLOBAL_KEYS: &[Key] = &["refresh","Reload usage and server health now. F5 also refreshes.",),+ ("?", "help", "Show or hide this help."),("q","quit","Quit the app. The server keeps running. Ctrl-C also quits.",),];+const POPUP_KEYS: &[Key] = &[("↑↓", "scroll", ""), ("esc", "close", "")];/// Theme maps each kind of text to one style. NO_COLOR keeps the text modifiers.#[derive(Clone, Copy)]@@ -53,9 +57,11 @@ struct Theme {muted: Style,key: Style,ok: Style,+ warn: Style,error: Style,selected: Style,border: Style,+ bar: Style,}impl Theme {fn new(color: bool) -> Self {@@ -65,9 +71,11 @@ impl Theme {muted: plain.add_modifier(Modifier::DIM),key: plain.add_modifier(Modifier::BOLD),ok: plain,+ warn: plain.add_modifier(Modifier::BOLD),error: plain.add_modifier(Modifier::BOLD | Modifier::UNDERLINED),selected: plain.add_modifier(Modifier::REVERSED),border: plain,+ bar: plain,};}// Named ANSI colors follow the terminal's palette, so they work on light and dark themes.@@ -75,10 +83,12 @@ impl Theme {muted: plain.fg(Color::DarkGray),key: plain.fg(Color::Cyan).add_modifier(Modifier::BOLD),ok: plain.fg(Color::Green),+ warn: plain.fg(Color::Yellow),error: plain.fg(Color::Red),// A fixed foreground keeps dim cells readable on the selected row.selected: plain.fg(Color::Black).bg(Color::Cyan),border: plain.fg(Color::DarkGray),+ bar: plain.fg(Color::Cyan),}}}@@ -103,6 +113,47 @@ impl Tab {}}+#[derive(Clone, Copy, PartialEq, Eq)]+enum Period {+ Today,+ Week,+}+impl Period {+ fn name(self) -> &'static str {+ match self {+ Period::Today => "Today",+ Period::Week => "Past 7 days",+ }+ }+ /// The estimate is `None` when the usage log could not be read.+ fn estimate(self, snapshot: &Snapshot) -> Option<Estimate> {+ let key = match self {+ Period::Today => "today",+ Period::Week => "week",+ };+ snapshot.estimates.get(key).copied().flatten()+ }+}++enum Popup {+ Help {+ scroll: u16,+ },+ Message {+ title: &'static str,+ text: String,+ error: bool,+ scroll: u16,+ },+}+impl Popup {+ fn scroll_mut(&mut self) -> &mut u16 {+ match self {+ Popup::Help { scroll } | Popup::Message { scroll, .. } => scroll,+ }+ }+}+enum Job {Refresh,}@@ -116,18 +167,22 @@ enum Done {struct Request {job: Job,label: &'static str,+ automatic: bool,}impl Request {- fn refresh() -> Self {+ fn refresh(automatic: bool) -> Self {Self {job: Job::Refresh,label: "Refreshing",+ automatic,}}}struct Busy {label: &'static str,started: Instant,+ /// The UI retains the refresh origin so automatic failures preserve the current popup.+ automatic: bool,}struct Toast {text: String,@@ -139,6 +194,7 @@ struct App {theme: Theme,data: Snapshot,tab: Tab,+ popup: Option<Popup>,toast: Option<Toast>,busy: Option<Busy>,/// A quit request waits for the active refresh to finish.@@ -154,6 +210,7 @@ impl App {theme,data: Snapshot::default(),tab: Tab::Overview,+ popup: None,toast: None,busy: None,quit: false,@@ -163,9 +220,19 @@ impl App {}}- /// Messages appear in the status bar.+ /// Short single-line messages appear in the status bar; others open a scrollable window.fn notify(&mut self, text: String, error: bool) {- if !text.is_empty() {+ if text.is_empty() {+ return;+ }+ if text.contains('\n') || text.chars().count() + 8 > usize::from(self.width) * 2 / 3 {+ self.popup = Some(Popup::Message {+ title: if error { "Error" } else { "Done" },+ text,+ error,+ scroll: 0,+ });+ } else {self.toast = Some(Toast {text,error,@@ -175,7 +242,7 @@ impl App {}fn finish(&mut self, snapshot: Result<Box<Snapshot>, String>) {- self.busy = None;+ let automatic = self.busy.take().is_some_and(|busy| busy.automatic);match snapshot {Ok(data) => {self.data = *data;@@ -184,7 +251,15 @@ impl App {Err(error) => {// Overview keeps the error after the status message is dismissed.self.data.errors = vec![error.clone()];- self.notify(error, true);+ if automatic {+ self.toast = Some(Toast {+ text: error.lines().next().unwrap_or_default().into(),+ error: true,+ shown: Instant::now(),+ });+ } else {+ self.notify(error, true);+ }}}}@@ -221,12 +296,16 @@ impl App {self.busy = Some(Busy {label: request.label,started: Instant::now(),+ automatic: request.automatic,});Ok(())}fn keys(&self) -> &'static [Key] {- &[]+ match (&self.popup, self.tab) {+ (Some(_), _) => POPUP_KEYS,+ (None, Tab::Overview) => &[],+ }}fn key(&mut self, key: KeyEvent) -> Option<Request> {@@ -234,8 +313,12 @@ impl App {self.quit = true;return None;}+ if self.popup.is_some() {+ return self.popup_key(key);+ }match key.code {KeyCode::Char('q') => self.quit = true,+ KeyCode::Char('?') => self.popup = Some(Popup::Help { scroll: 0 }),KeyCode::Char(digit @ '1'..='1') => {self.tab = TABS[digit as usize - '1' as usize];}@@ -243,12 +326,85 @@ impl App {KeyCode::BackTab | KeyCode::Left => {self.tab = TABS[(self.tab.index() + TABS.len() - 1) % TABS.len()];}- KeyCode::Char('r') | KeyCode::F(5) => return Some(Request::refresh()),+ KeyCode::Char('r') | KeyCode::F(5) => return Some(Request::refresh(false)),KeyCode::Esc => self.toast = None,_ => {}}None}++ fn popup_key(&mut self, key: KeyEvent) -> Option<Request> {+ let popup = self.popup.as_mut()?;+ match key.code {+ KeyCode::Esc | KeyCode::Enter | KeyCode::Char('q' | '?') => self.popup = None,+ // Drawing clamps the scroll to the text, so the last line here has no fixed value.+ code => {+ let scroll = popup.scroll_mut();+ if let Some(next) = step(code, usize::from(*scroll), usize::from(u16::MAX)) {+ *scroll = next as u16;+ }+ }+ }+ None+ }+}++/// This function moves a list position for the arrow, vim, page, and jump keys.+fn step(code: KeyCode, current: usize, last: usize) -> Option<usize> {+ Some(match code {+ KeyCode::Down | KeyCode::Char('j') => current.saturating_add(1).min(last),+ KeyCode::Up | KeyCode::Char('k') => current.saturating_sub(1),+ KeyCode::PageDown => current.saturating_add(10).min(last),+ KeyCode::PageUp => current.saturating_sub(10),+ KeyCode::Home | KeyCode::Char('g') => 0,+ KeyCode::End | KeyCode::Char('G') => last,+ _ => return None,+ })+}++fn count(value: u64) -> String {+ let digits = value.to_string();+ let mut text = String::with_capacity(digits.len() + digits.len() / 3);+ for (index, digit) in digits.chars().enumerate() {+ if index > 0 && (digits.len() - index).is_multiple_of(3) {+ text.push(',');+ }+ text.push(digit);+ }+ text+}++/// This function shows a total only when every call has a cost. Otherwise it shows the known+/// part as a lower bound, or "unknown", so a missing cost never reads as $0.+fn cost(theme: Theme, total: Option<f64>, known: f64) -> Span<'static> {+ match total {+ Some(total) => Span::raw(money(total)),+ None if known > 0.0 => Span::styled(format!("≥ {}", money(known)), theme.warn),+ None => Span::styled("unknown", theme.warn),+ }+}++/// This function shows the savings and their share of the baseline, or "hidden" when+/// `Estimate::savings` has no figure. With `baseline`, it also shows the baseline cost.+fn saved(theme: Theme, estimate: &Estimate, baseline: bool) -> Vec<Span<'static>> {+ let Some(savings) = estimate.savings() else {+ return vec![Span::styled("hidden", theme.warn)];+ };+ let style = if savings.saved() < 0.0 {+ theme.error+ } else {+ theme.ok+ };+ let mut spans = vec![Span::styled(money(savings.saved()), style.bold())];+ if let Some(percent) = savings.percent() {+ let text = if baseline {+ format!(" · {percent:.0}% of {}", money(savings.baseline))+ } else {+ format!(" · {percent:.0}%")+ };+ spans.push(Span::styled(text, theme.muted));+ }+ spans}fn server_state(theme: Theme, running: bool) -> [Span<'static>; 2] {@@ -270,6 +426,10 @@ fn draw(frame: &mut Frame, app: &mut App) {let Snapshot {data_state: _,metrics: _,+ today: _,+ estimates: _,+ activity: _,+ limited: _,errors: _,refresh_seconds: _,} = &app.data;@@ -290,6 +450,7 @@ fn draw(frame: &mut Frame, app: &mut App) {Tab::Overview => draw_overview(frame, app, body),}draw_status(frame, app, status);+ draw_popup(frame, app, body);}fn draw_too_small(frame: &mut Frame, theme: Theme, area: Rect) {@@ -367,6 +528,38 @@ fn draw_header(frame: &mut Frame, app: &App, area: Rect) {fn draw_overview(frame: &mut Frame, app: &App, area: Rect) {let theme = app.theme;let data = &app.data;+ let lines: Vec<Line> = data+ .errors+ .iter()+ .flat_map(|error| error.lines())+ .map(|line| Line::styled(line, theme.error))+ .collect();+ let errors = Paragraph::new(lines).wrap(Wrap { trim: false });+ let error_height = if data.errors.is_empty() {+ 0+ } else {+ // The panel needs rows for wrapped text as well as its top and bottom borders.+ errors+ .line_count(area.width.saturating_sub(2))+ .saturating_add(2)+ .min(usize::from(area.height / 2)) as u16+ };+ let [errors_area, rest] =+ Layout::vertical([Constraint::Length(error_height), Constraint::Fill(1)]).areas(area);+ if error_height > 0 {+ frame.render_widget(+ errors.block(block(theme, "Data errors").border_style(theme.error)),+ errors_area,+ );+ }+ let usage = data.data_state.usage.state == Availability::Available;+ let chart = if usage && rest.height >= 24 { 9 } else { 0 };+ let [cards, chart_area, _] = Layout::vertical([+ Constraint::Length(5),+ Constraint::Length(chart),+ Constraint::Fill(1),+ ])+ .areas(rest);let mut server = vec![Line::from(server_state(theme, data.metrics.running).to_vec()),Line::styled(data.metrics.server_url.as_str(), theme.muted),@@ -374,27 +567,98 @@ fn draw_overview(frame: &mut Frame, app: &App, area: Rect) {if let Some(reason) = data.data_state.health["reason"].as_str() {server.push(Line::styled(reason.to_string(), theme.muted));}- for error in &data.errors {- server.push(Line::styled(error.as_str(), theme.error));+ // Without usage data, the page shows only the connection so nothing reads as zero usage.+ if !usage {+ let [card, _] = Layout::horizontal([Constraint::Fill(1), Constraint::Fill(2)]).areas(cards);+ draw_card(frame, theme, "Server", server, card);+ return;}- if data.data_state.usage.state == Availability::Available {- server.push(Line::from(format!(- "Today: {} calls · {} tokens",- data.metrics.today.requests, data.metrics.today.tokens- )));- server.push(Line::from(format!(- "Past 7 days: {} calls · {} tokens",- data.metrics.week.requests, data.metrics.week.tokens- )));+ // The header already shows the server state, so narrow terminals give its card to usage.+ let periods = if cards.width >= 100 {+ let [server_card, rest] =+ Layout::horizontal([Constraint::Fill(1), Constraint::Fill(2)]).areas(cards);+ draw_card(frame, theme, "Server", server, server_card);+ rest+ } else {+ cards+ };+ let [today, week] = Layout::horizontal([Constraint::Fill(1); 2]).areas(periods);+ let today_title = format!("Today · {}", data.today.format("%b %-d"));+ for (period, title, card) in [+ (Period::Today, today_title.as_str(), today),+ (Period::Week, Period::Week.name(), week),+ ] {+ let lines = period_lines(app, period, card.width >= 36);+ draw_card(frame, theme, title, lines, card);}+ if chart > 0 {+ draw_activity(frame, app, chart_area);+ }+}++fn draw_card(frame: &mut Frame, theme: Theme, title: &str, lines: Vec<Line>, area: Rect) {frame.render_widget(- Paragraph::new(server)- .wrap(Wrap { trim: false })- .block(block(theme, "Server").padding(Padding::horizontal(1))),+ Paragraph::new(lines).block(block(theme, title).padding(Padding::horizontal(1))),area,);}+/// This function builds one period's calls, spending, and savings for an Overview card.+fn period_lines(app: &App, period: Period, baseline: bool) -> Vec<Line<'static>> {+ let theme = app.theme;+ let counts = match period {+ Period::Today => &app.data.metrics.today,+ _ => &app.data.metrics.week,+ };+ let mut lines = vec![Line::from(vec![+ Span::styled(count(counts.requests), Modifier::BOLD),+ Span::styled(" calls · ", theme.muted),+ Span::styled(tokens(counts.tokens), Modifier::BOLD),+ Span::styled(" tokens", theme.muted),+ ])];+ if let Some(estimate) = period.estimate(&app.data) {+ lines.push(Line::from(vec![+ Span::styled("Spent ", theme.muted),+ cost(theme, estimate.actual, estimate.known).bold(),+ ]));+ let mut savings = vec![Span::styled("Saved ", theme.muted)];+ savings.extend(saved(theme, &estimate, baseline));+ lines.push(Line::from(savings));+ }+ lines+}++fn draw_activity(frame: &mut Frame, app: &App, area: Rect) {+ let theme = app.theme;+ let data = &app.data.activity;+ let peak = data.iter().copied().max().unwrap_or_default();+ let mut outer = block(theme, "Calls per hour · past 24h")+ .title_top(Line::styled(format!(" peak {} ", count(peak)), theme.muted).right_aligned())+ .title_bottom(Line::styled(" 24h ago ", theme.muted))+ .title_bottom(Line::styled(" now ", theme.muted).right_aligned());+ if app.data.limited {+ outer = outer+ .title_bottom(Line::styled(" Recent history is limited. ", theme.muted).centered());+ }+ let inner = outer.inner(area);+ frame.render_widget(outer, area);+ let bars = data.len() as u16;+ let gap = u16::from(inner.width >= bars * 3);+ let width = ((inner.width + gap) / bars).saturating_sub(gap).max(1);+ let chart = inner.centered_horizontally(Constraint::Length(bars * (width + gap) - gap));+ let bars: Vec<Bar> = data+ .iter()+ .map(|&value| Bar::new(value).text_value(String::new()))+ .collect();+ frame.render_widget(+ BarChart::new(bars)+ .bar_width(width)+ .bar_gap(gap)+ .bar_style(theme.bar),+ chart,+ );+}+fn draw_status(frame: &mut Frame, app: &App, area: Rect) {let theme = app.theme;let left = if let Some(busy) = &app.busy {@@ -417,7 +681,7 @@ fn draw_status(frame: &mut Frame, app: &App, area: Rect) {Line::default()};let room = usize::from(area.width).saturating_sub(left.width() + 2);- let global = true;+ let global = app.popup.is_none();let hints = fit_keys(theme, app.keys(), global, room);let [left_area, right_area] =Layout::horizontal([Constraint::Length(left.width() as u16), Constraint::Fill(1)])@@ -426,8 +690,8 @@ fn draw_status(frame: &mut Frame, app: &App, area: Rect) {frame.render_widget(Paragraph::new(hints.right_aligned()), right_area);}-/// This function lists the page's keys, then the global keys, and stops before a hint would be-/// cut.+/// This function adds page and global key hints while they fit in the status bar.+/// It reserves room for the help key when global hints are shown.fn fit_keys(theme: Theme, keys: &[Key], global: bool, room: usize) -> Line<'static> {let hint = |key: &'static str, label: &str| {[@@ -435,10 +699,14 @@ fn fit_keys(theme: Theme, keys: &[Key], global: bool, room: usize) -> Line<'statSpan::styled(format!(" {label} "), theme.muted),]};+ const HELP_WIDTH: usize = "? help ".len();let mut spans = Vec::new();- let mut used = 0;+ let mut used = if global { HELP_WIDTH } else { 0 };let globals = if global { GLOBAL_KEYS } else { &[] };for (key, label, _) in keys.iter().chain(globals) {+ if *key == "?" {+ continue;+ }let width = key.chars().count() + label.chars().count() + 3;if used + width > room {break;@@ -446,9 +714,118 @@ fn fit_keys(theme: Theme, keys: &[Key], global: bool, room: usize) -> Line<'statused += width;spans.extend(hint(key, label));}+ if global && room >= HELP_WIDTH {+ spans.extend(hint("?", "help"));+ }Line::from(spans)}+fn draw_popup(frame: &mut Frame, app: &mut App, area: Rect) {+ let theme = app.theme;+ let Some(popup) = &app.popup else {+ return;+ };+ let footer = |pairs: &[(&'static str, &'static str)]| {+ let mut spans = Vec::new();+ for (key, label) in pairs {+ spans.push(Span::styled(format!(" {key} "), theme.key));+ spans.push(Span::raw(*label));+ }+ spans.push(Span::raw(" "));+ Line::from(spans)+ };+ let close = footer(&[("esc", "close")]);+ // The close key stays on the border while the popup text scrolls.+ let (title, lines, pinned, border, preferred, footer) = match popup {+ Popup::Help { .. } => {+ let width = 76;+ let text_width = width.min(area.width.saturating_sub(2)).saturating_sub(4);+ let lines = help_lines(theme, usize::from(text_width));+ ("Help", lines, Vec::new(), theme.key, width, close)+ }+ Popup::Message {+ title, text, error, ..+ } => (+ *title,+ text.lines()+ .map(|line| Line::from(line.to_string()))+ .collect(),+ Vec::new(),+ if *error { theme.error } else { theme.key },+ 76,+ close,+ ),+ };+ let width = preferred.min(area.width.saturating_sub(2));+ // The text area is inside the two border columns and the two padding columns.+ let text_width = width.saturating_sub(4);+ let paragraph = Paragraph::new(lines).wrap(Wrap { trim: false });+ let pinned = Paragraph::new(pinned).wrap(Wrap { trim: false });+ let rows = paragraph.line_count(text_width) as u16;+ let pinned_rows = pinned.line_count(text_width) as u16;+ let rect = area.centered(+ Constraint::Length(width),+ Constraint::Length((rows + pinned_rows + 2).min(area.height.saturating_sub(2))),+ );+ let outer = Block::bordered()+ .border_type(BorderType::Rounded)+ .border_style(border)+ .title(Span::styled(format!(" {title} "), border.bold()))+ .title_bottom(footer.right_aligned())+ .padding(Padding::horizontal(1));+ let [text_area, pinned_area] =+ Layout::vertical([Constraint::Fill(1), Constraint::Length(pinned_rows)])+ .areas(outer.inner(rect));+ // Scrolling stops at the last line, so scrolling back up responds at once.+ let last = rows.saturating_sub(text_area.height);+ let scroll = match app.popup.as_mut().map(Popup::scroll_mut) {+ Some(scroll) => {+ *scroll = (*scroll).min(last);+ *scroll+ }+ None => 0,+ };+ frame.render_widget(Clear, rect);+ frame.render_widget(outer, rect);+ frame.render_widget(paragraph.scroll((scroll, 0)), text_area);+ frame.render_widget(pinned, pinned_area);+}++/// The help window indents wrapped descriptions under their first line, so keys stay in one column.+fn help_lines(theme: Theme, width: usize) -> Vec<Line<'static>> {+ const KEY_WIDTH: usize = 8;+ let room = width.saturating_sub(KEY_WIDTH).max(20);+ let mut lines = Vec::new();+ for (section, keys) in [("Every page", GLOBAL_KEYS)] {+ if !lines.is_empty() {+ lines.push(Line::default());+ }+ lines.push(Line::styled(format!(" {section} "), theme.selected.bold()));+ for (key, _, about) in keys {+ let mut rows = Vec::new();+ let mut row = String::new();+ for word in about.split_whitespace() {+ if !row.is_empty() && row.chars().count() + 1 + word.chars().count() > room {+ rows.push(std::mem::take(&mut row));+ }+ if !row.is_empty() {+ row.push(' ');+ }+ row.push_str(word);+ }+ rows.push(row);+ for (index, row) in rows.into_iter().enumerate() {+ let key = if index == 0 { *key } else { "" };+ lines.push(Line::from(vec![+ Span::styled(format!("{key:<KEY_WIDTH$}"), theme.key),+ Span::raw(row),+ ]));+ }+ }+ }+ lines+}+struct PasteMode;impl Drop for PasteMode {fn drop(&mut self) {@@ -476,7 +853,7 @@ pub fn run(mut controller: Controller) -> Result<(), String> {});let result = ratatui::run(|terminal| -> Result<(), String> {// The initial refresh starts after terminal setup so a blocked read cannot delay drawing.- app.start(&jobs, Request::refresh())?;+ app.start(&jobs, Request::refresh(true))?;loop {app.poll_results(&results)?;if app.quit && app.busy.is_none() {@@ -505,7 +882,7 @@ pub fn run(mut controller: Controller) -> Result<(), String> {}}if !app.quit && app.refresh_due() {- app.start(&jobs, Request::refresh())?;+ app.start(&jobs, Request::refresh(true))?;}}});@@ -521,7 +898,7 @@ pub fn run(mut controller: Controller) -> Result<(), String> {#[cfg(test)]mod tests {- use super::{App, KeyCode, KeyEvent, KeyModifiers, Request, Theme, draw, mpsc};+ use super::{App, Done, KeyCode, KeyEvent, KeyModifiers, Popup, Request, Theme, draw, mpsc};use ratatui::{Terminal, backend::TestBackend};// Esc dismisses the status message while Overview keeps the refresh error.@@ -547,7 +924,7 @@ mod tests {fn worker_disconnect_returns_an_error_with_a_refresh_in_flight() {let mut app = App::new(Theme::new(false));let (jobs, _inbox) = mpsc::channel();- app.start(&jobs, Request::refresh()).expect("refresh");+ app.start(&jobs, Request::refresh(false)).expect("refresh");let (done, results) = mpsc::channel();assert!(app.poll_results(&results).is_ok());drop(done);@@ -556,4 +933,71 @@ mod tests {Err("The terminal operation worker stopped unexpectedly.".into()));}++ #[test]+ fn automatic_refresh_errors_leave_dismissed_popups_and_help_alone() {+ let mut app = App::new(Theme::new(false));+ let error = "Could not read settings.\nCheck the TOML file.";+ let (jobs, _inbox) = mpsc::channel();+ let (done, results) = mpsc::channel();+ app.start(&jobs, Request::refresh(false))+ .expect("manual refresh");+ done.send(Done::Finished {+ snapshot: Err(error.into()),+ })+ .expect("result");+ app.poll_results(&results).expect("manual result");+ assert!(matches!(app.popup, Some(Popup::Message { .. })));+ app.key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));+ for help in [false, true] {+ if help {+ app.key(KeyEvent::new(KeyCode::Char('?'), KeyModifiers::NONE));+ app.key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE));+ }+ app.start(&jobs, Request::refresh(true))+ .expect("automatic refresh");+ done.send(Done::Finished {+ snapshot: Err(error.into()),+ })+ .expect("result");+ app.poll_results(&results).expect("automatic result");+ assert!(if help {+ matches!(app.popup, Some(Popup::Help { scroll: 1 }))+ } else {+ app.popup.is_none()+ });+ assert_eq!(+ app.toast.as_ref().expect("error toast").text,+ "Could not read settings."+ );+ assert_eq!(app.data.errors, [error]);+ }+ }++ #[test]+ fn data_errors_split_newlines_and_reserve_wrapped_rows_at_minimum_size() {+ for error in [+ "Could not read model prices.\nSpecific cause".to_string(),+ format!(+ "Could not read model prices at {}: Specific cause",+ "long-directory/".repeat(8)+ ),+ ] {+ let mut app = App::new(Theme::new(false));+ app.data.errors = vec![error.clone()];+ let mut terminal = Terminal::new(TestBackend::new(60, 16)).expect("terminal");+ terminal.draw(|frame| draw(frame, &mut app)).expect("draw");+ let rows: Vec<String> = terminal+ .backend()+ .buffer()+ .content+ .chunks(60)+ .map(|row| row.iter().map(|cell| cell.symbol()).collect())+ .collect();+ assert!(+ rows[3..].iter().any(|row| row.contains("Specific cause")),+ "{error}: {rows:?}"+ );+ }+ }}