fix(server): poll provider usage only while visible #31032
ClosedElliotDrel(GitHub profile, opens in a new tab)wants to merge 174 commits into
main fromrefs/pull/31032/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/server/src/provider/ProviderInstanceRegistry.test.ts lines 1025 to 1027OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -659,4 +655,6 @@659655 }).pipe(Effect.provideService(HttpClient.HttpClient, client));660656 const instance = yield* registry.getInstance(instanceId);661657 expect(instance).toBeDefined();662- const before = yield* instance!.snapshot.refresh;658+ const before = yield* instance!.snapshot.refresh.pipe(659+ Effect.provideService(UsagePolling, true),660+ );apps/server/src/provider/ProviderRegistry.ts lines 653 to 669OutdatedResolvedby ElliotDrel(GitHub profile, opens in a new tab)@@ -619,3 +627,16 @@619627 );620628 });621629630+ const refreshUsage = Effect.fn("ProviderRegistry.refreshUsage")(function* (631+ instanceId?: ProviderInstanceId,632+ ) {633+ const instances = yield* instanceRegistry.listInstances;634+ yield* Effect.forEach(635+ instances.filter(636+ (instance) => instanceId === undefined || instance.instanceId === instanceId,637+ ),638+ (instance) => refreshOneSource(instance, true),639+ { concurrency: "unbounded" },640+ );641+ return yield* Ref.get(providersRef);642+ });apps/web/src/hooks/useLiveRefresh.ts lines 114 to 117OutdatedResolvedby ElliotDrel(GitHub profile, opens in a new tab)@@ -106,7 +108,10 @@106108 const visible = () => document.visibilityState === "visible";107109 const onArrival = () => {108110 const now = Date.now();109- if (now - lastInteractedAt >= LIVE_REFRESH_IDLE_AFTER_MS) return;111+ if (!refreshWhileIdle && now - lastInteractedAt >= LIVE_REFRESH_IDLE_AFTER_MS) return;110112 const lastRefreshedAt = lastRefreshedAtByView.get(viewId);111113 if (lastRefreshedAt === undefined) {112- lastRefreshedAtByView.set(viewId, now);114+ if (visible()) {115+ if (refreshOnShow) read(now);116+ else lastRefreshedAtByView.set(viewId, now);117+ }packages/provider-core/src/server/usageHttpClient.ts line 60OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +14,21 @@14+ const parsed = URL.parse(url);15+ if (!parsed) return false;16+ return (17+ (parsed.hostname === "api.anthropic.com" && parsed.pathname === "/api/oauth/usage") ||18+ (parsed.hostname === "opencode.ai" && parsed.pathname === "/zen/go/v1/usage") ||19+ (parsed.hostname === "cli-chat-proxy.grok.com" && parsed.pathname === "/v1/billing") ||20+ parsed.pathname === "/aiserver.v1.DashboardService/GetCurrentPeriodUsage" ||21+ (["daily-cloudcode-pa.googleapis.com", "cloudcode-pa.googleapis.com"].includes(22+ parsed.hostname,23+ ) &&24+ ["/v1internal:fetchAvailableModels", "/v1internal:retrieveUserQuotaSummary"].includes(25+ parsed.pathname,26+ ))27+ );28+}29+30+export function usageRetryDelay(header: string | undefined, now: number) {31+ if (header === undefined) return TTL_MS;32+ const seconds = /^\d+(?:\.\d+)?$/.test(header.trim()) ? Number(header) : NaN;33+ const delay = Number.isFinite(seconds) ? seconds * 1000 : Date.parse(header) - now;34+ return Number.isFinite(delay) && delay >= 0 ? Math.max(1000, delay) : TTL_MS;
- apps/server/src/provider/Drivers/ClaudeDriver.ts line 230OutdatedResolvedby ElliotDrel(GitHub profile, opens in a new tab)@@ -224,8 +217,14 @@224217 );225- const capabilitiesCacheKey = yield* makeClaudeCapabilitiesCacheKey(226- effectiveConfig,227- stateDir,228- processEnv,229- );230- const resolveCapabilities = Cache.get(capabilitiesProbeCache, capabilitiesCacheKey).pipe(231- Effect.map((result) => result.capabilities),218+ const resolveCapabilities = Effect.gen(function* () {219+ let includeUsage = yield* UsagePolling;220+ if (includeUsage && usageHttpClient) {221+ const token = yield* ClaudeResetCredits.readAccessToken(configDir).pipe(222+ Effect.orElseSucceed(() => undefined),223+ );224+ if (225+ token &&226+ (yield* usageHttpClient.isCoolingDown("https://api.anthropic.com", `Bearer ${token}`))227+ )228+ includeUsage = false;229+ }230+ return (yield* Cache.get(capabilitiesProbeCache, includeUsage)).capabilities;packages/contracts/src/rpc.ts lines 662 to 664OutdatedResolvedby ElliotDrel(GitHub profile, opens in a new tab)@@ -643,3 +647,6 @@643647 instanceId: Schema.optional(ProviderInstanceId),644648 cwd: Schema.optional(TrimmedNonEmptyString),645649 fresh: Schema.optional(Schema.Boolean),650+ usage: Schema.optional(Schema.Boolean),651+ usageSources: Schema.optional(Schema.Boolean),652+ usageProviders: Schema.optional(Schema.Array(ProviderDriverKind)),@@ -2439,6 +2441,15 @@2439- })2440- : input.reloadSecrets === true2441- ? providerRegistry.reloadSecretsAndRefresh(input.instanceId)2442- : input.instanceId !== undefined2443- ? providerRegistry.refreshInstance(input.instanceId)2444- : providerRegistry.refresh();2441+ let providers = yield* (2442+ input.cwd !== undefined && input.instanceId !== undefined2443+ ? providerRegistry.refreshWorkspaceSnapshot({2444+ instanceId: input.instanceId,2445+ cwd: input.cwd,2446+ fresh: input.fresh === true,2447+ })2448+ : input.reloadSecrets === true2449+ ? providerRegistry.reloadSecretsAndRefresh(input.instanceId)2450+ : input.usage === true2451+ ? providerRegistry.refreshUsage(input.instanceId)2452+ : input.instanceId !== undefined2453+ ? providerRegistry.refreshInstance(input.instanceId)2454+ : providerRegistry.refresh()2455+ ).pipe(Effect.provideService(UsagePolling, input.usage === true));packages/provider-core/src/server/managedProvider.ts line 485OutdatedResolvedby ElliotDrel(GitHub profile, opens in a new tab)@@ -360,4 +387,4 @@360387 ),361388 Effect.ignoreCause({ log: true }),362389 ),363- ).pipe(Effect.forkScoped);390+ ).pipe(Effect.provideService(UsagePolling, false), Effect.forkScoped);apps/web/src/components/chat/useUsageLimitsPanel.ts line 45OutdatedResolvedby ElliotDrel(GitHub profile, opens in a new tab)@@ -41,3 +42,4 @@4142 panel !== null && panelKey !== null && panel.key === panelKey && providerInstanceId !== null4243 ? collectProviderUsageLimits(providerInstanceId, providers, sources, panel.now)4344 : null;45+ useUsageLimitsRefresh(environmentId, providerInstanceId, report !== null, providerDriver);apps/web/src/hooks/useLiveRefresh.ts lines 114 to 116OutdatedResolvedby ElliotDrel(GitHub profile, opens in a new tab)@@ -106,7 +108,9 @@106108 const visible = () => document.visibilityState === "visible";107109 const onArrival = () => {108110 const now = Date.now();109- if (now - lastInteractedAt >= LIVE_REFRESH_IDLE_AFTER_MS) return;111+ if (!refreshWhileIdle && now - lastInteractedAt >= LIVE_REFRESH_IDLE_AFTER_MS) return;110112 const lastRefreshedAt = lastRefreshedAtByView.get(viewId);111113 if (lastRefreshedAt === undefined) {112- lastRefreshedAtByView.set(viewId, now);114+ if (visible()) {115+ if (refreshOnShow) read(now);116+ else lastRefreshedAtByView.set(viewId, now);
- apps/server/src/provider/AntigravityProvider.ts line 247OutdatedResolvedby ElliotDrel(GitHub profile, opens in a new tab)@@ -233,4 +234,4 @@233234 const republish = yield* Deferred.make<Effect.Effect<ServerProvider>>();234235 const scope = yield* Effect.scope;235236 const refreshUsage = Effect.fn("AntigravityProvider.refreshUsage")(function* () {236- if (!options.probeUsage || (yield* PublishingUsage)) return;237+ if (!options.probeUsage || (yield* PublishingUsage) || !(yield* UsagePolling)) return;apps/server/src/usage/cliproxyApi.ts line 333OutdatedResolvedby ElliotDrel(GitHub profile, opens in a new tab)@@ -268,3 +313,21 @@268313 .toSorted((a, b) => Date.parse(a.expires_at) - Date.parse(b.expires_at));269314 });270315316+ const usageCache = yield* Cache.makeWith(317+ (key: string) =>318+ decodeApiCallInput(key).pipe(319+ Effect.mapError(320+ () => new UsageLimitSourceError({ detail: "Could not read the usage request." }),321+ ),322+ Effect.flatMap(({ hub, account, url }) => apiCallUncached(hub, account, url)),323+ ),324+ { capacity: 128, timeToLive: () => Duration.minutes(5) },325+ );326+ const apiCall = Effect.fn("CliproxyApi.cachedApiCall")(function* (327+ hub: CliproxyHub,328+ account: typeof AuthFile.Type,329+ url: string,330+ data?: unknown,331+ ) {332+ if (data !== undefined) return yield* apiCallUncached(hub, account, url, data);333+ return yield* Cache.get(usageCache, yield* encodeJson({ hub, account, url }));packages/provider-core/src/server/managedProvider.ts line 175OutdatedResolvedby ElliotDrel(GitHub profile, opens in a new tab)@@ -150,4 +157,19 @@150157 return state.snapshot;151158 }152159153- const probedSnapshot = yield* input.checkProvider;160+ const now = yield* Clock.currentTimeMillis;161+ const current = (yield* Ref.get(snapshotStateRef)).snapshot;162+ const pollingUsage =163+ (yield* UsagePolling) &&164+ ((yield* UsageAfterReset) ||165+ now >= usageRefreshAfter ||166+ current.usageLimits?.unavailable?.reason === "unsupported");167+ const probedSnapshot =168+ pollingUsage &&169+ input.checkUsageLimits &&170+ current.installed &&171+ current.status === "ready" &&172+ current.auth.status === "authenticated"173+ ? withUsageLimits(current, yield* input.checkUsageLimits)174+ : yield* input.checkProvider.pipe(Effect.provideService(UsagePolling, pollingUsage));175+ if (pollingUsage) usageRefreshAfter = (yield* Clock.currentTimeMillis) + 5 * 60_000;
- apps/web/src/hooks/useUsageLimitsRefresh.ts lines 23 to 25OutdatedResolvedby ElliotDrel(GitHub profile, opens in a new tab)@@ -0,0 +5,21 @@5+import { serverEnvironment } from "../state/server";6+import { useLiveRefresh } from "./useLiveRefresh";7+8+export function useUsageLimitsRefresh(9+ environmentId: EnvironmentId,10+ instanceId: ProviderInstanceId | null,11+ enabled = true,12+ driver?: ProviderDriverKind | null,13+) {14+ const presentation = useAtomValue(environmentPresentations.presentationAtom(environmentId));15+ const connected = presentation?.connection.phase === "connected";16+ const refresh = useAtomCommand(serverEnvironment.refreshProviders, { reportFailure: false });17+ useLiveRefresh(18+ () => {19+ return Promise.all([20+ instanceId !== null21+ ? refresh({ environmentId, input: { instanceId, usage: true } })22+ : undefined,23+ driver24+ ? refresh({ environmentId, input: { usageSources: true, usageProviders: [driver] } })25+ : undefined,
- apps/web/src/hooks/useUsageLimitsRefresh.ts lines 20 to 21OutdatedResolvedby ElliotDrel(GitHub profile, opens in a new tab)@@ -0,0 +1,21 @@1+import { useAtomValue } from "@effect/atom-react";2+import { environmentPresentations } from "../state/presentation";3+import type { EnvironmentId, ProviderInstanceId, ProviderDriverKind } from "@t3tools/contracts";4+import { useAtomCommand } from "../state/use-atom-command";5+import { serverEnvironment } from "../state/server";6+import { useLiveRefresh } from "./useLiveRefresh";7+8+export function useUsageLimitsRefresh(9+ environmentId: EnvironmentId,10+ instanceId: ProviderInstanceId | null,11+ enabled = true,12+ driver?: ProviderDriverKind | null,13+) {14+ const presentation = useAtomValue(environmentPresentations.presentationAtom(environmentId));15+ const connected = presentation?.connection.phase === "connected";16+ const refresh = useAtomCommand(serverEnvironment.refreshProviders, { reportFailure: false });17+ useLiveRefresh(18+ () => {19+ return Promise.all([20+ instanceId !== null21+ ? refresh({ environmentId, input: { instanceId, usage: true } })packages/provider-core/src/server/usageHttpClient.ts lines 79 to 81OutdatedResolvedby ElliotDrel(GitHub profile, opens in a new tab)@@ -0,0 +61,21 @@61+ ]);62+ let account = accounts.get(accountKey);63+ if (!account) {64+ account = { lock: Semaphore.makeUnsafe(1), retryAt: 0 };65+ accounts.set(accountKey, account);66+ }67+ const state = account;68+ const key = encodeKey([69+ accountKey,70+ request.method,71+ request.url,72+ request.urlParams,73+ request.body,74+ ]);75+ return yield* state.lock.withPermits(1)(76+ Effect.gen(function* () {77+ const now = yield* Clock.currentTimeMillis;78+ const previous = cached.get(key);79+ if (previous && now < previous.expiresAt) {80+ const saved = yield* previous.result;81+ return HttpClientResponse.fromWeb(request, new Response(saved.body.slice(0), saved));
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- packages/provider-core/src/server/usageHttpClient.ts lines 150 to 153OutdatedResolvedby ElliotDrel(GitHub profile, opens in a new tab)@@ -0,0 +133,21 @@133+ cached.set(key, {134+ accountKey,135+ result,136+ expiresAt: Math.max(finishedAt + TTL_MS, state.retryAt),137+ });138+ const saved = yield* result;139+ const response = HttpClientResponse.fromWeb(140+ request,141+ new Response(saved.body.slice(0), saved),142+ );143+ sampleTimes.set(response, saved.checkedAt);144+ return response;145+ }),146+ );147+ });148+ });149+ return Object.assign(cachedClient, {150+ invalidateSuccessfulReads: (origin: string, authorization: string) =>151+ Effect.sync(() => {152+ const accountKey = encodeKey([origin, authorization]);153+ for (const [key, saved] of cached) {
- packages/provider-core/src/server/usageHttpClient.ts lines 72 to 75OutdatedResolvedby ElliotDrel(GitHub profile, opens in a new tab)@@ -0,0 +55,21 @@55+ readonly body: ArrayBuffer;56+ };57+ const cached = new Map<58+ string,59+ {60+ readonly accountKey: string;61+ readonly result: Exit.Exit<Snapshot, HttpClientError.HttpClientError>;62+ readonly expiresAt: number;63+ }64+ >();65+ const accounts = new Map<66+ string,67+ { readonly lock: Semaphore.Semaphore; retryAt: number; generation: number }68+ >();69+ const cachedClient = HttpClient.transform(client, (read, request) => {70+ if (!isUsageUrl(request.url)) return read;71+ return Effect.gen(function* () {72+ const accountKey = encodeKey([73+ new URL(request.url).origin,74+ request.headers.authorization ?? "",75+ ]);
- apps/server/src/provider/antigravityUsageLimits.ts line 312OutdatedResolvedby ElliotDrel(GitHub profile, opens in a new tab)@@ -293,4 +304,9 @@293304 token.project_id ? { project: token.project_id } : {},294305 ),295306 ),307+ (sampleAt) => {308+ if (sampleAt) requestedAt = Date.parse(sampleAt);309+ sampleTimes.push(sampleAt || DateTime.formatIso(DateTime.makeUnsafe(requestedAt)));310+ },296311 ).pipe(312+ Effect.provideService(UsageAccountIdentity, `antigravity:${account}`),
- packages/provider-core/src/server/usageHttpClient.ts lines 150 to 154OutdatedResolvedby ElliotDrel(GitHub profile, opens in a new tab)@@ -0,0 +134,21 @@134+ return {135+ checkedAt: DateTime.formatIso(DateTime.makeUnsafe(now)),136+ status: response.status,137+ headers: response.headers,138+ body: yield* response.arrayBuffer,139+ };140+ }),141+ ),142+ Effect.exit,143+ );144+ const finishedAt = yield* Clock.currentTimeMillis;145+ if (146+ generation === state.generation ||147+ Exit.isFailure(result) ||148+ result.value.status >= 400149+ )150+ cached.set(key, {151+ accountKey,152+ result,153+ expiresAt: Math.max(finishedAt + TTL_MS, state.retryAt),154+ });
- apps/server/src/provider/claudeResetCredits.ts line 237OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -215,3 +230,8 @@215230 if (!token || !organization) {216231 return yield* new ClaudeResetCreditError({ reason: "signedOut" });217232 }233+ if (234+ input.usageHttpClient &&235+ (yield* input.usageHttpClient.isCoolingDown(API_BASE, `Bearer ${token}`))236+ ) {237+ return yield* new ClaudeResetCreditError({ reason: "coolingDown" });
- packages/provider-core/src/server/managedProvider.ts lines 198 to 201OutdatedResolvedby ElliotDrel(GitHub profile, opens in a new tab)@@ -165,8 +187,15 @@165187 differs(probedSnapshot.auth.email?.toLowerCase(), previous.email?.toLowerCase()) ||166188 (probedSnapshot.auth.workspaceId !== undefined &&167189 probedSnapshot.auth.workspaceId !== previous.workspaceId);190+ if (switchedAccount && !pollingUsage) usageRefreshAfter = 0;168191 const usageLimits = switchedAccount169192 ? probedSnapshot.usageLimits170193 : resolveUsageLimitsAfterProbe({171194 published: state.snapshot.usageLimits,172- probed: probedSnapshot.usageLimits,195+ probed:196+ !pollingUsage &&197+ probedSnapshot.auth.status === "authenticated" &&198+ (probedSnapshot.usageLimits === undefined ||199+ probedSnapshot.usageLimits.unavailable?.reason === "probeFailed") &&200+ state.snapshot.usageLimits201+ ? state.snapshot.usageLimits
- apps/server/src/provider/AntigravityProvider.ts lines 247 to 248OutdatedResolvedby ElliotDrel(GitHub profile, opens in a new tab)@@ -233,5 +243,5 @@233243 const republish = yield* Deferred.make<Effect.Effect<ServerProvider>>();234244 const scope = yield* Effect.scope;235245 const refreshUsage = Effect.fn("AntigravityProvider.refreshUsage")(function* () {236- if (!options.probeUsage || (yield* PublishingUsage)) return;246+ if (!options.probeUsage || (yield* PublishingUsage) || !(yield* UsagePolling)) return;237247 yield* FiberHandle.run(apps/server/src/provider/Drivers/ClaudeDriver.ts lines 238 to 240OutdatedResolvedby ElliotDrel(GitHub profile, opens in a new tab)@@ -229,3 +223,18 @@229- );230- const resolveCapabilities = Cache.get(capabilitiesProbeCache, capabilitiesCacheKey).pipe(231- Effect.map((result) => result.capabilities),223+ let lastAccount: ClaudeCapabilitiesProbe | undefined;224+ let lastIdentity: string | undefined;225+ const resolveCapabilities = Effect.gen(function* () {226+ const identity = yield* ClaudeResetCredits.readClaudeAccountCacheKey(accountConfigPath);227+ if (lastIdentity !== identity) {228+ yield* Cache.invalidateAll(capabilitiesProbeCache);229+ yield* Ref.set(lastGoodCapabilities, undefined);230+ lastAccount = undefined;231+ lastIdentity = identity;232+ }233+ let includeUsage = yield* UsagePolling;234+ if (includeUsage && usageHttpClient) {235+ const token = yield* ClaudeResetCredits.readAccessToken(configDir).pipe(236+ Effect.orElseSucceed(() => undefined),237+ );238+ if (239+ token &&240+ (yield* usageHttpClient.isCoolingDown("https://api.anthropic.com", `Bearer ${token}`))
Sign in to join this conversation.
Codex Review Summary: ✅ Completed
This comment shows the latest Codex review activity on this pull request.
9866871ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.