use crate::config::ProvidersConfig;
use crate::display::common::ProviderTotal;
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::{
ProviderStats, UsageProviderTotals, UsageRow, UsageTotals, build_provider_total_rows,
build_usage_summary, merge_rows_by_base_model,
};
use crate::models::{
ClaudeQuotaSnapshot, CodexQuotaSnapshot, CopilotQuotaSnapshot, CursorQuotaSnapshot,
PerProviderUsage, ProviderActiveDays, QuotaSource, QuotaWindow, UsageResult,
};
use crate::pricing::{ModelPricingMap, fetch_model_pricing};
use crate::quota::{
CLAUDE_LOGIN_HINT, CODEX_LOGIN_HINT, COPILOT_LOGIN_HINT, CURSOR_LOGIN_HINT, ClaudeState,
CodexState, CopilotState, CursorState, load_claude_cache, load_codex_cache, load_copilot_cache,
load_cursor_cache, save_claude_cache, save_codex_cache, save_copilot_cache, save_cursor_cache,
spawn_quota_worker,
};
use crate::utils::{
format_compact, format_cost, format_cost_compact, format_duration_until,
get_claude_credentials_path, get_copilot_config_path, get_cursor_auth_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);
const COPILOT_COLOR: RatatuiColor = RatatuiColor::Rgb(46, 160, 67);
const CURSOR_COLOR: RatatuiColor = RatatuiColor::Rgb(64, 180, 180);
const PANEL_MIN_W: u16 = 28;
const BAND_TABLE_MIN_W: u16 = 38;
const PANELS_2ROW_MIN_H: u16 = 26;
#[derive(Clone, Copy, Default)]
struct QuotaPresence {
claude: bool,
codex: bool,
copilot: bool,
cursor: 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);
let copilot = get_copilot_config_path()
.map(|p| p.exists())
.unwrap_or(false);
let cursor = get_cursor_auth_path().map(|p| p.exists()).unwrap_or(false);
Self {
claude,
codex,
copilot,
cursor,
}
}
fn count(&self) -> usize {
self.claude as usize + self.codex as usize + self.copilot as usize + self.cursor as usize
}
}
struct QuotaView<'a> {
claude: &'a ClaudeQuotaSnapshot,
codex: &'a CodexQuotaSnapshot,
copilot: &'a CopilotQuotaSnapshot,
cursor: &'a CursorQuotaSnapshot,
present: QuotaPresence,
band_enabled: bool,
}
const CLAUDE_REFRESH_SECS: u64 = 60;
const COPILOT_REFRESH_SECS: u64 = 60;
const CURSOR_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,
merge_providers: bool,
quota_panels: Vec<String>,
providers: ProvidersConfig,
refresh_secs: u64,
) -> anyhow::Result<()> {
let mut terminal = setup_terminal()?;
let mut refresh_state = RefreshState::new(refresh_secs.max(1));
let panel_on = |name: &str| crate::config::quota_panel_selected("a_panels, name);
let band_enabled = !quota_panels.is_empty();
let mut present = if band_enabled {
QuotaPresence::detect()
} else {
QuotaPresence::default()
};
present.claude &= providers.claude && panel_on("claude");
present.codex &= providers.codex && panel_on("codex");
present.copilot &= providers.copilot && panel_on("copilot");
present.cursor &= providers.cursor && panel_on("cursor");
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(),
));
let copilot_shared = Arc::new(Mutex::new(
present
.copilot
.then(load_copilot_cache)
.flatten()
.unwrap_or_default(),
));
let cursor_shared = Arc::new(Mutex::new(
present
.cursor
.then(load_cursor_cache)
.flatten()
.unwrap_or_default(),
));
if present.claude || present.codex || present.copilot || present.cursor {
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);
},
);
}
if present.copilot {
let (c, sh, shared) = (
client.clone(),
Arc::clone("a_shutdown),
Arc::clone(&copilot_shared),
);
let mut state = CopilotState;
spawn_quota_worker(
"copilot",
shared,
sh,
COPILOT_REFRESH_SECS,
move || state.resolve(&c),
|s| {
let _ = save_copilot_cache(s);
},
);
}
if present.cursor {
let (c, sh, shared) = (
client.clone(),
Arc::clone("a_shutdown),
Arc::clone(&cursor_shared),
);
let mut state = CursorState;
spawn_quota_worker(
"cursor",
shared,
sh,
CURSOR_REFRESH_SECS,
move || state.resolve(&c),
|s| {
let _ = save_cursor_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 stored_costs = crate::usage::StoredCosts::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 merge_enabled = merge_providers;
let mut display_rows: Vec<UsageRow> = Vec::new();
let mut claude_snapshot = ClaudeQuotaSnapshot::default();
let mut codex_snapshot = CodexQuotaSnapshot::default();
let mut copilot_snapshot = CopilotQuotaSnapshot::default();
let mut cursor_snapshot = CursorQuotaSnapshot::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_with(time_range, providers) {
Ok(data) => {
usage_data = data.models;
per_provider_usage = data.per_provider;
provider_days = data.provider_days;
stored_costs = data.stored_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();
stored_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,
&stored_costs,
);
let prev_model = {
let view = current_view(merge_enabled, &rows_data, &display_rows);
scroll
.table
.selected()
.and_then(|i| view.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;
if merge_enabled {
display_rows = merge_rows_by_base_model(&rows_data);
}
let view = current_view(merge_enabled, &rows_data, &display_rows);
let model_names: Vec<String> = view.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();
copilot_snapshot = copilot_shared.lock().map(|g| g.clone()).unwrap_or_default();
cursor_snapshot = cursor_shared.lock().map(|g| g.clone()).unwrap_or_default();
usage_data.clear();
per_provider_usage = PerProviderUsage::default();
let current_row_keys: Vec<String> = view.iter().map(|row| row.model.clone()).collect();
update_tracker.cleanup(current_row_keys);
for row in view {
update_tracker.track_update(row.model.clone(), &row_fingerprint(row));
}
render_usage_frame(
&mut terminal,
view,
&totals,
&provider_totals,
&update_tracker,
&sys,
pid,
&QuotaView {
claude: &claude_snapshot,
codex: &codex_snapshot,
copilot: &copilot_snapshot,
cursor: &cursor_snapshot,
present,
band_enabled,
},
&mut scroll,
merge_enabled,
)?;
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::ToggleMerge => {
let prev_model = {
let view = current_view(merge_enabled, &rows_data, &display_rows);
scroll
.table
.selected()
.and_then(|i| view.get(i))
.map(|row| row.model.clone())
};
merge_enabled = !merge_enabled;
let _ = crate::config::save_merge_models(merge_enabled);
if merge_enabled {
display_rows = merge_rows_by_base_model(&rows_data);
} else {
display_rows = Vec::new();
}
let view = current_view(merge_enabled, &rows_data, &display_rows);
let model_names: Vec<String> = view.iter().map(|row| row.model.clone()).collect();
scroll.sync(prev_model.as_deref(), &model_names);
for row in view {
update_tracker.prime(row.model.clone(), &row_fingerprint(row));
}
render_usage_frame(
&mut terminal,
view,
&totals,
&provider_totals,
&update_tracker,
&sys,
pid,
&QuotaView {
claude: &claude_snapshot,
codex: &codex_snapshot,
copilot: &copilot_snapshot,
cursor: &cursor_snapshot,
present,
band_enabled,
},
&mut scroll,
merge_enabled,
)?;
}
InputAction::Navigate(nav) => {
let view = current_view(merge_enabled, &rows_data, &display_rows);
scroll.apply(nav, view.len());
render_usage_frame(
&mut terminal,
view,
&totals,
&provider_totals,
&update_tracker,
&sys,
pid,
&QuotaView {
claude: &claude_snapshot,
codex: &codex_snapshot,
copilot: &copilot_snapshot,
cursor: &cursor_snapshot,
present,
band_enabled,
},
&mut scroll,
merge_enabled,
)?;
}
InputAction::Resize => {
let view = current_view(merge_enabled, &rows_data, &display_rows);
render_usage_frame(
&mut terminal,
view,
&totals,
&provider_totals,
&update_tracker,
&sys,
pid,
&QuotaView {
claude: &claude_snapshot,
codex: &codex_snapshot,
copilot: &copilot_snapshot,
cursor: &cursor_snapshot,
present,
band_enabled,
},
&mut scroll,
merge_enabled,
)?;
}
InputAction::Continue => {}
}
}
restore_terminal(&mut terminal)?;
Ok(())
}
fn current_view<'a>(
merge_enabled: bool,
rows_data: &'a [UsageRow],
display_rows: &'a [UsageRow],
) -> &'a [UsageRow] {
if merge_enabled {
display_rows
} else {
rows_data
}
}
fn row_fingerprint(row: &UsageRow) -> (i64, i64, i64, i64) {
(
row.input_tokens,
row.output_with_reasoning(),
row.cache_read,
row.cache_creation,
)
}
#[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,
merge_enabled: bool,
) -> 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 n = quota.present.count();
let arrange = arrange_band(area.width, area.height, n);
let panels_height = (quota.band_enabled && area.height >= USAGE_PANELS_MIN_H)
.then(|| band_height(&arrange, provider_rows.len()));
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 grid = split_band(panel_area, &arrange, n);
if let Some(table_area) = grid.table {
let block = Block::default()
.borders(Borders::ALL)
.border_style(Style::default().fg(RatatuiColor::Magenta));
let inner = block.inner(table_area);
f.render_widget(block, table_area);
let cells = RatatuiLayout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Min(2), Constraint::Length(1)])
.split(inner);
let (rows_area, bar_area) = (cells[0], cells[1]);
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_compact(row.stats.total_cost),
],
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(),
])
.style(Style::default().fg(RatatuiColor::DarkGray)),
);
}
let totals_header = vec!["Provider", "Tokens", "Cost"];
let totals_widths = [
Constraint::Min(9),
Constraint::Length(11),
Constraint::Length(11),
];
let totals_table = create_ratatui_table(
totals_rows,
totals_header,
&totals_widths,
RatatuiColor::Magenta,
)
.block(Block::default());
f.render_widget(totals_table, rows_area);
f.render_widget(
Paragraph::new(provider_share_bar(&provider_rows, bar_area.width)),
bar_area,
);
}
let now = chrono::Local::now().timestamp();
let mut idx = 0;
if quota.present.claude {
render_claude_quota(f, grid.panels[idx], quota.claude, now);
idx += 1;
}
if quota.present.codex {
render_codex_quota(f, grid.panels[idx], quota.codex, now);
idx += 1;
}
if quota.present.copilot {
render_copilot_quota(f, grid.panels[idx], quota.copilot, now);
idx += 1;
}
if quota.present.cursor {
render_cursor_quota(f, grid.panels[idx], quota.cursor, 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);
let merge_hint = if merge_enabled {
" split "
} else {
" merge "
};
f.render_widget(create_controls(&[("m", merge_hint)]), 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 provider_share_bar(rows: &[ProviderTotal<'_, ProviderStats>], width: u16) -> Line<'static> {
let width = width as usize;
let segments: Vec<(RatatuiColor, i64)> = rows
.iter()
.filter(|row| row.label != "All Providers" && row.stats.total_tokens > 0)
.map(|row| (row.tui_color, row.stats.total_tokens))
.collect();
let total: i64 = segments.iter().map(|(_, t)| *t).sum();
if width == 0 || total <= 0 {
return Line::from(Span::styled(
"â–‘".repeat(width),
Style::default().fg(RatatuiColor::DarkGray),
));
}
let mut widths: Vec<usize> = Vec::with_capacity(segments.len());
let mut remainders: Vec<(usize, f64)> = Vec::with_capacity(segments.len());
let mut used = 0usize;
for (i, (_, tokens)) in segments.iter().enumerate() {
let exact = *tokens as f64 / total as f64 * width as f64;
let floor = exact.floor() as usize;
widths.push(floor);
remainders.push((i, exact - floor as f64));
used += floor;
}
let mut leftover = width.saturating_sub(used);
remainders.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
for (i, _) in remainders {
if leftover == 0 {
break;
}
widths[i] += 1;
leftover -= 1;
}
let spans: Vec<Span<'static>> = segments
.iter()
.enumerate()
.filter_map(|(i, (color, _))| {
let w = widths[i];
(w > 0).then(|| Span::styled("â–ˆ".repeat(w), Style::default().fg(*color)))
})
.collect();
Line::from(spans)
}
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 quota_gauge_line_value(label: &str, pct: f64, value: &str) -> Line<'static> {
let color = gauge_color(pct);
Line::from(vec![
Span::styled(
format!("{label:<6} "),
Style::default().fg(RatatuiColor::Gray),
),
Span::styled(mini_bar(pct), Style::default().fg(color)),
Span::styled(format!(" {value}"), Style::default().fg(color)),
])
}
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),
))
}
enum BandArrange {
SingleRow { table: bool },
TwoRow { top: usize, table_in_hole: bool },
}
fn arrange_band(w: u16, area_h: u16, n: usize) -> BandArrange {
if n == 0 {
return BandArrange::SingleRow { table: true };
}
let panels_w = PANEL_MIN_W.saturating_mul(n as u16);
if w >= BAND_TABLE_MIN_W + panels_w {
BandArrange::SingleRow { table: true }
} else if w >= panels_w {
BandArrange::SingleRow { table: false }
} else if area_h >= PANELS_2ROW_MIN_H {
let top = n.div_ceil(2);
BandArrange::TwoRow {
top,
table_in_hole: top * 2 > n,
}
} else {
BandArrange::SingleRow { table: false }
}
}
fn band_height(arrange: &BandArrange, provider_rows: usize) -> u16 {
match arrange {
BandArrange::SingleRow { table: true } => (provider_rows as u16)
.saturating_add(5)
.max(QUOTA_PANEL_MIN_HEIGHT),
BandArrange::SingleRow { table: false } => QUOTA_PANEL_MIN_HEIGHT,
BandArrange::TwoRow { .. } => QUOTA_PANEL_MIN_HEIGHT.saturating_mul(2),
}
}
struct BandGrid {
table: Option<Rect>,
panels: Vec<Rect>,
}
fn split_even(area: Rect, k: usize) -> Vec<Rect> {
if k == 0 {
return Vec::new();
}
let cons = vec![Constraint::Ratio(1, k as u32); k];
RatatuiLayout::default()
.direction(Direction::Horizontal)
.constraints(cons)
.split(area)
.to_vec()
}
fn split_band(band: Rect, arrange: &BandArrange, n: usize) -> BandGrid {
match *arrange {
BandArrange::SingleRow { table } => {
let mut cons: Vec<Constraint> = Vec::new();
if table {
cons.push(Constraint::Min(BAND_TABLE_MIN_W));
}
let panel_span = if table {
band.width.saturating_sub(BAND_TABLE_MIN_W)
} else {
band.width
};
let pw = if n > 0 {
(panel_span / n as u16).max(PANEL_MIN_W)
} else {
PANEL_MIN_W
};
for _ in 0..n {
cons.push(Constraint::Length(pw));
}
let cells = RatatuiLayout::default()
.direction(Direction::Horizontal)
.constraints(cons)
.split(band);
let (table_rect, off) = if table {
(Some(cells[0]), 1)
} else {
(None, 0)
};
BandGrid {
table: table_rect,
panels: cells[off..off + n].to_vec(),
}
}
BandArrange::TwoRow { top, table_in_hole } => {
let rows = RatatuiLayout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(QUOTA_PANEL_MIN_HEIGHT),
Constraint::Length(QUOTA_PANEL_MIN_HEIGHT),
])
.split(band);
let bottom = n - top;
let row0 = split_even(rows[0], top);
let row1 = split_even(rows[1], bottom + table_in_hole as usize);
let mut panels = row0;
panels.extend_from_slice(&row1[..bottom]);
let table_rect = table_in_hole.then(|| row1[bottom]);
BandGrid {
table: table_rect,
panels,
}
}
}
}
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 render_copilot_quota(f: &mut Frame, area: Rect, copilot: &CopilotQuotaSnapshot, now: i64) {
let block = quota_block(" Copilot ", COPILOT_COLOR, copilot.limit_reached);
let mut lines: Vec<Line> = Vec::new();
if let Some(plan) = &copilot.plan_type {
lines.push(plan_line(plan));
}
if let Some(w) = &copilot.premium {
lines.push(quota_gauge_line("prem", w, now));
if let (Some(rem), Some(total)) = (copilot.premium_remaining, copilot.premium_entitlement)
&& total > 0
{
let used = (total - rem).max(0);
let pct = (used as f64 / total as f64) * 100.0;
lines.push(quota_gauge_line_value(
"reqs",
pct,
&format!("{used}/{total}"),
));
}
} else if copilot.premium_unlimited {
lines.push(dim_line("premium: unlimited"));
}
let has_content = !lines.is_empty();
if has_content {
lines.push(staleness_line(copilot.fetched_at, now));
}
if copilot.needs_login {
lines.push(login_hint_line(COPILOT_LOGIN_HINT));
} else if !has_content {
lines.push(dim_line("no Copilot quota"));
}
f.render_widget(Paragraph::new(lines).block(block), area);
}
fn render_cursor_quota(f: &mut Frame, area: Rect, cursor: &CursorQuotaSnapshot, now: i64) {
let block = quota_block(" Cursor ", CURSOR_COLOR, cursor.limit_reached);
let mut lines: Vec<Line> = Vec::new();
if let Some(plan) = &cursor.plan_type {
lines.push(plan_line(plan));
}
if let Some(w) = &cursor.total {
lines.push(quota_gauge_line("total", w, now));
}
if let Some(w) = &cursor.auto {
lines.push(quota_gauge_line("auto", w, now));
}
if let Some(w) = &cursor.api {
lines.push(quota_gauge_line("api", w, now));
}
if let Some(d) = cursor.on_demand_dollars {
lines.push(dim_line(&format!("on-demand: ${d:.2}")));
}
let has_content = !lines.is_empty();
if has_content {
lines.push(staleness_line(cursor.fetched_at, now));
}
if cursor.needs_login {
lines.push(login_hint_line(CURSOR_LOGIN_HINT));
} else if !has_content {
lines.push(dim_line("no Cursor quota"));
}
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)))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::models::Provider;
fn stats(tokens: i64) -> ProviderStats {
ProviderStats {
total_tokens: tokens,
total_cost: 0.0,
days_count: 1,
}
}
#[test]
fn share_bar_fills_exact_width() {
let (c, x, p) = (stats(710), stats(210), stats(80));
let rows = vec![
ProviderTotal::new(Provider::ClaudeCode, &c, false),
ProviderTotal::new(Provider::Codex, &x, false),
ProviderTotal::new(Provider::Copilot, &p, false),
];
let bar = provider_share_bar(&rows, 20);
let total: usize = bar.spans.iter().map(|s| s.content.chars().count()).sum();
assert_eq!(total, 20, "segments must fill the whole bar width");
assert!(bar.spans[0].content.chars().count() >= bar.spans[1].content.chars().count());
}
#[test]
fn share_bar_placeholder_when_no_tokens() {
let empty = stats(0);
let rows = vec![ProviderTotal::new(Provider::ClaudeCode, &empty, false)];
let bar = provider_share_bar(&rows, 10);
let total: usize = bar.spans.iter().map(|s| s.content.chars().count()).sum();
assert_eq!(total, 10);
assert_eq!(
bar.spans.len(),
1,
"no-data bar is a single placeholder span"
);
}
#[test]
fn share_bar_zero_width_is_empty() {
let c = stats(100);
let rows = vec![ProviderTotal::new(Provider::ClaudeCode, &c, false)];
let bar = provider_share_bar(&rows, 0);
let total: usize = bar.spans.iter().map(|s| s.content.chars().count()).sum();
assert_eq!(total, 0);
}
#[test]
fn arrange_wide_keeps_table_in_one_row() {
match arrange_band(BAND_TABLE_MIN_W + PANEL_MIN_W * 4, 40, 4) {
BandArrange::SingleRow { table } => assert!(table),
_ => panic!("expected single row with table"),
}
}
#[test]
fn arrange_medium_drops_table_but_stays_one_row() {
match arrange_band(PANEL_MIN_W * 4, 40, 4) {
BandArrange::SingleRow { table } => assert!(!table),
_ => panic!("expected single row without table"),
}
}
#[test]
fn arrange_narrow_tall_wraps_to_two_rows() {
match arrange_band(80, PANELS_2ROW_MIN_H, 4) {
BandArrange::TwoRow { top, table_in_hole } => {
assert_eq!(top, 2);
assert!(!table_in_hole, "even count fills both rows");
}
_ => panic!("expected two-row grid"),
}
}
#[test]
fn arrange_three_panels_fills_hole_with_table() {
match arrange_band(80, PANELS_2ROW_MIN_H, 3) {
BandArrange::TwoRow { top, table_in_hole } => {
assert_eq!(top, 2);
assert!(table_in_hole, "odd count leaves a hole for the table");
}
_ => panic!("expected two-row grid"),
}
}
#[test]
fn arrange_narrow_short_falls_back_to_single_row() {
match arrange_band(80, PANELS_2ROW_MIN_H - 1, 4) {
BandArrange::SingleRow { table } => assert!(!table),
_ => panic!("expected single-row fallback"),
}
}
#[test]
fn arrange_zero_panels_is_table_only() {
match arrange_band(100, 40, 0) {
BandArrange::SingleRow { table } => assert!(table),
_ => panic!("expected table-only row"),
}
}
#[test]
fn split_band_always_yields_exactly_n_panels() {
let area = Rect::new(0, 0, 200, 16);
for n in 0..=4 {
let arrange = arrange_band(area.width, area.height, n);
let grid = split_band(area, &arrange, n);
assert_eq!(grid.panels.len(), n, "n={n}");
}
}
#[test]
fn split_band_two_row_three_panels_has_table_in_hole() {
let area = Rect::new(0, 0, 80, 16);
let arrange = BandArrange::TwoRow {
top: 2,
table_in_hole: true,
};
let grid = split_band(area, &arrange, 3);
assert_eq!(grid.panels.len(), 3);
assert!(grid.table.is_some(), "the hole is filled with the table");
}
}