Skip to content

Commit d02e570

Browse files
committed
fix(usage): keep each login's 5-hour block apart in the forecast history
The forecast history was kept per Claude config directory, and a reading joined the window whose reset was within a minute of its own. After /login to another account in the same directory, that account's block can reset at the same moment as the last one's, since the usage API's resets fall on whole 10-minute marks. Its readings then joined the first account's window, where a lower percent counted as a stale session's and was dropped, and the forecast went from the first account's percent: switching from an account at 100% to one at 10% hid Block Forecast and Block Limit Timer until the reset. The history now goes by config directory and login, the login being the usage cache's fingerprint of its refresh token (#536). That stays the same when Claude Code reissues the access token every few hours, and changes with /login. getUsageLoginFingerprint reads it through the usage widgets' credential lookup, including its 30-second backoff after finding no login. Without one (a token from the environment, say), the history goes by the config directory alone, as before. On macOS that is one keychain read per render that has a forecast widget and a 5-hour percent; a render whose percent comes from the payload didn't read the keychain before.
1 parent 87b3563 commit d02e570

9 files changed

Lines changed: 101 additions & 8 deletions

‎docs/DEVELOPMENT.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ bun run docs
5757
- `~/.cache/ccstatusline/terminal-width.json` - per-session no-width probe results; detected numeric widths are not persisted by the renderer
5858
- `~/.cache/ccstatusline/usage.json` and `~/.cache/ccstatusline/usage.lock` - usage API data cache and fetch backoff lock
5959
- `~/.cache/ccstatusline/usage-credentials.lock` - 30-second backoff after a usage credential lookup finds no OAuth login, tagged with the profile it applies to
60-
- `~/.cache/ccstatusline/session-usage-history.json` and `~/.cache/ccstatusline/session-usage-history.json.lock` - 5-hour usage readings for Block Forecast and Block Limit Timer, per Claude config directory, and the lock a render holds while writing them
60+
- `~/.cache/ccstatusline/session-usage-history.json` and `~/.cache/ccstatusline/session-usage-history.json.lock` - 5-hour usage readings for Block Forecast and Block Limit Timer, per Claude config directory and login, and the lock a render holds while writing them
6161
- `~/.cache/ccstatusline/claude-status.json` and `~/.cache/ccstatusline/claude-status.lock` - Claude service-status cache and failed-fetch backoff lock
6262
- `~/.cache/ccstatusline/skills/skills-<sessionId>.jsonl` - skill hook records; session IDs must contain only ASCII letters, digits, `-`, or `_`
6363

‎docs/USAGE.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ ccstatusline --version
6262
- **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.
6363
- **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.
6464
- **Block Usage** / **Weekly Usage** / **Weekly Sonnet Usage** / **Weekly Opus Usage** / **Weekly Fable Usage** / **Extra Usage Utilization** / **Extra Usage Remaining** / **Extra Usage Used** / **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. 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`. 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.
65-
- **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. Each renders nothing until it has something to show, so they sit naturally right after the 5-hour usage widget. Add them as separate widgets rather than merging them into it: a merge carries across a widget that renders nothing, so a hidden forecast would join the usage widget to whatever follows it. 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. 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.
65+
- **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. Each renders nothing until it has something to show, so they sit naturally right after the 5-hour usage widget. Add them as separate widgets rather than merging them into it: a merge carries across a widget that renders nothing, so a hidden forecast would join the usage widget to whatever follows it. 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.
6666

6767
An explicit per-model quota at 0% is shown even when its reset timestamp is still missing; the time cursor appears only once a usable window is available. Weekly Fable Usage uses the label `Weekly Fable:` and stays empty when the API reports no Fable quota.
6868

‎src/utils/__tests__/session-forecast-prefetch.test.ts‎

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,14 +104,44 @@ describe('computeSessionForecastIfNeeded', () => {
104104
expect(forecast?.limitInMs).toBeNull();
105105
});
106106

107-
it('files readings under the Claude config directory', () => {
107+
it('files readings under the Claude config directory and login', () => {
108108
const deps = makeDeps();
109+
deps.loginFingerprint = () => 'aaaaaaaaaaaaaaaa';
110+
111+
computeSessionForecastIfNeeded([[{ id: '1', type: 'block-forecast' }]], usageData, deps);
112+
113+
expect(storedProfiles(deps)).toEqual([`${path.resolve(PROFILE)}#aaaaaaaaaaaaaaaa`]);
114+
});
115+
116+
// Signed in with a token from the environment, say
117+
it('files readings under the Claude config directory alone without a login', () => {
118+
const deps = makeDeps();
119+
deps.loginFingerprint = () => null;
109120

110121
computeSessionForecastIfNeeded([[{ id: '1', type: 'block-forecast' }]], usageData, deps);
111122

112123
expect(storedProfiles(deps)).toEqual([path.resolve(PROFILE)]);
113124
});
114125

126+
// After /login to another account in the same config directory, that
127+
// account's block can reset at the very moment the last one's does. Its
128+
// lower percent isn't a stale session's to drop.
129+
it('keeps another login\'s readings apart, even when its block resets at the same moment', () => {
130+
const deps = makeDeps();
131+
const lines: WidgetItem[][] = [[{ id: '1', type: 'block-forecast' }]];
132+
133+
deps.loginFingerprint = () => 'aaaaaaaaaaaaaaaa';
134+
computeSessionForecastIfNeeded(lines, { ...usageData, sessionUsage: 100 }, deps);
135+
deps.loginFingerprint = () => 'bbbbbbbbbbbbbbbb';
136+
const forecast = computeSessionForecastIfNeeded(lines, { ...usageData, sessionUsage: 10 }, deps);
137+
138+
expect(forecast?.currentPercent).toBe(10);
139+
expect(storedProfiles(deps)).toEqual([
140+
`${path.resolve(PROFILE)}#aaaaaaaaaaaaaaaa`,
141+
`${path.resolve(PROFILE)}#bbbbbbbbbbbbbbbb`
142+
]);
143+
});
144+
115145
it('shares one history whether or not the config directory has a trailing slash', () => {
116146
const deps = makeDeps();
117147
const lines: WidgetItem[][] = [[{ id: '1', type: 'block-forecast' }]];
@@ -132,9 +162,15 @@ describe('computeSessionForecastIfNeeded', () => {
132162
['no usage data', null]
133163
])('does nothing with %s', (_label, data: RenderUsageData | null) => {
134164
const deps = makeDeps();
165+
let loginLookups = 0;
166+
deps.loginFingerprint = () => {
167+
loginLookups += 1;
168+
return null;
169+
};
135170

136171
expect(computeSessionForecastIfNeeded([[{ id: '1', type: 'block-forecast' }]], data, deps)).toBeNull();
137172
expect(deps.reads).toBe(0);
173+
expect(loginLookups).toBe(0);
138174
});
139175

140176
it('clamps a session percent over 100 and has nothing to forecast', () => {

‎src/utils/__tests__/session-usage-history.test.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,10 @@ import {
1616
recordSessionUsageReading,
1717
type SessionUsageHistoryDeps
1818
} from '../session-usage-history';
19-
import { getUsageFetchedAtMs } from '../usage';
19+
import {
20+
getUsageFetchedAtMs,
21+
getUsageLoginFingerprint
22+
} from '../usage';
2023

2124
const CACHE_PATH = '/cache/ccstatusline/session-usage-history.json';
2225
const LOCK_PATH = `${CACHE_PATH}.lock`;
@@ -572,6 +575,10 @@ describe('getDefaultSessionUsageHistoryDeps', () => {
572575
expect(getDefaultSessionUsageHistoryDeps().percentSeenAt).toBe(getUsageFetchedAtMs);
573576
});
574577

578+
it('tells logins apart by the usage credentials', () => {
579+
expect(getDefaultSessionUsageHistoryDeps().loginFingerprint).toBe(getUsageLoginFingerprint);
580+
});
581+
575582
// The payload's percent is still from a response: one before this
576583
// transcript began, as after /clear
577584
it('finds no time for a payload\'s percent without a response in its transcript', () => {

‎src/utils/__tests__/usage-token.test.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import * as claudeSettings from '../claude-settings';
1616
import {
1717
getMacKeychainConfigDirService,
1818
getUsageCredentials,
19+
getUsageLoginFingerprint,
1920
getUsageToken,
2021
parseMacKeychainCredentialCandidates
2122
} from '../usage-fetch';
@@ -328,6 +329,33 @@ describe('getUsageToken', () => {
328329
});
329330
});
330331

332+
describe('getUsageLoginFingerprint', () => {
333+
beforeEach(() => {
334+
vi.restoreAllMocks();
335+
vi.spyOn(claudeSettings, 'getClaudeConfigDir').mockReturnValue('/fake/claude');
336+
vi.spyOn(process, 'platform', 'get').mockReturnValue('linux');
337+
});
338+
339+
afterEach(() => {
340+
vi.restoreAllMocks();
341+
});
342+
343+
// Claude Code reissues the access token every few hours; /login brings a
344+
// new refresh token
345+
it('stays the same across an access-token refresh, and changes with the login', () => {
346+
mockCredentialsFile(makeTokenPayload('access-1', 'refresh-1'));
347+
const login = getUsageLoginFingerprint();
348+
mockCredentialsFile(makeTokenPayload('access-2', 'refresh-1'));
349+
const refreshed = getUsageLoginFingerprint();
350+
mockCredentialsFile(makeTokenPayload('access-3', 'refresh-2'));
351+
const otherLogin = getUsageLoginFingerprint();
352+
353+
expect(login).toBe(createHash('sha256').update('refresh-1').digest('hex').slice(0, 16));
354+
expect(refreshed).toBe(login);
355+
expect(otherLogin).not.toBe(login);
356+
});
357+
});
358+
331359
describe('getMacKeychainConfigDirService', () => {
332360
it('returns null for the default profile', () => {
333361
expect(getMacKeychainConfigDirService()).toBeNull();

‎src/utils/session-forecast-prefetch.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,9 @@ const SESSION_FORECAST_WIDGET_TYPES = new Set(['block-forecast', 'block-limit-ti
1515
/**
1616
* Records this render's session percent and forecasts the 5-hour window, once
1717
* per status line, for Block Forecast and Block Limit Timer to read. Each
18-
* Claude config directory keeps its own history: its account has its own window.
18+
* Claude config directory keeps its own history: its account has its own
19+
* window. So does each login within it: after /login to another account, that
20+
* account's window can reset at the very moment the last one's does.
1921
*/
2022
export function computeSessionForecastIfNeeded(
2123
lines: WidgetItem[][],
@@ -34,6 +36,8 @@ export function computeSessionForecastIfNeeded(
3436
}
3537

3638
const clampedPercent = Math.max(0, Math.min(100, percent));
37-
const readings = recordSessionUsageReading(getClaudeConfigDir(), resetAtMs, clampedPercent, deps);
39+
const login = deps.loginFingerprint?.() ?? null;
40+
const profileKey = login === null ? getClaudeConfigDir() : `${getClaudeConfigDir()}#${login}`;
41+
const readings = recordSessionUsageReading(profileKey, resetAtMs, clampedPercent, deps);
3842
return forecastSessionUsage({ readings, nowMs, resetAtMs, percent: clampedPercent });
3943
}

‎src/utils/session-usage-history.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,10 @@ import {
1313
LOOKBACK_MS,
1414
type SessionUsageReading
1515
} from './session-forecast';
16-
import { getUsageFetchedAtMs } from './usage';
16+
import {
17+
getUsageFetchedAtMs,
18+
getUsageLoginFingerprint
19+
} from './usage';
1720

1821
const HISTORY_SCHEMA_VERSION = 1 as const;
1922
// One window's reset time jitters by under a second between sources (the API
@@ -61,6 +64,9 @@ export interface SessionUsageHistoryDeps {
6164
// usage API's can come from its cache. Undefined when nothing shows when
6265
// that was. Left out, the percent is current.
6366
percentSeenAt?: () => number | undefined;
67+
// The login the percent belongs to (see getUsageLoginFingerprint), or null
68+
// when none is found. Left out, the history goes by config directory alone.
69+
loginFingerprint?: () => string | null;
6470
cachePath: string;
6571
}
6672

@@ -115,6 +121,7 @@ export function getDefaultSessionUsageHistoryDeps(payload?: StatusJSON): Session
115121
mkdirSync: (p: string) => { fs.mkdirSync(p, { recursive: true }); },
116122
now: () => Date.now(),
117123
percentSeenAt: isPayloadPercent ? () => getLastResponseAtMs(payload.transcript_path) : getUsageFetchedAtMs,
124+
loginFingerprint: getUsageLoginFingerprint,
118125
cachePath: path.join(os.homedir(), '.cache', 'ccstatusline', 'session-usage-history.json')
119126
};
120127
}

‎src/utils/usage-fetch.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -677,6 +677,16 @@ function getUsageCredentialsWithBackoff(now: number): UsageCredentials | null {
677677
return credentials;
678678
}
679679

680+
/**
681+
* The login whose usage the status line shows: the usage cache's fingerprint
682+
* of it (see getUsageCacheIdentity), or null with no OAuth login found. It
683+
* stays the same across access-token refreshes, and changes with /login.
684+
*/
685+
export function getUsageLoginFingerprint(): string | null {
686+
const credentials = getUsageCredentialsWithBackoff(Math.floor(Date.now() / 1000));
687+
return credentials ? getUsageCacheIdentity(credentials).preferredHash : null;
688+
}
689+
680690
function readStaleUsageCache(cacheIdentity: UsageCacheIdentity | null): { data: UsageData; fetchedAtMs: number } | null {
681691
try {
682692
const fetchedAtMs = fs.statSync(CACHE_FILE).mtimeMs;

‎src/utils/usage.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
export {
22
fetchUsageData,
3-
getUsageFetchedAtMs
3+
getUsageFetchedAtMs,
4+
getUsageLoginFingerprint
45
} from './usage-fetch';
56
export {
67
formatUsageDuration,

0 commit comments

Comments
 (0)