mirror of
https://github.com/AgentSeal/codeburn.git
synced 2026-11-29 10:43:47 +00:00
fix(windows): the daily budget lives where the CLI keeps it
The app wrote the spend limit as a top-level dailyBudget in dollars. The CLI's own config type has never had that key: it reads budget.daily, in the display currency. So a limit set in the settings window did nothing for `codeburn report`, and a limit set by the CLI did nothing for the tray. The limit is budget.daily now, written as the reader typed it, in whatever currency they are looking at, which is what the CLI's other budget tiers already mean. Every comparison converts it back to dollars against the rate the app already has for the currency, because the payload is in dollars; the popover re-reads it when the currency changes, since what a limit is worth in dollars moves with the rate. An existing dailyBudget is read once more and moved across on the first read after this build, rate applied, old key removed, so a limit set before this does not silently switch off. The token budget has no CLI counterpart and stays exactly where it was.
This commit is contained in:
parent
ff56796640
commit
2b3c106da8
6 changed files with 160 additions and 44 deletions
|
|
@ -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<f64>,
|
||||
today_tokens: Option<f64>,
|
||||
|
|
@ -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<Value, String> {
|
||||
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<f64>) -> Result<(), String> {
|
||||
pub async fn set_daily_budget(
|
||||
app: AppHandle,
|
||||
state: State<'_, AppState>,
|
||||
key: String,
|
||||
amount: Option<f64>,
|
||||
) -> 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(())
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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<f64>) -> 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<f64>) -> 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<f64>) -> 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<f64> {
|
||||
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
|
||||
|
|
|
|||
|
|
@ -76,23 +76,36 @@ pub fn tray_icon(tint: Option<[u8; 3]>) -> Result<Image<'static>> {
|
|||
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<f64> {
|
||||
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<f64> {
|
||||
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<f64> {
|
||||
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<f64> {
|
||||
budget("dailyTokenBudget")
|
||||
config_number(&["dailyTokenBudget"])
|
||||
}
|
||||
|
||||
fn budget(key: &str) -> Option<f64> {
|
||||
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<f64> {
|
||||
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.
|
||||
|
|
|
|||
|
|
@ -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<Budgets>('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<CurrencyState>('codeburn://currency-changed', event => {
|
||||
if (event.payload) setCurrency(event.payload)
|
||||
invoke<Budgets>('daily_budgets').then(setBudgets).catch(() => {})
|
||||
})
|
||||
return () => {
|
||||
unlistenRefresh.then(fn => fn())
|
||||
|
|
|
|||
|
|
@ -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
|
|||
<div className="hero-note hero-note-warn">
|
||||
<WarningIcon size={10} />
|
||||
<span>
|
||||
Daily budget of {isTokenMetric ? `${formatTokens(dailyBudget)} tok` : formatCurrency(dailyBudget, USD)} exceeded
|
||||
Daily budget of {isTokenMetric ? `${formatTokens(dailyBudget)} tok` : formatCurrency(dailyBudget, currency)} exceeded
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
|
|
|||
|
|
@ -181,7 +181,7 @@ export function GeneralPane({ quota, anchor }: Props) {
|
|||
|
||||
<TerminalSection settings={settings} />
|
||||
|
||||
<AlertsSection settings={settings} />
|
||||
<AlertsSection settings={settings} currency={currency} />
|
||||
|
||||
<Group title="System">
|
||||
<Row
|
||||
|
|
@ -405,29 +405,35 @@ function TerminalSection({ settings }: { settings: AppSettings }) {
|
|||
)
|
||||
}
|
||||
|
||||
/// The mac's Alerts section. The budget tracks whatever the tray figure shows: dollars for
|
||||
/// the Cost metric, tokens for the two token metrics. Both are stored beside the currency in
|
||||
/// the CLI config, because the tray reads them before any webview exists.
|
||||
/// The mac's Alerts section. The budget tracks whatever the tray figure shows: money for the
|
||||
/// Cost metric, tokens for the two token metrics. Both live in the CLI config, because the
|
||||
/// tray reads them before any webview exists. The spend limit is the CLI's own `budget.daily`
|
||||
/// and so is kept in the display currency, which is why the presets carry its symbol; the
|
||||
/// token limit has no CLI counterpart and stays where this app put it.
|
||||
const COST_PRESETS = [0, 25, 50, 100, 200, 500]
|
||||
const TOKEN_PRESETS = [0, 1e6, 5e6, 10e6, 25e6, 50e6, 100e6]
|
||||
const CUSTOM = -1
|
||||
|
||||
function AlertsSection({ settings }: { settings: AppSettings }) {
|
||||
const [budgets, setBudgets] = useState<{ cost: number | null; tokens: number | null }>({ 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<Budgets>({ 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<Budgets>('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 && (
|
||||
<Row
|
||||
label={isTokens ? 'Millions of tokens' : 'Amount in USD'}
|
||||
label={isTokens ? 'Millions of tokens' : `Amount in ${currency.code}`}
|
||||
control={
|
||||
<Field
|
||||
ariaLabel="Custom daily budget"
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue