Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

account-usage: each sign-in's 5-hour and weekly limit (server) (#604)

Oleksandr Ivanchenkoc529a77ebd75
diff --git a/src/db/profiles.rs b/src/db/profiles.rs
index e3a435dc..9c3a0f0e 100644
--- a/src/db/profiles.rs
+++ b/src/db/profiles.rs
@@ -39,6 +39,13 @@ impl Database {
)
.execute(&self.pool)
.await;
+ // account-usage: each account's last 5-hour/weekly reading, kept apart from its failure
+ for sql in [
+ "ALTER TABLE llm_profile_state ADD COLUMN usage_json TEXT;",
+ "ALTER TABLE llm_profile_state ADD COLUMN usage_checked_at TIMESTAMP;",
+ ] {
+ let _ = sqlx::query(sql).execute(&self.pool).await;
+ }
for engine in PROFILE_ENGINES {
sqlx::query(
"INSERT OR IGNORE INTO llm_profiles (id, engine, name, kind, home_dir, priority, enabled, is_default)
@@ -207,9 +214,11 @@ impl Database {
Ok(rows.into_iter().map(|(id,)| id).collect())
}
+ /// Profiles with a recorded failure. A row that only holds a usage reading isn't one.
pub async fn list_profile_states(&self) -> Result<HashMap<String, LlmProfileState>, DbError> {
let rows = sqlx::query_as::<_, LlmProfileState>(
- "SELECT profile_id, limited_until, last_error FROM llm_profile_state",
+ "SELECT profile_id, limited_until, last_error FROM llm_profile_state
+ WHERE limited_until IS NOT NULL OR last_error IS NOT NULL",
)
.fetch_all(&self.pool)
.await?;
@@ -240,7 +249,68 @@ impl Database {
Ok(())
}
- /// Forgets a profile's failure after it served a turn, or after a new login or key.
+ /// Forgets a profile's failure after it served a turn, keeping its usage reading.
+ pub async fn clear_profile_failure(&self, id: &str) -> Result<(), DbError> {
+ sqlx::query(
+ "UPDATE llm_profile_state SET limited_until = NULL, last_error = NULL, updated_at = CURRENT_TIMESTAMP
+ WHERE profile_id = ?",
+ )
+ .bind(id)
+ .execute(&self.pool)
+ .await?;
+ Ok(())
+ }
+
+ /// Saves a profile's latest 5-hour/weekly reading. Leaves its failure as it is.
+ pub async fn record_profile_usage(
+ &self,
+ id: &str,
+ usage: &crate::profiles::usage::AccountUsage,
+ ) -> Result<(), DbError> {
+ sqlx::query(
+ "INSERT INTO llm_profile_state (profile_id, usage_json, usage_checked_at, updated_at)
+ VALUES (?, ?, ?, CURRENT_TIMESTAMP)
+ ON CONFLICT(profile_id) DO UPDATE SET usage_json = excluded.usage_json,
+ usage_checked_at = excluded.usage_checked_at, updated_at = CURRENT_TIMESTAMP",
+ )
+ .bind(id)
+ .bind(usage.to_stored())
+ .bind(usage.checked_at)
+ .execute(&self.pool)
+ .await?;
+ Ok(())
+ }
+
+ /// One profile's latest usage reading, if it has one this version can read.
+ pub async fn get_profile_usage(&self, id: &str) -> Result<Option<crate::profiles::usage::AccountUsage>, DbError> {
+ let row: Option<(String, DateTime<Utc>)> = sqlx::query_as(
+ "SELECT usage_json, usage_checked_at FROM llm_profile_state
+ WHERE profile_id = ? AND usage_json IS NOT NULL AND usage_checked_at IS NOT NULL",
+ )
+ .bind(id)
+ .fetch_optional(&self.pool)
+ .await?;
+ Ok(row.and_then(|(json, at)| crate::profiles::usage::AccountUsage::from_stored(&json, at)))
+ }
+
+ /// Each profile's latest usage reading, by profile id.
+ pub async fn list_profile_usage(
+ &self,
+ ) -> Result<HashMap<String, crate::profiles::usage::AccountUsage>, DbError> {
+ let rows: Vec<(String, String, DateTime<Utc>)> = sqlx::query_as(
+ "SELECT profile_id, usage_json, usage_checked_at FROM llm_profile_state
+ WHERE usage_json IS NOT NULL AND usage_checked_at IS NOT NULL",
+ )
+ .fetch_all(&self.pool)
+ .await?;
+ Ok(rows
+ .into_iter()
+ .filter_map(|(id, json, at)| crate::profiles::usage::AccountUsage::from_stored(&json, at).map(|u| (id, u)))
+ .collect())
+ }
+
+ /// Forgets a profile's failure and usage reading, after a new login or key (the account
+ /// may be another one now).
pub async fn clear_profile_state(&self, id: &str) -> Result<(), DbError> {
sqlx::query("DELETE FROM llm_profile_state WHERE profile_id = ?")
.bind(id)
diff --git a/src/drivers/cli.rs b/src/drivers/cli.rs
index cc3ef168..7ad00944 100644
--- a/src/drivers/cli.rs
+++ b/src/drivers/cli.rs
@@ -1108,6 +1108,8 @@ struct ClaudeStream {
/// Tools, MCP servers, skills and slash commands claude's `init` line said it has; `None`
/// until that line arrives.
offered: Option<Vec<String>>,
+ /// The account's windows from the last `rate_limit_event` line.
+ rate_limits: Option<crate::profiles::usage::UsageReading>,
}
/// Longest reason kept from a failed tool result.
@@ -1143,6 +1145,11 @@ impl ClaudeStream {
let blocks = v["message"]["content"].as_array().map(Vec::as_slice).unwrap_or_default();
match v["type"].as_str() {
Some("result") => self.result_line = Some(line.to_string()),
+ Some("rate_limit_event") => {
+ if let Some(reading) = crate::profiles::usage::from_claude_event(&v) {
+ self.rate_limits = Some(reading);
+ }
+ }
Some("system") if v["subtype"] == "init" => {
let offered = self.offered.get_or_insert_with(Vec::new);
for key in ["tools", "mcp_servers", "skills", "slash_commands"] {
@@ -1888,13 +1895,15 @@ impl Driver for CliDriver {
return Err(no_tools_broken(&self.tool_kind, &what));
}
}
+ // The account's windows, from a container run too (its stdout is the same stream)
+ let rate_limits = claude_stream.rate_limits.take();
let stdout = claude_stream.into_stdout();
if let Some(t) = isolated.take() {
if let Some(notice) = isolated_end(&t, &input, &stdout, exit) {
if let Some(u) = ClaudeResult::parse(&stdout).and_then(|r| r.split().map(|u| (r.main_model(), u))) {
record_cli_usage(&input, u.0, &u.1).await;
}
- return Ok(notice);
+ return Ok(notice.with_usage(rate_limits));
}
}
@@ -1924,7 +1933,7 @@ impl Driver for CliDriver {
let bare_limit = crate::profiles::classify::is_limit_line(&result.result);
if (result.is_error && result.num_turns <= 1) || bare_limit {
if let Some(failure) = refusal(&result.result) {
- return Ok(TurnOutput::refused(failure));
+ return Ok(TurnOutput::refused(failure).with_usage(rate_limits));
}
}
tokens = result.tokens();
@@ -1967,6 +1976,7 @@ impl Driver for CliDriver {
tokens_used: tokens,
usage,
is_error,
+ usage_windows: rate_limits,
..Default::default()
})
}
@@ -2232,6 +2242,25 @@ endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & \"%_prog%\" \"%dp0%\\n
assert_eq!(parsed.tokens(), Some(7));
}
+ /// account-usage: the stream keeps the last `rate_limit_event` (a recorded turn) and the
+ /// result line still parses.
+ #[test]
+ fn claude_stream_keeps_the_accounts_windows_from_a_recorded_turn() {
+ let t0 = Instant::now();
+ let mut s = ClaudeStream::default();
+ for line in include_str!("../../tests/fixtures/claude_rate_limit_event.jsonl").lines() {
+ s.line(line, t0);
+ }
+ let r = s.rate_limits.clone().expect("the rate_limit_event was kept");
+ assert_eq!(r.status.as_deref(), Some("ok"));
+ assert_eq!(r.windows.iter().map(|w| (w.kind.as_str(), w.used_pct)).collect::<Vec<_>>(), vec![("five_hour", 14), ("weekly", 56)]);
+ // A later event wins; an empty one doesn't wipe what was read
+ s.line(r#"{"type":"rate_limit_event","rate_limit_info":{"status":"allowed_warning","unifiedWindows":{"five_hour":{"utilization":0.9,"resetsAt":1794605400}}}}"#, t0);
+ s.line(r#"{"type":"rate_limit_event","rate_limit_info":{}}"#, t0);
+ assert_eq!(s.rate_limits.as_ref().unwrap().status.as_deref(), Some("warning"));
+ assert_eq!(ClaudeResult::parse(&s.into_stdout()).unwrap().result, "OK");
+ }
+
/// 0.9.5: claude's init line names servers that failed or want a sign-in (said like the API
/// driver says them), and a failed tool result keeps why it failed.
#[test]
diff --git a/src/drivers/mod.rs b/src/drivers/mod.rs
index e5d35f38..87e068db 100644
--- a/src/drivers/mod.rs
+++ b/src/drivers/mod.rs
@@ -896,6 +896,10 @@ pub struct TurnOutput {
/// a caller that opts in (`TurnOpts::error_result_fails`) gets it as the turn's error.
#[serde(skip)]
pub is_error: bool,
+ /// The account's 5-hour and weekly windows as the engine reported them during the turn
+ /// (Claude's last `rate_limit_event`), kept per profile by the turn's caller.
+ #[serde(skip)]
+ pub usage_windows: Option<crate::profiles::usage::UsageReading>,
}
impl TurnOutput {
@@ -908,6 +912,11 @@ impl TurnOutput {
pub fn refused(failure: crate::profiles::ProviderFailure) -> Self {
Self { failure: Some(failure), ..Default::default() }
}
+
+ /// The same output, carrying the account's windows read during the turn.
+ pub fn with_usage(self, usage_windows: Option<crate::profiles::usage::UsageReading>) -> Self {
+ Self { usage_windows: usage_windows.or(self.usage_windows), ..self }
+ }
}
#[async_trait]
diff --git a/src/profiles/mod.rs b/src/profiles/mod.rs
index fa24be6e..73f89d60 100644
--- a/src/profiles/mod.rs
+++ b/src/profiles/mod.rs
@@ -4,6 +4,7 @@
pub mod classify;
pub mod login;
pub mod status;
+pub mod usage;
use crate::db::models::{LlmProfile, LlmProfileState, ProfileKey};
use chrono::{DateTime, Utc};
diff --git a/src/profiles/status.rs b/src/profiles/status.rs
index 67b94768..3b982d0a 100644
--- a/src/profiles/status.rs
+++ b/src/profiles/status.rs
@@ -31,6 +31,8 @@ pub struct ProfileManager {
cache: Mutex<HashMap<String, (Instant, ProfileStatus)>>,
/// The last check of each Custom API account: its status and the models it lists.
custom: Mutex<HashMap<String, (Instant, crate::drivers::custom::CustomCheck)>>,
+ /// When each account's limits were last read on the person's "Check now".
+ usage_checks: Mutex<HashMap<String, Instant>>,
}
impl ProfileManager {
@@ -40,9 +42,22 @@ impl ProfileManager {
logins: LoginManager::default(),
cache: Mutex::new(HashMap::new()),
custom: Mutex::new(HashMap::new()),
+ usage_checks: Mutex::new(HashMap::new()),
}
}
+ /// Takes this account's turn to read its limits fresh: `true` at most once per
+ /// [`super::usage::CHECK_EVERY`], since each Claude read spends a little of its limit.
+ pub fn claim_usage_check(&self, id: &str) -> bool {
+ let Ok(mut checks) = self.usage_checks.lock() else { return false };
+ let now = Instant::now();
+ if checks.get(id).is_some_and(|at| now.duration_since(*at) < super::usage::CHECK_EVERY) {
+ return false;
+ }
+ checks.insert(id.to_string(), now);
+ true
+ }
+
/// The config dir a `cli_home` profile runs with.
pub fn home_of(&self, p: &LlmProfile) -> Option<PathBuf> {
(p.kind == "cli_home").then(|| {
diff --git a/src/profiles/usage.rs b/src/profiles/usage.rs
new file mode 100644
index 00000000..206f6b6f
--- /dev/null
+++ b/src/profiles/usage.rs
@@ -0,0 +1,267 @@
+//! How much of an AI account's 5-hour and weekly limit is used, and when each resets: read from
+//! the `rate_limit_event` line Claude's `stream-json` prints on every turn, or from Codex's
+//! `account/rateLimits/read`. Kept per profile (`llm_profile_state.usage_json`) and shown as
+//! `usage` on `GET /api/profiles` (contract: autonomy/account-usage/brief.md).
+
+use chrono::{DateTime, TimeZone, Utc};
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+
+/// The least time between two "Check now" reads of one account: each Claude read spends a
+/// little of the person's limit.
+pub const CHECK_EVERY: std::time::Duration = std::time::Duration::from_secs(60);
+
+/// One limit window: how much of it is used (0–100, rounded) and when it resets.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct UsageWindow {
+ /// `five_hour` or `weekly`.
+ pub kind: String,
+ pub used_pct: u8,
+ pub resets_at: Option<DateTime<Utc>>,
+}
+
+/// What one turn or check read: the account's state and its windows.
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub struct UsageReading {
+ /// `ok`, `warning` or `out`; `None` when the CLI didn't say.
+ pub status: Option<String>,
+ /// `five_hour` first, then `weekly`; windows of any other length are dropped.
+ pub windows: Vec<UsageWindow>,
+}
+
+impl UsageReading {
+ /// Keeps the last reading's window of any kind this one doesn't report, while that window
+ /// hasn't reset yet (or has no reset time): Claude can send a `rate_limit_event` with only its
+ /// weekly window, and the 5-hour bar shouldn't vanish until the next full report.
+ pub fn keep_unreported(&mut self, last: &[UsageWindow], now: DateTime<Utc>) {
+ for w in last {
+ let reported = self.windows.iter().any(|n| n.kind == w.kind);
+ let live = w.resets_at.is_none_or(|at| at > now);
+ if !reported && live {
+ self.windows.push(w.clone());
+ }
+ }
+ self.windows = sorted(std::mem::take(&mut self.windows));
+ }
+}
+
+/// An account's last reading, as `GET /api/profiles` shows it.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct AccountUsage {
+ pub checked_at: DateTime<Utc>,
+ /// `turn` (read from a bot's turn) or `check` (the person pressed Check now).
+ pub source: String,
+ pub status: Option<String>,
+ pub windows: Vec<UsageWindow>,
+}
+
+impl AccountUsage {
+ pub fn new(reading: UsageReading, source: &str, checked_at: DateTime<Utc>) -> Self {
+ Self { checked_at, source: source.into(), status: reading.status, windows: reading.windows }
+ }
+
+ /// The stored form (`usage_json`): everything but `checked_at`, which has its own column.
+ pub fn to_stored(&self) -> String {
+ serde_json::json!({ "source": self.source, "status": self.status, "windows": self.windows }).to_string()
+ }
+
+ /// Reads a stored row back; `None` for a row this version can't read.
+ pub fn from_stored(json: &str, checked_at: DateTime<Utc>) -> Option<Self> {
+ #[derive(Deserialize)]
+ struct Stored {
+ source: String,
+ status: Option<String>,
+ windows: Vec<UsageWindow>,
+ }
+ let s: Stored = serde_json::from_str(json).ok()?;
+ Some(Self { checked_at, source: s.source, status: s.status, windows: s.windows })
+ }
+}
+
+/// The contract's `status` for Claude's: `allowed` → ok, `allowed_warning` → warning,
+/// `rejected` → out; anything else → `None`.
+pub fn claude_status(raw: &str) -> Option<String> {
+ match raw {
+ "allowed" => Some("ok".into()),
+ "allowed_warning" => Some("warning".into()),
+ "rejected" => Some("out".into()),
+ _ => None,
+ }
+}
+
+/// A fraction (0..1) or percent already (Codex) as 0–100, rounded and clamped.
+fn pct(v: f64) -> u8 {
+ if v.is_finite() {
+ v.round().clamp(0.0, 100.0) as u8
+ } else {
+ 0
+ }
+}
+
+fn epoch(v: &Value) -> Option<DateTime<Utc>> {
+ let secs = v.as_i64().or_else(|| v.as_f64().map(|f| f as i64))?;
+ // Some builds report milliseconds
+ let secs = if secs > 100_000_000_000 { secs / 1000 } else { secs };
+ Utc.timestamp_opt(secs, 0).single()
+}
+
+fn sorted(mut windows: Vec<UsageWindow>) -> Vec<UsageWindow> {
+ windows.sort_by_key(|w| (w.kind != "five_hour") as u8);
+ windows.dedup_by(|a, b| a.kind == b.kind);
+ windows
+}
+
+/// Claude's `{"type":"rate_limit_event","rate_limit_info":{…}}` line, read. `None` when it holds
+/// neither a status nor a window.
+pub fn from_claude_event(line: &Value) -> Option<UsageReading> {
+ let info = &line["rate_limit_info"];
+ let status = info["status"].as_str().and_then(claude_status);
+ let mut windows = Vec::new();
+ for (key, kind) in [("five_hour", "five_hour"), ("seven_day", "weekly")] {
+ let w = &info["unifiedWindows"][key];
+ let Some(used) = w["utilization"].as_f64() else {
+ continue;
+ };
+ windows.push(UsageWindow { kind: kind.into(), used_pct: pct(used * 100.0), resets_at: epoch(&w["resetsAt"]) });
+ }
+ (status.is_some() || !windows.is_empty()).then(|| UsageReading { status, windows: sorted(windows) })
+}
+
+/// The contract's window kind for a Codex window `minutes` long: 300 → five_hour, 10080 →
+/// weekly, anything else dropped.
+pub fn codex_kind(minutes: i64) -> Option<&'static str> {
+ match minutes {
+ 300 => Some("five_hour"),
+ 10080 => Some("weekly"),
+ _ => None,
+ }
+}
+
+/// The `result` of Codex's `account/rateLimits/read` (`{"rateLimits":{"primary":{"usedPercent",
+/// "windowDurationMins","resetsAt"},"secondary":…,"rateLimitReachedType":…},…}`), read. `None`
+/// when it has no window of a known length.
+pub fn from_codex_rate_limits(result: &Value) -> Option<UsageReading> {
+ let limits = &result["rateLimits"];
+ let windows: Vec<UsageWindow> = ["primary", "secondary"]
+ .iter()
+ .filter_map(|k| {
+ let w = &limits[*k];
+ let kind = codex_kind(w["windowDurationMins"].as_i64()?)?;
+ let used = w["usedPercent"].as_f64()?;
+ Some(UsageWindow { kind: kind.into(), used_pct: pct(used), resets_at: epoch(&w["resetsAt"]) })
+ })
+ .collect();
+ if windows.is_empty() {
+ return None;
+ }
+ let reached = !limits["rateLimitReachedType"].is_null() || result["ordinaryUsageAllowed"] == false;
+ let status = if reached || windows.iter().any(|w| w.used_pct >= 100) { "out" } else { "ok" };
+ Some(UsageReading { status: Some(status.into()), windows: sorted(windows) })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// Lines recorded from claude 2.1.323 `-p --output-format stream-json --verbose` (ids blanked).
+ const RECORDED: &str = include_str!("../../tests/fixtures/claude_rate_limit_event.jsonl");
+
+ fn recorded() -> Value {
+ RECORDED.lines().map(|l| serde_json::from_str::<Value>(l).unwrap()).find(|v| v["type"] == "rate_limit_event").unwrap()
+ }
+
+ #[test]
+ fn a_recorded_rate_limit_event_reads_as_two_windows() {
+ let r = from_claude_event(&recorded()).unwrap();
+ assert_eq!(r.status.as_deref(), Some("ok"));
+ assert_eq!(
+ r.windows,
+ vec![
+ UsageWindow { kind: "five_hour".into(), used_pct: 14, resets_at: Utc.timestamp_opt(1794605400, 0).single() },
+ UsageWindow { kind: "weekly".into(), used_pct: 56, resets_at: Utc.timestamp_opt(1794960000, 0).single() },
+ ]
+ );
+ }
+
+ #[test]
+ fn claude_statuses_map_to_the_contract() {
+ assert_eq!(claude_status("allowed").as_deref(), Some("ok"));
+ assert_eq!(claude_status("allowed_warning").as_deref(), Some("warning"));
+ assert_eq!(claude_status("rejected").as_deref(), Some("out"));
+ assert_eq!(claude_status("something_new"), None);
+ let line = serde_json::json!({"type":"rate_limit_event","rate_limit_info":{"status":"allowed_warning","unifiedWindows":{"seven_day":{"utilization":0.826,"resetsAt":1795136340}}}});
+ let r = from_claude_event(&line).unwrap();
+ assert_eq!(r.status.as_deref(), Some("warning"));
+ assert_eq!(r.windows.len(), 1);
+ assert_eq!((r.windows[0].kind.as_str(), r.windows[0].used_pct), ("weekly", 83));
+ }
+
+ #[test]
+ fn a_one_window_event_keeps_the_other_window_until_it_resets() {
+ let now = Utc.timestamp_opt(1794600000, 0).single().unwrap();
+ let both = from_claude_event(&serde_json::json!({"type":"rate_limit_event","rate_limit_info":{"status":"allowed","unifiedWindows":{
+ "five_hour":{"utilization":0.14,"resetsAt":1794605400},"seven_day":{"utilization":0.56,"resetsAt":1794960000}}}}))
+ .unwrap();
+ let weekly_only = serde_json::json!({"type":"rate_limit_event","rate_limit_info":{"status":"allowed_warning","unifiedWindows":{
+ "seven_day":{"utilization":0.83,"resetsAt":1794960000}}}});
+ let mut r = from_claude_event(&weekly_only).unwrap();
+ r.keep_unreported(&both.windows, now);
+ assert_eq!(r.status.as_deref(), Some("warning"));
+ assert_eq!(
+ r.windows,
+ vec![
+ UsageWindow { kind: "five_hour".into(), used_pct: 14, resets_at: Utc.timestamp_opt(1794605400, 0).single() },
+ UsageWindow { kind: "weekly".into(), used_pct: 83, resets_at: Utc.timestamp_opt(1794960000, 0).single() },
+ ]
+ );
+ // A reported window wins over the kept one, and keeping twice adds nothing
+ r.keep_unreported(&both.windows, now);
+ assert_eq!(r.windows.len(), 2);
+ assert_eq!(r.windows[1].used_pct, 83);
+ // Once the 5-hour window has reset, its old numbers are gone
+ let mut r = from_claude_event(&weekly_only).unwrap();
+ r.keep_unreported(&both.windows, Utc.timestamp_opt(1794605400, 0).single().unwrap());
+ assert_eq!(r.windows.iter().map(|w| w.kind.as_str()).collect::<Vec<_>>(), vec!["weekly"]);
+ // A window with no reset time is kept
+ let mut r = UsageReading { status: None, windows: vec![] };
+ r.keep_unreported(&[UsageWindow { kind: "weekly".into(), used_pct: 40, resets_at: None }], now);
+ assert_eq!(r.windows.len(), 1);
+ }
+
+ #[test]
+ fn an_empty_event_is_no_reading() {
+ assert!(from_claude_event(&serde_json::json!({"type":"rate_limit_event","rate_limit_info":{}})).is_none());
+ assert!(from_claude_event(&serde_json::json!({"type":"rate_limit_event"})).is_none());
+ }
+
+ #[test]
+ fn codex_windows_map_by_length_and_others_are_dropped() {
+ let v = serde_json::json!({"rateLimits":{
+ "primary":{"usedPercent":12,"windowDurationMins":300,"resetsAt":1794608940},
+ "secondary":{"usedPercent":40,"windowDurationMins":10080,"resetsAt":1795136340},
+ "rateLimitReachedType":null}});
+ let r = from_codex_rate_limits(&v).unwrap();
+ assert_eq!(r.status.as_deref(), Some("ok"));
+ assert_eq!(r.windows.iter().map(|w| (w.kind.as_str(), w.used_pct)).collect::<Vec<_>>(), vec![("five_hour", 12), ("weekly", 40)]);
+ // Weekly reported first, an odd window dropped, a reached limit is out
+ let v = serde_json::json!({"rateLimits":{
+ "primary":{"usedPercent":100,"windowDurationMins":10080,"resetsAt":null},
+ "secondary":{"usedPercent":3,"windowDurationMins":60},
+ "rateLimitReachedType":"rate_limit_reached"}});
+ let r = from_codex_rate_limits(&v).unwrap();
+ assert_eq!(r.status.as_deref(), Some("out"));
+ assert_eq!(r.windows, vec![UsageWindow { kind: "weekly".into(), used_pct: 100, resets_at: None }]);
+ assert!(from_codex_rate_limits(&serde_json::json!({"rateLimits":{"primary":null}})).is_none());
+ }
+
+ #[test]
+ fn stored_usage_reads_back() {
+ let at = Utc.timestamp_opt(1794600000, 0).single().unwrap();
+ let u = AccountUsage::new(from_claude_event(&recorded()).unwrap(), "turn", at);
+ assert_eq!(AccountUsage::from_stored(&u.to_stored(), at), Some(u.clone()));
+ let v = serde_json::to_value(&u).unwrap();
+ assert_eq!(v["checked_at"], "2026-11-13T20:00:00Z");
+ assert_eq!(v["windows"][0]["resets_at"], "2026-11-13T21:30:00Z");
+ assert!(AccountUsage::from_stored("not json", at).is_none());
+ }
+}
diff --git a/src/server/account_usage.rs b/src/server/account_usage.rs
new file mode 100644
index 00000000..9bd5455b
--- /dev/null
+++ b/src/server/account_usage.rs
@@ -0,0 +1,226 @@
+//! An AI account's 5-hour and weekly limit: kept from each turn's report (Claude's
+//! `rate_limit_event`), and read fresh when the person presses "Check now"
+//! (`POST /api/profiles/:id/usage`). Contract: autonomy/account-usage/brief.md.
+
+use super::{profile_turn, AppState};
+use crate::db::models::{Kwant, LlmProfile};
+use crate::drivers::engines::{choose_model, known_models, Tier};
+use crate::drivers::TurnInput;
+use crate::profiles::usage::{from_codex_rate_limits, AccountUsage, UsageReading};
+use crate::profiles::{CliEnv, Engine};
+use std::time::Duration;
+use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
+
+/// How long one Claude "Reply with OK" may take, container start included.
+const CLAUDE_CHECK_TIMEOUT: Duration = Duration::from_secs(90);
+/// How long Codex's app server may take to answer.
+const CODEX_CHECK_TIMEOUT: Duration = Duration::from_secs(20);
+
+/// Whether this kind of account has 5-hour and weekly windows at all: sign-ins do, API keys
+/// and Custom API servers don't.
+pub fn has_windows(p: &LlmProfile) -> bool {
+ matches!(p.kind.as_str(), "system" | "cli_home")
+ && matches!(Engine::parse(&p.engine), Some(Engine::Claude | Engine::Codex))
+}
+
+/// Saves what a turn or check read for this account. API-key and Custom API accounts keep none.
+pub async fn record(state: &AppState, p: &LlmProfile, mut reading: UsageReading, source: &str) -> Option<AccountUsage> {
+ if !has_windows(p) || reading.windows.is_empty() && reading.status.is_none() {
+ return None;
+ }
+ let now = chrono::Utc::now();
+ if let Ok(Some(last)) = state.db.get_profile_usage(&p.id).await {
+ reading.keep_unreported(&last.windows, now);
+ }
+ let usage = AccountUsage::new(reading, source, now);
+ if let Err(e) = state.db.record_profile_usage(&p.id, &usage).await {
+ tracing::warn!(profile = %p.id, error = %e, "couldn't save account usage");
+ }
+ Some(usage)
+}
+
+/// Why a fresh read gave nothing, in the person's words.
+#[derive(Debug)]
+pub enum CheckError {
+ /// The engine can't report this (an engine without windows).
+ Unsupported(String),
+ /// The read ran and failed or reported no windows.
+ Failed(String),
+}
+
+/// Reads fresh numbers for one account. Claude: one tiny turn of that account, like a normal one.
+/// Codex: its app server's `account/rateLimits/read` (no model call). Saved with source `check`.
+pub async fn check(state: &AppState, p: &LlmProfile) -> Result<AccountUsage, CheckError> {
+ if !has_windows(p) {
+ return Err(CheckError::Unsupported("this account has no 5-hour or weekly limit to show".into()));
+ }
+ let reading = match Engine::parse(&p.engine) {
+ Some(Engine::Claude) => claude(state, p).await?,
+ Some(Engine::Codex) => codex(state, p).await?,
+ _ => return Err(CheckError::Unsupported("this engine doesn't report its limits".into())),
+ };
+ record(state, p, reading, "check")
+ .await
+ .ok_or_else(|| CheckError::Failed("the account reported no limits".into()))
+}
+
+/// One "Reply with OK" turn on the cheapest model, with no tools, through the same driver a
+/// turn of this account uses (its home, env and isolation).
+async fn claude(state: &AppState, p: &LlmProfile) -> Result<UsageReading, CheckError> {
+ let target_model = p.engine.clone();
+ let (key, endpoint) = if p.kind == "system" {
+ (
+ super::routes::get_configured_key(&state.db, &target_model).await,
+ super::routes::get_configured_endpoint(&state.db, &target_model).await,
+ )
+ } else {
+ (None, None)
+ };
+ let (driver, host_engine) = profile_turn::driver_for(state, Some(p), &target_model, key, endpoint)
+ .await
+ .map_err(CheckError::Failed)?;
+ let runs_on = host_engine.or_else(|| profile_turn::profile_engine(p));
+ let model = runs_on
+ .and_then(|e| choose_model(&known_models(&state.engines, e), None, Tier::Fast))
+ .and_then(|c| c.run_id().map(str::to_string));
+ let dir = state.profiles.data_dir.join("tmp").join(format!("usage-check-{}", uuid::Uuid::new_v4().simple()));
+ std::fs::create_dir_all(&dir).map_err(|e| {
+ tracing::warn!(profile = %p.id, error = %e, "usage check: couldn't make a scratch folder");
+ CheckError::Failed("couldn't make a scratch folder for the check".into())
+ })?;
+ let input = TurnInput {
+ thread_id: format!("usage-check-{}", uuid::Uuid::new_v4().simple()),
+ kwant: Kwant {
+ space_id: p.space_id.clone(),
+ id: "usage-check".into(),
+ name: "UsageCheck".into(),
+ title: "Usage check".into(),
+ persona_prompt: "Reply with OK and nothing else.".into(),
+ soul: String::new(),
+ avatar_sprite: String::new(),
+ driver_type: "cli".into(),
+ preferred_model: target_model,
+ temperature: 0.0,
+ max_tokens: 16,
+ level: 1,
+ turns_completed: 0,
+ created_at: None,
+ },
+ prompt: "Reply with OK".into(),
+ history: Vec::new(),
+ model_override: None,
+ model,
+ effort_level: None,
+ team_context: None,
+ workspace_dir: Some(dir.clone()),
+ browser_api_url: None,
+ sandbox_id: None,
+ teammates: Vec::new(),
+ continuity: String::new(),
+ skills: String::new(),
+ person: Default::default(),
+ store: None,
+ mcp: None,
+ no_tools: true,
+ read_only: false,
+ delivery: None,
+ fresh_eyes: true,
+ expects: String::new(),
+ };
+ let (tx, mut rx) = tokio::sync::mpsc::channel(64);
+ let drain = tokio::spawn(async move { while rx.recv().await.is_some() {} });
+ let out = tokio::time::timeout(CLAUDE_CHECK_TIMEOUT, driver.stream_turn(input, tx)).await;
+ drain.abort();
+ let _ = std::fs::remove_dir_all(&dir);
+ let out = match out {
+ Err(_) => return Err(CheckError::Failed(format!("no answer within {} s", CLAUDE_CHECK_TIMEOUT.as_secs()))),
+ Ok(Err(e)) => {
+ tracing::warn!(profile = %p.id, error = %e, "usage check: claude failed");
+ return Err(CheckError::Failed("couldn't run Claude for this account".into()));
+ }
+ Ok(Ok(o)) => o,
+ };
+ if let Some(failure) = &out.failure {
+ // Out of usage or signed out: failover learns it now rather than on the next turn
+ profile_turn::record_failure(state, p, failure).await;
+ }
+ match out.usage_windows {
+ Some(reading) => Ok(reading),
+ None => Err(CheckError::Failed(match &out.failure {
+ Some(f) if f.class == crate::profiles::FailClass::Quota => "the account is out of usage".into(),
+ Some(_) => "the account is signed out".into(),
+ None => "Claude didn't report this account's limits".into(),
+ })),
+ }
+}
+
+/// Codex's windows from `codex app-server`: `initialize`, then `account/rateLimits/read`.
+async fn codex(state: &AppState, p: &LlmProfile) -> Result<UsageReading, CheckError> {
+ let bin = crate::drivers::find_cli_binary("codex")
+ .ok_or_else(|| CheckError::Failed("the codex CLI isn't installed".into()))?;
+ let mut cmd = match state.profiles.home_of(p) {
+ Some(home) => CliEnv::for_home(Engine::Codex, &home).command(bin),
+ None => crate::drivers::cli::cli_command(bin),
+ };
+ cmd.arg("app-server")
+ .env("NO_COLOR", "1")
+ .stdin(std::process::Stdio::piped())
+ .stdout(std::process::Stdio::piped())
+ .stderr(std::process::Stdio::null())
+ .kill_on_drop(true);
+ let read = async move {
+ let mut child = cmd.spawn().map_err(|e| {
+ tracing::warn!(error = %e, "usage check: couldn't start codex");
+ "couldn't start codex".to_string()
+ })?;
+ let mut stdin = child.stdin.take().ok_or("codex has no input")?;
+ let stdout = child.stdout.take().ok_or("codex has no output")?;
+ let requests = [
+ serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"clientInfo":{"name":"kwant","version":env!("CARGO_PKG_VERSION")}}}),
+ serde_json::json!({"jsonrpc":"2.0","method":"initialized"}),
+ serde_json::json!({"jsonrpc":"2.0","id":2,"method":"account/rateLimits/read"}),
+ ];
+ for r in requests {
+ stdin.write_all(format!("{r}\n").as_bytes()).await.map_err(|_| "codex stopped answering")?;
+ }
+ stdin.flush().await.map_err(|_| "codex stopped answering")?;
+ let mut lines = BufReader::new(stdout).lines();
+ while let Some(line) = lines.next_line().await.map_err(|_| "codex stopped answering")? {
+ let Ok(v) = serde_json::from_str::<serde_json::Value>(&line) else { continue };
+ if v["id"] != 2 {
+ continue;
+ }
+ drop(stdin);
+ let _ = child.start_kill();
+ return codex_answer(&v);
+ }
+ Err("codex stopped without answering".to_string())
+ };
+ match tokio::time::timeout(CODEX_CHECK_TIMEOUT, read).await {
+ Err(_) => Err(CheckError::Failed(format!("codex didn't answer within {} s", CODEX_CHECK_TIMEOUT.as_secs()))),
+ Ok(Err(why)) => Err(CheckError::Failed(why)),
+ Ok(Ok(r)) => Ok(r),
+ }
+}
+
+/// The reply to `account/rateLimits/read`, read: its windows, or why there are none.
+fn codex_answer(v: &serde_json::Value) -> Result<UsageReading, String> {
+ if let Some(msg) = v["error"]["message"].as_str() {
+ return Err(if msg.contains("authentication") { "Codex is signed out".into() } else { format!("codex: {msg}") });
+ }
+ from_codex_rate_limits(&v["result"]).ok_or_else(|| "Codex didn't report a 5-hour or weekly limit".into())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_signed_out_codex_says_so() {
+ // Recorded from codex 0.162.1 `app-server` with no login
+ let v = serde_json::json!({"jsonrpc":"2.0","id":2,"error":{"code":-32600,"message":"codex account authentication required to read rate limits"}});
+ assert_eq!(codex_answer(&v).unwrap_err(), "Codex is signed out");
+ let v = serde_json::json!({"id":2,"result":{"rateLimits":{"primary":{"usedPercent":7,"windowDurationMins":300,"resetsAt":1794608940},"secondary":null,"rateLimitReachedType":null}}});
+ assert_eq!(codex_answer(&v).unwrap().windows[0].used_pct, 7);
+ }
+}
diff --git a/src/server/mod.rs b/src/server/mod.rs
index f3b3ac6b..14e42cd1 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -9,6 +9,7 @@ pub mod mcp_routes;
pub mod mcp_runtime;
pub mod profile_routes;
pub mod profile_turn;
+pub mod account_usage;
pub mod engine_routes;
pub mod engine_login;
pub mod auth;
@@ -258,6 +259,7 @@ pub fn create_router(state: AppState) -> Router {
.route("/api/profiles/:id", axum::routing::patch(profile_routes::update).delete(profile_routes::remove))
.route("/api/profiles/:id/key", put(profile_routes::set_key).delete(profile_routes::delete_key))
.route("/api/profiles/:id/check", post(profile_routes::check))
+ .route("/api/profiles/:id/usage", post(profile_routes::usage))
.route("/api/profiles/:id/login", post(profile_routes::start_login))
.route(
"/api/profiles/:id/login/:flow_id",
diff --git a/src/server/profile_routes.rs b/src/server/profile_routes.rs
index 5a875770..55638c03 100644
--- a/src/server/profile_routes.rs
+++ b/src/server/profile_routes.rs
@@ -59,6 +59,9 @@ pub struct ProfileOut {
pub last_error: Option<String>,
/// A Custom API account's server and last check; `None` for every other kind.
pub custom: Option<CustomOut>,
+ /// The account's 5-hour and weekly limits as last read; `None` before the first reading,
+ /// and always for API-key and Custom API accounts.
+ pub usage: Option<crate::profiles::usage::AccountUsage>,
}
/// A Custom API account's server, as the API shows it (never its key).
@@ -120,6 +123,7 @@ pub(super) async fn views(state: &AppState, profiles: Vec<LlmProfile>) -> Vec<Pr
let own_keys = state.db.profile_ids_with_key().await.unwrap_or_default();
let keyed = keyed_ids(state, &profiles).await;
let states = state.db.list_profile_states().await.unwrap_or_default();
+ let mut usage = state.db.list_profile_usage().await.unwrap_or_default();
let statuses = state.profiles.statuses(&profiles, &keyed).await;
profiles
.into_iter()
@@ -141,6 +145,7 @@ pub(super) async fn views(state: &AppState, profiles: Vec<LlmProfile>) -> Vec<Pr
}
});
ProfileOut {
+ usage: usage.remove(&p.id).filter(|_| super::account_usage::has_windows(&p)),
custom,
home_dir: state
.profiles
@@ -515,6 +520,38 @@ pub async fn check(State(state): State<AppState>, Path(id): Path<String>) -> Res
view_of(&state, &id).await
}
+/// `POST /api/profiles/:id/usage`: reads fresh 5-hour and weekly numbers for a Claude or Codex
+/// sign-in and returns its `usage`. At most once a minute per account: a press within the minute
+/// returns the last reading (429 when there is none yet). Never called on a timer.
+pub async fn usage(State(state): State<AppState>, Path(id): Path<String>) -> Response {
+ let p = match load(&state, &id).await {
+ Ok(p) => p,
+ Err(r) => return r,
+ };
+ if !super::account_usage::has_windows(&p) {
+ return err(StatusCode::BAD_REQUEST, "only Claude and Codex sign-ins have 5-hour and weekly limits");
+ }
+ if !state.profiles.claim_usage_check(&id) {
+ let last = state.db.get_profile_usage(&id).await.ok().flatten();
+ return match last {
+ Some(u) => Json(u).into_response(),
+ None => {
+ let mut r = err(StatusCode::TOO_MANY_REQUESTS, "checked less than a minute ago; try again shortly");
+ r.headers_mut().insert(
+ axum::http::header::RETRY_AFTER,
+ axum::http::HeaderValue::from(crate::profiles::usage::CHECK_EVERY.as_secs()),
+ );
+ r
+ }
+ };
+ }
+ match super::account_usage::check(&state, &p).await {
+ Ok(u) => Json(u).into_response(),
+ Err(super::account_usage::CheckError::Unsupported(why)) => err(StatusCode::BAD_REQUEST, why),
+ Err(super::account_usage::CheckError::Failed(why)) => err(StatusCode::BAD_GATEWAY, why),
+ }
+}
+
/// `DELETE /api/profiles/:id/key`
pub async fn delete_key(State(state): State<AppState>, Path(id): Path<String>) -> Response {
if let Err(r) = load(&state, &id).await {
diff --git a/src/server/routes.rs b/src/server/routes.rs
index cc06d698..c59359bb 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -3693,6 +3693,12 @@ async fn run_kwant_turn_inner(
break;
}
let result = driver_task.await;
+ // The account's 5-hour/weekly windows, when the engine reported them (refused turns too)
+ if let (Some(p), Ok(Ok(out))) = (profile, &result) {
+ if let Some(reading) = out.usage_windows.clone() {
+ super::account_usage::record(state, p, reading, "turn").await;
+ }
+ }
// Isolated Claude didn't start, or hit its request cap: the notice is the turn's end,
// saved like a stall (a kwant message with meta), never another account or this computer
if let Ok(Ok(out)) = &result {
@@ -3783,7 +3789,7 @@ async fn run_kwant_turn_inner(
}
if let Some(p) = profile {
if had_state.contains_key(&p.id) && matches!(result, Ok(Ok(_))) {
- let _ = state.db.clear_profile_state(&p.id).await;
+ let _ = state.db.clear_profile_failure(&p.id).await;
}
}
// Sent once the failure is saved, so the chat it refreshes already shows it
diff --git a/tests/account_usage_test.rs b/tests/account_usage_test.rs
new file mode 100644
index 00000000..11bc47bf
--- /dev/null
+++ b/tests/account_usage_test.rs
@@ -0,0 +1,283 @@
+//! Each Claude sign-in's 5-hour and weekly limit: kept from its turns, read fresh at most once a
+//! minute on "Check now", and shown as `usage` on `GET /api/profiles`. A fake claude CLI on PATH
+//! prints a `rate_limit_event` like the real one. Its own test binary: it changes PATH.
+
+#[path = "common/exe.rs"]
+mod exe;
+
+use axum::{
+ body::{to_bytes, Body},
+ http::{Request, StatusCode},
+ Router,
+};
+use kwnt::{
+ broker::PermissionBroker,
+ config::Config,
+ db::Database,
+ drivers::RuntimeEvent,
+ router::LayaRouter,
+ server::{create_router, AppState},
+ tools::ToolRunner,
+};
+use serde_json::{json, Value};
+use std::path::{Path, PathBuf};
+use std::time::Duration;
+use tower::ServiceExt;
+
+/// `util`, `status`, `no-usage` and `out-of-usage` in the profile's home steer what it reports;
+/// every model call adds a line to `calls`.
+const FAKE_CLAUDE: &str = r#"#!/bin/sh
+if [ "$1" = --settings ]; then shift 2; fi
+case "$1" in
+ auth) echo '{"loggedIn":true,"email":"[email protected]"}'; exit 0 ;;
+esac
+h="$CLAUDE_CONFIG_DIR"
+echo "call" >> "$h/calls"
+util=$(cat "$h/util" 2>/dev/null || echo 0.14)
+st=$(cat "$h/status" 2>/dev/null || echo allowed)
+echo '{"type":"system","subtype":"init","tools":[],"mcp_servers":[]}'
+if [ ! -f "$h/no-usage" ]; then
+ echo '{"type":"rate_limit_event","rate_limit_info":{"status":"'"$st"'","resetsAt":1794605400,"rateLimitType":"five_hour","unifiedWindows":{"five_hour":{"utilization":'"$util"',"resetsAt":1794605400,"status":"'"$st"'"},"seven_day":{"utilization":0.56,"resetsAt":1794960000,"status":"allowed"}}}}'
+fi
+if [ -f "$h/out-of-usage" ]; then
+ echo '{"type":"result","is_error":true,"num_turns":1,"result":"Claude AI usage limit reached|'"$FAKE_RESET"'"}'
+ exit 1
+fi
+echo '{"type":"result","is_error":false,"num_turns":1,"result":"OK","usage":{"input_tokens":3,"output_tokens":1}}'
+"#;
+
+async fn call(app: &Router, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value, Option<String>) {
+ let resp = app
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method(method)
+ .uri(uri)
+ .header("content-type", "application/json")
+ .body(body.map(|v| Body::from(v.to_string())).unwrap_or_else(Body::empty))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ let s = resp.status();
+ let retry = resp.headers().get("retry-after").and_then(|v| v.to_str().ok()).map(str::to_string);
+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ (s, serde_json::from_slice(&bytes).unwrap_or(Value::Null), retry)
+}
+
+async fn run_turn(app: &Router, state: &AppState, kwant_id: &str) {
+ let mut rx = state.event_sender.subscribe();
+ let (s, v, _) = call(app, "POST", "/api/chat/send", Some(json!({"kwant_id": kwant_id, "prompt": "hi", "sender_id": "user"}))).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ tokio::time::timeout(Duration::from_secs(60), async {
+ while let Ok(e) = rx.recv().await {
+ if matches!(e.unscoped(), RuntimeEvent::TurnEnded { kwant_id: k, .. } if k == kwant_id) {
+ break;
+ }
+ }
+ })
+ .await
+ .expect("turn did not end");
+}
+
+async fn profile(app: &Router, id: &str) -> Value {
+ let (_, all, _) = call(app, "GET", "/api/profiles", None).await;
+ all.as_array().unwrap().iter().find(|p| p["id"] == id).cloned().unwrap()
+}
+
+fn calls(home: &Path) -> usize {
+ std::fs::read_to_string(home.join("calls")).map(|s| s.lines().count()).unwrap_or(0)
+}
+
+#[tokio::test]
+async fn usage_is_kept_from_turns_and_checked_at_most_once_a_minute() {
+ let tmp = tempfile::tempdir().unwrap();
+ let bin = tmp.path().join("bin");
+ std::fs::create_dir_all(&bin).unwrap();
+ exe::write_executable(bin.join("claude"), FAKE_CLAUDE);
+ std::env::set_var("PATH", format!("{}:{}", bin.display(), std::env::var("PATH").unwrap_or_default()));
+ std::env::set_var("FAKE_RESET", (chrono::Utc::now().timestamp() + 2 * 3600).to_string());
+
+ let data = tmp.path().join("data");
+ let db = Database::init(&data).await.unwrap();
+ let config = Config {
+ data_dir: data.clone(),
+ laya_url: "http://127.0.0.1:9".into(),
+ browser_cdp_url: Some("http://127.0.0.1:9".into()),
+ ..Config::default()
+ };
+ let state = AppState::new(
+ config.clone(),
+ db,
+ ToolRunner::new(data.join("workspace")),
+ PermissionBroker::new(),
+ LayaRouter::new(config.laya_url.clone()),
+ );
+ let app = create_router(state.clone());
+
+ let (_, work, _) = call(&app, "POST", "/api/profiles", Some(json!({"engine": "claude", "name": "Work", "kind": "cli_home", "is_default": true, "priority": 1}))).await;
+ let (_, personal, _) = call(&app, "POST", "/api/profiles", Some(json!({"engine": "claude", "name": "Personal", "kind": "cli_home", "priority": 2}))).await;
+ let (s, _, _) = call(&app, "PATCH", "/api/profiles/prf_system_claude", Some(json!({"enabled": false}))).await;
+ assert_eq!(s, StatusCode::OK);
+ let work_id = work["id"].as_str().unwrap().to_string();
+ let personal_id = personal["id"].as_str().unwrap().to_string();
+ let work_home = PathBuf::from(work["home_dir"].as_str().unwrap());
+ let personal_home = PathBuf::from(personal["home_dir"].as_str().unwrap());
+ std::fs::create_dir_all(&work_home).unwrap();
+ std::fs::create_dir_all(&personal_home).unwrap();
+ std::fs::write(personal_home.join("no-usage"), "").unwrap();
+
+ // No reading yet: null
+ assert_eq!(profile(&app, &work_id).await["usage"], Value::Null);
+
+ let (_, kwants, _) = call(&app, "GET", "/api/kwants", None).await;
+ let k = kwants[0].clone();
+ let kid = k["id"].as_str().unwrap().to_string();
+ let mut body = k.clone();
+ body.as_object_mut()
+ .unwrap()
+ .retain(|key, _| ["name", "title", "persona_prompt", "soul", "avatar_sprite"].contains(&key.as_str()));
+ body["preferred_model"] = json!("claude");
+ let (s, v, _) = call(&app, "PUT", &format!("/api/kwants/{kid}"), Some(body)).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+
+ // 1. A turn keeps the account's windows
+ run_turn(&app, &state, &kid).await;
+ let u = profile(&app, &work_id).await["usage"].clone();
+ assert_eq!(u["source"], "turn", "{u}");
+ assert_eq!(u["status"], "ok");
+ assert_eq!(
+ u["windows"],
+ json!([
+ {"kind": "five_hour", "used_pct": 14, "resets_at": "2026-11-13T21:30:00Z"},
+ {"kind": "weekly", "used_pct": 56, "resets_at": "2026-11-18T00:00:00Z"}
+ ])
+ );
+ assert!(u["checked_at"].as_str().unwrap().ends_with('Z'));
+
+ // 2. Check now reads it fresh: allowed_warning shows as warning
+ std::fs::write(work_home.join("util"), "0.904").unwrap();
+ std::fs::write(work_home.join("status"), "allowed_warning").unwrap();
+ let before = calls(&work_home);
+ let (s, first, _) = call(&app, "POST", &format!("/api/profiles/{work_id}/usage"), None).await;
+ assert_eq!(s, StatusCode::OK, "{first}");
+ assert_eq!(calls(&work_home), before + 1);
+ assert_eq!(first["source"], "check");
+ assert_eq!(first["status"], "warning");
+ assert_eq!(first["windows"][0], json!({"kind": "five_hour", "used_pct": 90, "resets_at": "2026-11-13T21:30:00Z"}));
+ assert_eq!(profile(&app, &work_id).await["usage"], first);
+
+ // 3. A second press within the minute returns that reading and makes no call
+ std::fs::write(work_home.join("util"), "0.99").unwrap();
+ let (s, again, _) = call(&app, "POST", &format!("/api/profiles/{work_id}/usage"), None).await;
+ assert_eq!(s, StatusCode::OK, "{again}");
+ assert_eq!(again, first);
+ assert_eq!(calls(&work_home), before + 1);
+
+ // 4. An account that reports nothing: the read fails, and a press within the minute waits
+ let (s, v, _) = call(&app, "POST", &format!("/api/profiles/{personal_id}/usage"), None).await;
+ assert_eq!(s, StatusCode::BAD_GATEWAY, "{v}");
+ let n = calls(&personal_home);
+ let (s, _, retry) = call(&app, "POST", &format!("/api/profiles/{personal_id}/usage"), None).await;
+ assert_eq!(s, StatusCode::TOO_MANY_REQUESTS);
+ assert_eq!(retry.as_deref(), Some("60"));
+ assert_eq!(calls(&personal_home), n);
+ assert_eq!(profile(&app, &personal_id).await["usage"], Value::Null);
+
+ // 5. A refused turn still keeps its windows: rejected shows as out, next to "out of usage"
+ std::fs::write(work_home.join("status"), "rejected").unwrap();
+ std::fs::write(work_home.join("util"), "1").unwrap();
+ std::fs::write(work_home.join("out-of-usage"), "").unwrap();
+ run_turn(&app, &state, &kid).await;
+ let w = profile(&app, &work_id).await;
+ assert!(w["limited_until"].is_string(), "{w}");
+ assert_eq!(w["usage"]["source"], "turn");
+ assert_eq!(w["usage"]["status"], "out");
+ assert_eq!(w["usage"]["windows"][0]["used_pct"], 100);
+
+ // 6. API-key accounts have no windows: no usage, and Check now is refused
+ let (s, key, _) = call(
+ &app,
+ "POST",
+ "/api/profiles",
+ Some(json!({"engine": "claude", "name": "Work API", "kind": "api_key", "api_key": "sk-ant-api03-0123456789abcdef"})),
+ )
+ .await;
+ assert_eq!(s, StatusCode::CREATED, "{key}");
+ let key_id = key["id"].as_str().unwrap();
+ assert_eq!(profile(&app, key_id).await["usage"], Value::Null);
+ let (s, _, _) = call(&app, "POST", &format!("/api/profiles/{key_id}/usage"), None).await;
+ assert_eq!(s, StatusCode::BAD_REQUEST);
+ let (s, _, _) = call(&app, "POST", "/api/profiles/prf_nope/usage", None).await;
+ assert_eq!(s, StatusCode::NOT_FOUND);
+}
+
+/// A served turn forgets the account's failure but keeps its usage; a new sign-in forgets both.
+#[tokio::test]
+async fn clearing_a_failure_keeps_the_usage_reading() {
+ use kwnt::profiles::usage::{AccountUsage, UsageReading, UsageWindow};
+ let tmp = tempfile::tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ let id = "prf_system_claude";
+ let reading = UsageReading {
+ status: Some("out".into()),
+ windows: vec![UsageWindow { kind: "five_hour".into(), used_pct: 100, resets_at: None }],
+ };
+ let at = chrono::Utc::now();
+ let usage = AccountUsage::new(reading, "turn", chrono::DateTime::from_timestamp(at.timestamp(), 0).unwrap());
+ db.record_profile_failure(id, "quota", Some(at + chrono::Duration::hours(1))).await.unwrap();
+ db.record_profile_usage(id, &usage).await.unwrap();
+ assert!(db.list_profile_states().await.unwrap().contains_key(id));
+ assert_eq!(db.list_profile_usage().await.unwrap().get(id), Some(&usage));
+
+ db.clear_profile_failure(id).await.unwrap();
+ assert!(db.list_profile_states().await.unwrap().is_empty(), "a usage-only row is no failure");
+ assert_eq!(db.list_profile_usage().await.unwrap().get(id), Some(&usage));
+
+ // A new failure leaves the reading alone too
+ db.record_profile_failure(id, "auth", None).await.unwrap();
+ assert_eq!(db.list_profile_usage().await.unwrap().get(id), Some(&usage));
+
+ db.clear_profile_state(id).await.unwrap();
+ assert!(db.list_profile_usage().await.unwrap().is_empty());
+}
+
+/// D1: Claude can report one window alone (a weekly-only warning). The other bar stays, with its
+/// last numbers, until it resets; a window past its reset time is dropped.
+#[tokio::test]
+async fn a_one_window_turn_keeps_the_other_bar() {
+ use kwnt::profiles::usage::{UsageReading, UsageWindow};
+ use kwnt::server::account_usage::record;
+ let tmp = tempfile::tempdir().unwrap();
+ let data = tmp.path().join("data");
+ let db = Database::init(&data).await.unwrap();
+ let config = Config { data_dir: data.clone(), laya_url: "http://127.0.0.1:9".into(), ..Config::default() };
+ let state = AppState::new(
+ config.clone(),
+ db,
+ ToolRunner::new(data.join("workspace")),
+ PermissionBroker::new(),
+ LayaRouter::new(config.laya_url.clone()),
+ );
+ let app = create_router(state.clone());
+ let p = state.db.get_profile("prf_system_claude").await.unwrap().expect("the built-in Claude account");
+ let at = |h: i64| chrono::DateTime::from_timestamp(chrono::Utc::now().timestamp() + h * 3600, 0);
+ let window = |kind: &str, used_pct: u8, resets_at| UsageWindow { kind: kind.into(), used_pct, resets_at };
+
+ let both = UsageReading { status: Some("ok".into()), windows: vec![window("five_hour", 14, at(2)), window("weekly", 56, at(90))] };
+ record(&state, &p, both, "turn").await.unwrap();
+ let weekly_only = UsageReading { status: Some("warning".into()), windows: vec![window("weekly", 83, at(90))] };
+ record(&state, &p, weekly_only, "turn").await.unwrap();
+ let u = profile(&app, &p.id).await["usage"].clone();
+ assert_eq!(u["status"], "warning", "{u}");
+ assert_eq!(u["windows"].as_array().unwrap().len(), 2, "{u}");
+ assert_eq!((u["windows"][0]["kind"].as_str(), u["windows"][0]["used_pct"].as_u64()), (Some("five_hour"), Some(14)));
+ assert_eq!((u["windows"][1]["kind"].as_str(), u["windows"][1]["used_pct"].as_u64()), (Some("weekly"), Some(83)));
+
+ // A 5-hour window past its reset time isn't carried over
+ let stale = UsageReading { status: Some("ok".into()), windows: vec![window("five_hour", 99, at(-1)), window("weekly", 60, at(90))] };
+ record(&state, &p, stale, "turn").await.unwrap();
+ record(&state, &p, UsageReading { status: Some("ok".into()), windows: vec![window("weekly", 61, at(90))] }, "turn").await.unwrap();
+ let u = profile(&app, &p.id).await["usage"].clone();
+ assert_eq!(u["windows"], json!([{"kind": "weekly", "used_pct": 61, "resets_at": u["windows"][0]["resets_at"]}]), "{u}");
+}
diff --git a/tests/fixtures/claude_rate_limit_event.jsonl b/tests/fixtures/claude_rate_limit_event.jsonl
new file mode 100644
index 00000000..0c604427
--- /dev/null
+++ b/tests/fixtures/claude_rate_limit_event.jsonl
@@ -0,0 +1,3 @@
+{"type":"system","subtype":"init","tools":[],"mcp_servers":[],"session_id":"00000000-0000-0000-0000-000000000001"}
+{"type":"rate_limit_event","rate_limit_info":{"status":"allowed","resetsAt":1794605400,"rateLimitType":"five_hour","overageStatus":"rejected","overageDisabledReason":"org_level_disabled","isUsingOverage":false,"unifiedWindows":{"five_hour":{"utilization":0.14,"resetsAt":1794605400,"status":"allowed"},"seven_day":{"utilization":0.56,"resetsAt":1794960000,"status":"allowed"}}},"uuid":"00000000-0000-0000-0000-000000000002","session_id":"00000000-0000-0000-0000-000000000001"}
+{"type":"result","subtype":"success","is_error":false,"num_turns":1,"result":"OK","usage":{"input_tokens":2,"cache_creation_input_tokens":6113,"cache_read_input_tokens":13713,"output_tokens":4},"total_cost_usd":0.00136,"session_id":"00000000-0000-0000-0000-000000000001"}