From 53abea3bdca8b9d1e0aa7cd2acb7064d95d2a09f Mon Sep 17 00:00:00 2001 From: Angel-Mario Savin Date: Wed, 18 Nov 2026 10:50:28 +0200 Subject: [PATCH 1/3] Show Codex's 5-hour and 7-day limits in the sidebar when Codex subagents are on --- README.md | 2 +- src/app/headless.rs | 10 +++ src/app/ingest.rs | 19 +++-- src/app/mod.rs | 4 + src/claude/codex_limits.rs | 160 +++++++++++++++++++++++++++++++++++++ src/claude/mod.rs | 4 +- src/datadir.rs | 2 + src/panels/sidebar.rs | 28 +++++-- src/panels/theme.rs | 2 + src/panels/widgets.rs | 5 +- 10 files changed, 220 insertions(+), 16 deletions(-) create mode 100644 src/claude/codex_limits.rs diff --git a/README.md b/README.md index 5e224ab..2bfe319 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ Claudiu is a native desktop app, written in Rust with [Rune](https://github.com/ ## What it does -Each session is your own `claude` process in a real terminal, and sign-in stays with Claude Code. Around it, Claudiu adds a sidebar of running and recent sessions, notifications when a background session finishes or asks something, an editor mode (Ctrl+Shift+E), usage meters, a GitHub pane, cards Claude draws inline, sessions that move between git worktrees, extra accounts that share one configuration, and Codex and OpenCode subagents (Settings → Custom subagents). Codex subagents need Node and a `codex login`, OpenCode subagents need `opencode` on PATH, and with Allow edits on, either acts without Claude Code's permission rules. Settings lists the rest. +Each session is your own `claude` process in a real terminal, and sign-in stays with Claude Code. Around it, Claudiu adds a sidebar of running and recent sessions, notifications when a background session finishes or asks something, an editor mode (Ctrl+Shift+E), usage meters, a GitHub pane, cards Claude draws inline, sessions that move between git worktrees, extra accounts that share one configuration, and Codex and OpenCode subagents (Settings → Custom subagents). Codex subagents need Node and a `codex login`, OpenCode subagents need `opencode` on PATH, and with Allow edits on, either acts without Claude Code's permission rules. With Codex subagents on, the sidebar also shows Codex's 5-hour and 7-day limits, which Claudiu reads from the session logs in `~/.codex`. Settings lists the rest. ## What it touches diff --git a/src/app/headless.rs b/src/app/headless.rs index 96de8c2..b339536 100644 --- a/src/app/headless.rs +++ b/src/app/headless.rs @@ -215,6 +215,16 @@ fn the_workspace_draws_and_its_controls_answer() { } /// Sessions and the shell under them, the sidebars' widths, cards and the GitHub view, with a stand-in `claude`. +#[test] +fn codex_limits_show_only_with_codex_subagents_on() { + let mut h = Harness::new(|_| vec![]); + let limit = crate::store::RateLimit { utilization: Some(0.24), resets_at: Some(now() + 3600), seen_at: now() }; + h.step(|ws| ws.codex_usage = Some(crate::store::AccountUsage { five_hour: Some(limit.clone()), seven_day: Some(limit) })); + assert!(h.drawn("meter-5h") && !h.drawn("meter-codex-5h"), "Codex subagents are off: {:?}", h.keys()); + h.step(|ws| ws.store.data.settings.custom_subagents.codex.on = true); + assert!(h.drawn("meter-codex-5h") && h.drawn("meter-codex-7d"), "Codex's row draws under Claude's: {:?}", h.keys()); +} + #[test] fn sessions_and_the_shell_panel() { let mut h = Harness::new(|_| vec![]); diff --git a/src/app/ingest.rs b/src/app/ingest.rs index 5e33758..9b584e7 100644 --- a/src/app/ingest.rs +++ b/src/app/ingest.rs @@ -4,16 +4,25 @@ use super::*; use crate::store::RateLimit; +use crate::claude::codex_limits; use crate::claude::usage::Snapshot; impl Workspace { - /// Costs no tokens; the files are tiny. + /// Costs no tokens. The mod's files are tiny; a Codex log costs under 1 MiB of reading. pub(super) fn ingest_usage(&mut self) { + let codex_on = self.store.data.settings.custom_subagents.codex.on; self.rt.spawn_quietly( - move || { (usage::read_snapshots(&usage::snapshot_dir()), mcp::read_attached()) }, - move |ws: &mut Workspace, (snaps, items)| { - let mut changed = false; - changed |= snaps.iter().fold(false, |c, snap| ws.apply_snapshot(snap) | c); + move || { + let codex = if codex_on { codex_limits::codex_home().and_then(|home| codex_limits::read(&home)) } else { None }; + (usage::read_snapshots(&usage::snapshot_dir()), mcp::read_attached(), codex) + }, + move |ws: &mut Workspace, (snaps, items, codex)| { + // A new Codex session has no reading until its first turn; the last one stays until then. + if codex.is_some() && ws.codex_usage != codex { + ws.codex_usage = codex; + ws.rt.dirty = true; + } + let mut changed = snaps.iter().fold(false, |c, snap| ws.apply_snapshot(snap) | c); changed |= items.into_iter().fold(false, |c, (stem, item)| ws.apply_attachment(&stem, item) | c); if changed { ws.store.mark_dirty(); diff --git a/src/app/mod.rs b/src/app/mod.rs index d8f7b0f..24ddc0b 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -483,6 +483,9 @@ pub struct Workspace { pub worktrees_page: worktrees::WorktreesPage, /// Whether the Custom subagents page is asking each agent for its models. Not saved to disk. pub model_lookups: settings::ModelLookups, + /// Codex's own limits from its session logs (`claude/codex_limits.rs`); the sidebar shows them under Claude's. + /// Not saved to disk: the logs are read again on start. + pub codex_usage: Option, pub menu: Option, pub menu_serial: u64, pub toast: Option, @@ -577,6 +580,7 @@ impl Workspace { settings_page: SettingsPage::default(), worktrees_page: Default::default(), model_lookups: Default::default(), + codex_usage: None, menu: None, menu_serial: 0, toast: None, diff --git a/src/claude/codex_limits.rs b/src/claude/codex_limits.rs new file mode 100644 index 0000000..fd03fbd --- /dev/null +++ b/src/claude/codex_limits.rs @@ -0,0 +1,160 @@ +//! Codex's 5-hour and 7-day limits, read from the session logs Codex writes under `$CODEX_HOME/sessions` (default +//! `~/.codex`). Each turn Codex logs a `token_count` event carrying its current `rate_limits`; the newest one is the +//! reading. Read-only, no network, no tokens. The log format is Codex's own and undocumented, so anything that doesn't +//! parse is skipped and the sidebar shows no Codex row. + +use std::path::{Path, PathBuf}; + +use serde_json::Value; + +use crate::store::{AccountUsage, RateLimit}; + +/// Codex files a log under the day its session started, so a session still running from yesterday writes into +/// yesterday's folder. Looking at the last few days finds it. +const DAYS_TO_LOOK_AT: usize = 3; +/// Logs tried, newest first, before giving up: a session that hasn't finished a turn yet has no reading. Kept small +/// because every try reads up to 896 KiB, every few seconds, and a sign-in by API key never logs a reading. +const LOGS_TO_TRY: usize = 3; + +pub fn codex_home() -> Option { + match std::env::var_os("CODEX_HOME") { + Some(dir) if !dir.is_empty() => Some(PathBuf::from(dir)), + _ => crate::platform::home_dir().map(|h| h.join(".codex")), + } +} + +/// The newest limits Codex logged, or `None` when there are none to read. +pub fn read(codex_home: &Path) -> Option { + newest_logs(&codex_home.join("sessions")).iter().find_map(|log| read_log(log)) +} + +/// Rollout logs in the last few `YYYY/MM/DD` folders, most recently written first. +fn newest_logs(sessions: &Path) -> Vec { + let days: Vec = subdirs_newest_first(sessions) + .into_iter() + .flat_map(|year| subdirs_newest_first(&year)) + .flat_map(|month| subdirs_newest_first(&month)) + .take(DAYS_TO_LOOK_AT) + .collect(); + let mut logs: Vec<(std::time::SystemTime, PathBuf)> = days + .iter() + .filter_map(|day| std::fs::read_dir(day).ok()) + .flat_map(|entries| entries.flatten()) + .filter(|e| e.path().extension().and_then(|x| x.to_str()) == Some("jsonl")) + .filter_map(|e| Some((e.metadata().ok()?.modified().ok()?, e.path()))) + .collect(); + logs.sort_by_key(|(modified, _)| std::cmp::Reverse(*modified)); + logs.into_iter().take(LOGS_TO_TRY).map(|(_, path)| path).collect() +} + +/// Folder names are zero-padded numbers, so sorting by name sorts by date. Walking stays lazy: only the newest years +/// and months are opened. +fn subdirs_newest_first(dir: &Path) -> Vec { + let Ok(entries) = std::fs::read_dir(dir) else { return vec![] }; + let mut dirs: Vec = entries.flatten().map(|e| e.path()).filter(|p| p.is_dir()).collect(); + dirs.sort_by(|a, b| b.cmp(a)); + dirs +} + +fn read_log(path: &Path) -> Option { + let (head, tail, whole, _, _) = super::read_chunks(path).ok()?; + let text = if whole { head } else { tail }; + text.lines().rev().filter(|line| line.contains("\"rate_limits\"")).find_map(parse_line) +} + +fn parse_line(line: &str) -> Option { + let v: Value = serde_json::from_str(line).ok()?; + let payload = v.get("payload")?; + if payload.get("type")?.as_str()? != "token_count" { + return None; + } + let limits = payload.get("rate_limits")?; + // One log line carries one bucket; only the `codex` bucket is the account's plan limit. + if limits.get("limit_id").and_then(Value::as_str).is_some_and(|id| id != "codex") { + return None; + } + let seen_at = super::parse_rfc3339(v.get("timestamp")?.as_str()?)?; + let mut usage = AccountUsage::default(); + for window in [limits.get("primary"), limits.get("secondary")].into_iter().flatten() { + let Some(minutes) = window.get("window_minutes").and_then(Value::as_i64) else { continue }; + let limit = RateLimit { + utilization: window.get("used_percent").and_then(Value::as_f64).map(|p| (p / 100.0) as f32), + resets_at: window.get("resets_at").and_then(Value::as_i64), + seen_at, + }; + match minutes { + 300 => usage.five_hour = Some(limit), + 10080 => usage.seven_day = Some(limit), + _ => {} + } + } + (usage.five_hour.is_some() || usage.seven_day.is_some()).then_some(usage) +} + +#[cfg(test)] +mod tests { + use super::*; + + // The shape Codex writes, trimmed of the token counts. + const READING: &str = r#"{"timestamp":"2026-11-18T07:54:11.728Z","type":"event_msg","payload":{"type":"token_count","info":{},"rate_limits":{"limit_id":"codex","limit_name":null,"primary":{"used_percent":24.0,"window_minutes":300,"resets_at":1794999616},"secondary":{"used_percent":19.0,"window_minutes":10080,"resets_at":1795510335},"credits":{"has_credits":false,"unlimited":false,"balance":"0"},"plan_type":"plus"}}}"#; + const SEEN_AT: i64 = 1_794_988_451; + + fn write_log(home: &Path, day: &str, name: &str, lines: &[&str]) -> PathBuf { + let dir = home.join("sessions").join(day); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join(name); + std::fs::write(&path, lines.join("\n")).unwrap(); + path + } + + #[test] + fn reads_both_windows_from_a_token_count_event() { + let home = tempfile::tempdir().unwrap(); + write_log(home.path(), "2026/11/18", "rollout-a.jsonl", &[r#"{"type":"session_meta","payload":{}}"#, READING]); + let usage = read(home.path()).unwrap(); + assert_eq!(usage.five_hour, Some(RateLimit { utilization: Some(0.24), resets_at: Some(1794999616), seen_at: SEEN_AT })); + assert_eq!(usage.seven_day, Some(RateLimit { utilization: Some(0.19), resets_at: Some(1795510335), seen_at: SEEN_AT })); + } + + #[test] + fn a_later_event_without_limits_does_not_hide_the_earlier_reading() { + let home = tempfile::tempdir().unwrap(); + let without = r#"{"timestamp":"2026-11-18T08:00:00Z","type":"event_msg","payload":{"type":"token_count","info":{},"rate_limits":null}}"#; + write_log(home.path(), "2026/11/18", "rollout-a.jsonl", &[READING, without, "not json"]); + assert_eq!(read(home.path()).unwrap().five_hour.unwrap().seen_at, SEEN_AT); + } + + #[test] + fn nothing_readable_gives_none() { + let home = tempfile::tempdir().unwrap(); + assert_eq!(read(home.path()), None, "no sessions folder"); + write_log(home.path(), "2026/11/18", "rollout-a.jsonl", &["garbage \"rate_limits\"", r#"{"payload":{"type":"token_count","rate_limits":{}}}"#]); + assert_eq!(read(home.path()), None); + } + + #[test] + fn unknown_windows_and_other_buckets_are_ignored() { + let home = tempfile::tempdir().unwrap(); + let odd_window = READING.replace("\"window_minutes\":300", "\"window_minutes\":60"); + let other_bucket = READING.replace("\"limit_id\":\"codex\"", "\"limit_id\":\"codex_other\""); + write_log(home.path(), "2026/11/18", "rollout-a.jsonl", &[&odd_window, &other_bucket]); + let usage = read(home.path()).unwrap(); + assert_eq!(usage.five_hour, None); + assert!(usage.seven_day.is_some()); + } + + #[test] + fn a_session_started_on_an_earlier_day_still_counts() { + let home = tempfile::tempdir().unwrap(); + let older = write_log(home.path(), "2026/11/17", "rollout-old.jsonl", &[READING]); + let newer = write_log(home.path(), "2026/11/18", "rollout-new.jsonl", &[r#"{"type":"session_meta","payload":{}}"#]); + assert!(read(home.path()).is_some(), "today's log has no reading yet; yesterday's running session has one"); + + // The most recently written log wins, whichever day folder it sits in. + std::fs::write(&newer, READING).unwrap(); + std::fs::write(&older, READING.replace("24.0", "50.0")).unwrap(); + let hour_ago = std::time::SystemTime::now() - std::time::Duration::from_secs(3600); + std::fs::File::options().write(true).open(&newer).unwrap().set_modified(hour_ago).unwrap(); + assert_eq!(read(home.path()).unwrap().five_hour.unwrap().utilization, Some(0.5)); + } +} diff --git a/src/claude/mod.rs b/src/claude/mod.rs index 2856d9e..77ffaa8 100644 --- a/src/claude/mod.rs +++ b/src/claude/mod.rs @@ -6,12 +6,14 @@ //! //! Channels between Claudiu and the sessions it runs: `accounts` (alt config folders), `usage` (the mod's snapshots), //! `ask` (one-shot completions through the mod), `bridge` (requests from a session), `mcp` (the tab-title server and the -//! per-session config) and `plugin` (the mod Claudiu ships). +//! per-session config) and `plugin` (the mod Claudiu ships). `codex_limits` reads Codex's own usage limits from its +//! session logs. pub mod accounts; pub mod acp; pub mod ask; pub mod bridge; +pub mod codex_limits; pub mod config_sync; pub mod costly; pub mod defaults; diff --git a/src/datadir.rs b/src/datadir.rs index 4b7af96..41bff34 100644 --- a/src/datadir.rs +++ b/src/datadir.rs @@ -17,6 +17,8 @@ pub fn use_throwaway_folders() -> (PathBuf, PathBuf) { unsafe { std::env::set_var("CLAUDIU_DATA_DIR", dirs.0.path()); std::env::set_var("CLAUDE_CONFIG_DIR", dirs.1.path()); + // Keeps the sidebar's Codex limits from reading the real `~/.codex`. + std::env::set_var("CODEX_HOME", dirs.0.path().join("codex")); } dirs }); diff --git a/src/panels/sidebar.rs b/src/panels/sidebar.rs index 3207505..f46b741 100644 --- a/src/panels/sidebar.rs +++ b/src/panels/sidebar.rs @@ -8,7 +8,7 @@ use crate::app::{Act, Activity, MenuAnchor, MenuItem, SideDrag, Workspace}; use crate::panels::icons; use crate::panels::status_icon::{SessionDot, status_icon}; use crate::panels::theme::{self, rgb}; -use crate::panels::widgets::{ago, avatar, clawd, countdown, font, icon, icon_button, key_hint, label, meter, section_label, shortcut, tick}; +use crate::panels::widgets::{ago, avatar, clawd, countdown, font, icon, icon_button, key_hint, label, meter, METER_WARN_AT, section_label, shortcut, tick}; use crate::store::{ExternalState, Id, Project, SessionKind, SessionRecord, now}; pub const SIDEBAR_W: f32 = 284.0; @@ -671,8 +671,9 @@ impl Workspace { fn sidebar_footer(&self) -> El { let t = now(); let usage = self.store.active_account().map(|a| a.usage.clone()).unwrap_or_default(); - // Captions are short: two meters share a row. - let limit = |key: &str, label: &str, l: &Option| -> El { + // Captions are short: two meters share a row. `calm` colors a bar that is not yet near its limit; near it, the + // meter's own warning colors win. + let limit = |key: &str, label: &str, l: &Option, calm: Option| -> El { match l { Some(l) => match (l.resets_at, l.utilization) { (Some(reset), util) if reset > t => { @@ -680,7 +681,8 @@ impl Workspace { if t - l.seen_at > 900 { caption.push_str(&format!(" · {} ago", ago(l.seen_at, t))); } - meter(key, label, util, caption, None) + let tone = calm.filter(|_| util.is_none_or(|f| f < METER_WARN_AT)).map(rgb); + meter(key, label, util, caption, tone) } (Some(_), _) => meter(key, label, None, "reset · unknown".into(), None), (None, util) => meter(key, label, util, format!("seen {} ago", ago(l.seen_at, t)), None), @@ -688,7 +690,7 @@ impl Workspace { None => meter(key, label, None, "after first message".into(), None), } }; - col() + let mut footer = col() .gap(8.0) .px(14.0) .pt(6.0) @@ -698,9 +700,19 @@ impl Workspace { .child( row() .gap(12.0) - .child(limit("meter-5h", "5 HOUR", &usage.five_hour).grow(1.0).shrink()) - .child(limit("meter-7d", "7 DAY", &usage.seven_day).grow(1.0).shrink()), - ) + .child(limit("meter-5h", "5 HOUR", &usage.five_hour, None).grow(1.0).shrink()) + .child(limit("meter-7d", "7 DAY", &usage.seven_day, None).grow(1.0).shrink()), + ); + // Only with Codex subagents on and once Codex has logged a reading, so people who don't use Codex see no row. + if let Some(codex) = self.codex_usage.as_ref().filter(|_| self.store.data.settings.custom_subagents.codex.on) { + footer = footer.child( + row() + .gap(12.0) + .child(limit("meter-codex-5h", "CODEX 5 HOUR", &codex.five_hour, Some(theme::CODEX)).grow(1.0).shrink()) + .child(limit("meter-codex-7d", "CODEX 7 DAY", &codex.seven_day, Some(theme::CODEX)).grow(1.0).shrink()), + ); + } + footer } } diff --git a/src/panels/theme.rs b/src/panels/theme.rs index 7f7b049..3659b83 100644 --- a/src/panels/theme.rs +++ b/src/panels/theme.rs @@ -28,6 +28,8 @@ pub const OK: u32 = 0x7fb069; pub const WARN: u32 = 0xe5c07b; pub const DANGER: u32 = 0xe06c75; pub const SELECTION: u32 = 0x3d4a5c; +/// Codex's usage bars, so they read apart from Claude's at a glance. The terminal palette's blue. +pub const CODEX: u32 = 0x61afef; /// Search matches in the editor, faint, and the current one stronger. pub const FOUND: u32 = 0xe5c07b; diff --git a/src/panels/widgets.rs b/src/panels/widgets.rs index 10d70a5..9d24291 100644 --- a/src/panels/widgets.rs +++ b/src/panels/widgets.rs @@ -63,12 +63,15 @@ pub fn section_label(s: impl Into) -> El { text(s).font(font(10.5, 600.0).tracking(0.3)).color(rgb(theme::TEXT_FAINT)) } +/// From here up, a meter's bar turns to the warning color. +pub const METER_WARN_AT: f32 = 0.7; + /// Progress bar. `fraction == None` renders the neutral "unavailable" state. The bar springs to a new value. pub fn meter(key: &str, label: &str, fraction: Option, caption: String, tone: Option) -> El { let color = tone.unwrap_or_else(|| { rgb(match fraction { Some(f) if f >= 0.9 => theme::DANGER, - Some(f) if f >= 0.7 => theme::WARN, + Some(f) if f >= METER_WARN_AT => theme::WARN, _ => theme::ACCENT, }) }); From a8bfe0d1d2aa9d6f6f0eb580641dd8fe95e6e81f Mon Sep 17 00:00:00 2001 From: Angel-Mario Savin Date: Wed, 18 Nov 2026 11:04:33 +0200 Subject: [PATCH 2/3] Read Codex's logs again only after Codex writes to them --- src/app/headless.rs | 2 +- src/app/ingest.rs | 4 +-- src/claude/codex_limits.rs | 52 +++++++++++++++++++++++++++++++++----- 3 files changed, 49 insertions(+), 9 deletions(-) diff --git a/src/app/headless.rs b/src/app/headless.rs index b339536..a9fadc8 100644 --- a/src/app/headless.rs +++ b/src/app/headless.rs @@ -214,7 +214,6 @@ fn the_workspace_draws_and_its_controls_answer() { assert!(h.ws().is_running(&id)); } -/// Sessions and the shell under them, the sidebars' widths, cards and the GitHub view, with a stand-in `claude`. #[test] fn codex_limits_show_only_with_codex_subagents_on() { let mut h = Harness::new(|_| vec![]); @@ -225,6 +224,7 @@ fn codex_limits_show_only_with_codex_subagents_on() { assert!(h.drawn("meter-codex-5h") && h.drawn("meter-codex-7d"), "Codex's row draws under Claude's: {:?}", h.keys()); } +/// Sessions and the shell under them, the sidebars' widths, cards and the GitHub view, with a stand-in `claude`. #[test] fn sessions_and_the_shell_panel() { let mut h = Harness::new(|_| vec![]); diff --git a/src/app/ingest.rs b/src/app/ingest.rs index 9b584e7..9c347a3 100644 --- a/src/app/ingest.rs +++ b/src/app/ingest.rs @@ -3,12 +3,12 @@ //! off the UI thread; applying them is a handful of small, separately testable steps. use super::*; -use crate::store::RateLimit; use crate::claude::codex_limits; use crate::claude::usage::Snapshot; +use crate::store::RateLimit; impl Workspace { - /// Costs no tokens. The mod's files are tiny; a Codex log costs under 1 MiB of reading. + /// Costs no tokens. The mod's files are tiny, and Codex's logs are read again only after Codex writes to them. pub(super) fn ingest_usage(&mut self) { let codex_on = self.store.data.settings.custom_subagents.codex.on; self.rt.spawn_quietly( diff --git a/src/claude/codex_limits.rs b/src/claude/codex_limits.rs index fd03fbd..209b6fa 100644 --- a/src/claude/codex_limits.rs +++ b/src/claude/codex_limits.rs @@ -4,6 +4,9 @@ //! parse is skipped and the sidebar shows no Codex row. use std::path::{Path, PathBuf}; +use std::collections::HashMap; +use std::sync::{LazyLock, Mutex}; +use std::time::SystemTime; use serde_json::Value; @@ -13,9 +16,21 @@ use crate::store::{AccountUsage, RateLimit}; /// yesterday's folder. Looking at the last few days finds it. const DAYS_TO_LOOK_AT: usize = 3; /// Logs tried, newest first, before giving up: a session that hasn't finished a turn yet has no reading. Kept small -/// because every try reads up to 896 KiB, every few seconds, and a sign-in by API key never logs a reading. +/// because a try reads up to 896 KiB, and a sign-in by API key never logs a reading. const LOGS_TO_TRY: usize = 3; +/// Per Codex folder, the logs last looked at, with when each was written, and what they gave. The sidebar asks every +/// few seconds and the logs are large, so they are read again only when one of them was written since. +static LAST: LazyLock>> = LazyLock::new(Default::default); + +struct Seen { + logs: Vec, + usage: Option, +} + +/// A rollout log and when it was last written. +type Log = (SystemTime, PathBuf); + pub fn codex_home() -> Option { match std::env::var_os("CODEX_HOME") { Some(dir) if !dir.is_empty() => Some(PathBuf::from(dir)), @@ -25,18 +40,27 @@ pub fn codex_home() -> Option { /// The newest limits Codex logged, or `None` when there are none to read. pub fn read(codex_home: &Path) -> Option { - newest_logs(&codex_home.join("sessions")).iter().find_map(|log| read_log(log)) + let logs = newest_logs(&codex_home.join("sessions")); + let mut last = LAST.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(seen) = last.get(codex_home) + && seen.logs == logs + { + return seen.usage.clone(); + } + let usage = logs.iter().find_map(|(_, log)| read_log(log)); + last.insert(codex_home.to_path_buf(), Seen { logs, usage: usage.clone() }); + usage } -/// Rollout logs in the last few `YYYY/MM/DD` folders, most recently written first. -fn newest_logs(sessions: &Path) -> Vec { +/// Rollout logs in the last few `YYYY/MM/DD` folders, with when each was written, most recently written first. +fn newest_logs(sessions: &Path) -> Vec { let days: Vec = subdirs_newest_first(sessions) .into_iter() .flat_map(|year| subdirs_newest_first(&year)) .flat_map(|month| subdirs_newest_first(&month)) .take(DAYS_TO_LOOK_AT) .collect(); - let mut logs: Vec<(std::time::SystemTime, PathBuf)> = days + let mut logs: Vec = days .iter() .filter_map(|day| std::fs::read_dir(day).ok()) .flat_map(|entries| entries.flatten()) @@ -44,7 +68,8 @@ fn newest_logs(sessions: &Path) -> Vec { .filter_map(|e| Some((e.metadata().ok()?.modified().ok()?, e.path()))) .collect(); logs.sort_by_key(|(modified, _)| std::cmp::Reverse(*modified)); - logs.into_iter().take(LOGS_TO_TRY).map(|(_, path)| path).collect() + logs.truncate(LOGS_TO_TRY); + logs } /// Folder names are zero-padded numbers, so sorting by name sorts by date. Walking stays lazy: only the newest years @@ -143,6 +168,21 @@ mod tests { assert!(usage.seven_day.is_some()); } + #[test] + fn a_log_is_read_again_only_once_it_was_written() { + let home = tempfile::tempdir().unwrap(); + let log = write_log(home.path(), "2026/11/18", "rollout-a.jsonl", &[READING]); + let written = std::fs::metadata(&log).unwrap().modified().unwrap(); + assert_eq!(read(home.path()).unwrap().five_hour.unwrap().utilization, Some(0.24)); + + std::fs::write(&log, READING.replace("24.0", "50.0")).unwrap(); + std::fs::File::options().write(true).open(&log).unwrap().set_modified(written).unwrap(); + assert_eq!(read(home.path()).unwrap().five_hour.unwrap().utilization, Some(0.24), "same write time, not read again"); + + std::fs::File::options().write(true).open(&log).unwrap().set_modified(written + std::time::Duration::from_secs(1)).unwrap(); + assert_eq!(read(home.path()).unwrap().five_hour.unwrap().utilization, Some(0.5)); + } + #[test] fn a_session_started_on_an_earlier_day_still_counts() { let home = tempfile::tempdir().unwrap(); From 46006dcca1bcd1536227dd85b0e4d119b507bdf9 Mon Sep 17 00:00:00 2001 From: Angel-Mario Savin Date: Wed, 18 Nov 2026 11:13:07 +0200 Subject: [PATCH 3/3] Notice Codex's writes while it holds a log open, and retry a log that couldn't be read --- src/claude/codex_limits.rs | 65 ++++++++++++++++++++++++++++++++------ 1 file changed, 55 insertions(+), 10 deletions(-) diff --git a/src/claude/codex_limits.rs b/src/claude/codex_limits.rs index 209b6fa..c72bc8b 100644 --- a/src/claude/codex_limits.rs +++ b/src/claude/codex_limits.rs @@ -28,8 +28,13 @@ struct Seen { usage: Option, } -/// A rollout log and when it was last written. -type Log = (SystemTime, PathBuf); +/// A rollout log, with its write time and size: either changes when Codex writes to it. +#[derive(PartialEq)] +struct Log { + modified: SystemTime, + len: u64, + path: PathBuf, +} pub fn codex_home() -> Option { match std::env::var_os("CODEX_HOME") { @@ -47,8 +52,17 @@ pub fn read(codex_home: &Path) -> Option { { return seen.usage.clone(); } - let usage = logs.iter().find_map(|(_, log)| read_log(log)); - last.insert(codex_home.to_path_buf(), Seen { logs, usage: usage.clone() }); + // A log that couldn't be opened (Windows lets a writer lock it) is tried again next time rather than remembered. + let mut failed = false; + let usage = logs.iter().find_map(|log| { + read_log(&log.path).unwrap_or_else(|_| { + failed = true; + None + }) + }); + if !failed { + last.insert(codex_home.to_path_buf(), Seen { logs, usage: usage.clone() }); + } usage } @@ -64,10 +78,16 @@ fn newest_logs(sessions: &Path) -> Vec { .iter() .filter_map(|day| std::fs::read_dir(day).ok()) .flat_map(|entries| entries.flatten()) - .filter(|e| e.path().extension().and_then(|x| x.to_str()) == Some("jsonl")) - .filter_map(|e| Some((e.metadata().ok()?.modified().ok()?, e.path()))) + .map(|e| e.path()) + .filter(|path| path.extension().and_then(|x| x.to_str()) == Some("jsonl")) + // Asked of the file, not of the folder listing: on Windows the listing can show an old write time and size + // while Codex still has the log open. + .filter_map(|path| { + let meta = std::fs::metadata(&path).ok()?; + Some(Log { modified: meta.modified().ok()?, len: meta.len(), path }) + }) .collect(); - logs.sort_by_key(|(modified, _)| std::cmp::Reverse(*modified)); + logs.sort_by_key(|log| std::cmp::Reverse(log.modified)); logs.truncate(LOGS_TO_TRY); logs } @@ -81,10 +101,10 @@ fn subdirs_newest_first(dir: &Path) -> Vec { dirs } -fn read_log(path: &Path) -> Option { - let (head, tail, whole, _, _) = super::read_chunks(path).ok()?; +fn read_log(path: &Path) -> std::io::Result> { + let (head, tail, whole, _, _) = super::read_chunks(path)?; let text = if whole { head } else { tail }; - text.lines().rev().filter(|line| line.contains("\"rate_limits\"")).find_map(parse_line) + Ok(text.lines().rev().filter(|line| line.contains("\"rate_limits\"")).find_map(parse_line)) } fn parse_line(line: &str) -> Option { @@ -183,6 +203,31 @@ mod tests { assert_eq!(read(home.path()).unwrap().five_hour.unwrap().utilization, Some(0.5)); } + #[test] + fn a_log_still_open_for_writing_is_read_again() { + use std::io::Write; + let home = tempfile::tempdir().unwrap(); + let log = write_log(home.path(), "2026/11/18", "rollout-a.jsonl", &[READING]); + assert_eq!(read(home.path()).unwrap().five_hour.unwrap().utilization, Some(0.24)); + let mut codex = std::fs::OpenOptions::new().append(true).open(&log).unwrap(); + write!(codex, " +{}", READING.replace("24.0", "50.0")).unwrap(); + codex.flush().unwrap(); + assert_eq!(read(home.path()).unwrap().five_hour.unwrap().utilization, Some(0.5)); + } + + #[cfg(windows)] + #[test] + fn a_log_locked_by_its_writer_is_tried_again() { + use std::os::windows::fs::OpenOptionsExt; + let home = tempfile::tempdir().unwrap(); + let log = write_log(home.path(), "2026/11/18", "rollout-a.jsonl", &[READING]); + let locked = std::fs::OpenOptions::new().read(true).share_mode(0).open(&log).unwrap(); + assert_eq!(read(home.path()), None); + drop(locked); + assert!(read(home.path()).is_some(), "the failed read was not remembered"); + } + #[test] fn a_session_started_on_an_earlier_day_still_counts() { let home = tempfile::tempdir().unwrap();