Skip to content

feat: add a Daily Cost Rate widget - #817

Open
eric-engberg wants to merge 53 commits into
sirmalloc:mainfrom
eric-engberg:feat/daily-cost-rate
Open

eric-engberg wants to merge 53 commits into
sirmalloc:mainfrom
eric-engberg:feat/daily-cost-rate

Conversation

@eric-engberg

Copy link
Copy Markdown
Contributor

What

A new Daily Cost Rate widget shows today's cost per hour across all of today's Claude Code sessions: Rate Today: $6.20/hr. It's the cross-session version of Session Cost Rate.

Why

A single session's rate says little when work is spread over several sessions, some running in parallel. The useful number is what today has cost per hour of work so far. On usage-based plans, where every request is billed, it reads as the agent's hourly rate for the day.

How

  • Session tracking. Claude Code reports each session's cost and time as running totals. When a line shows the widget, each render stores its session's totals in Extra Usage Today's daily state file (feat: add an Extra Usage Today widget #811) (~/.cache/ccstatusline/daily.json), per Claude Code profile (CLAUDE_CONFIG_DIR, or default), along with where they stood when the UTC day began. A session that started today began at zero. An overnight session starts from the last totals seen yesterday, or from the first seen today when it wasn't seen yesterday. Unchanged totals aren't rewritten more than once a minute, and records older than yesterday are pruned.
  • Today's totals. Cost and active time (Claude working, from the API duration) add up across sessions, so parallel sessions count separately. Clock time is the time any session was running: overlapping sessions count once and gaps between sessions don't count. The totals reach widgets as dailyCost in the render context.
  • Two options. t switches from active time to clock time. b switches from Claude Code's own session costs to today's billed spend, the value Extra Usage Today shows, which includes claude.ai and other machines. With billed spend on, the widget makes the usage prefetch fetch the extra usage state and work out today's spend. Without it, the widget triggers no usage fetch at all, because the prefetch requirement table now has a per-setting rule for it, like the time cursor's. The hours only ever come from this machine's Claude Code sessions, so with billed spend, heavy claude.ai use reads as a higher rate. The docs say so. The editor row names both choices, e.g. (active time, Claude Code cost).
  • First minute. It shows nothing until a full minute of the chosen time has passed. With billed spend it also waits until today's spend is known. The preview sample is $6.20/hr.
  • Label. The label editor can change its Rate Today: label, as on the other labeled widgets.

Update: Count a resumed, forked or re-logged-in session from its new totals; Settle session records stamped while the clock ran ahead; Show billed spend in the account's currency

  • Resumed and forked sessions. claude --resume, --continue, /resume and --fork-session restore a session's cost and API time. They also backdate its start by the time it ran before, so the restored totals used to count as today's spend. A session's totals now carry on from its record only while two things hold: neither cost nor API time went down, and its start (now minus total_duration_ms) moved no more than a minute later. Otherwise they're treated as a new run, counted from the totals first seen (zero for a new session). Its clock time counts from a new firstSeenAt field, not from the backdated start. The "started today, so begin at zero" shortcut is gone, so a record from yesterday is always honored. Without a record, a resumed session can't be told apart from a new one, so a session first seen with spend already on it counts from that point. docs/USAGE.md says so.
  • /login in a running session. /login sets the session's totals back to zero under the same session id, which used to drop everything the session had counted today. Now, when today's record of a session stops carrying on, the old run is kept under <session id>@<time last seen> and a new record starts. Both count towards today, so spend and API time from before the login stay, and each run keeps its own clock interval. A restart is always written to the state file.
  • A clock that ran ahead. A render while the system clock runs ahead stamps its session's record with a future time, and past UTC midnight with a future day. Once the clock was put right, that record used to count on the next real day, including clock time that hadn't happened yet. Each record now also keeps dayFirstSeenAt, the time its day's starting point was taken. Any record last seen more than a minute after now is settled. If it's dated today and dayFirstSeenAt has already passed, it stays, marked as last seen now. Otherwise it's dropped. Settling a record forces a write.
  • Billed spend in the account's currency. With billed spend on, the rate now uses the currency the usage API reports, as Extra Usage Today does (€23.45/hr), including the thousands separator ($1,234.50/hr). Claude Code's own costs stay in US dollars.

Demo

Rendered through the real pipeline from a scratch home whose state file holds an earlier session from today ($3.70, 30 minutes of Claude working, running 30 minutes). The rendered session adds $2.50 and 30 minutes of work over its 1-hour run. Billed spend comes from a fake login ($123.45 this month, $100.00 by the end of yesterday). From left: active time ($6.20 ÷ 1 h), clock time ($6.20 ÷ 1.5 h), billed spend ($23.45 ÷ 1 h), and Extra Usage Today.

Powerline

Daily Cost Rate with active time, clock time and billed spend, Powerline mode

Plain

Daily Cost Rate with active time, clock time and billed spend, plain mode

Switching t and b in the line editor:

Powerline

Toggling time and cost source for Daily Cost Rate, Powerline mode

Plain

Toggling time and cost source for Daily Cost Rate, plain mode

Update

Daily Cost Rate (active time | clock time) rendered through the real pipeline, each render at a set clock time, with made-up sessions and amounts: a session that cost $8.00 yesterday is resumed today with claude --resume. Before, the resume alone shows $12.00/hr | $4.00/hr, and 30 minutes later $11.40/hr | $3.80/hr. After, it shows nothing until something is spent today, then $9.00/hr | $3.00/hr.

Powerline, before and after:

Before, Powerline

After, Powerline

Plain, before and after:

Before, Plain

After, Plain

Daily Cost Rate (active time | clock time) through the real pipeline at set clock times, with made-up amounts: a session runs /login at 10:00 after $6.00 and 30 minutes of work today. Before, the line goes blank and then reads $36.00/hr | $9.00/hr, which counts only what came after the login. After, it stays at $12.00/hr | $3.00/hr and then reads $15.43/hr | $3.86/hr for the whole day.

Powerline, before and after:

Before, Powerline

After, Powerline

Plain, before and after:

Before, Plain

After, Plain

Daily Cost Rate (active time | clock time) through the real pipeline at set clock times, with made-up sessions: the system clock runs a day ahead for one render of session A, then is put right. Before, the next real day's line still counts A and reads $14.00/hr | $0.35/hr. After, it counts only session B, which actually ran that day: $6.00/hr | $1.00/hr.

Powerline, before and after:

Before, Powerline

After, Powerline

Plain, before and after:

Before, Plain

After, Plain

Daily Cost Rate (active time, clock time, billed spend) next to Extra Usage Today, rendered from a fake login's usage cache (fake data, nothing fetched) for an account billed in euros and a US-dollar account spending over $1,000 an hour. Before, billed spend reads $23.45/hr and $1234.50/hr. After, it reads €23.45/hr and $1,234.50/hr, matching Extra Usage Today.

Powerline, before and after:

Before, Powerline

After, Powerline

Plain, before and after:

Before, Plain

After, Plain

Testing

  • On main as of 2.2.34 (0c94df7): it merges after one docs conflict next to feat(thinking-effort): optional brackets and per-level colors #777's Thinking Effort sentence, resolved by keeping both. bun run lint is clean, and bun test on Linux CI gives 4442 pass, 0 fail (4403 on main). The built CLI under Bun 1.4.4 and Node 26.13.0 agrees across runtimes and matches main in plain and Powerline mode, and the TUI opens and exits cleanly under both. It adds no JavaScript or Node API newer than Node 14, the build's target.
  • Session records with hand-checked times: a session started today, an overnight session with and without a record from yesterday, a same-day update keeping the start values. Totals: cost and active time across sessions, clock time for overlapping and gapped sessions, an overnight session's clock time starting at 00:00 UTC, yesterday's sessions left out. Two profiles kept apart, no write when nothing changed within a minute, and a held lock still counting this render's session. The state file validates and prunes sessions.
  • prefetchDailyCostIfNeeded: nothing recorded without the widget or without a session id, cost and both durations; recorded under CLAUDE_CONFIG_DIR or default.
  • Prefetch: no usage fetch for the widget without billed spend, and a fetch of exactly extraUsageEnabled / extraUsageUsed plus today's spend with it.
  • Widget: active and clock time, billed spend, nothing before today's billed spend is known, nothing before a full minute, no totals, the cost number format, the preview, both keybinds, the editor row, and its label in the label editor.
  • With HOME pointed at an empty directory the new and touched test files pass (100 tests) and leave no ccstatusline files there. Under Node (Vitest) the same files pass, 100 of 100.
  • Real pipeline from a scratch home (as in the demo): Rate Today: $6.20/hr | Rate Today: $4.13/hr | Rate Today: $23.45/hr | Spend Today: $23.45, and the state file then holds both sessions.
  • Built CLI under Bun 1.4.2 and Node 26.10.0 with that home and payload: all runtimes give identical output in plain and Powerline modes. The TUI opens and exits cleanly under both.

Update:

  • Under Node (Vitest), the daily-cost, daily-state and Daily Cost Rate test files pass, 44 of 44.
  • New session tests, each failing before the fix: a session resumed the next day counts $0 / 0 min / 0 h (was $8 / 40 min / 2 h); a fork counts only its own $5 / 20 min / 1 h (was $10 / 40 min / 2 h); a /login keeps the $6 / 30 min / 2 h counted before it (was 0 / 0 / 0); a session resumed the same day gets 3 h of clock time, leaving the gap out (was 2 h).
  • Clock-ahead tests: a session the skewed render carried into the next day drops out there, leaving $0.50 / 5 min / 30 min (was $3.50 / 35 min / 2.5 h). A skew put right the same day keeps $8 / 80 min / 10 h 5 min across three sessions: one first seen today, one open since yesterday, and one no longer rendering.
  • Widget: billed spend on a EUR account renders Rate Today: €50.00/hr (was $50.00/hr).
  • Real pipeline with each render's clock set, as in the demos (before → after): resume $12.00/hr | $4.00/hr → nothing, then $11.40/hr | $3.80/hr → $9.00/hr | $3.00/hr; /login nothing → $12.00/hr | $3.00/hr, then $36.00/hr | $9.00/hr → $15.43/hr | $3.86/hr; next real day after the clock ran ahead $14.00/hr | $0.35/hr → $6.00/hr | $1.00/hr; billed spend $23.45/hr → €23.45/hr and $1234.50/hr → $1,234.50/hr. A clock that ran 2 h ahead and was put right the same day renders identically before and after.

On usage-based plans (Claude Enterprise) the usage API reports every
rate-limit window as null and no limits[] entries: there's no plan limit
to go over, and extra usage is the account's whole spend. The Extra
Usage widgets still called it overage ("Overage Used: $123.45"), and
their picker descriptions only mentioned pay-as-you-go overage, so
Enterprise users had no reason to think these widgets were theirs.
Searching the picker for "enterprise" or "spend" didn't find them.

The parser now flags a response that explicitly reports no plan limits
(`noPlanLimits`). The flag is kept in the usage cache and through the
merge with statusline rate_limits, and the three widgets label their
value "Spend Used", "Spend Left" and "Spend" when it's set. Only an
explicit null counts and any limits[] entry counts as a limit, so every
uncertain case keeps the "Overage" label. A cache written before this
change keeps the old label until its next refresh.

The widget descriptions now mention both Pro/Max overage and Enterprise
spend, which also makes the picker's search find them.
Move the terminal width cache's best-effort O_EXCL lock into its own
module so other cache files can use the same read-modify-write
protection instead of copying it. No behavior change.
Some usage figures are per UTC day, but ccstatusline only ever sees the
current month-to-date totals. Keep a small state file next to the other
caches that records what was seen and when, modeled on the terminal
width cache: one JSON file, the shared lock around each
read-modify-write, an atomic temp-file rename, pruning to today and
yesterday, and injected file and clock dependencies.
The usage API reports extra usage spent month to date only. Record the
total per login in the daily state file and work out today's spend from
where it stood when the UTC day began: the last value seen the previous
day, zero on the 1st (extra usage resets at 00:00 UTC), or otherwise the
first value seen today. A total that drops mid-day never makes today's
spend negative, and an observation that loses the state lock to another
process still reports today's spend.
fetchUsageData now remembers the token fingerprint of the login it
used. When a line shows today's spend, the prefetch records the
month-to-date total for that login in the daily state file and adds
extraUsageUsedToday (cents) to the usage data. It's worked out on every
render, cache hits included, and never stored in the usage cache.
Shows the extra usage spent since 00:00 UTC, including claude.ai and
other machines, labeled like its siblings: "Spend Today" on accounts
without plan limits, "Overage Today" otherwise. It shows nothing until a
usage fetch has run since the UTC day began, and n/a when extra usage
is off, with the same hide options, currency and cost number format as
the other Extra Usage widgets.
Today's spend recorded every usage prefetch as an observation at render
time, cache hits and stale fallbacks included. A total fetched at 23:58
UTC on the last day of the month and replayed from the cache at 00:01
became the 1st's first observation, so Spend Today showed the whole
previous month for up to three minutes, or for as long as the API stayed
unreachable.

fetchUsageData now reports when its data came from the API
(getUsageFetchedAt: now for a fresh fetch, the cache file's write time
for a cache hit or stale fallback), and the observation is recorded at
that time. A total fetched before midnight updates the previous day's
record, so today's spend shows nothing until a total fetched today
arrives, and an older fetch replayed after a newer one is ignored.
Today's extra usage spend depends on fetchUsageData recording which
login and which fetch its data came from, and every other test replaces
that link with a spy. Run the real fetch in the probe harness and check
it reports the login fingerprint the usage cache is written with and the
API fetch time, and neither when there are no credentials.
Claude Code reports each session's cost and time as running totals.
Keep each session's totals per Claude Code profile in the daily state
file, with where they stood when the UTC day began (zero for a session
that started today, otherwise the last totals seen yesterday, or the
first seen today), and work out today's totals across the profile's
sessions: cost, active time (parallel sessions add up) and clock time
(the time any session was running, counted once). Unchanged totals
aren't rewritten more than once a minute.
When a line shows Daily Cost Rate, each render records its session's
totals under the Claude Code profile (CLAUDE_CONFIG_DIR, or default)
and passes today's totals to widgets as dailyCost. With the widget's
billed spend option on, the usage prefetch also fetches the extra usage
state and works out today's billed spend; without it, the widget
triggers no usage fetch at all.
Session Cost Rate shows one session's cost per hour; Daily Cost Rate
shows it across all of today's Claude Code sessions ("Rate Today:
$6.20/hr"). It divides Claude Code's own session costs by default; the
b keybind switches to today's billed spend (as Extra Usage Today shows
it, including claude.ai and other machines). The t keybind switches from
active time (Claude working, parallel sessions adding up) to clock time
(the time any session was running). It shows nothing until a full minute
of the chosen time has passed.
# Conflicts:
#	src/widgets/ExtraUsageRemaining.ts
#	src/widgets/ExtraUsageUsed.ts
#	src/widgets/ExtraUsageUtilization.ts
Upstream's label editor (sirmalloc#601) gives each widget one default label,
while Extra Usage Used, Remaining and Utilization pick "Overage" or
"Spend" by account. The editor offers the Overage label, since it has
no usage data, and an edited label replaces whichever one the account
would show.
With the label editor (sirmalloc#601) in main, anyone on a usage-based Enterprise
plan can relabel the Extra Usage widgets' "Overage" to "Spend" in a few
keys, so detecting those accounts from the usage API's response shape
isn't worth its cache field and heuristics.

What stays is the wording: the three widgets' descriptions say they
cover Pro/Max overage and Enterprise spend, the docs say the same and
point at the label editor, and picker searches for "enterprise" or
"spend" list the three widgets first, which a new test checks.
…to feat/extra-usage-today

#32 no longer detects accounts without plan limits, so Extra Usage Today
keeps a fixed "Overage Today: " label, as the other Extra Usage widgets
do; the label editor can change it.
The two widgets were the same class apart from how the amount is worked
out, and their label, name, description and preview sample. They now
extend ExtraUsageAmountWidget, the way the Tokens widgets share
TokenCountWidget. Rendering is unchanged.
Extra Usage Today ignores a fetch older than the one it last recorded,
so a cached fetch a concurrent render replays late can't move the day
back. A single render made while the system clock ran ahead defeats
that: it records a fetch stamped at a time that hasn't come yet. Once
the clock is put right, every real fetch looks older and is ignored, so
Today disappears for the rest of the day; and when the clock reaches the
stamped time, that record is taken as the day's, with the previous
day's total as its start. With $10 seen at 09:00, one render a day
ahead, then $25 and $40 later that day, Today was hidden for the rest of
the day and showed $40 the next day for at most $10 of real spend.

The usage cache that render wrote is stamped by the same clock and is
served as fresh until the clock catches up with it, so its fetch keeps
arriving with the future time and would store the same record again.

A record last seen more than a minute ahead of now is now dropped and
the day starts afresh, and a fetch stamped more than a minute ahead
isn't recorded. The minute's leeway keeps a small step back of the
clock, such as an NTP correction just after a fetch, from dropping the
day's starting point. Now is read after the state file, so a fetch
another render has just recorded is never taken for one from the
future and the replay guard still holds.
# Conflicts:
#	docs/USAGE.md
#	src/utils/usage-prefetch.ts
… its new totals

Daily Cost Rate worked out each session's share of today from Claude
Code's running totals, assuming they count up without a break from the
session's start. They don't always:

- On --resume, /resume and --fork-session, Claude Code restores the
  session's earlier cost and API time and backdates its start by the
  time it ran before. A session that ran yesterday for 2 hours and cost
  $8 read as started 2 hours ago, so it counted from zero and today
  showed yesterday's $8, 40 minutes of API time and 2 hours of clock
  time. A fork added its source's totals a second time.
- /login sets the totals and the duration back to zero under the same
  session id. The day's starting point dropped with them, so the
  session's $6 and 2 hours so far today were lost.

A session's totals now carry on from its record only while neither
total goes down and its start doesn't move later. Otherwise this is a
new run: it counts from the totals it was first seen with (zero for a
new session) and its clock time from when it was first seen, kept in
the record's new firstSeenAt. A run recorded earlier the same day is
kept under its own key, so what it counted still counts and its clock
time stays where it was. A same-day resume therefore no longer counts
the time between the two runs either.

A session first seen with spend already on it, such as one open before
the widget was added, now counts from then rather than from zero, the
same as an overnight session first seen today already did.
…head

A session record keeps the time it was last seen. When the system clock
ran ahead past the next UTC midnight for a render and was then put
right, that render's record stayed dated the day after. Pruning keeps
everything from yesterday on, so the record was kept, and when that day
came Daily Cost Rate counted the session as one of its own: its cost
and active time, plus clock time up to a last-seen time that hadn't
happened yet (2.5 hours of clock time at 07:00 for a session that never
ran that day).

A record last seen more than a minute after now was stamped while the
clock ran ahead; the minute allows for small clock corrections, as in
Extra Usage Today. Each record now also keeps when it was first seen on
its day, which is when that day's starting point was taken. If that was
today, at a time that has come, only the last-seen time is off, and the
record counts as last seen now: a clock that runs ahead and is put right
within the day leaves the day's totals as they were. Otherwise the
record's day can't be trusted either, and it's dropped; the session
counts afresh from its current totals. What it had counted on the day
the clock ran ahead past midnight isn't recovered, as with Extra Usage
Today.
With billed spend on, Daily Cost Rate divides today's extra usage spend,
which the usage API reports in the account's own currency. The rate was
always formatted as US dollars, so a euro account read "Rate Today:
$50.00/hr" next to Extra Usage Today's "Overage Today: €50.00" for the
same spend.

Billed spend is now formatted in the reported currency, as the Extra
Usage widgets do; Claude Code's own costs stay in US dollars.
updateDailyState writes daily.json through a temp file named
daily.json.<pid>.tmp and renames it into place. When the write or the
rename failed, for example a write cut short by a full disk or a rename
refused with EPERM while a Windows virus scanner or sync client holds
daily.json, the error went to the catch-all and the temp file stayed
behind. Every status line render is a new process with a new pid, so
each failing render left another orphan in ~/.cache/ccstatusline, and
nothing ever deleted them.

A failed write or rename now unlinks the temp file. A failed unlink is
ignored; as before, the state stays best-effort and the render goes on.

The same handle can be held on the temp file itself, and then it
refuses the unlink as well as the rename. So each write also removes
the other daily.json.<digits>.tmp files next to the state file once
they are a minute or more old, which no running write can still own.
While a handle stays held, only the last minute's temp files remain,
and orphans an older build left behind are cleared as well. The temp
name stays per process, so two renders never write through the same
file.
Extra Usage Today keeps each login's month-to-date total at the start of
the UTC day in daily.json, keyed by the usage cache's token fingerprint,
a hash of the refresh token. Claude Code saves a new refresh token each
time it refreshes the access token, which happens several times on a
working day. The key then changed mid-day, the new key had no record,
and today's spend started over from that moment: $15.00 at 13:00, then
$0.00 at 17:00 instead of $35.00 and $10.00 at 18:00 instead of $45.00.
The old record stayed behind until it was pruned.

The record is now kept under the account and organization the
credentials belong to. While a widget shows today's spend, ccstatusline
asks /api/oauth/profile through the usage fetch's own request, proxy
and credential code, once per token fingerprint, and keeps the answers
in ~/.cache/ccstatusline/usage-account.json. A failed lookup holds off
that fingerprint alone, for 30 seconds or a 429's Retry-After (at most
a day), and the hold-off is written before the request goes out, so
renders running side by side send one request between them.

Until the lookup answers, the record stays under the fingerprint as
before. Once the account is known, the records under its fingerprints,
written by an earlier build or while the lookup was failing, are folded
into the account's record once, so the day keeps its starting total.
A record seen while the clock ran ahead is dropped instead, as it would
be under its own key. A fingerprint that was never looked up can't be
placed with an account, so today's spend still starts over once when
an earlier build kept the record under a refresh token that has since
changed, or when a lookup outage spans a refresh.

The organization is part of the key because one account can sign in to
a personal organization and a work one, each with its own extra usage
total. The key is a hash, so neither cache file names the account.
mergeSpendRecord goes through an arrow, so reduce's index and array
arguments never reach it, and the account id is built before it's
fingerprinted instead of inside a nested template literal.
Upstream sirmalloc#699 added getUsageFetchedAtMs, which records the same fetch time
as this branch's getUsageFetchedAt, so Extra Usage Today now reads that one.
Upstream sirmalloc#724's account email lookup also asks the profile endpoint; this
branch's account lookup keeps its own schema (ProfileAccountIdsSchema) and
cache next to it.
Brings in upstream main through #36. Daily Cost Rate's billed-spend test
reads the fetch time from getUsageFetchedAtMs, which #36 now uses.
…and the account key

The Claude Account Email widget (sirmalloc#724) and Extra Usage Today each asked
/api/oauth/profile about the same login, each with its own cache and backoff.
One request now answers both. lookUpProfile runs under the email lookup's
per-login lease and backoff files, and each caller keeps its part of the
answer in its own cache: the email in account-email-<hash>.json, the account
key in usage-account.json, which now holds only named logins. An answer that
leaves out the caller's part holds that login off as before, and the other
part is still kept.

A rate-limited lookup's Retry-After is kept within the day the backoff reader
trusts, as the account lookup did, so the email lookup no longer reads a
Retry-After further off as no backoff at all.
The account key nested the id's template inside its own on one line. Build
the id first, as the account lookup did before it shared the profile
request.
It names its label like the other labeled widgets, so the label editor
offers it.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant