Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
aa7c1f5
fix(usage): keep an API failure's label across renders
eric-engberg Oct 16, 2026
c990c5e
fix(usage): ignore a short usage lock dated ahead by a clock set back
eric-engberg Oct 16, 2026
bde962c
fix(usage): stop waiting once the usage response stream fails
eric-engberg Oct 16, 2026
85321b4
fix(usage): keep fetch backoff working when ~/.cache can't be written
eric-engberg Oct 16, 2026
c1c3bbb
fix(usage): show lasting fetch errors on reset-only timer lines
eric-engberg Oct 16, 2026
0121a13
fix(usage): keep reset timers loading through failures that clear up
eric-engberg Oct 16, 2026
856bb0f
fix(usage): keep a proxy's refused CONNECT a lasting error under Bun
eric-engberg Oct 16, 2026
a01192b
fix(usage): show a server certificate that doesn't verify as a lastin…
eric-engberg Oct 16, 2026
4369b0a
fix(usage): count a 408 answer as a failure that clears up on its own
eric-engberg Oct 16, 2026
a2ac2c3
fix(usage): show three more certificate failures as lasting errors
eric-engberg Oct 16, 2026
4fde2f5
fix(usage): count every certificate verification failure as lasting
eric-engberg Oct 16, 2026
69e5b09
Merge branch 'main' into fix/usage-fetch-failures
eric-engberg Oct 27, 2026
3a9f166
Merge branch 'main' into fix/usage-fetch-failures
eric-engberg Oct 30, 2026
f2c37f8
Merge branch 'main' into fix/usage-fetch-failures
eric-engberg Oct 30, 2026
62a4e93
Merge branch 'main' into fix/usage-fetch-failures
eric-engberg Oct 30, 2026
0a85320
Merge branch 'main' into fix/usage-fetch-failures
eric-engberg Oct 30, 2026
d2d0c60
Merge branch 'main' into fix/usage-fetch-failures
eric-engberg Oct 30, 2026
c5629fe
Merge branch 'main' into fix/usage-fetch-failures
eric-engberg Nov 6, 2026
c22e826
refactor(usage): resolve the writable cache folder without ??=
eric-engberg Nov 6, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions docs/DEVELOPMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ With `CCSTATUSLINE_DEV_RELOAD=1`, Ctrl+R restarts the interactive process with i
- `~/.cache/ccstatusline/claude-status.json` and `~/.cache/ccstatusline/claude-status.lock` - Claude service-status cache and failed-fetch backoff lock; `claude-status.inflight` coordinates concurrent fetches
- `~/.cache/ccstatusline/skills/skills-<sessionId>.jsonl` - skill hook records; session IDs must contain only ASCII letters, digits, `-`, or `_`

When `~/.cache/ccstatusline` can't be created or written, the usage and Claude Status files move to `ccstatusline-<uid>` in the system temp folder (`ccstatusline` on Windows), so their fetch backoff still holds between renders. That folder is used only while it is a real folder owned by the current account that no other account can write to.

If you use a custom Claude config location, set `CLAUDE_CONFIG_DIR` and ccstatusline will read/write that path instead of `~/.claude`.

On macOS, usage credentials for a custom profile come from `Claude Code-credentials-<sha256(configDir)[:8]>`, then that profile's `.credentials.json`; the lookup does not fall back to another profile's Keychain entry. The hash uses the raw `CLAUDE_CONFIG_DIR` value normalized to NFC, without path resolution. `CLAUDE_SECURESTORAGE_CONFIG_DIR` overrides that hash input, including an empty value to force the default service lookup. Default lookup tries the plain service, then the same service scoped to `os.userInfo().username` if no OAuth token was found, then discovered suffixed services and the credentials file. If the OS username cannot be resolved, the account-scoped retry is skipped. Both access and refresh tokens are preserved for cache identity checks. Other platforms use the credentials file directly. Each Keychain subprocess has a five-second timeout; a timeout stops further Keychain probes for that lookup (including the username retry) and continues with the current profile’s credentials file, while an ordinary miss continues to the next source. A missing OAuth login triggers a profile-specific 30-second lookup backoff.
Expand All @@ -91,11 +93,11 @@ Configuration exports snapshot the live TUI settings and add an `exportedBy` pac

`ImportPreviewDialog` compares the selected mode's effective Custom Command strings with the current settings, lists new commands without duplicates, and requires confirmation with Cancel selected by default before applying them. Imports without new commands keep the direct apply flow. Preview paths, values, and commands escape C0/C1 controls as visible `\uXXXX` text.

Usage-fetch tests spawn subprocess probes. Keep those probes sandboxed by setting `HOME`, `USERPROFILE`, `CLAUDE_CONFIG_DIR`, and proxy variables explicitly so tests cannot read or write a developer's live ccstatusline usage cache.
Usage-fetch tests spawn subprocess probes. Keep those probes sandboxed by setting `HOME`, `USERPROFILE`, `CLAUDE_CONFIG_DIR`, the temp-folder variables (`TMPDIR`, `TMP`, `TEMP`), and proxy variables explicitly so tests cannot read or write a developer's live ccstatusline usage cache.

Usage-lock deadlines more than 24 hours ahead are treated as poisoned and ignored, so mocked clocks, system clock jumps, or old test artifacts cannot suppress usage fetching indefinitely. Valid deadlines up to 24 hours ahead, including API `Retry-After` backoffs, remain active. Likewise, a usage cache file modified more than its 180-second lifetime in the future counts as stale rather than fresh.
Usage-lock deadlines further ahead than their kind of lock allows are treated as poisoned and ignored, so mocked clocks, system clock jumps, or old test artifacts cannot suppress usage fetching. Rate-limit locks stay active up to 24 hours ahead, which covers API `Retry-After` backoffs. Every other lock is written 30 seconds ahead and counts for up to a minute ahead, leaving room for a concurrent render that read the clock a moment later; one dated further ahead was written under a clock since set back. Likewise, a usage cache file modified more than its 180-second lifetime in the future counts as stale rather than fresh.

After a complete successful usage fetch, the process clears the lock only if its contents still match the in-flight record it wrote, preserving a concurrent render's newer rate-limit backoff.
After a complete successful usage fetch, the process clears the lock only if its contents still match the in-flight record it wrote, preserving a concurrent render's newer rate-limit backoff. A request that fails without a 429 replaces that same in-flight record with a 30-second `api-error` lock, so renders inside the backoff report `[API Error]` rather than `[Timeout]`. When the failure clears up on its own (a 5xx or 408 response, a network error, or a request past the 5-second deadline), the lock also records `"transient": true`, so the reset timers keep their loading placeholder inside the backoff as well. Any other failure, such as a 401 or 403 for a rejected token or a server certificate that doesn't verify (for example a self-signed one, one from an unknown CA or signed by a certificate that may not sign others, an expired or not-yet-valid one, or one for another host), writes no marker, and a lock without one, including one written before the marker existed, reads as a lasting failure.

Stale-cache fallback removes each expired window's usage and reset fields while retaining other usable fields. Partial fallback data can carry an error for missing required fields without suppressing widgets whose data remains valid. `getUsageFetchedAtMs()` preserves the original fetch time (disk-cache mtime for cached answers), rather than treating a stale read as a new observation.

Expand Down
2 changes: 1 addition & 1 deletion docs/USAGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ ccstatusline --version
- **Context Length** / **Context Window** / **Context %** / **Context % (usable)** / **Context Bar** - Show current context length, total context window size, used/remaining percentage, usable-window percentage, or a progress bar. When Claude Code omits a percentage, the percentage calculated from its current usage counts input, cache-read, and cache-write tokens, excluding output tokens until a later turn reads them as input. Reported percentages retain precedence unless `CCSTATUSLINE_CONTEXT_WINDOW_SIZE` overrides the window, in which case percentages are recalculated from token usage. The window size comes first from that override, then Claude Code's reported `context_window.context_window_size`, then a model-name hint (e.g. a `[1m]` suffix), and finally a fixed fallback. The override accepts token counts or case-insensitive `k`/`M` suffixes, such as `200000`, `200k`, or `1M`, including decimal values and comma/underscore separators; values are rounded to whole tokens and ignored if invalid or below 1,000. Set `CCSTATUSLINE_CONTEXT_SIZE_FALLBACK` to a positive integer to override that last-resort fallback (defaults to `200000`) — useful when an older Claude Code does not report the window size for a 1M-context model, so the bar would otherwise read against 200k. Immediately after `/compact`, transcript fallback uses the latest `compact_boundary.postTokens` value until a new main-chain turn reports the current size, so the widgets do not retain the pre-compaction context.
- **Compaction Counter** - Show how many context compactions have been detected in the current session by scanning transcript compaction markers. It can render as icon plus number, text plus number, or number-only, and can hide while the count is zero. Two optional, independent per-item add-ons toggle extra detail: a trigger split (`↻ 3 (2 auto, 1 manual)`; a compaction whose trigger is missing or unrecognized is bucketed as `unknown`) and tokens reclaimed (`↻ 3 ↓887.0k`, each compaction's `preTokens - postTokens` floored at 0 and summed, shown only when greater than 0 — so very old transcripts predating the `postTokens` field display nothing). Its value selector can instead render the total count, one trigger count (`auto`, `manual`, or `unknown`), or reclaimed tokens as a standalone value; hide-when-zero applies to the selected value.
- **Spend Limit Usage** / **Spend Limit Amount** - For developers behind a Claude apps gateway with spend limits (Claude Code 2.1.251 or later). Spend Limit Usage shows the share of the limit used, as a percentage or bar, and can show the remaining share instead. Spend Limit Amount shows `$314.12 / $500.00` and renders nothing until the gateway reports the dollar figures (Claude Code and gateway 2.1.284 or later). Both read `rate_limits.spend_limit` from the status line payload only and never call the usage API; without a spend limit they render nothing.
- **Block Usage** / **Weekly Usage** / **Weekly Sonnet Usage** / **Weekly Opus Usage** / **Weekly Fable Usage** / **Extra Usage Utilization** / **Extra Usage Remaining** / **Extra Usage Used** / **Extra Usage Limit** / **Extra Usage Today** / **Extra Usage Daily Budget** / **Block Timer** / **Block Reset Timer** / **Weekly Reset Timer** - Show usage percentages, monthly pay-as-you-go overage usage, and current block/reset timing. Block Usage and the all-model Weekly Usage read the legacy flat API buckets when available and fall back per field to `session` and `weekly_all` entries in the newer `limits[]` response. The per-model widgets prefer `weekly_scoped` entries for Sonnet, Opus, and Fable, with legacy Sonnet/Opus buckets as fallbacks; Weekly Fable Usage renders nothing when the API reports no Fable quota. Block Usage, the weekly percentage widgets, and Extra Usage Utilization can show either used or remaining percentage in every display mode. Block and weekly usage bars can also show a time cursor: elapsed time in used mode, or time remaining in remaining mode. Extra usage widgets accept known extra-usage state as complete when an account has no monthly limit configured, avoid repeated refetches and stale `[Timeout]` output, and format amounts with the API-reported billing currency when available. On accounts with no plan limits (usage-based Enterprise plans), extra usage is all of the account's spend rather than overage beyond a plan; the label editor can change the Extra Usage widgets' `Overage` labels to read `Spend`. Extra Usage Limit shows the monthly limit itself, or `none` when extra usage is on without a monthly limit. Extra Usage Today shows the extra usage spent since 00:00 UTC, including claude.ai and other machines. The usage API only reports month-to-date totals, so ccstatusline keeps each login's total at the start of the UTC day in `~/.cache/ccstatusline/daily.json`: the last total it saw the previous day, zero on the 1st (extra usage resets then), or otherwise the first total it sees that day, which misses spend from before Claude Code was opened. Before the first charge of the month the API reports no utilization, so Extra Usage Utilization works it out from the amount spent and the monthly limit. Extra Usage Daily Budget divides what's left of the monthly limit by the days left in the month, today included, optionally skipping future weekend days (today always counts). It requires a monthly limit and amount spent, and displays zero once the limit is exhausted. Days are UTC days, since monthly limits reset at 00:00 UTC on the 1st. Reset timers can show remaining time, progress, or exact reset date/time with timezone and locale controls; while reset data is still arriving at startup, they show a labeled loading placeholder instead of a transient API error.
- **Block Usage** / **Weekly Usage** / **Weekly Sonnet Usage** / **Weekly Opus Usage** / **Weekly Fable Usage** / **Extra Usage Utilization** / **Extra Usage Remaining** / **Extra Usage Used** / **Extra Usage Limit** / **Extra Usage Today** / **Extra Usage Daily Budget** / **Block Timer** / **Block Reset Timer** / **Weekly Reset Timer** - Show usage percentages, monthly pay-as-you-go overage usage, and current block/reset timing. Block Usage and the all-model Weekly Usage read the legacy flat API buckets when available and fall back per field to `session` and `weekly_all` entries in the newer `limits[]` response. The per-model widgets prefer `weekly_scoped` entries for Sonnet, Opus, and Fable, with legacy Sonnet/Opus buckets as fallbacks; Weekly Fable Usage renders nothing when the API reports no Fable quota. Block Usage, the weekly percentage widgets, and Extra Usage Utilization can show either used or remaining percentage in every display mode. Block and weekly usage bars can also show a time cursor: elapsed time in used mode, or time remaining in remaining mode. Extra usage widgets accept known extra-usage state as complete when an account has no monthly limit configured, avoid repeated refetches and stale `[Timeout]` output, and format amounts with the API-reported billing currency when available. On accounts with no plan limits (usage-based Enterprise plans), extra usage is all of the account's spend rather than overage beyond a plan; the label editor can change the Extra Usage widgets' `Overage` labels to read `Spend`. Extra Usage Limit shows the monthly limit itself, or `none` when extra usage is on without a monthly limit. Extra Usage Today shows the extra usage spent since 00:00 UTC, including claude.ai and other machines. The usage API only reports month-to-date totals, so ccstatusline keeps each login's total at the start of the UTC day in `~/.cache/ccstatusline/daily.json`: the last total it saw the previous day, zero on the 1st (extra usage resets then), or otherwise the first total it sees that day, which misses spend from before Claude Code was opened. Before the first charge of the month the API reports no utilization, so Extra Usage Utilization works it out from the amount spent and the monthly limit. Extra Usage Daily Budget divides what's left of the monthly limit by the days left in the month, today included, optionally skipping future weekend days (today always counts). It requires a monthly limit and amount spent, and displays zero once the limit is exhausted. Days are UTC days, since monthly limits reset at 00:00 UTC on the 1st. Reset timers can show remaining time, progress, or exact reset date/time with timezone and locale controls. While their reset time is still on its way, they show a labeled loading placeholder: when the usage API answers 429 before Claude Code's payload carries `rate_limits`, while another render's fetch is still in flight, and through failures that clear up on their own (a 5xx or 408 response, a network error, or a request that runs past the 5-second limit). A failure that lasts shows its usage error instead, such as no OAuth login, a token the API rejects or another 4xx answer other than 408, a server certificate that can't be verified (for example from a proxy or firewall that intercepts TLS with a certificate the runtime doesn't trust), or a response that can't be read.
- **Block Forecast** / **Block Limit Timer** - Forecast the 5-hour block from the recent pace. Block Forecast shows the projected usage at reset (`→83.2%`), and Block Limit Timer shows how long until 100% (`Limit in: 1hr 13m`) when that comes before the reset. Both go away once the block reaches 100%, by the session's percent or, with Block Usage's `at-limit` or Block Reset Timer's `under-limit` hide state on, by those states' check (the usage API's percent), whichever gets there first. So they never sit next to the reset countdown. Each renders nothing until it has something to show, so they sit naturally right after the 5-hour usage widget. The pace is measured over the last 30 minutes from readings saved in `~/.cache/ccstatusline/session-usage-history.json`, kept separately for each Claude config directory and each login within it. A stretch with no status-line updates (the machine asleep, or usage on another device) is spread evenly across the gap, and a new block can be forecast once it is 10 minutes old.
- **Weekly Limit Timer** / **Weekly Fable Limit Timer** - Show how long until the all-models or the Fable-only 7-day limit at this week's average pace (`Weekly limit in: 1d 22hr 40m`, `Fable limit in: 2d 4hr`), when that comes before the window's reset. The pace is the window's percent over the time since it started, which is its reset time minus 7 days, so nights and days off count toward it. Each renders nothing during the window's first day, when the pace reaches the limit only after the reset, and at 100%, where Weekly Reset Timer takes over. They read the same percent and reset time as Weekly Usage and Weekly Fable Usage (Fable's window uses the all-models reset when the API sends none of its own), and save no history.

Expand Down
93 changes: 93 additions & 0 deletions src/utils/__tests__/cache-dir.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import {
afterEach,
beforeEach,
describe,
expect,
it
} from 'vitest';

import { __testing } from '../cache-dir';

// Root can write anywhere, and Windows ignores the read-only mode on folders
const canMakeReadOnly = process.platform !== 'win32' && process.getuid?.() !== 0;

describe('writable cache folder', () => {
let tempRoot = '';
let home = '';
let tmpDir = '';
let userCacheDir = '';
let preferredDir = '';
let fallbackDir = '';

beforeEach(() => {
tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'ccstatusline-cache-dir-test-'));
home = path.join(tempRoot, 'home');
tmpDir = path.join(tempRoot, 'tmp');
userCacheDir = path.join(home, '.cache');
preferredDir = path.join(userCacheDir, 'ccstatusline');
fallbackDir = path.join(tmpDir, `ccstatusline-${process.getuid?.()}`);
fs.mkdirSync(home);
fs.mkdirSync(tmpDir);
});

afterEach(() => {
if (fs.existsSync(userCacheDir)) {
fs.chmodSync(userCacheDir, 0o755);
}
fs.rmSync(tempRoot, { recursive: true, force: true });
});

function makeUserCacheReadOnly(): void {
fs.mkdirSync(userCacheDir);
fs.chmodSync(userCacheDir, 0o555);
}

it('uses ~/.cache/ccstatusline, creating it', () => {
expect(__testing.resolveWritableCacheDir(home, tmpDir)).toBe(preferredDir);
expect(fs.statSync(preferredDir).isDirectory()).toBe(true);
expect(fs.existsSync(fallbackDir)).toBe(false);
});

it.skipIf(!canMakeReadOnly)('falls back to a folder only this account can use when ~/.cache cannot be written', () => {
makeUserCacheReadOnly();

expect(__testing.resolveWritableCacheDir(home, tmpDir)).toBe(fallbackDir);
expect(fs.statSync(fallbackDir).mode & 0o777).toBe(0o700);
});

it.skipIf(!canMakeReadOnly)('reuses the fallback folder a previous render created', () => {
makeUserCacheReadOnly();
fs.mkdirSync(fallbackDir, { mode: 0o700 });
fs.writeFileSync(path.join(fallbackDir, 'usage.lock'), '{}');

expect(__testing.resolveWritableCacheDir(home, tmpDir)).toBe(fallbackDir);
expect(fs.readdirSync(fallbackDir)).toEqual(['usage.lock']);
});

// Another account could put made-up usage data or backoff locks there
it.skipIf(!canMakeReadOnly).each([
{
name: 'a folder other accounts can write to',
create: () => {
fs.mkdirSync(fallbackDir);
fs.chmodSync(fallbackDir, 0o777);
}
},
{
name: 'a link to another folder',
create: () => {
const target = path.join(tempRoot, 'elsewhere');
fs.mkdirSync(target, { mode: 0o700 });
fs.symlinkSync(target, fallbackDir);
}
}
])('passes over a fallback that is $name', ({ create }) => {
makeUserCacheReadOnly();
create();

expect(__testing.resolveWritableCacheDir(home, tmpDir)).toBe(preferredDir);
});
});
Loading
Loading