Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

feat(antigravity): show the Google account's 5-hour and weekly limits (#6091)

Milind Soni28ccfc177d38
diff --git a/NOTICE b/NOTICE
index d800e9f9fd..11a9d37c13 100644
--- a/NOTICE
+++ b/NOTICE
@@ -6,8 +6,8 @@ Version 2.0, with the consent of all contributors whose copyright was
incorporated before the transition.
The Google Antigravity ACP integration adapts release, installation, profile,
-authentication, sign-out, session setup, client name, turn-outcome, and
-runtime temporary-folder behavior from T3 Code, Copyright 2026 T3 Tools Inc., used under the MIT License
+authentication, sign-out, session setup, client name, turn-outcome,
+usage-limit, and runtime temporary-folder behavior from T3 Code, Copyright 2026 T3 Tools Inc., used under the MIT License
(third_party/t3-code/LICENSE).
Selected-text citation matching adapts T3 Code's assistant citation selection,
diff --git a/server/drivers/antigravity-account.ts b/server/drivers/antigravity-account.ts
index 8ea85a4edb..96fe23f519 100644
--- a/server/drivers/antigravity-account.ts
+++ b/server/drivers/antigravity-account.ts
@@ -30,19 +30,35 @@ export async function antigravityAccount(tokenPath: string): Promise<Identity> {
}
}
-async function lookup(credentials: { client_id: string; client_secret: string; refresh_token: string }): Promise<Identity> {
+export interface AntigravityStoredSignIn { client_id: string; client_secret: string; refresh_token: string }
+type AccessFetch = (url: string, init: { method?: "POST"; headers?: Record<string, string>; body?: string | URLSearchParams; redirect: "error" | "manual"; signal: AbortSignal }) => Promise<Pick<Response, "ok" | "json">>;
+
+/** A short-lived access token for the stored sign-in, from Google only. The token stays in memory: it is never logged,
+ * written or returned to a client. Undefined when Google refuses or cannot be reached. */
+export async function refreshAntigravityAccess(
+ credentials: AntigravityStoredSignIn,
+ signal: AbortSignal,
+ fetchImpl: AccessFetch = fetch,
+ redirect: "error" | "manual" = "error",
+): Promise<{ accessToken: string; expiresInSeconds: number | null } | undefined> {
+ const response = await fetchImpl("https://oauth2.googleapis.com/token", {
+ method: "POST", redirect, signal,
+ body: new URLSearchParams({ grant_type: "refresh_token", client_id: credentials.client_id,
+ client_secret: credentials.client_secret, refresh_token: credentials.refresh_token }),
+ });
+ if (!response.ok) return undefined;
+ const token = await response.json() as { access_token?: unknown; expires_in?: unknown };
+ if (typeof token.access_token !== "string" || !token.access_token) return undefined;
+ return { accessToken: token.access_token, expiresInSeconds: typeof token.expires_in === "number" && token.expires_in > 0 ? token.expires_in : null };
+}
+
+async function lookup(credentials: AntigravityStoredSignIn): Promise<Identity> {
try {
const signal = AbortSignal.timeout(3_000);
- const response = await fetch("https://oauth2.googleapis.com/token", {
- method: "POST", redirect: "error", signal,
- body: new URLSearchParams({ grant_type: "refresh_token", client_id: credentials.client_id,
- client_secret: credentials.client_secret, refresh_token: credentials.refresh_token }),
- });
- if (!response.ok) return undefined;
- const token = await response.json() as { access_token?: unknown };
- if (typeof token.access_token !== "string" || !token.access_token) return undefined;
+ const access = await refreshAntigravityAccess(credentials, signal);
+ if (!access) return undefined;
const identity = await fetch("https://www.googleapis.com/oauth2/v3/userinfo", {
- headers: { Authorization: `Bearer ${token.access_token}` }, redirect: "error", signal,
+ headers: { Authorization: `Bearer ${access.accessToken}` }, redirect: "error", signal,
});
if (!identity.ok) return undefined;
const user = await identity.json() as { email?: unknown };
diff --git a/server/drivers/antigravity-usage-limits.test.ts b/server/drivers/antigravity-usage-limits.test.ts
new file mode 100644
index 0000000000..68b0ccf658
--- /dev/null
+++ b/server/drivers/antigravity-usage-limits.test.ts
@@ -0,0 +1,400 @@
+// Adapted from pingdotgg/t3code@b732621b51, MIT License, Copyright (c) 2026
+// T3 Tools Inc. (full text in third_party/t3-code/LICENSE); modified:
+// - apps/server/src/provider/antigravityUsageLimits.test.ts (the quota
+// fixtures and the cases of the limits reader).
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { clearPlanUsageCache, fetchPlanUsage, planAccountsFromInstances, type PlanFetch } from "../plan-usage.ts";
+import { removeTempDir } from "../testing/cleanup.ts";
+import { antigravityTokenPath } from "./antigravity-acp.ts";
+import {
+ antigravityPlanUsage,
+ antigravityPlanWindows,
+ clearAntigravityUsageAccess,
+ readAntigravityUsageWindows,
+} from "./antigravity-usage-limits.ts";
+
+const summary = {
+ groups: [
+ {
+ displayName: "Gemini Models",
+ buckets: [
+ { bucketId: "gemini-weekly", window: "weekly", remainingFraction: 0.96, resetTime: "2026-10-12T19:41:43Z" },
+ { bucketId: "gemini-5h", window: "5h", remainingFraction: 0.91, resetTime: "2026-10-09T16:06:01Z" },
+ ],
+ },
+ {
+ displayName: "Claude and GPT models",
+ buckets: [
+ { bucketId: "3p-weekly", window: "weekly", remainingFraction: 0, resetTime: "2026-10-10T15:28:22Z" },
+ { bucketId: "3p-5h", window: "5h", remainingFraction: 0.44, resetTime: "2026-10-09T16:06:30Z" },
+ ],
+ },
+ ],
+};
+
+const scratch: string[] = [];
+
+interface FixtureOptions {
+ summary?: unknown;
+ /** Per-host quota summaries; hosts not listed fall back to `summary`. */
+ summaryByHost?: Record<string, unknown>;
+ models?: unknown;
+ summaryStatus?: number;
+ summaryStatusByHost?: Record<string, number>;
+ tokenStatus?: number;
+ /** Requests whose address holds one of these never answer, and ignore their signal. */
+ hangs?: string[];
+ missingToken?: boolean;
+ now?: number;
+ /** The clock after the token refresh answers. */
+ refreshedAt?: number;
+}
+
+function fixture(options: FixtureOptions = {}) {
+ const directory = mkdtempSync(join(tmpdir(), "omb-antigravity-usage-"));
+ scratch.push(directory);
+ mkdirSync(join(directory, "antigravity-acp"));
+ const tokenPath = join(directory, "antigravity-acp", "acp_token.json");
+ const writeToken = (refreshToken: string) => writeFileSync(tokenPath, JSON.stringify({
+ client_id: "client-id", client_secret: "client-secret", refresh_token: refreshToken, project_id: "project-id",
+ }));
+ if (!options.missingToken) writeToken("refresh-a");
+ const requests: Array<{ url: string; body: string }> = [];
+ let clock = options.now ?? Date.parse("2026-10-09T12:00:00Z");
+ const respond = (body: unknown, status = 200) => ({ ok: status >= 200 && status < 300, status, text: async () => JSON.stringify(body) });
+ const fetch: PlanFetch = async (url, init) => {
+ expect(init.redirect).toBe("manual");
+ expect(init.method).toBe("POST");
+ requests.push({ url, body: init.body ?? "" });
+ if (options.hangs?.some((part) => url.includes(part))) return new Promise(() => {});
+ if (url.endsWith("/token")) {
+ expect(new URLSearchParams(init.body).get("grant_type")).toBe("refresh_token");
+ if (options.refreshedAt !== undefined) clock = options.refreshedAt;
+ return respond({ access_token: "access-token", expires_in: 3600 }, options.tokenStatus ?? 200);
+ }
+ expect(init.headers.Authorization).toBe("Bearer access-token");
+ expect(JSON.parse(init.body!)).toEqual({ project: "project-id" });
+ expect(init.headers["User-Agent"]).toMatch(/^antigravity\/hub\/2\.24\.0 /);
+ const host = new URL(url).host;
+ return url.endsWith(":retrieveUserQuotaSummary")
+ ? respond(options.summaryByHost?.[host] ?? options.summary ?? summary, options.summaryStatusByHost?.[host] ?? options.summaryStatus ?? 200)
+ : respond(options.models ?? { models: {} });
+ };
+ const deps = { fetch, now: () => clock };
+ return { deps, requests, writeToken, tokenPath, windows: () => readAntigravityUsageWindows(tokenPath, deps), advance: (ms: number) => { clock += ms; } };
+}
+
+const at = (iso: string) => Date.parse(iso);
+const resets = (windows: Array<{ id: string; resetsAt?: string }>) =>
+ Object.fromEntries(windows.map(({ id, resetsAt }) => [id, resetsAt]));
+
+beforeEach(() => {
+ clearAntigravityUsageAccess();
+ clearPlanUsageCache();
+});
+
+afterEach(async () => {
+ vi.restoreAllMocks();
+ while (scratch.length) await removeTempDir(scratch.pop()!);
+});
+
+describe("Antigravity subscription limits", () => {
+ it("omits rolling resets for untouched summary buckets and keeps used Gemini resets", async () => {
+ const { windows } = fixture({
+ now: at("2026-10-21T10:16:04Z"),
+ summary: {
+ groups: [{
+ buckets: [
+ { bucketId: "3p-5h", window: "5h", remainingFraction: 1, resetTime: "2026-10-21T15:16:05Z" },
+ { bucketId: "3p-weekly", window: "weekly", remainingFraction: 1, resetTime: "2026-10-28T10:16:05Z" },
+ { bucketId: "gemini-5h", window: "5h", remainingFraction: 0.848104, resetTime: "2026-10-21T13:29:53Z",
+ description: "You have used some of your 5-hour limit, it will fully refresh in 3 hours, 13 minutes." },
+ { bucketId: "gemini-weekly", window: "weekly", remainingFraction: 0.9620177, resetTime: "2026-10-28T08:29:53Z",
+ description: "You have used some of your weekly limit, it will fully refresh in 6 days, 22 hours." },
+ ],
+ }],
+ },
+ });
+ const byId = new Map((await windows()).map((window) => [window.id, window]));
+ expect(byId.get("3p-5h")).toEqual({ id: "3p-5h", family: "Claude & GPT (shared)", name: "5-hour", kind: "session", usedPercent: 0, windowDurationMins: 300 });
+ expect(byId.get("3p-weekly")).toEqual({ id: "3p-weekly", family: "Claude & GPT (shared)", name: "Weekly", kind: "weekly", usedPercent: 0, windowDurationMins: 10080 });
+ expect(byId.get("gemini-5h")?.resetsAt).toBe("2026-10-21T13:29:53.000Z");
+ expect(byId.get("gemini-weekly")?.resetsAt).toBe("2026-10-28T08:29:53.000Z");
+ });
+
+ it("uses summary request time after authentication for the reset tolerance", async () => {
+ const { windows } = fixture({
+ now: at("2026-10-21T10:16:02Z"),
+ refreshedAt: at("2026-10-21T10:16:04Z"),
+ summary: { buckets: [{ bucketId: "3p-5h", window: "5h", remainingFraction: 1, resetTime: "2026-10-21T15:17:03Z" }] },
+ });
+ expect((await windows())[0]?.resetsAt).toBeUndefined();
+ });
+
+ it("keeps summary resets with a description, a distant reset, or no quota left", async () => {
+ const { windows } = fixture({
+ now: at("2026-10-21T10:16:04Z"),
+ summary: {
+ buckets: [
+ { bucketId: "described", window: "5h", remainingFraction: 1, description: "Reported reset", resetTime: "2026-10-21T15:16:04Z" },
+ { bucketId: "distant", window: "weekly", remainingFraction: 1, resetTime: "2026-10-28T12:16:04Z" },
+ { bucketId: "spent", window: "5h", remainingFraction: 0, resetTime: "2026-10-21T15:16:04Z" },
+ { bucketId: "overfull", window: "5h", remainingFraction: 1.01, resetTime: "2026-10-21T15:16:04Z" },
+ { bucketId: "empty-description", window: "5h", remainingFraction: 1, description: "", resetTime: "2026-10-21T15:16:04Z" },
+ ],
+ },
+ });
+ expect(resets(await windows())).toEqual({
+ described: "2026-10-21T15:16:04.000Z",
+ "empty-description": "2026-10-21T15:16:04.000Z",
+ overfull: "2026-10-21T15:16:04.000Z",
+ spent: "2026-10-21T15:16:04.000Z",
+ distant: "2026-10-28T12:16:04.000Z",
+ });
+ });
+
+ it("omits summary resets 59 seconds away but keeps resets 61 seconds away", async () => {
+ const { windows } = fixture({
+ now: at("2026-10-21T10:16:04Z"),
+ summary: {
+ buckets: [
+ { bucketId: "5h-before", window: "5h", remainingFraction: 1, resetTime: "2026-10-21T15:15:05Z" },
+ { bucketId: "5h-after", window: "5h", remainingFraction: 1, resetTime: "2026-10-21T15:17:05Z" },
+ { bucketId: "5h-edge", window: "5h", remainingFraction: 1, resetTime: "2026-10-21T15:17:04Z" },
+ { bucketId: "weekly-after", window: "weekly", remainingFraction: 1, resetTime: "2026-10-28T10:17:03Z" },
+ { bucketId: "weekly-before", window: "weekly", remainingFraction: 1, resetTime: "2026-10-28T10:15:03Z" },
+ { bucketId: "weekly-edge", window: "weekly", remainingFraction: 1, resetTime: "2026-10-28T10:15:04Z" },
+ ],
+ },
+ });
+ expect(resets(await windows())).toEqual({
+ "5h-after": "2026-10-21T15:17:05.000Z",
+ "5h-before": undefined,
+ "5h-edge": undefined,
+ "weekly-after": undefined,
+ "weekly-before": "2026-10-28T10:15:03.000Z",
+ "weekly-edge": undefined,
+ });
+ });
+
+ it("keeps full model fallback resets even at a full window from the request", async () => {
+ const { windows } = fixture({
+ now: at("2026-10-21T10:16:04Z"),
+ summaryStatus: 404,
+ models: { models: { "gemini-a": {
+ quotaInfo: { remainingFraction: 1, resetTime: "2026-10-21T15:16:04Z" },
+ weeklyQuotaInfo: { remainingFraction: 1, resetTime: "2026-10-28T10:16:04Z" },
+ } } },
+ });
+ expect((await windows()).map(({ id, resetsAt, windowDurationMins }) => ({ id, resetsAt, windowDurationMins })).sort((a, b) => b.id.localeCompare(a.id))).toEqual([
+ { id: "gemini-weekly", resetsAt: "2026-10-28T10:16:04.000Z", windowDurationMins: 10080 },
+ { id: "gemini-quota", resetsAt: "2026-10-21T15:16:04.000Z", windowDurationMins: undefined },
+ ]);
+ });
+
+ it("reports separate Gemini and shared Claude/GPT five-hour and weekly limits, refreshing access once", async () => {
+ const { windows, requests } = fixture();
+ const first = await windows();
+ expect(first).toHaveLength(4);
+ const byId = new Map(first.map((window) => [window.id, window]));
+ expect(byId.get("gemini-weekly")?.usedPercent).toBeCloseTo(4);
+ expect(byId.get("gemini-5h")?.usedPercent).toBeCloseTo(9);
+ expect(byId.get("3p-weekly")).toMatchObject({ family: "Claude & GPT (shared)", name: "Weekly", kind: "weekly", usedPercent: 100, windowDurationMins: 10080, resetsAt: "2026-10-10T15:28:22.000Z" });
+ expect(byId.get("3p-5h")).toMatchObject({ kind: "session", windowDurationMins: 300 });
+ expect(byId.get("3p-5h")?.usedPercent).toBeCloseTo(56);
+ await windows();
+ expect(requests.filter((request) => request.url.endsWith("/token"))).toHaveLength(1);
+ expect(requests.filter((request) => request.url.endsWith(":retrieveUserQuotaSummary"))).toHaveLength(4);
+ expect(requests.some((request) => request.url.endsWith(":fetchAvailableModels"))).toBe(false);
+ });
+
+ it("merges quota groups that only one endpoint reports", async () => {
+ const { windows } = fixture({
+ summaryByHost: {
+ // The daily endpoint can omit Gemini while the other endpoint returns all groups.
+ "daily-cloudcode-pa.googleapis.com": { groups: [{ displayName: "Claude and GPT models", buckets: [
+ { bucketId: "3p-weekly", window: "weekly", remainingFraction: 0.5 },
+ { bucketId: "3p-5h", window: "5h", remainingFraction: 0.3 },
+ ] }] },
+ },
+ });
+ const all = await windows();
+ expect(all.map((window) => window.id).sort()).toEqual(["3p-5h", "3p-weekly", "gemini-5h", "gemini-weekly"]);
+ const byId = new Map(all.map((window) => [window.id, window]));
+ expect(byId.get("gemini-weekly")).toMatchObject({ family: "Gemini", name: "Weekly" });
+ expect(byId.get("3p-5h")?.usedPercent).toBeCloseTo(70);
+ expect(byId.get("3p-weekly")?.usedPercent).toBe(50);
+ });
+
+ it("reports a personal account's quota from the daily endpoint it is metered on", async () => {
+ const argon = (remainingFraction: number, resetTime: string) => ({
+ groups: [{ displayName: "Gemini 4 Argon", buckets: [{ bucketId: "gemini-argon-wtu-weekly", window: "weekly", remainingFraction, resetTime }] }],
+ });
+ const { windows } = fixture({
+ now: at("2026-11-07T12:00:00Z"),
+ summaryByHost: {
+ "daily-cloudcode-pa.googleapis.com": argon(0.8623059, "2026-11-14T08:41:35Z"),
+ "cloudcode-pa.googleapis.com": argon(0, "2026-11-08T18:27:14Z"),
+ },
+ });
+ expect(await windows()).toEqual([
+ expect.objectContaining({ id: "gemini-argon-wtu-weekly", usedPercent: expect.closeTo(13.77, 2), resetsAt: "2026-11-14T08:41:35.000Z" }),
+ ]);
+ });
+
+ it("labels Argon and Carbon quotas apart from the default Gemini quota", async () => {
+ const { windows } = fixture({
+ summary: {
+ groups: [
+ ...summary.groups,
+ { displayName: "Gemini 4 Argon", buckets: [{ bucketId: "gemini-argon-wtu-weekly", window: "weekly", remainingFraction: 0.6 }] },
+ { displayName: "Gemini 4 Carbon", buckets: [{ bucketId: "gemini-carbon-wtu-weekly", window: "weekly", remainingFraction: 0.4 }] },
+ { displayName: " ", buckets: [{ bucketId: "gemini-carbon-5h", window: "5h", remainingFraction: 0.8 }] },
+ ],
+ },
+ });
+ const byId = new Map((await windows()).map((window) => [window.id, window]));
+ expect(byId.get("gemini-weekly")).toMatchObject({ family: "Gemini", name: "Weekly" });
+ expect(byId.get("gemini-argon-wtu-weekly")).toMatchObject({ family: "Gemini 4 Argon", name: "Weekly" });
+ expect(byId.get("gemini-carbon-wtu-weekly")).toMatchObject({ family: "Gemini 4 Carbon", name: "Weekly" });
+ expect(byId.get("gemini-carbon-5h")).toMatchObject({ family: "Gemini Carbon", name: "5-hour" });
+ });
+
+ it("keeps one endpoint's quotas when the other fails", async () => {
+ const { windows } = fixture({ summaryStatusByHost: { "daily-cloudcode-pa.googleapis.com": 503 } });
+ expect(await windows()).toHaveLength(4);
+ });
+
+ it("re-reads changed credentials and asks for access again after the sign-in was removed", async () => {
+ const { deps, requests, writeToken, tokenPath } = fixture();
+ const refreshes = () => requests.filter((request) => request.url.endsWith("/token")).length;
+ expect(await antigravityPlanUsage("instance", deps, tokenPath)).not.toBeNull();
+ writeToken("refresh-b");
+ expect(await antigravityPlanUsage("instance", deps, tokenPath)).not.toBeNull();
+ expect(refreshes()).toBe(2);
+ rmSync(tokenPath);
+ const before = requests.length;
+ expect(await antigravityPlanUsage("instance", deps, tokenPath)).toBeNull();
+ expect(requests).toHaveLength(before);
+ writeToken("refresh-b");
+ await antigravityPlanUsage("instance", deps, tokenPath);
+ expect(refreshes()).toBe(3);
+ });
+
+ it("falls back to model quotas without inventing a window duration", async () => {
+ const { windows } = fixture({
+ summaryStatus: 404,
+ models: { models: {
+ "gemini-a": { modelProvider: "MODEL_PROVIDER_GOOGLE", quotaInfo: { remainingFraction: 0.8, resetTime: "2026-10-10T12:00:00Z" } },
+ "gemini-b": { modelProvider: "MODEL_PROVIDER_GOOGLE", quotaInfo: { remainingFraction: 0.6, resetTime: "2026-10-10T12:00:00Z" } },
+ "claude-a": { quotaInfo: { remainingFraction: 0.2 } },
+ } },
+ });
+ const all = await windows();
+ expect(all).toHaveLength(2);
+ expect(all.find((window) => window.id === "gemini-quota")?.usedPercent).toBe(40);
+ expect(all.every((window) => window.kind === "other" && window.windowDurationMins === undefined)).toBe(true);
+ });
+
+ it("skips disabled and missing fractions and clamps valid percentages", async () => {
+ const { windows } = fixture({
+ summary: { buckets: [
+ { bucketId: "disabled", remainingFraction: 0, disabled: true },
+ { bucketId: "missing", resetTime: "2026-10-10T12:00:00Z" },
+ { bucketId: "gemini-5h", window: "5h", remainingFraction: 2, resetTime: "invalid" },
+ ] },
+ });
+ expect(await windows()).toEqual([{ id: "gemini-5h", family: "Gemini", name: "5-hour", kind: "session", usedPercent: 0, windowDurationMins: 300 }]);
+ });
+});
+
+describe("the Antigravity row of the usage report", () => {
+ it("leads with Gemini's own 5-hour and weekly windows and lists every other allowance by family", async () => {
+ const { windows } = fixture();
+ expect(antigravityPlanWindows(await windows())).toEqual({
+ plan: null,
+ fiveHour: { available: true, usedPercent: expect.closeTo(9, 5), remainingPercent: expect.closeTo(91, 5), resetsAt: "2026-10-09T16:06:01.000Z" },
+ weekly: { available: true, usedPercent: expect.closeTo(4, 5), remainingPercent: expect.closeTo(96, 5), resetsAt: "2026-10-12T19:41:43.000Z" },
+ extra: [],
+ models: [{ name: "Claude & GPT (shared)", windows: [
+ { label: "Weekly", usedPercent: 100, remainingPercent: 0, resetsAt: "2026-10-10T15:28:22.000Z" },
+ { label: "5-hour", usedPercent: expect.closeTo(56, 5), remainingPercent: expect.closeTo(44, 5), resetsAt: "2026-10-09T16:06:30.000Z" },
+ ] }],
+ });
+ expect(antigravityPlanWindows([{ id: "gemini-quota", family: "Gemini", name: "Reported quota", kind: "other", usedPercent: 40 }])).toMatchObject({
+ fiveHour: { available: false }, weekly: { available: false }, models: [{ name: "Gemini", windows: [{ label: "Reported quota", usedPercent: 40, resetsAt: null }] }],
+ });
+ });
+
+ it.each([
+ ["Google refuses the stored sign-in", { tokenStatus: 401 }, 1],
+ ["Google cannot be reached for the refresh", { tokenStatus: 503 }, 1],
+ ["Google refuses both quota calls", { summaryStatus: 403, models: "nothing" }, 5],
+ ["Google reports nothing usable", { summary: { buckets: [] } }, 5],
+ ["nobody is signed in", { missingToken: true }, 0],
+ ] as Array<[string, FixtureOptions, number]>)("is no row at all, and says nothing, when %s", async (_name, options, calls) => {
+ const { deps, requests, tokenPath } = fixture(options);
+ const warn = vi.spyOn(console, "warn"), error = vi.spyOn(console, "error"), log = vi.spyOn(console, "log");
+ expect(await antigravityPlanUsage("instance", deps, tokenPath)).toBeNull();
+ expect(requests).toHaveLength(calls);
+ for (const spy of [warn, error, log]) expect(spy).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ["the refresh", ["/token"]],
+ ["both quota hosts", ["cloudcode-pa.googleapis.com"]],
+ ["one quota host", ["daily-cloudcode-pa.googleapis.com"]],
+ ])("gives up on the whole read after one deadline when %s never answers", async (_name, hangs) => {
+ const { deps, tokenPath } = fixture({ hangs });
+ const started = Date.now();
+ const usage = await antigravityPlanUsage("instance", { ...deps, timeoutMs: 300 }, tokenPath);
+ expect(Date.now() - started).toBeLessThan(2_000);
+ if (hangs[0] === "daily-cloudcode-pa.googleapis.com") expect(usage).not.toBeNull();
+ else expect(usage).toBeNull();
+ });
+
+ it("does not ask Google again for a sign-in it refused until a quarter of an hour has passed or the sign-in changed", async () => {
+ const { deps, requests, tokenPath, writeToken, advance } = fixture({ tokenStatus: 401 });
+ for (let read = 0; read < 3; read += 1) expect(await antigravityPlanUsage("instance", deps, tokenPath)).toBeNull();
+ expect(requests).toHaveLength(1);
+ advance(15 * 60_000 - 1);
+ await antigravityPlanUsage("instance", deps, tokenPath);
+ expect(requests).toHaveLength(1);
+ advance(1);
+ await antigravityPlanUsage("instance", deps, tokenPath);
+ expect(requests).toHaveLength(2);
+ writeToken("refresh-b");
+ await antigravityPlanUsage("instance", deps, tokenPath);
+ expect(requests).toHaveLength(3);
+ });
+
+ it("is no row, and makes no request, once the switch is off", async () => {
+ const { deps, requests, tokenPath } = fixture();
+ expect(await antigravityPlanUsage("instance", deps, tokenPath, false)).toBeNull();
+ expect(requests).toEqual([]);
+ });
+
+ it("never returns the sign-in, the access token or the account", async () => {
+ const { deps, tokenPath } = fixture();
+ expect(JSON.stringify(await antigravityPlanUsage("instance", deps, tokenPath))).not.toMatch(/client-secret|client-id|refresh-a|access-token|project-id/);
+ });
+
+ it("joins the report beside the other engines, and is left out when it cannot be read", async () => {
+ const instanceId = "antigravity-usage-row";
+ const accounts = planAccountsFromInstances({ [instanceId]: { driver: "antigravityAgent", displayName: "", enabled: true, config: {}, environment: {} } } as never);
+ expect(accounts).toEqual([{ id: instanceId, name: "Antigravity", driver: "antigravity", environment: {} }]);
+ const { deps } = fixture();
+ const credentials = { read: () => { throw new Error("the report's own credential reader is not used for Antigravity"); } };
+ expect((await fetchPlanUsage(accounts, { ...deps, credentials })).providers).toEqual([]);
+ const tokenPath = antigravityTokenPath(instanceId);
+ mkdirSync(join(tokenPath, ".."), { recursive: true });
+ writeFileSync(tokenPath, JSON.stringify({ client_id: "client-id", client_secret: "client-secret", refresh_token: "refresh-a", project_id: "project-id" }));
+ const report = await fetchPlanUsage(accounts, { ...deps, credentials });
+ expect(report.providers).toMatchObject([{ id: instanceId, name: "Antigravity", driver: "antigravity", ok: true, error: null, fiveHour: { available: true }, weekly: { available: true } }]);
+ expect(JSON.stringify(report)).not.toMatch(/client-secret|refresh-a|access-token/);
+ });
+});
diff --git a/server/drivers/antigravity-usage-limits.ts b/server/drivers/antigravity-usage-limits.ts
new file mode 100644
index 0000000000..a75d97a2cb
--- /dev/null
+++ b/server/drivers/antigravity-usage-limits.ts
@@ -0,0 +1,344 @@
+// The 5-hour and weekly limits of the Google account an Antigravity instance is signed in to, for the plan-usage report.
+//
+// Adapted from pingdotgg/t3code@b732621b51, MIT License, Copyright (c) 2026
+// T3 Tools Inc. (full text in third_party/t3-code/LICENSE); modified:
+// - apps/server/src/provider/antigravityUsageLimits.ts (the endpoints and
+// their order, the request's client line, the summary and per-model
+// quota readers, the untouched-bucket reset rule, and the access cache).
+// Only the personal Google sign-in is read, the account fingerprint is left out, and every failure is no row at all.
+//
+// Security: the access token lives in this module's memory and in request headers only. It is never logged, written or
+// put in a result, and only the instance's own stored sign-in is read.
+import { createHash } from "node:crypto";
+import { readFile, stat } from "node:fs/promises";
+
+import type { PlanExtra, PlanFetch, PlanModelUsage, PlanWindow, PlanWindows } from "../plan-usage.ts";
+import { antigravityTokenPath } from "./antigravity-acp.ts";
+import { refreshAntigravityAccess } from "./antigravity-account.ts";
+
+/** Whether Antigravity accounts are asked for their limits at all. Off, they have no row in the usage report. */
+export const ANTIGRAVITY_USAGE_LIMITS = true;
+
+export function antigravityUserAgent(platform: NodeJS.Platform, architecture: string): string {
+ return `antigravity/hub/2.24.0 (aidev_client; os_type=${platform}; arch=${architecture}; cl=963137146)`;
+}
+
+const DAILY_ENDPOINT = "https://daily-cloudcode-pa.googleapis.com";
+const PROD_ENDPOINT = "https://cloudcode-pa.googleapis.com";
+// The ACP runtime meters consumer tiers on the daily host and GCP-terms tiers on prod.
+const PERSONAL_ENDPOINTS = [DAILY_ENDPOINT, PROD_ENDPOINT];
+const SUMMARY_WINDOW_MINS = new Map([
+ ["5h", 5 * 60],
+ ["weekly", 7 * 24 * 60],
+]);
+// The whole read, as long as any other engine's usage may take.
+const READ_DEADLINE_MS = 8_000;
+const REFUSED_REFRESH_HOLD_MS = 15 * 60_000;
+const FAILED_REFRESH_HOLD_MS = 60_000;
+const TOKEN_FILE_MAX_BYTES = 1024 * 1024;
+
+interface Quota {
+ remainingFraction?: number;
+ resetTime?: string;
+}
+
+interface Bucket extends Quota {
+ bucketId: string;
+ window?: string;
+ displayName?: string;
+ description?: string;
+ disabled?: boolean;
+}
+
+export interface AntigravityUsageWindow {
+ id: string;
+ /** Whose allowance it is: "Gemini", "Claude & GPT (shared)", or the group's own name. */
+ family: string;
+ /** "5-hour", "Weekly", or what the account calls it. */
+ name: string;
+ kind: "session" | "weekly" | "other";
+ usedPercent: number;
+ resetsAt?: string;
+ windowDurationMins?: number;
+}
+
+const record = (value: unknown): Record<string, unknown> | null =>
+ value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : null;
+const text = (value: unknown): string | undefined => typeof value === "string" ? value : undefined;
+
+function quota(value: unknown): Quota | null {
+ const fields = record(value);
+ if (!fields) return null;
+ return {
+ ...(typeof fields.remainingFraction === "number" ? { remainingFraction: fields.remainingFraction } : {}),
+ ...(typeof fields.resetTime === "string" ? { resetTime: fields.resetTime } : {}),
+ };
+}
+
+function bucket(value: unknown): Bucket | null {
+ const fields = record(value);
+ if (!fields || typeof fields.bucketId !== "string" || !fields.bucketId) return null;
+ return {
+ ...quota(fields),
+ bucketId: fields.bucketId,
+ window: text(fields.window),
+ displayName: text(fields.displayName),
+ description: text(fields.description),
+ disabled: fields.disabled === true,
+ };
+}
+
+function iso(value: string | undefined): string | undefined {
+ const parsed = value ? Date.parse(value) : Number.NaN;
+ return Number.isFinite(parsed) ? new Date(parsed).toISOString() : undefined;
+}
+
+function quotaWindow(
+ id: string,
+ family: string,
+ name: string,
+ value: Quota,
+ kind: AntigravityUsageWindow["kind"] = "other",
+ windowDurationMins?: number,
+): AntigravityUsageWindow | undefined {
+ if (value.remainingFraction === undefined || !Number.isFinite(value.remainingFraction)) return undefined;
+ const resetsAt = iso(value.resetTime);
+ return {
+ id,
+ family,
+ name,
+ kind,
+ usedPercent: (1 - Math.max(0, Math.min(1, value.remainingFraction))) * 100,
+ ...(resetsAt ? { resetsAt } : {}),
+ ...(windowDurationMins === undefined ? {} : { windowDurationMins }),
+ };
+}
+
+function summaryResetTime(entry: Bucket, windowDurationMins: number | undefined, requestedAt: number): string | undefined {
+ // Untouched summary buckets report a rolling full-window reset.
+ const untouched = entry.remainingFraction === 1
+ && entry.description === undefined
+ && windowDurationMins !== undefined
+ && Math.abs(Date.parse(entry.resetTime ?? "") - requestedAt - windowDurationMins * 60_000) <= 60_000;
+ return untouched ? undefined : entry.resetTime;
+}
+
+/** Windows from a `retrieveUserQuotaSummary` answer requested at `requestedAt`. */
+export function antigravitySummaryWindows(response: unknown, requestedAt: number): AntigravityUsageWindow[] {
+ const summary = record(response);
+ if (!summary) return [];
+ const buckets = (value: unknown) => (Array.isArray(value) ? value : []).map(bucket).filter((entry) => entry !== null);
+ const listed = (Array.isArray(summary.groups) ? summary.groups : []).map(record).filter((group) => group !== null)
+ .map((group) => ({ displayName: text(group.displayName), buckets: buckets(group.buckets) }));
+ const groups = listed.some((group) => group.buckets.length) ? listed : [{ displayName: undefined, buckets: buckets(summary.buckets) }];
+ const windows = new Map<string, AntigravityUsageWindow>();
+ for (const group of groups) {
+ for (const entry of group.buckets) {
+ if (entry.disabled) continue;
+ // Argon and Carbon are metered separately from the default Gemini buckets.
+ const family = entry.bucketId.startsWith("gemini-argon-")
+ ? group.displayName?.trim() || "Gemini Argon"
+ : entry.bucketId.startsWith("gemini-carbon-")
+ ? group.displayName?.trim() || "Gemini Carbon"
+ : entry.bucketId.startsWith("gemini-")
+ ? "Gemini"
+ : entry.bucketId.startsWith("3p-")
+ ? "Claude & GPT (shared)"
+ : group.displayName?.trim() || entry.bucketId;
+ const weekly = entry.window === "weekly";
+ const session = entry.window === "5h";
+ const windowDurationMins = SUMMARY_WINDOW_MINS.get(entry.window ?? "");
+ const window = quotaWindow(
+ entry.bucketId,
+ family,
+ weekly ? "Weekly" : session ? "5-hour" : entry.displayName?.trim() || "Quota",
+ { ...entry, resetTime: summaryResetTime(entry, windowDurationMins, requestedAt) },
+ weekly ? "weekly" : session ? "session" : "other",
+ windowDurationMins,
+ );
+ if (window) windows.set(window.id, window);
+ }
+ }
+ return [...windows.values()];
+}
+
+/** Older accounts expose model quotas without a window length. Do not invent a reset cadence. */
+export function antigravityModelWindows(response: unknown): AntigravityUsageWindow[] {
+ const models = record(record(response)?.models);
+ if (!models) return [];
+ const windows = new Map<string, AntigravityUsageWindow>();
+ for (const [modelId, value] of Object.entries(models)) {
+ const model = record(value);
+ if (!model) continue;
+ const family = model.modelProvider === "MODEL_PROVIDER_GOOGLE" || modelId.startsWith("gemini-")
+ ? "Gemini"
+ : model.modelProvider === "MODEL_PROVIDER_ANTHROPIC" || modelId.startsWith("claude-")
+ ? "Claude"
+ : model.modelProvider === "MODEL_PROVIDER_OPENAI" || modelId.startsWith("gpt-")
+ ? "GPT"
+ : undefined;
+ if (!family) continue;
+ for (const [suffix, entry] of [["quota", quota(model.quotaInfo)], ["weekly", quota(model.weeklyQuotaInfo)]] as const) {
+ if (!entry) continue;
+ const window = quotaWindow(
+ `${family.toLowerCase()}-${suffix}`,
+ family,
+ suffix === "weekly" ? "Weekly" : "Reported quota",
+ entry,
+ suffix === "weekly" ? "weekly" : "other",
+ suffix === "weekly" ? 7 * 24 * 60 : undefined,
+ );
+ if (!window) continue;
+ const previous = windows.get(window.id);
+ if (!previous || window.usedPercent > previous.usedPercent) windows.set(window.id, window);
+ }
+ }
+ return [...windows.values()];
+}
+
+const clamp = (value: number) => Math.min(100, Math.max(0, value));
+
+/** The report's shape: Gemini's own 5-hour and weekly windows lead the row, every other allowance is listed by family. */
+export function antigravityPlanWindows(windows: readonly AntigravityUsageWindow[]): PlanWindows {
+ const closed = (): PlanWindow => ({ available: false, remainingPercent: null, usedPercent: null, resetsAt: null });
+ const open = (window: AntigravityUsageWindow): PlanWindow =>
+ ({ available: true, usedPercent: clamp(window.usedPercent), remainingPercent: clamp(100 - window.usedPercent), resetsAt: window.resetsAt ?? null });
+ const lead = (kind: "session" | "weekly") => windows.find((window) => window.family === "Gemini" && window.kind === kind);
+ const fiveHour = lead("session"), weekly = lead("weekly");
+ const models: PlanModelUsage[] = [];
+ for (const window of windows) {
+ if (window === fiveHour || window === weekly) continue;
+ const line: PlanExtra = { label: window.name, usedPercent: clamp(window.usedPercent), remainingPercent: clamp(100 - window.usedPercent), resetsAt: window.resetsAt ?? null };
+ const family = models.find((model) => model.name === window.family);
+ if (family) family.windows.push(line);
+ else models.push({ name: window.family, windows: [line] });
+ }
+ return { plan: null, fiveHour: fiveHour ? open(fiveHour) : closed(), weekly: weekly ? open(weekly) : closed(), extra: [], models };
+}
+
+interface StoredSignIn {
+ client_id: string;
+ client_secret: string;
+ refresh_token: string;
+ project_id?: string;
+}
+
+async function storedSignIn(tokenPath: string): Promise<{ signIn: StoredSignIn; fingerprint: string } | null> {
+ const info = await stat(tokenPath);
+ if (!info.isFile() || info.size > TOKEN_FILE_MAX_BYTES) return null;
+ const fields = record(JSON.parse(await readFile(tokenPath, "utf8")));
+ if (!fields || !["client_id", "client_secret", "refresh_token"].every((key) => typeof fields[key] === "string" && fields[key])) return null;
+ const signIn: StoredSignIn = {
+ client_id: fields.client_id as string, client_secret: fields.client_secret as string, refresh_token: fields.refresh_token as string,
+ ...(typeof fields.project_id === "string" ? { project_id: fields.project_id } : {}),
+ };
+ const fingerprint = createHash("sha256").update(`${signIn.client_id}\0${signIn.refresh_token}\0${signIn.project_id ?? ""}`).digest("hex");
+ return { signIn, fingerprint };
+}
+
+const cachedAccess = new Map<string, { fingerprint: string; accessToken: string; expiresAt: number }>();
+
+export function clearAntigravityUsageAccess(): void {
+ cachedAccess.clear();
+ refreshHolds.clear();
+}
+
+export interface AntigravityUsageDeps {
+ fetch: PlanFetch;
+ now?: () => number;
+ timeoutMs?: number;
+}
+
+/** `work`, or a rejection once `signal` aborts: a request that ignores its signal does not hold the others' answers. */
+function untilAborted<T>(work: Promise<T>, signal: AbortSignal): Promise<T> {
+ if (signal.aborted) return Promise.reject(new Error("deadline"));
+ return new Promise<T>((done, fail) => {
+ const stop = () => fail(new Error("deadline"));
+ signal.addEventListener("abort", stop, { once: true });
+ work.then(done, fail).finally(() => signal.removeEventListener("abort", stop));
+ });
+}
+
+async function postJson(deps: AntigravityUsageDeps, signal: AbortSignal, url: string, headers: Record<string, string>, body: string): Promise<unknown> {
+ return untilAborted((async () => {
+ const response = await deps.fetch(url, { method: "POST", headers, body, redirect: "manual", signal });
+ if (!response.ok) throw new Error("refused");
+ return JSON.parse(await response.text());
+ })(), signal);
+}
+
+/** Sign-ins Google would not refresh, or that could not be refreshed, and when to ask again: a refused one is not
+ * posted again with every report. A sign-in that changed is asked at once. */
+const refreshHolds = new Map<string, { fingerprint: string; until: number }>();
+
+/** The windows Google reports for the sign-in stored at `tokenPath`; empty when it reports none. Throws on any failure.
+ * Every request shares `signal`, the one deadline of the whole read. */
+export async function readAntigravityUsageWindows(tokenPath: string, deps: AntigravityUsageDeps, signal: AbortSignal = AbortSignal.timeout(deps.timeoutMs ?? READ_DEADLINE_MS)): Promise<AntigravityUsageWindow[]> {
+ const stored = await storedSignIn(tokenPath).catch(() => null);
+ if (!stored) {
+ cachedAccess.delete(tokenPath);
+ return [];
+ }
+ const now = deps.now ?? Date.now;
+ const { signIn, fingerprint } = stored;
+ let cached = cachedAccess.get(tokenPath);
+ if (cached?.fingerprint !== fingerprint || cached.expiresAt <= now() + 60_000) {
+ cachedAccess.delete(tokenPath);
+ const held = refreshHolds.get(tokenPath);
+ if (held?.fingerprint === fingerprint && now() < held.until) throw new Error("held");
+ const started = now();
+ let refused = false;
+ const access = await untilAborted(refreshAntigravityAccess(signIn, signal, async (url, init) => {
+ const response = await deps.fetch(url, { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: String(init.body), redirect: "manual", signal: init.signal });
+ refused = !response.ok;
+ return { ok: response.ok, json: async () => JSON.parse(await response.text()) };
+ }, "manual"), signal).catch(() => undefined);
+ if (!access || access.expiresInSeconds === null) {
+ if (refreshHolds.size >= 128) refreshHolds.delete(refreshHolds.keys().next().value!);
+ refreshHolds.set(tokenPath, { fingerprint, until: now() + (refused ? REFUSED_REFRESH_HOLD_MS : FAILED_REFRESH_HOLD_MS) });
+ throw new Error("refused");
+ }
+ refreshHolds.delete(tokenPath);
+ cached = { fingerprint, accessToken: access.accessToken, expiresAt: started + access.expiresInSeconds * 1000 };
+ if (cachedAccess.size >= 128) cachedAccess.delete(cachedAccess.keys().next().value!);
+ cachedAccess.set(tokenPath, cached);
+ }
+ const { accessToken } = cached;
+ const headers = { Authorization: `Bearer ${accessToken}`, "User-Agent": antigravityUserAgent(process.platform, process.arch), "content-type": "application/json" };
+ const body = JSON.stringify(signIn.project_id ? { project: signIn.project_id } : {});
+ // Merge endpoints because quota groups differ; the metered host's reading of a bucket wins.
+ const fetchWindows = async (operation: string, parse: (response: unknown, requestedAt: number) => AntigravityUsageWindow[]) => {
+ const responses = await Promise.all(PERSONAL_ENDPOINTS.map(async (endpoint) => {
+ // Capture each request after auth, so refresh latency does not widen the tolerance.
+ const requestedAt = now();
+ try {
+ return parse(await postJson(deps, signal, `${endpoint}/v1internal:${operation}`, headers, body), requestedAt);
+ } catch {
+ return [];
+ }
+ }));
+ const windows = new Map<string, AntigravityUsageWindow>();
+ for (const window of responses.flat()) if (!windows.has(window.id)) windows.set(window.id, window);
+ return [...windows.values()];
+ };
+ const summary = await fetchWindows("retrieveUserQuotaSummary", antigravitySummaryWindows);
+ return summary.length ? summary : fetchWindows("fetchAvailableModels", (response) => antigravityModelWindows(response));
+}
+
+/** An Antigravity instance's limits for the usage report, or null for no row: the switch is off, nobody is signed in,
+ * Google refused or could not be reached, or it reported nothing usable. It never throws and reports no error. */
+export async function antigravityPlanUsage(
+ instanceId: string,
+ deps: AntigravityUsageDeps,
+ tokenPath = antigravityTokenPath(instanceId),
+ enabled = ANTIGRAVITY_USAGE_LIMITS,
+): Promise<PlanWindows | null> {
+ if (!enabled) return null;
+ try {
+ // One deadline for the refresh, the summary and the fallback together.
+ const windows = await readAntigravityUsageWindows(tokenPath, deps, AbortSignal.timeout(deps.timeoutMs ?? READ_DEADLINE_MS));
+ return windows.length ? antigravityPlanWindows(windows) : null;
+ } catch {
+ return null;
+ }
+}
diff --git a/server/engine-limits.test.ts b/server/engine-limits.test.ts
index fce083e566..b315ce9274 100644
--- a/server/engine-limits.test.ts
+++ b/server/engine-limits.test.ts
@@ -43,6 +43,23 @@ describe("usage limits a bot reads", () => {
});
});
+ it("names Antigravity's leading windows as Gemini's, and says its limits could not be checked when it has no row", () => {
+ const antigravity = instance("antigravity", "antigravityAgent", "Antigravity");
+ const [account] = read({
+ instances: [antigravity],
+ report: report(row("antigravity", { driver: "antigravity", plan: null,
+ models: [{ name: "Claude & GPT (shared)", windows: [{ label: "5-hour", usedPercent: 56, remainingPercent: 44, resetsAt: AT }] }] })),
+ });
+ expect(account).toMatchObject({ status: "ok", windows: [
+ { name: "Gemini 5-hour", usedPercent: 40.3 }, { name: "Gemini weekly", usedPercent: 70 }, { name: "Claude & GPT (shared) 5-hour", usedPercent: 56 },
+ ] });
+ expect(read({ instances: [antigravity] })).toEqual([
+ { account: "Antigravity", engine: "antigravityAgent", status: "unknown", checkedAt: AT, windows: [], why: "Usage could not be checked just now. Try again later." },
+ ]);
+ expect(read({ instances: [antigravity], status: () => ({ ...ready, authenticated: false }) })).toEqual([]);
+ expect(read({ instances: [instance("claude")], report: report(row("claude")) })[0]!.windows[0]!.name).toBe("5-hour");
+ });
+
it("tells unknown from unsupported", () => {
const accounts = read({
instances: [instance("signed-out", "claudeAgent", "Signed out"), instance("quiet", "codex", "Quiet"), instance("cursor", "cursorAgent", "Cursor"), instance("key", "claudeAgent", "Key")],
diff --git a/server/engine-limits.ts b/server/engine-limits.ts
index f5a0478f12..aa6653790b 100644
--- a/server/engine-limits.ts
+++ b/server/engine-limits.ts
@@ -7,6 +7,7 @@ import { audienceMember, type Audience } from "./audience.ts";
import type { InstanceConfig, InstanceConfigMap, ProviderSnapshot } from "./contracts.ts";
import { audienceHomeKey, engineHomesRoot } from "./engine-homes/layout.ts";
import type { PlanProviderRow, PlanUsageReport, PlanWindow } from "./plan-usage.ts";
+import { ANTIGRAVITY_USAGE_LIMITS } from "./drivers/antigravity-usage-limits.ts";
export interface EngineLimitWindow {
name: string;
@@ -35,7 +36,8 @@ export interface EngineLimitInstance {
enabled: boolean;
}
-const REPORTING_DRIVERS: ReadonlySet<string> = new Set(["claudeAgent", "codex", "grokAgent", "opencodeGo"]);
+const REPORTING_DRIVERS: ReadonlySet<string> = new Set(["claudeAgent", "codex", "grokAgent", "opencodeGo", "antigravityAgent"]);
+const ANTIGRAVITY = "antigravityAgent";
const UNSUPPORTED_WHY = "This AI does not report usage limits to this app.";
const NO_WINDOWS_WHY = "The account answered but reported no usage windows.";
const NOT_CHECKED_WHY = "Usage could not be checked just now. Try again later.";
@@ -64,9 +66,10 @@ export function accountReadableFrom(entry: InstanceConfig | undefined, turn: Aud
const percent = (value: number) => Math.round(value * 10) / 10;
-function rowWindows(row: PlanProviderRow): EngineLimitWindow[] {
+/** `lead` names whose allowance an account's two leading windows are, when its models do not all share them. */
+function rowWindows(row: PlanProviderRow, lead = ""): EngineLimitWindow[] {
const line = (name: string, window: PlanWindow): EngineLimitWindow[] => window.available && window.usedPercent !== null
- ? [{ name, usedPercent: percent(window.usedPercent), resetsAt: window.resetsAt }] : [];
+ ? [{ name: `${lead}${name}`, usedPercent: percent(window.usedPercent), resetsAt: window.resetsAt }] : [];
return [
...line("5-hour", row.fiveHour),
...line("weekly", row.weekly),
@@ -101,14 +104,17 @@ export function engineLimitsFor(input: {
seen.set(name, count);
return { account: count > 1 ? `${name} ${count}` : name, engine: instance.driverKind };
})();
- if (!REPORTING_DRIVERS.has(instance.driverKind) || snapshot.billing === "metered") {
+ if (!REPORTING_DRIVERS.has(instance.driverKind) || snapshot.billing === "metered" || (instance.driverKind === ANTIGRAVITY && !ANTIGRAVITY_USAGE_LIMITS)) {
return snapshot.authenticated === false ? [] : [{ ...base, status: "unsupported", checkedAt: null, windows: [], why: UNSUPPORTED_WHY }];
}
if (!report) return [{ ...base, status: "unknown", checkedAt: null, windows: [], why: NOT_CHECKED_WHY }];
const row = report.providers.find((candidate) => candidate.id === instance.instanceId);
+ // An Antigravity account has no row when its limits could not be read just now, or when nobody is signed in.
+ if (!row && instance.driverKind === ANTIGRAVITY) return snapshot.authenticated === false ? [] : [{ ...base, status: "unknown", checkedAt: report.fetchedAt, windows: [], why: NOT_CHECKED_WHY }];
if (!row) return [{ ...base, status: "unsupported", checkedAt: null, windows: [], why: UNSUPPORTED_WHY }];
if (!row.ok) return [{ ...base, status: "unknown", checkedAt: report.fetchedAt, windows: [], why: row.error ?? NOT_CHECKED_WHY }];
- const windows = rowWindows(row);
+ // Antigravity's leading windows are Gemini's own; its other models draw on the allowances listed after them.
+ const windows = rowWindows(row, instance.driverKind === ANTIGRAVITY ? "Gemini " : "");
const plan = row.plan ? { plan: row.plan } : {};
return [windows.length
? { ...base, ...plan, status: "ok", checkedAt: report.fetchedAt, windows }
diff --git a/server/limit-resets.test.ts b/server/limit-resets.test.ts
index 1d56642667..6e9ad55b5c 100644
--- a/server/limit-resets.test.ts
+++ b/server/limit-resets.test.ts
@@ -235,6 +235,18 @@ describe("LimitResetClock", () => {
await instance.refresh(true);
expect(load).toHaveBeenCalledTimes(1);
});
+
+ it("does not ask for the usage of an engine whose usage holds nothing here", async () => {
+ const load = vi.fn(async (_asked: Array<{ id: string }>) => report(claude([50, NOW + HOUR], [5, NOW + 90 * HOUR])));
+ const antigravity = { id: "antigravity", name: "Antigravity", driver: "antigravity" as const, environment: {} };
+ let current = [...accounts, antigravity];
+ const instance = new LimitResetClock({ accounts: () => current, now: () => NOW, loadUsage: load });
+ await instance.refresh(true);
+ expect(load.mock.calls.map(([asked]) => asked.map((account) => account.id))).toEqual([["claude"]]);
+ current = [antigravity];
+ await instance.refresh(true);
+ expect(load).toHaveBeenCalledTimes(1);
+ });
});
describe("codexLimitResetsAt", () => {
diff --git a/server/limit-resets.ts b/server/limit-resets.ts
index 608a71c278..3577c48a93 100644
--- a/server/limit-resets.ts
+++ b/server/limit-resets.ts
@@ -265,7 +265,8 @@ export class LimitResetClock {
async refresh(force: boolean): Promise<void> {
if (this.loading) return this.loading;
- const accounts = this.options.accounts();
+ // An engine whose usage holds nothing here (engineLimitFromUsage) is not asked for it.
+ const accounts = this.options.accounts().filter((account) => REPORTED_DRIVERS.has(account.driver));
this.loading = (async () => {
try {
if (!accounts.length) { this.checkedAt = this.now(); this.failures = 0; return; }
@@ -360,6 +361,6 @@ export class LimitResetClock {
private unnamed(engine: string): EngineLimit {
const account = this.options.accounts().find((candidate) => candidate.id === engine);
- return { engine, name: account?.name ?? engine, driver: account?.driver ?? "claude", window: null, usedPercent: null, resetsAt: null, blocked: false };
+ return { engine, name: account?.name ?? engine, driver: account && REPORTED_DRIVERS.has(account.driver) ? account.driver as Driver : "claude", window: null, usedPercent: null, resetsAt: null, blocked: false };
}
}
diff --git a/server/plan-usage.test.ts b/server/plan-usage.test.ts
index 66a9d1fec0..f62e5b1ccf 100644
--- a/server/plan-usage.test.ts
+++ b/server/plan-usage.test.ts
@@ -466,6 +466,26 @@ describe("plan usage fetcher", () => {
expect(fetchImpl).toHaveBeenCalledTimes(3);
});
+ it("serves a caller that asks for some of a report's accounts from that read, and reads again for one it does not hold", async () => {
+ const fetchImpl = vi.fn<PlanFetch>(async () => jsonResponse({
+ five_hour: { utilization: 25, resets_at: "2026-09-26T12:00:00.000Z" },
+ seven_day: { utilization: 40, resets_at: "2026-10-03T00:00:00.000Z" },
+ }));
+ const both = [account("claude"), account("claude", { id: "second", name: "Second" })];
+ const credentials = { read: () => ({ token: SECRET, accountId: null, expired: false }) };
+ await loadPlanUsage({ accounts: both, now: NOW, fetch: fetchImpl, credentials });
+ expect(fetchImpl).toHaveBeenCalledTimes(2);
+ const some = await loadPlanUsage({ accounts: [both[1]!], now: NOW + 1_000, fetch: fetchImpl, credentials });
+ expect(some.providers.map((row) => row.id)).toEqual(["second"]);
+ expect(fetchImpl).toHaveBeenCalledTimes(2);
+ expect((await loadPlanUsage({ accounts: both, now: NOW + 2_000, fetch: fetchImpl, credentials })).providers).toHaveLength(2);
+ expect(fetchImpl).toHaveBeenCalledTimes(2);
+ await loadPlanUsage({ accounts: [account("claude", { id: "third", name: "Third" })], now: NOW + 3_000, fetch: fetchImpl, credentials });
+ expect(fetchImpl).toHaveBeenCalledTimes(3);
+ await loadPlanUsage({ accounts: [{ ...both[1]!, configDir: "/elsewhere" }], now: NOW + 4_000, fetch: fetchImpl, credentials });
+ expect(fetchImpl).toHaveBeenCalledTimes(4);
+ });
+
it("does not share the cache when GROK_HOME changes", async () => {
const fetchImpl = vi.fn<PlanFetch>(async () => jsonResponse({
five_hour: { utilization: 25, resets_at: "2026-09-26T12:00:00.000Z" },
diff --git a/server/plan-usage.ts b/server/plan-usage.ts
index c7d04e56dd..4906f972f6 100644
--- a/server/plan-usage.ts
+++ b/server/plan-usage.ts
@@ -7,9 +7,10 @@ import { join } from "node:path";
import type { InstanceConfigMap } from "./contracts.ts";
import { resolveClaudeConfigDir } from "./drivers/claude.ts";
import { codexHome } from "./drivers/codex-identity.ts";
+import { antigravityPlanUsage } from "./drivers/antigravity-usage-limits.ts";
import { harnessHome, sealedFixture } from "./env-path.ts";
-export type PlanDriver = "claude" | "codex" | "grok" | "opencode";
+export type PlanDriver = "claude" | "codex" | "grok" | "opencode" | "antigravity";
export interface PlanWindow {
available: boolean;
@@ -94,7 +95,7 @@ export interface PlanResponse {
export type PlanFetch = (
url: string,
- init: { headers: Record<string, string>; signal: AbortSignal },
+ init: { headers: Record<string, string>; signal: AbortSignal; method?: "POST"; body?: string; redirect?: "manual" },
) => Promise<PlanResponse>;
export interface PlanUsageDeps {
@@ -136,18 +137,14 @@ const WEEK_MAX_SECONDS = 9 * 86400;
const MONTH_MIN_SECONDS = 27 * 86400;
const MONTH_MAX_SECONDS = 32 * 86400;
-const DRIVER_OF: Record<string, PlanDriver> = {
- claudeAgent: "claude",
- codex: "codex",
- grokAgent: "grok",
- opencodeGo: "opencode",
-};
+const DRIVER_OF: Record<string, PlanDriver> = { claudeAgent: "claude", codex: "codex", grokAgent: "grok", opencodeGo: "opencode", antigravityAgent: "antigravity" };
const PRODUCT_NAME: Record<PlanDriver, string> = {
claude: "Claude",
codex: "Codex",
grok: "Grok",
opencode: "OpenCode",
+ antigravity: "Antigravity",
};
export function planAccountsFromInstances(instances: InstanceConfigMap): PlanAccount[] {
@@ -297,7 +294,7 @@ export async function fetchPlanUsage(accounts: PlanAccount[], deps: PlanUsageDep
return { fetchedAt: new Date(now).toISOString(), providers };
}
-let cachedReport: { at: number; key: string; report: PlanUsageReport } | null = null;
+let cachedReport: { at: number; key: string; accounts: Set<string>; report: PlanUsageReport } | null = null;
export function clearPlanUsageCache(): void {
cachedReport = null;
@@ -314,8 +311,9 @@ export async function loadPlanUsage(input: {
}): Promise<PlanUsageReport> {
const now = input.now ?? Date.now();
const key = planUsageCacheKey(input.accounts);
- if (!input.refresh && cachedReport && cachedReport.key === key && now - cachedReport.at < PLAN_USAGE_CACHE_MS) {
- return cachedReport.report;
+ if (!input.refresh && cachedReport && now - cachedReport.at < PLAN_USAGE_CACHE_MS) { // a read of more accounts serves a caller that asks for some of them (the limit clock)
+ if (cachedReport.key === key) return cachedReport.report;
+ if (input.accounts.every((account) => cachedReport!.accounts.has(planUsageCacheKey([account])))) return { ...cachedReport.report, providers: cachedReport.report.providers.filter((row) => input.accounts.some((account) => account.id === row.id)) };
}
const report = await fetchPlanUsage(input.accounts, {
fetch: input.fetch ?? ((url, init) => globalThis.fetch(url, init)),
@@ -323,7 +321,7 @@ export async function loadPlanUsage(input: {
now: () => now,
timeoutMs: input.timeoutMs,
});
- cachedReport = { at: now, key, report };
+ cachedReport = { at: now, key, accounts: new Set(input.accounts.map((account) => planUsageCacheKey([account]))), report };
return report;
}
@@ -921,6 +919,7 @@ function okRow(account: PlanAccount, windows: PlanWindows): PlanProviderRow {
async function fetchProvider(account: PlanAccount, deps: PlanUsageDeps): Promise<PlanProviderRow | null> { // null: OpenCode, in every fleet, with no key of its own
let credential: PlanCredential;
+ if (account.driver === "antigravity") { const windows = await antigravityPlanUsage(account.id, deps); return windows && okRow(account, windows); } // null: no sign-in, or Google gave nothing
try {
credential = await deps.credentials.read(account);
} catch {