diff --git a/apps/server/src/provider/AntigravityProvider.test.ts b/apps/server/src/provider/AntigravityProvider.test.ts index 88589d1c9a773..c747786e9eade 100644 --- a/apps/server/src/provider/AntigravityProvider.test.ts +++ b/apps/server/src/provider/AntigravityProvider.test.ts @@ -138,6 +138,7 @@ const makeHarness = Effect.fn("makeAntigravityProviderHarness")(function* ( readonly auth?: { readonly type: string; readonly label: string }; readonly enabled?: boolean; readonly safe?: boolean; + readonly readAccountEmail?: Effect.Effect; readonly probeUsage?: Effect.Effect; readonly rememberedRuntimeModes?: ReadonlyArray; } = {}, @@ -155,6 +156,7 @@ const makeHarness = Effect.fn("makeAntigravityProviderHarness")(function* ( { stampIdentity: (snapshot) => Effect.succeed({ ...snapshot, instanceId, driver }), ...(options.auth ? { auth: options.auth } : {}), + ...(options.readAccountEmail ? { readAccountEmail: options.readAccountEmail } : {}), ...(options.probeUsage ? { probeUsage: options.probeUsage } : {}), ...(options.rememberedRuntimeModes ? { rememberedRuntimeModes: options.rememberedRuntimeModes } @@ -886,6 +888,170 @@ it.layer(layerTest)("Antigravity provider snapshots", (it) => { expect((yield* republished)?.usageLimits).toEqual(failed); }), ); + + it.effect( + "reports the stored Google email on startup and session start, and clears limits and email on account switch or sign-out", + () => + Effect.gen(function* () { + const emailRef = yield* Ref.make(" alice@example.com "); + const firstLimits: ServerProviderUsageLimits = { + checkedAt: "2026-10-09T12:00:00.000Z", + windows: [ + { id: "gemini-5h", kind: "session", label: "Gemini · 5-hour", usedPercent: 25 }, + ], + }; + const failedLimits: ServerProviderUsageLimits = { + checkedAt: "2026-10-09T12:05:00.000Z", + windows: [], + unavailable: { reason: "probeFailed" }, + }; + const thirdLimits: ServerProviderUsageLimits = { + checkedAt: "2026-10-09T12:10:00.000Z", + windows: [{ id: "gemini-5h", kind: "session", label: "Gemini · 5-hour", usedPercent: 5 }], + }; + const secondReadStarted = yield* Deferred.make(); + const usage = yield* Ref.make>( + Effect.succeed(firstLimits), + ); + const harness = yield* makeHarness({ + auth: { type: "oauth-personal", label: "Google account" }, + readAccountEmail: Ref.get(emailRef), + probeUsage: Ref.get(usage).pipe(Effect.flatten), + }); + const firstPublished = yield* harness.nextPublish((snapshot) => !!snapshot.usageLimits); + yield* harness.initialize; + + // Startup populates the email without marking the provider authenticated before a session. + expect(yield* firstPublished).toMatchObject({ + status: "warning", + auth: { status: "unknown", type: "oauth-personal", email: "alice@example.com" }, + usageLimits: firstLimits, + }); + + yield* harness.provider.onSessionStarted(started); + expect(yield* harness.provider.snapshot.getSnapshot).toMatchObject({ + status: "ready", + auth: { + status: "authenticated", + type: "oauth-personal", + label: "Google account", + email: "alice@example.com", + }, + usageLimits: firstLimits, + }); + + // A transient missing read preserves the last known email so a later switch is still detected. + yield* Ref.set(emailRef, undefined); + yield* Ref.set(harness.probe, Effect.succeed(initializeResult)); + yield* harness.provider.snapshot.refresh; + expect((yield* harness.provider.snapshot.getSnapshot).auth.email).toBe("alice@example.com"); + + // Switching accounts at session start clears published limits even if the new quota read fails. + yield* Ref.set(emailRef, "bob@example.com"); + yield* Ref.set( + usage, + Deferred.succeed(secondReadStarted, undefined).pipe(Effect.as(failedLimits)), + ); + const switchedPublished = yield* harness.nextPublish( + (snapshot) => + snapshot.auth.email === "bob@example.com" && + snapshot.usageLimits?.unavailable?.reason === "probeFailed", + ); + yield* harness.provider.onSessionStarted(started); + yield* Deferred.await(secondReadStarted); + expect(yield* switchedPublished).toMatchObject({ + auth: { status: "authenticated", email: "bob@example.com" }, + usageLimits: failedLimits, + }); + + // Switching accounts detected by checkProvider cancels an in-flight read and clears old limits. + const staleReadStarted = yield* Deferred.make(); + const staleReadResult = yield* Deferred.make(); + yield* Ref.set( + usage, + Deferred.succeed(staleReadStarted, undefined).pipe( + Effect.andThen(Deferred.await(staleReadResult)), + ), + ); + yield* harness.provider.snapshot.refresh; + yield* Deferred.await(staleReadStarted); + yield* Ref.set(emailRef, "carol@example.com"); + yield* Ref.set(usage, Effect.succeed(thirdLimits)); + const checkSwitchPublished = yield* harness.nextPublish( + (snapshot) => + snapshot.auth.email === "carol@example.com" && + snapshot.usageLimits?.windows[0]?.usedPercent === 5, + ); + yield* harness.provider.snapshot.refresh; + yield* Deferred.succeed(staleReadResult, firstLimits); + expect(yield* checkSwitchPublished).toMatchObject({ + auth: { status: "authenticated", email: "carol@example.com" }, + usageLimits: thirdLimits, + }); + + // onSignedIn clears the previous account's email even when the follow-up probe fails. + yield* Ref.set( + harness.probe, + Effect.fail(EffectAcpErrors.AcpRequestError.internalError("probe failed")), + ); + yield* harness.provider.onSignedIn; + expect((yield* harness.provider.snapshot.getSnapshot).auth.email).toBeUndefined(); + + // onSignedOut clears email and health checks do not restore it while unauthenticated. + yield* Ref.set(harness.probe, Effect.succeed(initializeResult)); + yield* harness.provider.onSessionStarted(started); + yield* harness.provider.onSignedOut; + expect((yield* harness.provider.snapshot.getSnapshot).auth).toMatchObject({ + status: "unauthenticated", + }); + expect((yield* harness.provider.snapshot.getSnapshot).auth.email).toBeUndefined(); + yield* harness.provider.snapshot.refresh; + expect((yield* harness.provider.snapshot.getSnapshot).auth.email).toBeUndefined(); + }), + ); + + it.effect("cancels an in-flight quota read when a session starts under a different email", () => + Effect.gen(function* () { + const emailRef = yield* Ref.make("alice@example.com"); + const aliceReadStarted = yield* Deferred.make(); + const aliceReadResult = yield* Deferred.make(); + const aliceLimits: ServerProviderUsageLimits = { + checkedAt: "2026-10-09T12:00:00.000Z", + windows: [{ id: "gemini-5h", kind: "session", label: "Gemini · 5-hour", usedPercent: 80 }], + }; + const bobLimits: ServerProviderUsageLimits = { + checkedAt: "2026-10-09T12:01:00.000Z", + windows: [{ id: "gemini-5h", kind: "session", label: "Gemini · 5-hour", usedPercent: 10 }], + }; + const usage = yield* Ref.make>( + Deferred.succeed(aliceReadStarted, undefined).pipe( + Effect.andThen(Deferred.await(aliceReadResult)), + ), + ); + const harness = yield* makeHarness({ + auth: { type: "oauth-personal", label: "Google account" }, + readAccountEmail: Ref.get(emailRef), + probeUsage: Ref.get(usage).pipe(Effect.flatten), + }); + yield* harness.initialize; + yield* Deferred.await(aliceReadStarted); + + yield* Ref.set(emailRef, "bob@example.com"); + yield* Ref.set(usage, Effect.succeed(bobLimits)); + const bobPublished = yield* harness.nextPublish( + (snapshot) => + snapshot.auth.email === "bob@example.com" && + snapshot.usageLimits?.windows[0]?.usedPercent === 10, + ); + yield* harness.provider.onSessionStarted(started); + yield* Deferred.succeed(aliceReadResult, aliceLimits); + expect(yield* bobPublished).toMatchObject({ + auth: { status: "authenticated", email: "bob@example.com" }, + usageLimits: bobLimits, + }); + expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toEqual(bobLimits); + }), + ); }); it.layer(makeLayerTest(true))("Antigravity periodic health checks", (it) => { diff --git a/apps/server/src/provider/AntigravityProvider.ts b/apps/server/src/provider/AntigravityProvider.ts index f5e18f6bece9d..242867cb73557 100644 --- a/apps/server/src/provider/AntigravityProvider.ts +++ b/apps/server/src/provider/AntigravityProvider.ts @@ -168,6 +168,7 @@ interface AntigravityProviderOptions { EffectAcpErrors.AcpError | ProviderSetupError >; readonly supportsTextGeneration: Effect.Effect; + readonly readAccountEmail?: Effect.Effect; readonly probeUsage?: Effect.Effect; readonly clearUsage?: Effect.Effect; readonly maintenanceCapabilities?: ProviderMaintenanceCapabilities; @@ -177,6 +178,26 @@ interface AntigravityProviderOptions { readonly rememberRuntimeModes?: (modes: ReadonlyArray) => Effect.Effect; } +function withAuthEmail( + auth: ServerProviderDraft["auth"], + email: string | undefined, +): ServerProviderDraft["auth"] { + const trimmed = email?.trim(); + if (trimmed) return { ...auth, email: trimmed }; + const { email: _previous, ...rest } = auth; + return rest; +} + +function isDifferentEmail(previous: string | undefined, next: string | undefined): boolean { + const previousNormalized = previous?.trim().toLowerCase(); + const nextNormalized = next?.trim().toLowerCase(); + return ( + previousNormalized !== undefined && + nextNormalized !== undefined && + previousNormalized !== nextNormalized + ); +} + const RUNTIME_MODES_WITHOUT_AUTO = [ "approval-required", "auto-accept-edits", @@ -268,20 +289,25 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func const scope = yield* Effect.scope; const refreshUsage = Effect.fn("AntigravityProvider.refreshUsage")(function* () { if (!options.probeUsage || (yield* PublishingUsage)) return; + const startedEmail = (yield* SubscriptionRef.get(metadata)).draft.auth.email; yield* FiberHandle.run( usageRead, options.probeUsage.pipe( Effect.flatMap((probed) => - SubscriptionRef.update(metadata, (state) => ({ - ...state, - draft: { - ...state.draft, - usageLimits: resolveUsageLimitsAfterProbe({ - published: state.draft.usageLimits, - probed, - }), - }, - })), + SubscriptionRef.update(metadata, (state) => + isDifferentEmail(startedEmail, state.draft.auth.email) + ? state + : { + ...state, + draft: { + ...state.draft, + usageLimits: resolveUsageLimitsAfterProbe({ + published: state.draft.usageLimits, + probed, + }), + }, + }, + ), ), // Enrichment cannot change published limits; a health check publishes them. Effect.andThen( @@ -328,28 +354,40 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func : `Antigravity did not respond to its local health check within ${timeoutMs / 1_000} seconds.`; const supportsTextGeneration = initialized !== undefined ? yield* options.supportsTextGeneration : false; + const accountEmail = + initialized !== undefined && options.readAccountEmail + ? yield* options.readAccountEmail + : undefined; const updatedAt = DateTime.formatIso(yield* DateTime.now); const applyCheck = (state: AntigravityProviderState) => { if (state.authRevision !== before.authRevision) return state; const { message: _previousMessage, ...draft } = state.draft; - const authenticated = draft.auth.status === "authenticated"; + const auth = + initialized !== undefined && + options.readAccountEmail !== undefined && + draft.auth.status !== "unauthenticated" + ? withAuthEmail(draft.auth, accountEmail ?? draft.auth.email) + : draft.auth; + const switchedAccount = isDifferentEmail(draft.auth.email, auth.email); + const authenticated = auth.status === "authenticated"; const message = errorMessage ?? (authenticated ? undefined - : draft.auth.status === "unauthenticated" + : auth.status === "unauthenticated" ? signInMessage : authUncheckedMessage); return { ...state, draft: { ...draft, + auth, installed: !missingInstallation, // Lightweight custom-launcher probes lack versions; preserve the real handshake's version. version: version === "unknown" ? draft.version : version || draft.version, status: errorMessage ? "error" : authenticated ? "ready" : "warning", checkedAt: updatedAt, - usageLimits: missingInstallation ? undefined : draft.usageLimits, + usageLimits: missingInstallation || switchedAccount ? undefined : draft.usageLimits, ...(missingInstallation ? { models: [], @@ -361,8 +399,7 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func : {}), ...(initialized !== undefined ? { - supportsTextGeneration: - supportsTextGeneration && draft.auth.status !== "unauthenticated", + supportsTextGeneration: supportsTextGeneration && auth.status !== "unauthenticated", } : {}), ...(message ? { message } : {}), @@ -371,11 +408,19 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func }; // This state is published as it changes, so a failure the managed provider discards stays out. const deferFailure = errorMessage !== undefined && (yield* DeferringFailedCheck); - const next = yield* SubscriptionRef.modifySome(metadata, (state) => { - const checked = applyCheck(state); - const stored = deferFailure && state.draft.status === "ready" ? state : checked; - return [checked, stored === state ? Option.none() : Option.some(stored)]; - }); + const { checked: next, switchedAccount } = yield* SubscriptionRef.modifySome( + metadata, + (state) => { + const checked = applyCheck(state); + const switchedAccount = isDifferentEmail(state.draft.auth.email, checked.draft.auth.email); + const stored = deferFailure && state.draft.status === "ready" ? state : checked; + return [ + { checked, switchedAccount }, + stored === state ? Option.none() : Option.some(stored), + ]; + }, + ); + if (switchedAccount) yield* resetUsage; if (initialized !== undefined) yield* refreshUsage(); return yield* options.stampIdentity(next.draft); }); @@ -410,53 +455,87 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func observeThinkingLevels(started.sessionSetupResult.configOptions); const before = yield* SubscriptionRef.get(metadata); const supportsTextGeneration = yield* options.supportsTextGeneration; + const accountEmail = options.readAccountEmail ? yield* options.readAccountEmail : undefined; const updatedAt = DateTime.formatIso(yield* DateTime.now); const supportedRuntimeModes = antigravityRuntimeModes(started.sessionSetupResult); - const previousModes = yield* SubscriptionRef.modify(metadata, (state) => { - if ( - state.authRevision !== before.authRevision && - state.draft.auth.status === "unauthenticated" - ) { - return [supportedRuntimeModes, state] as const; - } - const { message: _previousMessage, ...draft } = state.draft; - const workspaces = draft.workspaceSnapshots ?? []; - const workspace = cwd ? workspaces.find((entry) => entry.cwd === cwd) : undefined; - const next = { - authRevision: state.authRevision + 1, - draft: { - ...draft, - installed: true, - status: "ready", - version: started.initializeResult.agentInfo?.version || draft.version, - auth: { - status: "authenticated", - type: options.auth?.type ?? "oauth-personal", - label: options.auth?.label ?? "Google account", + const { previousModes, shouldRefreshUsage, switchedAccount } = yield* SubscriptionRef.modify( + metadata, + (state) => { + if ( + state.authRevision !== before.authRevision && + state.draft.auth.status === "unauthenticated" + ) { + return [ + { + previousModes: supportedRuntimeModes, + shouldRefreshUsage: false, + switchedAccount: false, + }, + state, + ] as const; + } + const { message: _previousMessage, ...draft } = state.draft; + const email = + state.authRevision === before.authRevision + ? (accountEmail ?? state.draft.auth.email) + : state.draft.auth.email; + const switchedAccount = isDifferentEmail(draft.auth.email, email); + const workspaces = draft.workspaceSnapshots ?? []; + const workspace = cwd ? workspaces.find((entry) => entry.cwd === cwd) : undefined; + const nextUsageLimits = switchedAccount ? undefined : draft.usageLimits; + return [ + { + previousModes: draft.supportedRuntimeModes, + shouldRefreshUsage: !nextUsageLimits || Boolean(nextUsageLimits.unavailable), + switchedAccount, }, - checkedAt: updatedAt, - models: buildAntigravityModelsFromSession(started.sessionSetupResult, thinkingLevels), - supportedRuntimeModes, - supportsTextGeneration, - ...(cwd - ? { - workspaceSnapshots: [ - ...workspaces.filter((entry) => entry.cwd !== cwd), - { - cwd, - checkedAt: updatedAt, - slashCommands: workspace?.slashCommands ?? draft.slashCommands, - skills: workspace?.skills ?? discoveredSkills.get(cwd) ?? [], - }, - ].slice(-MAX_WORKSPACE_SNAPSHOTS), - } - : {}), - }, - } satisfies AntigravityProviderState; - return [draft.supportedRuntimeModes, next] as const; - }); + { + authRevision: state.authRevision + 1, + draft: { + ...draft, + installed: true, + status: "ready", + version: started.initializeResult.agentInfo?.version || draft.version, + auth: withAuthEmail( + { + status: "authenticated", + type: options.auth?.type ?? "oauth-personal", + label: options.auth?.label ?? "Google account", + }, + email, + ), + usageLimits: nextUsageLimits, + checkedAt: updatedAt, + models: buildAntigravityModelsFromSession(started.sessionSetupResult, thinkingLevels), + supportedRuntimeModes, + supportsTextGeneration, + ...(cwd + ? { + workspaceSnapshots: [ + ...workspaces.filter((entry) => entry.cwd !== cwd), + { + cwd, + checkedAt: updatedAt, + slashCommands: workspace?.slashCommands ?? draft.slashCommands, + skills: workspace?.skills ?? discoveredSkills.get(cwd) ?? [], + }, + ].slice(-MAX_WORKSPACE_SNAPSHOTS), + } + : {}), + }, + } satisfies AntigravityProviderState, + ] as const; + }, + ); yield* rememberRuntimeModes(previousModes, supportedRuntimeModes); - if (!before.draft.usageLimits || before.draft.usageLimits.unavailable) yield* refreshUsage(); + if (switchedAccount) { + yield* resetUsage; + yield* Deferred.await(republish).pipe( + Effect.flatten, + Effect.provideService(PublishingUsage, true), + ); + } + if (shouldRefreshUsage) yield* refreshUsage(); }); const onConfigOptionsUpdated = Effect.fn("AntigravityProvider.onConfigOptionsUpdated")(function* ( @@ -576,7 +655,10 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func Effect.andThen( SubscriptionRef.update(metadata, (state) => { const { usageLimits: _previousAccount, ...draft } = state.draft; - return { ...state, draft }; + return { + authRevision: state.authRevision + 1, + draft: { ...draft, auth: withAuthEmail(draft.auth, undefined) }, + }; }), ), Effect.andThen( diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.test.ts b/apps/server/src/provider/Drivers/AntigravityDriver.test.ts index 3c0135f419c66..9967b827940ad 100644 --- a/apps/server/src/provider/Drivers/AntigravityDriver.test.ts +++ b/apps/server/src/provider/Drivers/AntigravityDriver.test.ts @@ -703,4 +703,54 @@ it.layer(layerTest)("AntigravityDriver", (it) => { expect(yield* fs.exists(legacyRoot)).toBe(false); }), ); + + it.effect.skipIf(windowsHost)( + "reports the stored Google email only for personal OAuth instances", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const writeStoredToken = (profileDirectory: string, email: string) => + Effect.gen(function* () { + const acpDir = path.join(profileDirectory, "antigravity-acp"); + yield* fs.makeDirectory(acpDir, { recursive: true }); + yield* fs.writeFileString( + path.join(acpDir, "antigravity-oauth-token"), + JSON.stringify({ id_token_email: email }), + ); + }); + + const personal = yield* makeHarness({ config: { authMethod: "oauth-personal" } }); + yield* writeStoredToken(personal.profileDirectory, "personal@example.com"); + expect((yield* personal.instance.snapshot.refresh).auth).toMatchObject({ + status: "unknown", + type: "oauth-personal", + email: "personal@example.com", + }); + yield* personal.refresh(); + expect((yield* personal.instance.snapshot.getSnapshot).auth).toMatchObject({ + status: "authenticated", + type: "oauth-personal", + label: "Google account", + email: "personal@example.com", + }); + yield* personal.assertClosed; + + const enterprise = yield* makeHarness({ + config: { + authMethod: "oauth-business", + gcpProject: "demo-project", + gcpLocation: "us-central1", + }, + }); + yield* writeStoredToken(enterprise.profileDirectory, "ignored@example.com"); + const enterpriseAuth = (yield* enterprise.instance.snapshot.refresh).auth; + expect(enterpriseAuth).toMatchObject({ + status: "unknown", + type: "oauth-business", + }); + expect(enterpriseAuth.email).toBeUndefined(); + yield* enterprise.assertClosed; + }), + ); }); diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.ts b/apps/server/src/provider/Drivers/AntigravityDriver.ts index b0d11b453dc61..6c08f2e1b81c7 100644 --- a/apps/server/src/provider/Drivers/AntigravityDriver.ts +++ b/apps/server/src/provider/Drivers/AntigravityDriver.ts @@ -46,6 +46,7 @@ import { buildAntigravityAcpSpawnInput, isAntigravitySignInRequiredError, prepareAntigravityProfile, + readAntigravityStoredEmail, resolveAntigravityInstanceDirectories, type AntigravityAuthConfig, } from "../antigravityAuthSupport.ts"; @@ -591,6 +592,14 @@ export const AntigravityDriver: ProviderDriver< probe, probeUsage: usage.probe, clearUsage: usage.clear, + ...(auth.authMethod === "oauth-personal" + ? { + readAccountEmail: readAntigravityStoredEmail(profileDirectory).pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), + ), + } + : {}), auth: { type: auth.authMethod, label: antigravityAuthLabel(auth.authMethod) }, ...(rememberedRuntimeModes ? { rememberedRuntimeModes } : {}), rememberRuntimeModes: (modes) => diff --git a/apps/server/src/provider/antigravityAuthSupport.test.ts b/apps/server/src/provider/antigravityAuthSupport.test.ts index ca759ef80a72f..7a2693b7e8bec 100644 --- a/apps/server/src/provider/antigravityAuthSupport.test.ts +++ b/apps/server/src/provider/antigravityAuthSupport.test.ts @@ -33,6 +33,7 @@ import { antigravityLoginResponse, parseAntigravityAuthorizationUrl, prepareAntigravityProfile, + readAntigravityStoredEmail, resolveAntigravityInstanceDirectories, } from "./antigravityAuthSupport.ts"; @@ -904,4 +905,32 @@ it.layer(NodeServices.layer)("Antigravity profile preparation", (it) => { } }), ); + + it.effect("reads and trims the stored Google email from antigravity-oauth-token", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const profileDirectory = yield* fs.makeTempDirectoryScoped(); + const acpDirectory = path.join(profileDirectory, "antigravity-acp"); + const tokenPath = path.join(acpDirectory, "antigravity-oauth-token"); + + expect(yield* readAntigravityStoredEmail(profileDirectory)).toBeUndefined(); + + yield* fs.makeDirectory(acpDirectory, { recursive: true }); + yield* fs.writeFileString( + tokenPath, + JSON.stringify({ id_token_email: " user@example.com " }), + ); + expect(yield* readAntigravityStoredEmail(profileDirectory)).toBe("user@example.com"); + + for (const contents of [ + JSON.stringify({ id_token_email: " " }), + JSON.stringify({ token: { access_token: "abc" } }), + "not-json", + ]) { + yield* fs.writeFileString(tokenPath, contents); + expect(yield* readAntigravityStoredEmail(profileDirectory)).toBeUndefined(); + } + }), + ); }); diff --git a/apps/server/src/provider/antigravityAuthSupport.ts b/apps/server/src/provider/antigravityAuthSupport.ts index 8edd875839773..f61662a5c7e2e 100644 --- a/apps/server/src/provider/antigravityAuthSupport.ts +++ b/apps/server/src/provider/antigravityAuthSupport.ts @@ -39,6 +39,13 @@ const maxStdoutLineBytes = 16 * 1024 * 1024; const authPrefixBytes = new TextEncoder().encode(ANTIGRAVITY_AUTH_STDOUT_PREFIX); const decodeUrl = Schema.decodeUnknownEffect(Schema.URLFromString); const decodeBrowserHelperUrl = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.String)); +const decodeStoredSignInEmail = Schema.decodeUnknownEffect( + Schema.fromJsonString( + Schema.Struct({ + id_token_email: Schema.optional(Schema.String), + }), + ), +); const ProfileSettingsFile = Schema.Struct({ auth: Schema.Struct({ type: Schema.String }), gcp: Schema.optional( @@ -543,6 +550,23 @@ export const prepareAntigravityProfile = Effect.fn("prepareAntigravityProfile")( return profile; }); +/** Reads the signed-in Google email from the instance's 1.5.x profile token file, if present. */ +export const readAntigravityStoredEmail = Effect.fn("readAntigravityStoredEmail")(function* ( + profileDirectory: string, +): Effect.fn.Return { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const tokenPath = path.join(profileDirectory, "antigravity-acp", "antigravity-oauth-token"); + return yield* fs.readFileString(tokenPath).pipe( + Effect.flatMap(decodeStoredSignInEmail), + Effect.map((stored) => { + const email = stored.id_token_email?.trim(); + return email && email.length > 0 ? email : undefined; + }), + Effect.orElseSucceed(() => undefined), + ); +}); + export function buildAntigravityAcpSpawnInput(input: { readonly installation: { readonly executablePath: string }; readonly profile: AntigravityProfile; diff --git a/apps/server/src/usage/cliproxyApi.ts b/apps/server/src/usage/cliproxyApi.ts index af80091c3eb41..1bb0a1a000837 100644 --- a/apps/server/src/usage/cliproxyApi.ts +++ b/apps/server/src/usage/cliproxyApi.ts @@ -384,7 +384,7 @@ const HUB_PROVIDERS = new Map([ if (windows.length === 0) { return yield* new UsageLimitSourceError({ detail: "No Antigravity quota reported." }); } - // Local Antigravity reports no e-mail, so the Google account fingerprint is what pools the two. + // Google account fingerprints pool hub readings with local Antigravity across server versions. const fingerprint = yield* call("https://www.googleapis.com/oauth2/v2/userinfo").pipe( Effect.flatMap(decodeJson), Effect.flatMap(antigravityAccountFingerprint), diff --git a/docs/user/providers-antigravity.md b/docs/user/providers-antigravity.md index 614fda68f2c1d..e46aa140ae461 100644 --- a/docs/user/providers-antigravity.md +++ b/docs/user/providers-antigravity.md @@ -158,8 +158,9 @@ Open **Usage > Limits** to see the remaining Gemini and shared Claude/GPT allowa for Google sign-ins. Each group has separate five-hour and weekly limits and reset times. Limits refresh with provider status and include usage outside T3 Code. -A server restart keeps your Google sign-in. The provider shows the saved account -until a session, a refresh, or a sign-out reports something new. +A server restart keeps your Google sign-in. The provider checks sign-in and loads +models on the next session or model refresh. For personal Google sign-ins, Usage > Limits +shows the signed-in email right away. To check access and reload models, use **Refresh provider status** in web or desktop provider settings, or **Refresh models** in mobile thread settings. If asked to diff --git a/packages/shared/src/usageLimits.test.ts b/packages/shared/src/usageLimits.test.ts index 0019c74e1d5cd..3777c53aedb52 100644 --- a/packages/shared/src/usageLimits.test.ts +++ b/packages/shared/src/usageLimits.test.ts @@ -439,6 +439,80 @@ describe("pools", () => { ); expect(accounts).toHaveLength(1); expect(accounts[0]?.limits.windows[0]?.usedPercent).toBe(30); + + // Local Antigravity reporting its signed-in email must still pool with a hub entry that only has a fingerprint. + const withEmail = { + ...local, + auth: { status: "authenticated" as const, email: "g@example.com" }, + }; + const pooledWithEmail = collectLimitAccounts( + new Map([ + [ + EnvironmentId.make("env-a"), + { + ...laptop, + serverConfig: { + providers: [withEmail], + usageLimitSources: [{ ...source, accounts: [hubAccount] }], + }, + }, + ], + ]), + ); + expect(pooledWithEmail).toHaveLength(1); + expect(pooledWithEmail[0]?.email).toBe("g@example.com"); + expect(pooledWithEmail[0]?.limits.windows[0]?.usedPercent).toBe(30); + + // Merging an older environment without email ahead of a newer one with email still pools and keeps the email. + const acrossEnvs = collectLimitAccounts( + new Map([ + [ + EnvironmentId.make("env-old"), + { + ...laptop, + serverConfig: { providers: [local] }, + }, + ], + [ + EnvironmentId.make("env-new"), + { + entry: { target: { label: "Desktop" } }, + serverConfig: { providers: [withEmail] }, + }, + ], + ]), + ); + expect(acrossEnvs).toHaveLength(1); + expect(acrossEnvs[0]?.email).toBe("g@example.com"); + + const report = collectProviderUsageLimits( + withEmail.instanceId, + [withEmail], + [{ ...source, accounts: [hubAccount] }], + now, + ); + expect(report?.accounts).toHaveLength(1); + expect(report?.accounts[0]?.email).toBe("g@example.com"); + + // Two bridged instances: a fresher credential-only report keeps the older instance's email. + const fresherWithoutEmail = { + ...local, + instanceId: ProviderInstanceId.make("antigravity-2"), + usageLimits: { + checkedAt: "2026-09-03T12:15:00.000Z", + credentialFingerprint: "google-key", + windows: [{ ...window, id: "gemini-weekly", usedPercent: 45 }], + }, + }; + const bridgedReport = collectProviderUsageLimits( + withEmail.instanceId, + [withEmail, fresherWithoutEmail], + [], + now, + ); + expect(bridgedReport?.accounts).toHaveLength(1); + expect(bridgedReport?.accounts[0]?.email).toBe("g@example.com"); + expect(bridgedReport?.accounts[0]?.limits.windows[0]?.usedPercent).toBe(45); }); it("takes windows from a fresher hub read but credits and redeem from the native instance", () => { diff --git a/packages/shared/src/usageLimits.ts b/packages/shared/src/usageLimits.ts index 711f3637d0a9f..59ea019b23077 100644 --- a/packages/shared/src/usageLimits.ts +++ b/packages/shared/src/usageLimits.ts @@ -242,15 +242,34 @@ const nativeReport = (provider: ServerProvider): AccountReport => ({ // Include every enabled login, even unreadable workspaces. function accountKeyResolver(reports: Iterable) { - const workspaces = new Map>(); - for (const report of reports) { + const reportList = [...reports]; + const credentialEmails = new Map>(); + for (const report of reportList) { + const email = report.email?.trim().toLowerCase(); + const fingerprint = report.usageLimits?.credentialFingerprint; + if (email && fingerprint) { + const credentialKey = `${report.driver}:credential:${fingerprint}`; + credentialEmails.set( + credentialKey, + (credentialEmails.get(credentialKey) ?? new Set()).add(`${report.driver}:${email}`), + ); + } + } + const baseKey = (report: AccountReport): string | null => { const key = accountKey(report.driver, report.email, report.usageLimits); + if (!key) return null; + const mapped = credentialEmails.get(key); + return mapped && mapped.size === 1 ? [...mapped][0]! : key; + }; + const workspaces = new Map>(); + for (const report of reportList) { + const key = baseKey(report); if (key && report.workspaceId) { workspaces.set(key, (workspaces.get(key) ?? new Set()).add(report.workspaceId)); } } return (report: AccountReport): string | null => { - const key = accountKey(report.driver, report.email, report.usageLimits); + const key = baseKey(report); if (!key) return null; if (report.workspaceId) return `${key}:${report.workspaceId}`; const known = workspaces.get(key); @@ -378,6 +397,7 @@ export function collectLimitAccounts(presentations: LimitPresentations): readonl displayName?.toLowerCase() === PROVIDER_DISPLAY_NAMES[previous.driver]?.toLowerCase() ? null : displayName, + email: previous.email ?? next.email, plan: planSources.get(key)?.plan ?? previous.plan ?? next.plan, accentColor: previous.accentColor ?? next.accentColor, environments, @@ -979,7 +999,7 @@ export function collectProviderUsageLimits( type NativeSnapshot = { provider: ServerProvider; limits: ServerProviderUsageLimits }; const nativeByAccount = new Map< string, - { usage: NativeSnapshot; credits: NativeSnapshot | null } + { usage: NativeSnapshot; credits: NativeSnapshot | null; email: string | undefined } >(); for (const provider of providersWithLimits(providers)) { if (!drivers.has(provider.driver) || !provider.usageLimits) continue; @@ -1005,6 +1025,9 @@ export function collectProviderUsageLimits( nativeByAccount.set(key, { usage: providerWins ? snapshot : previous.usage, credits, + email: providerWins + ? (provider.auth.email ?? previous?.email) + : (previous.email ?? provider.auth.email), }); } const native = [...nativeByAccount.values()]; @@ -1019,6 +1042,7 @@ export function collectProviderUsageLimits( for (const { usage: { provider, limits }, credits, + email, } of native) { const key = resolveKey(nativeReport(provider)); // Only a hub this instance reaches may redeem a credit for its thread. @@ -1060,7 +1084,7 @@ export function collectProviderUsageLimits( : { instanceId: credits?.provider.instanceId ?? provider.instanceId }, ...(provider.displayName ? { displayName: provider.displayName } : {}), ...(provider.accentColor ? { accentColor: provider.accentColor } : {}), - ...(provider.auth.email ? { email: provider.auth.email } : {}), + ...(email ? { email } : {}), limits: shownCredits ? { ...limits, resetCredits: shownCredits } : limits, }); }