use crate::display::common::table::{
create_controls, create_provider_row, create_ratatui_table, create_summary, main_layout,
render_scrollable_table, render_too_small, styled_row,
};
use crate::display::common::tui::{
InputAction, RefreshState, ScrollState, UpdateTracker, handle_input, restore_terminal,
setup_terminal,
};
use crate::display::usage::averages::{
UsageProviderTotals, UsageRow, UsageTotals, build_provider_total_rows, build_usage_summary,
};
use crate::models::{
ClaudeQuotaSnapshot, CodexQuotaSnapshot, PerProviderUsage, ProviderActiveDays, QuotaSource,
QuotaWindow, UsageResult,
};
use crate::pricing::{ModelPricingMap, fetch_model_pricing};
use crate::quota::{
CLAUDE_LOGIN_HINT, CODEX_LOGIN_HINT, ClaudeState, CodexState, load_claude_cache,
load_codex_cache, save_claude_cache, save_codex_cache, spawn_quota_worker,
};
use crate::utils::{
format_compact, format_cost, format_duration_until, get_claude_credentials_path, resolve_paths,
};
use ratatui::{
Frame, Terminal,
backend::CrosstermBackend,
layout::{Constraint, Direction, Layout as RatatuiLayout, Rect},
style::{Color as RatatuiColor, Modifier, Style, Stylize},
text::{Line, Span},
widgets::{Block, Borders, Paragraph, Row as RatatuiRow},
};
use std::collections::HashMap;
use std::io;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use sysinfo::{Pid, System};
const QUOTA_PANEL_MIN_HEIGHT: u16 = 8;
const CLAUDE_COLOR: RatatuiColor = RatatuiColor::Rgb(190, 116, 87);
const CODEX_COLOR: RatatuiColor = RatatuiColor::Rgb(118, 127, 198);
#[derive(Clone, Copy, Default)]
struct QuotaPresence {
claude: bool,
codex: bool,
}
impl QuotaPresence {
fn detect() -> Self {
let claude = get_claude_credentials_path()
.map(|p| p.exists())
.unwrap_or(false);
let codex = resolve_paths()
.map(|p| p.codex_dir.join("auth.json").exists() || p.codex_session_dir.exists())
.unwrap_or(false);
Self { claude, codex }
}
fn count(&self) -> usize {
self.claude as usize + self.codex as usize
}
}
struct QuotaView<'a> {
claude: &'a ClaudeQuotaSnapshot,
codex: &'a CodexQuotaSnapshot,
present: QuotaPresence,
}
const USAGE_REFRESH_SECS: u64 = 10;
const CLAUDE_REFRESH_SECS: u64 = 60;
const PRICING_REFRESH_SECS: u64 = 300;
const MAX_TRACKED_ROWS: usize = 100;
const USAGE_MIN_W: u16 = 74;
const USAGE_MIN_H: u16 = 14;
const USAGE_PANELS_MIN_H: u16 = 22;
pub fn display_usage_interactive(time_range: crate::cli::TimeRange) -> anyhow::Result<()> {
let mut terminal = setup_terminal()?;
let mut refresh_state = RefreshState::new(USAGE_REFRESH_SECS);
let present = QuotaPresence::detect();
let quota_shutdown = Arc::new(AtomicBool::new(false));
let claude_shared = Arc::new(Mutex::new(
present
.claude
.then(load_claude_cache)
.flatten()
.unwrap_or_default(),
));
let codex_shared = Arc::new(Mutex::new(
present
.codex
.then(load_codex_cache)
.flatten()
.unwrap_or_default(),
));
if present.claude || present.codex {
match crate::quota::http::build_client() {
Ok(client) => {
if present.claude {
let (c, sh, shared) = (
client.clone(),
Arc::clone("a_shutdown),
Arc::clone(&claude_shared),
);
let mut state = ClaudeState::default();
spawn_quota_worker(
"claude",
shared,
sh,
CLAUDE_REFRESH_SECS,
move || state.resolve(&c),
|s| {
let _ = save_claude_cache(s);
},
);
}
if present.codex {
let (c, sh, shared) = (
client.clone(),
Arc::clone("a_shutdown),
Arc::clone(&codex_shared),
);
let mut state = CodexState::default();
spawn_quota_worker(
"codex",
shared,
sh,
crate::quota::provider::REFRESH_SECS,
move || state.resolve(&c),
|s| {
let _ = save_codex_cache(s);
},
);
}
}
Err(e) => log::warn!("quota workers disabled: failed to build HTTP client: {e}"),
}
}
let pid =
sysinfo::get_current_pid().expect("Failed to get current process ID for memory monitoring");
let mut sys = System::new();
sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true);
let mut usage_data = UsageResult::default();
let mut per_provider_usage = PerProviderUsage::default();
let mut provider_days = ProviderActiveDays::default();
let mut opencode_costs: crate::constants::FastHashMap<String, f64> = Default::default();
let mut has_usage_data = false;
let mut pricing_map = match fetch_model_pricing() {
Ok(map) => map,
Err(e) => {
log::warn!("Failed to fetch initial pricing: {}", e);
ModelPricingMap::new(HashMap::new())
}
};
let mut last_pricing_refresh = Instant::now();
let mut update_tracker = UpdateTracker::new(MAX_TRACKED_ROWS, 1000);
let mut scroll = ScrollState::new();
let mut rows_data: Vec<UsageRow> = Vec::new();
let mut totals = UsageTotals::default();
let mut provider_totals = UsageProviderTotals::default();
let mut claude_snapshot = ClaudeQuotaSnapshot::default();
let mut codex_snapshot = CodexQuotaSnapshot::default();
loop {
if refresh_state.should_refresh() {
refresh_state.mark_refreshed();
sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true);
match crate::usage::get_usage_from_directories(time_range) {
Ok(data) => {
usage_data = data.models;
per_provider_usage = data.per_provider;
provider_days = data.provider_days;
opencode_costs = data.opencode_costs;
has_usage_data = true;
}
Err(e) => {
log::warn!("Failed to get usage data: {}", e);
if !has_usage_data {
usage_data.clear();
per_provider_usage = PerProviderUsage::default();
opencode_costs = Default::default();
}
}
}
if last_pricing_refresh.elapsed() >= Duration::from_secs(PRICING_REFRESH_SECS)
|| pricing_map.is_empty()
{
match fetch_model_pricing() {
Ok(map) => {
pricing_map = map;
last_pricing_refresh = Instant::now();
}
Err(e) => log::warn!("Failed to refresh pricing: {}", e),
}
}
let summary = build_usage_summary(
&usage_data,
&per_provider_usage,
&provider_days,
&pricing_map,
&opencode_costs,
);
let prev_model = scroll
.table
.selected()
.and_then(|i| rows_data.get(i))
.map(|row| row.model.clone());
rows_data = summary.rows;
rows_data.retain(|row| row.total != 0 || row.cost != 0.0);
totals = summary.totals;
provider_totals = summary.provider_totals;
let model_names: Vec<String> = rows_data.iter().map(|row| row.model.clone()).collect();
scroll.sync(prev_model.as_deref(), &model_names);
claude_snapshot = claude_shared.lock().map(|g| g.clone()).unwrap_or_default();
codex_snapshot = codex_shared.lock().map(|g| g.clone()).unwrap_or_default();
usage_data.clear();
per_provider_usage = PerProviderUsage::default();
let current_row_keys: Vec<String> =
rows_data.iter().map(|row| row.model.clone()).collect();
update_tracker.cleanup(current_row_keys);
for row in &rows_data {
let row_key = row.model.clone();
let current_data = (
row.input_tokens,
row.output_with_reasoning(),
row.cache_read,
row.cache_creation,
);
update_tracker.track_update(row_key, ¤t_data);
}
render_usage_frame(
&mut terminal,
&rows_data,
&totals,
&provider_totals,
&update_tracker,
&sys,
pid,
&QuotaView {
claude: &claude_snapshot,
codex: &codex_snapshot,
present,
},
&mut scroll,
)?;
crate::utils::release_freed_heap();
}
let action = handle_input()?;
match action {
InputAction::Quit => {
quota_shutdown.store(true, Ordering::Relaxed);
break;
}
InputAction::Refresh => refresh_state.force(),
InputAction::Navigate(nav) => {
scroll.apply(nav, rows_data.len());
render_usage_frame(
&mut terminal,
&rows_data,
&totals,
&provider_totals,
&update_tracker,
&sys,
pid,
&QuotaView {
claude: &claude_snapshot,
codex: &codex_snapshot,
present,
},
&mut scroll,
)?;
}
InputAction::Resize => render_usage_frame(
&mut terminal,
&rows_data,
&totals,
&provider_totals,
&update_tracker,
&sys,
pid,
&QuotaView {
claude: &claude_snapshot,
codex: &codex_snapshot,
present,
},
&mut scroll,
)?,
InputAction::Continue => {}
}
}
restore_terminal(&mut terminal)?;
Ok(())
}
#[allow(clippy::too_many_arguments)]
fn render_usage_frame(
terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
rows_data: &[UsageRow],
totals: &UsageTotals,
provider_totals: &UsageProviderTotals,
update_tracker: &UpdateTracker,
sys: &System,
pid: Pid,
quota: &QuotaView,
scroll: &mut ScrollState,
) -> anyhow::Result<()> {
let provider_rows = build_provider_total_rows(provider_totals);
terminal.draw(|f| {
let area = f.area();
if area.width < USAGE_MIN_W || area.height < USAGE_MIN_H {
render_too_small(f, USAGE_MIN_W, USAGE_MIN_H);
return;
}
let totals_height = (provider_rows.len() as u16)
.saturating_add(4)
.max(QUOTA_PANEL_MIN_HEIGHT);
let panels_height = (area.height >= USAGE_PANELS_MIN_H).then_some(totals_height);
let chunks = main_layout(area, panels_height);
let header = vec![
"Model",
"Input",
"Output",
"Cache Read",
"Cache Write",
"Total",
"Cost (USD)",
];
let rows: Vec<RatatuiRow> = rows_data
.iter()
.map(|row| {
let style = if update_tracker.is_recently_updated(&row.model) {
Style::default().bg(RatatuiColor::Rgb(60, 80, 60)).bold()
} else {
Style::default()
};
styled_row(
vec![
row.display_model.clone(),
format_compact(row.input_tokens),
format_compact(row.output_with_reasoning()),
format_compact(row.cache_read),
format_compact(row.cache_creation),
format_compact(row.total),
format_cost(row.cost),
],
style,
1,
)
})
.collect();
let widths = [
Constraint::Min(16),
Constraint::Length(9),
Constraint::Length(9),
Constraint::Length(11),
Constraint::Length(11),
Constraint::Length(9),
Constraint::Length(12),
];
let row_count = rows.len();
render_scrollable_table(
f,
chunks.table,
header,
rows,
&widths,
RatatuiColor::Green,
row_count,
scroll,
);
if let Some(panel_area) = chunks.panels {
let mut totals_rows: Vec<RatatuiRow> = provider_rows
.iter()
.filter(|row| row.label != "All Providers")
.map(|row| {
create_provider_row(
vec![
row.label.to_string(),
format_compact(row.stats.total_tokens),
format_cost(row.stats.total_cost),
format_compact(row.stats.days_count as i64),
],
row.tui_color,
row.emphasize,
)
})
.collect();
if totals_rows.is_empty() {
totals_rows.push(
RatatuiRow::new(vec![
"No provider data yet".to_string(),
"-".to_string(),
"-".to_string(),
"-".to_string(),
])
.style(Style::default().fg(RatatuiColor::DarkGray)),
);
}
let totals_header = vec!["Provider", "Tokens", "Cost", "Active Days"];
let totals_widths = [
Constraint::Min(20),
Constraint::Length(16),
Constraint::Length(14),
Constraint::Length(14),
];
let totals_table = create_ratatui_table(
totals_rows,
totals_header,
&totals_widths,
RatatuiColor::Magenta,
);
let now = chrono::Local::now().timestamp();
let band = RatatuiLayout::default()
.direction(Direction::Horizontal)
.constraints(band_constraints(quota.present.count()))
.split(panel_area);
f.render_widget(totals_table, band[0]);
let mut idx = 1;
if quota.present.claude {
render_claude_quota(f, band[idx], quota.claude, now);
idx += 1;
}
if quota.present.codex {
render_codex_quota(f, band[idx], quota.codex, now);
}
}
let total_cost_str = format_cost(totals.cost);
let total_tokens_str = format_compact(totals.total);
let entries_str = format!("{}", rows_data.len());
let summary_items = vec![
("Total Cost:", total_cost_str.as_str(), RatatuiColor::Yellow),
(
"Total Tokens:",
total_tokens_str.as_str(),
RatatuiColor::Cyan,
),
("Models:", entries_str.as_str(), RatatuiColor::Blue),
];
let summary = create_summary(summary_items, sys, pid);
f.render_widget(summary, chunks.summary);
f.render_widget(create_controls(), chunks.controls);
})?;
Ok(())
}
fn gauge_color(pct: f64) -> RatatuiColor {
if pct >= 90.0 {
RatatuiColor::Red
} else if pct >= 70.0 {
RatatuiColor::Yellow
} else {
RatatuiColor::Green
}
}
fn mini_bar(pct: f64) -> String {
let filled = ((pct / 20.0).ceil() as i64).clamp(0, 5) as usize;
(0..5).map(|i| if i < filled { '▰' } else { '▱' }).collect()
}
fn quota_gauge_line(label: &str, w: &QuotaWindow, now: i64) -> Line<'static> {
let pct = w.used_percent;
let color = gauge_color(pct);
let mut spans = vec![
Span::styled(
format!("{label:<6} "),
Style::default().fg(RatatuiColor::Gray),
),
Span::styled(mini_bar(pct), Style::default().fg(color)),
Span::styled(format!(" {pct:>3.0}%"), Style::default().fg(color)),
];
if let Some(reset) = w.resets_at_unix {
spans.push(Span::styled(
format!(" ↻ {}", format_duration_until(reset, now)),
Style::default().fg(RatatuiColor::DarkGray),
));
}
Line::from(spans)
}
fn staleness_line(fetched_at: i64, now: i64) -> Line<'static> {
if fetched_at <= 0 {
return dim_line("updated: never");
}
let age = (now - fetched_at).max(0);
let color = if age > 6 * 3600 {
RatatuiColor::Red
} else if age > 3600 {
RatatuiColor::Yellow
} else {
RatatuiColor::DarkGray
};
let ago = format_duration_until(now, fetched_at);
let text = if ago == "now" {
"updated just now".to_string()
} else {
format!("updated {ago} ago")
};
Line::from(Span::styled(text, Style::default().fg(color)))
}
fn dim_line(text: &str) -> Line<'static> {
Line::from(Span::styled(
text.to_string(),
Style::default().fg(RatatuiColor::DarkGray),
))
}
fn login_hint_line(hint: &str) -> Line<'static> {
Line::from(Span::styled(
hint.to_string(),
Style::default()
.fg(RatatuiColor::Red)
.add_modifier(Modifier::BOLD),
))
}
fn band_constraints(top_n: usize) -> Vec<Constraint> {
match top_n {
0 => vec![Constraint::Percentage(100)],
1 => vec![Constraint::Percentage(58), Constraint::Percentage(42)],
_ => vec![
Constraint::Percentage(46),
Constraint::Percentage(27),
Constraint::Percentage(27),
],
}
}
fn quota_block(title: &str, border: RatatuiColor, limit_reached: bool) -> Block<'static> {
let mut block = Block::default()
.borders(Borders::ALL)
.title(Line::from(title.to_string()))
.border_style(Style::default().fg(border));
if limit_reached {
block = block.title(
Line::from(Span::styled(
"LIMIT ",
Style::default()
.fg(RatatuiColor::Red)
.add_modifier(Modifier::BOLD),
))
.right_aligned(),
);
}
block
}
fn render_claude_quota(f: &mut Frame, area: Rect, claude: &ClaudeQuotaSnapshot, now: i64) {
let block = quota_block(" Claude ", CLAUDE_COLOR, claude.limit_reached);
let mut lines: Vec<Line> = Vec::new();
if let Some(plan) = &claude.plan_type {
lines.push(plan_line(plan));
}
let mut has_data = false;
if let Some(w) = &claude.five_hour {
lines.push(quota_gauge_line("5h", w, now));
has_data = true;
}
if let Some(w) = &claude.seven_day {
lines.push(quota_gauge_line("7d", w, now));
has_data = true;
}
if let (Some(w), Some(label)) = (&claude.scoped_weekly, &claude.scoped_label) {
lines.push(quota_gauge_line(label, w, now));
has_data = true;
}
if has_data {
lines.push(claude_balance_line(claude));
lines.push(staleness_line(claude.fetched_at, now));
}
if claude.needs_login {
lines.push(login_hint_line(CLAUDE_LOGIN_HINT));
} else if !has_data {
lines.push(dim_line("no rate-limit data"));
}
f.render_widget(Paragraph::new(lines).block(block), area);
}
fn render_codex_quota(f: &mut Frame, area: Rect, codex: &CodexQuotaSnapshot, now: i64) {
let title = match codex.source {
QuotaSource::Api => " Codex ",
QuotaSource::SessionFallback => " Codex (session) ",
QuotaSource::None => " Codex ",
};
let block = quota_block(title, CODEX_COLOR, codex.limit_reached == Some(true));
let lines: Vec<Line> = if codex.source == QuotaSource::None {
let mut v = vec![dim_line("no Codex quota")];
if codex.needs_login {
v.push(login_hint_line(CODEX_LOGIN_HINT));
} else {
v.push(dim_line("(no auth.json / sessions)"));
}
v
} else {
let mut v = vec![plan_line(codex.plan_type.as_deref().unwrap_or("?"))];
if let Some(w) = &codex.primary {
v.push(quota_gauge_line("5h", w, now));
}
if let Some(w) = &codex.secondary {
v.push(quota_gauge_line("7d", w, now));
}
if codex.needs_login {
v.push(login_hint_line(CODEX_LOGIN_HINT));
} else {
v.push(credits_line(codex));
if let Some(extra) = codex_extras_line(codex) {
v.push(extra);
}
}
v.push(staleness_line(codex.fetched_at, now));
v
};
f.render_widget(Paragraph::new(lines).block(block), area);
}
fn plan_line(plan: &str) -> Line<'static> {
Line::from(Span::styled(
format!("Plan: {plan}"),
Style::default().fg(RatatuiColor::Gray),
))
}
fn credits_line(codex: &CodexQuotaSnapshot) -> Line<'static> {
let mut s = String::from("Credits: ");
if codex.unlimited == Some(true) {
s.push_str("unlimited");
} else if let Some(bal) = &codex.credits_balance {
s.push_str(bal);
} else {
s.push('-');
}
if let Some(n) = codex.reset_credits_available
&& n > 0
{
s.push_str(&format!(" +{n} reset"));
}
Line::from(Span::styled(s, Style::default().fg(RatatuiColor::Gray)))
}
fn codex_extras_line(codex: &CodexQuotaSnapshot) -> Option<Line<'static>> {
let mut parts: Vec<String> = Vec::new();
if let Some((low, high)) = codex.approx_messages {
if low == high {
parts.push(format!("~{low} msgs"));
} else {
parts.push(format!("~{low}-{high} msgs"));
}
}
if let Some(cap) = codex.spend_limit {
let cap_str = if cap.fract() == 0.0 {
format!("${cap:.0}")
} else {
format!("${cap:.2}")
};
parts.push(format!("cap {cap_str}"));
}
if parts.is_empty() {
return None;
}
Some(Line::from(Span::styled(
parts.join(" · "),
Style::default().fg(RatatuiColor::DarkGray),
)))
}
fn claude_balance_line(claude: &ClaudeQuotaSnapshot) -> Line<'static> {
let mut s = String::from("Balance: ");
match &claude.balance {
Some(b) => s.push_str(b),
None => s.push('-'),
}
if let Some(used) = &claude.spend_used {
s.push_str(&format!(" {used} used"));
}
Line::from(Span::styled(s, Style::default().fg(RatatuiColor::Gray)))
}