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

antigravityUsageLimits.test.ts

268 lines10.5 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 models?: unknown;
54 summaryStatus?: number;
55 tokenStatus?: number;
56 refreshToken?: string;
57 userId?: string;
58 missingToken?: boolean;
59 authMethod?: "oauth-personal" | "gemini-api-key";
60 } = {},
61) {
62 const fs = yield* FileSystem.FileSystem;
63 const path = yield* Path.Path;
64 const profileDirectory = yield* fs.makeTempDirectoryScoped();
65 yield* fs.makeDirectory(path.join(profileDirectory, "antigravity-acp"));
66 const tokenPath = path.join(profileDirectory, "antigravity-acp", "acp_token.json");
67 const writeToken = (refreshToken: string) =>
68 fs.writeFileString(
69 tokenPath,
70 JSON.stringify({
71 client_id: "client-id",
72 client_secret: "client-secret",
73 refresh_token: refreshToken,
74 project_id: "project-id",
75 }),
76 );
77 if (!options.missingToken) yield* writeToken(options.refreshToken ?? "refresh-a");
78 const requests: Array<{ url: string; body: string }> = [];
79 const http = HttpClient.make((request, _url, _signal, fiber) =>
80 Effect.sync(() => {
81 const init = Context.getOrUndefined(fiber.context, FetchHttpClient.RequestInit);
82 expect(init?.redirect).toBe("manual");
83 const body =
84 request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "";
85 requests.push({ url: request.url, body });
86 if (request.url.endsWith("/token")) {
87 expect(new URLSearchParams(body).get("grant_type")).toBe("refresh_token");
88 return HttpClientResponse.fromWeb(
89 request,
90 Response.json(
91 { access_token: "access-token", expires_in: 3600 },
92 { status: options.tokenStatus ?? 200 },
93 ),
94 );
95 }
96 expect(request.headers.authorization).toBe("Bearer access-token");
97 if (request.url.endsWith("/userinfo")) {
98 return HttpClientResponse.fromWeb(
99 request,
100 options.userId
101 ? Response.json({ id: options.userId, email: "someone@example.com" })
102 : Response.json({}, { status: 403 }),
103 );
104 }
105 expect(JSON.parse(body)).toEqual({ project: "project-id" });
106 return HttpClientResponse.fromWeb(
107 request,
108 request.url.endsWith(":retrieveUserQuotaSummary")
109 ? Response.json(options.summary ?? summary, { status: options.summaryStatus ?? 200 })
110 : Response.json(options.models ?? { models: {} }),
111 );
112 }),
113 );
114 const usage = yield* makeAntigravityUsageProbe({
115 profileDirectory,
116 authMethod: options.authMethod ?? "oauth-personal",
117 }).pipe(Effect.provideService(HttpClient.HttpClient, http));
118 return { ...usage, requests, writeToken, tokenPath };
119});
120​
121describe("Antigravity subscription limits", () => {
122 it.effect("reports separate Gemini and shared Claude/GPT five-hour and weekly limits", () =>
123 Effect.gen(function* () {
124 const { probe, requests } = yield* fixture();
125 const limits = yield* probe;
126 expect(limits.windows).toHaveLength(4);
127 expect(limits.unavailable).toBeUndefined();
128 expect(limits.credentialFingerprint).toMatch(/^[0-9a-f]{64}$/);
129 const byId = new Map(limits.windows.map((window) => [window.id, window]));
130 expect(byId.get("gemini-weekly")?.usedPercent).toBeCloseTo(4);
131 expect(byId.get("gemini-5h")?.usedPercent).toBeCloseTo(9);
132 expect(byId.get("3p-weekly")).toMatchObject({
133 label: "Claude & GPT (shared) · Weekly",
134 kind: "weekly",
135 usedPercent: 100,
136 windowDurationMins: 10080,
137 resetsAt: "2026-10-10T15:28:22.000Z",
138 });
139 expect(byId.get("3p-5h")).toMatchObject({ kind: "session", windowDurationMins: 300 });
140 expect(byId.get("3p-5h")?.usedPercent).toBeCloseTo(56);
141 yield* probe;
142 expect(requests.filter((request) => request.url.endsWith("/token"))).toHaveLength(1);
143 expect(
144 requests.filter((request) => request.url.endsWith(":retrieveUserQuotaSummary")),
145 ).toHaveLength(2);
146 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
147 );
148​
149 it.effect("re-reads changed credentials and clears cached access after sign-out", () =>
150 Effect.gen(function* () {
151 const { probe, clear, requests, writeToken, tokenPath } = yield* fixture();
152 const first = yield* probe;
153 yield* writeToken("refresh-b");
154 const second = yield* probe;
155 expect(second.credentialFingerprint).not.toBe(first.credentialFingerprint);
156 expect(requests.filter((request) => request.url.endsWith("/token"))).toHaveLength(2);
157 yield* (yield* FileSystem.FileSystem).remove(tokenPath);
158 expect((yield* probe).unavailable?.reason).toBe("unsupported");
159 yield* writeToken("refresh-b");
160 yield* probe;
161 expect(requests.filter((request) => request.url.endsWith("/token"))).toHaveLength(3);
162 yield* clear;
163 yield* probe;
164 expect(requests.filter((request) => request.url.endsWith("/token"))).toHaveLength(4);
165 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
166 );
167​
168 it.effect("names one Google account the same way from every sign-in", () =>
169 Effect.gen(function* () {
170 const read = (refreshToken: string, userId: string) =>
171 fixture({ refreshToken, userId }).pipe(Effect.flatMap((usage) => usage.probe));
172 const machineA = yield* read("refresh-a", "google-user-1");
173 const machineB = yield* read("refresh-b", "google-user-1");
174 const otherAccount = yield* read("refresh-c", "google-user-2");
175 expect(machineA.credentialFingerprint).toMatch(/^[0-9a-f]{64}$/);
176 expect(machineB.credentialFingerprint).toBe(machineA.credentialFingerprint);
177 expect(otherAccount.credentialFingerprint).not.toBe(machineA.credentialFingerprint);
178 expect(JSON.stringify(machineA)).not.toMatch(/google-user-1|someone@example.com/);
179 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
180 );
181​
182 it.effect("falls back to model quotas without inventing a window duration", () =>
183 Effect.gen(function* () {
184 const { probe } = yield* fixture({
185 summaryStatus: 404,
186 models: {
187 models: {
188 "gemini-a": {
189 modelProvider: "MODEL_PROVIDER_GOOGLE",
190 quotaInfo: { remainingFraction: 0.8, resetTime: "2026-10-10T12:00:00Z" },
191 },
192 "gemini-b": {
193 modelProvider: "MODEL_PROVIDER_GOOGLE",
194 quotaInfo: { remainingFraction: 0.6, resetTime: "2026-10-10T12:00:00Z" },
195 },
196 "claude-a": { quotaInfo: { remainingFraction: 0.2 } },
197 },
198 },
199 });
200 const limits = yield* probe;
201 expect(limits.windows).toHaveLength(2);
202 expect(limits.windows.find((window) => window.id === "gemini-quota")?.usedPercent).toBe(40);
203 expect(
204 limits.windows.every(
205 (window) => window.kind === "other" && window.windowDurationMins === undefined,
206 ),
207 ).toBe(true);
208 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
209 );
210​
211 it.effect("skips disabled and missing fractions and clamps valid percentages", () =>
212 Effect.gen(function* () {
213 const { probe } = yield* fixture({
214 summary: {
215 buckets: [
216 { bucketId: "disabled", remainingFraction: 0, disabled: true },
217 { bucketId: "missing", resetTime: "2026-10-10T12:00:00Z" },
218 { bucketId: "gemini-5h", window: "5h", remainingFraction: 2, resetTime: "invalid" },
219 ],
220 },
221 });
222 expect((yield* probe).windows).toEqual([
223 {
224 id: "gemini-5h",
225 kind: "session",
226 label: "Gemini · 5-hour",
227 usedPercent: 0,
228 windowDurationMins: 300,
229 },
230 ]);
231 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
232 );
233​
234 it.effect("preserves cached access token when quota endpoints return no usable windows", () =>
235 Effect.gen(function* () {
236 const { probe, requests } = yield* fixture({
237 summary: { groups: [] },
238 models: { models: {} },
239 });
240 const first = yield* probe;
241 expect(first.unavailable?.reason).toBe("probeFailed");
242 expect(requests.filter((request) => request.url.endsWith("/token"))).toHaveLength(1);
243 const second = yield* probe;
244 expect(second.unavailable?.reason).toBe("probeFailed");
245 expect(requests.filter((request) => request.url.endsWith("/token"))).toHaveLength(1);
246 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
247 );
248​
249 it.effect("returns a safe failure when OAuth refresh fails", () =>
250 Effect.gen(function* () {
251 const { probe } = yield* fixture({ tokenStatus: 401 });
252 const limits = yield* probe;
253 expect(limits.windows).toEqual([]);
254 expect(limits.unavailable?.reason).toBe("probeFailed");
255 expect(JSON.stringify(limits)).not.toMatch(/client-secret|refresh-a|access-token/);
256 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
257 );
258​
259 it.effect("does not make network requests for API keys or missing sign-ins", () =>
260 Effect.gen(function* () {
261 for (const options of [{ authMethod: "gemini-api-key" as const }, { missingToken: true }]) {
262 const { probe, requests } = yield* fixture(options);
263 expect((yield* probe).unavailable?.reason).toBe("unsupported");
264 expect(requests).toEqual([]);
265 }
266 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
267 );
268});