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

antigravityUsageLimits.test.ts

306 lines12.0 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 // Both quota endpoints are read on every probe.
150 expect(
151 requests.filter((request) => request.url.endsWith(":retrieveUserQuotaSummary")),
152 ).toHaveLength(4);
153 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
154 );
155​
156 it.effect("merges quota groups that only one endpoint reports", () =>
157 Effect.gen(function* () {
158 const { probe } = yield* fixture({
159 summaryByHost: {
160 // The daily endpoint has answered with only the Claude/GPT group; the
161 // other endpoint returns the full default summary.
162 "daily-cloudcode-pa.googleapis.com": {
163 groups: [
164 {
165 displayName: "Claude and GPT models",
166 buckets: [
167 { bucketId: "3p-weekly", window: "weekly", remainingFraction: 0.5 },
168 { bucketId: "3p-5h", window: "5h", remainingFraction: 0.3 },
169 ],
170 },
171 ],
172 },
173 },
174 });
175 const limits = yield* probe;
176 expect(limits.windows.map((window) => window.id).toSorted()).toEqual([
177 "3p-5h",
178 "3p-weekly",
179 "gemini-5h",
180 "gemini-weekly",
181 ]);
182 const byId = new Map(limits.windows.map((window) => [window.id, window]));
183 expect(byId.get("gemini-weekly")?.label).toBe("Gemini · Weekly");
184 // When endpoints disagree about a bucket, the most-used reading wins,
185 // whichever endpoint reported it.
186 expect(byId.get("3p-5h")?.usedPercent).toBeCloseTo(70);
187 expect(byId.get("3p-weekly")?.usedPercent).toBe(100);
188 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
189 );
190​
191 it.effect("keeps one endpoint's quotas when the other fails", () =>
192 Effect.gen(function* () {
193 const { probe } = yield* fixture({
194 summaryStatusByHost: { "daily-cloudcode-pa.googleapis.com": 503 },
195 });
196 const limits = yield* probe;
197 expect(limits.unavailable).toBeUndefined();
198 expect(limits.windows).toHaveLength(4);
199 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
200 );
201​
202 it.effect("re-reads changed credentials and clears cached access after sign-out", () =>
203 Effect.gen(function* () {
204 const { probe, clear, requests, writeToken, tokenPath } = yield* fixture();
205 const first = yield* probe;
206 yield* writeToken("refresh-b");
207 const second = yield* probe;
208 expect(second.credentialFingerprint).not.toBe(first.credentialFingerprint);
209 expect(requests.filter((request) => request.url.endsWith("/token"))).toHaveLength(2);
210 yield* (yield* FileSystem.FileSystem).remove(tokenPath);
211 expect((yield* probe).unavailable?.reason).toBe("unsupported");
212 yield* writeToken("refresh-b");
213 yield* probe;
214 expect(requests.filter((request) => request.url.endsWith("/token"))).toHaveLength(3);
215 yield* clear;
216 yield* probe;
217 expect(requests.filter((request) => request.url.endsWith("/token"))).toHaveLength(4);
218 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
219 );
220​
221 it.effect("names one Google account the same way from every sign-in", () =>
222 Effect.gen(function* () {
223 const read = (refreshToken: string, userId: string) =>
224 fixture({ refreshToken, userId }).pipe(Effect.flatMap((usage) => usage.probe));
225 const machineA = yield* read("refresh-a", "google-user-1");
226 const machineB = yield* read("refresh-b", "google-user-1");
227 const otherAccount = yield* read("refresh-c", "google-user-2");
228 expect(machineA.credentialFingerprint).toMatch(/^[0-9a-f]{64}$/);
229 expect(machineB.credentialFingerprint).toBe(machineA.credentialFingerprint);
230 expect(otherAccount.credentialFingerprint).not.toBe(machineA.credentialFingerprint);
231 expect(JSON.stringify(machineA)).not.toMatch(/google-user-1|someone@example.com/);
232 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
233 );
234​
235 it.effect("falls back to model quotas without inventing a window duration", () =>
236 Effect.gen(function* () {
237 const { probe } = yield* fixture({
238 summaryStatus: 404,
239 models: {
240 models: {
241 "gemini-a": {
242 modelProvider: "MODEL_PROVIDER_GOOGLE",
243 quotaInfo: { remainingFraction: 0.8, resetTime: "2026-10-10T12:00:00Z" },
244 },
245 "gemini-b": {
246 modelProvider: "MODEL_PROVIDER_GOOGLE",
247 quotaInfo: { remainingFraction: 0.6, resetTime: "2026-10-10T12:00:00Z" },
248 },
249 "claude-a": { quotaInfo: { remainingFraction: 0.2 } },
250 },
251 },
252 });
253 const limits = yield* probe;
254 expect(limits.windows).toHaveLength(2);
255 expect(limits.windows.find((window) => window.id === "gemini-quota")?.usedPercent).toBe(40);
256 expect(
257 limits.windows.every(
258 (window) => window.kind === "other" && window.windowDurationMins === undefined,
259 ),
260 ).toBe(true);
261 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
262 );
263​
264 it.effect("skips disabled and missing fractions and clamps valid percentages", () =>
265 Effect.gen(function* () {
266 const { probe } = yield* fixture({
267 summary: {
268 buckets: [
269 { bucketId: "disabled", remainingFraction: 0, disabled: true },
270 { bucketId: "missing", resetTime: "2026-10-10T12:00:00Z" },
271 { bucketId: "gemini-5h", window: "5h", remainingFraction: 2, resetTime: "invalid" },
272 ],
273 },
274 });
275 expect((yield* probe).windows).toEqual([
276 {
277 id: "gemini-5h",
278 kind: "session",
279 label: "Gemini · 5-hour",
280 usedPercent: 0,
281 windowDurationMins: 300,
282 },
283 ]);
284 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
285 );
286​
287 it.effect("returns a safe failure when OAuth refresh fails", () =>
288 Effect.gen(function* () {
289 const { probe } = yield* fixture({ tokenStatus: 401 });
290 const limits = yield* probe;
291 expect(limits.windows).toEqual([]);
292 expect(limits.unavailable?.reason).toBe("probeFailed");
293 expect(JSON.stringify(limits)).not.toMatch(/client-secret|refresh-a|access-token/);
294 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
295 );
296​
297 it.effect("does not make network requests for API keys or missing sign-ins", () =>
298 Effect.gen(function* () {
299 for (const options of [{ authMethod: "gemini-api-key" as const }, { missingToken: true }]) {
300 const { probe, requests } = yield* fixture(options);
301 expect((yield* probe).unavailable?.reason).toBe("unsupported");
302 expect(requests).toEqual([]);
303 }
304 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
305 );
306});