feat(antigravity): add weekly quota tracking and free-tier handling (#3892)

This commit is contained in:
Christian Gennari
2026-09-09 09:54:40 +07:00
parent 628ff1eab5
commit e3bf94ee25
10 changed files with 811 additions and 9 deletions

View File

@@ -37,6 +37,7 @@ export default {
},
usage: {
quotaApiUrl: `${ANTIGRAVITY_IDE_BASE_URL}/v1internal:fetchAvailableModels`,
quotaSummaryApiUrl: `${ANTIGRAVITY_IDE_BASE_URL}/v1internal:retrieveUserQuotaSummary`,
loadProjectApiUrl: "https://cloudcode-pa.googleapis.com/v1internal:loadCodeAssist",
tokenUrl: "https://oauth2.googleapis.com/token",
},

View File

@@ -0,0 +1,150 @@
/**
* Antigravity weekly quota — best-effort retrieval from retrieveUserQuotaSummary.
* Failure never breaks existing per-model quota display.
*/
import { U, parseResetTime, fetchWithTimeout } from "./shared.js";
import { ANTIGRAVITY_IDE_USER_AGENT, ANTIGRAVITY_IDE_VERSION } from "../../providers/shared.js";
// — Weekly quota summary config ——————————————————————————————
const WEEKLY_CONFIG = {
...U("antigravity"),
userAgent: ANTIGRAVITY_IDE_USER_AGENT,
};
// — Cache: TTL + in-flight dedup per project ———————————————
const WEEKLY_CACHE_TTL_MS = 180_000; // 3 minutes
const weeklyCache = new Map(); // cacheKey -> { result, expiresAt } | { promise }
function cacheKey(accessToken, projectId) {
return `${accessToken}::${projectId || ""}`;
}
// Exported for tests only
export function _clearWeeklyCache() {
weeklyCache.clear();
}
// — Group-name to stable key mapping ——————————————————————
const GROUP_MATCHERS = [
{ pattern: /gemini/i, key: "gemini_weekly", displayName: "Gemini (Weekly)" },
{ pattern: /claude|gpt/i, key: "claude_gpt_weekly", displayName: "Claude & GPT (Weekly)" },
];
/**
* Parse a retrieveUserQuotaSummary response into normalized weekly quotas.
* Pure function — safe to unit-test without network.
*
* @param {Object|null} data Raw JSON response
* @returns {Object} e.g. { gemini_weekly: { used, total, ... }, claude_gpt_weekly: { ... } }
*/
export function parseWeeklyQuotaSummary(data) {
if (!data || typeof data !== "object") return {};
// Groups may live at data.groups or data.quotaSummary.groups
const groups = Array.isArray(data.groups)
? data.groups
: Array.isArray(data.quotaSummary?.groups)
? data.quotaSummary.groups
: null;
if (!groups) return {};
const result = {};
for (const group of groups) {
if (!group || typeof group !== "object") continue;
const displayName = group.displayName || "";
const buckets = Array.isArray(group.buckets) ? group.buckets : [];
for (const bucket of buckets) {
if (!bucket || typeof bucket !== "object") continue;
// Identify weekly buckets by checking bucketId + displayName for "weekly"
const bucketText = `${bucket.bucketId || ""} ${bucket.displayName || ""}`.toLowerCase();
if (!bucketText.includes("weekly")) continue;
// Skip disabled buckets
if (bucket.disabled === true) continue;
const remainingFraction = Number(bucket.remainingFraction);
if (!Number.isFinite(remainingFraction)) continue;
// Match group to a known family
for (const matcher of GROUP_MATCHERS) {
if (matcher.pattern.test(displayName)) {
const total = 1000;
const remaining = Math.round(total * remainingFraction);
const used = Math.max(0, total - remaining);
result[matcher.key] = {
used,
total,
resetAt: parseResetTime(bucket.resetTime),
remainingPercentage: remainingFraction * 100,
unlimited: false,
displayName: matcher.displayName,
};
break; // first matching bucket per family wins
}
}
}
}
return result;
}
/**
* Fetch weekly quota summary — cached, deduped, never throws.
*/
export async function fetchAntigravityWeeklyQuota(accessToken, projectId, proxyOptions = null) {
const key = cacheKey(accessToken, projectId);
// Serve in-flight or cached
const hit = weeklyCache.get(key);
if (hit?.promise) return hit.promise;
if (hit && hit.expiresAt > Date.now()) return hit.result;
const promise = (async () => {
try {
const url = WEEKLY_CONFIG.quotaSummaryApiUrl;
if (!url) return {};
const response = await fetchWithTimeout(url, {
method: "POST",
headers: {
"Authorization": `Bearer ${accessToken}`,
"User-Agent": WEEKLY_CONFIG.userAgent,
"Content-Type": "application/json",
"X-Client-Name": "antigravity",
"X-Client-Version": ANTIGRAVITY_IDE_VERSION,
},
body: JSON.stringify({
...(projectId ? { project: projectId } : {}),
}),
}, 10000, proxyOptions);
if (!response.ok) return {};
const data = await response.json();
return parseWeeklyQuotaSummary(data);
} catch {
return {};
}
})();
weeklyCache.set(key, { promise });
try {
const result = await promise;
if (result && Object.keys(result).length > 0) {
weeklyCache.set(key, { result, expiresAt: Date.now() + WEEKLY_CACHE_TTL_MS });
} else {
weeklyCache.delete(key);
}
return result;
} catch {
weeklyCache.delete(key);
return {};
}
}

View File

@@ -5,6 +5,7 @@
import { CLIENT_METADATA } from "../../config/appConstants.js";
import { ANTIGRAVITY_IDE_USER_AGENT, ANTIGRAVITY_IDE_VERSION, ANTIGRAVITY_OAUTH_CLIENT } from "../../providers/shared.js";
import { U, parseResetTime, normalizeCloudCodeProjectId, fetchWithTimeout } from "./shared.js";
import { fetchAntigravityWeeklyQuota } from "./antigravity-weekly.js";
// Antigravity API config (from Quotio) — urls from registry, oauth client + dynamic UA kept here
const ANTIGRAVITY_CONFIG = {
@@ -157,8 +158,15 @@ export async function getAntigravityUsage(accessToken, providerSpecificData, pro
const data = await response.json();
const quotas = {};
// Parse model quotas (inspired by vscode-antigravity-cockpit)
if (data.models) {
// Detect tier: free-tier accounts only have weekly quotas (no separate 5h window).
// On free-tier, fetchAvailableModels returns misleading per-model quota info
// (missing remainingFraction defaults to 0, or reflects the weekly limit not a 5h window).
const paidTierId = subscriptionInfo?.paidTier?.id;
const isFreeTier = !paidTierId || paidTierId === "free-tier";
// Parse model quotas only for paid-tier accounts.
// Free-tier accounts skip this — their only meaningful quota is the weekly limit.
if (!isFreeTier && data.models) {
// Filter only recommended/important models (must match PROVIDER_MODELS ag ids)
const importantModels = [
'gemini-3.8-flash-high',
@@ -212,6 +220,56 @@ export async function getAntigravityUsage(accessToken, providerSpecificData, pro
}
}
// Best-effort weekly quota overlay — never blocks or breaks per-model results
try {
const weeklyQuotas = await fetchAntigravityWeeklyQuota(
accessToken,
projectId,
proxyOptions
);
// Reconcile weekly quota against model family status:
// If every model in a family is locked/exhausted (remainingPercentage === 0)
// until a future reset time, the weekly limit cannot be 100% available.
// On Google's Free Starter tier, retrieveUserQuotaSummary buggily reports
// remainingFraction: 1 even after the starter quota is depleted and all models 429.
const entries = Object.entries(quotas);
const geminiModels = entries.filter(([k]) => k.startsWith("gemini-") && !k.includes("image"));
const claudeModels = entries.filter(([k]) => k.startsWith("claude-"));
if (weeklyQuotas.gemini_weekly && geminiModels.length > 0) {
const allGeminiExhausted = geminiModels.every(([, q]) => (q.remainingPercentage ?? 0) === 0);
if (allGeminiExhausted && weeklyQuotas.gemini_weekly.remainingPercentage > 0) {
const maxResetAt = geminiModels.reduce((max, [, q]) =>
!max || (q.resetAt && new Date(q.resetAt) > new Date(max)) ? q.resetAt : max, null
);
weeklyQuotas.gemini_weekly.used = weeklyQuotas.gemini_weekly.total;
weeklyQuotas.gemini_weekly.remainingPercentage = 0;
if (maxResetAt) {
weeklyQuotas.gemini_weekly.resetAt = maxResetAt;
}
}
}
if (weeklyQuotas.claude_gpt_weekly && claudeModels.length > 0) {
const allClaudeExhausted = claudeModels.every(([, q]) => (q.remainingPercentage ?? 0) === 0);
if (allClaudeExhausted && weeklyQuotas.claude_gpt_weekly.remainingPercentage > 0) {
const maxResetAt = claudeModels.reduce((max, [, q]) =>
!max || (q.resetAt && new Date(q.resetAt) > new Date(max)) ? q.resetAt : max, null
);
weeklyQuotas.claude_gpt_weekly.used = weeklyQuotas.claude_gpt_weekly.total;
weeklyQuotas.claude_gpt_weekly.remainingPercentage = 0;
if (maxResetAt) {
weeklyQuotas.claude_gpt_weekly.resetAt = maxResetAt;
}
}
}
Object.assign(quotas, weeklyQuotas);
} catch {
// Silently ignore — weekly is best-effort
}
return {
plan: subscriptionInfo?.currentTier?.name || "Unknown",
quotas,