diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.ts b/apps/server/src/provider/Drivers/AntigravityDriver.ts index 3d426785813c3..54acea5a7ebe3 100644 --- a/apps/server/src/provider/Drivers/AntigravityDriver.ts +++ b/apps/server/src/provider/Drivers/AntigravityDriver.ts @@ -570,7 +570,6 @@ export const AntigravityDriver: ProviderDriver< stampIdentity: classifyModels, probe, probeUsage: usage.probe, - clearUsage: usage.clear, auth: { type: auth.authMethod, label: antigravityAuthLabel(auth.authMethod) }, supportsTextGeneration: isAntigravityTextGenerationAvailable(profileDirectory).pipe( Effect.provideService(FileSystem.FileSystem, fileSystem), diff --git a/apps/server/src/provider/antigravityUsageLimits.test.ts b/apps/server/src/provider/antigravityUsageLimits.test.ts index eec70e2e44fce..46f9fc8c82ec2 100644 --- a/apps/server/src/provider/antigravityUsageLimits.test.ts +++ b/apps/server/src/provider/antigravityUsageLimits.test.ts @@ -56,6 +56,15 @@ const summary = { ], }; +const cliToken = (refreshToken: string) => + JSON.stringify({ + token: { + access_token: "access-token", + refresh_token: refreshToken, + expiry: "2099-01-01T00:00:00Z", + }, + }); + const fixture = Effect.fn("AntigravityUsageTest.fixture")(function* ( options: { summary?: unknown; @@ -65,11 +74,13 @@ const fixture = Effect.fn("AntigravityUsageTest.fixture")(function* ( summaryStatus?: number; /** Per-host summary statuses; hosts not listed fall back to `summaryStatus`. */ summaryStatusByHost?: Record; - tokenStatus?: number; refreshToken?: string; userId?: string; userInfoAt?: number; + /** The CLI is signed out: no antigravity-oauth-token file. */ missingToken?: boolean; + /** An acp_token.json left in the profile by a runtime below 1.5 or an earlier account. */ + leftoverAcpToken?: boolean; authMethod?: "oauth-personal" | "oauth-business" | "gemini-api-key"; keyringSecret?: string; /** Reads the OS keyring instead of `keyringSecret`. */ @@ -80,18 +91,21 @@ const fixture = Effect.fn("AntigravityUsageTest.fixture")(function* ( const path = yield* Path.Path; const profileDirectory = yield* fs.makeTempDirectoryScoped(); yield* fs.makeDirectory(path.join(profileDirectory, "antigravity-acp")); - const tokenPath = path.join(profileDirectory, "antigravity-acp", "acp_token.json"); - const writeToken = (refreshToken: string) => - fs.writeFileString( - tokenPath, + if (options.leftoverAcpToken) { + yield* fs.writeFileString( + path.join(profileDirectory, "antigravity-acp", "acp_token.json"), JSON.stringify({ client_id: "client-id", client_secret: "client-secret", - refresh_token: refreshToken, + refresh_token: "stale-refresh", project_id: "project-id", }), ); - if (!options.missingToken) yield* writeToken(options.refreshToken ?? "refresh-a"); + } + const cliTokenPath = path.join(profileDirectory, "antigravity-acp", "antigravity-oauth-token"); + if (!options.missingToken) { + yield* fs.writeFileString(cliTokenPath, cliToken(options.refreshToken ?? "refresh-a")); + } const requests: Array<{ url: string; body: string }> = []; const http = HttpClient.make((request, url, _signal, fiber) => Effect.sync(() => { @@ -100,16 +114,7 @@ const fixture = Effect.fn("AntigravityUsageTest.fixture")(function* ( const body = request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : ""; requests.push({ url: request.url, body }); - if (request.url.endsWith("/token")) { - expect(new URLSearchParams(body).get("grant_type")).toBe("refresh_token"); - return HttpClientResponse.fromWeb( - request, - Response.json( - { access_token: "access-token", expires_in: 3600 }, - { status: options.tokenStatus ?? 200 }, - ), - ); - } + expect(request.url).not.toMatch(/\/token$/); expect(request.headers.authorization).toBe("Bearer access-token"); if (request.url.endsWith("/userinfo")) { return HttpClientResponse.fromWeb( @@ -119,7 +124,7 @@ const fixture = Effect.fn("AntigravityUsageTest.fixture")(function* ( : Response.json({}, { status: 403 }), ); } - expect(JSON.parse(body)).toEqual(options.missingToken ? {} : { project: "project-id" }); + expect(JSON.parse(body)).toEqual({}); expect(request.headers["user-agent"]).toMatch(/^antigravity\/hub\/2\.24\.0 /); return HttpClientResponse.fromWeb( request, @@ -142,7 +147,7 @@ const fixture = Effect.fn("AntigravityUsageTest.fixture")(function* ( authMethod: options.authMethod ?? "oauth-personal", ...(options.nativeKeyring ? {} : { readKeyringSecret: Effect.succeed(options.keyringSecret) }), }).pipe(Effect.provideService(HttpClient.HttpClient, http)); - return { ...usage, requests, writeToken, tokenPath }; + return { ...usage, requests, cliTokenPath }; }); describe("Antigravity subscription limits", () => { @@ -448,7 +453,6 @@ describe("Antigravity subscription limits", () => { expect(byId.get("3p-5h")).toMatchObject({ kind: "session", windowDurationMins: 300 }); expect(byId.get("3p-5h")?.usedPercent).toBeCloseTo(56); yield* probe; - expect(requests.filter((request) => request.url.endsWith("/token"))).toHaveLength(1); expect( requests.filter((request) => request.url.endsWith(":retrieveUserQuotaSummary")), ).toHaveLength(4); @@ -568,22 +572,17 @@ describe("Antigravity subscription limits", () => { }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); - it.effect("re-reads changed credentials and clears cached access after sign-out", () => + it.effect("re-reads a changed sign-in on every probe", () => Effect.gen(function* () { - const { probe, clear, requests, writeToken, tokenPath } = yield* fixture(); + const fs = yield* FileSystem.FileSystem; + const { probe, cliTokenPath } = yield* fixture({ missingToken: true }); + yield* fs.writeFileString(cliTokenPath, cliToken("refresh-a")); const first = yield* probe; - yield* writeToken("refresh-b"); + yield* fs.writeFileString(cliTokenPath, cliToken("refresh-b")); const second = yield* probe; expect(second.credentialFingerprint).not.toBe(first.credentialFingerprint); - expect(requests.filter((request) => request.url.endsWith("/token"))).toHaveLength(2); - yield* (yield* FileSystem.FileSystem).remove(tokenPath); + yield* fs.remove(cliTokenPath); expect((yield* probe).unavailable?.reason).toBe("unsupported"); - yield* writeToken("refresh-b"); - yield* probe; - expect(requests.filter((request) => request.url.endsWith("/token"))).toHaveLength(3); - yield* clear; - yield* probe; - expect(requests.filter((request) => request.url.endsWith("/token"))).toHaveLength(4); }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); @@ -653,24 +652,13 @@ describe("Antigravity subscription limits", () => { }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); - it.effect("returns a safe failure when OAuth refresh fails", () => - Effect.gen(function* () { - const { probe } = yield* fixture({ tokenStatus: 401 }); - const limits = yield* probe; - expect(limits.windows).toEqual([]); - expect(limits.unavailable?.reason).toBe("probeFailed"); - expect(JSON.stringify(limits)).not.toMatch(/client-secret|refresh-a|access-token/); - }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), - ); - - it.effect("reads the native CLI's stored sign-in when acp_token.json is absent", () => + it.effect("reads the native CLI's stored sign-in file", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const { probe, tokenPath } = yield* fixture({ missingToken: true }); - // The 1.5.x CLI never writes acp_token.json; without a keyring it stores this file instead. + const { probe, cliTokenPath } = yield* fixture({ missingToken: true }); + // Without a keyring the CLI stores its sign-in in this file. yield* fs.writeFileString( - path.join(path.dirname(tokenPath), "antigravity-oauth-token"), + cliTokenPath, JSON.stringify({ token: { access_token: "access-token", @@ -691,6 +679,30 @@ describe("Antigravity subscription limits", () => { }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); + it.effect("ignores a leftover acp_token.json for the CLI's sign-in", () => + Effect.gen(function* () { + // The CLI never writes or updates acp_token.json, so any copy is another account's. + const file = yield* fixture({ leftoverAcpToken: true, refreshToken: "refresh-b" }); + const limits = yield* file.probe; + expect(limits.unavailable).toBeUndefined(); + expect(limits.windows).toHaveLength(4); + expect(file.requests.map((request) => request.body).join("\n")).not.toContain( + "stale-refresh", + ); + + const keyring = yield* fixture({ + authMethod: "oauth-business", + leftoverAcpToken: true, + missingToken: true, + keyringSecret: cliToken("refresh-b"), + }); + expect((yield* keyring.probe).unavailable).toBeUndefined(); + expect(keyring.requests.map((request) => request.body).join("\n")).not.toContain( + "stale-refresh", + ); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ); + it.effect("reads a Gemini Enterprise keyring sign-in and reports when it has expired", () => Effect.gen(function* () { yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-09T12:00:00Z"))); @@ -776,7 +788,11 @@ describe("Antigravity subscription limits", () => { it.effect("does not make network requests for API keys or missing sign-ins", () => Effect.gen(function* () { - for (const options of [{ authMethod: "gemini-api-key" as const }, { missingToken: true }]) { + for (const options of [ + { authMethod: "gemini-api-key" as const }, + { missingToken: true }, + { missingToken: true, leftoverAcpToken: true }, + ]) { const { probe, requests } = yield* fixture(options); expect((yield* probe).unavailable?.reason).toBe("unsupported"); expect(requests).toEqual([]); diff --git a/apps/server/src/provider/antigravityUsageLimits.ts b/apps/server/src/provider/antigravityUsageLimits.ts index fadf2207c31f2..4867132a8d008 100644 --- a/apps/server/src/provider/antigravityUsageLimits.ts +++ b/apps/server/src/provider/antigravityUsageLimits.ts @@ -34,14 +34,9 @@ const SUMMARY_WINDOW_MINS = new Map([ ["weekly", 7 * 24 * 60], ]); const MANUAL_REDIRECT: RequestInit = { redirect: "manual" }; -const TokenFile = Schema.Struct({ - client_id: Schema.NonEmptyString, - client_secret: Schema.NonEmptyString, - refresh_token: Schema.NonEmptyString, - project_id: Schema.optional(Schema.String), -}); -// The 1.5.x CLI never writes acp_token.json: it keeps its sign-in in the OS keyring, or in -// antigravity-oauth-token without one or when T3 bypasses the keyring. It stores no OAuth client, so T3 cannot refresh it. +// Runtimes below 1.5 are refused, so an acp_token.json in the profile is always a leftover. The +// CLI keeps its sign-in in the OS keyring, or in antigravity-oauth-token without one or when T3 +// bypasses the keyring. It stores no OAuth client, so T3 cannot refresh it. const CliToken = Schema.Struct({ token: Schema.Struct({ access_token: Schema.NonEmptyString, @@ -49,10 +44,6 @@ const CliToken = Schema.Struct({ expiry: Schema.optional(Schema.String), }), }); -const TokenResponse = Schema.Struct({ - access_token: Schema.NonEmptyString, - expires_in: Schema.Number.check(Schema.isGreaterThan(0)), -}); const UserInfo = Schema.Struct({ id: Schema.NonEmptyString }); const Quota = Schema.Struct({ remainingFraction: Schema.optional(Schema.Number), @@ -88,9 +79,7 @@ const Models = Schema.Struct({ ), }); -const decodeTokenFile = Schema.decodeEffect(Schema.fromJsonString(TokenFile)); const decodeCliToken = Schema.decodeEffect(Schema.fromJsonString(CliToken)); -const decodeTokenResponse = Schema.decodeUnknownEffect(TokenResponse); const decodeUserInfo = Schema.decodeUnknownEffect(UserInfo); const decodeSummary = Schema.decodeUnknownEffect(Summary); const decodeModels = Schema.decodeUnknownEffect(Models); @@ -328,17 +317,12 @@ export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")( const crypto = yield* Digest.Digest; const platform = yield* HostProcess.Platform; const architecture = yield* HostProcess.Architecture; - const tokenPath = path.join(input.profileDirectory, "antigravity-acp", "acp_token.json"); const cliTokenPath = path.join( input.profileDirectory, "antigravity-acp", "antigravity-oauth-token", ); const readKeyringSecret = input.readKeyringSecret ?? readCliKeyringSecret(platform, architecture); - let cached: - | { fingerprint: string; account: string; accessToken: string; expiresAt: number } - | undefined; - let generation = 0; const request = (request: HttpClientRequest.HttpClientRequest) => client.execute(request).pipe( @@ -348,89 +332,42 @@ export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")( Effect.timeout("10 seconds"), ); const read = Effect.gen(function* () { - const startedGeneration = generation; const checkedAt = DateTime.formatIso(yield* DateTime.now); if (input.authMethod !== "oauth-personal" && input.authMethod !== "oauth-business") { return makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" }); } const now = yield* Clock.currentTimeMillis; - let accessToken: string; - let account: string; - let projectId: string | undefined; - if (!(yield* fs.exists(tokenPath))) { - cached = undefined; - // Google account instances bypass the keyring, whose one entry every profile shares. - const stored = (yield* fs.exists(cliTokenPath)) - ? yield* fs.readFileString(cliTokenPath) - : input.authMethod === "oauth-business" - ? yield* readKeyringSecret - : undefined; - if (stored === undefined) { - return makeUnavailableUsageLimits({ - checkedAt, - reason: "unsupported", - message: "Sign in with Google to see Antigravity limits.", - }); - } - const { token } = yield* decodeCliToken(stored); - if (!(Date.parse(token.expiry ?? "") > now + 60_000)) { - return makeUnavailableUsageLimits({ - checkedAt, - reason: "probeFailed", - message: - "Antigravity's saved sign-in has expired. Start an Antigravity turn to renew it, then refresh limits.", - }); - } - accessToken = token.access_token; - account = yield* request( - HttpClientRequest.get("https://www.googleapis.com/oauth2/v2/userinfo").pipe( - HttpClientRequest.setHeaders({ Authorization: `Bearer ${accessToken}` }), - ), - ).pipe( - Effect.flatMap(antigravityAccountFingerprint), - Effect.catch(() => sha256(`antigravity-cli\0${token.refresh_token || accessToken}`)), - ); - } else { - const token = yield* fs.readFileString(tokenPath).pipe(Effect.flatMap(decodeTokenFile)); - projectId = token.project_id; - const fingerprint = yield* sha256( - `${token.client_id}\0${token.refresh_token}\0${token.project_id ?? ""}`, - ); - if (cached?.fingerprint !== fingerprint || cached.expiresAt <= now + 60_000) { - cached = undefined; - const refreshed = yield* request( - HttpClientRequest.post("https://oauth2.googleapis.com/token").pipe( - HttpClientRequest.bodyUrlParams({ - client_id: token.client_id, - client_secret: token.client_secret, - refresh_token: token.refresh_token, - grant_type: "refresh_token", - }), - ), - ).pipe(Effect.flatMap(decodeTokenResponse)); - accessToken = refreshed.access_token; - // Use Google account IDs to merge accounts across environments; refresh tokens differ per machine. - account = yield* request( - HttpClientRequest.get("https://www.googleapis.com/oauth2/v2/userinfo").pipe( - HttpClientRequest.setHeaders({ Authorization: `Bearer ${accessToken}` }), - ), - ).pipe( - Effect.flatMap(antigravityAccountFingerprint), - Effect.orElseSucceed(() => fingerprint), - ); - if (generation === startedGeneration) { - cached = { - fingerprint, - account, - accessToken, - expiresAt: now + refreshed.expires_in * 1000, - }; - } - } else { - accessToken = cached.accessToken; - account = cached.account; - } + // Google account instances bypass the keyring, whose one entry every profile shares. + const stored = (yield* fs.exists(cliTokenPath)) + ? yield* fs.readFileString(cliTokenPath) + : input.authMethod === "oauth-business" + ? yield* readKeyringSecret + : undefined; + if (stored === undefined) { + return makeUnavailableUsageLimits({ + checkedAt, + reason: "unsupported", + message: "Sign in with Google to see Antigravity limits.", + }); + } + const { token } = yield* decodeCliToken(stored); + if (!(Date.parse(token.expiry ?? "") > now + 60_000)) { + return makeUnavailableUsageLimits({ + checkedAt, + reason: "probeFailed", + message: + "Antigravity's saved sign-in has expired. Start an Antigravity turn to renew it, then refresh limits.", + }); } + const accessToken = token.access_token; + const account = yield* request( + HttpClientRequest.get("https://www.googleapis.com/oauth2/v2/userinfo").pipe( + HttpClientRequest.setHeaders({ Authorization: `Bearer ${accessToken}` }), + ), + ).pipe( + Effect.flatMap(antigravityAccountFingerprint), + Effect.catch(() => sha256(`antigravity-cli\0${token.refresh_token || accessToken}`)), + ); const endpoints = ENDPOINTS[input.authMethod]; // Merge endpoints because quota groups differ; the metered host's reading of a bucket wins. const fetchWindows = Effect.fn("AntigravityUsageProbe.fetchWindows")(function* ( @@ -452,7 +389,7 @@ export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")( Authorization: `Bearer ${accessToken}`, "User-Agent": antigravityUserAgent(platform, architecture), }), - HttpClientRequest.bodyJsonUnsafe(projectId ? { project: projectId } : {}), + HttpClientRequest.bodyJsonUnsafe({}), ), ).pipe( Effect.flatMap((response) => parse(response, requestedAt)), @@ -495,11 +432,5 @@ export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")( }), ), ); - return { - probe, - clear: Effect.sync(() => { - cached = undefined; - generation++; - }), - }; + return { probe }; });