Skip to content

Commit fefd971

Browse files
lukasbxycursoragent
andcommitted
fix(antigravity): refresh Gemini limits after sign-in and token expiry
Limits stayed on the pre-login unsupported snapshot until the next health check, and an expired stored access token skipped refresh and failed the quota read. Re-probe on session start, and retry Cloud Code once after a 401. Co-authored-by: Cursor <[email protected]>
1 parent c3ff68a commit fefd971

4 files changed

Lines changed: 113 additions & 12 deletions

File tree

‎apps/server/src/provider/Layers/AntigravityProvider.test.ts‎

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ import type * as EffectAcpSchema from "effect-acp/schema";
2121
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
2222
import { ServerSettingsService } from "../../serverSettings.ts";
2323
import type { AcpSessionRuntimeStartResult } from "../acp/AcpSessionRuntime.ts";
24-
import { makeUsageLimits } from "../providerUsageLimits.ts";
24+
import { makeUnavailableUsageLimits, makeUsageLimits } from "../providerUsageLimits.ts";
2525
import {
2626
buildAntigravityModelsFromSession,
2727
makeAntigravityProvider,
@@ -336,13 +336,53 @@ it.layer(testLayer)("Antigravity provider snapshots", (it) => {
336336
expect(yield* Ref.get(usageCalls)).toBe(1);
337337
expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toEqual(limits);
338338
yield* harness.provider.onSessionStarted(started);
339+
expect(yield* Ref.get(usageCalls)).toBe(2);
339340
expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toEqual(limits);
340341
yield* harness.provider.onSignedOut;
341342
expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toBeUndefined();
342343
}),
343344
),
344345
);
345346

347+
it.effect("replaces an unsupported probe with live limits when a session starts", () =>
348+
Effect.scoped(
349+
Effect.gen(function* () {
350+
const limits = makeUsageLimits({
351+
checkedAt: "2026-09-18T12:00:00.000Z",
352+
windows: [
353+
{
354+
id: "gemini_five_hour",
355+
kind: "session",
356+
label: "Gemini · Session",
357+
usedPercent: 40,
358+
windowDurationMins: 5 * 60,
359+
},
360+
],
361+
});
362+
const usageCalls = yield* Ref.make(0);
363+
const harness = yield* makeHarness({
364+
usageLimits: Ref.update(usageCalls, (count) => count + 1).pipe(
365+
Effect.flatMap((count) =>
366+
count === 1
367+
? Effect.succeed(
368+
makeUnavailableUsageLimits({
369+
checkedAt: "2026-09-18T11:00:00.000Z",
370+
reason: "unsupported",
371+
}),
372+
)
373+
: Effect.succeed(limits),
374+
),
375+
),
376+
});
377+
yield* harness.initialize;
378+
expect(yield* Ref.get(usageCalls)).toBe(1);
379+
yield* harness.provider.onSessionStarted(started);
380+
expect(yield* Ref.get(usageCalls)).toBe(2);
381+
expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toEqual(limits);
382+
}),
383+
),
384+
);
385+
346386
it.effect("does not read usage limits while disabled", () =>
347387
Effect.scoped(
348388
Effect.gen(function* () {

‎apps/server/src/provider/Layers/AntigravityProvider.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -271,6 +271,7 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func
271271
) {
272272
const before = yield* SubscriptionRef.get(metadata);
273273
const supportsTextGeneration = yield* options.supportsTextGeneration;
274+
const usageLimits = yield* options.usageLimits ?? Effect.succeed(undefined);
274275
const updatedAt = DateTime.formatIso(yield* DateTime.now);
275276
yield* SubscriptionRef.update(metadata, (state) => {
276277
if (
@@ -310,6 +311,7 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func
310311
].slice(-MAX_WORKSPACE_SNAPSHOTS),
311312
}
312313
: {}),
314+
...(usageLimits ? { usageLimits } : {}),
313315
},
314316
} satisfies AntigravityProviderState;
315317
});

‎apps/server/src/provider/Layers/antigravityUsageLimits.test.ts‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,52 @@ it.effect("exchanges the stored refresh token before reading Cloud Code quota",
206206
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
207207
);
208208

209+
it.effect("refreshes an expired stored access token after Cloud Code returns 401", () =>
210+
Effect.gen(function* () {
211+
const fs = yield* FileSystem.FileSystem;
212+
const path = yield* Path.Path;
213+
const directory = yield* fs.makeTempDirectoryScoped();
214+
const tokenPath = path.join(directory, "acp_token.json");
215+
yield* fs.writeFileString(
216+
tokenPath,
217+
'{"token":{"access_token":"ya29.expired"},"client_id":"client.apps.googleusercontent.com","client_secret":"client-secret","refresh_token":"refresh-token","token_uri":"https://oauth2.googleapis.com/token"}',
218+
);
219+
const authorizations: string[] = [];
220+
const limits = yield* readAntigravityUsageLimits({
221+
enabled: true,
222+
authMethod: "oauth-personal",
223+
tokenPath,
224+
}).pipe(
225+
Effect.provideService(
226+
HttpClient.HttpClient,
227+
HttpClient.make((request) => {
228+
if (request.url === "https://oauth2.googleapis.com/token") {
229+
return Effect.succeed(
230+
HttpClientResponse.fromWeb(
231+
request,
232+
Response.json({ access_token: "ya29.refreshed", expires_in: 3600 }),
233+
),
234+
);
235+
}
236+
authorizations.push(request.headers.authorization ?? "");
237+
if (request.headers.authorization === "Bearer ya29.expired") {
238+
return Effect.succeed(
239+
HttpClientResponse.fromWeb(request, Response.json({}, { status: 401 })),
240+
);
241+
}
242+
NodeAssert.equal(request.headers.authorization, "Bearer ya29.refreshed");
243+
return Effect.succeed(HttpClientResponse.fromWeb(request, Response.json(liveSummary)));
244+
}),
245+
),
246+
);
247+
NodeAssert.deepEqual(authorizations, ["Bearer ya29.expired", "Bearer ya29.refreshed"]);
248+
NodeAssert.deepEqual(
249+
limits.windows.map((window) => window.id),
250+
["gemini_five_hour", "gemini_seven_day"],
251+
);
252+
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
253+
);
254+
209255
it.effect("does not send refresh credentials to a non-Google token URI", () =>
210256
Effect.gen(function* () {
211257
const fs = yield* FileSystem.FileSystem;

‎apps/server/src/provider/Layers/antigravityUsageLimits.ts‎

Lines changed: 24 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,18 @@ import {
2121

2222
/** `cloudcode-pa` answers the same RPC with remainingFraction 1 on every bucket. */
2323
const QUOTA_URL = "https://daily-cloudcode-pa.googleapis.com/v1internal:retrieveUserQuotaSummary";
24+
25+
function quotaRequest(token: string, project: string | undefined) {
26+
return HttpClientRequest.post(QUOTA_URL).pipe(
27+
HttpClientRequest.bearerToken(token),
28+
HttpClientRequest.setHeaders({
29+
"user-agent": "antigravity",
30+
"content-type": "application/json",
31+
}),
32+
HttpClientRequest.bodyJsonUnsafe(project ? { project } : {}),
33+
);
34+
}
35+
2436
const SESSION_MINS = 5 * 60;
2537
const WEEK_MINS = 7 * 24 * 60;
2638

@@ -243,21 +255,22 @@ export const readAntigravityUsageLimits = Effect.fn("readAntigravityUsageLimits"
243255
);
244256
if (!contents.trim()) return unsupported;
245257
const file = yield* decodeTokenFile(contents);
246-
const token = accessTokenFromFile(file) ?? (yield* refreshAccessToken(file));
258+
const stored = accessTokenFromFile(file);
259+
const token = stored ?? (yield* refreshAccessToken(file));
247260
if (!token) return unsupported;
248261

249262
const client = yield* HttpClient.HttpClient;
250263
const project = input.gcpProject?.trim();
251-
const response = yield* client.execute(
252-
HttpClientRequest.post(QUOTA_URL).pipe(
253-
HttpClientRequest.bearerToken(token),
254-
HttpClientRequest.setHeaders({
255-
"user-agent": "antigravity",
256-
"content-type": "application/json",
257-
}),
258-
HttpClientRequest.bodyJsonUnsafe(project ? { project } : {}),
259-
),
260-
);
264+
const firstResponse = yield* client.execute(quotaRequest(token, project));
265+
const response =
266+
firstResponse.status === 401 && stored
267+
? yield* Effect.gen(function* () {
268+
const refreshed = yield* refreshAccessToken(file);
269+
return refreshed
270+
? yield* client.execute(quotaRequest(refreshed, project))
271+
: firstResponse;
272+
})
273+
: firstResponse;
261274
if (response.status === 403) return unsupported;
262275
const body = yield* HttpClientResponse.filterStatusOk(response).pipe(
263276
Effect.flatMap(HttpClientResponse.schemaBodyJson(QuotaSummary)),

0 commit comments

Comments
 (0)