diff --git a/apps/server/src/provider/AntigravityProvider.test.ts b/apps/server/src/provider/AntigravityProvider.test.ts index 9612fb535ddd9..f57ea91c57ce7 100644 --- a/apps/server/src/provider/AntigravityProvider.test.ts +++ b/apps/server/src/provider/AntigravityProvider.test.ts @@ -30,6 +30,7 @@ import { buildAntigravityModelsFromSession, makeAntigravityProvider, } from "./AntigravityProvider.ts"; +import type { AntigravityUsageProbeResult } from "./antigravityUsageLimits.ts"; const decodeSettings = Schema.decodeSync(AntigravitySettings); const instanceId = ProviderInstanceId.make("antigravity-test"); @@ -134,7 +135,7 @@ const makeHarness = Effect.fn("makeAntigravityProviderHarness")(function* ( readonly auth?: { readonly type: string; readonly label: string }; readonly enabled?: boolean; readonly safe?: boolean; - readonly probeUsage?: Effect.Effect; + readonly probeUsage?: Effect.Effect; } = {}, ) { const initialProbe = yield* Deferred.make(); @@ -677,11 +678,16 @@ it.layer(layerTest)("Antigravity provider snapshots", (it) => { }, ], }; - const usage = yield* Ref.make(limits); + const usage = yield* Ref.make({ + limits, + email: "user@example.com", + }); const harness = yield* makeHarness({ probeUsage: Ref.get(usage) }); const published = yield* harness.nextPublish((snapshot) => !!snapshot.usageLimits); yield* harness.initialize; - expect((yield* published)?.usageLimits).toEqual(limits); + const first = yield* published; + expect(first?.usageLimits).toEqual(limits); + expect(first?.auth.email).toBe("user@example.com"); // The second health check is the one the failed background read triggers. const checks = yield* Ref.make(0); const failedReadApplied = yield* Deferred.make(); @@ -695,34 +701,55 @@ it.layer(layerTest)("Antigravity provider snapshots", (it) => { ), ); yield* Ref.set(usage, { - checkedAt: "2026-10-09T12:01:00.000Z", - windows: [], - unavailable: { reason: "probeFailed" }, + limits: { + checkedAt: "2026-10-09T12:01:00.000Z", + windows: [], + unavailable: { reason: "probeFailed" }, + }, }); yield* harness.provider.snapshot.refresh; yield* Deferred.await(failedReadApplied); - expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toEqual(limits); + const retained = yield* harness.provider.snapshot.getSnapshot; + expect(retained.usageLimits).toEqual(limits); + expect(retained.auth.email).toBe("user@example.com"); + const firstSignedOutPublish = yield* harness.provider.snapshot.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.auth.status === "unauthenticated"), + Stream.take(1), + Stream.runCollect, + Effect.forkChild, + ); + yield* Effect.yieldNow; yield* harness.provider.onSignedOut; - expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toBeUndefined(); + const streamedSignedOut = Array.from(yield* Fiber.join(firstSignedOutPublish))[0]; + expect(streamedSignedOut?.auth.status).toBe("unauthenticated"); + expect(streamedSignedOut?.usageLimits).toBeUndefined(); + expect(streamedSignedOut?.auth.email).toBeUndefined(); + const signedOut = yield* harness.provider.snapshot.getSnapshot; + expect(signedOut.usageLimits).toBeUndefined(); + expect(signedOut.auth.email).toBeUndefined(); yield* Ref.set(usage, { - checkedAt: "2026-10-09T12:02:00.000Z", - windows: [], - unavailable: { reason: "unsupported" }, + limits: { + checkedAt: "2026-10-09T12:02:00.000Z", + windows: [], + unavailable: { reason: "unsupported" }, + }, }); const unsupported = yield* harness.nextPublish( (snapshot) => snapshot.usageLimits?.unavailable?.reason === "unsupported", ); yield* harness.provider.snapshot.refresh; - expect((yield* unsupported)?.usageLimits?.windows).toEqual([]); + const afterUnsupported = yield* unsupported; + expect(afterUnsupported?.usageLimits?.windows).toEqual([]); + expect(afterUnsupported?.auth.email).toBeUndefined(); }), ); it.effect("a quota read finishing after sign-out cannot restore account limits", () => Effect.gen(function* () { const readStarted = yield* Deferred.make(); - const readResult = yield* Deferred.make(); - const usage = yield* Ref.make>( - Effect.succeed({ checkedAt: "2026-10-09T12:00:00.000Z", windows: [] }), + const readResult = yield* Deferred.make(); + const usage = yield* Ref.make>( + Effect.succeed({ limits: { checkedAt: "2026-10-09T12:00:00.000Z", windows: [] } }), ); const harness = yield* makeHarness({ probeUsage: Ref.get(usage).pipe(Effect.flatten) }); yield* harness.initialize; @@ -735,11 +762,18 @@ it.layer(layerTest)("Antigravity provider snapshots", (it) => { yield* Deferred.await(readStarted); yield* harness.provider.onSignedOut; yield* Deferred.succeed(readResult, { - checkedAt: "2026-10-09T12:01:00.000Z", - windows: [{ id: "gemini-5h", kind: "session", label: "Gemini · 5-hour", usedPercent: 10 }], + email: "stale@example.com", + limits: { + checkedAt: "2026-10-09T12:01:00.000Z", + windows: [ + { id: "gemini-5h", kind: "session", label: "Gemini · 5-hour", usedPercent: 10 }, + ], + }, }); yield* Fiber.join(refresh); - expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toBeUndefined(); + const snapshot = yield* harness.provider.snapshot.getSnapshot; + expect(snapshot.usageLimits).toBeUndefined(); + expect(snapshot.auth.email).toBeUndefined(); }), ); @@ -747,7 +781,7 @@ it.layer(layerTest)("Antigravity provider snapshots", (it) => { Effect.gen(function* () { const reads = yield* Ref.make(0); const readStarted = yield* Deferred.make(); - const readResult = yield* Deferred.make(); + const readResult = yield* Deferred.make(); const harness = yield* makeHarness({ probeUsage: Ref.update(reads, (count) => count + 1).pipe( Effect.andThen(Deferred.succeed(readStarted, undefined)), @@ -767,8 +801,13 @@ it.layer(layerTest)("Antigravity provider snapshots", (it) => { checkedAt: "2026-10-09T12:00:00.000Z", windows: [{ id: "gemini-5h", kind: "session", label: "Gemini · 5-hour", usedPercent: 10 }], } satisfies ServerProviderUsageLimits; - yield* Deferred.succeed(readResult, limits); - expect((yield* published)?.usageLimits).toEqual(limits); + yield* Deferred.succeed(readResult, { limits, email: "first@example.com" }); + const afterProbe = yield* published; + expect(afterProbe?.usageLimits).toEqual(limits); + expect(afterProbe?.auth.email).toBe("first@example.com"); + // Subsequent session starts keep the email resolved from the usage probe. + yield* harness.provider.onSessionStarted(started, "/workspace"); + expect((yield* harness.provider.snapshot.getSnapshot).auth.email).toBe("first@example.com"); }), ); @@ -779,31 +818,317 @@ it.layer(layerTest)("Antigravity provider snapshots", (it) => { checkedAt: "2026-10-09T12:01:00.000Z", windows: [{ id: "3p-weekly", kind: "weekly", label: "Weekly", usedPercent: 40 }], } satisfies ServerProviderUsageLimits; - const usage = yield* Ref.make>( + const usage = yield* Ref.make>( Deferred.succeed(oldReadStarted, undefined).pipe(Effect.andThen(Effect.never)), ); const harness = yield* makeHarness({ probeUsage: Ref.get(usage).pipe(Effect.flatten) }); const published = yield* harness.nextPublish((snapshot) => !!snapshot.usageLimits); yield* harness.initialize; yield* Deferred.await(oldReadStarted); - yield* Ref.set(usage, Effect.succeed(newLimits)); + yield* Ref.set(usage, Effect.succeed({ limits: newLimits, email: "new@example.com" })); yield* harness.provider.onSignedIn; yield* harness.provider.onSessionStarted(started); - expect((yield* published)?.usageLimits).toEqual(newLimits); + const afterSignIn = yield* published; + expect(afterSignIn?.usageLimits).toEqual(newLimits); + expect(afterSignIn?.auth.email).toBe("new@example.com"); // Switching again must not republish the previous account's limits, even if the read fails. const failed = { checkedAt: "2026-10-09T12:02:00.000Z", windows: [], unavailable: { reason: "probeFailed" }, } satisfies ServerProviderUsageLimits; - yield* Ref.set(usage, Effect.succeed(failed)); + yield* Ref.set(usage, Effect.succeed({ limits: failed })); const republished = yield* harness.nextPublish( (snapshot) => snapshot.usageLimits?.unavailable?.reason === "probeFailed", ); yield* harness.provider.onSignedIn; - expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toBeUndefined(); + const cleared = yield* harness.provider.snapshot.getSnapshot; + expect(cleared.usageLimits).toBeUndefined(); + expect(cleared.auth.email).toBeUndefined(); yield* harness.provider.onSessionStarted(started); - expect((yield* republished)?.usageLimits).toEqual(failed); + const afterFailedSwitch = yield* republished; + expect(afterFailedSwitch?.usageLimits).toEqual(failed); + expect(afterFailedSwitch?.auth.email).toBeUndefined(); + }), + ); + + const makePublicationCollector = (stream: Stream.Stream) => + Effect.gen(function* () { + const emitted = yield* Ref.make>([]); + const waiters = yield* Ref.make< + Array<{ + readonly match: (snapshot: ServerProvider, count: number) => boolean; + readonly deferred: Deferred.Deferred; + }> + >([]); + yield* stream.pipe( + Stream.runForEach((snapshot) => + Effect.gen(function* () { + const count = yield* Ref.modify(emitted, (all) => { + const next = [...all, snapshot]; + return [next.length, next] as const; + }); + const matched = yield* Ref.modify(waiters, (current) => { + const ready: Array> = []; + const pending: typeof current = []; + for (const waiter of current) { + if (waiter.match(snapshot, count)) { + ready.push(waiter.deferred); + } else { + pending.push(waiter); + } + } + return [ready, pending] as const; + }); + for (const deferred of matched) { + yield* Deferred.succeed(deferred, snapshot); + } + }), + ), + Effect.forkScoped, + ); + yield* Effect.yieldNow; + return { + emitted: Ref.get(emitted), + waitFor: (predicate: (snapshot: ServerProvider) => boolean) => + Effect.gen(function* () { + const deferred = yield* Deferred.make(); + yield* Ref.update(waiters, (current) => [ + ...current, + { match: (snapshot) => predicate(snapshot), deferred }, + ]); + return Deferred.await(deferred); + }), + waitForCount: (delta: number) => + Effect.gen(function* () { + const target = (yield* Ref.get(emitted)).length + delta; + const deferred = yield* Deferred.make(); + yield* Ref.update(waiters, (current) => [ + ...current, + { match: (_snapshot, count) => count >= target, deferred }, + ]); + return Deferred.await(deferred); + }), + }; + }); + + it.effect( + "does not pair a previous account's email or retained limits with a different credential", + () => + Effect.gen(function* () { + const accountALimits: ServerProviderUsageLimits = { + checkedAt: "2026-10-09T12:00:00.000Z", + credentialFingerprint: "fingerprint-a", + windows: [ + { + id: "3p-weekly", + kind: "weekly", + label: "Claude & GPT (shared) · Weekly", + usedPercent: 75, + }, + ], + }; + const usage = yield* Ref.make({ + limits: accountALimits, + email: "Account-A@example.com", + }); + const harness = yield* makeHarness({ probeUsage: Ref.get(usage) }); + const collector = yield* makePublicationCollector(harness.provider.snapshot.streamChanges); + const initialPublish = yield* collector.waitFor((snapshot) => !!snapshot.usageLimits); + yield* harness.initialize; + const first = yield* initialPublish; + expect(first.auth.email).toBe("Account-A@example.com"); + expect(first.usageLimits).toEqual(accountALimits); + + const waitForUsageRefresh = Effect.gen(function* () { + const secondPublish = yield* collector.waitForCount(2); + yield* harness.provider.snapshot.refresh; + return yield* secondPublish; + }); + + // Case-only email difference on unchanged credential fingerprint retains limits on failure. + yield* Ref.set(usage, { + email: "account-a@example.com", + limits: { + checkedAt: "2026-10-09T12:00:30.000Z", + credentialFingerprint: "fingerprint-a", + windows: [], + unavailable: { reason: "probeFailed" }, + }, + }); + const afterCaseOnlyFailure = yield* waitForUsageRefresh; + expect(afterCaseOnlyFailure.auth.email).toBe("account-a@example.com"); + expect(afterCaseOnlyFailure.usageLimits).toEqual(accountALimits); + + // Missing email on unchanged credential fingerprint retains the previous email. + const updatedALimits: ServerProviderUsageLimits = { + ...accountALimits, + checkedAt: "2026-10-09T12:01:00.000Z", + windows: [{ ...accountALimits.windows[0]!, usedPercent: 80 }], + }; + yield* Ref.set(usage, { limits: updatedALimits }); + const sameAccountWithoutEmail = yield* waitForUsageRefresh; + expect(sameAccountWithoutEmail.auth.email).toBe("account-a@example.com"); + expect(sameAccountWithoutEmail.usageLimits).toEqual(updatedALimits); + + // Quota-read failure for a different account must not retain account A's limits. + const failedAccountBLimits: ServerProviderUsageLimits = { + checkedAt: "2026-10-09T12:02:00.000Z", + credentialFingerprint: "fingerprint-b", + windows: [], + unavailable: { reason: "probeFailed" }, + }; + yield* Ref.set(usage, { + limits: failedAccountBLimits, + email: "account-b@example.com", + }); + const afterFailedSwitch = yield* waitForUsageRefresh; + expect(afterFailedSwitch.auth.email).toBe("account-b@example.com"); + expect(afterFailedSwitch.usageLimits).toEqual(failedAccountBLimits); + + // Successful read for another credential without email must not keep account B's email. + const accountCLimits: ServerProviderUsageLimits = { + checkedAt: "2026-10-09T12:03:00.000Z", + credentialFingerprint: "fingerprint-c", + windows: [ + { + id: "gemini-5h", + kind: "session", + label: "Gemini · 5-hour", + usedPercent: 20, + }, + ], + }; + yield* Ref.set(usage, { limits: accountCLimits }); + const afterMissingEmailSwitch = yield* waitForUsageRefresh; + expect(afterMissingEmailSwitch.auth.email).toBeUndefined(); + expect(afterMissingEmailSwitch.usageLimits).toEqual(accountCLimits); + + // Quota-read failure with a newly discovered email that was not verified for fingerprint-c + // must not retain fingerprint-c's limits. + const unverifiedFailedLimits: ServerProviderUsageLimits = { + checkedAt: "2026-10-09T12:04:00.000Z", + windows: [], + unavailable: { reason: "probeFailed" }, + }; + yield* Ref.set(usage, { + limits: unverifiedFailedLimits, + email: "account-d@example.com", + }); + const afterUnverifiedEmailFailure = yield* waitForUsageRefresh; + expect(afterUnverifiedEmailFailure.auth.email).toBe("account-d@example.com"); + expect(afterUnverifiedEmailFailure.usageLimits).toEqual(unverifiedFailedLimits); + + // Every published snapshot must keep email and fingerprint from the same account. + const snapshots = yield* collector.emitted; + for (const snapshot of snapshots) { + const email = snapshot.auth.email?.toLowerCase(); + const fp = snapshot.usageLimits?.credentialFingerprint; + if (email === "account-a@example.com") expect(fp).toBe("fingerprint-a"); + if (email === "account-b@example.com") expect(fp).toBe("fingerprint-b"); + if (email === "account-d@example.com") expect(fp).toBeUndefined(); + if (fp === "fingerprint-c") expect(email).toBeUndefined(); + } + }), + ); + + it.effect("keeps published email and usage limits from the same account during enrichment", () => + Effect.gen(function* () { + const accountALimits: ServerProviderUsageLimits = { + checkedAt: "2026-10-09T12:00:00.000Z", + credentialFingerprint: "fingerprint-a", + windows: [ + { + id: "3p-weekly", + kind: "weekly", + label: "Claude & GPT (shared) · Weekly", + usedPercent: 75, + }, + ], + }; + const accountBLimits: ServerProviderUsageLimits = { + checkedAt: "2026-10-09T12:05:00.000Z", + credentialFingerprint: "fingerprint-b", + windows: [ + { + id: "3p-weekly", + kind: "weekly", + label: "Claude & GPT (shared) · Weekly", + usedPercent: 10, + }, + ], + }; + const usage = yield* Ref.make({ + limits: accountALimits, + email: "account-a@example.com", + }); + const harness = yield* makeHarness({ probeUsage: Ref.get(usage) }); + const collector = yield* makePublicationCollector(harness.provider.snapshot.streamChanges); + + const initialPublish = yield* collector.waitFor((snapshot) => !!snapshot.usageLimits); + yield* harness.initialize; + const first = yield* initialPublish; + expect(first.auth.email).toBe("account-a@example.com"); + expect(first.usageLimits).toEqual(accountALimits); + + // Hold the republish health check after account B's usage probe finishes so enrichment runs + // while account A's usageLimits are still the published snapshot. + const checks = yield* Ref.make(0); + const republishEntered = yield* Deferred.make(); + const releaseRepublish = yield* Deferred.make(); + yield* Ref.set( + harness.probe, + Ref.updateAndGet(checks, (count) => count + 1).pipe( + Effect.flatMap((count) => + count === 2 + ? Deferred.succeed(republishEntered, undefined).pipe( + Effect.andThen(Deferred.await(releaseRepublish)), + Effect.as(initializeResult), + ) + : Effect.succeed(initializeResult), + ), + ), + ); + yield* Ref.set(usage, { + limits: accountBLimits, + email: "account-b@example.com", + }); + yield* harness.provider.snapshot.refresh; + yield* Deferred.await(republishEntered); + + // Trigger an enrichment publish while account B is already in metadata.draft but republish + // has not replaced the published limits yet. + const enrichedCommand = yield* collector.waitFor( + (snapshot) => snapshot.slashCommands.length > 0, + ); + yield* harness.provider.onAvailableCommands(commands, "/workspace"); + const duringEnrichment = yield* enrichedCommand; + expect(duringEnrichment.auth.email).toBe("account-a@example.com"); + expect(duringEnrichment.usageLimits).toEqual(accountALimits); + + const accountBPublished = yield* collector.waitFor( + (snapshot) => snapshot.usageLimits?.credentialFingerprint === "fingerprint-b", + ); + yield* Deferred.succeed(releaseRepublish, undefined); + const finalSnapshot = yield* accountBPublished; + expect(finalSnapshot.auth.email).toBe("account-b@example.com"); + expect(finalSnapshot.usageLimits).toEqual(accountBLimits); + + const snapshots = yield* collector.emitted; + expect( + snapshots.some( + (snapshot) => + snapshot.auth.email === "account-b@example.com" && + snapshot.usageLimits?.credentialFingerprint === "fingerprint-a", + ), + ).toBe(false); + expect( + snapshots.some( + (snapshot) => + snapshot.auth.email === "account-a@example.com" && + snapshot.usageLimits?.credentialFingerprint === "fingerprint-b", + ), + ).toBe(false); }), ); }); diff --git a/apps/server/src/provider/AntigravityProvider.ts b/apps/server/src/provider/AntigravityProvider.ts index 7510106f2c5dc..b8840a076bc7b 100644 --- a/apps/server/src/provider/AntigravityProvider.ts +++ b/apps/server/src/provider/AntigravityProvider.ts @@ -7,7 +7,6 @@ import { type ServerProvider, type ServerProviderModel, type ServerProviderSlashCommand, - type ServerProviderUsageLimits, } from "@t3tools/contracts"; import { createModelCapabilities } from "@t3tools/shared/model"; import * as Context from "effect/Context"; @@ -38,6 +37,7 @@ import { import { resolveUsageLimitsAfterProbe } from "@t3tools/provider-core/server/usageLimits"; import { antigravityThinkingConfig } from "./acp/AntigravityAcpSupport.ts"; +import type { AntigravityUsageProbeResult } from "./antigravityUsageLimits.ts"; const EMPTY_MODEL_CAPABILITIES = createModelCapabilities({ optionDescriptors: [] }); const MAX_WORKSPACE_SNAPSHOTS = 32; @@ -163,7 +163,7 @@ interface AntigravityProviderOptions { EffectAcpErrors.AcpError | ProviderSetupError >; readonly supportsTextGeneration: Effect.Effect; - readonly probeUsage?: Effect.Effect; + readonly probeUsage?: Effect.Effect; readonly clearUsage?: Effect.Effect; readonly maintenanceCapabilities?: ProviderMaintenanceCapabilities; readonly auth?: { readonly type: string; readonly label: string }; @@ -240,16 +240,54 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func 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) => { + const { email: previousEmail, ...auth } = state.draft.auth; + const previousLimits = state.draft.usageLimits; + const previousFingerprint = previousLimits?.credentialFingerprint; + const previousEmailKey = previousEmail?.toLowerCase(); + const probedEmail = probed.email?.trim() || undefined; + const probedEmailKey = probedEmail?.toLowerCase(); + const probedFingerprint = probed.limits.credentialFingerprint; + const fingerprintConflict = + (probedFingerprint !== undefined || !probed.limits.unavailable) && + probedFingerprint !== previousFingerprint; + const emailConflict = + probedEmailKey !== undefined && + previousEmailKey !== undefined && + probedEmailKey !== previousEmailKey; + const sameFingerprint = + probedFingerprint !== undefined && probedFingerprint === previousFingerprint; + const sameEmail = probedEmailKey !== undefined && probedEmailKey === previousEmailKey; + const transientFailureWithoutIdentity = + probed.limits.unavailable?.reason === "probeFailed" && + probedFingerprint === undefined && + probedEmail === undefined; + const sameAccount = + !fingerprintConflict && + !emailConflict && + (sameFingerprint || sameEmail || transientFailureWithoutIdentity); + const usageLimits = resolveUsageLimitsAfterProbe({ + published: sameAccount ? previousLimits : undefined, + probed: probed.limits, + }); + const email = + probed.limits.unavailable?.reason === "unsupported" + ? undefined + : (probedEmail ?? (sameAccount ? previousEmail : undefined)); + return { + ...state, + draft: { + ...state.draft, + auth: + state.draft.auth.status === "unauthenticated" + ? auth + : email + ? { ...auth, email } + : auth, + usageLimits, + }, + }; + }), ), // Enrichment cannot change published limits; a health check publishes them. Effect.andThen( @@ -354,10 +392,25 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func haveSettingsChanged: () => false, initialSnapshot: () => getSnapshot, checkProvider: checkProvider(), - enrichSnapshot: ({ publishSnapshot }) => + enrichSnapshot: ({ getSnapshot: getPublished, publishSnapshot }) => SubscriptionRef.changes(metadata).pipe( Stream.runForEach((state) => - options.stampIdentity(state.draft).pipe(Effect.flatMap(publishSnapshot)), + Effect.gen(function* () { + const published = yield* getPublished; + // publishEnrichedSnapshot keeps the published usageLimits; align auth.email to that + // same snapshot so a different-account usage read never publishes a mixed identity. + const draft = + state.draft.auth.status === "unauthenticated" + ? state.draft + : (() => { + const { email: _draftEmail, ...auth } = state.draft.auth; + return { + ...state.draft, + auth: published.auth.email ? { ...auth, email: published.auth.email } : auth, + }; + })(); + yield* options.stampIdentity(draft).pipe(Effect.flatMap(publishSnapshot)); + }), ), ), }); @@ -393,6 +446,7 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func status: "authenticated", type: options.auth?.type ?? "oauth-personal", label: options.auth?.label ?? "Google account", + ...(draft.auth.email ? { email: draft.auth.email } : {}), }, checkedAt: updatedAt, models: buildAntigravityModelsFromSession(started.sessionSetupResult, thinkingLevels), @@ -532,7 +586,8 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func Effect.andThen( SubscriptionRef.update(metadata, (state) => { const { usageLimits: _previousAccount, ...draft } = state.draft; - return { ...state, draft }; + const { email: _previousEmail, ...auth } = draft.auth; + return { ...state, draft: { ...draft, auth } }; }), ), Effect.andThen( diff --git a/apps/server/src/provider/antigravityUsageLimits.test.ts b/apps/server/src/provider/antigravityUsageLimits.test.ts index 9defd9df90dce..3ce9499955865 100644 --- a/apps/server/src/provider/antigravityUsageLimits.test.ts +++ b/apps/server/src/provider/antigravityUsageLimits.test.ts @@ -63,6 +63,7 @@ const fixture = Effect.fn("AntigravityUsageTest.fixture")(function* ( tokenStatus?: number; refreshToken?: string; userId?: string; + userEmail?: string | null | undefined; userInfoAt?: number; missingToken?: boolean; authMethod?: "oauth-personal" | "oauth-business" | "gemini-api-key"; @@ -107,7 +108,14 @@ const fixture = Effect.fn("AntigravityUsageTest.fixture")(function* ( return HttpClientResponse.fromWeb( request, options.userId - ? Response.json({ id: options.userId, email: "someone@example.com" }) + ? Response.json({ + id: options.userId, + ...(options.userEmail === undefined + ? { email: "someone@example.com" } + : options.userEmail === null + ? {} + : { email: options.userEmail }), + }) : Response.json({}, { status: 403 }), ); } @@ -179,7 +187,7 @@ describe("Antigravity subscription limits", () => { ], }, }); - const limits = yield* probe; + const { limits } = yield* probe; const byId = new Map(limits.windows.map((window) => [window.id, window])); expect(byId.get("3p-5h")).toEqual({ id: "3p-5h", @@ -217,7 +225,7 @@ describe("Antigravity subscription limits", () => { ], }, }); - expect((yield* probe).windows[0]?.resetsAt).toBeUndefined(); + expect((yield* probe).limits.windows[0]?.resetsAt).toBeUndefined(); }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); @@ -263,7 +271,7 @@ describe("Antigravity subscription limits", () => { ], }, }); - expect((yield* probe).windows.map(({ id, resetsAt }) => ({ id, resetsAt }))).toEqual([ + expect((yield* probe).limits.windows.map(({ id, resetsAt }) => ({ id, resetsAt }))).toEqual([ { id: "described", resetsAt: "2026-10-21T15:16:04.000Z" }, { id: "empty-description", resetsAt: "2026-10-21T15:16:04.000Z" }, { id: "overfull", resetsAt: "2026-10-21T15:16:04.000Z" }, @@ -319,7 +327,7 @@ describe("Antigravity subscription limits", () => { ], }, }); - expect((yield* probe).windows.map(({ id, resetsAt }) => ({ id, resetsAt }))).toEqual([ + expect((yield* probe).limits.windows.map(({ id, resetsAt }) => ({ id, resetsAt }))).toEqual([ { id: "5h-after", resetsAt: "2026-10-21T15:17:05.000Z" }, { id: "5h-before", resetsAt: undefined }, { id: "5h-edge", resetsAt: undefined }, @@ -371,7 +379,7 @@ describe("Antigravity subscription limits", () => { }, }, }); - expect((yield* probe).windows).toEqual([ + expect((yield* probe).limits.windows).toEqual([ { id: "3p-5h", label: "Claude & GPT (shared) · 5-hour", @@ -407,7 +415,7 @@ describe("Antigravity subscription limits", () => { }, }); expect( - (yield* probe).windows.map(({ id, resetsAt, windowDurationMins }) => ({ + (yield* probe).limits.windows.map(({ id, resetsAt, windowDurationMins }) => ({ id, resetsAt, windowDurationMins, @@ -422,7 +430,8 @@ describe("Antigravity subscription limits", () => { it.effect("reports separate Gemini and shared Claude/GPT five-hour and weekly limits", () => Effect.gen(function* () { const { probe, requests } = yield* fixture(); - const limits = yield* probe; + const { limits, email } = yield* probe; + expect(email).toBeUndefined(); expect(limits.windows).toHaveLength(4); expect(limits.unavailable).toBeUndefined(); expect(limits.credentialFingerprint).toMatch(/^[0-9a-f]{64}$/); @@ -464,7 +473,7 @@ describe("Antigravity subscription limits", () => { }, }, }); - const limits = yield* probe; + const { limits } = yield* probe; expect(limits.windows.map((window) => window.id).toSorted()).toEqual([ "3p-5h", "3p-weekly", @@ -504,7 +513,7 @@ describe("Antigravity subscription limits", () => { "cloudcode-pa.googleapis.com": argon(0, "2026-11-08T18:27:14Z"), }, }); - expect((yield* probe).windows).toEqual([ + expect((yield* probe).limits.windows).toEqual([ expect.objectContaining({ id: "gemini-argon-wtu-weekly", usedPercent: expect.closeTo(13.77, 2), @@ -539,7 +548,7 @@ describe("Antigravity subscription limits", () => { ], }, }); - const limits = yield* probe; + const { limits } = yield* probe; const byId = new Map(limits.windows.map((window) => [window.id, window])); expect(byId.get("gemini-weekly")?.label).toBe("Gemini · Weekly"); expect(byId.get("gemini-argon-wtu-weekly")?.label).toBe("Gemini 4 Argon · Weekly"); @@ -553,7 +562,7 @@ describe("Antigravity subscription limits", () => { const { probe } = yield* fixture({ summaryStatusByHost: { "daily-cloudcode-pa.googleapis.com": 503 }, }); - const limits = yield* probe; + const { limits } = yield* probe; expect(limits.unavailable).toBeUndefined(); expect(limits.windows).toHaveLength(4); }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), @@ -565,10 +574,10 @@ describe("Antigravity subscription limits", () => { const first = yield* probe; yield* writeToken("refresh-b"); const second = yield* probe; - expect(second.credentialFingerprint).not.toBe(first.credentialFingerprint); + expect(second.limits.credentialFingerprint).not.toBe(first.limits.credentialFingerprint); expect(requests.filter((request) => request.url.endsWith("/token"))).toHaveLength(2); yield* (yield* FileSystem.FileSystem).remove(tokenPath); - expect((yield* probe).unavailable?.reason).toBe("unsupported"); + expect((yield* probe).limits.unavailable?.reason).toBe("unsupported"); yield* writeToken("refresh-b"); yield* probe; expect(requests.filter((request) => request.url.endsWith("/token"))).toHaveLength(3); @@ -578,17 +587,49 @@ describe("Antigravity subscription limits", () => { }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); + it.effect("caches normalized account email across probes and clears it on sign-out", () => + Effect.gen(function* () { + const { probe, requests, writeToken, tokenPath } = yield* fixture({ + userId: "google-user-1", + userEmail: " someone@example.com ", + }); + const first = yield* probe; + expect(first.email).toBe("someone@example.com"); + expect((yield* probe).email).toBe("someone@example.com"); + expect(requests.filter((request) => request.url.endsWith("/userinfo"))).toHaveLength(1); + yield* (yield* FileSystem.FileSystem).remove(tokenPath); + const signedOut = yield* probe; + expect(signedOut.limits.unavailable?.reason).toBe("unsupported"); + expect(signedOut.email).toBeUndefined(); + yield* writeToken("refresh-b"); + expect((yield* probe).email).toBe("someone@example.com"); + expect(requests.filter((request) => request.url.endsWith("/userinfo"))).toHaveLength(2); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ); + it.effect("names one Google account the same way from every sign-in", () => Effect.gen(function* () { - const read = (refreshToken: string, userId: string) => - fixture({ refreshToken, userId }).pipe(Effect.flatMap((usage) => usage.probe)); + const read = (refreshToken: string, userId: string, userEmail?: string | null) => + fixture({ refreshToken, userId, userEmail }).pipe(Effect.flatMap((usage) => usage.probe)); const machineA = yield* read("refresh-a", "google-user-1"); const machineB = yield* read("refresh-b", "google-user-1"); - const otherAccount = yield* read("refresh-c", "google-user-2"); - expect(machineA.credentialFingerprint).toMatch(/^[0-9a-f]{64}$/); - expect(machineB.credentialFingerprint).toBe(machineA.credentialFingerprint); - expect(otherAccount.credentialFingerprint).not.toBe(machineA.credentialFingerprint); - expect(JSON.stringify(machineA)).not.toMatch(/google-user-1|someone@example.com/); + const otherAccount = yield* read("refresh-c", "google-user-2", "other@example.com"); + const missingEmail = yield* read("refresh-d", "google-user-3", null); + const blankEmail = yield* read("refresh-e", "google-user-3", " "); + expect(machineA.limits.credentialFingerprint).toMatch(/^[0-9a-f]{64}$/); + expect(machineB.limits.credentialFingerprint).toBe(machineA.limits.credentialFingerprint); + expect(otherAccount.limits.credentialFingerprint).not.toBe( + machineA.limits.credentialFingerprint, + ); + expect(machineA.email).toBe("someone@example.com"); + expect(machineB.email).toBe("someone@example.com"); + expect(otherAccount.email).toBe("other@example.com"); + expect(missingEmail.email).toBeUndefined(); + expect(blankEmail.email).toBeUndefined(); + expect(blankEmail.limits.credentialFingerprint).toBe( + missingEmail.limits.credentialFingerprint, + ); + expect(JSON.stringify(machineA.limits)).not.toMatch(/google-user-1|someone@example.com/); }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); @@ -610,7 +651,7 @@ describe("Antigravity subscription limits", () => { }, }, }); - const limits = yield* probe; + const { limits } = yield* probe; expect(limits.windows).toHaveLength(2); expect(limits.windows.find((window) => window.id === "gemini-quota")?.usedPercent).toBe(40); expect( @@ -632,7 +673,7 @@ describe("Antigravity subscription limits", () => { ], }, }); - expect((yield* probe).windows).toEqual([ + expect((yield* probe).limits.windows).toEqual([ { id: "gemini-5h", kind: "session", @@ -647,18 +688,36 @@ describe("Antigravity subscription limits", () => { it.effect("returns a safe failure when OAuth refresh fails", () => Effect.gen(function* () { const { probe } = yield* fixture({ tokenStatus: 401 }); - const limits = yield* probe; + const { limits, email } = yield* probe; + expect(email).toBeUndefined(); 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("includes account identity when quota endpoints return no usable windows", () => + Effect.gen(function* () { + const { probe } = yield* fixture({ + userId: "google-user-1", + userEmail: "someone@example.com", + summaryStatus: 503, + models: { models: {} }, + }); + const { limits, email } = yield* probe; + expect(email).toBe("someone@example.com"); + expect(limits.unavailable?.reason).toBe("probeFailed"); + expect(limits.credentialFingerprint).toMatch(/^[0-9a-f]{64}$/); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ); + 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 }]) { const { probe, requests } = yield* fixture(options); - expect((yield* probe).unavailable?.reason).toBe("unsupported"); + const result = yield* probe; + expect(result.limits.unavailable?.reason).toBe("unsupported"); + expect(result.email).toBeUndefined(); expect(requests).toEqual([]); } }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), diff --git a/apps/server/src/provider/antigravityUsageLimits.ts b/apps/server/src/provider/antigravityUsageLimits.ts index ede0e5c47d20e..be8ada1c6bfd4 100644 --- a/apps/server/src/provider/antigravityUsageLimits.ts +++ b/apps/server/src/provider/antigravityUsageLimits.ts @@ -1,4 +1,8 @@ -import type { AntigravitySettings, ServerProviderUsageWindow } from "@t3tools/contracts"; +import type { + AntigravitySettings, + ServerProviderUsageLimits, + ServerProviderUsageWindow, +} from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Clock from "effect/Clock"; import * as Digest from "effect/crypto/Digest"; @@ -42,7 +46,15 @@ const TokenResponse = Schema.Struct({ access_token: Schema.NonEmptyString, expires_in: Schema.Number.check(Schema.isGreaterThan(0)), }); -const UserInfo = Schema.Struct({ id: Schema.NonEmptyString }); +const UserInfo = Schema.Struct({ + id: Schema.NonEmptyString, + email: Schema.optional(Schema.NullOr(Schema.String)), +}); + +export interface AntigravityUsageProbeResult { + readonly limits: ServerProviderUsageLimits; + readonly email?: string | undefined; +} const Quota = Schema.Struct({ remainingFraction: Schema.optional(Schema.Number), resetTime: Schema.optional(Schema.String), @@ -219,7 +231,13 @@ export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")( const architecture = yield* HostProcess.Architecture; const tokenPath = path.join(input.profileDirectory, "antigravity-acp", "acp_token.json"); let cached: - | { fingerprint: string; account: string; accessToken: string; expiresAt: number } + | { + fingerprint: string; + account: string; + email: string | undefined; + accessToken: string; + expiresAt: number; + } | undefined; let generation = 0; @@ -234,15 +252,17 @@ export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")( const startedGeneration = generation; const checkedAt = DateTime.formatIso(yield* DateTime.now); if (input.authMethod !== "oauth-personal" && input.authMethod !== "oauth-business") { - return makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" }); + return { limits: makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" }) }; } if (!(yield* fs.exists(tokenPath))) { cached = undefined; - return makeUnavailableUsageLimits({ - checkedAt, - reason: "unsupported", - message: "Sign in with Google to see Antigravity limits.", - }); + return { + limits: makeUnavailableUsageLimits({ + checkedAt, + reason: "unsupported", + message: "Sign in with Google to see Antigravity limits.", + }), + }; } const token = yield* fs.readFileString(tokenPath).pipe(Effect.flatMap(decodeTokenFile)); const fingerprint = yield* sha256( @@ -251,7 +271,9 @@ export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")( const now = yield* Clock.currentTimeMillis; let accessToken: string; let account: string; + let email: string | undefined; if (cached?.fingerprint !== fingerprint || cached.expiresAt <= now + 60_000) { + const previous = cached?.fingerprint === fingerprint ? cached : undefined; cached = undefined; const refreshed = yield* request( HttpClientRequest.post("https://oauth2.googleapis.com/token").pipe( @@ -265,18 +287,32 @@ export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")( ).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( + const identity = yield* request( HttpClientRequest.get("https://www.googleapis.com/oauth2/v2/userinfo").pipe( HttpClientRequest.setHeaders({ Authorization: `Bearer ${accessToken}` }), ), ).pipe( - Effect.flatMap(antigravityAccountFingerprint), - Effect.orElseSucceed(() => fingerprint), + Effect.flatMap(decodeUserInfo), + Effect.flatMap((info) => + sha256(`google-account\0${info.id}`).pipe( + Effect.map((id) => ({ + account: id, + email: info.email?.trim() || undefined, + })), + ), + ), + Effect.orElseSucceed(() => ({ + account: previous?.account ?? fingerprint, + email: previous?.email, + })), ); + account = identity.account; + email = identity.email; if (generation === startedGeneration) { cached = { fingerprint, account, + email, accessToken, expiresAt: now + refreshed.expires_in * 1000, }; @@ -284,6 +320,7 @@ export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")( } else { accessToken = cached.accessToken; account = cached.account; + email = cached.email; } const endpoints = ENDPOINTS[input.authMethod]; // Merge endpoints because quota groups differ; the metered host's reading of a bucket wins. @@ -330,24 +367,35 @@ export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")( decodeModels(response).pipe(Effect.map(modelWindows)), ); if (windows.length === 0) { - return makeUnavailableUsageLimits({ - checkedAt, - reason: "probeFailed", - message: "Antigravity did not return usable quota information.", - }); + return { + limits: { + ...makeUnavailableUsageLimits({ + checkedAt, + reason: "probeFailed", + message: "Antigravity did not return usable quota information.", + }), + credentialFingerprint: account, + }, + ...(email ? { email } : {}), + }; } - return { ...makeUsageLimits({ checkedAt, windows }), credentialFingerprint: account }; + return { + limits: { ...makeUsageLimits({ checkedAt, windows }), credentialFingerprint: account }, + ...(email ? { email } : {}), + }; }); - const probe = read.pipe( + const probe: Effect.Effect = read.pipe( Effect.provideService(Digest.Digest, crypto), Effect.timeout("30 seconds"), Effect.catch(() => Effect.gen(function* () { - return makeUnavailableUsageLimits({ - checkedAt: DateTime.formatIso(yield* DateTime.now), - reason: "probeFailed", - message: "Could not read Antigravity limits. Refresh provider status to retry.", - }); + return { + limits: makeUnavailableUsageLimits({ + checkedAt: DateTime.formatIso(yield* DateTime.now), + reason: "probeFailed", + message: "Could not read Antigravity limits. Refresh provider status to retry.", + }), + }; }), ), ); diff --git a/packages/provider-core/src/server/managedProvider.test.ts b/packages/provider-core/src/server/managedProvider.test.ts index f878b2f44ecca..682be51dbc58d 100644 --- a/packages/provider-core/src/server/managedProvider.test.ts +++ b/packages/provider-core/src/server/managedProvider.test.ts @@ -1029,4 +1029,185 @@ describe("makeManagedServerProvider", () => { }), ).pipe(Effect.provide(layerAlwaysRunTest)), ); + + it.effect( + "does not retain fingerprinted limits across a failed probe with a different fingerprint or unverified email", + () => + Effect.scoped( + Effect.gen(function* () { + const accountALimits = { + checkedAt: "2026-04-10T00:00:01.000Z", + credentialFingerprint: "fp-a", + windows: [{ id: "primary", kind: "session", label: "Session", usedPercent: 30 }], + } as const; + const probeSnapshot = yield* Ref.make({ + ...refreshedSnapshot, + auth: { status: "authenticated" }, + usageLimits: accountALimits, + }); + const provider = yield* makeManagedServerProvider({ + resolveMaintenance: () => Effect.succeed(maintenanceCapabilities), + getSettings: Effect.succeed({ enabled: true }), + streamSettings: Stream.empty, + haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled, + initialSnapshot: () => Effect.succeed(initialSnapshot), + checkProvider: Ref.get(probeSnapshot), + refreshOnInterval: false, + }); + yield* Stream.take(provider.streamChanges, 1).pipe(Stream.runDrain); + + // Same fingerprint with newly discovered email verifies identity and retains limits. + const sameFpFailed = { + checkedAt: "2026-04-10T00:00:02.000Z", + credentialFingerprint: "fp-a", + windows: [], + unavailable: { reason: "probeFailed" }, + } as const; + yield* Ref.set(probeSnapshot, { + ...refreshedSnapshot, + auth: { status: "authenticated", email: "a@example.com" }, + usageLimits: sameFpFailed, + }); + const verified = yield* provider.refresh; + assert.strictEqual(verified.auth.email, "a@example.com"); + assert.deepStrictEqual(verified.usageLimits, accountALimits); + + // Different fingerprint without email must not retain account A's limits. + const otherFpFailed = { + checkedAt: "2026-04-10T00:00:03.000Z", + credentialFingerprint: "fp-b", + windows: [], + unavailable: { reason: "probeFailed" }, + } as const; + yield* Ref.set(probeSnapshot, { + ...refreshedSnapshot, + auth: { status: "authenticated" }, + usageLimits: otherFpFailed, + }); + const switchedFp = yield* provider.refresh; + assert.strictEqual(switchedFp.auth.email, undefined); + assert.deepStrictEqual(switchedFp.usageLimits, otherFpFailed); + + // Publish a fingerprinted account without email, then fail with an unverified email. + const accountCLimits = { + checkedAt: "2026-04-10T00:00:04.000Z", + credentialFingerprint: "fp-c", + windows: [{ id: "primary", kind: "session", label: "Session", usedPercent: 50 }], + } as const; + yield* Ref.set(probeSnapshot, { + ...refreshedSnapshot, + auth: { status: "authenticated" }, + usageLimits: accountCLimits, + }); + assert.deepStrictEqual((yield* provider.refresh).usageLimits, accountCLimits); + + const unverifiedFailed = { + checkedAt: "2026-04-10T00:00:05.000Z", + windows: [], + unavailable: { reason: "probeFailed" }, + } as const; + yield* Ref.set(probeSnapshot, { + ...refreshedSnapshot, + auth: { status: "authenticated", email: "d@example.com" }, + usageLimits: unverifiedFailed, + }); + const unverified = yield* provider.refresh; + assert.strictEqual(unverified.auth.email, "d@example.com"); + assert.deepStrictEqual(unverified.usageLimits, unverifiedFailed); + + // Unfingerprinted providers retain valid limits when a failed probe first discovers email. + const unfingerprintedLimits = { + checkedAt: "2026-04-10T00:00:06.000Z", + windows: [{ id: "primary", kind: "session", label: "Session", usedPercent: 45 }], + } as const; + yield* Ref.set(probeSnapshot, { + ...refreshedSnapshot, + auth: { status: "authenticated" }, + usageLimits: unfingerprintedLimits, + }); + assert.deepStrictEqual((yield* provider.refresh).usageLimits, unfingerprintedLimits); + + yield* Ref.set(probeSnapshot, { + ...refreshedSnapshot, + auth: { status: "authenticated", email: "claude@example.com" }, + usageLimits: { + checkedAt: "2026-04-10T00:00:07.000Z", + windows: [], + unavailable: { reason: "probeFailed" }, + }, + }); + const firstEmailFailure = yield* provider.refresh; + assert.strictEqual(firstEmailFailure.auth.email, "claude@example.com"); + assert.deepStrictEqual(firstEmailFailure.usageLimits, unfingerprintedLimits); + }), + ).pipe(Effect.provide(layerAlwaysRunTest)), + ); + + it.effect( + "clears published usage limits when enrichment publishes an unauthenticated reset", + () => + Effect.scoped( + Effect.gen(function* () { + const limits = { + checkedAt: "2026-04-10T00:00:01.000Z", + windows: [{ id: "primary", kind: "session", label: "Session", usedPercent: 30 }], + } as const; + const publishEnrichedDeferred = + yield* Deferred.make<(snapshot: ServerProvider) => Effect.Effect>(); + const provider = yield* makeManagedServerProvider({ + resolveMaintenance: () => Effect.succeed(maintenanceCapabilities), + getSettings: Effect.succeed({ enabled: true }), + streamSettings: Stream.empty, + haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled, + initialSnapshot: () => Effect.succeed(initialSnapshot), + checkProvider: Effect.succeed({ + ...refreshedSnapshot, + auth: { status: "authenticated", email: "a@example.com" }, + usageLimits: limits, + }), + enrichSnapshot: ({ publishSnapshot }) => + Deferred.succeed(publishEnrichedDeferred, publishSnapshot).pipe(Effect.asVoid), + refreshOnInterval: false, + }); + const publishEnriched = yield* Deferred.await(publishEnrichedDeferred); + yield* provider.applyUsageLimits({ ...limits, complete: true, authLabel: "Pro" }); + + // Ordinary authenticated enrichment keeps published limits and auth label. + const authEnrichedFiber = yield* provider.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.models.length > 0), + Stream.take(1), + Stream.runCollect, + Effect.forkChild, + ); + yield* Effect.yieldNow; + yield* publishEnriched({ + ...enrichedSnapshot, + auth: { status: "authenticated", email: "a@example.com" }, + }); + const authEnriched = Array.from(yield* Fiber.join(authEnrichedFiber))[0]; + assert.deepStrictEqual(authEnriched?.usageLimits, limits); + assert.strictEqual(authEnriched?.auth.label, "Pro"); + + // Unauthenticated reset enrichment clears published limits and auth label immediately. + const signedOutFiber = yield* provider.streamChanges.pipe( + Stream.filter((snapshot) => snapshot.auth.status === "unauthenticated"), + Stream.take(1), + Stream.runCollect, + Effect.forkChild, + ); + yield* Effect.yieldNow; + yield* publishEnriched({ + ...refreshedSnapshot, + status: "warning", + auth: { status: "unauthenticated" }, + usageLimits: undefined, + }); + const signedOut = Array.from(yield* Fiber.join(signedOutFiber))[0]; + assert.strictEqual(signedOut?.auth.status, "unauthenticated"); + assert.strictEqual(signedOut?.auth.email, undefined); + assert.strictEqual(signedOut?.auth.label, undefined); + assert.strictEqual(signedOut?.usageLimits, undefined); + }), + ).pipe(Effect.provide(layerAlwaysRunTest)), + ); }); diff --git a/packages/provider-core/src/server/managedProvider.ts b/packages/provider-core/src/server/managedProvider.ts index 33a8273359d13..37a5aca6e3f03 100644 --- a/packages/provider-core/src/server/managedProvider.ts +++ b/packages/provider-core/src/server/managedProvider.ts @@ -97,20 +97,30 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")( if (state.enrichmentGeneration !== generation) { return [null, state] as const; } - // Enrichment must not revert usage updates newer than its input snapshot. + // Enrichment must not revert usage updates newer than its input snapshot, except when + // signing out or clearing authentication drops the previous account's limits together. + const clearUsageForSignOut = + nextSnapshot.auth.status === "unauthenticated" && nextSnapshot.usageLimits === undefined; const merged = withUsageLimits( - state.usageAuthLabel === undefined + clearUsageForSignOut || state.usageAuthLabel === undefined ? nextSnapshot : { ...nextSnapshot, auth: { ...nextSnapshot.auth, label: state.usageAuthLabel ?? undefined }, }, - state.snapshot.usageLimits, + clearUsageForSignOut ? undefined : state.snapshot.usageLimits, ); if (Equal.equals(state.snapshot, merged)) { return [null, state] as const; } - return [merged, { ...state, snapshot: merged }] as const; + return [ + merged, + { + ...state, + snapshot: merged, + ...(clearUsageForSignOut ? { usageAuthLabel: undefined } : {}), + }, + ] as const; }); if (snapshotToPublish === null) { return; @@ -199,10 +209,20 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")( : state.enrichmentGeneration; // Failed reads retain limits only for the same account and original workspace. const previous = state.snapshot.auth; + const previousEmail = previous.email?.toLowerCase(); + const probedEmail = probedSnapshot.auth.email?.toLowerCase(); + const previousFingerprint = state.snapshot.usageLimits?.credentialFingerprint; + const probedFingerprint = probedSnapshot.usageLimits?.credentialFingerprint; + const sameFingerprint = + probedFingerprint !== undefined && probedFingerprint === previousFingerprint; const differs = (a: string | undefined, b: string | undefined) => a !== undefined && b !== undefined && a !== b; const switchedAccount = - differs(probedSnapshot.auth.email?.toLowerCase(), previous.email?.toLowerCase()) || + differs(probedEmail, previousEmail) || + differs(probedFingerprint, previousFingerprint) || + (previousFingerprint !== undefined && + !sameFingerprint && + probedEmail !== previousEmail) || (probedSnapshot.auth.workspaceId !== undefined && probedSnapshot.auth.workspaceId !== previous.workspaceId); const usageLimits = switchedAccount diff --git a/packages/provider-core/src/server/usageLimits.test.ts b/packages/provider-core/src/server/usageLimits.test.ts index 2acdb0ba15d79..8c7498bf7939e 100644 --- a/packages/provider-core/src/server/usageLimits.test.ts +++ b/packages/provider-core/src/server/usageLimits.test.ts @@ -142,5 +142,11 @@ describe("resolveUsageLimitsAfterProbe", () => { expect(resolveUsageLimitsAfterProbe({ published, probed: failed })).toBe(published); expect(resolveUsageLimitsAfterProbe({ published, probed: unsupported })).toBe(unsupported); expect(resolveUsageLimitsAfterProbe({ published: undefined, probed: failed })).toBe(failed); + + const publishedWithFp = { ...published, credentialFingerprint: "fp-a" }; + const failedOtherFp = { ...failed, credentialFingerprint: "fp-b" }; + expect( + resolveUsageLimitsAfterProbe({ published: publishedWithFp, probed: failedOtherFp }), + ).toBe(failedOtherFp); }); }); diff --git a/packages/provider-core/src/server/usageLimits.ts b/packages/provider-core/src/server/usageLimits.ts index 7d1f6e6a910e9..612edad9beb38 100644 --- a/packages/provider-core/src/server/usageLimits.ts +++ b/packages/provider-core/src/server/usageLimits.ts @@ -115,6 +115,13 @@ export function resolveUsageLimitsAfterProbe(input: { readonly probed: ServerProviderUsageLimits | undefined; }): ServerProviderUsageLimits | undefined { const { published, probed } = input; + if ( + published?.credentialFingerprint !== undefined && + probed?.credentialFingerprint !== undefined && + published.credentialFingerprint !== probed.credentialFingerprint + ) { + return probed; + } if (probed?.unavailable?.reason === "probeFailed" && published && !published.unavailable) { return published; } diff --git a/packages/shared/src/usageLimits.test.ts b/packages/shared/src/usageLimits.test.ts index 0078c21b566b7..6d0fd4fd25e1b 100644 --- a/packages/shared/src/usageLimits.test.ts +++ b/packages/shared/src/usageLimits.test.ts @@ -406,7 +406,7 @@ describe("pools", () => { const local = provider({ driver: antigravity, instanceId: ProviderInstanceId.make("antigravity"), - auth: { status: "authenticated" }, + auth: { status: "authenticated", email: "g@example.com" }, usageLimits: { checkedAt, credentialFingerprint: "google-key", @@ -437,6 +437,7 @@ describe("pools", () => { ]), ); expect(accounts).toHaveLength(1); + expect(accounts[0]?.email).toBe("g@example.com"); expect(accounts[0]?.limits.windows[0]?.usedPercent).toBe(30); }); diff --git a/packages/shared/src/usageLimits.ts b/packages/shared/src/usageLimits.ts index 693d82b956971..9e8ec0cb937fe 100644 --- a/packages/shared/src/usageLimits.ts +++ b/packages/shared/src/usageLimits.ts @@ -241,15 +241,35 @@ const nativeReport = (provider: ServerProvider): AccountReport => ({ // Include every enabled login, even unreadable workspaces. function accountKeyResolver(reports: Iterable) { + const emailByCredential = new Map(); const workspaces = new Map>(); - for (const report of reports) { - const key = accountKey(report.driver, report.email, report.usageLimits); + const reportList = [...reports]; + for (const report of reportList) { + const normalizedEmail = report.email?.trim().toLowerCase(); + const fingerprint = report.usageLimits?.credentialFingerprint; + if (normalizedEmail && fingerprint) { + const credKey = `${report.driver}:credential:${fingerprint}`; + const emailKey = `${report.driver}:${normalizedEmail}`; + const existing = emailByCredential.get(credKey); + emailByCredential.set( + credKey, + existing === undefined || existing === emailKey ? emailKey : null, + ); + } + } + const baseKey = (report: AccountReport): string | null => { + const direct = accountKey(report.driver, report.email, report.usageLimits); + if (!direct) return null; + return emailByCredential.get(direct) ?? direct; + }; + 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); @@ -346,6 +366,7 @@ export function collectLimitAccounts(presentations: LimitPresentations): readonl const displayName = previous.displayName ?? next.displayName; accounts.set(key, { ...previous, + email: previous.email ?? next.email, displayName: hubEmail && displayName?.toLowerCase() === PROVIDER_DISPLAY_NAMES[previous.driver]?.toLowerCase()