Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { describe, expect, it } from "@effect/vitest";
3import * as Context from "effect/Context";
4import * as DateTime from "effect/DateTime";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as Path from "effect/Path";
8import * as TestClock from "effect/testing/TestClock";
9import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/http";
10
11import { makeAntigravityUsageProbe } from "./antigravityUsageLimits.ts";
12
13const summary = {
14 groups: [
15 {
16 displayName: "Gemini Models",
17 buckets: [
18 {
19 bucketId: "gemini-weekly",
20 window: "weekly",
21 remainingFraction: 0.96,
22 resetTime: "2026-10-12T19:41:43Z",
23 },
24 {
25 bucketId: "gemini-5h",
26 window: "5h",
27 remainingFraction: 0.91,
28 resetTime: "2026-10-09T16:06:01Z",
29 },
30 ],
31 },
32 {
33 displayName: "Claude and GPT models",
34 buckets: [
35 {
36 bucketId: "3p-weekly",
37 window: "weekly",
38 remainingFraction: 0,
39 resetTime: "2026-10-10T15:28:22Z",
40 },
41 {
42 bucketId: "3p-5h",
43 window: "5h",
44 remainingFraction: 0.44,
45 resetTime: "2026-10-09T16:06:30Z",
46 },
47 ],
48 },
49 ],
50};
51
52const fixture = Effect.fn("AntigravityUsageTest.fixture")(function* (
53 options: {
54 summary?: unknown;
55 /** Per-host quota summaries; hosts not listed fall back to `summary`. */
56 summaryByHost?: Record<string, unknown>;
57 models?: unknown;
58 summaryStatus?: number;
59 /** Per-host summary statuses; hosts not listed fall back to `summaryStatus`. */
60 summaryStatusByHost?: Record<string, number>;
61 tokenStatus?: number;
62 refreshToken?: string;
63 userId?: string;
64 userInfoAt?: number;
65 missingToken?: boolean;
66 authMethod?: "oauth-personal" | "gemini-api-key";
67 } = {},
68) {
69 const fs = yield* FileSystem.FileSystem;
70 const path = yield* Path.Path;
71 const profileDirectory = yield* fs.makeTempDirectoryScoped();
72 yield* fs.makeDirectory(path.join(profileDirectory, "antigravity-acp"));
73 const tokenPath = path.join(profileDirectory, "antigravity-acp", "acp_token.json");
74 const writeToken = (refreshToken: string) =>
75 fs.writeFileString(
76 tokenPath,
77 JSON.stringify({
78 client_id: "client-id",
79 client_secret: "client-secret",
80 refresh_token: refreshToken,
81 project_id: "project-id",
82 }),
83 );
84 if (!options.missingToken) yield* writeToken(options.refreshToken ?? "refresh-a");
85 const requests: Array<{ url: string; body: string }> = [];
86 const http = HttpClient.make((request, url, _signal, fiber) =>
87 Effect.sync(() => {
88 const init = Context.getOrUndefined(fiber.context, FetchHttpClient.RequestInit);
89 expect(init?.redirect).toBe("manual");
90 const body =
91 request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "";
92 requests.push({ url: request.url, body });
93 if (request.url.endsWith("/token")) {
94 expect(new URLSearchParams(body).get("grant_type")).toBe("refresh_token");
95 return HttpClientResponse.fromWeb(
96 request,
97 Response.json(
98 { access_token: "access-token", expires_in: 3600 },
99 { status: options.tokenStatus ?? 200 },
100 ),
101 );
102 }
103 expect(request.headers.authorization).toBe("Bearer access-token");
104 if (request.url.endsWith("/userinfo")) {
105 return HttpClientResponse.fromWeb(
106 request,
107 options.userId
108 ? Response.json({ id: options.userId, email: "someone@example.com" })
109 : Response.json({}, { status: 403 }),
110 );
111 }
112 expect(JSON.parse(body)).toEqual({ project: "project-id" });
113 expect(request.headers["user-agent"]).toMatch(/^antigravity\/hub\/2\.24\.0 /);
114 return HttpClientResponse.fromWeb(
115 request,
116 request.url.endsWith(":retrieveUserQuotaSummary")
117 ? Response.json(options.summaryByHost?.[url.host] ?? options.summary ?? summary, {
118 status: options.summaryStatusByHost?.[url.host] ?? options.summaryStatus ?? 200,
119 })
120 : Response.json(options.models ?? { models: {} }),
121 );
122 }).pipe(
123 Effect.tap(() =>
124 request.url.endsWith("/userinfo") && options.userInfoAt !== undefined
125 ? TestClock.setTime(options.userInfoAt)
126 : Effect.void,
127 ),
128 ),
129 );
130 const usage = yield* makeAntigravityUsageProbe({
131 profileDirectory,
132 authMethod: options.authMethod ?? "oauth-personal",
133 }).pipe(Effect.provideService(HttpClient.HttpClient, http));
134 return { ...usage, requests, writeToken, tokenPath };
135});
136
137describe("Antigravity subscription limits", () => {
138 // Oracle: the 10:16 UTC payload and its narrow Workaround rule.
139 it.effect("omits rolling resets for untouched summary buckets and keeps used Gemini resets", () =>
140 Effect.gen(function* () {
141 yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-21T10:16:04Z")));
142 const { probe } = yield* fixture({
143 summary: {
144 groups: [
145 {
146 buckets: [
147 {
148 bucketId: "3p-5h",
149 window: "5h",
150 remainingFraction: 1,
151 resetTime: "2026-10-21T15:16:05Z",
152 },
153 {
154 bucketId: "3p-weekly",
155 window: "weekly",
156 remainingFraction: 1,
157 resetTime: "2026-10-28T10:16:05Z",
158 },
159 {
160 bucketId: "gemini-5h",
161 window: "5h",
162 remainingFraction: 0.848104,
163 resetTime: "2026-10-21T13:29:53Z",
164 description:
165 "You have used some of your 5-hour limit, it will fully refresh in 3 hours, 13 minutes.",
166 },
167 {
168 bucketId: "gemini-weekly",
169 window: "weekly",
170 remainingFraction: 0.9620177,
171 resetTime: "2026-10-28T08:29:53Z",
172 description:
173 "You have used some of your weekly limit, it will fully refresh in 6 days, 22 hours.",
174 },
175 ],
176 },
177 ],
178 },
179 });
180 const limits = yield* probe;
181 const byId = new Map(limits.windows.map((window) => [window.id, window]));
182 expect(byId.get("3p-5h")).toEqual({
183 id: "3p-5h",
184 label: "Claude & GPT (shared) · 5-hour",
185 kind: "session",
186 usedPercent: 0,
187 windowDurationMins: 300,
188 });
189 expect(byId.get("3p-weekly")).toEqual({
190 id: "3p-weekly",
191 label: "Claude & GPT (shared) · Weekly",
192 kind: "weekly",
193 usedPercent: 0,
194 windowDurationMins: 10080,
195 });
196 expect(byId.get("gemini-5h")?.resetsAt).toBe("2026-10-21T13:29:53.000Z");
197 expect(byId.get("gemini-weekly")?.resetsAt).toBe("2026-10-28T08:29:53.000Z");
198 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
199 );
200
201 // Oracle: measure the tolerance from the summary request, after auth.
202 it.effect("uses summary request time after authentication for the reset tolerance", () =>
203 Effect.gen(function* () {
204 yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-21T10:16:02Z")));
205 const { probe } = yield* fixture({
206 userInfoAt: DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-21T10:16:04Z")),
207 summary: {
208 buckets: [
209 {
210 bucketId: "3p-5h",
211 window: "5h",
212 remainingFraction: 1,
213 resetTime: "2026-10-21T15:17:03Z",
214 },
215 ],
216 },
217 });
218 expect((yield* probe).windows[0]?.resetsAt).toBeUndefined();
219 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
220 );
221
222 // Oracle: keep descriptions, measured resets, and spent buckets.
223 it.effect("keeps summary resets with a description, a distant reset, or no quota left", () =>
224 Effect.gen(function* () {
225 yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-21T10:16:04Z")));
226 const { probe } = yield* fixture({
227 summary: {
228 buckets: [
229 {
230 bucketId: "described",
231 window: "5h",
232 remainingFraction: 1,
233 description: "Reported reset",
234 resetTime: "2026-10-21T15:16:04Z",
235 },
236 {
237 bucketId: "distant",
238 window: "weekly",
239 remainingFraction: 1,
240 resetTime: "2026-10-28T12:16:04Z",
241 },
242 {
243 bucketId: "spent",
244 window: "5h",
245 remainingFraction: 0,
246 resetTime: "2026-10-21T15:16:04Z",
247 },
248 {
249 bucketId: "overfull",
250 window: "5h",
251 remainingFraction: 1.01,
252 resetTime: "2026-10-21T15:16:04Z",
253 },
254 {
255 bucketId: "empty-description",
256 window: "5h",
257 remainingFraction: 1,
258 description: "",
259 resetTime: "2026-10-21T15:16:04Z",
260 },
261 ],
262 },
263 });
264 expect((yield* probe).windows.map(({ id, resetsAt }) => ({ id, resetsAt }))).toEqual([
265 { id: "described", resetsAt: "2026-10-21T15:16:04.000Z" },
266 { id: "empty-description", resetsAt: "2026-10-21T15:16:04.000Z" },
267 { id: "overfull", resetsAt: "2026-10-21T15:16:04.000Z" },
268 { id: "spent", resetsAt: "2026-10-21T15:16:04.000Z" },
269 { id: "distant", resetsAt: "2026-10-28T12:16:04.000Z" },
270 ]);
271 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
272 );
273
274 // Oracle: the 60-second tolerance applies to both known window lengths.
275 it.effect("omits summary resets 59 seconds away but keeps resets 61 seconds away", () =>
276 Effect.gen(function* () {
277 yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-21T10:16:04Z")));
278 const { probe } = yield* fixture({
279 summary: {
280 buckets: [
281 {
282 bucketId: "5h-before",
283 window: "5h",
284 remainingFraction: 1,
285 resetTime: "2026-10-21T15:15:05Z",
286 },
287 {
288 bucketId: "5h-after",
289 window: "5h",
290 remainingFraction: 1,
291 resetTime: "2026-10-21T15:17:05Z",
292 },
293 {
294 bucketId: "5h-edge",
295 window: "5h",
296 remainingFraction: 1,
297 resetTime: "2026-10-21T15:17:04Z",
298 },
299 {
300 bucketId: "weekly-after",
301 window: "weekly",
302 remainingFraction: 1,
303 resetTime: "2026-10-28T10:17:03Z",
304 },
305 {
306 bucketId: "weekly-before",
307 window: "weekly",
308 remainingFraction: 1,
309 resetTime: "2026-10-28T10:15:03Z",
310 },
311 {
312 bucketId: "weekly-edge",
313 window: "weekly",
314 remainingFraction: 1,
315 resetTime: "2026-10-28T10:15:04Z",
316 },
317 ],
318 },
319 });
320 expect((yield* probe).windows.map(({ id, resetsAt }) => ({ id, resetsAt }))).toEqual([
321 { id: "5h-after", resetsAt: "2026-10-21T15:17:05.000Z" },
322 { id: "5h-before", resetsAt: undefined },
323 { id: "5h-edge", resetsAt: undefined },
324 { id: "weekly-after", resetsAt: undefined },
325 { id: "weekly-before", resetsAt: "2026-10-28T10:15:03.000Z" },
326 { id: "weekly-edge", resetsAt: undefined },
327 ]);
328 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
329 );
330
331 // Oracle: the existing endpoint merge keeps the most-used reading.
332 it.effect("keeps the used endpoint reading and its reset over an untouched reading", () =>
333 Effect.gen(function* () {
334 yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-21T10:16:04Z")));
335 const { probe } = yield* fixture({
336 summaryByHost: {
337 "daily-cloudcode-pa.googleapis.com": {
338 buckets: [
339 {
340 bucketId: "3p-5h",
341 window: "5h",
342 remainingFraction: 1,
343 resetTime: "2026-10-21T15:16:04Z",
344 },
345 {
346 bucketId: "3p-weekly",
347 window: "weekly",
348 remainingFraction: 0.5,
349 resetTime: "2026-10-27T10:16:04Z",
350 },
351 ],
352 },
353 "cloudcode-pa.googleapis.com": {
354 buckets: [
355 {
356 bucketId: "3p-5h",
357 window: "5h",
358 remainingFraction: 0.5,
359 resetTime: "2026-10-21T13:16:04Z",
360 },
361 {
362 bucketId: "3p-weekly",
363 window: "weekly",
364 remainingFraction: 1,
365 resetTime: "2026-10-28T10:16:04Z",
366 },
367 ],
368 },
369 },
370 });
371 expect((yield* probe).windows).toEqual([
372 {
373 id: "3p-5h",
374 label: "Claude & GPT (shared) · 5-hour",
375 kind: "session",
376 usedPercent: 50,
377 windowDurationMins: 300,
378 resetsAt: "2026-10-21T13:16:04.000Z",
379 },
380 {
381 id: "3p-weekly",
382 label: "Claude & GPT (shared) · Weekly",
383 kind: "weekly",
384 usedPercent: 50,
385 windowDurationMins: 10080,
386 resetsAt: "2026-10-27T10:16:04.000Z",
387 },
388 ]);
389 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
390 );
391
392 // Oracle: model quotas have no evidence for the summary-only rule.
393 it.effect("keeps full model fallback resets even at a full window from the request", () =>
394 Effect.gen(function* () {
395 yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-21T10:16:04Z")));
396 const { probe } = yield* fixture({
397 summaryStatus: 404,
398 models: {
399 models: {
400 "gemini-a": {
401 quotaInfo: { remainingFraction: 1, resetTime: "2026-10-21T15:16:04Z" },
402 weeklyQuotaInfo: { remainingFraction: 1, resetTime: "2026-10-28T10:16:04Z" },
403 },
404 },
405 },
406 });
407 expect(
408 (yield* probe).windows.map(({ id, resetsAt, windowDurationMins }) => ({
409 id,
410 resetsAt,
411 windowDurationMins,
412 })),
413 ).toEqual([
414 { id: "gemini-weekly", resetsAt: "2026-10-28T10:16:04.000Z", windowDurationMins: 10080 },
415 { id: "gemini-quota", resetsAt: "2026-10-21T15:16:04.000Z", windowDurationMins: undefined },
416 ]);
417 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
418 );
419
420 it.effect("reports separate Gemini and shared Claude/GPT five-hour and weekly limits", () =>
421 Effect.gen(function* () {
422 const { probe, requests } = yield* fixture();
423 const limits = yield* probe;
424 expect(limits.windows).toHaveLength(4);
425 expect(limits.unavailable).toBeUndefined();
426 expect(limits.credentialFingerprint).toMatch(/^[0-9a-f]{64}$/);
427 const byId = new Map(limits.windows.map((window) => [window.id, window]));
428 expect(byId.get("gemini-weekly")?.usedPercent).toBeCloseTo(4);
429 expect(byId.get("gemini-5h")?.usedPercent).toBeCloseTo(9);
430 expect(byId.get("3p-weekly")).toMatchObject({
431 label: "Claude & GPT (shared) · Weekly",
432 kind: "weekly",
433 usedPercent: 100,
434 windowDurationMins: 10080,
435 resetsAt: "2026-10-10T15:28:22.000Z",
436 });
437 expect(byId.get("3p-5h")).toMatchObject({ kind: "session", windowDurationMins: 300 });
438 expect(byId.get("3p-5h")?.usedPercent).toBeCloseTo(56);
439 yield* probe;
440 expect(requests.filter((request) => request.url.endsWith("/token"))).toHaveLength(1);
441 expect(
442 requests.filter((request) => request.url.endsWith(":retrieveUserQuotaSummary")),
443 ).toHaveLength(4);
444 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
445 );
446
447 it.effect("merges quota groups that only one endpoint reports", () =>
448 Effect.gen(function* () {
449 const { probe } = yield* fixture({
450 summaryByHost: {
451 // The daily endpoint can omit Gemini while the other endpoint returns all groups.
452 "daily-cloudcode-pa.googleapis.com": {
453 groups: [
454 {
455 displayName: "Claude and GPT models",
456 buckets: [
457 { bucketId: "3p-weekly", window: "weekly", remainingFraction: 0.5 },
458 { bucketId: "3p-5h", window: "5h", remainingFraction: 0.3 },
459 ],
460 },
461 ],
462 },
463 },
464 });
465 const limits = yield* probe;
466 expect(limits.windows.map((window) => window.id).toSorted()).toEqual([
467 "3p-5h",
468 "3p-weekly",
469 "gemini-5h",
470 "gemini-weekly",
471 ]);
472 const byId = new Map(limits.windows.map((window) => [window.id, window]));
473 expect(byId.get("gemini-weekly")?.label).toBe("Gemini · Weekly");
474 expect(byId.get("3p-5h")?.usedPercent).toBeCloseTo(70);
475 expect(byId.get("3p-weekly")?.usedPercent).toBe(100);
476 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
477 );
478
479 it.effect("labels Argon's weekly quota apart from the default Gemini weekly quota", () =>
480 Effect.gen(function* () {
481 const { probe } = yield* fixture({
482 summary: {
483 groups: [
484 ...summary.groups,
485 {
486 displayName: "Gemini 4 Argon",
487 buckets: [
488 { bucketId: "gemini-argon-wtu-weekly", window: "weekly", remainingFraction: 0.6 },
489 ],
490 },
491 ],
492 },
493 });
494 const limits = yield* probe;
495 const byId = new Map(limits.windows.map((window) => [window.id, window]));
496 expect(byId.get("gemini-weekly")?.label).toBe("Gemini · Weekly");
497 expect(byId.get("gemini-argon-wtu-weekly")?.label).toBe("Gemini 4 Argon · Weekly");
498 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
499 );
500
501 it.effect("keeps one endpoint's quotas when the other fails", () =>
502 Effect.gen(function* () {
503 const { probe } = yield* fixture({
504 summaryStatusByHost: { "daily-cloudcode-pa.googleapis.com": 503 },
505 });
506 const limits = yield* probe;
507 expect(limits.unavailable).toBeUndefined();
508 expect(limits.windows).toHaveLength(4);
509 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
510 );
511
512 it.effect("re-reads changed credentials and clears cached access after sign-out", () =>
513 Effect.gen(function* () {
514 const { probe, clear, requests, writeToken, tokenPath } = yield* fixture();
515 const first = yield* probe;
516 yield* writeToken("refresh-b");
517 const second = yield* probe;
518 expect(second.credentialFingerprint).not.toBe(first.credentialFingerprint);
519 expect(requests.filter((request) => request.url.endsWith("/token"))).toHaveLength(2);
520 yield* (yield* FileSystem.FileSystem).remove(tokenPath);
521 expect((yield* probe).unavailable?.reason).toBe("unsupported");
522 yield* writeToken("refresh-b");
523 yield* probe;
524 expect(requests.filter((request) => request.url.endsWith("/token"))).toHaveLength(3);
525 yield* clear;
526 yield* probe;
527 expect(requests.filter((request) => request.url.endsWith("/token"))).toHaveLength(4);
528 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
529 );
530
531 it.effect("names one Google account the same way from every sign-in", () =>
532 Effect.gen(function* () {
533 const read = (refreshToken: string, userId: string) =>
534 fixture({ refreshToken, userId }).pipe(Effect.flatMap((usage) => usage.probe));
535 const machineA = yield* read("refresh-a", "google-user-1");
536 const machineB = yield* read("refresh-b", "google-user-1");
537 const otherAccount = yield* read("refresh-c", "google-user-2");
538 expect(machineA.credentialFingerprint).toMatch(/^[0-9a-f]{64}$/);
539 expect(machineB.credentialFingerprint).toBe(machineA.credentialFingerprint);
540 expect(otherAccount.credentialFingerprint).not.toBe(machineA.credentialFingerprint);
541 expect(JSON.stringify(machineA)).not.toMatch(/google-user-1|someone@example.com/);
542 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
543 );
544
545 it.effect("falls back to model quotas without inventing a window duration", () =>
546 Effect.gen(function* () {
547 const { probe } = yield* fixture({
548 summaryStatus: 404,
549 models: {
550 models: {
551 "gemini-a": {
552 modelProvider: "MODEL_PROVIDER_GOOGLE",
553 quotaInfo: { remainingFraction: 0.8, resetTime: "2026-10-10T12:00:00Z" },
554 },
555 "gemini-b": {
556 modelProvider: "MODEL_PROVIDER_GOOGLE",
557 quotaInfo: { remainingFraction: 0.6, resetTime: "2026-10-10T12:00:00Z" },
558 },
559 "claude-a": { quotaInfo: { remainingFraction: 0.2 } },
560 },
561 },
562 });
563 const limits = yield* probe;
564 expect(limits.windows).toHaveLength(2);
565 expect(limits.windows.find((window) => window.id === "gemini-quota")?.usedPercent).toBe(40);
566 expect(
567 limits.windows.every(
568 (window) => window.kind === "other" && window.windowDurationMins === undefined,
569 ),
570 ).toBe(true);
571 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
572 );
573
574 it.effect("skips disabled and missing fractions and clamps valid percentages", () =>
575 Effect.gen(function* () {
576 const { probe } = yield* fixture({
577 summary: {
578 buckets: [
579 { bucketId: "disabled", remainingFraction: 0, disabled: true },
580 { bucketId: "missing", resetTime: "2026-10-10T12:00:00Z" },
581 { bucketId: "gemini-5h", window: "5h", remainingFraction: 2, resetTime: "invalid" },
582 ],
583 },
584 });
585 expect((yield* probe).windows).toEqual([
586 {
587 id: "gemini-5h",
588 kind: "session",
589 label: "Gemini · 5-hour",
590 usedPercent: 0,
591 windowDurationMins: 300,
592 },
593 ]);
594 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
595 );
596
597 it.effect("returns a safe failure when OAuth refresh fails", () =>
598 Effect.gen(function* () {
599 const { probe } = yield* fixture({ tokenStatus: 401 });
600 const limits = yield* probe;
601 expect(limits.windows).toEqual([]);
602 expect(limits.unavailable?.reason).toBe("probeFailed");
603 expect(JSON.stringify(limits)).not.toMatch(/client-secret|refresh-a|access-token/);
604 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
605 );
606
607 it.effect("does not make network requests for API keys or missing sign-ins", () =>
608 Effect.gen(function* () {
609 for (const options of [{ authMethod: "gemini-api-key" as const }, { missingToken: true }]) {
610 const { probe, requests } = yield* fixture(options);
611 expect((yield* probe).unavailable?.reason).toBe("unsupported");
612 expect(requests).toEqual([]);
613 }
614 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
615 );
616});