diff --git a/windows/src-tauri/src/lib.rs b/windows/src-tauri/src/lib.rs index fc45716a..5b510831 100644 --- a/windows/src-tauri/src/lib.rs +++ b/windows/src-tauri/src/lib.rs @@ -905,11 +905,12 @@ mod commands { } /// Tints the tray logo from the worst connected provider's quota severity, falling back - /// to the daily-budget warning. `today_cost` is the figure the hero shows; the limit it - /// is measured against is the CLI's own `dailyBudget`. + /// to the daily-budget warning. `today_cost` is the figure the hero shows, in dollars, so + /// the limit is converted out of the display currency the CLI's `budget.daily` holds. #[tauri::command] - pub fn set_tray_severity( + pub async fn set_tray_severity( app: AppHandle, + state: State<'_, AppState>, severity: String, today_cost: Option, today_tokens: Option, @@ -922,8 +923,16 @@ mod commands { (Some(value), Some(limit)) => value >= limit, _ => false, }; - let over_budget = over(today_cost, crate::tray_status::daily_budget()) - || over(today_tokens, crate::tray_status::daily_token_budget()); + let budget_usd = match crate::tray_status::daily_budget_display() { + Some(display) => { + let rate = display_rate(&state).await; + Some(if rate > 0.0 { display / rate } else { display }) + } + // Not migrated yet: the old key was already in dollars. + None => crate::tray_status::legacy_daily_budget(), + }; + let over_budget = + over(today_cost, budget_usd) || over(today_tokens, crate::tray_status::daily_token_budget()); super::apply_tray_tint(&app, crate::tray_status::tint_for(severity, over_budget)) } @@ -1147,19 +1156,50 @@ mod commands { Ok(stored) } + /// The rate the display currency is worth against the dollar, from the cache the currency + /// command already fills. A missing rate falls back to 1, which is the same answer the + /// currency command gives: figures stay in the dollars the CLI reports rather than being + /// multiplied by a guess. + async fn display_rate(state: &AppState) -> f64 { + let code = crate::config::read() + .get("currency") + .and_then(|currency| currency.get("code")) + .and_then(Value::as_str) + .unwrap_or("USD") + .to_string(); + if code == "USD" { + return 1.0; + } + state.fx.rate_for(&code).await.unwrap_or(1.0) + } + /// Both daily alert thresholds. `None` on either means that alert is off. + /// + /// The spend limit comes back twice: `cost` in dollars, which is what the payload is + /// measured in, and `costDisplay` in the currency it is stored and edited in. The + /// migration off the old top-level key happens here, on the first read after an upgrade. #[tauri::command] - pub fn daily_budgets() -> Value { - serde_json::json!({ - "cost": crate::tray_status::daily_budget(), + pub async fn daily_budgets(state: State<'_, AppState>) -> Result { + let rate = display_rate(&state).await; + let display = crate::settings::migrate_daily_budget(rate); + Ok(serde_json::json!({ + "cost": display.map(|amount| if rate > 0.0 { amount / rate } else { amount }), + "costDisplay": display, "tokens": crate::tray_status::daily_token_budget(), - }) + })) } #[tauri::command] - pub fn set_daily_budget(app: AppHandle, key: String, amount: Option) -> Result<(), String> { + pub async fn set_daily_budget( + app: AppHandle, + state: State<'_, AppState>, + key: String, + amount: Option, + ) -> Result<(), String> { crate::settings::set_daily_budget(&key, amount).map_err(|e| e.to_string())?; - let _ = app.emit("codeburn://budget-changed", daily_budgets()); + if let Ok(budgets) = daily_budgets(state).await { + let _ = app.emit("codeburn://budget-changed", budgets); + } Ok(()) } diff --git a/windows/src-tauri/src/settings.rs b/windows/src-tauri/src/settings.rs index c24bc8e0..1f2ba379 100644 --- a/windows/src-tauri/src/settings.rs +++ b/windows/src-tauri/src/settings.rs @@ -119,11 +119,17 @@ pub fn set_claude_config_dirs(dirs: &[String]) -> Result<()> { Ok(()) } -/// The daily alert thresholds. Both live beside the currency because the tray reads them -/// from Rust, before any webview exists. Zero means off, which is stored as the key's -/// absence rather than a zero the CLI would have to special-case. +/// The daily alert thresholds. Both live in the CLI's config because the tray reads them from +/// Rust, before any webview exists. Zero means off, which is stored as the key's absence +/// rather than a zero the CLI would have to special-case. +/// +/// The spend limit goes where the CLI's own config type has always had it, `budget.daily` in +/// the display currency; the token limit has no CLI counterpart and stays at the top level. pub fn set_daily_budget(key: &str, amount: Option) -> Result<()> { - if !matches!(key, "dailyBudget" | "dailyTokenBudget") { + if key == "dailyBudget" { + return set_cli_daily_budget(amount); + } + if key != "dailyTokenBudget" { return Err(anyhow!("unknown budget key `{key}`")); } let key = key.to_owned(); @@ -138,6 +144,51 @@ pub fn set_daily_budget(key: &str, amount: Option) -> Result<()> { Ok(()) } +/// `budget` is an object of tiers on the CLI's side, so the whole object is read and written +/// back rather than one key, and an unset tier is removed rather than stored as a zero. The +/// app's old top-level key is dropped on the way past: the two never coexist. +fn set_cli_daily_budget(amount: Option) -> Result<()> { + crate::config::update(move |obj| { + obj.remove("dailyBudget"); + let mut budget = obj + .get("budget") + .and_then(Value::as_object) + .cloned() + .unwrap_or_default(); + match amount { + Some(value) if value > 0.0 => { + budget.insert("daily".into(), serde_json::json!(value)); + } + _ => { + budget.remove("daily"); + } + } + if budget.is_empty() { + obj.remove("budget"); + } else { + obj.insert("budget".into(), Value::Object(budget)); + } + })?; + Ok(()) +} + +/// Moves a limit written by an older build onto the CLI's key, once. The old key was in +/// dollars and the new one is in the display currency, so the rate is applied on the way +/// across; a `budget.daily` that already exists wins, and the old key is removed either way so +/// this never runs twice. Returns the limit in the display currency. +pub fn migrate_daily_budget(rate: f64) -> Option { + let stored = crate::tray_status::daily_budget_display(); + let Some(legacy) = crate::tray_status::legacy_daily_budget() else { + return stored; + }; + let display = stored.unwrap_or(legacy * rate); + if let Err(err) = set_cli_daily_budget(Some(display)) { + eprintln!("codeburn: failed to move the daily budget onto budget.daily: {err}"); + return Some(display); + } + Some(display) +} + // Provider API keys --------------------------------------------------------------------- /// Keys the CLI's quota adapters read from the environment, from `src/quota/*.ts`. Only diff --git a/windows/src-tauri/src/tray_status.rs b/windows/src-tauri/src/tray_status.rs index ec15d954..9d666f01 100644 --- a/windows/src-tauri/src/tray_status.rs +++ b/windows/src-tauri/src/tray_status.rs @@ -76,23 +76,36 @@ pub fn tray_icon(tint: Option<[u8; 3]>) -> Result> { Ok(Image::new_owned(rgba, width, height)) } -/// Today's spend limit, kept beside the currency in the CLI's config so the tray can read it -/// before any webview exists. Absent or zero means no budget. The settings window writes it. -pub fn daily_budget() -> Option { - budget("dailyBudget") +/// Today's spend limit, where the CLI's own config type keeps it: `budget.daily`, in the +/// display currency (`src/config.ts`). Read from Rust because the tray is judged against it +/// before any webview exists. Absent or zero means no budget. +pub fn daily_budget_display() -> Option { + config_number(&["budget", "daily"]) +} + +/// What this app wrote before it learned the CLI's key: top level, and in dollars. Read once +/// so a limit set by an older build survives the move, after which +/// `settings::migrate_daily_budget` removes it. +pub fn legacy_daily_budget() -> Option { + config_number(&["dailyBudget"]) } /// The same alert measured in tokens, for the token display metrics. Only one of the two is -/// ever armed, since the metric decides which one the flame is judged against. +/// ever armed, since the metric decides which one the flame is judged against. The CLI has no +/// token budget of its own, so this one stays where this app put it. pub fn daily_token_budget() -> Option { - budget("dailyTokenBudget") + config_number(&["dailyTokenBudget"]) } -fn budget(key: &str) -> Option { - let path = dirs::home_dir()?.join(".config/codeburn/config.json"); - let value: serde_json::Value = serde_json::from_slice(&fs::read(path).ok()?).ok()?; - let budget = value.get(key)?.as_f64()?; - (budget > 0.0).then_some(budget) +fn config_number(path: &[&str]) -> Option { + let config = crate::config::read(); + let (first, rest) = path.split_first()?; + let mut value = config.get(*first)?; + for key in rest { + value = value.get(key)?; + } + let number = value.as_f64()?; + (number > 0.0).then_some(number) } /// The badge text and tooltip from the last successful refresh. diff --git a/windows/src/App.tsx b/windows/src/App.tsx index fa405625..75d33996 100644 --- a/windows/src/App.tsx +++ b/windows/src/App.tsx @@ -98,7 +98,9 @@ type FetchOptions = { } /// The two daily alert thresholds from the CLI config. Only the one the display metric is -/// measured in is ever shown, as on the mac; `null` means that alert is off. +/// measured in is ever shown, as on the mac; `null` means that alert is off. `cost` arrives in +/// dollars, since that is what the payload is measured in; the settings window edits the +/// display-currency figure that the CLI's `budget.daily` actually holds. type Budgets = { cost: number | null; tokens: number | null } export function App() { @@ -323,8 +325,11 @@ export function App() { const unlistenBudget = listen('codeburn://budget-changed', event => { if (event.payload) setBudgets(event.payload) }) + // The spend limit is stored in the display currency, so what it is worth in the dollars + // the payload reports changes with the currency, not only with the limit. const unlistenCurrency = listen('codeburn://currency-changed', event => { if (event.payload) setCurrency(event.payload) + invoke('daily_budgets').then(setBudgets).catch(() => {}) }) return () => { unlistenRefresh.then(fn => fn()) diff --git a/windows/src/components/HeroSection.tsx b/windows/src/components/HeroSection.tsx index 7d346a66..11ca8aba 100644 --- a/windows/src/components/HeroSection.tsx +++ b/windows/src/components/HeroSection.tsx @@ -1,6 +1,6 @@ import type { CombinedUsage, MenubarPayload } from '../lib/payload' import type { CurrencyState } from '../lib/currency' -import { USD, formatCurrency, formatTokens, plural } from '../lib/currency' +import { formatCurrency, formatTokens, plural } from '../lib/currency' import { prettyDate, todayKey } from '../lib/dates' import { SectionCaption } from './CollapsibleSection' import { ArrowDownRight, ArrowUpRight, LeafIcon, MonitorIcon, WarningIcon } from './Icons' @@ -41,9 +41,10 @@ export function HeroSection({ payload, currency, periodLabel, isToday, dailyBudg const label = payload?.current.label || periodLabel const caption = combined ? `Combined · ${label}` : isToday ? `Today · ${todayLabel}` : label - // The budget is defined in USD, matching the CLI config and the presets the settings - // window offers, so it is compared and printed in USD rather than converted. Combined - // totals are several machines' spend, which the limit was never set against. + // The spend limit is stored in the display currency, as the CLI's own budget.daily is, and + // reaches this component already converted to the dollars the payload is measured in. It is + // printed back in the display currency, which is what the reader typed. Combined totals are + // several machines' spend, which the limit was never set against. const measured = isTokenMetric ? inputTokens + outputTokens : cost const overBudget = isToday && !combinedScope && dailyBudget !== null && payload !== null && measured >= dailyBudget const savings = combined ? 0 : payload?.current.localModelSavings?.totalUSD ?? 0 @@ -80,7 +81,7 @@ export function HeroSection({ payload, currency, periodLabel, isToday, dailyBudg
- Daily budget of {isTokenMetric ? `${formatTokens(dailyBudget)} tok` : formatCurrency(dailyBudget, USD)} exceeded + Daily budget of {isTokenMetric ? `${formatTokens(dailyBudget)} tok` : formatCurrency(dailyBudget, currency)} exceeded
)} diff --git a/windows/src/settings/GeneralPane.tsx b/windows/src/settings/GeneralPane.tsx index 627d126c..1a5d379d 100644 --- a/windows/src/settings/GeneralPane.tsx +++ b/windows/src/settings/GeneralPane.tsx @@ -181,7 +181,7 @@ export function GeneralPane({ quota, anchor }: Props) { - + ({ cost: null, tokens: null }) +/// What `daily_budgets` answers; its `cost`, the same limit in dollars, is for the surfaces +/// that compare it against the payload rather than edit it. +type Budgets = { costDisplay: number | null; tokens: number | null } + +function AlertsSection({ settings, currency }: { settings: AppSettings; currency: CurrencyState }) { + const [budgets, setBudgets] = useState({ costDisplay: null, tokens: null }) const [custom, setCustom] = useState(false) const [draft, setDraft] = useState('') const isTokens = settings.metric === 'tokens' || settings.metric === 'totalTokens' - const stored = isTokens ? budgets.tokens : budgets.cost + const stored = isTokens ? budgets.tokens : budgets.costDisplay const presets = isTokens ? TOKEN_PRESETS : COST_PRESETS const key = isTokens ? 'dailyTokenBudget' : 'dailyBudget' const unit = isTokens ? 1e6 : 1 const read = () => { - invoke<{ cost: number | null; tokens: number | null }>('daily_budgets') + invoke('daily_budgets') .then(next => { setBudgets(next) - const value = (settings.metric === 'tokens' || settings.metric === 'totalTokens') ? next.tokens : next.cost + const value = (settings.metric === 'tokens' || settings.metric === 'totalTokens') ? next.tokens : next.costDisplay const list = (settings.metric === 'tokens' || settings.metric === 'totalTokens') ? TOKEN_PRESETS : COST_PRESETS // A stored amount that is not one of the presets is a custom one, so the field opens // with it rather than the picker silently rounding it to a preset. @@ -442,7 +448,7 @@ function AlertsSection({ settings }: { settings: AppSettings }) { const write = (amount: number | null) => { invoke('set_daily_budget', { key, amount }) - .then(() => setBudgets(current => ({ ...current, [isTokens ? 'tokens' : 'cost']: amount }))) + .then(() => setBudgets(current => ({ ...current, [isTokens ? 'tokens' : 'costDisplay']: amount }))) .catch(() => {}) } @@ -464,7 +470,7 @@ function AlertsSection({ settings }: { settings: AppSettings }) { const label = (value: number) => { if (value === 0) return 'Off' - return isTokens ? `${trim(value / 1e6)}M` : `$${trim(value)}` + return isTokens ? `${trim(value / 1e6)}M` : `${currency.symbol}${trim(value)}` } const armed = stored !== null && stored > 0 @@ -490,7 +496,7 @@ function AlertsSection({ settings }: { settings: AppSettings }) { /> {custom && (