The best way to control Claude Code, Codex and more from any computer or phone

main
ts 786 lines 30.6 KB
Raw
1 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2 import * as NodeServices from "@effect/platform-node/NodeServices";
3 import * as HostProcess from "@t3tools/shared/HostProcess";
4 import * as Layer from "effect/Layer";
5 import { describe, expect, it } from "@effect/vitest";
6 import * as Context from "effect/Context";
7 import * as DateTime from "effect/DateTime";
8 import * as Effect from "effect/Effect";
9 import * as FileSystem from "effect/FileSystem";
10 import * as Path from "effect/Path";
11 import * as TestClock from "effect/testing/TestClock";
12 import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/http";
13
14 import {
15 decodeGoKeyringSecret,
16 makeAntigravityUsageProbe,
17 readWindowsCliCredential,
18 } from "./antigravityUsageLimits.ts";
19
20 const summary = {
21 groups: [
22 {
23 displayName: "Gemini Models",
24 buckets: [
25 {
26 bucketId: "gemini-weekly",
27 window: "weekly",
28 remainingFraction: 0.96,
29 resetTime: "2026-10-12T19:41:43Z",
30 },
31 {
32 bucketId: "gemini-5h",
33 window: "5h",
34 remainingFraction: 0.91,
35 resetTime: "2026-10-09T16:06:01Z",
36 },
37 ],
38 },
39 {
40 displayName: "Claude and GPT models",
41 buckets: [
42 {
43 bucketId: "3p-weekly",
44 window: "weekly",
45 remainingFraction: 0,
46 resetTime: "2026-10-10T15:28:22Z",
47 },
48 {
49 bucketId: "3p-5h",
50 window: "5h",
51 remainingFraction: 0.44,
52 resetTime: "2026-10-09T16:06:30Z",
53 },
54 ],
55 },
56 ],
57 };
58
59 const fixture = Effect.fn("AntigravityUsageTest.fixture")(function* (
60 options: {
61 summary?: unknown;
62 /** Per-host quota summaries; hosts not listed fall back to `summary`. */
63 summaryByHost?: Record<string, unknown>;
64 models?: unknown;
65 summaryStatus?: number;
66 /** Per-host summary statuses; hosts not listed fall back to `summaryStatus`. */
67 summaryStatusByHost?: Record<string, number>;
68 tokenStatus?: number;
69 refreshToken?: string;
70 userId?: string;
71 userInfoAt?: number;
72 missingToken?: boolean;
73 authMethod?: "oauth-personal" | "oauth-business" | "gemini-api-key";
74 keyringSecret?: string;
75 /** Reads the OS keyring instead of `keyringSecret`. */
76 nativeKeyring?: boolean;
77 } = {},
78 ) {
79 const fs = yield* FileSystem.FileSystem;
80 const path = yield* Path.Path;
81 const profileDirectory = yield* fs.makeTempDirectoryScoped();
82 yield* fs.makeDirectory(path.join(profileDirectory, "antigravity-acp"));
83 const tokenPath = path.join(profileDirectory, "antigravity-acp", "acp_token.json");
84 const writeToken = (refreshToken: string) =>
85 fs.writeFileString(
86 tokenPath,
87 JSON.stringify({
88 client_id: "client-id",
89 client_secret: "client-secret",
90 refresh_token: refreshToken,
91 project_id: "project-id",
92 }),
93 );
94 if (!options.missingToken) yield* writeToken(options.refreshToken ?? "refresh-a");
95 const requests: Array<{ url: string; body: string }> = [];
96 const http = HttpClient.make((request, url, _signal, fiber) =>
97 Effect.sync(() => {
98 const init = Context.getOrUndefined(fiber.context, FetchHttpClient.RequestInit);
99 expect(init?.redirect).toBe("manual");
100 const body =
101 request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "";
102 requests.push({ url: request.url, body });
103 if (request.url.endsWith("/token")) {
104 expect(new URLSearchParams(body).get("grant_type")).toBe("refresh_token");
105 return HttpClientResponse.fromWeb(
106 request,
107 Response.json(
108 { access_token: "access-token", expires_in: 3600 },
109 { status: options.tokenStatus ?? 200 },
110 ),
111 );
112 }
113 expect(request.headers.authorization).toBe("Bearer access-token");
114 if (request.url.endsWith("/userinfo")) {
115 return HttpClientResponse.fromWeb(
116 request,
117 options.userId
118 ? Response.json({ id: options.userId, email: "someone@example.com" })
119 : Response.json({}, { status: 403 }),
120 );
121 }
122 expect(JSON.parse(body)).toEqual(options.missingToken ? {} : { project: "project-id" });
123 expect(request.headers["user-agent"]).toMatch(/^antigravity\/hub\/2\.24\.0 /);
124 return HttpClientResponse.fromWeb(
125 request,
126 request.url.endsWith(":retrieveUserQuotaSummary")
127 ? Response.json(options.summaryByHost?.[url.host] ?? options.summary ?? summary, {
128 status: options.summaryStatusByHost?.[url.host] ?? options.summaryStatus ?? 200,
129 })
130 : Response.json(options.models ?? { models: {} }),
131 );
132 }).pipe(
133 Effect.tap(() =>
134 request.url.endsWith("/userinfo") && options.userInfoAt !== undefined
135 ? TestClock.setTime(options.userInfoAt)
136 : Effect.void,
137 ),
138 ),
139 );
140 const usage = yield* makeAntigravityUsageProbe({
141 profileDirectory,
142 authMethod: options.authMethod ?? "oauth-personal",
143 ...(options.nativeKeyring ? {} : { readKeyringSecret: Effect.succeed(options.keyringSecret) }),
144 }).pipe(Effect.provideService(HttpClient.HttpClient, http));
145 return { ...usage, requests, writeToken, tokenPath };
146 });
147
148 describe("Antigravity subscription limits", () => {
149 // Oracle: the 10:16 UTC payload and its narrow Workaround rule.
150 it.effect("omits rolling resets for untouched summary buckets and keeps used Gemini resets", () =>
151 Effect.gen(function* () {
152 yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-21T10:16:04Z")));
153 const { probe } = yield* fixture({
154 summary: {
155 groups: [
156 {
157 buckets: [
158 {
159 bucketId: "3p-5h",
160 window: "5h",
161 remainingFraction: 1,
162 resetTime: "2026-10-21T15:16:05Z",
163 },
164 {
165 bucketId: "3p-weekly",
166 window: "weekly",
167 remainingFraction: 1,
168 resetTime: "2026-10-28T10:16:05Z",
169 },
170 {
171 bucketId: "gemini-5h",
172 window: "5h",
173 remainingFraction: 0.848104,
174 resetTime: "2026-10-21T13:29:53Z",
175 description:
176 "You have used some of your 5-hour limit, it will fully refresh in 3 hours, 13 minutes.",
177 },
178 {
179 bucketId: "gemini-weekly",
180 window: "weekly",
181 remainingFraction: 0.9620177,
182 resetTime: "2026-10-28T08:29:53Z",
183 description:
184 "You have used some of your weekly limit, it will fully refresh in 6 days, 22 hours.",
185 },
186 ],
187 },
188 ],
189 },
190 });
191 const limits = yield* probe;
192 const byId = new Map(limits.windows.map((window) => [window.id, window]));
193 expect(byId.get("3p-5h")).toEqual({
194 id: "3p-5h",
195 label: "Claude & GPT (shared) · 5-hour",
196 kind: "session",
197 usedPercent: 0,
198 windowDurationMins: 300,
199 });
200 expect(byId.get("3p-weekly")).toEqual({
201 id: "3p-weekly",
202 label: "Claude & GPT (shared) · Weekly",
203 kind: "weekly",
204 usedPercent: 0,
205 windowDurationMins: 10080,
206 });
207 expect(byId.get("gemini-5h")?.resetsAt).toBe("2026-10-21T13:29:53.000Z");
208 expect(byId.get("gemini-weekly")?.resetsAt).toBe("2026-10-28T08:29:53.000Z");
209 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
210 );
211
212 // Oracle: measure the tolerance from the summary request, after auth.
213 it.effect("uses summary request time after authentication for the reset tolerance", () =>
214 Effect.gen(function* () {
215 yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-21T10:16:02Z")));
216 const { probe } = yield* fixture({
217 userInfoAt: DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-21T10:16:04Z")),
218 summary: {
219 buckets: [
220 {
221 bucketId: "3p-5h",
222 window: "5h",
223 remainingFraction: 1,
224 resetTime: "2026-10-21T15:17:03Z",
225 },
226 ],
227 },
228 });
229 expect((yield* probe).windows[0]?.resetsAt).toBeUndefined();
230 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
231 );
232
233 // Oracle: keep descriptions, measured resets, and spent buckets.
234 it.effect("keeps summary resets with a description, a distant reset, or no quota left", () =>
235 Effect.gen(function* () {
236 yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-21T10:16:04Z")));
237 const { probe } = yield* fixture({
238 summary: {
239 buckets: [
240 {
241 bucketId: "described",
242 window: "5h",
243 remainingFraction: 1,
244 description: "Reported reset",
245 resetTime: "2026-10-21T15:16:04Z",
246 },
247 {
248 bucketId: "distant",
249 window: "weekly",
250 remainingFraction: 1,
251 resetTime: "2026-10-28T12:16:04Z",
252 },
253 {
254 bucketId: "spent",
255 window: "5h",
256 remainingFraction: 0,
257 resetTime: "2026-10-21T15:16:04Z",
258 },
259 {
260 bucketId: "overfull",
261 window: "5h",
262 remainingFraction: 1.01,
263 resetTime: "2026-10-21T15:16:04Z",
264 },
265 {
266 bucketId: "empty-description",
267 window: "5h",
268 remainingFraction: 1,
269 description: "",
270 resetTime: "2026-10-21T15:16:04Z",
271 },
272 ],
273 },
274 });
275 expect((yield* probe).windows.map(({ id, resetsAt }) => ({ id, resetsAt }))).toEqual([
276 { id: "described", resetsAt: "2026-10-21T15:16:04.000Z" },
277 { id: "empty-description", resetsAt: "2026-10-21T15:16:04.000Z" },
278 { id: "overfull", resetsAt: "2026-10-21T15:16:04.000Z" },
279 { id: "spent", resetsAt: "2026-10-21T15:16:04.000Z" },
280 { id: "distant", resetsAt: "2026-10-28T12:16:04.000Z" },
281 ]);
282 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
283 );
284
285 // Oracle: the 60-second tolerance applies to both known window lengths.
286 it.effect("omits summary resets 59 seconds away but keeps resets 61 seconds away", () =>
287 Effect.gen(function* () {
288 yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-21T10:16:04Z")));
289 const { probe } = yield* fixture({
290 summary: {
291 buckets: [
292 {
293 bucketId: "5h-before",
294 window: "5h",
295 remainingFraction: 1,
296 resetTime: "2026-10-21T15:15:05Z",
297 },
298 {
299 bucketId: "5h-after",
300 window: "5h",
301 remainingFraction: 1,
302 resetTime: "2026-10-21T15:17:05Z",
303 },
304 {
305 bucketId: "5h-edge",
306 window: "5h",
307 remainingFraction: 1,
308 resetTime: "2026-10-21T15:17:04Z",
309 },
310 {
311 bucketId: "weekly-after",
312 window: "weekly",
313 remainingFraction: 1,
314 resetTime: "2026-10-28T10:17:03Z",
315 },
316 {
317 bucketId: "weekly-before",
318 window: "weekly",
319 remainingFraction: 1,
320 resetTime: "2026-10-28T10:15:03Z",
321 },
322 {
323 bucketId: "weekly-edge",
324 window: "weekly",
325 remainingFraction: 1,
326 resetTime: "2026-10-28T10:15:04Z",
327 },
328 ],
329 },
330 });
331 expect((yield* probe).windows.map(({ id, resetsAt }) => ({ id, resetsAt }))).toEqual([
332 { id: "5h-after", resetsAt: "2026-10-21T15:17:05.000Z" },
333 { id: "5h-before", resetsAt: undefined },
334 { id: "5h-edge", resetsAt: undefined },
335 { id: "weekly-after", resetsAt: undefined },
336 { id: "weekly-before", resetsAt: "2026-10-28T10:15:03.000Z" },
337 { id: "weekly-edge", resetsAt: undefined },
338 ]);
339 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
340 );
341
342 // Oracle: workspace sign-ins are metered on cloudcode-pa, so its reading wins even when less used.
343 it.effect("reports a business account's quota from the endpoint it is metered on", () =>
344 Effect.gen(function* () {
345 yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-21T10:16:04Z")));
346 const { probe } = yield* fixture({
347 authMethod: "oauth-business",
348 summaryByHost: {
349 "daily-cloudcode-pa.googleapis.com": {
350 buckets: [
351 {
352 bucketId: "3p-5h",
353 window: "5h",
354 remainingFraction: 1,
355 resetTime: "2026-10-21T15:16:04Z",
356 },
357 {
358 bucketId: "3p-weekly",
359 window: "weekly",
360 remainingFraction: 0.5,
361 resetTime: "2026-10-27T10:16:04Z",
362 },
363 ],
364 },
365 "cloudcode-pa.googleapis.com": {
366 buckets: [
367 {
368 bucketId: "3p-5h",
369 window: "5h",
370 remainingFraction: 0.5,
371 resetTime: "2026-10-21T13:16:04Z",
372 },
373 {
374 bucketId: "3p-weekly",
375 window: "weekly",
376 remainingFraction: 1,
377 resetTime: "2026-10-28T10:16:04Z",
378 },
379 ],
380 },
381 },
382 });
383 expect((yield* probe).windows).toEqual([
384 {
385 id: "3p-5h",
386 label: "Claude & GPT (shared) · 5-hour",
387 kind: "session",
388 usedPercent: 50,
389 windowDurationMins: 300,
390 resetsAt: "2026-10-21T13:16:04.000Z",
391 },
392 {
393 id: "3p-weekly",
394 label: "Claude & GPT (shared) · Weekly",
395 kind: "weekly",
396 usedPercent: 0,
397 windowDurationMins: 10080,
398 },
399 ]);
400 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
401 );
402
403 // Oracle: model quotas have no evidence for the summary-only rule.
404 it.effect("keeps full model fallback resets even at a full window from the request", () =>
405 Effect.gen(function* () {
406 yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-21T10:16:04Z")));
407 const { probe } = yield* fixture({
408 summaryStatus: 404,
409 models: {
410 models: {
411 "gemini-a": {
412 quotaInfo: { remainingFraction: 1, resetTime: "2026-10-21T15:16:04Z" },
413 weeklyQuotaInfo: { remainingFraction: 1, resetTime: "2026-10-28T10:16:04Z" },
414 },
415 },
416 },
417 });
418 expect(
419 (yield* probe).windows.map(({ id, resetsAt, windowDurationMins }) => ({
420 id,
421 resetsAt,
422 windowDurationMins,
423 })),
424 ).toEqual([
425 { id: "gemini-weekly", resetsAt: "2026-10-28T10:16:04.000Z", windowDurationMins: 10080 },
426 { id: "gemini-quota", resetsAt: "2026-10-21T15:16:04.000Z", windowDurationMins: undefined },
427 ]);
428 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
429 );
430
431 it.effect("reports separate Gemini and shared Claude/GPT five-hour and weekly limits", () =>
432 Effect.gen(function* () {
433 const { probe, requests } = yield* fixture();
434 const limits = yield* probe;
435 expect(limits.windows).toHaveLength(4);
436 expect(limits.unavailable).toBeUndefined();
437 expect(limits.credentialFingerprint).toMatch(/^[0-9a-f]{64}$/);
438 const byId = new Map(limits.windows.map((window) => [window.id, window]));
439 expect(byId.get("gemini-weekly")?.usedPercent).toBeCloseTo(4);
440 expect(byId.get("gemini-5h")?.usedPercent).toBeCloseTo(9);
441 expect(byId.get("3p-weekly")).toMatchObject({
442 label: "Claude & GPT (shared) · Weekly",
443 kind: "weekly",
444 usedPercent: 100,
445 windowDurationMins: 10080,
446 resetsAt: "2026-10-10T15:28:22.000Z",
447 });
448 expect(byId.get("3p-5h")).toMatchObject({ kind: "session", windowDurationMins: 300 });
449 expect(byId.get("3p-5h")?.usedPercent).toBeCloseTo(56);
450 yield* probe;
451 expect(requests.filter((request) => request.url.endsWith("/token"))).toHaveLength(1);
452 expect(
453 requests.filter((request) => request.url.endsWith(":retrieveUserQuotaSummary")),
454 ).toHaveLength(4);
455 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
456 );
457
458 it.effect("merges quota groups that only one endpoint reports", () =>
459 Effect.gen(function* () {
460 const { probe } = yield* fixture({
461 summaryByHost: {
462 // The daily endpoint can omit Gemini while the other endpoint returns all groups.
463 "daily-cloudcode-pa.googleapis.com": {
464 groups: [
465 {
466 displayName: "Claude and GPT models",
467 buckets: [
468 { bucketId: "3p-weekly", window: "weekly", remainingFraction: 0.5 },
469 { bucketId: "3p-5h", window: "5h", remainingFraction: 0.3 },
470 ],
471 },
472 ],
473 },
474 },
475 });
476 const limits = yield* probe;
477 expect(limits.windows.map((window) => window.id).toSorted()).toEqual([
478 "3p-5h",
479 "3p-weekly",
480 "gemini-5h",
481 "gemini-weekly",
482 ]);
483 const byId = new Map(limits.windows.map((window) => [window.id, window]));
484 expect(byId.get("gemini-weekly")?.label).toBe("Gemini · Weekly");
485 expect(byId.get("3p-5h")?.usedPercent).toBeCloseTo(70);
486 expect(byId.get("3p-weekly")?.usedPercent).toBe(50);
487 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
488 );
489
490 // Oracle: reported payloads for a personal sign-in, whose runtime meters on the daily endpoint.
491 it.effect("reports a personal account's quota from the daily endpoint it is metered on", () =>
492 Effect.gen(function* () {
493 yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe("2026-11-07T12:00:00Z")));
494 const argon = (remainingFraction: number, resetTime: string) => ({
495 groups: [
496 {
497 displayName: "Gemini 4 Argon",
498 buckets: [
499 {
500 bucketId: "gemini-argon-wtu-weekly",
501 window: "weekly",
502 remainingFraction,
503 resetTime,
504 },
505 ],
506 },
507 ],
508 });
509 const { probe } = yield* fixture({
510 authMethod: "oauth-personal",
511 summaryByHost: {
512 "daily-cloudcode-pa.googleapis.com": argon(0.8623059, "2026-11-14T08:41:35Z"),
513 "cloudcode-pa.googleapis.com": argon(0, "2026-11-08T18:27:14Z"),
514 },
515 });
516 expect((yield* probe).windows).toEqual([
517 expect.objectContaining({
518 id: "gemini-argon-wtu-weekly",
519 usedPercent: expect.closeTo(13.77, 2),
520 resetsAt: "2026-11-14T08:41:35.000Z",
521 }),
522 ]);
523 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
524 );
525
526 it.effect("labels Argon and Carbon quotas apart from the default Gemini quota", () =>
527 Effect.gen(function* () {
528 const { probe } = yield* fixture({
529 summary: {
530 groups: [
531 ...summary.groups,
532 {
533 displayName: "Gemini 4 Argon",
534 buckets: [
535 { bucketId: "gemini-argon-wtu-weekly", window: "weekly", remainingFraction: 0.6 },
536 ],
537 },
538 {
539 displayName: "Gemini 4 Carbon",
540 buckets: [
541 { bucketId: "gemini-carbon-wtu-weekly", window: "weekly", remainingFraction: 0.4 },
542 ],
543 },
544 {
545 displayName: " ",
546 buckets: [{ bucketId: "gemini-carbon-5h", window: "5h", remainingFraction: 0.8 }],
547 },
548 ],
549 },
550 });
551 const limits = yield* probe;
552 const byId = new Map(limits.windows.map((window) => [window.id, window]));
553 expect(byId.get("gemini-weekly")?.label).toBe("Gemini · Weekly");
554 expect(byId.get("gemini-argon-wtu-weekly")?.label).toBe("Gemini 4 Argon · Weekly");
555 expect(byId.get("gemini-carbon-wtu-weekly")?.label).toBe("Gemini 4 Carbon · Weekly");
556 expect(byId.get("gemini-carbon-5h")?.label).toBe("Gemini Carbon · 5-hour");
557 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
558 );
559
560 it.effect("keeps one endpoint's quotas when the other fails", () =>
561 Effect.gen(function* () {
562 const { probe } = yield* fixture({
563 summaryStatusByHost: { "daily-cloudcode-pa.googleapis.com": 503 },
564 });
565 const limits = yield* probe;
566 expect(limits.unavailable).toBeUndefined();
567 expect(limits.windows).toHaveLength(4);
568 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
569 );
570
571 it.effect("re-reads changed credentials and clears cached access after sign-out", () =>
572 Effect.gen(function* () {
573 const { probe, clear, requests, writeToken, tokenPath } = yield* fixture();
574 const first = yield* probe;
575 yield* writeToken("refresh-b");
576 const second = yield* probe;
577 expect(second.credentialFingerprint).not.toBe(first.credentialFingerprint);
578 expect(requests.filter((request) => request.url.endsWith("/token"))).toHaveLength(2);
579 yield* (yield* FileSystem.FileSystem).remove(tokenPath);
580 expect((yield* probe).unavailable?.reason).toBe("unsupported");
581 yield* writeToken("refresh-b");
582 yield* probe;
583 expect(requests.filter((request) => request.url.endsWith("/token"))).toHaveLength(3);
584 yield* clear;
585 yield* probe;
586 expect(requests.filter((request) => request.url.endsWith("/token"))).toHaveLength(4);
587 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
588 );
589
590 it.effect("names one Google account the same way from every sign-in", () =>
591 Effect.gen(function* () {
592 const read = (refreshToken: string, userId: string) =>
593 fixture({ refreshToken, userId }).pipe(Effect.flatMap((usage) => usage.probe));
594 const machineA = yield* read("refresh-a", "google-user-1");
595 const machineB = yield* read("refresh-b", "google-user-1");
596 const otherAccount = yield* read("refresh-c", "google-user-2");
597 expect(machineA.credentialFingerprint).toMatch(/^[0-9a-f]{64}$/);
598 expect(machineB.credentialFingerprint).toBe(machineA.credentialFingerprint);
599 expect(otherAccount.credentialFingerprint).not.toBe(machineA.credentialFingerprint);
600 expect(JSON.stringify(machineA)).not.toMatch(/google-user-1|someone@example.com/);
601 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
602 );
603
604 it.effect("falls back to model quotas without inventing a window duration", () =>
605 Effect.gen(function* () {
606 const { probe } = yield* fixture({
607 summaryStatus: 404,
608 models: {
609 models: {
610 "gemini-a": {
611 modelProvider: "MODEL_PROVIDER_GOOGLE",
612 quotaInfo: { remainingFraction: 0.8, resetTime: "2026-10-10T12:00:00Z" },
613 },
614 "gemini-b": {
615 modelProvider: "MODEL_PROVIDER_GOOGLE",
616 quotaInfo: { remainingFraction: 0.6, resetTime: "2026-10-10T12:00:00Z" },
617 },
618 "claude-a": { quotaInfo: { remainingFraction: 0.2 } },
619 },
620 },
621 });
622 const limits = yield* probe;
623 expect(limits.windows).toHaveLength(2);
624 expect(limits.windows.find((window) => window.id === "gemini-quota")?.usedPercent).toBe(40);
625 expect(
626 limits.windows.every(
627 (window) => window.kind === "other" && window.windowDurationMins === undefined,
628 ),
629 ).toBe(true);
630 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
631 );
632
633 it.effect("skips disabled and missing fractions and clamps valid percentages", () =>
634 Effect.gen(function* () {
635 const { probe } = yield* fixture({
636 summary: {
637 buckets: [
638 { bucketId: "disabled", remainingFraction: 0, disabled: true },
639 { bucketId: "missing", resetTime: "2026-10-10T12:00:00Z" },
640 { bucketId: "gemini-5h", window: "5h", remainingFraction: 2, resetTime: "invalid" },
641 ],
642 },
643 });
644 expect((yield* probe).windows).toEqual([
645 {
646 id: "gemini-5h",
647 kind: "session",
648 label: "Gemini · 5-hour",
649 usedPercent: 0,
650 windowDurationMins: 300,
651 },
652 ]);
653 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
654 );
655
656 it.effect("returns a safe failure when OAuth refresh fails", () =>
657 Effect.gen(function* () {
658 const { probe } = yield* fixture({ tokenStatus: 401 });
659 const limits = yield* probe;
660 expect(limits.windows).toEqual([]);
661 expect(limits.unavailable?.reason).toBe("probeFailed");
662 expect(JSON.stringify(limits)).not.toMatch(/client-secret|refresh-a|access-token/);
663 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
664 );
665
666 it.effect("reads the native CLI's stored sign-in when acp_token.json is absent", () =>
667 Effect.gen(function* () {
668 const fs = yield* FileSystem.FileSystem;
669 const path = yield* Path.Path;
670 const { probe, tokenPath } = yield* fixture({ missingToken: true });
671 // The 1.5.x CLI never writes acp_token.json; without a keyring it stores this file instead.
672 yield* fs.writeFileString(
673 path.join(path.dirname(tokenPath), "antigravity-oauth-token"),
674 JSON.stringify({
675 token: {
676 access_token: "access-token",
677 token_type: "Bearer",
678 refresh_token: "refresh-a",
679 expiry: "2099-01-01T00:00:00Z",
680 expires_in: 3600,
681 },
682 auth_method: "consumer",
683 id_token_email: "someone@example.com",
684 }),
685 );
686 const limits = yield* probe;
687 expect(limits.unavailable?.message).not.toBe(
688 "Sign in with Google to see Antigravity limits.",
689 );
690 expect(limits.unavailable?.reason).not.toBe("unsupported");
691 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
692 );
693
694 it.effect("reads a Gemini Enterprise keyring sign-in and reports when it has expired", () =>
695 Effect.gen(function* () {
696 yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-09T12:00:00Z")));
697 const keyringSecret = (expiry: string) =>
698 JSON.stringify({ token: { access_token: "access-token", refresh_token: "r", expiry } });
699 // Google account instances keep their own sign-in; the shared entry belongs to another app.
700 const personal = yield* fixture({
701 missingToken: true,
702 keyringSecret: keyringSecret("2026-10-09T14:00:00Z"),
703 });
704 expect((yield* personal.probe).unavailable?.message).toBe(
705 "Sign in with Google to see Antigravity limits.",
706 );
707 expect(personal.requests).toEqual([]);
708
709 const signedIn = yield* fixture({
710 authMethod: "oauth-business",
711 missingToken: true,
712 userId: "google-user-1",
713 keyringSecret: keyringSecret("2026-10-09T14:00:00.123456789+01:00"),
714 });
715 const limits = yield* signedIn.probe;
716 expect(limits.unavailable).toBeUndefined();
717 expect(limits.windows).toHaveLength(4);
718 expect(signedIn.requests.some((request) => request.url.endsWith("/token"))).toBe(false);
719
720 const expired = yield* fixture({
721 authMethod: "oauth-business",
722 missingToken: true,
723 keyringSecret: keyringSecret("2026-10-09T12:00:30Z"),
724 });
725 expect((yield* expired.probe).unavailable?.reason).toBe("probeFailed");
726 expect(expired.requests).toEqual([]);
727 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
728 );
729
730 it.effect.runIf(HostProcess.Platform.defaultValue() === "win32")(
731 "reads go-keyring's Windows credential target without changing it",
732 (ctx) =>
733 Effect.gen(function* () {
734 // Never overwrite a real sign-in on a developer's machine.
735 if (readWindowsCliCredential(HostProcess.Architecture.defaultValue())) return ctx.skip();
736 yield* TestClock.setTime(
737 DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-09T12:00:00Z")),
738 );
739 const { AsyncEntry } = yield* Effect.promise(() => import("@napi-rs/keyring"));
740 // go-keyring writes the UTF-8 JSON at `<service>:<user>`.
741 const target = AsyncEntry.withTarget("gemini:antigravity", "gemini", "antigravity");
742 const stored = new TextEncoder().encode(
743 JSON.stringify({
744 token: { access_token: "access-token", expiry: "2026-10-09T14:00:00Z" },
745 }),
746 );
747 yield* Effect.acquireRelease(
748 Effect.promise(() => target.setSecret(stored)),
749 () => Effect.promise(() => target.deleteCredential()),
750 );
751 const { probe } = yield* fixture({
752 authMethod: "oauth-business",
753 missingToken: true,
754 nativeKeyring: true,
755 });
756 const limits = yield* probe;
757 expect(limits.unavailable).toBeUndefined();
758 expect(limits.windows).toHaveLength(4);
759 expect(readWindowsCliCredential(HostProcess.Architecture.defaultValue())).toEqual(
760 Buffer.from(stored),
761 );
762 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
763 );
764
765 it("decodes go-keyring's macOS encodings", () => {
766 const value = '{"token":{}}';
767 const bytes = (text: string) => new TextEncoder().encode(text);
768 expect(decodeGoKeyringSecret(bytes(value))).toBe(value);
769 expect(
770 decodeGoKeyringSecret(bytes(`go-keyring-base64:${Buffer.from(value).toString("base64")}`)),
771 ).toBe(value);
772 expect(
773 decodeGoKeyringSecret(bytes(`go-keyring-encoded:${Buffer.from(value).toString("hex")}`)),
774 ).toBe(value);
775 });
776
777 it.effect("does not make network requests for API keys or missing sign-ins", () =>
778 Effect.gen(function* () {
779 for (const options of [{ authMethod: "gemini-api-key" as const }, { missingToken: true }]) {
780 const { probe, requests } = yield* fixture(options);
781 expect((yield* probe).unavailable?.reason).toBe("unsupported");
782 expect(requests).toEqual([]);
783 }
784 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
785 );
786 });