use crossterm::event::{KeyCode, KeyEvent};
use ratatui::Frame;
use ratatui::layout::Rect;
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::Paragraph;
use crate::app_view::AppView;
use crate::theme::Theme;
use crate::ui::{fmt_cost, humanize};
use super::chrome::{self, PopupFrame, hint, keys};
#[allow(clippy::too_many_lines)] pub fn render(f: &mut Frame, app: &AppView) {
let area = chrome::popup_area(app, f.area(), "usage", chrome::WIDE);
let Some(data) = &app.usage_data else {
return;
};
let theme = &app.theme;
let dim = Style::default().fg(theme.fg_dim);
let inner = chrome::render_popup(
f,
area,
&PopupFrame {
title: "Usage",
count: app.usage_range.label(),
hints: &[
hint(keys::SIDE, "period"),
hint(keys::MOVE, "recent"),
hint("r", "refresh"),
hint(keys::ESC, "close"),
],
tone: chrome::Tone::Normal,
focused: true,
},
app,
);
let active = dugix_core::db::UsageRange::CYCLE
.iter()
.position(|range| *range == app.usage_range)
.unwrap_or_default();
let inner = chrome::render_tabs(f, inner, &["24h", "7d", "30d", "All"], active, theme);
if data.totals.requests == 0 {
let message = match app.usage_range {
dugix_core::db::UsageRange::Day => {
"No usage in the last 24 hours. ←→ widens the period."
}
dugix_core::db::UsageRange::Week => {
"No usage in the last 7 days. ←→ widens the period."
}
dugix_core::db::UsageRange::Month => {
"No usage in the last 30 days. ←→ widens the period."
}
dugix_core::db::UsageRange::All => "No usage logged yet. Send a message first.",
};
chrome::render_empty(f, inner, message, theme);
return;
}
let mut next_y = inner.y;
let mut rows_left = inner.height;
let mut take = |n: u16| {
let n = n.min(rows_left);
let r = Rect::new(inner.x, next_y, inner.width, n);
next_y += n;
rows_left -= n;
r
};
let rows = [
take(4), take(1), take(1 + data.by_backend.len() as u16), take(1), take(1), take(1 + data.by_model.len() as u16), take(1), take(1), take(1), take(u16::MAX), ];
render_summary(f, app, rows[0]);
let width = rows[0].width;
f.render_widget(
Paragraph::new(crate::ui::style::section(
theme,
"by backend",
width as usize,
)),
rows[1],
);
let mut backend_lines: Vec<Line> = vec![Line::from(vec![
Span::styled(" ", dim),
Span::styled(format!("{:<14}", "backend"), dim),
Span::styled(format!("{:>6} {:>9} {:>8} ", "req", "prompt", "out"), dim),
Span::styled(format!("{:<6} ", "cached"), dim),
Span::styled(format!("{:<6} ", "reused"), dim),
Span::styled(format!("{:>9}", "cost"), dim),
])];
for b in &data.by_backend {
let cached = rate(b.rated_cache_read_tokens, b.rated_prompt_tokens);
let reused = rate(b.reused_tokens, b.reusable_tokens);
let name = chrome::truncate(&b.backend, 14);
let mut row = vec![
Span::styled("● ", Style::default().fg(backend_color(theme, &b.backend))),
Span::styled(
format!("{name:<14}"),
Style::default().fg(theme.fg).add_modifier(Modifier::BOLD),
),
];
row.extend(numeric_cells(
theme,
b.requests,
b.prompt_tokens,
b.completion_tokens,
(cached, reused),
b.cost,
));
backend_lines.push(Line::from(row));
}
f.render_widget(
Paragraph::new(chrome::fit_lines(backend_lines, width)),
rows[2],
);
f.render_widget(
Paragraph::new(crate::ui::style::section(
theme,
"most used models",
width as usize,
)),
rows[4],
);
let mut model_lines: Vec<Line> = vec![Line::from(vec![
Span::styled(" ", dim),
Span::styled(format!("{:<30}", "model"), dim),
Span::styled(format!("{:>6} {:>9} {:>8} ", "req", "prompt", "out"), dim),
Span::styled(format!("{:<6} ", "cached"), dim),
Span::styled(format!("{:<6} ", "reused"), dim),
Span::styled(format!("{:>9}", "cost"), dim),
])];
for (i, m) in data.by_model.iter().enumerate() {
let cached = rate(m.rated_cache_read_tokens, m.rated_prompt_tokens);
let reused = rate(m.reused_tokens, m.reusable_tokens);
let rank_style = if i == 0 {
Style::default()
.fg(theme.warning)
.add_modifier(Modifier::BOLD)
} else {
dim
};
let name = chrome::truncate(&m.model, 30);
let mut row = vec![
Span::styled(format!("{:>2} ", i + 1), rank_style),
Span::styled(format!("{name:<30}"), Style::default().fg(theme.fg)),
];
row.extend(numeric_cells(
theme,
m.requests,
m.prompt_tokens,
m.completion_tokens,
(cached, reused),
m.cost,
));
model_lines.push(Line::from(row));
}
f.render_widget(
Paragraph::new(chrome::fit_lines(model_lines, width)),
rows[5],
);
if !data.misses.is_empty() {
let parts: Vec<String> = data
.misses
.iter()
.map(|(verdict, count)| format!("{} {count}", verdict.replace('_', " ")))
.collect();
f.render_widget(
Paragraph::new(chrome::fit_lines(
vec![Line::from(Span::styled(
format!(" cache requests · {}", parts.join(" · ")),
dim,
))],
width,
)),
rows[6],
);
}
f.render_widget(
Paragraph::new(crate::ui::style::section(
theme,
"recent requests",
width as usize,
)),
rows[8],
);
let recent_area = rows[9];
let visible = recent_area.height as usize;
let top = app
.usage_scroll
.min(data.recent.len().saturating_sub(visible));
let mut recent_lines: Vec<Line> = Vec::with_capacity(visible);
for r in data.recent.iter().skip(top).take(visible) {
let cached = r
.prompt_convention
.ratio_is_meaningful()
.then(|| rate(r.cache_read_tokens, r.prompt_tokens))
.flatten();
let time = r
.created_at
.parse::<chrono::DateTime<chrono::Utc>>()
.map_or_else(|_| "--:--".to_string(), |t| t.format("%H:%M").to_string());
let model = chrome::truncate(&r.model, 24);
let tokens = format!(
"{}→{}",
humanize(r.prompt_tokens),
humanize(r.completion_tokens)
);
recent_lines.push(Line::from(vec![
Span::styled(format!("{time} "), dim),
Span::styled("● ", Style::default().fg(backend_color(theme, &r.backend))),
Span::styled(format!("{model:<24}"), Style::default().fg(theme.fg)),
Span::styled(format!("{tokens:>13} "), dim),
Span::styled(
"█".repeat(cached.map_or(0, |c| (c * 8.0).round() as usize)),
Style::default().fg(cache_color(theme, cached)),
),
Span::styled(
"░".repeat(8 - cached.map_or(0, |c| (c * 8.0).round() as usize)),
Style::default().fg(theme.border_dim),
),
Span::styled(
format!(" {:>5}", fmt_rate(cached)),
Style::default()
.fg(cache_color(theme, cached))
.add_modifier(Modifier::BOLD),
),
Span::styled(
format!(" {:>9}", fmt_cost(r.cost)),
cost_style(theme, r.cost.unwrap_or(0.0)),
),
]));
}
f.render_widget(
Paragraph::new(chrome::fit_lines(recent_lines, recent_area.width)),
recent_area,
);
}
fn cache_legend(theme: &Theme) -> Line<'static> {
Line::from(Span::styled(
" — = provider reported no cache accounting (or row predates normalization); excluded from rates",
Style::default().fg(theme.fg_dim),
))
}
fn render_summary(f: &mut Frame, app: &AppView, area: Rect) {
let theme = &app.theme;
let Some(data) = &app.usage_data else { return };
let t = &data.totals;
let dim = Style::default().fg(theme.fg_dim);
let accent_bold = Style::default()
.fg(theme.accent)
.add_modifier(Modifier::BOLD);
let headline = Line::from(vec![
Span::styled(format!("{} requests", t.requests), accent_bold),
Span::styled(
format!(
" · {} prompt · {} output · {} cache writes",
humanize(t.prompt_tokens),
humanize(t.completion_tokens),
humanize(t.cache_creation_tokens),
),
dim,
),
Span::styled(
format!(" · {}", fmt_cost_agg(t.cost)),
cost_style(theme, t.cost),
),
]);
let cached = rate(t.rated_cache_read_tokens, t.rated_prompt_tokens);
let bar_line = if let Some(cached_rate) = cached {
let mut spans: Vec<Span> = vec![Span::raw(" ")];
spans.extend(cache_bar(cached_rate, 24, theme));
spans.push(Span::styled(
format!(" {:.0}% of prompt served from cache", cached_rate * 100.0),
Style::default()
.fg(cache_color(theme, cached))
.add_modifier(Modifier::BOLD),
));
let unrated = t.prompt_tokens.saturating_sub(t.rated_prompt_tokens);
if unrated > 0 {
spans.push(Span::styled(
format!(
" (excludes {} unaccounted prompt tokens)",
humanize(unrated)
),
dim,
));
}
Line::from(spans)
} else {
Line::from(Span::styled(" no cache data reported", dim))
};
let mut lines = vec![headline, Line::from(""), bar_line];
if t.prompt_tokens > t.rated_prompt_tokens {
lines.push(cache_legend(theme));
}
f.render_widget(Paragraph::new(chrome::fit_lines(lines, area.width)), area);
}
fn numeric_cells(
theme: &Theme,
requests: u64,
prompt: u64,
completion: u64,
(cached, reused): (Option<f64>, Option<f64>),
cost: f64,
) -> Vec<Span<'static>> {
let dim = Style::default().fg(theme.fg_dim);
vec![
Span::styled(
format!(
"{:>6} {:>9} {:>8} ",
requests,
humanize(prompt),
humanize(completion)
),
dim,
),
Span::styled(
format!("{:>7} ", fmt_rate(cached)),
Style::default().fg(cache_color(theme, cached)),
),
Span::styled(
format!("{:>7} ", fmt_rate(reused)),
Style::default().fg(cache_color(theme, reused)),
),
Span::styled(
format!("{:>9}", fmt_cost_agg(cost)),
cost_style(theme, cost),
),
]
}
fn rate(rated_cache_read: u64, rated_prompt: u64) -> Option<f64> {
(rated_prompt > 0).then(|| rated_cache_read as f64 / rated_prompt as f64)
}
fn fmt_rate(rate: Option<f64>) -> String {
rate.map_or_else(|| "—".to_string(), |r| format!("{:.0}%", r * 100.0))
}
fn cache_color(theme: &Theme, rate: Option<f64>) -> Color {
let Some(rate) = rate else {
return theme.fg_dim;
};
if rate >= 0.7 {
theme.success
} else if rate >= 0.4 {
theme.warning
} else {
theme.error
}
}
fn backend_color(theme: &Theme, backend: &str) -> Color {
match backend {
"OpenRouter" => theme.accent,
"OpenAI" => theme.success,
"Codex" => theme.accent2,
_ => theme.warning,
}
}
fn cache_bar(rate: f64, width: usize, theme: &Theme) -> Vec<Span<'static>> {
let filled = (rate * width as f64).round() as usize;
vec![
Span::styled(
"█".repeat(filled),
Style::default().fg(cache_color(theme, Some(rate))),
),
Span::styled(
"░".repeat(width - filled),
Style::default().fg(theme.border_dim),
),
]
}
fn cost_style(theme: &Theme, cost: f64) -> Style {
if cost > 0.0 {
Style::default()
.fg(theme.success)
.add_modifier(Modifier::BOLD)
} else {
Style::default().fg(theme.fg_dim)
}
}
fn fmt_cost_agg(cost: f64) -> String {
if cost > 0.0 {
fmt_cost(Some(cost))
} else {
"—".to_string()
}
}
pub fn handle_key(app: &mut AppView, key: KeyEvent) {
use dugix_core::app::Popup;
match key.code {
KeyCode::Esc => app.popup = Popup::None,
KeyCode::Up | KeyCode::Char('k') => app.scroll_usage(-1),
KeyCode::Down | KeyCode::Char('j') => app.scroll_usage(1),
KeyCode::PageUp => app.scroll_usage(-10),
KeyCode::PageDown => app.scroll_usage(10),
KeyCode::Home => app.scroll_usage(i32::MIN / 2),
KeyCode::End => app.scroll_usage(i32::MAX / 2),
KeyCode::Left | KeyCode::Char('h') => app.cycle_usage_range(-1),
KeyCode::Right | KeyCode::Char('l' | 't') => app.cycle_usage_range(1),
KeyCode::Char('r') if !super::is_chord(key) => {
app.refresh_usage();
}
_ => {}
}
}