Repository navigation
feat: add a Daily Cost Rate widget - #37
Open
eric-engberg wants to merge 208 commits into
Open
eric-engberg wants to merge 208 commits into
eric-engberg wants to merge 208 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.
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.
eric-engberg
force-pushed
the
feat/daily-cost-rate
branch
from
October 5, 2026 15:35
3f630cb to
548e3bd
Compare
This was referenced Oct 6, 2026
* feat(git-is-fork): render forks as an editable glyph Replace the isFork: true label with a glyph (default U+2442 OCR FORK) when origin and upstream diverge. The glyph is editable via the existing symbol override editor (g); raw value still renders true. The not-fork output and its not-fork hide state are unchanged. Refs sirmalloc#615 Co-Authored-By: Claude Code <noreply@anthropic.com> * fix(git-is-fork): detect forks with inverted remotes via a "fork" remote A real GitHub fork with the inverted local layout (origin points at the parent, the personal copy is a remote named "fork", no literal upstream) was misdetected as not-a-fork, hiding the glyph. getForkStatus now falls back to the literal "fork" remote as the peer when "upstream" is absent; unnamed extra remotes still never trigger the detection. Deliberately not routed through getUpstreamRemoteInfo, whose tracking-remote fallback can resolve to origin itself. Co-Authored-By: Claude Code <noreply@anthropic.com> --------- Co-authored-by: axisrow <axisrow@users.noreply.github.com> Co-authored-by: Claude Code <noreply@anthropic.com>
…irmalloc#606) Since Claude Code 2.1.51 a custom statusLine command only runs in a trusted workspace, and since 2.1.232 a git repository nested under a trusted parent folder no longer inherits that trust. Claude Code does not always re-show the trust dialog, so in such a folder ccstatusline is never invoked and the status line is an empty row, while running the command by hand works and other folders are fine. It looks exactly like a ccstatusline bug, and several repos under one parent break at once. Add a troubleshooting entry to docs/USAGE.md with the check (`hasTrustDialogAccepted` for the project path in ~/.claude.json) and a pointer to it from the README next to the other quick-start notes. Closes sirmalloc#552 Co-authored-by: D-L-Narayana <249577150+D-L-Narayana@users.noreply.github.com>
# 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.
eric-engberg
force-pushed
the
feat/daily-cost-rate
branch
from
October 6, 2026 16:47
7d0e4de to
2fd75d9
Compare
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.
…t/daily-cost-rate
…to feat/extra-usage-today
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.
…o picker fixes (sirmalloc#782) * fix(usage): print es-ES's 12-hour day period as AM/PM, not "A M" With the 12-hour clock in date mode, the Block and Weekly Reset Timers turn the locale's day period into AM/PM by dropping its dots and uppercasing it. That works for "am", "pm", "a.m." and "p.m.", but ICU writes es-ES's as "a. m." and "p. m.", with a space after the first dot, so the timers showed "10:30 A M CEST" in the status line and the preview. Locales typed in by hand such as ca, bs and es-AR write it the same way. Drop each dot together with the space after it, so "a. m." becomes "AM" like the other forms, while a day period without dots keeps its spaces. * fix(usage): keep reset dates Gregorian whatever the locale's calendar In date mode, the Block and Weekly Reset Timers ask Intl for the year, month and day in the chosen locale and fill them into a YYYY-MM-DD layout, without saying which calendar to use. ar-SA, which the locale picker offers, defaults to Gregorian in Node's ICU data but to the Islamic (Umm al-Qura) calendar in Bun's, where the month comes back as a name even though two digits were asked for. The same settings then showed "٢٠٢٦-١٠-١٣ ١٦:٠٥" under npx and "١٤٤٨-جمادى الأولى-٠٢ ١٦:٠٥" under bunx: a Hijri year with its era dropped and a month name inside the numeric layout. th-TH (Buddhist year 2569) and fa-IR (Persian year 1405) typed in by hand gave non-Gregorian dates under both runtimes. Ask for the Gregorian calendar, so the parts always fit the layout and both runtimes print the same date. The locale keeps its own digits, as it already does in its zone name and time. * fix(usage): format reset timestamps in the chosen locale at UTC too The Block and Weekly Reset Timers offer a locale in date mode whatever the timezone, and the line editor shows it ("locale: de-DE"). But with the timezone at its default, UTC, the formatter returned its fixed English format before it looked at the locale, so the weekday names and day period stayed English: "Sun 08:30 UTC" for de-DE and "8:30 AM UTC" for ja-JP, while Etc/UTC, the same zone under another name, gave "So 08:30 UTC" and "8:30 午前 UTC". When a locale is set, format UTC through Intl in that locale, as every other zone already is. The output keeps the UTC format's shape: every locale names the zone "UTC", and compact mode still ends in "Z". Without a locale the fixed format is unchanged, and en-US gives the same output as no locale. * fix(tui): let 'uk' and 'ca' pick en-GB and en-CA in the locale picker The reset timers' locale picker searches each listed locale by a few keywords, and en-GB's include 'uk' and en-CA's 'ca'. It also offers a search that is a valid locale tag not in the list as a "Use <tag>" custom row, placed first. 'uk' and 'ca' are valid tags too, for Ukrainian and Catalan, so typing either put "Use uk" or "Use ca" above en-GB or en-CA, and since the picker selects the first row after each keystroke, Enter saved Ukrainian or Catalan formatting. Put a locale whose keywords include the search ahead of the custom row. The custom row still comes next, so a Ukrainian or Catalan tag is one Down away, and any other tag the list doesn't offer, such as en-AU, still comes first. * fix(tui): open the timezone picker on a configured zone the runtime doesn't list A reset timer's timezone picker should open on the configured zone, so Enter keeps it. A valid zone that Intl doesn't list, such as Asia/Kolkata (both Node and Bun list it as Asia/Calcutta) or Etc/GMT-5 picked under Bun and reopened under Node, gets its own "Configured timezone" row right after Local. The picker found the starting row's index in the options as given, but shows them sorted, and the sort puts that row after Africa/Abidjan. So the picker opened on Africa/Abidjan, and Enter without moving saved it, switching the reset time to GMT. Find the starting row in the list as the empty search shows it. * fix(tui): keep 'uk' and 'ca' on en-GB and en-CA when either is the system or configured locale The locale picker lists the system locale and the configured locale in their own rows above the common ones, and drops the common row for the same locale. Those rows carried only "system ..." or "configured ..." search words, so when en-GB or en-CA was the system or configured locale, the 'uk' and 'ca' keywords went with the dropped row. Typing either put "Use uk" or "Use ca" first again and Enter saved Ukrainian or Catalan; for 'uk', en-GB was not even listed. That is the case for a UK or Canadian user under Node, which takes its default locale from LANG, and for anyone reopening the picker after choosing en-GB or en-CA. Give the System and Configured rows the keywords of the common locale they replace, so they match and rank the same way it would. The keyword tests now pin the runtime's locale: they passed under Bun, which reports en-US whatever LANG says, and failed under Node with LANG=en_GB.UTF-8 or en_CA.UTF-8. * fix(usage): keep the UTC label on locale-formatted UTC reset timestamps With a locale set and the timezone left at its default, UTC, the full date-mode stamp now goes through Intl in that locale and takes the zone name Intl gives. For most locales that is "UTC", but a few spell it differently: el-GR writes "2026-03-15 08:30 Συντονισμένη Παγκόσμια Ώρα", and sd, ku, sc and so give "م ع و", "SGH", "TCU" and "Waqtiga UTC", the same under Bun and Node. Without a locale these stamps end in "UTC". At UTC, the full form now ends in the fixed "UTC" label, as compact mode already ends in a fixed "Z". The weekday, day period and digits still follow the locale. An explicitly chosen IANA zone such as Etc/UTC keeps Intl's zone name, as any other zone does. * test(usage): cover the fixed UTC format when Intl rejects the locale With a locale set and the timezone at UTC, a reset timestamp goes through Intl in that locale, and keeps the fixed format when Intl can't use the locale. Only the localized outcome had tests. A POSIX-style tag such as "de_DE" is not a valid language tag, and Intl throws on it under both Bun and Node. The stamp then reads "Sun 08:30 UTC" in the full form and "Sun 08:30Z" in compact mode, where de-DE gives "So 08:30 UTC" and "So 08:30Z". * refactor(usage): format UTC reset timestamps in their own helper formatUsageResetAt parsed the timestamp, split its overloaded locale-or-hour12 argument, and then held both zone paths inline: the UTC one, which tries the chosen locale, adds the compact "Z" and falls back to the fixed format, and the IANA or local one with its en-US fallback. The UTC path moves into formatResetAtUtcInLocale, next to formatResetAtUtc and formatResetAtInTimezone, the two formatters it chooses between. formatUsageResetAt now reads as parse, normalize, then format for the zone, and its UTC branch is a single call. The output is the same for every timezone, locale and option.
…bs as one space (sirmalloc#781) * fix(ansi): hide charset escapes and DCS/APC strings whole With Preserve Colors off, Custom Command reduces its output to visible text with getVisibleText before the renderer's sanitizer sees it. The escape parser behind it read ESC and any character other than [ or ] as a complete two-character sequence. That is right for ESC 7 or ESC c, but not for ESC ( B, a character-set selection with an intermediate byte, which `tput sgr0` prints before ESC [ m on xterm-256color. Its final "B" was left as text, so a script printing "$(tput setaf 2)OK$(tput sgr0) done" showed "OKB done". DCS, SOS, PM and APC strings (ESC P ... ESC \) lost only their first two characters, so their payload printed as text. By the time the sanitizer ran, these were ordinary characters it had no reason to remove. Read these forms the way terminal-sanitize.ts already does: ESC, intermediate bytes (0x20-0x2F) and a final byte as one sequence, and a DCS, SOS, PM or APC string up to ST or BEL, stopping before any other ESC so an unterminated string doesn't hide the text after it. Visible width goes through the same parser, so with Preserve Colors on these sequences no longer count toward Max Width either. * fix(ansi): recognize color codes written with colons SGR parameters can be separated with colons, the ITU T.416 form: ESC[38:5:196m, ESC[38:2::255:0:0m, or ESC[4:3m for a curly underline, which `tput Smulx 3` prints on xterm-256color. The terminal sanitizer keeps these, but the color pattern in ansi.ts only allowed digits and semicolons, so everything downstream treated them as unknown: - a Preserve Colors Custom Command cut by Max Width never got its closing reset, so its color or underline ran into the separators and widgets after it - a global foreground override left the command's own colon-form color in place, where the semicolon form is recolored - in Powerline mode, a colon-form reset such as ESC[0;38:5:196m didn't get the segment background re-applied after it Allow colons in the pattern. When reading a sequence for a background reset, an extended color written with colons holds its arguments in its own parameter, so the following parameters are no longer skipped as if they were its arguments: ESC[48:5:1;0m ends with the background cleared, and ESC[0;38:2::0:0:0;41m keeps its red background. * fix(render): print tabs as one space and measure them as one column Widget output kept its tabs: the terminal sanitizer let them through, and width measurement gave them no columns, as string-width does for control characters. A terminal moves a tab on to the next tab stop, up to 8 columns, so a line holding one printed wider than it was measured. A Custom Command such as `git rev-list --left-right --count HEAD...@{u}`, which prints "0<tab>3", beside a flex separator filled the line to its width by count and then ran past it on screen, where it wraps or gets cut off. Max Width and the line's own truncation let the extra columns through the same way. How far a tab moves depends on the column it lands in. That isn't known while a widget is measured, before the line is laid out, and it changes with where the host draws the line, so measuring tabs at their real width can't be done reliably. Instead, the sanitizer prints each tab as one space, and width measurement counts a tab as one column, so text measured before it is sanitized, as Custom Command's Max Width is, agrees with what is printed. A single space reads as the field separator a tab usually is in one-line output, without spending up to 8 columns of the status line on it. * test(ansi): cover an escape whose final byte never comes An escape with intermediate bytes (ESC ( B) was only tested with its final byte present. Pin down what happens when it is missing: at the end of the text the escape is hidden up to where it stops, and a character that cannot end it, here an emoji, stays visible after it. * refactor(ansi): read escape bytes as code points and name the final-byte range The scan for ESC, intermediate bytes and a final byte compared raw UTF-16 units and spelled the final-byte range inline in the slice call. It now reads code points, as the grapheme-cluster scan in this file does, and tests the final byte with isEscapeFinalByte next to isIntermediateByte, so the return reads as "one past the final byte if there is one". The parse is the same for every input: both ranges are ASCII, and code points only differ from code units at a surrogate pair (a value of 0x10000 or more instead of 0xD800 to 0xDBFF) and past the end of the text (undefined instead of NaN), which neither range accepts either way.
…fter a sub-screen (sirmalloc#780) * fix(tui): keep Merge highlighted after cancelling the shell-command confirmation When an import adds a Custom Command, choosing Replace All or Merge first asks "Apply this import? It adds a shell command...". Cancel says "Go back to the preview without importing", but coming back from Merge put the highlight on Replace All and switched the preview to the Replace diff. The confirmation doesn't name the mode, so pressing Enter again and confirming applied Replace All, which resets every setting the file leaves out to its default. The confirmation replaces the preview's List, and the List mounted again at its first row, then reported that row as the new selection. Mount it on the mode the preview was showing instead. * fix(tui): let Escape leave Import Preview and its shell-command confirmation Escape did nothing on Import Preview, on both the diff and the "Apply this import? It adds a shell command..." confirmation. The only way out was to arrow down to Cancel and press Enter. The Import Config path dialog one step earlier, and the other menus, go back on Escape, and docs/USAGE.md already says Escape returns from the confirmation to the preview. The dialog had no input handler of its own, and its List only handles the arrows and Enter. Escape now steps back one screen: from the confirmation to the preview, where the mode stays highlighted, and from the preview out of the import, as Cancel does. * fix(tui): keep Color Level highlighted after the custom-colors warning In Terminal Options you press Enter on Color Level to cycle through the levels. With an ansi256 or hex widget color, leaving 256 Color or Truecolor first warns "Custom colors detected!". After Yes, No or Escape the highlight was back on Terminal Width, so the next Enter opened the Terminal Width screen instead of cycling on. The warning replaces the List, and the List mounted again at its first row. Remember the highlighted row, as Powerline Setup does around its confirmations, and mount the List on it. * fix(tui): keep the cancelled setting highlighted in Configure Status Line Pressing Escape on a Refresh Interval or cache TTL prompt brought the list back with the highlight on the first row, Refresh Interval (or Git Cache TTL when Refresh Interval needs a newer Claude Code). Pressing Enter again opened a different setting from the one just left. Saving returns to the Main Menu, so only cancelling showed it. Each prompt replaces the List, and the List mounted again at its first row. Remember the highlighted row and mount the List on it. * fix(tui): keep the chosen update style highlighted when going back in Install In Install to Claude Code, going back from the package manager step (Escape or "← Back") highlighted Pinned global install again, with its description, even after choosing Auto-update. Pressing Enter then led into the pinned global install commands instead of the npx/bunx ones. The style List mounts again on the way back, and it always started on its first row. Start it on the style still held from the first pick. * test(import-preview): mark the command import with colorLevel instead of flexMode flexMode is going away with the Terminal Width options; any non-default key the import carries serves this fixture. * test(terminal-options): start the warning tests on Color Level, now the first row With sirmalloc#765 Terminal Options lists only Color Level, so the two tests start there instead of stepping down from Terminal Width. * fix(tui): drop the Terminal Options row change, which sirmalloc#765 made moot With sirmalloc#765, Color Level is Terminal Options' only setting and the custom-colors warning opens only from it, so the menu comes back on that row without help.
…ttings as v1 (sirmalloc#779) * fix(config): don't migrate a version-less settings.json with later settings as v1 A settings.json, or an Import Config file, with no "version" key was always read as a v1 config, since v1 predates the field. loadSettings validated it with the v1 schema, which ignores keys it doesn't know, and ran the v1->v2 migration, which rebuilds the config from `lines` and the nine v1 fields only. Every later setting (powerline, defaultPaddingSide, minimalistMode, gitCacheTtlSeconds, ...) went back to its default, the result was written over the file with no copy kept, and the v2->v3 step added a "ccstatusline updated to v2.0.2" message that then showed for 12 renders. Import ran the same migration and took its merge keys from the migrated result, so Merge applied nothing from such a file and Replace applied defaults, while the TUI reported a successful import. needsMigration now reads a version-less config as v1 only when it holds none of the settings added after v1 (the keys SettingsSchema has beyond SettingsSchema_v1). One that does is validated as the current version: if it is valid it loads as written, and the file isn't rewritten just to add a version; if it is invalid it takes the existing invalid-file path (defaults in memory, the warning badge and TUI banner, file untouched). Genuine v1 files hold only v1 fields, so they still migrate. Before a migration is written back, the original is now copied beside the settings file as <file>.v<N>.bak, N being the version it was migrated from, with the original's permissions. If that copy can't be written, the migration isn't persisted: the file stays as it was and the load reports the error, like any other file it can't use. Import validation shares the check and takes its merge keys from the file's own keys rather than the migrated result's, so Merge applies every setting the file holds. * fix(config): keep current settings a v1 import's migration drops A merge import applies only the keys the file holds. For a version-less v1 file, those keys were taken from the raw file, but the v1 migration keeps only fields of the right type and drops a lines value that isn't a list. The schema then filled the dropped keys with defaults, and the merge wrote those defaults over the current values: a v1 file with "flexMode": null reset Flex Mode to full, and one with a non-list lines replaced the current lines with the default ones. The merge now takes the raw keys that are still in the migrated result, so a dropped value leaves the current setting alone. * fix(config): back up settings.json byte for byte before a migration The .v<N>.bak copy was written from the text decoded as UTF-8. Bytes that aren't UTF-8, such as a Latin-1 é an editor saved in a custom text, decode to U+FFFD and were written back as EF BF BD, so the backup was not the original file. It is now written from the bytes read. * fix(config): use a migration in memory when its backup can't be written A migration is written back only after the original is copied to settings.json.v<N>.bak. When that copy failed, for example because the config folder is read-only, the load fell back to the built-in defaults and reported the file as invalid: the status line rendered the defaults behind the invalid-config badge, and the TUI showed the defaults and offered to overwrite the file with them, although the file was valid and only needed upgrading. Now the migrated settings are used for that run without being written, and every load tries the backup again, so the file is upgraded as soon as the copy can be made. The status line renders the user's lines, with no badge and nothing on stderr. The update message a migration adds is held back until then, since counting it down would rewrite the file. The TUI shows a notice instead of the invalid-config warning. A save from it writes the backup first; if that still fails, the save fails with the existing "Could not save configuration" message and the file is left as it was. Recording installation metadata skips its write in that case, as it does for an unreadable file. * fix(config): don't replace a newer backup when saving over a held migration When a load can't back up settings.json before migrating it, the migrated settings are used from memory and the next save writes the backup first. That save backed up the bytes the load had read, which in the TUI can be minutes old. If the file was edited in the meantime, and a status line render then backed up the edited file and migrated it, the save deleted that backup, wrote the older bytes in its place and wrote the TUI's settings over the file, so the edit was left nowhere. The save now reads the file again before backing it up. If it still needs migrating, the bytes it holds now are backed up, under their own version. If it is already at the current version, another run has migrated it and kept its own backup, and that backup is left as it is. * test(config): mark kept settings with colorLevel instead of flexMode flexMode and compactThreshold are going away with the Terminal Width options, so these tests tell the user's settings from the defaults by a non-default colorLevel (and defaultPadding for the second invalid v1 field). * fix(config): preserve legacy hiding in versionless settings --------- Co-authored-by: Matthew Breedlove <sirmalloc@gmail.com>
…c#778) (a) in Edit Colors opens the whole 256-color palette as a grid (the 16 basic colors, the 6x6x6 cube and the 24 grays) instead of asking for a number. The arrow keys move the cursor and the preview follows it, typing a number jumps to that color, Enter keeps it and ESC restores the previous one. Picks are still saved as ansi256:N, and (a) is now offered at truecolor too.
…irmalloc#791) With a tag named like the current branch, `git symbolic-ref --short HEAD` prints "heads/<branch>". The refresh child keys the PR cache by the full ref with "refs/heads/" stripped since sirmalloc#774, but the render's lookup through the cached runGit (sirmalloc#639) still used --short. The two then hash to different cache files: the child writes the PR to one, Git PR and Git CI Status read the other, and the widgets show "(no PR)" on every render while a refresh runs again each time its lock goes stale. The child also never releases the lock it was handed, since that lock belongs to the other cache file. The render's lookup now reads `symbolic-ref HEAD` and strips the prefix the same way, which is also the command Git Branch already runs, so the cached runGit answers both. Co-authored-by: effectustasi <216187407+effectustasi@users.noreply.github.com>
…sirmalloc#793) Enabling Powerline replaced a theme of 'custom' with the default theme, the same as a first enable with no theme set. 'custom' can only be set from the Themes menu (picking Custom, or customizing a built-in theme into widget colors), which is disabled while Powerline is off. So turning Powerline off and on again switched a customized status line to nord-aurora, and the widget colors stopped showing until Custom was picked again. Only a missing theme now falls back to the default. Co-authored-by: effectustasi <216187407+effectustasi@users.noreply.github.com>
…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.
…ode (sirmalloc#810) - Shared bar rendering: Block Timer, Block Reset Timer, Weekly Reset Timer, Extra Usage Utilization and the usage-percent widgets each built their bars with the same blocks. formatUsageBar in usage-display.ts now builds every bar mode (block, line and slider, with or without the percentage) in one place and returns null outside them, so each widget only adds its label. The time cursor is still resolved only in bar modes. - One class for the usage-percent widgets: Block, Weekly, Weekly Sonnet, Weekly Opus and Fable Weekly Usage were identical apart from their kind. UsagePercentWidget holds the class once and each widget names its kind. Spend Limit Usage extends it too and keeps only its color; the class takes the time cursor and the API-error state from the kind. - A shared base for the Context % widgets: Context % and Context % (usable) differed only in name, color, description, label prefix, preview sample and how they measure the used share. ContextPercentageWidgetBase holds the rest. No change in behavior.
…nd root dir widgets (sirmalloc#809) * refactor(powerline): drop the font install's unreachable fallback return After the clone, installPowerlineFonts either runs install.sh (macOS and Linux) or copies the font files (Windows), and each branch returns its result or throws. The "Platform-specific installation not implemented" result after them could never be returned, and an unsupported platform already returns its own message before the clone. * refactor(renderer): step through Powerline auto-align padding with a while loop The padding pass jumped its for-loop counter past each merge group from inside the body, so the loop header no longer said how it stepped. A while loop now sets the next widget explicitly: the following one, or the one after a merge group once the group is padded. The output is unchanged. Two new tests pin the cases that depend on the stepping and had no test: an auto-align exclusion on a widget merged into the previous one is ignored and the columns after the group are still padded, and a line rendered without column widths keeps its natural widths. * refactor(guid): truncate the random hex digit with Math.trunc generateGuid dropped the fraction of Math.random() * 16 with a bitwise "| 0". Math.trunc says that directly. For the values this sees, [0, 16), both give the same digit: they differ only past 2^31, for NaN and for Infinity, none of which Math.random() * 16 can produce. New tests pin the UUID v4 shape and the digits Math.random() at 0, 1/16, 1/2 and its largest value turn into, including the variant digit's 8 to b range. * refactor(widgets): drop the root dir widgets' redundant separator trim Git Root Dir and JJ Root Dir stripped trailing separators from the root path, then split it on separators and dropped the empty parts. The split already drops the empty parts trailing separators leave, so the strip changed nothing: - With a name in the path, both give the same last part. - With no name, as for "/", the strip left an empty string and the code fell back to the original path, which is what the fallback now uses directly. The strip's pattern also rescanned a long run of separators from every position in it: 50,000 slashes before a name took 1.6s under Bun and 4.0s under Node. git and jj never print such a path, but the split alone does it in about a millisecond. An exhaustive check over every string of up to 8 characters drawn from "/", "\", "a", ":", " " and a newline gives the same name both ways. New tests cover trailing Windows separators in both widgets, "/" for JJ Root Dir and a path of separators alone for Git Root Dir.
…wide padding (sirmalloc#808) * fix(widgets): edit Link and Custom Command text by whole characters The Link text and URL editors and the Custom Command editor kept their cursor as a UTF-16 index and moved or deleted one code unit at a time. An emoji outside the Basic Multilingual Plane is two code units, so Backspace after it, Delete before it, or an arrow key over it split the pair: - Backspace on "Docs 📘" saved "Docs \ud83d", which the status line draws as "🔗 Docs �". - In the command "echo 🚀", Left then "x" saved "echo \ud83dx\ude80", so the shell received U+FFFD x U+FFFD instead of the rocket. The cursor cell also drew value[cursor], a single code unit, so with the cursor on an emoji a real terminal showed two replacement characters. The Custom Text and label editors already work by grapheme through text-cursor.ts. Its boundary lookup is now exported as getAdjacentBoundaries, and both editors use it for Left, Right, Backspace and Delete and to draw the whole grapheme under the cursor. Joined, skin-toned and flag emoji now move and delete as one character, as they do in Custom Text. Typing and pasting are unchanged. * fix(tui): keep joined emoji whole in Edit Lines and Global Overrides rows Each row in the line editor was a run of sibling Texts: the widget name and its text, then one for each tag such as "(merged→)", "(label: …)", the number style or "(no-align)". Ink lays a sibling out at the width string-width gives the text before it, which counts a joined, skin-toned or flag emoji (👩💻, 👍🏽, 🇺🇸) as two columns, but it writes every code point of that emoji into its own cells. The text ran past its box and the next tag overwrote the end. A Custom Text of 👩💻 merged into the next widget showed as "1. Custom Text (👩 (merged→)", a plain 👩 with no closing paren, and a 👍🏽 label lost its closing quote. Only the editor list was wrong; the saved config and the status line were fine. Global Overrides draws its Default Padding and Default Separator rows the same way: the quoted value, then a sibling " - Press (p) to edit" hint. A 👍🏽 padding showed as `Default Padding: "👍🏽 - Press (p) to edit`, without its closing quote, and a 👩💻 padding lost its 💻 as well. The row's name and tags are now nested Texts inside one Text, the way the label editor already draws its value, so they print as one string and nothing overwrites the emoji. The two Global Overrides rows nest their value and hint the same way. The styling of each part is unchanged. * fix(renderer): size auto-aligned columns by the padding's display width With Powerline Align Widgets on, the shared column widths added the default padding's string length to each widget's display width. The renderer then pads every cell by measuring its padded text in columns. The two only agree when every padding character is one UTF-16 unit and one column wide. With the ideographic space U+3000 as padding (what the space bar types under a full-width Japanese or Chinese IME), the columns came out 2 narrower than the padded cells. On lines [A, B] and [CCCCC, D] the first separator landed at column 7 on one line and 9 on the other. A padding glyph from outside the Basic Multilingual Plane went the other way and added spaces to every column. The padding is now measured with getVisibleWidth, the same measure used for the cells.
…y from the config the status line loads (sirmalloc#807) * fix(tui): open Configure Status Line before ccstatusline is installed Configure Status Line was disabled with "(install first)" unless Claude Code's statusLine command was one of the exact commands the installer writes, with padding 0. A wrapper script, `bunx ccstatusline`, `npx ccstatusline@latest` without -y, or any other padding all counted as not installed. That menu is the only place in the TUI to edit the Git, Custom Command and Terminal Width cache TTLs. They are ccstatusline's own settings, saved to its settings.json and read on every render however Claude Code runs it. With such a status line they couldn't be changed, for example to turn on custom command caching, which is off by default. The menu now always opens. Only its Refresh Interval row needs the install: Claude Code keeps that value in its statusLine setting, which ccstatusline edits only for a status line it recognizes as its own. Until then the row is disabled with "(install first)"; an older Claude Code still shows its version requirement instead. The main menu's description of the item says which part needs the install. * fix(hooks): sync widget hooks only from the config the status line loads Saving a config rewrote Claude Code's ccstatusline-managed hooks from that config's widgets, whichever config it was. The installed status line command loads one config: the path after its --config, or the default config without one. Saving any other config, such as one opened with `ccstatusline --config <file>` to try something out, still rewrote the hooks to match it: - If the status line shows Skills and the saved config doesn't, the Skills hooks were removed and the status line's Skills widget stopped updating. - In the other direction, hooks were added that make Claude Code run `<command> --hook` on every prompt and Skill call, for a status line that doesn't need them. Either way the TUI only said "Configuration saved". syncWidgetHooks now works out which config the status line command loads and leaves the hooks as they are when that isn't the config being saved. getStatusLineConfigPath splits the command into words the way a POSIX shell passes them on (quotes and backslash escapes; on Windows only double quotes group), expands a leading ~ and $HOME, and resolves the path as the --config argument is resolved at startup, through resolveConfigPath, which initConfigPath now uses too. A command without --config, a wrapper script included, is taken to load the default config. Installing still syncs the hooks, since the command it writes names the config the TUI has open. * fix(claude-settings): start a quoted word without ??= Node 14, the build's target, has no logical assignment operators, and the build passes them through unchanged. * fix: preserve config identity when syncing widget hooks --------- Co-authored-by: Matthew Breedlove <sirmalloc@gmail.com>
…and re-check (sirmalloc#806) * fix(update): bound the registry check with an overall deadline Check for Updates is meant to give up on the npm registry after five seconds, but its only timer was the request's socket timeout. That timer starts once the socket has connected, and Bun's doesn't fire while it connects at all. On a network that silently drops outbound HTTPS (a firewall that expects a proxy, a captive portal), the Updates screen sat on "Checking npm registry..." until the OS gave up on the connection: about 75 seconds on macOS under Bun, and the same on Node 18 and older, whose global agent has no default timeout. Node 19+ only stopped at five seconds because its global agent's own socket timeout happens to match. The check now arms one timer for the whole request, as the usage and status-page requests already do. When it fires, it destroys the request and fails the check with "npm registry request timed out after 5000ms". The socket timeout is gone, since the deadline always fires first. The request function can be passed in, so tests can stand in for the network. * fix(update): send the registry check through HTTPS_PROXY The usage and Claude Status requests go through the proxy named by HTTPS_PROXY unless NO_PROXY excludes the host, but Check for Updates called https.request with no agent, and neither Node nor Bun reads the proxy variables on its own. On a network where only the proxy gets out, every other network widget worked while the Updates screen failed with "npm registry request timed out after 5000ms" (and under Bun waited about 75 seconds for the OS to give up first). The registry request now uses the same helpers: createProxyAgent for HTTPS_PROXY, skipped when isExcludedFromProxy matches registry.npmjs.org. At the deadline it also closes the agent's connection to a proxy that never answers CONNECT, which would otherwise keep the process alive. A HTTPS_PROXY that isn't a URL fails the check with a message that says so. The proxy docs now list the update check, and the test helper that clears the proxy variables is shared by both suites that need it. * fix(update): compare a self-managed global install's own version With Claude Code's status line set to the global `ccstatusline` command and no pinned metadata, Check for Updates compared the latest release with the version of the TUI that was running. The README starts the TUI with npx or bunx, so that is often a different copy from the global package Claude Code runs. Manage Installation showed "Active PATH match: npm global 2.2.20", yet Check for Updates said "Current: 2.2.32 ... ccstatusline is up to date" and offered nothing, and a global already at the latest release got an offer to reinstall it whenever the TUI was older. Pinned installs already use the version found on PATH. Self-managed installs now do too when that version is known, and fall back to the running TUI's version otherwise. The offered command already targeted that global package's manager, so the version shown now matches what it would update. * fix(update): check again after a global update from the Updates screen After "Run npm install -g ccstatusline@X" succeeded, the TUI flashed "Global package updated" (or showed the Update Complete notice) and went back to the Updates screen, which still held the result from before the update: the old Current version, "An update is available." and the same install command, which reinstalled X if picked again. Only Check again showed that the install was up to date. A successful update now runs the check again. It runs from an effect once the new installation metadata has reached `settings`: calling the check from the update's own callback would read the settings from before the update, so a self-managed install would still show as one, and a pinned install whose PATH version can't be read would compare the old version. Both the flash path and the PATH-warning notice path land on the fresh result. * fix(update): compare a checkout status line with its own version, not PATH's A status line that runs a local checkout (any command running ccstatusline.ts) is classified as self-managed, the same as the bare global `ccstatusline` command. Check for Updates then compared the latest release with the version of whatever global `ccstatusline` sits first on PATH, a copy Claude Code never runs for that status line. A checkout at the latest release with an old global on PATH was told an update is available and offered `npm install -g`; a checkout behind the latest release read as up to date when the global was current. The PATH version now applies only when the status line command is the global `ccstatusline` (with or without --config). Every other self-managed command compares this TUI's own version again, as before the self-managed change. * fix(proxy): read an HTTPS_PROXY with no scheme as an HTTP proxy A proxy given as host:port, such as `proxy.corp:3128` (a form curl accepts as http://), went to HttpsProxyAgent as it was. `new URL()` parses it without complaint but takes `proxy.corp:` as the scheme and leaves the host empty, so the agent connected to localhost:80. Check for Updates, which now goes through HTTPS_PROXY, then failed with only "Unable to query npm registry", where it used to connect directly and work wherever direct connections were allowed. The invalid-URL check missed this form, since nothing threw. createProxyAgent now adds `http://` when the value has no `scheme://`, as curl does, so the request goes through the named proxy. Values that still aren't URLs, like one with spaces, fail as before. The usage and Claude Status requests build their agents with the same helper, so they read the variable the same way. * fix: close failed registry requests before clearing deadline --------- Co-authored-by: Matthew Breedlove <sirmalloc@gmail.com>
The "link to repo" option on Git Branch and the Git Origin/Upstream widgets builds its link with buildRepoWebUrl, which always wrote https://. For http and https remotes parseRemoteUrl keeps the port, as the forge's web port, so an origin of http://git.example.lan:3000/team/app.git (a Gitea or GitLab served over plain HTTP on a LAN) linked to https://git.example.lan:3000/team/app and .../tree/<branch>. That port speaks no TLS, so clicking the link failed. Take the scheme from the remote: an http:// remote links over http, and https, ssh, git and scp-style remotes still link over https. An http://github.com remote now links to http://github.com/..., which GitHub redirects to https.
…s in fish mode (sirmalloc#803) * fix(cwd): keep whole characters in fish-style segments Fish style shortens each middle directory to its first character, but it took that character with part[0] (and part[1] after a leading dot), which index UTF-16 code units. A folder whose name starts with an emoji or other character outside the Basic Multilingual Plane was cut in half, leaving a lone surrogate that the terminal prints as U+FFFD: "~/🚀 rockets/sub/last" showed as "~/�/s/last". A decomposed accented name such as "Über" lost its combining mark, and a joined emoji such as "👨👩👧" printed as U+FFFD too. Take the first grapheme instead, using the getGraphemes helper the symbol editors already use, so the abbreviation keeps one whole user-visible character, including after the dot of a hidden directory. * fix(cwd): keep a UNC path's root in fish style Fish style splits the path on separators, drops the empty pieces and then rebuilds it, putting a single separator back only when the path started with '/'. A Windows UNC path lost its leading '\\' entirely, so "\\server\share\team\repo" showed as the relative-looking "server\s\t\repo", and "//server/share/team/repo" kept only one of its two slashes. Keep the path's leading separators as they were and join the shortened parts after them. POSIX paths keep their '/', home and drive-letter paths have no leading separators and come out as before. * fix(cwd): turn fish style off when a segment count is saved Fish style and the segment count are mutually exclusive: turning fish style on clears the segment count, and turning on the home ~ option turns fish style off. The (s)egments editor broke that rule. It is offered while fish style is on, but on Enter it kept fish style and stored the count next to it. Fish style wins when both are set, so the item still read "(fish-style)" and the preview and status line didn't change, as if the edit had been dropped. The hidden count then cut the path the moment fish style was turned off. Saving a segment count now turns fish style off, the same way the home ~ option does, so the count takes effect as soon as it is entered and the item shows it. A blank entry still only clears the count. Settings saved before this fix, or edited by hand, can still hold both. Turning fish style off now drops the segment count as well, so the full path comes back instead of a count that was never shown. Since turning fish style on already clears the count, it can only sit next to fish style through the old editor or a hand edit.
…ked PATH dir once (sirmalloc#804) * fix(install): find package managers and ccstatusline on PATH without which The TUI asked `which` whether npm, npx, bun and bunx are installed and where ccstatusline resolves. `which` is a separate package that minimal Linux images (Fedora, RHEL/UBI) and a base Arch install leave out. Without it every lookup failed the way a missing tool does: the Install screen marked all four package managers "not installed" and disabled every option, update actions were disabled too, and Manage Installation said ccstatusline is not resolvable on PATH. When `which` can't be started, the lookup now searches PATH itself and lists what `which -a` would: each file the user can run, in PATH order. `command -v` could answer "is npm installed" but can't list every match, which the multiple-binaries warning needs, so both checks share this one search. The availability check now goes through the same lookup as the ccstatusline resolution, so the two can't disagree. Where `which` exists nothing changes, and Windows still uses `where`. * fix(install): count a PATH directory reached through a symlink once The "Multiple ccstatusline binaries are on PATH" warning counts the directories `which -a` lists ccstatusline in, comparing them as text. On merged-/usr Linux (Ubuntu 22.04+, Debian 12) /bin is a symlink to usr/bin and the default PATH lists both, so with npm's global prefix at /usr one installed binary shows up as /usr/bin/ccstatusline and /bin/ccstatusline. Manage Installation and the install and update notices then warned about a second install that doesn't exist. Both duplicate checks now compare each directory with its symlinks resolved, and fall back to the path as listed when it can't be resolved. The warning still shows the paths as PATH spells them. * fix(install): read PATH from process.env when the PATH search runs The PATH search used when there is no `which` kept the process.env object that existed when its module loaded. Code that replaces process.env with a new object afterwards (a test restoring a saved environment does) left the search reading the old object, so a PATH set on the new one was never seen. The default search now reads process.env each time it runs. * fix(install): list each other install once in the multiple-binaries warning The warning counts installs by directory, with symlinks resolved, but built its "Other matches" list from every path `which -a` printed after the first. With a real second install on a merged-/usr system, where /bin links to usr/bin, PATH order gives /usr/bin/ccstatusline, /bin/ccstatusline and then the other one, so the list named /bin/ccstatusline as another binary although it is the first match reached a second way. The list now takes the first path listed in each directory and leaves out the first match's directory, so each other install appears once, spelled as PATH lists it. * fix(install): resolve PATH directories' letter case the same under Node and Bun The duplicate-binary checks resolve each PATH directory with fs.realpathSync before comparing. Where the file system ignores letter case (macOS by default), Bun's realpathSync returns the case stored on disk but Node's returns the case it was given. A PATH that spells one directory two ways, such as .../bin and .../Bin, therefore showed "Multiple ccstatusline binaries are on PATH" when the TUI ran under Node and no warning under Bun. The lookup now uses fs.realpathSync.native, which asks the operating system and returns the on-disk case under both runtimes. A directory that can't be resolved still falls back to the path as listed. * test(install): keep the PATH search for when which is missing, not failing The lookup searches PATH itself only when `which` can't be started (ENOENT). When `which` runs and exits non-zero, it found nothing, and that answer stands. No test covered this: with the ENOENT check removed, every failed `which -a ccstatusline` would fall through to the PATH search, and the tests still passed. The new case has `which -a` exit with status 1 while PATH holds an executable ccstatusline, and expects no matches. * test(install): check that PATH directories resolve through the native realpath The letter-case test passes under Bun with or without the native call, because Bun's plain realpathSync already reports the on-disk case, and it is skipped where the file system is case-sensitive. A second test checks the call itself, so a revert fails under bun test on any system. * refactor(install): build the default PATH search in a named helper findAllOnPosixPath spelled its default search as an object literal inside the parameter list, which made the signature hard to read at a glance. The default now comes from defaultPosixPathSearch(), next to the isExecutableFile check it uses. A default parameter is evaluated on every call that leaves it out, so the helper still builds a fresh search from process.env as it is when the search runs: an env object swapped in after the module loaded is still seen.
…tings.json can't be changed (sirmalloc#805) * fix(install): stop Uninstall when Claude's settings.json can't be read uninstallStatusLine caught a load failure (invalid JSON such as a trailing comma, or a permission error), printed a warning and returned normally. The TUI's uninstall action treats a normal return as "Claude settings removed", so it went on to run `npm uninstall -g` or `bun remove -g`, switched the menu to not installed and flashed "✓ Uninstalled from Claude Code and removed global package". Nothing had been removed from settings.json: once the file was fixed, statusLine still ran the global binary that had just been uninstalled, which leaves a blank status line, and the managed --hook hooks and the installation metadata were still there. The settings-only options reported "✓ Uninstalled from Claude Code" the same way. The TUI only offers Uninstall when settings.json was readable at startup, so this takes the file breaking while the TUI is open, for example a hand edit saved with a syntax error in another window. uninstallStatusLine now throws on that failure, as installStatusLine already does, with the same message naming the file and the reason from a loader the two share. The TUI's existing failure branch then runs: it shows "✗ Uninstall failed", keeps the installed state and skips the global package removal. settings.json, the metadata and the hooks are left as they were. * fix(tui): report a refresh interval that couldn't be saved setRefreshInterval returned normally when Claude's settings.json could not be read or parsed, and when it had no statusLine, without writing anything. Configure Status Line sets the new value before the save and only puts the old one back if the save rejects, so in both cases it flashed "✓ Refresh interval updated" and kept showing the new value, while Claude Code went on using the old one. As with Uninstall, the menu is only enabled when settings.json was readable and had our statusLine at startup, so this takes the file changing while the TUI is open: a hand edit that leaves invalid JSON, or another tool replacing the file. setRefreshInterval now throws in both cases, the read failure with the message install and uninstall use. The TUI's existing failure branch then shows "✗ Failed to save refresh interval" and keeps the value that is still in effect. The file is left unchanged. * fix(install): stop Uninstall when the managed hooks can't be removed uninstallStatusLine ignored any failure to remove the managed --hook hooks. When statusLine was already gone from Claude's settings.json, so nothing was written before that step, and the file couldn't be written (read-only, for example), the hooks stayed in place and the uninstall returned normally. The TUI then ran `npm uninstall -g` or `bun remove -g` and flashed success, leaving hooks that run the binary it had just removed. The installation metadata was cleared before the hooks were tried, so it was gone as well. The hook cleanup failure now rejects the uninstall, and the hooks are removed before the metadata is cleared, so the TUI's existing failure branch shows "✗ Uninstall failed", skips the global package removal and leaves settings.json and the metadata as they were. removeManagedHooks no longer rewrites settings.json when it holds none of our hooks. An uninstall with neither statusLine nor managed hooks in the file still goes ahead even when the file can't be written, since nothing in it would be left pointing at the binary. It also stops reformatting the file and refreshing its .bak copy for no change. * fix(install): keep Uninstall working with a hand-edited hook it can't read Removing the managed hooks assumed every hook event held a list of objects, each with a list of hooks. A hand-edited settings.json can break that, for example a Stop hook written as an object, a null entry, or "hooks" set to a string. The cleanup then threw a TypeError, even when none of the hooks were ccstatusline's, and since the previous change that error rejects the uninstall. statusLine had already been removed in an earlier write, so the TUI showed "Uninstall failed" with statusLine gone, and every retry failed the same way. Entries without the expected shape are now left as they are, since they can't be ours. Uninstall also removes statusLine and the managed hooks in one write, so a failure to save leaves both in place, and the .bak copy holds the file as it was before the uninstall rather than the halfway state between the two writes. --------- Co-authored-by: Matthew Breedlove <sirmalloc@gmail.com>
* feat: label Extra Usage as spend on accounts without plan limits
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.
* refactor: share the cache file lock
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.
* feat: add a daily state file for per-day usage tracking
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.
* feat: track each day's starting extra usage spend
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.
* feat: work out today's extra usage spend during the usage prefetch
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.
* feat: add an Extra Usage Today widget
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.
* fix: count a cached extra usage total for the day it was fetched
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.
* test: check fetchUsageData reports the login and fetch time
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.
* test: cover the Spend label with an edited label
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.
* refactor: keep the Enterprise wording, drop the Spend label detection
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.
* test: check the picker lists the Extra Usage widgets first, however many there are
* test: look for the Extra Usage widgets among the widgets that mention the word
* refactor(widgets): share Extra Usage Used and Remaining's code
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.
* fix: drop extra usage times stamped while the clock ran ahead
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.
* fix(usage): remove daily.json's temp files when a write fails
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.
* fix(usage): keep today's extra usage spend across a token refresh
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.
* refactor(usage): tidy the account lookup and the record merge
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.
* refactor(usage): ask the profile endpoint once for the account email 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.
* docs(development): the account email and Extra Usage Today share one profile lookup
* refactor(usage): name the account id before fingerprinting it
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.
* fix: enable label editing for Extra Usage Today
---------
Co-authored-by: Matthew Breedlove <sirmalloc@gmail.com>
…loc#777) * feat(thinking-effort): optional brackets and per-level colors Thinking Effort gains two options, both off by default. (b)rackets wraps the rendered value in (), [], {} or <>. (l)evel colors opens an editor that colors the value by effort level, with the brackets either matching the level or keeping the widget color. With level colors on, the widget paints only the level, and the renderer colors the rest as it colors any widget, through a new optional Widget.colorsOnlyItsRuns(). At the 256 Color level, hex colors now render as the nearest 256-palette color instead of a 24-bit code those terminals can't draw. * test(tui): wait for the Thinking Effort row in the color menu's own-colors test The line and color editor tests no longer sleep a fixed 25ms after each render and key. They wait for the key's visible effect, and the sleep helper flushInk is gone. The color menu test that checks the note for a widget that sets some of its own colors still called flushInk after the first render, so it no longer compiled. It now waits until the frame shows the Thinking Effort row, then reads that frame as before.
…rmalloc#767) * fix(usage): show a newer usage API percent in a session left idle Claude Code sends the 5-hour and weekly percents with each of a session's API responses, and the usage widgets show those over the usage API's. A session left idle keeps the percents from its last response, so with `refreshInterval` its line redraws with the same numbers while other sessions or devices use up the limits. Once the transcript's last response is more than three minutes old (the usage cache's lifetime), the prefetch also asks the usage API for the windows the line shows, through the shared cache and without surfacing errors. Its percent wins when the API sent it after that response, for the same window and no lower, or for the next window once the payload's has reset. The forecast history dates the 5-hour percent by its source. * fix: retain accepted usage observation timestamps --------- Co-authored-by: Matthew Breedlove <sirmalloc@gmail.com>
It names its label like the other labeled widgets, so the label editor offers it.
|
eric-engberg
marked this pull request as ready for review
November 6, 2026 19:47
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.



Builds on #36 (which builds on #32): review the last three commits. Goes upstream after #36 does.
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
~/.cache/ccstatusline/daily.json), per Claude Code profile (CLAUDE_CONFIG_DIR, ordefault), 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.dailyCostin the render context.tswitches from active time to clock time.bswitches from Claude Code's own session costs to today's billed spend, the value feat: add an Extra Usage Today widget #36's 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).$6.20/hr.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
claude --resume,--continue,/resumeand--fork-sessionrestore 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 minustotal_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 newfirstSeenAtfield, 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./loginin a running session./loginsets 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.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 anddayFirstSeenAthas already passed, it stays, marked as last seen now. Otherwise it's dropped. Settling a record forces a write.€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
Plain
Switching
tandbin the line editor:Powerline
Plain
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:
Plain, before and after:
Daily Cost Rate (active time | clock time) through the real pipeline at set clock times, with made-up amounts: a session runs
/loginat 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/hrand then reads$15.43/hr | $3.86/hrfor the whole day.Powerline, before and after:
Plain, before and after:
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:
Plain, before and after:
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/hrand$1234.50/hr. After, it reads€23.45/hrand$1,234.50/hr, matching Extra Usage Today.Powerline, before and after:
Plain, before and after:
Testing
prefetchDailyCostIfNeeded: nothing recorded without the widget or without a session id, cost and both durations; recorded underCLAUDE_CONFIG_DIRordefault.extraUsageEnabled/extraUsageUsedplus today's spend with it.bun test: 2433 pass, 0 fail.bun run lintpasses.HOMEpointed 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.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.Update:
bun test: 3245 pass, 0 fail across 183 files (9279expect()calls).bun run lintpasses (tsc and ESLint, no warnings)./loginkeeps 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).Rate Today: €50.00/hr(was$50.00/hr).$12.00/hr | $4.00/hr→ nothing, then$11.40/hr | $3.80/hr→$9.00/hr | $3.00/hr;/loginnothing →$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/hrand$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.