Skip to content

fix(usage): show a newer usage API percent in a session left idle - #147

Closed
eric-engberg wants to merge 50 commits into
developfrom
fix/idle-session-usage
Closed

eric-engberg wants to merge 50 commits into
developfrom
fix/idle-session-usage

Conversation

@eric-engberg

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

Copy link
Copy Markdown
Owner

Standalone, cut from main (upstream-ready; #72 and #89 are upstream as sirmalloc#699 and sirmalloc#747).

What

In a Claude Code session left idle, Block Usage, Weekly Usage and the per-model weekly widgets now catch up with usage from other sessions or devices. Once the session's last response is more than three minutes old, they show the usage API's percent when it's newer than the one Claude Code sent with that response.

Why

Claude Code sends the 5-hour and weekly percents with each of a session's API responses, and ccstatusline shows those over the usage API's. A session left idle keeps the percents from its last response. With refreshInterval set, its line redraws on that interval, but with the same numbers: while another session took the 5-hour block from 20% to 60%, an idle one still said 20% until its next prompt. On this machine, with refreshInterval: 30, idle sessions' lines looked frozen although Claude Code was rerunning the command every 30 seconds.

How

  • When it asks: for each 5-hour, weekly or per-model window that a widget on the line reads and the payload supplies, once the session's last response is older than the usage API cache's lifetime (three minutes). The time comes from the transcript's last assistant entry, the same one Block Forecast's history uses. A session with a recent response makes no request, and neither does a transcript with no response to date the percents by (a new one after /clear): the payload's percents stand.
  • Which percent wins: the usage API's, when the API sent it after that response (getUsageFetchedAtMs), for the same window (resets within a minute of each other), and no lower: usage never falls within a window, so a lower percent is another login's, after the credentials changed since the session's last response. Once the payload's window has reset, the API's current window wins.
  • Failures: the request is made like the other widgets' optional fetches: a failed or rate-limited fetch isn't an error on the line, and the payload's percents stay.
  • Cost: idle sessions read the usage API through its shared cache, so at most one request every three minutes across all sessions, as for the usage widgets that always fetch.
  • Forecast history: the 5-hour percent is dated by its source: the transcript's last response for the payload's, the API's fetch time once the API's replaced it.

Demo

Piped with fake data in a scratch HOME: an idle session whose last response, 20 minutes ago, came with 5h 20% and weekly 50%, while the usage API's cache, written just now, says 60% and 55%. Before, the line keeps the payload's 20% and 50%. After, it shows the API's 60% and 55%.

Powerline, before and after:

Before, Powerline

After, Powerline

Plain, before and after:

Before, Plain

After, Plain

Testing

  • New tests in usage-prefetch.test.ts (a scratch transcript dates the payload, a fake clock fixes now):
    • takes the API's newer percents once the last response is over three minutes old, asking only for the windows the line shows
    • keeps the payload's, without a request, while the last response is recent, and when the transcript has no response
    • keeps the payload's when the API's answer is older than the last response, when the API's percent is lower, and when the API answers another window the payload's hasn't reached
    • takes the API's new window once the payload's has reset
    • keeps the payload's percents, with no error, when the API can't answer
  • New test in session-usage-history.test.ts: the 5-hour percent is dated by the API's fetch time once it replaced the payload's.
  • Breaking each part of the rule on purpose (the time comparison, the same-window and no-lower checks, the reset case, the three-minute wait, asking only for shown windows, the suppressed error, the history's source) fails at least one test.
  • On current main: bun test 3700 pass, 0 fail (Bun 1.4.2). bun run lint: clean.
  • Built CLI under Bun 1.4.2 and Node 26.10.0, in a scratch HOME with fake credentials and a stub security: an idle session (last response 20 minutes ago) went from 5h: 20.0% Weekly: 50.0% to 5h: 60.0% Weekly: 55.0%; with a response a minute ago it kept 5h: 20.0% Weekly: 50.0%.

@eric-engberg
eric-engberg changed the base branch from feat/session-forecast to develop October 30, 2026 07:14
eric-engberg and others added 3 commits October 30, 2026 11:45
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.
…oc#639)

getCachedGitReviewData derived its cache key from `git symbolic-ref
--short HEAD` (and `rev-parse --short HEAD` when detached) with a bare
execFileSync, so every render spawned git once per git-pr / git-ci-status
widget even when the PR data itself was a cache hit. The widgets now pass
their render context and the ref lookup goes through git.ts's runGit, whose
persistent cache (invalidated by HEAD/index mtime) is already shared with
the git-branch and git-sha widgets. Without a context (the detached refresh
child, fetchGitReviewData) the lookup is unchanged.

Measured on a warm render with no refresh due (model, git-branch, git-pr,
git-ci-status): 2 git spawns -> 0. bench2 CPU median 1363 -> 1319 ms
(-3.3%, 40 passes) and 1443 -> 1375 ms (-4.7%, 30 passes), wall median
-12% / -4%, p90 overlapping on this heavily loaded host. stdout is
byte-identical.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
… in flight (sirmalloc#635)

* perf(claude-status): hold a lock while the status page fetch is in flight

The claude-status widget only wrote its lock after a failed fetch. When the
300 s cache expired, every render that started before the first fetch
finished (other sessions, or renders of the same session) sent its own
request(s) to status.claude.com and blocked on them.

Write the lock before the fetch, as usage-fetch.ts already does, so
concurrent renders serve the expired cache for that one fetch. The lock is
still judged by mtime, so an empty lock from an older version keeps
working. It now holds contents unique to the fetch, and the success path
removes it only while it is still this render's own lock: a concurrent
failure lock survives. The lock is removed after the fresh cache is
written, not before.

Measured with 6 concurrent renders of the built dist per cache expiry,
https.request faked with a fixed round trip:
- 2 s round trip, renders 200 ms apart: requests per expiry median 4
  (2-5) before, 1 after.
- 250 ms round trip, simultaneous: median 1 both, max 3 before, 1 after.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(claude-status): acquire fetch locks atomically

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Matthew Breedlove <sirmalloc@gmail.com>
@eric-engberg
eric-engberg force-pushed the fix/idle-session-usage branch from 8725ac2 to 7183a1b Compare October 30, 2026 21:11
@eric-engberg
eric-engberg marked this pull request as ready for review October 30, 2026 21:11
eric-engberg and others added 24 commits October 30, 2026 18:45
With ui.color = "always" in the user's jj config, jj colors its output
even when it writes to a pipe. The jj widgets ran jj without a color
option, so their text kept jj's escape codes: JJ Revision's change ID
came out bold magenta and ended in a full reset, JJ Bookmarks' names
magenta and JJ Workspace's name green. Those codes override the
widget's own color, and the reset also drops the widget's bold and
background for the rest of the segment, which leaves a gap in a
Powerline segment's background before its arrow.

runJjArgs now puts the global --color=never ahead of every jj command.
The option overrides ui.color, and jj has had it since 0.5.0, long
before the commands these widgets run. NO_COLOR is no alternative: jj
ignores it when ui.color is set explicitly.
…tput with no visible text, pipe the JSON as it arrived (sirmalloc#775)

* fix(custom-command): render nothing when preserved output has no visible text

A command with preserve colors on that colors a value which can be empty,
such as printf '\033[32m%s\033[0m' "$branch", prints only the color codes
when the value is empty. With preserve colors off those codes are stripped,
the output is empty and the widget drops out. With it on, the codes were
returned as the widget's text.

The renderer decides whether a widget is there by whether its text is
empty, not by its width, so the invisible widget kept its separators:
"A |  | B" in plain mode, and an empty segment with an arrow on each side
in Powerline mode.

Output with no visible text now renders the widget empty, whether or not
its colors are preserved.

* fix(custom-command): pipe Claude Code's JSON to the command as it arrived

The docs say a Custom Command receives the same JSON ccstatusline gets
from Claude Code, plus terminal_width, so another status line tool can be
chained in. The command got the schema-validated copy instead. Only the
top level of that schema keeps keys it doesn't list. Nested objects drop
them, so workspace.added_dirs, workspace.git_worktree and workspace.repo,
which Claude Code sends, never reached the command, and neither did any
new key under model, cost, context_window or rate_limits. Number strings
also arrived as numbers.

The entry point now keeps the parsed JSON next to the validated copy and
passes it in the render context. The widget pipes that, and the other
widgets keep reading the validated copy.

* fix(renderer): keep a preserve-colors widget's styling after the command's resets

A Custom Command with preserve colors keeps the command's own escape
codes, and the renderer wraps them in the widget's background, bold and
dim. A reset in the output (\e[0m, \e[22m or \e[49m) clears that styling
too. Powerline mode re-applied the segment background after each reset,
but not bold or dim. Plain mode re-applied nothing: with a widget
background or a global background override, the text after the
command's first reset sat on the terminal's default background, between
the widget's colored padding cells, and lost its bold.

Both modes now re-apply the widget's background, bold and dim after each
color sequence in the output that clears them. 0 or an empty parameter
clears all three, 49 the background, and 22 bold and dim. Each is
tracked on its own: when the same sequence sets one again (1 for bold,
2 for dim, or a background color), the command's setting stays and only
the others are re-applied. In plain mode the background is the global
override when one is set, as for the rest of the widget.
…irmalloc#774)

git's short ref names add a prefix when the short name is ambiguous.
With a tag named like the current branch, `git symbolic-ref --short
HEAD` prints "heads/<branch>". Git PR and Git CI Status pass that name
to the lookup pinned to origin (`gh pr view --repo <origin> -- <branch>`,
and the same for glab), which then asks for a PR on a branch called
"heads/<branch>" and finds none. In a fork, where gh's own resolution
picks the upstream repository, that pinned lookup is the one that finds
the PR, so the widgets showed "(no PR)" for a branch that has one.

The tracking-remote fallback of the Git Upstream widgets has the same
flaw: `git rev-parse --abbrev-ref --symbolic-full-name @{upstream}`
prints "remotes/origin/<branch>" when a local branch or tag is named
"origin/<branch>", which matches no remote, so the widgets showed
"no upstream".

Both now read the full ref and strip "refs/heads/" or "refs/remotes/",
as Git Branch already does for the branch name.
In plain mode, manual separators placed next to each other between two
visible widgets rendered as one: [A, ' ', ' ', B] printed "A B",
[A, '|', '|', B] printed "A | B" and [A, ' ', '•', ' ', B] printed
"A•B". The TUI preview showed the same, so there was no way to stack
separators for a wider gap or to pad a custom glyph with spaces.

The backward scan that decides whether a separator renders treated any
earlier separator as if a widget that rendered empty sat between the
two. A visible earlier separator kept the boundary, so the current one
was dropped; a spacing-only one was removed and replaced by the current
one. That rule is for separators on either side of an empty widget,
where one of them has to go, but the scan applied it whether or not a
widget lay between them.

Separators with no widget between them now form one run that renders
whole: the scan steps over the run's earlier separators to the content
before it. Across an empty widget the rule is unchanged, per run: a run
with a visible separator keeps the boundary, and a spacing-only run is
replaced by the run after the empty widget. Only that run's first
separator removes the spacing it replaces, so the rest of the run is
kept.
…lloc#772)

* fix(claude-status): stop trusting a cache or backoff dated in the future

Claude Status counted its cache as fresh while `now - fetchedAt` was
under five minutes, and its failure lock as active while `now - mtime`
was under 30 seconds. Neither check had a lower bound, so a timestamp
ahead of the clock always passed. After a clock that ran fast is set
back (an NTP correction after a VM resume, or a dual-boot machine that
keeps the hardware clock in local time), the widget kept showing the
cached status, "ok" through a major incident for instance, and fetched
nothing until real time caught up with the stamp: for as long as the
clock had been ahead. A lock written in that window held off every
fetch just as long.

Both checks now follow the rule the usage cache already uses: a stamp
counts while it lies within the window on either side of now. One a
little ahead still counts, since clocks sharing a home directory can
sit slightly apart. One further ahead than the window was written
under a clock since set back, so the cache is refetched and the lock
ignored; a failed fetch rewrites the lock with the current time, so it
heals on the next render.

* fix(claude-status): stop serving a status over an hour old as current

While status.claude.com can't be reached (offline, a network that
blocks it, or the page itself failing), Claude Status falls back to its
cached status. It never checked how old that cache was, so the last
status stayed on screen as current for as long as fetches kept
failing: days later, a laptop that fetched during an incident still
showed "Claude: major". With the history strip on, an incident still
open in that cache counts as running until now, so it spread into a
new six-hour block every six hours, and two days on all eight blocks
showed red for hours nobody had seen.

The fallback now serves the cache only while it is under an hour old,
and after that shows `?`, the widget's existing state for status it
doesn't have. An hour rides out a dropped connection or a short
offline stretch, twelve refresh intervals, while a status that old
says little about now. It also keeps the strip honest: within the
hour, an open incident reaches only into the newest block, which the
part already seen overlaps, so it colors the same blocks it would had
it ended when last seen.

* fix(claude-status): apply the future-date check to the in-flight fetch claim

The in-flight fetch lock rechecks the cache once it holds the claim, and
judges another process's claim by its age. Both compared ages directly, so a
cache or claim dated hours ahead by a clock since set back counted as current:
the recheck served a far-future cache without fetching, and a far-future claim
left behind by a stopped process held off every fetch until real time caught
up. Both now use the same window as the cache and failure lock checks.
* fix(speed): count only a request's in-window tokens in windowed speed

With a speed window set (for example 10s), Output, Input and Total Speed
picked each request whose response landed inside the window and added all
of its tokens, but divided by only the part of its user-to-response
interval that falls inside the window. A response that ran longer than the
window, or a tool result arriving soon after one (it moves the window's
end), left a thin slice of time against the whole request's tokens. One
90s response at 50 t/s read 450 t/s at a 10s window, and 45.0k t/s when
its tool result came 9.9s later, while the session average showed 50 t/s.

Each selected request now keeps the share of its tokens that matches the
share of its interval inside the window. A single request reads its own
speed at any window size, and several requests average by the time each
spent inside the window. The subagent window test expected the old
mismatch (15 t/s for a 12 t/s request) and now expects 12 t/s.

* fix(metrics): stop spreading a transcript's rows into one push call

Speed metrics merged each transcript's requests with
requests.push(...part.requests), and the block scan gathered each file's
timestamps with timestamps.push(...fileTimestamps). Both pass one argument
per usage row. Past about 125k rows in one transcript under Node (the
npm/npx install), or about 640k under Bun, the call throws "RangeError:
Maximum call stack size exceeded".

The speed merge runs inside the transcript scan's single try, so the throw
discarded everything the scan had gathered: with any speed widget on the
line, Tokens read 0, speed read the em dash, and Compaction Counter and
Session Name went blank. The block scan's catch turned the throw into "no
block", so Block Timer, Block Reset Timer and the block usage-percent
fallback showed 0hr 0m or nothing, and because that result is cached for
only 60s, the failing full scan ran again every minute.

Both now push one item at a time.
* feat(widgets): add prompt cache miss widgets

Claude Code 2.1.251+ reports the main conversation's prompt cache
statistics in the status line payload (`prompt_cache`), the same figures
`/usage` shows on its "Prompt cache (main)" line. A cache miss re-sends
content the cache already held, which is what makes usage jump without
anything else changing. Four new Cache widgets show them:

- Cache Misses: misses out of the session's requests (`2/14`)
- Last Cache Miss: how long ago the last miss was and its likely cause
  (`3m ago, tools changed (+2)`; causes need Claude Code 2.1.260+)
- Cache Miss Tokens: tokens the misses wrote back to the cache (`310.2k`)
- Cache If Cold: what the next request re-caches if the cache has gone
  cold by then (`45.0k`)

They read only the payload: no transcript scan and no network. Without
`prompt_cache` (older Claude Code, or before the session's first API
response) they render nothing. Cache Misses and Cache Miss Tokens can
hide while the session has no misses.

The schema drops a `prompt_cache` field in an unexpected shape instead of
rejecting the payload, so a future change to the object can't blank the
status line.

* fix(widgets): preserve Node 14 compatibility in cache cause formatting

---------

Co-authored-by: Matthew Breedlove <sirmalloc@gmail.com>
The Input, Output and Total Speed widgets' rolling window was capped at
120 seconds. Nothing in the calculation needs that cap: every render
reads the whole transcript whatever the window, the window ends at the
transcript's last entry and counts only the time responses were being
generated, and a window longer than the session gives the session
average. The cap only rules out longer horizons, such as the last 10
minutes or the last hour of a session.

Raise the cap to 3600 seconds. The window editor already takes any
number of digits and clamps on save, so 3600 is now kept and a longer
value saves as 3600, the way 120 did before. Past the session's length a
window equals the session average, which 0 already gives, so a bound
loses nothing, and it keeps a typo such as 36000 from quietly meaning
the whole session. Windows saved under the old cap read the same.

Co-authored-by: Matthew Breedlove <sirmalloc@gmail.com>
…ets (sirmalloc#768)

Two widgets that say how long until a 7-day limit at this week's average
pace, shown only when that comes before the window's reset:
`Weekly limit in: 1d 22hr 40m` for the all-models window and
`Fable limit in: 1d 4hr 8m` for Fable's.

The pace is the window's percent over the time since it started (its reset
minus 7 days), so nights and days off count; a 30-minute pace like Block
Limit Timer's would put the limit a day away during any busy hour. Both stay
hidden during the window's first day, when the limit comes after the reset,
and at 100%.

Block Limit Timer's rendering, `s` key, raw value and 1-minute floor move
into a LimitTimerWidget base that all three timers share.
…irmalloc#766)

Block Forecast and Block Limit Timer went by this session's percent, which
comes from its last response. A session blocked at the 5-hour limit gets no
new responses, so it can say 99% while the usage API says 100%, and the
forecast kept `→100% Limit in: 1m` next to Block Reset Timer's countdown
until the reset.

computeSessionForecastIfNeeded() now returns no forecast once
isAtSessionLimit() says the block is at its limit, after recording the
session's reading. That check reads the API's percent only when it was
fetched for Block Usage's or Block Reset Timer's hide states, so other lines
render as before and nothing new is fetched.

Co-authored-by: Matthew Breedlove <sirmalloc@gmail.com>
…the Terminal Width options (sirmalloc#765)

* feat(terminal): read COLUMNS from Claude Code before probing

Claude Code 2.1.153+ sets COLUMNS (and LINES) to the terminal size when it
runs the status line. Reading it after CCSTATUSLINE_WIDTH and before the
session cache skips the ps/stty ancestor walk on macOS/BSD and gives
Windows a width without an override. Invalid values fall through to probing.

* docs(windows): say Claude Code's COLUMNS gives Windows a width

The troubleshooting entry for wrapped status lines still said Windows has
no width unless CCSTATUSLINE_WIDTH is set. Claude Code 2.1.153 and later
pass the width in COLUMNS, which is now read there too, so the override
is only needed with older builds.

* feat: remove the Terminal Width options; lines always use the full width

Claude Code keeps the status line full-width and, since the previous
commits, its width comes from the COLUMNS it passes in. The two modes that
held 40 columns back for the auto-compact message no longer have anything
to choose between, so every line now renders the way the default, Full
width always, did: the detected width minus 6 columns, in piped output and
the TUI preview alike. Notifications that share the row outside fullscreen
rendering are Claude Code's to fit; on narrow terminals it cuts the status
line short.

Removed: the flexMode and compactThreshold settings, the Terminal Width
entry under Terminal Options (which keeps Color Level), and the Main Menu
warning that pointed there when Full width minus 40 truncated the preview,
together with the preview's truncation callback that only fed it.

Settings files that still carry flexMode or compactThreshold load without
an error or warning, whatever their values: the schema no longer defines
them, so parsing drops them and the next save writes the file without
them, the way a legacy git-pr widget type is rewritten. The v1 migration
no longer copies them, and imports ignore them. The two config templates
lose them too.

* fix(terminal): remove one column of right-side padding

---------

Co-authored-by: Lance Marks <lance.marks@kaleido.io>
Co-authored-by: Matthew Breedlove <sirmalloc@gmail.com>
sirmalloc#592)

The Cache Timer was the only timer widget without the shared (s) short time
toggle, and the only one rendering its countdown as mm:ss instead of labeled
units. It now renders '4m 52s' by default and '4m52s' in short time mode,
matching Block Timer, Block Reset Timer and Weekly Reset Timer, and it gains
hour parts for TTLs longer than an hour.

Co-authored-by: Matthew Breedlove <sirmalloc@gmail.com>
…c#352)

Claude Code hardcodes context_window_size to 200k for non-Claude models
(e.g. custom API proxies), so the piped JSON value cannot be trusted for
third-party models with larger windows. This env var takes precedence
over the piped value and accepts raw numbers, k/M suffixes, and
underscore/comma separators (e.g. 1M, 200k, 1_000_000).

The parsed result is cached at module scope keyed on the raw env string
so the hot-path render does not re-parse on every status line refresh.
Values that would round to under 1000 tokens are rejected to avoid
silent footguns like "1.5" producing a 2-token window.

Co-authored-by: Matthew Breedlove <sirmalloc@gmail.com>
…on (sirmalloc#407)

* fix: validate settings schema before saving to prevent data loss

* fix: use env override and settings for usable context ratio calculation

* Fix legacy auto-compaction preference and window clamping

---------

Co-authored-by: Matthew Breedlove <sirmalloc@gmail.com>
…sirmalloc#801)

The final output swapped every space for U+00A0, and those terminals only let a
Private Use Area icon use two cells when the next cell is U+0020 or U+2002. A
space right after such an icon, with or without color codes or link closers in
between, now becomes an en space, which is not trimmed either.

Fixes sirmalloc#796

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Zed registers a zed://file handler that opens files and directories as a
workspace, so it belongs with the IDE link modes that Current Working Dir
and Git Root Dir already offer.

Adding 'zed' to IDE_LINK_MODES extends both widgets at once: the CWD link
cycle becomes file -> VS Code -> Cursor -> Zed -> off, and Git Root Dir
becomes VS Code -> Cursor -> Zed -> off. Legacy linkToCursor metadata
counts as the cursor mode, so its first toggle now lands on zed instead of
clearing the link.

Tests cover zed:// URLs for POSIX, Windows drive-letter, and UNC paths,
both widgets' rendering and editor modifiers, and the TUI link cycle. Docs
list Zed in the cycle descriptions.
…alloc#795)

Bumps the dev-dependencies group with 3 updates: [@remotion/cli](https://github.com/remotion-dev/remotion), [remotion](https://github.com/remotion-dev/remotion) and [typescript-eslint](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/typescript-eslint).


Updates `@remotion/cli` from 4.0.538 to 4.0.539
- [Release notes](https://github.com/remotion-dev/remotion/releases)
- [Commits](remotion-dev/remotion@v4.0.538...v4.0.539)

Updates `remotion` from 4.0.538 to 4.0.539
- [Release notes](https://github.com/remotion-dev/remotion/releases)
- [Commits](remotion-dev/remotion@v4.0.538...v4.0.539)

Updates `typescript-eslint` from 8.71.2 to 8.72.0
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/typescript-eslint/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.72.0/packages/typescript-eslint)

---
updated-dependencies:
- dependency-name: "@remotion/cli"
  dependency-version: 4.0.539
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-dependencies
- dependency-name: remotion
  dependency-version: 4.0.539
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-dependencies
- dependency-name: typescript-eslint
  dependency-version: 8.72.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
* feat(context-bar): add a thin line display mode

Block glyphs (█░, ▓░) read heavy in light themes and plain-text layouts.
The new 'line' mode draws used context as ━ and the rest as ─, at the
same 16-cell width as the medium bar. It joins the end of the p cycle,
so existing configurations are unchanged.

* feat(widgets): extend line mode to all progress bars

---------

Co-authored-by: Matthew Breedlove <sirmalloc@gmail.com>
…alloc#792)

With no reset time from the status line payload or the usage API, Block
Reset Timer falls back to the 5-hour block found in the transcripts. In
timestamp mode it then formatted the missing sessionResetAt, got
nothing, and showed the remaining duration ("Reset: 3hr 45m") instead of
the reset time the user chose to see.

The block's end is known, so timestamp mode now formats that instant
when no reset time was reported.

Co-authored-by: effectustasi <216187407+effectustasi@users.noreply.github.com>
…malloc#790)

* test(git): cover grapheme clusters in branch abbreviations

* test(git): cover grapheme clusters in worktree abbreviations

* fix(git): preserve complete graphemes in fish-style branch names

* fix(git): preserve complete graphemes in fish-style worktree names
…irmalloc#787)

* fix(tui): mark Full width always as the default terminal width

The Terminal Width menu still marked "Full width minus 40" as
"(default)" after the settings default for flexMode moved to "full".
On a fresh install, or with any settings.json that has no flexMode,
the menu showed "Full width always (active)" with "Full width minus 40
(default)" below it. Picking the "(default)" entry to get back to the
default saved full-minus-40 instead.

"Full width always" now carries "(default)" while another mode is
active, following the rule the old marker used, and "Full width minus
40" shows only "(active)". A test checks the marker against
DEFAULT_SETTINGS, so a later change to the default can't leave the
menu behind again.

* fix(tui): say Full width always reserves 6 columns, not 4

The Terminal Width menu's description of "Full width always" says it
uses the full terminal width minus 4 characters. The renderer has
reserved 6 columns for that mode, in the preview and in the piped
status line, since the reserve changed from 4 to 6, and the menu text
wasn't updated with it. At 100 columns a long line truncates, and a
flex separator fills, to 94 columns rather than the 96 the menu
promises.

The description now says 6, matching the renderer. The renderer is
unchanged. The test renders a long line in that mode at 100 columns
and checks that the description names the number of columns the
renderer left free, so a later change to the reserve can't leave the
menu behind again.

* fix(tui): put the space back in the delete-line dialog's heading

Pressing d in Edit Lines opened a confirmation headed "☰ Line2 (2
widgets)", while the list and move mode both show "☰ Line 2". In the
dialog's JSX, "☰ Line" and the line number sit on separate lines, and
JSX drops whitespace that contains a line break, so nothing separated
them. The {' '} that used to sit between them was lost when the menus
moved to the shared List component.

The heading puts {' '} between the two again, as move mode does. The
existing delete test accepted the heading with or without the space;
it now expects "☰ Line 2 (empty)" and "☰ Line 1 (1 widget)", and waits
for the dialog before checking the second, since the list row behind
it has the same text.
…sts (sirmalloc#788)

The line editor and color menu tests slept a fixed 25ms after rendering
and after each key, then asserted. Ink redraws, and React re-attaches
Ink's input listener, on their own schedule. On a loaded machine the
assertion ran before the redraw, or the next key reached the listener
left from before the last redraw and was applied to the old state.
Under load these tests failed intermittently, the number style and
label tests most often.

Each wait now retries until the key's visible effect shows (the row's
new suffix, the label editor's draft, the picker's search text, the
moved highlight), then yields two setImmediate turns before the next
key, through the shared helper in src/tui/__tests__/helpers/wait-for-ink.ts.
Assertions that only restated a wait move into it; the rest are
unchanged.
…t left glyphs entered by hex (sirmalloc#786)

* fix(colors): clear separator colors a new Color Level can't show

Changing Color Level resets each widget's ansi256 or hex color that the
new level can't show to the widget's default, and clears such
backgrounds. A separator's foreground was skipped, because separators
have no widget default to reset to, so it kept its color. A separator
given a hex color at Truecolor still had it after cycling on to 256
Color, and the 256-color line printed a 24-bit escape for it
(\x1b[38;2;0;255;0m) next to the widgets' 38;5 codes.

The reset warning counts separator colors as well, so with only a
colored separator it promised a reset, and confirming it changed
nothing.

Clear a separator foreground the new level can't show, as backgrounds
already are. Without a color, a separator renders in the separator
default, or takes the previous widget's colors when separators inherit
colors.

* fix(powerline): invert a left-facing separator entered by hex code

Picking Triangle Left or Round Left with the arrow keys turns on the
separator's background inversion, which a left-facing glyph needs to
draw the next segment's color on the previous segment's background.
Entering the same glyph with (h), as E0B2 or E0B6, kept the slot's old
inversion instead. On the default separator that is off, so the arrow
was drawn reversed (\x1b[31m\x1b[44m between a red and a blue segment,
instead of \x1b[34m\x1b[41m), and the list showed no [Inverted] to hint
that (t) was needed. Typing E0B0 over an inverted Triangle Left
likewise left the right triangle inverted.

When (h) enters one of the preset glyphs, set its inversion as the
arrow keys do: on for the left-facing ones, off for the right-facing
ones. A custom code point keeps the slot's inversion, since its
direction is unknown, and (t) still toggles it.
eric-engberg and others added 23 commits November 5, 2026 11:21
…or (sirmalloc#785)

Ink 6.2.0's insertBeforeNode returns early when it inserts a node before
an existing sibling, so it never marks the parent text dirty the way
appendChildNode (and its own append branch) do. Yoga keeps the text's
old measured size, and Ink wraps the line at the old width onto rows
the layout never reserved, where the next row draws over it. It stays
that way until something re-measures the text, such as the next key.

The Custom Command and Link editors render the value as three sibling
texts: the part before the cursor, the cursor cell and the rest. With
the cursor at the start, as in an empty field, the part before it
renders nothing, so the next input inserts a new text ahead of the
cursor cell. Pasting "npx ccusage statusline" into an empty Custom
Command field showed only "npx ccusage", though Enter saved the whole
command. A URL or link text pasted into an empty Link field was cut the
same way, with its cut-off end showing at the end of the next row. A
key typed at the start of a command that was already the editor's
widest row hid the command's last word.

Add a hunk to the ink patch that marks the node dirty after both
branches, as Ink does upstream from 6.8.0.
… at the configured Color Level (sirmalloc#784)

* fix(tui): keep the main menu's highlight when a save changes its entries

Pressing Ctrl+S on the main menu after making changes moved the
highlight back to the entry that was last opened. Saving swaps Save &
Exit and Exit without saving for a single Exit, and List reset its
highlight to initialSelection whenever the number of items changed. The
main menu's initialSelection is the entry last opened, not the one
highlighted, so the cursor left the entry the user had moved to and the
next Enter opened a different screen.

List gets a keepHighlightOnItemsChange prop, and the main menu sets it.
With it, a new initialSelection still moves the highlight, but when just
the number of items changes, the highlight stays on the item it was on;
if that item is gone, it stays on the same row, inside the list. On the
main menu, Install stays Install after a save, and Save & Exit or Exit
without saving become the Exit that replaces them.

Other lists still move the highlight to initialSelection when their
item count changes. Line selection and Powerline Setup keep their
initialSelection on the highlight and set it to place the highlight:
appending a line highlights the new line, and turning Powerline on
highlights Separator.

* fix(tui): build the preview's color codes for the configured color level

In a terminal that chalk detects at fewer colors than the configured
color level, such as tmux with TERM=screen or ssh with TERM=xterm, the
TUI preview and color menus drew different colors from the real status
line. At the default 256 colors, cyan, magenta and bright black widgets
were drawn black; a truecolor setting previewed 256-color
approximations.

chalk works out a 256-color or hex style's escape code when the style
is created, at the level set at that moment. COLOR_MAP creates its
styles when colors.ts loads, so its codes follow the level chalk
detected for the terminal. The piped render sets chalk.level and then
calls updateColorMap() to rebuild them; the TUI set chalk.level on
load, on import and in Terminal Options, but never rebuilt the map.

The TUI now calls updateColorMap() each time it sets chalk.level, as
the piped render does. The test sandbox rebuilds the map when it puts
chalk's level back, so later test files get the codes they expect.

* docs(tui): say the main menu's initialSelection is the highlighted row

The main menu now records its highlighted row as it moves, so
initialSelection is that row's index rather than the entry last opened.
Keeping the highlight on its entry across a save is still needed: the
save swaps Save & Exit and Exit without saving for one Exit, which moves
the entries below, so the index alone would land on another entry. The
comments on MainMenu and List's keepHighlightOnItemsChange say so.

* test(tui): walk the main menu to an entry rather than through a fixed list

The main menu highlight tests pressed down through a hard-coded list of
entries, so an entry another change adds or makes selectable (Configure
Status Line opening before an install, say) broke them. They now press
down until the target entry is highlighted, waiting for the highlight to
move on each press.

* test(app): open Color Level directly, now Terminal Options' first row

With sirmalloc#765 Terminal Options lists only Color Level, so the steps that went
through Terminal Width land on Color Level when the menu opens.
… temp files (sirmalloc#783)

* fix(terminal): stop leaking temp files when the width cache write fails

writeCachedWidth wrote a temp file named after the process id and renamed
it over terminal-width.json inside a catch that swallowed every error.
When the rename failed (EPERM on Windows while a virus scanner or sync
client holds a handle on the file), the temp file stayed behind. Every
render is a new process with a new pid, so each failed write left one
more terminal-width.json.<pid>.tmp in ~/.cache/ccstatusline, and nothing
ever removed them. On Windows this write is routine: probing is disabled
there, so the no-width entry is rewritten whenever it passes the TTL, and
on every render while the rename keeps failing, since a failed write
leaves the old entry stale.

Handle it the way the git cache does since sirmalloc#564: remove the temp file
when the write or rename fails, and use one stable name
(terminal-width.json.tmp), so a cleanup blocked by the same handle leaves
at most one file, which the next write truncates. Writers use it under
the cache lock; one that proceeds unlocked can at worst leave malformed
JSON, which readCache already treats as a miss.

* fix(custom-command): stop leaking temp files when the cache write fails

writePersistentCache wrote a temp file named after the process id and
the current time, and renamed it over the cache file inside a catch that
swallowed every error. When the rename failed (EPERM on Windows while a
virus scanner or sync client holds a handle on the file), the temp file
stayed behind. With customCommandCacheTtlSeconds above 0, nothing reaches
the cache while the rename keeps failing, so every repaint misses, runs
the command again and leaves one more cmd-<hash>.json.<pid>.<ms>.tmp in
~/.cache/ccstatusline/custom-command-cache. Nothing ever removed them.

Handle it the way the git cache does since sirmalloc#564: remove the temp file
when the write or rename fails, and use one stable name
(cmd-<hash>.json.tmp), so a cleanup blocked by the same handle leaves at
most one file per cache file, which the next write truncates. The cost is
the one the git cache accepted: two sessions writing the same directory's
cache at the same moment can tear the shared temp file, and
readPersistentCache treats the malformed JSON as a miss.
…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>
…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.
@sonarqubecloud

sonarqubecloud Bot commented Nov 6, 2026

Copy link
Copy Markdown

Quality Gate Failed Quality Gate failed

Failed conditions
1 New Critical Issues (required ≤ 0)

See analysis details on SonarQube Cloud

Catch issues before they fail your Quality Gate with our IDE extension SonarQube for IDE

@eric-engberg

Copy link
Copy Markdown
Owner Author

Merged upstream as sirmalloc#767.

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.