TypeScript
fix(claude): map monthly account spending limits (#19433)
James Cfd8dd51654f8
diff --git a/apps/server/src/provider/claudeUsageLimits.test.ts b/apps/server/src/provider/claudeUsageLimits.test.tsindex 99c3eb163f1..ac47781a896 100644--- a/apps/server/src/provider/claudeUsageLimits.test.ts+++ b/apps/server/src/provider/claudeUsageLimits.test.ts@@ -126,6 +126,121 @@ describe("claudeUsageResponseToLimits", () => {},]);});++ const enterpriseResponse = {+ rate_limits_available: true,+ rate_limits: {+ five_hour: null,+ seven_day: null,+ spend: {+ enabled: true,+ used: { amount_minor: 4_631, currency: "USD", exponent: 2 },+ limit: { amount_minor: 50_000, currency: "USD", exponent: 2 },+ percent: 9,+ },+ extra_usage: {+ is_enabled: true,+ used_credits: 4_631,+ monthly_limit: 50_000,+ utilization: 9.261999999999999,+ currency: "USD",+ decimal_places: 2,+ },+ },+ };+ const monthlyWindow = {+ id: "monthly_spend",+ kind: "monthly",+ label: "Monthly spend",+ usedPercent: expect.closeTo(9.262, 10),+ };++ it("maps the captured Enterprise budget precisely, preferring spend beside rolling windows", () => {+ expect(claudeUsageResponseToLimits({ checkedAt, response: enterpriseResponse }).limits).toEqual(+ {+ checkedAt,+ windows: [monthlyWindow],+ },+ );+ const response = {+ ...enterpriseResponse,+ rate_limits: {+ ...enterpriseResponse.rate_limits,+ five_hour: { utilization: 12, resets_at: null },+ extra_usage: {+ ...enterpriseResponse.rate_limits.extra_usage,+ used_credits: 30_000,+ utilization: 60,+ },+ },+ };+ expect(claudeUsageResponseToLimits({ checkedAt, response }).limits.windows).toEqual([+ {+ id: "five_hour",+ kind: "session",+ label: "Session",+ usedPercent: 12,+ windowDurationMins: 300,+ },+ monthlyWindow,+ ]);+ });++ it("falls back to enabled extra usage amounts or utilization when spend is unusable", () => {+ const response = {+ ...enterpriseResponse,+ rate_limits: {+ ...enterpriseResponse.rate_limits,+ spend: {+ ...enterpriseResponse.rate_limits.spend,+ enabled: false,+ used: { amount_minor: 30_000, currency: "USD", exponent: 2 },+ },+ extra_usage: { ...enterpriseResponse.rate_limits.extra_usage, utilization: 9 },+ },+ };+ expect(claudeUsageResponseToLimits({ checkedAt, response }).limits.windows).toEqual([+ monthlyWindow,+ ]);+ const utilizationOnly = {+ ...response,+ rate_limits: {+ ...response.rate_limits,+ spend: { enabled: true, used: null, limit: null, percent: 9 },+ extra_usage: {+ ...enterpriseResponse.rate_limits.extra_usage,+ used_credits: null,+ monthly_limit: null,+ },+ },+ };+ expect(+ claudeUsageResponseToLimits({ checkedAt, response: utilizationOnly }).limits.windows,+ ).toEqual([monthlyWindow]);+ });++ it("omits disabled budgets and refuses invalid money without an enabled fallback", () => {+ const rateLimits = enterpriseResponse.rate_limits;+ const response = {+ ...enterpriseResponse,+ rate_limits: {+ ...rateLimits,+ spend: { ...rateLimits.spend, enabled: false },+ extra_usage: { ...rateLimits.extra_usage, is_enabled: false },+ },+ };+ expect(claudeUsageResponseToLimits({ checkedAt, response }).limits.windows).toEqual([]);+ response.rate_limits.spend = {+ ...rateLimits.spend,+ limit: { ...rateLimits.spend.limit, currency: "EUR" },+ };+ expect(claudeUsageResponseToLimits({ checkedAt, response }).limits.windows).toEqual([]);+ response.rate_limits.spend = {+ ...rateLimits.spend,+ limit: { ...rateLimits.spend.limit, amount_minor: 0 },+ };+ expect(claudeUsageResponseToLimits({ checkedAt, response }).limits.windows).toEqual([]);+ });});describe("claudeRateLimitEventToUpdate", () => {diff --git a/apps/server/src/provider/claudeUsageLimits.ts b/apps/server/src/provider/claudeUsageLimits.tsindex de6379090e6..e41dac250ac 100644--- a/apps/server/src/provider/claudeUsageLimits.ts+++ b/apps/server/src/provider/claudeUsageLimits.ts@@ -8,6 +8,7 @@ import * as DateTime from "effect/DateTime";import * as Effect from "effect/Effect";import * as Option from "effect/Option";import * as Ref from "effect/Ref";+import * as Schema from "effect/Schema";import {clampPercent,@@ -34,6 +35,16 @@ const WINDOWS: Readonly<*/const OVERAGE_INCLUDED_EVENT_TYPE = "seven_day_overage_included";+// The SDK does not yet type the spend budget returned by `get_usage`.+const SpendMoney = Schema.Struct({+ amount_minor: Schema.Natural,+ currency: Schema.NonEmptyString,+ exponent: Schema.Natural,+});+const decodeSpendBudget = Schema.decodeUnknownOption(+ Schema.Struct({ enabled: Schema.Boolean, used: SpendMoney, limit: SpendMoney }),+);+export interface ClaudeScopedLimitNames {readonly overageIncluded: string | undefined;}@@ -61,6 +72,44 @@ function scopedWindow(};}+function percentFromAmounts(used: number | null | undefined, limit: number | null | undefined) {+ if (+ typeof used !== "number" ||+ typeof limit !== "number" ||+ !Number.isFinite(used) ||+ !Number.isFinite(limit) ||+ used < 0 ||+ limit <= 0+ ) {+ return undefined;+ }+ const percent = (used / limit) * 100;+ return Number.isFinite(percent) ? clampPercent(percent) : undefined;+}++function readSpendPercent(rateLimits: NonNullable<SDKControlGetUsageResponse["rate_limits"]>) {+ const spend = Option.getOrUndefined(+ decodeSpendBudget((rateLimits as { readonly spend?: unknown }).spend),+ );+ // Minor-unit ratios require matching currency and scale; spend.percent is rounded.+ if (+ spend?.enabled &&+ spend.used.currency.trim().length > 0 &&+ spend.used.currency.trim() === spend.limit.currency.trim() &&+ spend.used.exponent === spend.limit.exponent+ ) {+ const percent = percentFromAmounts(spend.used.amount_minor, spend.limit.amount_minor);+ if (percent !== undefined) return percent;+ }++ const extra = rateLimits.extra_usage;+ if (extra?.is_enabled !== true) return undefined;+ const percent = percentFromAmounts(extra.used_credits, extra.monthly_limit) ?? extra.utilization;+ return typeof percent === "number" && Number.isFinite(percent) && percent >= 0+ ? clampPercent(percent)+ : undefined;+}+/*** `model_scoped` shipped in the CLI after the SDK typings we pin, so it is* read structurally until the `.d.ts` catches up.@@ -165,6 +214,15 @@ export function claudeUsageResponseToLimits(input: {);overageIncluded ??= entry.display_name;}+ const spendPercent = readSpendPercent(response.rate_limits);+ if (spendPercent !== undefined) {+ windows.push({+ id: "monthly_spend",+ kind: "monthly",+ label: "Monthly spend",+ usedPercent: spendPercent,+ });+ }return {limits: makeUsageLimits({ checkedAt, windows }),names: { overageIncluded },