Repository navigation
feat(usage): color Extra Usage Used, Today and Utilization by break points or a gradient - #41
Draft
eric-engberg wants to merge 86 commits into
Draft
eric-engberg wants to merge 86 commits into
eric-engberg wants to merge 86 commits into
Conversation
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.
With a monthly extra usage limit, the useful number during a day is how much can still be spent per day without running out before the limit resets. Extra Usage Daily Budget shows what's left of the monthly limit divided by the days left in the month, today included, so it rises on light days and falls on heavy ones. Monthly limits reset at 00:00 UTC on the 1st, so days are UTC days. A `w` keybind switches to counting weekdays only (Saturday and Sunday in UTC); today always counts, even a weekend day, so the budget never divides by zero. Once the limit is used up it shows $0.00; without a monthly limit it shows nothing, like Extra Usage Remaining.
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.
…nto feat/value-coloring # Conflicts: # docs/USAGE.md
…t/value-coloring # Conflicts: # docs/USAGE.md # src/utils/__tests__/usage-prefetch.test.ts # src/utils/usage-prefetch.ts # src/utils/widget-manifest.ts # src/widgets/ExtraUsageUtilization.ts
Thinking Effort's level colors, Model's family colors and the color list editor each wrapped text in a color and restored the default foreground the same way. Value coloring would be the fourth, so they share one helper.
With value colors on, the percent is green below 70% used, yellow below 90% and red from 90%, following the used percent even while the widget shows what's left. A gradient mode instead places it along a bar gradient preset on truecolor terminals, falling back to the break points below that. `v` opens an editor for the mode, colors and break points in percentage mode; the bar modes keep their bar gradients. The coloring and its editor are shared, for Extra Usage Today next. The color list editor's setting rows now step both ways and can take a typed number.
Extra Usage Today's value colors measure today's spend against the same daily budget, so they need the same weekdays-only option.
With value colors on, today's spend is green below 80% of the day's budget, yellow up to all of it, and red above it or when nothing of the monthly limit was left as the day began. The budget is what was left when the UTC day began, spread over the days left in the month as Daily Budget does; `w` counts weekdays only. Without a monthly limit the value keeps the widget color. The usage fetch asks for the limit only while value colors are on.
# Conflicts: # src/widgets/shared/color-list-editor.tsx
…render The preview and the live value each worked out the bar or the colored percent the same way; one function now does both.
# Conflicts: # docs/USAGE.md # src/widgets/__tests__/ExtraUsageUtilization.test.ts
# Conflicts: # docs/USAGE.md
A break point held one above the other, or typed, kept its odd offset on every later step (71, 76, 81...), so it never landed on a multiple of 5 again. Steps now go to the next multiple of 5 in that direction.
Gradient mode reached its end color at the high break point and fell back to the break points below truecolor, so at the default 256-color level it showed the break point colors, and in both modes the editor listed settings that did nothing. Each mode now shows only its own settings. Gradient mode has an "ends at" percent (stored as valueGradientEnd, defaulting to where the high band starts) past which the value keeps the end color. The gradient steps through the 256-color palette at that level, and at Basic (16 colors) the value keeps the widget color. The editor gets the settings, draws its sample at the configured color level, and warns when the level can't show a smooth gradient.
Extra Usage Used gets value colors (v): its spend as a percent of the monthly limit, with Utilization's break points (green below 70%, yellow below 90%, red from 90%), or a gradient. Without a monthly limit it keeps the widget color. A gradient now ends by default at 100%, the whole limit or Extra Usage Today's whole budget, rather than where the high band starts, so a gradient reaches its end color at the limit.
The break point and gradient row lists are only ever asked whether they hold a key, so they're sets. The color list editor's selection state gets a setter named after it.
This was referenced Oct 6, 2026
…eat/value-coloring
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 #40. Extra Usage Today's files take the resolutions #36 made when main was merged into it. Its value colors test stubs getUsageFetchedAtMs, which #36 now reads in place of its own getUsageFetchedAt. # Conflicts: # docs/DEVELOPMENT.md # docs/USAGE.md # src/types/RenderContext.ts # src/utils/__tests__/usage-fetch.test.ts # src/utils/__tests__/usage-prefetch.test.ts # src/utils/usage-fetch.ts # src/utils/usage-prefetch.ts # src/utils/usage-types.ts # src/utils/usage.ts
eric-engberg
added a commit
that referenced
this pull request
Oct 30, 2026
Brings in upstream main through #41, which now holds #33 as upstream sirmalloc#756. Main adds Extra Usage Limit at the same places the #33 branch merged here did, so the widget manifest, the usage prefetch's widget list and requirements, and its prefetch test keep main's single entry. Daily Cost Rate's billed-spend test stubs getUsageFetchedAtMs, which #36 now reads in place of its own getUsageFetchedAt. # Conflicts: # docs/USAGE.md # src/ccstatusline.ts # src/types/RenderContext.ts
# Conflicts: # docs/USAGE.md
# Conflicts: # docs/USAGE.md
# Conflicts: # docs/USAGE.md
# Conflicts: # docs/USAGE.md
…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.
# Conflicts: # docs/USAGE.md
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.



Stacked on #40, and merges #34 (Daily Budget) and #36 (Extra Usage Today, which builds on #32): review the ten non-merge commits after those merges. A later merge brings in #40's follow-up refactors. It builds on #40's color list editor and #10's gradient presets, so it goes upstream after the stack, #34 and #36. Closes #39.
What
Extra Usage Used, Extra Usage Today and Extra Usage Utilization can color their value by how high it runs. With break points (the default), the value is green, yellow or red. In gradient mode it takes a place along a bar gradient preset, reaching the preset's end color at a set value: 100% by default, the whole limit or the whole day's budget.
vopens an editor that shows only the current mode's settings. Acolorssetting can color the whole widget instead of just the value: the label takes the value's color too, so the widget turns one color that moves with the value. Extra Usage Today also getswto count weekdays only. All three are off by default.Why
My old bash status line colored the day's spend against the day's budget and the month's spend by how close it was to the limit. A glance at the color told me whether to slow down, without reading the numbers. Here every value is the widget's single color, so $4.31 of a $4.79 budget looks the same as $4.31 of $13.16, and $450 spent of a $500 limit looks the same as $45.
How
Shared coloring (
value-coloring.ts): a value is a percent (of the day's budget, or of the monthly limit). Each widget supplies its default break points and whether a value exactly at the high one is already high:Gradient mode reuses the bar gradient presets (
trafficby default). The position is the value divided byends at, clamped to 0–1, so anything past it keeps the end color.ends atis the gradient's own setting, 100 by default; the break points belong to break points mode and don't move the gradient.Gradients at each color level. At truecolor the gradient is smooth. At 256 Color, the default level, it steps through the 256-color palette: one color per value needs no smooth blend, unlike a bar. At Basic (16 colors) there are too few colors for a gradient, so the value keeps the widget color. Bar gradients still need truecolor, and the line editor's
needs truecolornote still applies to them. The value gradient's modifier readsvalue colors: traffic gradient, so the note doesn't match it.Extra Usage Today's budget is what was left of the monthly limit when the UTC day began, spread over the days left in the month:
(limit − (used − today)) / countBudgetDaysLeft(now, weekdaysOnly). Daily Budget's own figure shrinks as today's spend grows, so it can't be the baseline. The percent is multiplied out (today × days × 100 / left), so an amount exactly at the budget reads as exactly 100%. Without a monthly limit the value keeps the widget color. The usage fetch asks forextraUsageLimitonly while value colors are on, the same way the time cursor adds its reset field, so an uncolored widget fetches exactly what it did before.wshares Daily Budget'sweekdaysOnlykey and is offered once value colors are on.Extra Usage Used measures its spend against the monthly limit (
used / limit), with Utilization's break points. Without a monthly limit, or with a zero one, the value keeps the widget color.Extra Usage Utilization colors the plain percent only. The bar modes keep their bar gradients, and
visn't offered there. The color follows the used percent even while the widget shows what's left.Rendering, as in feat(model): optional per-family colors #40: by default the label keeps the widget color, the value gets its own color followed by
\x1b[39m, andpreservesRenderedColorsis on while value colors show. Withcolorsset toWhole widget, the label and the value are painted together in the value's color. Raw value mode has no label, so only the value is colored either way. With colors off for the whole status line, the value renders as plain text.The
colorsrow is the editor's last row, in both modes; ←→ switch betweenValue onlyandWhole widget. With the whole widget on, the sample shows each value with the widget's label (each widget passes its default label to the editor, and an edited label shows as edited), and the line editor's modifier addswhole widget.Settings stay minimal. Each key below is stored only when it differs from its default, and
dresets everything but the on/off switch:valueColorsandvalueColorMode: gradient;valueColor.<low|mid|high>,valueMidFromandvalueHighFrom;valueGradientandvalueGradientEnd;valueColorScope: widgetfor the whole widget, in either mode.Editor: feat(model): optional per-family colors #40's color list editor gains:
isRowShown, which hides rows that don't apply;getNotice, a warning line;Rows by mode:
xcustom),mid from, andhigh from/high above.ends at.Percent rows step to the next multiple of 5 in that direction, so a value held one above the other break point, or typed, gets back onto the fives. The sample shows values on both sides of each break point (
40% 80% 100% 120% of today's budget), or along the gradient and past its end (25% 50% 75% 100% 125%).The editor knows the color level. Widget editors now receive the settings (
WidgetEditorProps.settings, optional), so the sample is drawn at the configured color level. In gradient mode the editor warns about each level below truecolor, pointing to Terminal Options:Without settings, as in tests, the sample uses 256 colors as before.
Refactors:
foreground.ts;daily-budget.ts;Previews:
Demo
Piped through the real pipeline with a fake login and a fresh usage cache (no API call), at three levels of spend; all amounts are made up. Each scenario renders break points, the gradient in truecolor, then the gradient at 256 colors (a copy of the config at that level). Powerline first; its config gives the segments a dark custom background.
Powerline
Plain
The editor on Extra Usage Used, at the default 256 colors:
mid fromto 75%.ends atdown to 90%.(value colors: traffic gradient).Powerline
Plain
Whole widget: Extra Usage Utilization's value colors (gradient, truecolor) switched from
Value onlytoWhole widget. The sample shows each value with its label, and after Enter the preview's Utilization segment is one color, label and all, while Extra Usage Used (break points) keeps its label in the widget color.Powerline
Plain
Testing
value-coloring.test.ts(30) covers:needs truecolornote leaves it alone;d, the modifier, and the label in the band's color or at the value's point on the gradient (also raw, edited label, no percent and colors disabled).value-colors-editor.test.ts(14 Ink tests) covers:high from/high abovelabel and the 100% cap;ends at;d;colorsrow in both modes, and the sample with the widget's label, but none in raw value mode.ExtraUsageUsed.test.ts(7 new) covers:preservesRenderedColors.ExtraUsageUtilization.test.ts(9 new) covers:preservesRenderedColors;ExtraUsageToday.test.ts(12 new) covers:preservesRenderedColors.usage-prefetch.test.ts(1 new) andforeground.test.ts(4).bun testgives 3308 pass, 0 fail (Bun 1.4.2).bun run lintis clean. An 8-run loop of the editor's and Utilization's tests had no failures after the whole-widget option.usage-fetch.test.ts(from feat: add an Extra Usage Today widget #36) fails 38 tests under Node withERR_MODULE_NOT_FOUND. The same 38 fail on b1403f3, this branch before the gradient rework, and nothing undersrc/utilshas changed since.vi.spyOnon ESM exports.runtime-check.sh -c value-colorswith a seeded fake home showed Bun 1.4.2 and Node 26.10.0 agreeing byte for byte in plain and Powerline modes. The TUI opens and exits under both.ends at95%, and save.