use chrono::{DateTime, Local, Utc};
use serde::Serialize;
use crate::app::context::Ctx;
use crate::core::guard::{Lines, State};
use crate::core::ids::{AccountId, ProjectKey, SeatId};
use crate::core::limits::{Level, Share};
use crate::core::units::{Pct, Usd};
use crate::limits::{AccountReport, WindowReport, all_reports};
use crate::ui::fmt;
use crate::ui::mask;
use crate::ui::style::Tone;
use crate::ui::table::{Align, Cell, Table};
use super::Format;
pub struct LimitsArgs<'a> {
pub format: Format,
pub top: usize,
pub seat: Option<&'a str>,
pub account: Option<&'a str>,
}
fn seat_named<'c>(ctx: &'c Ctx, name: &str) -> anyhow::Result<&'c crate::claude::seats::Seat> {
if name == "current" {
let dir = crate::statusline::current_config_dir(&ctx.dirs.home);
return ctx.resolve_seat(&dir.to_string_lossy());
}
ctx.resolve_seat(name)
}
fn account_in(ctx: &Ctx, seat: &SeatId) -> Option<AccountId> {
ctx.seats
.iter()
.zip(&ctx.seat_info)
.find(|(s, _)| &s.id == seat)
.and_then(|(_, si)| si.account.as_ref().map(|a| a.id()))
}
pub fn run(ctx: &Ctx, a: &LimitsArgs) -> anyhow::Result<()> {
let (idx, _) = ctx.index()?;
let mut reports = all_reports(&ctx.limits_inputs(&idx)?, &idx)?;
if let Some(name) = a.seat {
let seat = seat_named(ctx, name)?;
let held = account_in(ctx, &seat.id);
reports.retain(|r| held.as_ref() == Some(&r.account));
}
if let Some(name) = a.account {
let id = ctx.resolve_account(&idx, name)?;
reports.retain(|r| r.account == id);
}
let logins = crate::vault::saved_logins(&ctx.dirs.vault_dir()).unwrap_or_else(|e| {
crate::diag::log("limits", &format!("vault unreadable: {e:#}"));
Vec::new()
});
let lines: Vec<Lines> = reports
.iter()
.map(|r| crate::guard::lines_of(&r.account, &ctx.config, &logins))
.collect();
if ctx.mask {
for r in &mut reports {
r.name = ctx.shown_account_name(r.account.as_str());
for w in &mut r.windows {
w.reference = w.reference_id.as_deref().map(|a| ctx.shown_account_name(a));
for s in &mut w.shares {
s.project = ProjectKey::from_stored(ctx.show_path(s.project.as_str()));
s.name = ctx.show_path(&s.name);
}
}
}
}
match a.format {
Format::Json => {
let out: Vec<AccountOut> = reports
.iter_mut()
.zip(&lines)
.map(|(r, l)| account_out(ctx, r, l, &logins, a.top))
.collect();
println!("{}", serde_json::to_string_pretty(&out)?);
return Ok(());
}
Format::Csv => {
print!("{}", csv(ctx, &reports, &lines));
return Ok(());
}
Format::Table => {}
}
let p = &ctx.painter;
if reports.is_empty() {
let none = if a.seat.is_some() || a.account.is_some() {
"No limit readings for that account yet."
} else {
"No limit readings yet: Claude Code caches them after it shows usage. Run /usage in Claude Code once."
};
println!("{}", p.paint(none, Tone::Dim));
return Ok(());
}
for (i, (rep, l)) in reports.iter().zip(&lines).enumerate() {
if i > 0 {
println!();
}
let email = ctx
.email(rep.account.as_str())
.map(|e| format!(" · {e}"))
.unwrap_or_default();
let org = match ctx
.org_name(rep.account.as_str())
.filter(|o| o != &rep.name)
{
Some(o) => format!(" · {o}"),
None => String::new(),
};
let tier = rep
.tier
.as_deref()
.map(|t| format!(" · {}", crate::claude::config_json::format_tier_label(t)))
.unwrap_or_default();
println!(
"{} {}{}",
p.paint("ACCOUNT", Tone::Header),
p.paint(&rep.name, Tone::Bold),
p.paint(&format!("{email}{org}{tier}"), Tone::Dim)
);
let guarded = guarded_seats(ctx, &rep.account);
for w in &rep.windows {
print_window(ctx, w, a.top);
print_guard(ctx, w, l, &guarded);
}
}
println!();
println!(
"{}",
p.paint(
"≈ estimates: limit usage is assumed proportional to API-equivalent cost.",
Tone::Dim
)
);
Ok(())
}
fn seats_of<'c>(ctx: &'c Ctx, account: &AccountId) -> Vec<&'c crate::claude::seats::Seat> {
ctx.seats
.iter()
.zip(&ctx.seat_info)
.filter(|(_, si)| si.account.as_ref().is_some_and(|a| &a.id() == account))
.map(|(s, _)| s)
.collect()
}
fn guarded_seats(ctx: &Ctx, account: &AccountId) -> Vec<String> {
seats_of(ctx, account)
.into_iter()
.filter(|s| super::setup::seat_has_guard(s))
.map(|s| s.label.clone())
.collect()
}
fn guard_of(w: &WindowReport, lines: &Lines, now: DateTime<Utc>) -> Option<GuardOut> {
let line = lines.line(w.reading.kind)?;
let state = if w.reset_passed {
State::Go
} else {
crate::core::guard::verdict(&[w.reading], lines, now).state
};
Some(GuardOut {
line,
wrap_up_at: lines.wrap_up_at(w.reading.kind).unwrap_or(line),
state,
})
}
fn print_guard(ctx: &Ctx, w: &WindowReport, lines: &Lines, guarded: &[String]) {
let Some(g) = guard_of(w, lines, ctx.now) else {
return;
};
let p = &ctx.painter;
let seats = if guarded.is_empty() {
"in no guarded seat".to_string()
} else {
format!("guarded seats: {}", guarded.join(", "))
};
let (what, tone) = match g.state {
State::Go => ("", Tone::Dim),
State::WrapUp => (" · agents told to wrap up", Tone::Warn),
State::Stop => (" · agents stopped", Tone::Bad),
};
println!(
"{}{}",
" ".repeat(16),
p.paint(
&format!(
"guard: wrap up from {}, stop at {} ({seats}){what}",
fmt::pct(g.wrap_up_at.get()),
fmt::pct(g.line.get())
),
tone
)
);
}
#[derive(Serialize)]
struct AccountOut<'a> {
account_uuid: &'a AccountId,
name: &'a str,
tier: Option<&'a str>,
email: Option<String>,
org: Option<String>,
seats: Vec<SeatOut>,
logins: Vec<String>,
windows: Vec<WindowOut<'a>>,
}
#[derive(Serialize)]
struct SeatOut {
id: SeatId,
label: String,
guarded: bool,
}
#[derive(Serialize)]
struct WindowOut<'a> {
#[serde(flatten)]
report: &'a WindowReport,
level: &'static str,
runs_out_at: Option<DateTime<Utc>>,
at_reset: Option<Pct>,
#[serde(skip_serializing_if = "is_zero")]
shares_left_out: usize,
guard: Option<GuardOut>,
}
fn is_zero(n: &usize) -> bool {
*n == 0
}
#[derive(Serialize)]
struct GuardOut {
line: Pct,
wrap_up_at: Pct,
state: State,
}
fn level_key(l: Level) -> &'static str {
match l {
Level::Ok => "ok",
Level::Warn => "warn",
Level::Bad => "bad",
Level::Reached => "reached",
}
}
fn account_out<'a>(
ctx: &Ctx,
r: &'a mut AccountReport,
lines: &Lines,
logins: &[crate::vault::Login],
top: usize,
) -> AccountOut<'a> {
let left_out: Vec<usize> = r
.windows
.iter_mut()
.map(|w| {
let n = w.shares.len().saturating_sub(top);
w.shares.truncate(top);
n
})
.collect();
let seats = seats_of(ctx, &r.account)
.into_iter()
.map(|s| SeatOut {
id: s.id.clone(),
label: s.label.clone(),
guarded: super::setup::seat_has_guard(s),
})
.collect();
let saved = logins
.iter()
.filter(|l| l.account_uuid.as_deref().map(AccountId::new).as_ref() == Some(&r.account))
.map(|l| mask::login_label(&l.label, l.email.as_deref(), ctx.mask))
.collect();
let r: &'a AccountReport = r;
AccountOut {
account_uuid: &r.account,
name: &r.name,
tier: r.tier.as_deref(),
email: ctx.email(r.account.as_str()),
org: ctx.org_name(r.account.as_str()),
seats,
logins: saved,
windows: r
.windows
.iter()
.zip(left_out)
.map(|(w, n)| WindowOut {
report: w,
level: level_key(w.level()),
runs_out_at: w.runs_out_at,
at_reset: if w.reset_passed {
None
} else {
w.projection_at_reset(ctx.now)
},
shares_left_out: n,
guard: guard_of(w, lines, ctx.now),
})
.collect(),
}
}
fn csv(ctx: &Ctx, reports: &[AccountReport], lines: &[Lines]) -> String {
let cell = |s: &str| {
if s.contains([',', '"', '\n']) {
format!("\"{}\"", s.replace('"', "\"\""))
} else {
s.to_string()
}
};
let time = |t: Option<DateTime<Utc>>| t.map_or(String::new(), |t| t.to_rfc3339());
let num = |p: Option<Pct>| p.map_or(String::new(), |p| format!("{:.2}", p.get()));
let mut out = String::from(
"account_uuid,name,window,reading,reading_at,estimate_now,level,resets_at,runs_out_at,at_reset,cost_in_window_usd,guard_line,guard_state\n",
);
for (r, l) in reports.iter().zip(lines) {
for w in &r.windows {
let g = guard_of(w, l, ctx.now);
let state = g.as_ref().map(|g| match g.state {
State::Go => "go",
State::WrapUp => "wrap_up",
State::Stop => "stop",
});
out.push_str(&format!(
"{},{},{},{:.2},{},{:.2},{},{},{},{},{:.6},{},{}\n",
cell(r.account.as_str()),
cell(&r.name),
w.reading.kind.key(),
w.reading.utilization,
w.reading.fetched_at.to_rfc3339(),
w.estimate_now.get(),
level_key(w.level()),
w.window.end.to_rfc3339(),
time(w.runs_out_at),
num(if w.reset_passed {
None
} else {
w.projection_at_reset(ctx.now)
}),
w.cost_in_window.get(),
num(g.as_ref().map(|g| g.line)),
state.unwrap_or(""),
));
}
}
out
}
fn print_window(ctx: &Ctx, w: &WindowReport, top: usize) {
let p = &ctx.painter;
let r = &w.reading;
let shown = w.estimate_now.get();
let tone = Tone::of_utilization(shown);
let label = format!("{:<13}", r.kind.label());
let main = if w.reset_passed {
format!(
"{} ≈{} (new window since {}, no reading yet)",
fmt::gauge(shown / 100.0, 24),
fmt::pct(shown),
r.resets_at.with_timezone(&Local).format("%a %H:%M")
)
} else {
format!(
"{} {} ≈{} now",
fmt::gauge(shown / 100.0, 24),
fmt::pct(r.utilization),
fmt::pct(shown)
)
};
println!(" {} {}", p.paint(&label, Tone::Bold), p.paint(&main, tone));
let pad = " ".repeat(16);
println!(
"{pad}{}",
p.paint(
&format!(
"resets {} (in {}) · reading {} old",
w.window.end.with_timezone(&Local).format("%a %H:%M"),
fmt::duration(w.window.end - ctx.now),
fmt::duration(ctx.now - r.fetched_at)
),
Tone::Dim
)
);
if let Some(t) = w.manual_reset {
println!(
"{pad}{}",
p.paint(
&format!(
"limit reset by hand ≈{}; counting from there",
t.with_timezone(&Local).format("%a %H:%M")
),
Tone::Accent
)
);
}
let mut burn = format!("burn {}/h", fmt::money(w.burn_usd_per_hour));
if let Some(pph) = w.points_per_hour {
burn.push_str(&format!(" ≈ {pph:.1}%/h"));
}
match w.eta {
Some(d) if d.num_seconds() == 0 => burn.push_str(" · LIMIT REACHED"),
Some(d) => burn.push_str(&format!(
" → empty {} (in {})",
(ctx.now + d).with_timezone(&Local).format("%a %H:%M"),
fmt::duration(d)
)),
None if w.points_per_hour.is_some() && w.burn_usd_per_hour > Usd::ZERO => {
burn.push_str(" · lasts until reset")
}
None if w.burn_usd_per_hour > Usd::ZERO => burn.push_str(" · pace unknown"),
None => {}
}
println!(
"{pad}{}",
p.paint(
&burn,
if w.eta.is_some() {
Tone::Warn
} else {
Tone::Dim
}
)
);
if let (Some(u), Some(full)) = (w.usd_per_point, w.window_usd) {
let src = match &w.reference {
Some(r) => format!(" (reference: {r}, same plan)"),
None => String::new(),
};
println!(
"{pad}{}",
p.paint(
&format!(
"≈{}/pt · a full window ≈ {} API-equivalent{src}",
fmt::money(u),
fmt::money(full)
),
Tone::Dim
)
);
}
if let (Some(v), Some(o)) = (w.visible_points, w.outside_points)
&& o >= Pct::new(2.0)
{
println!(
"{pad}{}",
p.paint(&format!("on this machine ≈{v:.1}% · elsewhere (claude.ai, desktop, other computers) ≈{o:.1}%"), Tone::Warn)
);
}
if w.shares.is_empty() {
return;
}
let mut t = Table::new(&[
("PROJECT", Align::Left),
("COST", Align::Right),
("SHARE", Align::Left),
("≈ LIMIT", Align::Right),
]);
t.max_width = t.max_width.map(|m| m.saturating_sub(4));
let max = w.shares.first().map(|s| s.share).unwrap_or(0.0);
for s in w.shares.iter().take(top) {
t.row(vec![
Cell::new(s.name.clone()),
Cell::new(fmt::money(s.cost)),
Cell::tone(
format!(
"{:<20} {}",
fmt::bar(if max > 0.0 { s.share / max } else { 0.0 }, 20),
fmt::pct(s.share * 100.0)
),
Tone::Accent,
),
Cell::tone(format!("≈{:.1}%", s.limit_points), Tone::Bold),
]);
}
if w.shares.len() > top {
let rest: Vec<&Share> = w.shares.iter().skip(top).collect();
t.row(vec![
Cell::tone(format!("… {} more", rest.len()), Tone::Dim),
Cell::tone(
fmt::money(rest.iter().map(|s| s.cost).sum::<Usd>()),
Tone::Dim,
),
Cell::new(""),
Cell::tone(
format!("≈{:.1}%", rest.iter().map(|s| s.limit_points).sum::<Pct>()),
Tone::Dim,
),
]);
}
if let Some(o) = w.outside_points.filter(|o| *o >= Pct::new(2.0)) {
t.row(vec![
Cell::tone("(elsewhere)", Tone::Warn),
Cell::tone("?", Tone::Dim),
Cell::new(""),
Cell::tone(format!("≈{o:.1}%"), Tone::Warn),
]);
}
for line in t.render(p).lines() {
println!(" {line}");
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::Dirs;
use crate::core::pricing::PriceBook;
use crate::index::SeatInfo;
use crate::index::scenarios::{World, account, assistant, at, owner, weekly};
use crate::procs::ProcTable;
use crate::ui::style::{ColorChoice, Painter};
fn setup() -> (World, Ctx, Vec<AccountReport>) {
let w = World::new(&["work", "lab"]);
let resets = "2026-11-24T00:00:00Z";
let seat = |label: &str, acc: &str, used: f64| SeatInfo {
seat: Default::default(),
label: label.into(),
account: Some(account(acc, "2026-11-01T00:00:00Z")),
switched_at: None,
utilization: Some(weekly(acc, "2026-11-20T00:00:00Z", used, resets)),
};
let info = vec![seat("work", "acc-a", 82.0), seat("lab", "acc-b", 30.0)];
let req = |id: &str, cwd: &str| {
assistant(
id,
"2026-11-19T06:00:00Z",
"claude-sonnet-5-5",
cwd,
(500_000, 0),
&[],
)
};
w.append(
"work",
"s1",
&[owner("acc-a"), req("q1", "/w/shop"), req("q2", "/w/blog")],
);
let mut idx = w.index("i.sqlite");
w.refresh(&mut idx, &info, &PriceBook::builtin());
let ctx = Ctx {
dirs: Dirs {
data: w.dir.path().join("data"),
config: w.dir.path().join("config"),
home: w.dir.path().to_path_buf(),
},
config: toml::from_str("[guard]\nweek = 85\n").unwrap(),
seats: w.seats.clone(),
seat_info: info,
prices: PriceBook::builtin(),
procs: ProcTable::empty(),
painter: Painter::new(ColorChoice::Never),
mask: false,
now: at("2026-11-20T12:00:00Z"),
login_labels: Default::default(),
login_tiers: Default::default(),
problems: Vec::new(),
};
let reports = all_reports(&ctx.limits_inputs(&idx).unwrap(), &idx).unwrap();
(w, ctx, reports)
}
fn lines_for(ctx: &Ctx, reports: &[AccountReport]) -> Vec<Lines> {
reports
.iter()
.map(|r| crate::guard::lines_of(&r.account, &ctx.config, &[]))
.collect()
}
#[test]
fn a_seat_names_the_account_it_holds() {
let (_w, ctx, _) = setup();
let lab = seat_named(&ctx, "lab").unwrap();
assert_eq!(account_in(&ctx, &lab.id), Some(AccountId::new("acc-b")));
assert!(
seat_named(&ctx, "nowhere").is_err(),
"an unknown seat says so"
);
}
#[test]
fn json_says_what_an_agent_asks_next() {
let (_w, ctx, mut reports) = setup();
let lines = lines_for(&ctx, &reports);
let out: Vec<AccountOut> = reports
.iter_mut()
.zip(&lines)
.map(|(r, l)| account_out(&ctx, r, l, &[], 8))
.collect();
let v = serde_json::to_value(&out).unwrap();
let a = v
.as_array()
.unwrap()
.iter()
.find(|a| a["account_uuid"] == "acc-a")
.unwrap();
assert_eq!(a["seats"][0]["label"], "work");
assert_eq!(a["seats"][0]["guarded"], false);
let week = &a["windows"][0];
assert_eq!(week["reading"]["utilization"], 82.0);
assert_eq!(week["estimate_now"], 82.0);
assert_eq!(week["level"], "warn");
assert!(week.get("runs_out_at").is_some(), "{week}");
assert!(week.get("at_reset").is_some(), "{week}");
assert_eq!(week["shares"].as_array().unwrap().len(), 2);
assert!(week.get("shares_left_out").is_none(), "nothing left out");
assert_eq!(
week["guard"],
serde_json::json!({"line": 85.0, "wrap_up_at": 80.0, "state": "wrap_up"})
);
let b = v
.as_array()
.unwrap()
.iter()
.find(|a| a["account_uuid"] == "acc-b")
.unwrap();
assert_eq!(b["windows"][0]["guard"]["state"], "go");
}
#[test]
fn top_holds_for_json_too() {
let (_w, ctx, mut reports) = setup();
let lines = lines_for(&ctx, &reports);
let a = reports
.iter_mut()
.zip(&lines)
.find(|(r, _)| r.account.as_str() == "acc-a")
.unwrap();
let v = serde_json::to_value(account_out(&ctx, a.0, a.1, &[], 1)).unwrap();
assert_eq!(v["windows"][0]["shares"].as_array().unwrap().len(), 1);
assert_eq!(v["windows"][0]["shares_left_out"], 1);
}
#[test]
fn csv_has_one_row_per_account_and_window() {
let (_w, ctx, reports) = setup();
let text = csv(&ctx, &reports, &lines_for(&ctx, &reports));
let rows: Vec<&str> = text.lines().collect();
assert!(
rows[0].starts_with("account_uuid,name,window,reading,"),
"{text}"
);
assert_eq!(rows.len(), 3, "{text}");
let a = rows.iter().find(|r| r.starts_with("acc-a,")).unwrap();
assert!(a.contains(",seven_day,82.00,"), "{a}");
assert!(a.ends_with(",85.00,wrap_up"), "{a}");
}
}