Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
11 changes: 9 additions & 2 deletions apps/server/src/provider/Drivers/ClaudeDriver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -471,10 +471,17 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
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 }) =>
Expand Down
65 changes: 52 additions & 13 deletions apps/server/src/provider/Layers/ClaudeProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
RUNTIME_MODES,
type ServerProvider,
type ServerProviderAccountTokenUsage,
type ServerProviderAccountUsage,
type ServerProviderAuthCapabilities,
type ServerProviderModel,
type ServerProviderSignInEnds,
Expand Down Expand Up @@ -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
Expand All @@ -885,22 +904,31 @@ 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;
}
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;
Expand All @@ -918,37 +946,48 @@ 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: {
...pending.auth,
...(cached.auth.email ? { email: cached.auth.email } : {}),
...(cached.auth.usageEmail ? { usageEmail: cached.auth.usageEmail } : {}),
},
accountUsage: limits,
accountUsage: carried,
};
}

Expand Down
5 changes: 3 additions & 2 deletions apps/server/src/provider/Layers/ClaudeUsage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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 {
Expand Down
94 changes: 94 additions & 0 deletions apps/server/src/provider/Layers/ProviderRegistry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,9 @@ import {
type ClaudeReportedModels,
claudeReportedModelsFromCache,
type ClaudeReportedModelsStore,
makePendingClaudeProvider,
readClaudeNormalAuthEmail,
seedClaudeProviderUsage,
stopClaudeCliAfterSignInRenewal,
} from "./ClaudeProvider.ts";
import { checkOpenCodeProviderStatus } from "./OpenCodeProvider.ts";
Expand Down Expand Up @@ -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[] = [];
Expand Down
23 changes: 23 additions & 0 deletions apps/web/src/components/chat/ContextWindowMeter.browser.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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(
<ContextWindowMeter
usage={TEST_CONTEXT_WINDOW}
accountUsage={{
label: "Claude usage",
reachedLimit: false,
windows: [],
...(tokenUsage ? { tokenUsage } : {}),
}}
/>,
);

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(
Expand Down
12 changes: 11 additions & 1 deletion apps/web/src/components/chat/ContextWindowMeter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Loading