diff --git a/CHANGELOG.md b/CHANGELOG.md index ae2cec1cef4..d36b4f64b87 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ ## [Windows] Unreleased +- Usage & Spend and the tray Overview: only one spend summary is built at a time. The Overview asked for a new summary after every provider refresh, and each request started its own full scan of the local Codex and Claude logs, so with large histories the scans piled up until CodexBar held hundreds of threads and many gigabytes of memory and provider refreshes stalled. A request that arrives while a summary is being built now gets the previous summary, and a forced refresh waits for the running build. - Tray panel: **Settings > Menu > Panel look** switches between Modern and Classic. Classic is the layout from before the redesign (icon-only provider switcher, percent after the title, the full cost dashboard, shortcut hints and icons on every menu row). Drag either vertical edge of the panel to change its width (280 to 560 px at 100 % Panel scale); the width is saved, arrow keys on the focused edge step it, and a double-click or Home restores 310 px. At a high Panel scale the panel never grows wider than the screen's work area. - Tray panel: a new look. The panel sits on a soft tinted surface with larger type. Provider tabs show an icon and a name over a quota underline, wrap to extra rows when many providers are on, and keep the dense icon grid beyond 18. Each quota row is a title, a thicker bar, then the percent used on the left and the reset on the right. Sections are set off by hairlines, and the daily-cost dashboard becomes a collapsible **Cost** section that opens from a two-line summary. The menu is text-only: shortcut hints and the Settings, About and Quit icons are gone, and About no longer carries the version. - Claude: when Claude Code signs out but keeps its login entry with blank tokens, Settings and the tray still list the saved Claude Code accounts, and Switch and Add account work again. Before, every account action failed with "Claude login is missing accessToken" and "No Claude Code accounts found", even though the accounts were saved. diff --git a/apps/desktop-tauri/src-tauri/src/commands/usage_spend.rs b/apps/desktop-tauri/src-tauri/src/commands/usage_spend.rs index cb93e7d3065..cf883f98479 100644 --- a/apps/desktop-tauri/src-tauri/src/commands/usage_spend.rs +++ b/apps/desktop-tauri/src-tauri/src/commands/usage_spend.rs @@ -17,7 +17,8 @@ use tauri::State; use super::ProviderUsageSnapshot; use crate::state::AppState; use std::collections::{BTreeSet, HashMap}; -use std::sync::{Mutex, OnceLock}; +use std::sync::{Condvar, Mutex, OnceLock, PoisonError}; +use std::time::{Duration, Instant}; mod build; #[cfg(test)] @@ -155,6 +156,43 @@ struct UsageSpendCoordinator { next_generation: u64, current: Option<(UsageSpendRefreshOwner, UsageSpendRefreshPhase)>, cache: Option, + /// A summary build (a full local-log scan) is running. Only one runs at a + /// time: the tray Overview asks again on every `provider-updated` event and + /// the cache key moves with every provider refresh, so without this guard + /// slow builds stacked up until the blocking pool and memory ran out. + building: bool, +} + +/// What a request does about the shared summary build. +#[derive(Debug)] +enum UsageSpendBuildClaim { + /// Serve this summary without scanning. + Reuse(Box), + /// This request now owns the build slot and must release it. + Build, + /// Another build is running and there is nothing to serve yet (or the + /// caller forced a rebuild); wait for it to finish, then claim again. + Wait, +} + +/// Longest a request waits for another build before giving up. +const USAGE_SPEND_BUILD_WAIT: Duration = Duration::from_secs(10 * 60); + +/// Signalled whenever the build slot is released. +static USAGE_SPEND_BUILD_FINISHED: Condvar = Condvar::new(); + +/// Releases the build slot when the build ends, including by panic. +struct UsageSpendBuildSlot; + +impl Drop for UsageSpendBuildSlot { + fn drop(&mut self) { + let mut coordinator = usage_spend_coordinator() + .lock() + .unwrap_or_else(PoisonError::into_inner); + coordinator.release_build(); + drop(coordinator); + USAGE_SPEND_BUILD_FINISHED.notify_all(); + } } impl UsageSpendCoordinator { @@ -200,6 +238,38 @@ impl UsageSpendCoordinator { .as_ref() .filter(|existing| !force_refresh && existing.key == key) } + + /// Decide whether this request reuses a summary, builds one, or waits. + /// + /// While a build runs, a request that is not forced gets the last summary + /// even when its key is out of date (stale while revalidate) instead of + /// starting a second full scan. It carries no refresh owner, so it can + /// never clear the indexing state of the build that produced it. + fn claim_build(&mut self, key: &str, force_refresh: bool) -> UsageSpendBuildClaim { + if let Some(existing) = self.reusable(key, force_refresh) { + return UsageSpendBuildClaim::Reuse(Box::new(BuiltUsageSpendSummary { + key: existing.key.clone(), + summary: existing.summary.clone(), + refresh_owner: existing.refresh_owner.clone(), + })); + } + if self.building { + if !force_refresh && let Some(existing) = self.cache.as_ref() { + return UsageSpendBuildClaim::Reuse(Box::new(BuiltUsageSpendSummary { + key: existing.key.clone(), + summary: existing.summary.clone(), + refresh_owner: None, + })); + } + return UsageSpendBuildClaim::Wait; + } + self.building = true; + UsageSpendBuildClaim::Build + } + + fn release_build(&mut self) { + self.building = false; + } } static USAGE_SPEND_COORDINATOR: OnceLock> = OnceLock::new(); @@ -246,6 +316,7 @@ fn clear_usage_spend_refresh_if_owned(owner: &UsageSpendRefreshOwner) { } } +#[derive(Debug)] struct BuiltUsageSpendSummary { key: String, summary: UsageSpendSummary, @@ -340,24 +411,32 @@ fn build_usage_spend_summary_cached( ) -> Result { let settings = codexbar::settings::Settings::load(); let key = usage_spend_cache_key(cached, period, &settings); - { - let guard = usage_spend_coordinator() - .lock() - .map_err(|error| error.to_string())?; - if let Some(existing) = guard.reusable(&key, force_refresh) { - return Ok(BuiltUsageSpendSummary { - key: existing.key.clone(), - summary: existing.summary.clone(), - refresh_owner: existing.refresh_owner.clone(), - }); - } - } let owner = { let mut coordinator = usage_spend_coordinator() .lock() .map_err(|error| error.to_string())?; - coordinator.begin(key.clone()) + let deadline = Instant::now() + USAGE_SPEND_BUILD_WAIT; + loop { + match coordinator.claim_build(&key, force_refresh) { + UsageSpendBuildClaim::Reuse(built) => return Ok(*built), + UsageSpendBuildClaim::Build => break coordinator.begin(key.clone()), + UsageSpendBuildClaim::Wait => { + let remaining = deadline.saturating_duration_since(Instant::now()); + if remaining.is_zero() { + return Err( + "Usage & Spend is still being built; try again shortly.".to_string() + ); + } + coordinator = USAGE_SPEND_BUILD_FINISHED + .wait_timeout(coordinator, remaining) + .map_err(|error| error.to_string())? + .0; + } + } + } }; + // Declared before the coordinator guard below, so it is dropped after it. + let _build_slot = UsageSpendBuildSlot; let summary = build_usage_spend_summary(cached, period, &settings, force_refresh); let refreshing = summary_is_refreshing(&summary); let codex_scan_pause_reason = diff --git a/apps/desktop-tauri/src-tauri/src/commands/usage_spend/tests.rs b/apps/desktop-tauri/src-tauri/src/commands/usage_spend/tests.rs index 843da648a60..baecc93df03 100644 --- a/apps/desktop-tauri/src-tauri/src/commands/usage_spend/tests.rs +++ b/apps/desktop-tauri/src-tauri/src/commands/usage_spend/tests.rs @@ -40,6 +40,90 @@ fn trend_row(provider_id: &str, currency: &str, daily: &[(&str, f64)]) -> UsageS } } +fn cached_summary(key: &str, owner: Option) -> CachedUsageSpendSummary { + CachedUsageSpendSummary { + key: key.to_string(), + summary: empty_summary(), + refresh_owner: owner, + } +} + +#[test] +fn only_one_summary_build_runs_at_a_time() { + let mut coordinator = UsageSpendCoordinator::default(); + + assert!(matches!( + coordinator.claim_build("key:a", false), + UsageSpendBuildClaim::Build + )); + // Nothing to serve yet: a second request waits instead of scanning again. + assert!(matches!( + coordinator.claim_build("key:b", false), + UsageSpendBuildClaim::Wait + )); + + coordinator.release_build(); + assert!(matches!( + coordinator.claim_build("key:b", false), + UsageSpendBuildClaim::Build + )); +} + +#[test] +fn request_during_a_build_reuses_the_last_summary_without_its_owner() { + let mut coordinator = UsageSpendCoordinator::default(); + let owner = coordinator.begin("key:old".to_string()); + coordinator.cache = Some(cached_summary("key:old", Some(owner))); + assert!(matches!( + coordinator.claim_build("key:new", false), + UsageSpendBuildClaim::Build + )); + + // The provider snapshots moved on (new key) while the build runs. + match coordinator.claim_build("key:newer", false) { + UsageSpendBuildClaim::Reuse(built) => { + assert_eq!(built.key, "key:old"); + assert!(built.refresh_owner.is_none()); + } + other => panic!("expected the stale summary, got {other:?}"), + } + assert!(coordinator.building); +} + +#[test] +fn forced_request_waits_for_the_running_build() { + let mut coordinator = UsageSpendCoordinator { + cache: Some(cached_summary("key:a", None)), + ..UsageSpendCoordinator::default() + }; + assert!(matches!( + coordinator.claim_build("key:b", false), + UsageSpendBuildClaim::Build + )); + + assert!(matches!( + coordinator.claim_build("key:a", true), + UsageSpendBuildClaim::Wait + )); +} + +#[test] +fn matching_cache_is_reused_even_while_building() { + let mut coordinator = UsageSpendCoordinator { + cache: Some(cached_summary("key:a", None)), + ..UsageSpendCoordinator::default() + }; + assert!(matches!( + coordinator.claim_build("key:b", false), + UsageSpendBuildClaim::Build + )); + + match coordinator.claim_build("key:a", false) { + UsageSpendBuildClaim::Reuse(built) => assert_eq!(built.key, "key:a"), + other => panic!("expected the cached summary, got {other:?}"), + } +} + #[test] fn invalidated_owner_clears_orphaned_indexing_activity() { let mut coordinator = UsageSpendCoordinator::default();