Skip to content

Commit 79f2bae

Browse files
jieyuexingcodexjuliusmarminge
authored
fix(server): show zero-use Grok billing periods (#17061)
Co-authored-by: Codex (gpt-6.1-sol) <[email protected]> Co-authored-by: Julius Marminge <[email protected]>
1 parent 475e019 commit 79f2bae

2 files changed

Lines changed: 136 additions & 8 deletions

File tree

‎apps/server/src/provider/GrokProvider.test.ts‎

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -580,6 +580,63 @@ it.layer(NodeServices.layer)("checkGrokProviderStatus", (it) => {
580580

581581
describe("Grok usage limits", () => {
582582
const checkedAt = "2026-09-16T00:00:00.000Z";
583+
const weeklyPeriod = {
584+
type: "USAGE_PERIOD_TYPE_WEEKLY",
585+
start: "2026-09-11T03:10:30.159171+00:00",
586+
end: "2026-09-18T03:10:30.159171+00:00",
587+
};
588+
589+
it("shows zero usage for complete weekly and monthly periods with no percentage", () => {
590+
for (const [currentPeriod, kind, label, resetsAt] of [
591+
[weeklyPeriod, "weekly", "Weekly", "2026-09-18T03:10:30.159Z"],
592+
[
593+
{
594+
type: "USAGE_PERIOD_TYPE_MONTHLY",
595+
start: "2026-09-01T00:00:00.000Z",
596+
end: "2026-10-01T00:00:00.000Z",
597+
},
598+
"monthly",
599+
"Monthly",
600+
"2026-10-01T00:00:00.000Z",
601+
],
602+
] as const) {
603+
const response = { config: { currentPeriod } };
604+
expect
605+
.soft(grokUsageResponseToLimits(response, checkedAt).windows)
606+
.toEqual([{ id: "subscription", kind, label, usedPercent: 0, resetsAt }]);
607+
}
608+
});
609+
610+
it("keeps incomplete, invalid, unordered, and unknown periods unreported", () => {
611+
for (const currentPeriod of [
612+
undefined,
613+
{ ...weeklyPeriod, type: undefined },
614+
{ ...weeklyPeriod, type: "USAGE_PERIOD_TYPE_DAILY" },
615+
{ ...weeklyPeriod, start: undefined },
616+
{ ...weeklyPeriod, end: undefined },
617+
{ ...weeklyPeriod, start: "invalid" },
618+
{ ...weeklyPeriod, end: "invalid" },
619+
{ ...weeklyPeriod, start: weeklyPeriod.end },
620+
{ ...weeklyPeriod, start: weeklyPeriod.end, end: weeklyPeriod.start },
621+
]) {
622+
const response = { config: { currentPeriod } };
623+
expect
624+
.soft(grokUsageResponseToLimits(response, checkedAt).windows, JSON.stringify(response))
625+
.toEqual([]);
626+
}
627+
});
628+
629+
it("rejects impossible calendar dates at either period boundary", () => {
630+
for (const [start, end] of [
631+
["2026-02-30T00:00:00.000Z", "2026-03-09T00:00:00.000Z"],
632+
["2026-02-23T00:00:00.000Z", "2026-02-30T00:00:00.000Z"],
633+
]) {
634+
const response = { config: { currentPeriod: { ...weeklyPeriod, start, end } } };
635+
expect
636+
.soft(grokUsageResponseToLimits(response, checkedAt).windows, JSON.stringify(response))
637+
.toEqual([]);
638+
}
639+
});
583640

584641
it("uses the reported subscription percentage and weekly reset", () => {
585642
const limits = grokUsageResponseToLimits(
@@ -693,6 +750,50 @@ it.layer(NodeServices.layer)("readGrokAccount", (it) => {
693750
),
694751
);
695752

753+
it.effect("ignores malformed period starts without inventing usage", () =>
754+
Effect.gen(function* () {
755+
for (const start of [null, 42]) {
756+
for (const creditUsagePercent of [37.5, undefined]) {
757+
const response = {
758+
config: {
759+
creditUsagePercent,
760+
currentPeriod: {
761+
type: "USAGE_PERIOD_TYPE_WEEKLY",
762+
start,
763+
end: "2026-09-18T03:10:30.159171+00:00",
764+
},
765+
},
766+
};
767+
const { usageLimits } = yield* readGrokAccount({
768+
HOME: "/definitely/not/a/grok-home",
769+
GROK_AUTH: '{"https://accounts.x.ai/sign-in":{"key":"session-token"}}',
770+
}).pipe(
771+
Effect.provideService(
772+
HttpClient.HttpClient,
773+
HttpClient.make((request) =>
774+
Effect.succeed(HttpClientResponse.fromWeb(request, Response.json(response))),
775+
),
776+
),
777+
);
778+
expect.soft(usageLimits.unavailable, JSON.stringify(response)).toBeUndefined();
779+
expect.soft(usageLimits.windows, JSON.stringify(response)).toEqual(
780+
creditUsagePercent === undefined
781+
? []
782+
: [
783+
{
784+
id: "subscription",
785+
kind: "weekly",
786+
label: "Weekly",
787+
usedPercent: creditUsagePercent,
788+
resetsAt: "2026-09-18T03:10:30.159Z",
789+
},
790+
],
791+
);
792+
}
793+
}
794+
}),
795+
);
796+
696797
it.effect("does not use unrelated scopes, API keys, or custom auth deployments", () =>
697798
Effect.gen(function* () {
698799
for (const environment of [

‎packages/provider-grok/src/server/usageLimits.ts‎

Lines changed: 35 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -31,28 +31,55 @@ const GrokUsageResponse = Schema.Struct({
3131
currentPeriod: Schema.optional(
3232
Schema.Struct({
3333
type: Schema.optional(Schema.String),
34+
start: Schema.optional(Schema.Unknown),
3435
end: Schema.optional(Schema.String),
3536
}),
3637
),
3738
}),
3839
),
3940
});
4041

42+
function parsePeriodBoundary(value: string | undefined) {
43+
if (
44+
!value ||
45+
value !== value.trim() ||
46+
!/^(?:\d{4}|[+-]\d{6})-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?|24:00(?::00(?:\.0+)?)?)(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/.test(
47+
value,
48+
)
49+
) {
50+
return Number.NaN;
51+
}
52+
// Date parsing can normalize impossible calendar dates instead of rejecting them.
53+
const datePart = value.slice(0, value.indexOf("T"));
54+
const date = DateTime.make(`${datePart}T00:00:00.000Z`);
55+
if (Option.isNone(date)) return Number.NaN;
56+
const parts = DateTime.toPartsUtc(date.value);
57+
if (parts.month !== Number(datePart.slice(-5, -3)) || parts.day !== Number(datePart.slice(-2))) {
58+
return Number.NaN;
59+
}
60+
return Date.parse(value);
61+
}
62+
4163
export function grokUsageResponseToLimits(
4264
response: typeof GrokUsageResponse.Type,
4365
checkedAt: string,
4466
) {
45-
const usedPercent = response.config?.creditUsagePercent;
46-
if (usedPercent === undefined || !Number.isFinite(usedPercent)) {
47-
// A billing read that succeeded but carries no percentage is an account
48-
// with nothing metered yet, not one that can never report: xAI omits the
49-
// field entirely (rather than sending 0) until usage registers, then fills
50-
// it in.
51-
return makeUsageLimits({ checkedAt, windows: [] });
52-
}
5367
const period = response.config?.currentPeriod;
5468
const periodType = period?.type?.replace(/^USAGE_PERIOD_TYPE_/, "");
5569
const kind = periodType === "WEEKLY" ? "weekly" : periodType === "MONTHLY" ? "monthly" : "other";
70+
let usedPercent = response.config?.creditUsagePercent;
71+
if (
72+
usedPercent === undefined &&
73+
(kind === "weekly" || kind === "monthly") &&
74+
typeof period?.start === "string" &&
75+
parsePeriodBoundary(period?.start) < parsePeriodBoundary(period?.end)
76+
) {
77+
// Grok omits a zero percentage while retaining the complete subscription period.
78+
usedPercent = 0;
79+
}
80+
if (usedPercent === undefined || !Number.isFinite(usedPercent)) {
81+
return makeUsageLimits({ checkedAt, windows: [] });
82+
}
5683
const reset = period?.end ? DateTime.make(period.end) : Option.none();
5784
const window: ServerProviderUsageWindow = {
5885
id: "subscription",

0 commit comments

Comments
 (0)