use std::path::{Path, PathBuf};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use super::input::{Input, Window};
use crate::claude::config_json::Utilization;
use crate::core::ids::{AccountId, SeatId};
use crate::core::limits::{Reading, WindowKind};
pub const VERSION: u32 = 3;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct LiveLimits {
pub v: u32,
pub at: DateTime<Utc>,
pub account: AccountId,
pub config_dir: String,
pub session_id: Option<String>,
pub five_hour: Option<(f64, DateTime<Utc>)>,
pub seven_day: Option<(f64, DateTime<Utc>)>,
}
impl LiveLimits {
fn repeats(&self, other: &LiveLimits) -> bool {
self.account == other.account
&& self.five_hour == other.five_hour
&& self.seven_day == other.seven_day
}
}
pub fn file_for(data_dir: &Path, config_dir: &Path) -> PathBuf {
file_of(data_dir, &crate::claude::seats::seat_id(config_dir))
}
pub fn file_of(data_dir: &Path, seat: &SeatId) -> PathBuf {
data_dir.join("statusline").join(format!("{seat}.json"))
}
pub fn windows(input: &Input) -> Option<Windows> {
let rl = input.rate_limits.as_ref()?;
let five_hour = rl.five_hour.as_ref().and_then(Window::pair);
let seven_day = rl.seven_day.as_ref().and_then(Window::pair);
if five_hour.is_none() && seven_day.is_none() {
return None;
}
Some((five_hour, seven_day))
}
pub type Windows = (Option<(f64, DateTime<Utc>)>, Option<(f64, DateTime<Utc>)>);
pub fn same_numbers(old: Option<&LiveLimits>, w: &Windows) -> bool {
old.is_some_and(|o| o.five_hour == w.0 && o.seven_day == w.1)
}
pub fn live_from(
input: &Input,
config_dir: &Path,
account: AccountId,
at: DateTime<Utc>,
) -> Option<LiveLimits> {
let (five_hour, seven_day) = windows(input)?;
Some(LiveLimits {
v: VERSION,
at,
account,
config_dir: config_dir.to_string_lossy().into_owned(),
session_id: input.session_id.clone(),
five_hour,
seven_day,
})
}
pub fn next(old: Option<&LiveLimits>, new: LiveLimits) -> Option<LiveLimits> {
match old {
Some(o) if o.repeats(&new) || o.at > new.at => None,
Some(_) | None => Some(new),
}
}
pub fn write(path: &Path, live: &LiveLimits) -> std::io::Result<()> {
let bytes = serde_json::to_vec(live)?;
crate::fsutil::atomic_write(path, &bytes, crate::fsutil::Mode::Private)
}
pub fn read(path: &Path) -> Option<LiveLimits> {
serde_json::from_slice::<LiveLimits>(&std::fs::read(path).ok()?)
.ok()
.filter(|l| l.v == VERSION)
}
pub fn merge(
cached: Option<Utilization>,
account: &AccountId,
live: Option<LiveLimits>,
) -> Option<Utilization> {
let Some(live) = live.filter(|l| &l.account == account) else {
return cached;
};
if cached.as_ref().is_some_and(|c| c.fetched_at >= live.at) {
return cached;
}
let mut readings: Vec<Reading> = Vec::new();
for (kind, v) in [
(WindowKind::FiveHour, live.five_hour),
(WindowKind::SevenDay, live.seven_day),
] {
if let Some((utilization, resets_at)) = v {
readings.extend(Reading::parse(kind, utilization, resets_at, live.at));
}
}
let cached = cached.filter(|c| &c.account_id == account);
if let Some(c) = cached.as_ref() {
readings.extend(
c.readings
.iter()
.filter(|r| !matches!(r.kind, WindowKind::FiveHour | WindowKind::SevenDay))
.copied(),
);
}
Some(Utilization {
account_id: account.clone(),
org_from_profile: false,
fetched_at: live.at,
readings,
extra_usage_enabled: cached.is_some_and(|c| c.extra_usage_enabled),
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::statusline::input::parse_input;
use chrono::TimeZone;
const INPUT: &str = r#"{"session_id":"s1","model":{"display_name":"Opus"},"cost":{"total_cost_usd":4.2},
"context_window":{"used_percentage":42.0},
"rate_limits":{"five_hour":{"used_percentage":12.5,"resets_at":1795400000},
"seven_day":{"used_percentage":3,"resets_at":1795960000}}}"#;
fn acc(s: &str) -> AccountId {
AccountId::new(s)
}
#[test]
fn readings_come_from_rate_limits_and_win_when_newer() {
let input = parse_input(INPUT);
let at = Utc.timestamp_opt(1_795_380_000, 0).unwrap();
let live = live_from(&input, Path::new("/x/.claude"), acc("acc"), at).unwrap();
assert_eq!(live.seven_day.unwrap().0, 3.0);
assert_eq!(live.five_hour.unwrap().1.timestamp(), 1_795_400_000);
let cached = Utilization {
account_id: acc("acc"),
org_from_profile: false,
fetched_at: at - chrono::Duration::hours(1),
readings: vec![Reading {
kind: WindowKind::SevenDay,
utilization: 95.0,
resets_at: at,
fetched_at: at,
}],
extra_usage_enabled: false,
};
let m = merge(Some(cached.clone()), &acc("acc"), Some(live.clone())).unwrap();
let week = m
.readings
.iter()
.find(|r| r.kind == WindowKind::SevenDay)
.unwrap();
assert_eq!((week.utilization, m.fetched_at), (3.0, at));
let newer = Utilization {
fetched_at: at + chrono::Duration::minutes(1),
..cached.clone()
};
assert_eq!(
merge(Some(newer.clone()), &acc("acc"), Some(live.clone())),
Some(newer)
);
}
#[test]
fn a_reading_of_another_account_is_not_the_seats() {
let at = Utc.timestamp_opt(1_795_380_000, 0).unwrap();
let input = parse_input(INPUT);
let a = live_from(&input, Path::new("/x"), acc("acc-a"), at).unwrap();
let cached_b = Utilization {
account_id: acc("acc-b"),
org_from_profile: false,
fetched_at: at - chrono::Duration::hours(3),
readings: vec![],
extra_usage_enabled: true,
};
assert_eq!(
merge(Some(cached_b.clone()), &acc("acc-b"), Some(a.clone())),
Some(cached_b)
);
assert_eq!(merge(None, &acc("acc-b"), Some(a)), None);
}
#[test]
fn a_reading_without_its_account_is_ignored() {
let t = tempfile::tempdir().unwrap();
let p = t.path().join("r.json");
std::fs::write(
&p,
r#"{"at":"2026-11-22T10:00:00Z","config_dir":"/x","session_id":null,
"five_hour":[12.0,"2026-11-22T14:00:00Z"],"seven_day":null}"#,
)
.unwrap();
assert_eq!(read(&p), None);
let at = Utc.timestamp_opt(1_795_380_000, 0).unwrap();
let live = live_from(&parse_input(INPUT), Path::new("/x"), acc("acc-a"), at).unwrap();
write(&p, &live).unwrap();
assert_eq!(read(&p), Some(live));
}
#[test]
fn a_reading_keeps_the_time_its_numbers_were_first_true() {
let t0 = Utc.timestamp_opt(1_795_380_000, 0).unwrap();
let reading = |pct: f64, at: DateTime<Utc>| LiveLimits {
v: VERSION,
at,
account: acc("acc-a"),
config_dir: "/x".into(),
session_id: None,
five_hour: None,
seven_day: Some((pct, t0 + chrono::Duration::days(3))),
};
let first = reading(40.0, t0);
assert_eq!(
next(Some(&first), reading(40.0, t0 + chrono::Duration::hours(1))),
None
);
let busy = reading(55.0, t0 + chrono::Duration::hours(2));
assert_eq!(next(Some(&first), busy.clone()), Some(busy.clone()));
assert_eq!(next(Some(&busy), reading(40.0, t0)), None);
assert_eq!(next(Some(&reading(40.0, t0)), busy.clone()), Some(busy));
assert_eq!(next(None, first.clone()), Some(first));
}
}