Skip to content

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
feat/model-family-colorsfrom
feat/value-coloring
Draft

eric-engberg wants to merge 86 commits into
feat/model-family-colorsfrom
feat/value-coloring

Conversation

@eric-engberg

@eric-engberg eric-engberg commented Oct 5, 2026 •

Copy link
Copy Markdown
Owner

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. v opens an editor that shows only the current mode's settings. A colors setting 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 gets w to 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:

    green yellow red
    Extra Usage Used (% of the monthly limit) below 70% 70% to below 90% 90% and above
    Extra Usage Today (% of the day's budget) below 80% 80% to 100% above 100%, or nothing left as the day began
    Extra Usage Utilization (% used) below 70% 70% to below 90% 90% and above
  • Gradient mode reuses the bar gradient presets (traffic by default). The position is the value divided by ends at, clamped to 0–1, so anything past it keeps the end color. ends at is 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 truecolor note still applies to them. The value gradient's modifier reads value 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 for extraUsageLimit only 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. w shares Daily Budget's weekdaysOnly key 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 v isn'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, and preservesRenderedColors is on while value colors show. With colors set to Whole 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 colors row is the editor's last row, in both modes; ←→ switch between Value only and Whole 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 adds whole widget.

  • Settings stay minimal. Each key below is stored only when it differs from its default, and d resets everything but the on/off switch:

    • valueColors and valueColorMode: gradient;
    • break points mode: valueColor.<low|mid|high>, valueMidFrom and valueHighFrom;
    • gradient mode: valueGradient and valueGradientEnd;
    • valueColorScope: widget for 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;
    • setting rows that step both ways and take a typed number.

    Rows by mode:

    • Break points: mode, the three colors (←→ named, x custom), mid from, and high from/high above.
    • Gradient: mode, the preset, and 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:

    • 256 Color: coarse steps;
    • Basic: no gradient;
    • No Color: no color at all.

    Without settings, as in tests, the sample uses 256 colors as before.

  • Refactors:

    • the label/value painting that Thinking Effort and Model each had is now foreground.ts;
    • Daily Budget's weekdays toggle moved to daily-budget.ts;
    • Utilization's preview and live value share one function for "the bar, or the percent in its value color".
  • Previews:

    • Utilization's 85% sample previews in yellow.
    • Today's $46.10 sample is measured against Daily Budget's $194.70 sample, so it previews in green.
    • Used's $106.00 sample is measured against a $4,000 limit (Remaining's $3,894.00 sample plus it), so it previews in green.

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

Value colors, Powerline

Plain

Value colors, plain

The editor on Extra Usage Used, at the default 256 colors:

  1. Turn value colors on.
  2. Step mid from to 75%.
  3. Switch to the gradient: its rows replace the break points', and the 256-color warning appears.
  4. Step ends at down to 90%.
  5. Save. The row then reads (value colors: traffic gradient).

Powerline

Value colors editor, Powerline

Plain

Value colors editor, plain

Whole widget: Extra Usage Utilization's value colors (gradient, truecolor) switched from Value only to Whole 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

Whole widget value colors in Powerline mode

Plain

Whole widget value colors in plain mode

Testing

  • New tests:
    • value-coloring.test.ts (30) covers:
      • every band edge under both edge rules, custom break points and minimal metadata;
      • stepping, including back onto the fives from an odd value, and typed break points with their errors;
      • the gradient end: default, stepping, typing, and kept apart from the break points;
      • reset;
      • gradient positions against the end (0, half, at and past it, and nothing left) and the preset;
      • 256-color steps, and the widget color at 16;
      • the modifier, and that the line editor's needs truecolor note leaves it alone;
      • formatting: off, raw, label color, no percent, colors disabled;
      • the whole widget: stored and cleared, reset with 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:
      • break points mode's rows and sample, the high from/high above label and the 100% cap;
      • Space;
      • switching to the gradient, after which only its rows show and the sample runs past its end;
      • the preset both ways, and stepping and typing ends at;
      • the warning at 256 Color, Basic and No Color, and none at truecolor or in break points mode;
      • break point stepping, a typed value, a rejected one and ESC;
      • colors, and d;
      • the colors row in both modes, and the sample with the widget's label, but none in raw value mode.
    • ExtraUsageUsed.test.ts (7 new) covers:
      • bands at exact amounts: $349.99 / $350.00 / $449.99 / $450.00 of a $500.00 limit;
      • the label, and no limit (missing or zero);
      • the gradient against the limit, a custom end, 256 and 16 colors;
      • colors disabled, the preview, and the keybind, modifier and preservesRenderedColors.
    • ExtraUsageUtilization.test.ts (9 new) covers:
      • bands, the label, and the used percent while showing what's left;
      • the gradient at each color level, and colors disabled;
      • bar modes unchanged, the preview, keybinds and modifier, and preservesRenderedColors;
      • the whole widget: the label in the percent's color, the modifier, and the editor's sample with the widget's label.
    • ExtraUsageToday.test.ts (12 new) covers:
      • bands at exact amounts: $7.99 / $8.00 / $10.00 / $10.01 of a $10.00 budget;
      • the label, weekdays only, nothing left at the start of the day, no monthly limit, and today's spend not known yet;
      • the gradient at each color level, and colors disabled;
      • the preview, keybinds, modifiers and preservesRenderedColors.
    • usage-prefetch.test.ts (1 new) and foreground.test.ts (4).
  • Written first: the original tests, and the tests for the break point stepping fix and for Extra Usage Used, were written before their code, and I watched them fail. The stepping test failed with 76 where 75 was expected. The gradient rework's tests were written alongside it. The original shared coloring tests were mutation-checked: all 15 mutations were caught.
  • Flakiness: a 15-run loop of the value colors editor's Ink tests had no failures.
  • Bun: bun test gives 3308 pass, 0 fail (Bun 1.4.2). bun run lint is clean. An 8-run loop of the editor's and Utilization's tests had no failures after the whole-widget option.
  • Whole widget under Node 26 vitest: its three test files pass (69 tests).
  • Node 26 vitest: 12 of the 13 touched test files pass (228 tests).
  • Built CLI on both runtimes: runtime-check.sh -c value-colors with 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.
  • Editor under Node: I drove it in tmux under Node 26 with the built CLI on Extra Usage Used: on, the gradient, the 256-color warning, ends at 95%, and save.

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
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.
@eric-engberg eric-engberg changed the title feat(usage): color Extra Usage Today and Utilization by break points or a gradient feat(usage): color Extra Usage Used, Today and Utilization by break points or a gradient Oct 6, 2026
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.
@sonarqubecloud

Copy link
Copy Markdown

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
…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.
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.

Color Extra Usage Today and Utilization values by break points or gradient

1 participant