From aa5310b494a797f1862fffb46d0bac03972f3957 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:14:26 -0500 Subject: [PATCH] fix: the Claude usage calendar no longer goes blank at startup For a few seconds after every server start the Local token activity calendar was empty until the first Claude status check finished. The pending snapshot seeded from the saved status dropped the calendar on purpose, and the registry then replaced the saved status with it, since the pending sign-in is unknown. The pending snapshot now carries the saved calendar, also when the saved reading has no meter windows and for API-key sign-ins (which read the calendar but have no meters). A verified check whose calendar read came back partial keeps the last calendar. An account folder that shares the main history reads no calendar, so it carries none over. The composer's usage popover no longer shows an empty "Claude usage" heading when the only usage is a token calendar, which it doesn't draw. --- .../src/provider/Drivers/ClaudeDriver.ts | 11 ++- .../src/provider/Layers/ClaudeProvider.ts | 65 ++++++++++--- .../server/src/provider/Layers/ClaudeUsage.ts | 5 +- .../provider/Layers/ProviderRegistry.test.ts | 94 +++++++++++++++++++ .../chat/ContextWindowMeter.browser.tsx | 23 +++++ .../components/chat/ContextWindowMeter.tsx | 12 ++- 6 files changed, 192 insertions(+), 18 deletions(-) diff --git a/apps/server/src/provider/Drivers/ClaudeDriver.ts b/apps/server/src/provider/Drivers/ClaudeDriver.ts index 2e71b0ba4..099eebc0d 100644 --- a/apps/server/src/provider/Drivers/ClaudeDriver.ts +++ b/apps/server/src/provider/Drivers/ClaudeDriver.ts @@ -471,10 +471,17 @@ export const ClaudeDriver: ProviderDriver = { initialSnapshot: (settings) => makePendingClaudeProvider(settings, processEnv).pipe( Effect.map(stampIdentity), - Effect.map((pending) => seedClaudeProviderUsage(pending, cachedSnapshot)), + Effect.map((pending) => + seedClaudeProviderUsage(pending, cachedSnapshot, { + keepsTokenCalendar: readTokenUsage !== undefined, + }), + ), ), checkProvider, - reconcileSnapshot: carryClaudeUsageAcrossChecks, + reconcileSnapshot: (previous, next) => + carryClaudeUsageAcrossChecks(previous, next, { + keepsTokenCalendar: readTokenUsage !== undefined, + }), // Only the advisory is this enrichment's to write. Usage and chat // sign-in may have been patched since it started from `snapshot`. enrichSnapshot: ({ snapshot, updateSnapshot }) => diff --git a/apps/server/src/provider/Layers/ClaudeProvider.ts b/apps/server/src/provider/Layers/ClaudeProvider.ts index 5c1cdf0fd..90735da4a 100644 --- a/apps/server/src/provider/Layers/ClaudeProvider.ts +++ b/apps/server/src/provider/Layers/ClaudeProvider.ts @@ -8,6 +8,7 @@ import { RUNTIME_MODES, type ServerProvider, type ServerProviderAccountTokenUsage, + type ServerProviderAccountUsage, type ServerProviderAuthCapabilities, type ServerProviderModel, type ServerProviderSignInEnds, @@ -869,6 +870,24 @@ export function claudeChatAndUsageAccountsDiffer(auth: ServerProvider["auth"]): return auth.email !== undefined && auth.usageEmail !== undefined; } +export interface ClaudeUsageCarryOptions { + /** + * Whether this instance reads a local token calendar. An account folder that + * shares the main folder's history reads none (the main instance counts it), + * so a calendar saved before it became one must not carry over. + */ + readonly keepsTokenCalendar?: boolean; +} + +const usageToCarry = ( + usage: ServerProviderAccountUsage | undefined, + options: ClaudeUsageCarryOptions, +): ServerProviderAccountUsage | undefined => { + if (!usage || options.keepsTokenCalendar !== false || !usage.tokenUsage) return usage; + const { tokenUsage: _tokenUsage, ...withoutCalendar } = usage; + return withoutCalendar; +}; + /** * Folds the usage the previous snapshot knew into a freshly checked one, so * one failed check (a rate limit, a slow network, a signed-out normal @@ -885,6 +904,7 @@ export function claudeChatAndUsageAccountsDiffer(auth: ServerProvider["auth"]): export function carryClaudeUsageAcrossChecks( previous: ServerProvider, next: ServerProvider, + options: ClaudeUsageCarryOptions = {}, ): ServerProvider { if (!next.enabled || next.auth.status === "unauthenticated" || next.auth.type === "apiKey") { return next; @@ -892,15 +912,23 @@ export function carryClaudeUsageAcrossChecks( const previousAccount = claudeUsageAccountKey(previous.auth); const nextAccount = claudeUsageAccountKey(next.auth); if (previousAccount && nextAccount && previousAccount !== nextAccount) return next; + const previousUsage = usageToCarry(previous.accountUsage, options); if (next.auth.capabilities?.usage?.status === "verified") { - const accountUsage = preferNewerClaudeUsageReadings(previous.accountUsage, next.accountUsage); + const preferred = preferNewerClaudeUsageReadings(previousUsage, next.accountUsage); + // A check whose calendar read came back partial keeps the last calendar. + const keptTokenUsage = + preferred && !preferred.tokenUsage && previousUsage?.source === preferred.source + ? previousUsage.tokenUsage + : undefined; + const accountUsage = + preferred && keptTokenUsage ? { ...preferred, tokenUsage: keptTokenUsage } : preferred; return accountUsage === next.accountUsage || !accountUsage ? next : { ...next, accountUsage }; } const checkedAtMs = Date.parse(next.checkedAt); const carried = carryClaudeAccountUsageForward( - previous.accountUsage, + previousUsage, Number.isFinite(checkedAtMs) ? checkedAtMs : Date.now(), ); if (!carried) return next; @@ -918,29 +946,40 @@ export function carryClaudeUsageAcrossChecks( /** * The pending snapshot an instance starts from, carrying the usage its last - * run saved to the status cache so a restart does not blank the meters - * before the first check lands. The cached account identity comes along so - * `carryClaudeUsageAcrossChecks` can still tell a changed account. + * run saved to the status cache so a restart does not blank the meters or + * the token calendar before the first check lands. The cached account + * identity comes along so `carryClaudeUsageAcrossChecks` can still tell a + * changed account. */ export function seedClaudeProviderUsage( pending: ServerProvider, cached: ServerProvider | undefined, + options: ClaudeUsageCarryOptions = {}, ): ServerProvider { if ( !cached || !pending.enabled || cached.instanceId !== pending.instanceId || - cached.driver !== pending.driver || - cached.auth.type === "apiKey" + cached.driver !== pending.driver ) { return pending; } - const carried = carryClaudeAccountUsageForward( - cached.accountUsage, - Date.parse(pending.checkedAt), - ); + const savedUsage = usageToCarry(cached.accountUsage, options); + if (cached.auth.type === "apiKey") { + // An API key has no subscription meters, but it still reads the calendar. + if (savedUsage?.source !== "claude-oauth-usage" || !savedUsage.tokenUsage) return pending; + return { + ...pending, + accountUsage: { + source: savedUsage.source, + checkedAt: savedUsage.checkedAt, + limits: [], + tokenUsage: savedUsage.tokenUsage, + }, + }; + } + const carried = carryClaudeAccountUsageForward(savedUsage, Date.parse(pending.checkedAt)); if (!carried) return pending; - const { tokenUsage: _tokenUsage, ...limits } = carried; return { ...pending, auth: { @@ -948,7 +987,7 @@ export function seedClaudeProviderUsage( ...(cached.auth.email ? { email: cached.auth.email } : {}), ...(cached.auth.usageEmail ? { usageEmail: cached.auth.usageEmail } : {}), }, - accountUsage: limits, + accountUsage: carried, }; } diff --git a/apps/server/src/provider/Layers/ClaudeUsage.ts b/apps/server/src/provider/Layers/ClaudeUsage.ts index bb0156f2a..3ab8affbd 100644 --- a/apps/server/src/provider/Layers/ClaudeUsage.ts +++ b/apps/server/src/provider/Layers/ClaudeUsage.ts @@ -288,7 +288,8 @@ function hasUsageWindowReset( * reading, moved forward to `nowMs`. A window whose reset time has passed * starts over: nothing used, and no reset time until it is read again. Each * window keeps the time it was read, so the client can say how old it is. - * `undefined` when there is no window to keep. + * The local token calendar comes along as it was. `undefined` when there is + * neither a window nor a calendar to keep. */ export function carryClaudeAccountUsageForward( previous: ServerProviderAccountUsage | undefined, @@ -328,7 +329,7 @@ export function carryClaudeAccountUsageForward( }, ]; }); - return limits.length > 0 ? { ...previous, limits } : undefined; + return limits.length > 0 || previous.tokenUsage ? { ...previous, limits } : undefined; } function isNewerReading(candidate: string | undefined, than: string | undefined): boolean { diff --git a/apps/server/src/provider/Layers/ProviderRegistry.test.ts b/apps/server/src/provider/Layers/ProviderRegistry.test.ts index cbf8f5f8e..3d42eb1d6 100644 --- a/apps/server/src/provider/Layers/ProviderRegistry.test.ts +++ b/apps/server/src/provider/Layers/ProviderRegistry.test.ts @@ -52,7 +52,9 @@ import { type ClaudeReportedModels, claudeReportedModelsFromCache, type ClaudeReportedModelsStore, + makePendingClaudeProvider, readClaudeNormalAuthEmail, + seedClaudeProviderUsage, stopClaudeCliAfterSignInRenewal, } from "./ClaudeProvider.ts"; import { checkOpenCodeProviderStatus } from "./OpenCodeProvider.ts"; @@ -3982,6 +3984,98 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T ), ); + it.effect("keeps the token calendar on screen from startup through the first check", () => + Effect.gen(function* () { + const identity = { + instanceId: ProviderInstanceId.make("claudeAgent"), + driver: ProviderDriverKind.make("claudeAgent"), + }; + const tokenUsage = { + checkedAt: "2026-06-10T15:00:00.000Z", + scope: "local", + coverageStartDate: "2026-05-12", + coverageEndDate: "2026-06-10", + dailyBuckets: [{ startDate: "2026-06-09", tokens: 4200 }], + summary: { lifetimeTokens: 4200, peakDailyTokens: 4200 }, + } as const; + const check = checkClaudeProviderStatus( + defaultClaudeSettings, + claudeCapabilities(), + { [CLAUDE_CODE_OAUTH_TOKEN_ENV]: "sk-ant-oat01-test" }, + () => Effect.succeed({ _tag: "Unavailable", reason: "unreachable" } as const), + () => Effect.succeed("usage@example.com"), + ).pipe(Effect.map((draft) => ({ ...draft, ...identity }) satisfies ServerProvider)); + // What the last run saved: the calendar, and no subscription meters. + const lastRun = yield* check; + const saved: ServerProvider = { + ...lastRun, + accountUsage: { + source: "claude-oauth-usage", + checkedAt: tokenUsage.checkedAt, + limits: [], + tokenUsage, + }, + }; + + // The server starts: the first snapshot is a pending one seeded from the save. + const pendingDraft = { + ...(yield* makePendingClaudeProvider(defaultClaudeSettings)), + ...identity, + }; + const pending = seedClaudeProviderUsage(pendingDraft, saved); + const atStartup = mergeProviderSnapshot(saved, pending); + assert.deepStrictEqual(atStartup.accountUsage?.tokenUsage, tokenUsage); + + // The first check reads meters but its calendar read came back partial. + const firstCheck = yield* checkClaudeProviderStatus( + defaultClaudeSettings, + claudeCapabilities(), + { [CLAUDE_CODE_OAUTH_TOKEN_ENV]: "sk-ant-oat01-test" }, + () => + Effect.succeed({ + _tag: "Fresh", + usage: { + source: "claude-oauth-usage", + checkedAt: "2026-06-11T09:00:00.000Z", + limits: [], + }, + } as const), + () => Effect.succeed("usage@example.com"), + ).pipe(Effect.map((draft) => ({ ...draft, ...identity }) satisfies ServerProvider)); + const afterCheck = mergeProviderSnapshot( + atStartup, + carryClaudeUsageAcrossChecks(atStartup, firstCheck), + ); + assert.deepStrictEqual(afterCheck.accountUsage?.tokenUsage, tokenUsage); + + // An API key reads the calendar too, so its restart keeps it. + const onApiKey = { ...saved, auth: { ...saved.auth, type: "apiKey" } }; + assert.deepStrictEqual( + seedClaudeProviderUsage(pendingDraft, onApiKey).accountUsage?.tokenUsage, + tokenUsage, + ); + + // An account folder that shares the main history reads no calendar, so + // one saved before it became one doesn't carry over. + const noCalendar = { keepsTokenCalendar: false } as const; + const sharedPending = seedClaudeProviderUsage(pendingDraft, saved, noCalendar); + assert.strictEqual(sharedPending.accountUsage?.tokenUsage, undefined); + assert.strictEqual( + carryClaudeUsageAcrossChecks(atStartup, firstCheck, noCalendar).accountUsage + ?.tokenUsage, + undefined, + ); + }).pipe( + Effect.provide( + mockSpawnerLayer((args) => { + const joined = args.join(" "); + if (joined === "--version") return { stdout: "2.1.289\n", stderr: "", code: 0 }; + throw new Error(`Unexpected args: ${joined}`); + }), + ), + ), + ); + it.effect("does not run claude auth status while a sign-in renewal is due", () => Effect.gen(function* () { const commands: string[] = []; diff --git a/apps/web/src/components/chat/ContextWindowMeter.browser.tsx b/apps/web/src/components/chat/ContextWindowMeter.browser.tsx index 052380c6e..e84b1f1d9 100644 --- a/apps/web/src/components/chat/ContextWindowMeter.browser.tsx +++ b/apps/web/src/components/chat/ContextWindowMeter.browser.tsx @@ -113,6 +113,29 @@ describe("ContextWindowMeter", () => { } }); + it("leaves out a usage section that would only hold a token calendar", async () => { + const { tokenUsage } = TEST_ACCOUNT_USAGE; + const screen = await render( + , + ); + + try { + await page.getByRole("button", { name: /Context window/ }).click(); + await expect.element(page.getByText(/context used/)).toBeVisible(); + await expect.element(page.getByText("Claude usage")).not.toBeInTheDocument(); + } finally { + await screen.unmount(); + } + }); + it("marks the pace on a usage bar and opens the Usage page from its row", async () => { const openUsage = vi.fn(); const screen = await render( diff --git a/apps/web/src/components/chat/ContextWindowMeter.tsx b/apps/web/src/components/chat/ContextWindowMeter.tsx index 26719cc88..71c0c644e 100644 --- a/apps/web/src/components/chat/ContextWindowMeter.tsx +++ b/apps/web/src/components/chat/ContextWindowMeter.tsx @@ -198,7 +198,17 @@ export function ContextWindowMeter(props: { const [isPinnedOpen, setIsPinnedOpen] = useState(false); const [isHoverOpenSuppressed, setIsHoverOpenSuppressed] = useState(false); const [isBreakdownOpen, setIsBreakdownOpen] = useState(false); - const accountUsage = props.accountUsage ?? null; + // The popover draws no calendar, so usage that is only a token calendar + // (an API key, or a restart before the first check) has nothing to show. + const accountUsage = + props.accountUsage && + (props.accountUsage.windows.length > 0 || + props.accountUsage.notice || + props.accountUsage.spendControl || + props.accountUsage.resetCredits || + props.accountUsage.externalResets) + ? props.accountUsage + : null; const breakdownSegments = buildContextBreakdownSegments(usage); const hasContextCategories = (usage?.contextCategories?.length ?? 0) > 0; const cachedInputRate = deriveCachedInputRate(usage);