Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

antigravityUsageLimits.test.ts

302 lines11.8 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { describe, expect, it } from "@effect/vitest";
3import * as Context from "effect/Context";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Path from "effect/Path";
7import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/http";
8​
9import { makeAntigravityUsageProbe } from "./antigravityUsageLimits.ts";
10​
11const summary = {
12 groups: [
13 {
14 displayName: "Gemini Models",
15 buckets: [
16 {
17 bucketId: "gemini-weekly",
18 window: "weekly",
19 remainingFraction: 0.96,
20 resetTime: "2026-10-12T19:41:43Z",
21 },
22 {
23 bucketId: "gemini-5h",
24 window: "5h",
25 remainingFraction: 0.91,
26 resetTime: "2026-10-09T16:06:01Z",
27 },
28 ],
29 },
30 {
31 displayName: "Claude and GPT models",
32 buckets: [
33 {
34 bucketId: "3p-weekly",
35 window: "weekly",
36 remainingFraction: 0,
37 resetTime: "2026-10-10T15:28:22Z",
38 },
39 {
40 bucketId: "3p-5h",
41 window: "5h",
42 remainingFraction: 0.44,
43 resetTime: "2026-10-09T16:06:30Z",
44 },
45 ],
46 },
47 ],
48};
49​
50const fixture = Effect.fn("AntigravityUsageTest.fixture")(function* (
51 options: {
52 summary?: unknown;
53 /** Per-host quota summaries; hosts not listed fall back to `summary`. */
54 summaryByHost?: Record<string, unknown>;
55 models?: unknown;
56 summaryStatus?: number;
57 /** Per-host summary statuses; hosts not listed fall back to `summaryStatus`. */
58 summaryStatusByHost?: Record<string, number>;
59 tokenStatus?: number;
60 refreshToken?: string;
61 userId?: string;
62 missingToken?: boolean;
63 authMethod?: "oauth-personal" | "gemini-api-key";
64 } = {},
65) {
66 const fs = yield* FileSystem.FileSystem;
67 const path = yield* Path.Path;
68 const profileDirectory = yield* fs.makeTempDirectoryScoped();
69 yield* fs.makeDirectory(path.join(profileDirectory, "antigravity-acp"));
70 const tokenPath = path.join(profileDirectory, "antigravity-acp", "acp_token.json");
71 const writeToken = (refreshToken: string) =>
72 fs.writeFileString(
73 tokenPath,
74 JSON.stringify({
75 client_id: "client-id",
76 client_secret: "client-secret",
77 refresh_token: refreshToken,
78 project_id: "project-id",
79 }),
80 );
81 if (!options.missingToken) yield* writeToken(options.refreshToken ?? "refresh-a");
82 const requests: Array<{ url: string; body: string }> = [];
83 const http = HttpClient.make((request, url, _signal, fiber) =>
84 Effect.sync(() => {
85 const init = Context.getOrUndefined(fiber.context, FetchHttpClient.RequestInit);
86 expect(init?.redirect).toBe("manual");
87 const body =
88 request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "";
89 requests.push({ url: request.url, body });
90 if (request.url.endsWith("/token")) {
91 expect(new URLSearchParams(body).get("grant_type")).toBe("refresh_token");
92 return HttpClientResponse.fromWeb(
93 request,
94 Response.json(
95 { access_token: "access-token", expires_in: 3600 },
96 { status: options.tokenStatus ?? 200 },
97 ),
98 );
99 }
100 expect(request.headers.authorization).toBe("Bearer access-token");
101 if (request.url.endsWith("/userinfo")) {
102 return HttpClientResponse.fromWeb(
103 request,
104 options.userId
105 ? Response.json({ id: options.userId, email: "someone@example.com" })
106 : Response.json({}, { status: 403 }),
107 );
108 }
109 expect(JSON.parse(body)).toEqual({ project: "project-id" });
110 return HttpClientResponse.fromWeb(
111 request,
112 request.url.endsWith(":retrieveUserQuotaSummary")
113 ? Response.json(options.summaryByHost?.[url.host] ?? options.summary ?? summary, {
114 status: options.summaryStatusByHost?.[url.host] ?? options.summaryStatus ?? 200,
115 })
116 : Response.json(options.models ?? { models: {} }),
117 );
118 }),
119 );
120 const usage = yield* makeAntigravityUsageProbe({
121 profileDirectory,
122 authMethod: options.authMethod ?? "oauth-personal",
123 }).pipe(Effect.provideService(HttpClient.HttpClient, http));
124 return { ...usage, requests, writeToken, tokenPath };
125});
126​
127describe("Antigravity subscription limits", () => {
128 it.effect("reports separate Gemini and shared Claude/GPT five-hour and weekly limits", () =>
129 Effect.gen(function* () {
130 const { probe, requests } = yield* fixture();
131 const limits = yield* probe;
132 expect(limits.windows).toHaveLength(4);
133 expect(limits.unavailable).toBeUndefined();
134 expect(limits.credentialFingerprint).toMatch(/^[0-9a-f]{64}$/);
135 const byId = new Map(limits.windows.map((window) => [window.id, window]));
136 expect(byId.get("gemini-weekly")?.usedPercent).toBeCloseTo(4);
137 expect(byId.get("gemini-5h")?.usedPercent).toBeCloseTo(9);
138 expect(byId.get("3p-weekly")).toMatchObject({
139 label: "Claude & GPT (shared) · Weekly",
140 kind: "weekly",
141 usedPercent: 100,
142 windowDurationMins: 10080,
143 resetsAt: "2026-10-10T15:28:22.000Z",
144 });
145 expect(byId.get("3p-5h")).toMatchObject({ kind: "session", windowDurationMins: 300 });
146 expect(byId.get("3p-5h")?.usedPercent).toBeCloseTo(56);
147 yield* probe;
148 expect(requests.filter((request) => request.url.endsWith("/token"))).toHaveLength(1);
149 expect(
150 requests.filter((request) => request.url.endsWith(":retrieveUserQuotaSummary")),
151 ).toHaveLength(4);
152 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
153 );
154​
155 it.effect("merges quota groups that only one endpoint reports", () =>
156 Effect.gen(function* () {
157 const { probe } = yield* fixture({
158 summaryByHost: {
159 // The daily endpoint can omit Gemini while the other endpoint returns all groups.
160 "daily-cloudcode-pa.googleapis.com": {
161 groups: [
162 {
163 displayName: "Claude and GPT models",
164 buckets: [
165 { bucketId: "3p-weekly", window: "weekly", remainingFraction: 0.5 },
166 { bucketId: "3p-5h", window: "5h", remainingFraction: 0.3 },
167 ],
168 },
169 ],
170 },
171 },
172 });
173 const limits = yield* probe;
174 expect(limits.windows.map((window) => window.id).toSorted()).toEqual([
175 "3p-5h",
176 "3p-weekly",
177 "gemini-5h",
178 "gemini-weekly",
179 ]);
180 const byId = new Map(limits.windows.map((window) => [window.id, window]));
181 expect(byId.get("gemini-weekly")?.label).toBe("Gemini · Weekly");
182 expect(byId.get("3p-5h")?.usedPercent).toBeCloseTo(70);
183 expect(byId.get("3p-weekly")?.usedPercent).toBe(100);
184 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
185 );
186​
187 it.effect("keeps one endpoint's quotas when the other fails", () =>
188 Effect.gen(function* () {
189 const { probe } = yield* fixture({
190 summaryStatusByHost: { "daily-cloudcode-pa.googleapis.com": 503 },
191 });
192 const limits = yield* probe;
193 expect(limits.unavailable).toBeUndefined();
194 expect(limits.windows).toHaveLength(4);
195 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
196 );
197​
198 it.effect("re-reads changed credentials and clears cached access after sign-out", () =>
199 Effect.gen(function* () {
200 const { probe, clear, requests, writeToken, tokenPath } = yield* fixture();
201 const first = yield* probe;
202 yield* writeToken("refresh-b");
203 const second = yield* probe;
204 expect(second.credentialFingerprint).not.toBe(first.credentialFingerprint);
205 expect(requests.filter((request) => request.url.endsWith("/token"))).toHaveLength(2);
206 yield* (yield* FileSystem.FileSystem).remove(tokenPath);
207 expect((yield* probe).unavailable?.reason).toBe("unsupported");
208 yield* writeToken("refresh-b");
209 yield* probe;
210 expect(requests.filter((request) => request.url.endsWith("/token"))).toHaveLength(3);
211 yield* clear;
212 yield* probe;
213 expect(requests.filter((request) => request.url.endsWith("/token"))).toHaveLength(4);
214 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
215 );
216​
217 it.effect("names one Google account the same way from every sign-in", () =>
218 Effect.gen(function* () {
219 const read = (refreshToken: string, userId: string) =>
220 fixture({ refreshToken, userId }).pipe(Effect.flatMap((usage) => usage.probe));
221 const machineA = yield* read("refresh-a", "google-user-1");
222 const machineB = yield* read("refresh-b", "google-user-1");
223 const otherAccount = yield* read("refresh-c", "google-user-2");
224 expect(machineA.credentialFingerprint).toMatch(/^[0-9a-f]{64}$/);
225 expect(machineB.credentialFingerprint).toBe(machineA.credentialFingerprint);
226 expect(otherAccount.credentialFingerprint).not.toBe(machineA.credentialFingerprint);
227 expect(JSON.stringify(machineA)).not.toMatch(/google-user-1|someone@example.com/);
228 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
229 );
230​
231 it.effect("falls back to model quotas without inventing a window duration", () =>
232 Effect.gen(function* () {
233 const { probe } = yield* fixture({
234 summaryStatus: 404,
235 models: {
236 models: {
237 "gemini-a": {
238 modelProvider: "MODEL_PROVIDER_GOOGLE",
239 quotaInfo: { remainingFraction: 0.8, resetTime: "2026-10-10T12:00:00Z" },
240 },
241 "gemini-b": {
242 modelProvider: "MODEL_PROVIDER_GOOGLE",
243 quotaInfo: { remainingFraction: 0.6, resetTime: "2026-10-10T12:00:00Z" },
244 },
245 "claude-a": { quotaInfo: { remainingFraction: 0.2 } },
246 },
247 },
248 });
249 const limits = yield* probe;
250 expect(limits.windows).toHaveLength(2);
251 expect(limits.windows.find((window) => window.id === "gemini-quota")?.usedPercent).toBe(40);
252 expect(
253 limits.windows.every(
254 (window) => window.kind === "other" && window.windowDurationMins === undefined,
255 ),
256 ).toBe(true);
257 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
258 );
259​
260 it.effect("skips disabled and missing fractions and clamps valid percentages", () =>
261 Effect.gen(function* () {
262 const { probe } = yield* fixture({
263 summary: {
264 buckets: [
265 { bucketId: "disabled", remainingFraction: 0, disabled: true },
266 { bucketId: "missing", resetTime: "2026-10-10T12:00:00Z" },
267 { bucketId: "gemini-5h", window: "5h", remainingFraction: 2, resetTime: "invalid" },
268 ],
269 },
270 });
271 expect((yield* probe).windows).toEqual([
272 {
273 id: "gemini-5h",
274 kind: "session",
275 label: "Gemini · 5-hour",
276 usedPercent: 0,
277 windowDurationMins: 300,
278 },
279 ]);
280 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
281 );
282​
283 it.effect("returns a safe failure when OAuth refresh fails", () =>
284 Effect.gen(function* () {
285 const { probe } = yield* fixture({ tokenStatus: 401 });
286 const limits = yield* probe;
287 expect(limits.windows).toEqual([]);
288 expect(limits.unavailable?.reason).toBe("probeFailed");
289 expect(JSON.stringify(limits)).not.toMatch(/client-secret|refresh-a|access-token/);
290 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
291 );
292​
293 it.effect("does not make network requests for API keys or missing sign-ins", () =>
294 Effect.gen(function* () {
295 for (const options of [{ authMethod: "gemini-api-key" as const }, { missingToken: true }]) {
296 const { probe, requests } = yield* fixture(options);
297 expect((yield* probe).unavailable?.reason).toBe("unsupported");
298 expect(requests).toEqual([]);
299 }
300 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
301 );
302});