feat(panel): support independent Gemini 4 Argon quota pool for Pro accounts

This commit is contained in:
yuhuan2498281558
2026-10-30 21:39:58 +09:00
parent fad31d0464
commit 9e69227beb
7 changed files with 990 additions and 229 deletions
+122 -63
View File
@@ -840,11 +840,36 @@ function isEquivalentTelemetry(prev, next) {
}
}
if (prev.account?.tierName !== next.account?.tierName || prev.account?.planName !== next.account?.planName) {
return false;
}
const pQuot = prev.quotas?.activePool;
const nQuot = next.quotas?.activePool;
if (pQuot?.family !== nQuot?.family) return false;
if (pQuot?.usedPct !== nQuot?.usedPct) return false;
if (pQuot?.remainingPct !== nQuot?.remainingPct) return false;
if (pQuot?.weeklyUsedPct !== nQuot?.weeklyUsedPct) return false;
if (prev.quotas?.weekly?.usedPct !== next.quotas?.weekly?.usedPct) return false;
if (prev.quotas?.weekly?.remainingPct !== next.quotas?.weekly?.remainingPct) return false;
const pPools = prev.quotas?.pools || [];
const nPools = next.quotas?.pools || [];
if (pPools.length !== nPools.length) return false;
for (let i = 0; i < pPools.length; i++) {
if (
pPools[i]?.poolKey !== nPools[i]?.poolKey ||
pPools[i]?.poolLabel !== nPools[i]?.poolLabel ||
pPools[i]?.usedPct !== nPools[i]?.usedPct ||
pPools[i]?.remainingPct !== nPools[i]?.remainingPct ||
pPools[i]?.resetTime !== nPools[i]?.resetTime ||
pPools[i]?.weeklyUsedPct !== nPools[i]?.weeklyUsedPct ||
pPools[i]?.weeklyRemainingPct !== nPools[i]?.weeklyRemainingPct ||
pPools[i]?.weeklyResetTime !== nPools[i]?.weeklyResetTime
) {
return false;
}
}
if ((prev.conversations?.length || 0) !== (next.conversations?.length || 0)) return false;
@@ -2210,38 +2235,37 @@ const LiveOverviewView = defineComponent({
]),
]);
// 3. Official 5h & Weekly Quotas Panel (Gemini Pool + Claude Pool)
// 3. Official 5h & Weekly Quotas Panel (Dynamic Pools: Gemini, Argon on Pro, Claude & GPT, etc.)
const tierBadge = h('span', { className: 'panel-meta', text: 'Google AI · Pro' });
const poolsListEl = h('div', { style: 'display: flex; flex-direction: column; gap: 0;' });
function createPoolQuotaBlock(poolLabel) {
const title5h = h('span', { text: `5h 限额 (${poolLabel})` });
function createPoolQuotaRow() {
const title5h = h('span', { text: '5h 限额' });
const meta5h = h('span', { className: 'panel-meta text-mono', text: '--' });
const fill5h = h('div', { className: 'progress-fill' });
const titleWk = h('span', { text: `每周限额 (${poolLabel})` });
const metaWk = h('span', { className: 'panel-meta text-mono', text: '--' });
const fillWk = h('div', { className: 'progress-fill' });
const el = h('div', { style: 'display: flex; flex-direction: column; gap: 8px;' }, [
h('div', { style: 'display: flex; flex-direction: column; gap: 4px;' }, [
h('div', { className: 'panel-header' }, [title5h, meta5h]),
h('div', { className: 'progress-track' }, [fill5h]),
]),
h('div', { style: 'display: flex; flex-direction: column; gap: 4px;' }, [
h('div', { className: 'panel-header' }, [titleWk, metaWk]),
h('div', { className: 'progress-track' }, [fillWk]),
]),
const row5h = h('div', { style: 'display: flex; flex-direction: column; gap: 4px;' }, [
h('div', { className: 'panel-header' }, [title5h, meta5h]),
h('div', { className: 'progress-track' }, [fill5h]),
]);
return { el, title5h, meta5h, fill5h, titleWk, metaWk, fillWk };
}
const titleWk = h('span', { text: '每周限额' });
const metaWk = h('span', { className: 'panel-meta text-mono', text: '--' });
const fillWk = h('div', { className: 'progress-fill' });
const rowWk = h('div', { style: 'display: flex; flex-direction: column; gap: 4px;' }, [
h('div', { className: 'panel-header' }, [titleWk, metaWk]),
h('div', { className: 'progress-track' }, [fillWk]),
]);
const geminiQuotaBlock = createPoolQuotaBlock('Gemini');
const claudeQuotaBlock = createPoolQuotaBlock('Claude & GPT');
claudeQuotaBlock.el.setAttribute(
'style',
'display: flex; flex-direction: column; gap: 8px; margin-top: 3px; padding-top: 10px; border-top: 1px solid var(--border-hairline);'
);
const el = h('div', { style: 'display: flex; flex-direction: column; gap: 8px;' }, [
row5h,
rowWk,
]);
return {
el,
refs: { row5h, title5h, meta5h, fill5h, rowWk, titleWk, metaWk, fillWk },
};
}
const wkFootLeft = h('span', { className: 'text-muted', text: '本周本机: 0 ($0.00)' });
const wkFootRight = h('span', { className: 'text-muted', text: '' });
@@ -2254,8 +2278,7 @@ const LiveOverviewView = defineComponent({
]),
tierBadge,
]),
geminiQuotaBlock.el,
claudeQuotaBlock.el,
poolsListEl,
h('div', { className: 'panel-header', style: 'font-size: 11px; padding-top: 2px;' }, [
wkFootLeft,
wkFootRight,
@@ -2274,46 +2297,65 @@ const LiveOverviewView = defineComponent({
className: 'view-pane',
});
function syncPoolQuotaBlock(block, poolLabel, poolData, fallbackWeekly, isActiveFamily) {
function syncPoolQuotaRow(refs, item, idx, rowEl) {
const { poolData, poolLabel, fallbackWeekly, isActivePool } = item;
patchAttr(
rowEl,
'style',
idx === 0
? 'display: flex; flex-direction: column; gap: 8px;'
: 'display: flex; flex-direction: column; gap: 8px; margin-top: 10px; padding-top: 10px; border-top: 1px solid var(--border-hairline);'
);
const has5h = poolData?.usedPct != null && poolData?.remainingPct != null;
const used5hVal = has5h ? Number(poolData.usedPct) : 0;
const rem5hVal = has5h ? Number(poolData.remainingPct) : 0;
patchText(block.title5h, `5h 限额 (${poolLabel})`);
patchText(
block.meta5h,
has5h
? `${formatCountdown(poolData.resetTime)} · 已用 ${used5hVal.toFixed(1)}% (余 ${rem5hVal.toFixed(1)}%)`
: '获取失败 (--%)'
);
patchStyleVar(block.fill5h, '--fill-w', `${Math.min(100, used5hVal)}%`);
patchClasses(block.fill5h, {
'tone-warn': used5hVal >= 60 && used5hVal < 85,
'tone-danger': used5hVal >= 85,
});
const wkUsedRaw =
poolData?.weeklyUsedPct ?? (isActiveFamily ? fallbackWeekly?.usedPct : null);
poolData?.weeklyUsedPct ?? (isActivePool ? fallbackWeekly?.usedPct : null);
const wkRemRaw =
poolData?.weeklyRemainingPct ?? (isActiveFamily ? fallbackWeekly?.remainingPct : null);
poolData?.weeklyRemainingPct ?? (isActivePool ? fallbackWeekly?.remainingPct : null);
const wkResetRaw =
poolData?.weeklyResetTime || (isActiveFamily ? fallbackWeekly?.resetTime : null);
poolData?.weeklyResetTime || (isActivePool ? fallbackWeekly?.resetTime : null);
const hasWk = wkUsedRaw != null && wkRemRaw != null;
const usedWkVal = hasWk ? Number(wkUsedRaw) : 0;
const remWkVal = hasWk ? Number(wkRemRaw) : 0;
// Hide non-applicable window on weekly-only pools (e.g. Pro Argon pool or Plus tier)
// or 5h-only pools, while still showing both rows with error state if both failed.
const hide5h = !has5h && hasWk;
const hideWk = !hasWk && has5h;
refs.row5h.hidden = hide5h;
refs.row5h.style.display = hide5h ? 'none' : 'flex';
refs.rowWk.hidden = hideWk;
refs.rowWk.style.display = hideWk ? 'none' : 'flex';
patchText(refs.title5h, `5h 限额 (${poolLabel})`);
patchText(
refs.meta5h,
has5h
? `${formatCountdown(poolData.resetTime)} · 已用 ${used5hVal.toFixed(1)}% (余 ${rem5hVal.toFixed(1)}%)`
: '获取失败 (--%)'
);
patchStyleVar(refs.fill5h, '--fill-w', `${Math.min(100, used5hVal)}%`);
patchClasses(refs.fill5h, {
'tone-warn': used5hVal >= 60 && used5hVal < 85,
'tone-danger': used5hVal >= 85,
});
const customTitle =
isActiveFamily && fallbackWeekly?.isOfficial === false && fallbackWeekly?.title
isActivePool && fallbackWeekly?.isOfficial === false && fallbackWeekly?.title
? fallbackWeekly.title
: `每周限额 (${poolLabel})`;
patchText(block.titleWk, customTitle);
patchText(refs.titleWk, customTitle);
patchText(
block.metaWk,
refs.metaWk,
hasWk
? `${formatCountdown(wkResetRaw)} · 已用 ${usedWkVal.toFixed(1)}% (余 ${remWkVal.toFixed(1)}%)`
: '获取失败 (--%)'
);
patchStyleVar(block.fillWk, '--fill-w', `${Math.min(100, usedWkVal)}%`);
patchClasses(block.fillWk, {
patchStyleVar(refs.fillWk, '--fill-w', `${Math.min(100, usedWkVal)}%`);
patchClasses(refs.fillWk, {
'tone-warn': usedWkVal >= 60 && usedWkVal < 85,
'tone-danger': usedWkVal >= 85,
});
@@ -2367,28 +2409,45 @@ const LiveOverviewView = defineComponent({
patchText(bdSystemPrompt, formatTokens(ctx.systemPromptTokens || 0));
patchText(bdUserRules, formatTokens(ctx.userRulesTokens || 0));
// 3. Quotas (Gemini + Claude & GPT)
// 3. Quotas (Dynamic Pools: Gemini, Argon on Pro, Claude & GPT, etc.)
patchText(
tierBadge,
`${data.account?.tierName || 'Google AI'} · ${data.account?.planName || 'Pro'}`
);
const activePool = quotas.activePool || {};
const pools = quotas.pools || [];
const rawPools = Array.isArray(quotas.pools) && quotas.pools.length > 0
? quotas.pools
: [
{ poolKey: 'Gemini', poolLabel: 'Gemini', family: 'Gemini' },
{ poolKey: 'Claude & GPT', poolLabel: 'Claude & GPT', family: 'Claude & GPT' },
];
const weekly = quotas.weekly || {};
const minuteTick = Math.floor(Date.now() / 30000);
const poolItems = rawPools.map((p) => {
const key = p.poolKey || p.family || p.poolLabel || 'Other';
const poolLabel = p.poolLabel || p.family || key;
const isActivePool =
Boolean(activePool.family) &&
(activePool.poolKey === key ||
activePool.family === p.family ||
(key === 'Claude & GPT' && ['Claude', 'GPT'].includes(activePool.family)));
return {
key,
poolLabel,
poolData: p,
fallbackWeekly: weekly,
isActivePool,
minuteTick,
};
});
const geminiPool =
pools.find((p) => p.family === 'Gemini') ||
(activePool.family === 'Gemini' ? activePool : null) ||
{};
const claudePool =
pools.find((p) => p.family === 'Claude & GPT' || p.family === 'Claude') ||
(['Claude & GPT', 'Claude', 'GPT'].includes(activePool.family) ? activePool : null) ||
{};
const activeIsGemini = activePool.family === 'Gemini';
const activeIsThirdParty = ['Claude & GPT', 'Claude', 'GPT'].includes(activePool.family);
syncPoolQuotaBlock(geminiQuotaBlock, 'Gemini', geminiPool, weekly, activeIsGemini);
syncPoolQuotaBlock(claudeQuotaBlock, 'Claude & GPT', claudePool, weekly, activeIsThirdParty);
patchKeyedList(poolsListEl, poolItems, {
keyFn: (item) => item.key,
sigFn: (item, idx) =>
`${idx}:${item.poolLabel}:${item.isActivePool}:${item.minuteTick}:${item.poolData?.usedPct}:${item.poolData?.remainingPct}:${item.poolData?.resetTime}:${item.poolData?.weeklyUsedPct}:${item.poolData?.weeklyRemainingPct}:${item.poolData?.weeklyResetTime}:${item.fallbackWeekly?.isOfficial}:${item.fallbackWeekly?.usedPct}:${item.fallbackWeekly?.title}`,
createRow: createPoolQuotaRow,
updateRow: syncPoolQuotaRow,
});
patchText(
wkFootLeft,
+2 -2
View File
@@ -4,11 +4,11 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>测速与额度监控</title>
<link rel="stylesheet" href="/styles.css?v=1793127685706">
<link rel="stylesheet" href="/styles.css?v=1793363188185">
<script src="/preload.js"></script>
</head>
<body>
<div id="app-root"></div>
<script src="/app.js?v=1793127685706"></script>
<script src="/app.js?v=1793363188185"></script>
</body>
</html>
+338 -98
View File
@@ -107,6 +107,10 @@ const PLACEHOLDER_MAP = {
MODEL_PLACEHOLDER_M318: { modelId: 'gemini-3.8-flash-high', label: 'Gemini 3.8 Flash (High)' },
MODEL_PLACEHOLDER_M319: { modelId: 'gemini-3.8-flash-medium', label: 'Gemini 3.8 Flash (Medium)' },
MODEL_PLACEHOLDER_M320: { modelId: 'gemini-3.8-flash-low', label: 'Gemini 3.8 Flash (Low)' },
MODEL_PLACEHOLDER_M322: { modelId: 'gemini-3.8-flash', label: 'Gemini 3.8 Flash (Tiered)' },
MODEL_PLACEHOLDER_M198: { modelId: 'gemini-3.5-flash-lite', label: 'Gemini 3.5 Flash Lite' },
MODEL_PLACEHOLDER_M50: { modelId: 'gemini-3.1-flash-lite', label: 'Gemini 3.1 Flash Lite' },
MODEL_PLACEHOLDER_M18: { modelId: 'gemini-3-flash', label: 'Gemini 3 Flash' },
MODEL_GOOGLE_GEMINI_2_5_FLASH_LITE: { modelId: 'gemini-2.5-flash-lite', label: 'Gemini 2.5 Flash Lite' },
MODEL_GOOGLE_GEMINI_2_5_FLASH: { modelId: 'gemini-2.5-flash', label: 'Gemini 2.5 Flash' },
MODEL_GOOGLE_GEMINI_2_5_PRO: { modelId: 'gemini-2.5-pro', label: 'Gemini 2.5 Pro' },
@@ -124,7 +128,7 @@ let trajectoryCache = Object.fromEntries(Object.entries(loadedTrajectoryCache).m
let cacheNeedsSave = JSON.stringify(trajectoryCache) !== JSON.stringify(loadedTrajectoryCache);
let externalDeepStatsMemo = { sig: '', convos: new Map() };
const inFlightRequests = new Map();
let quotaSummaryCache = { ts: 0, data: null, error: null };
let quotaSummaryCache = { ts: 0, accountName: '', data: null, error: null };
function loadJson(filePath, fallback) {
if (!existsSync(filePath)) return fallback;
@@ -190,10 +194,16 @@ async function getOfficialQuotaSummary(forceRefresh = false) {
}
try {
const res = await callLsRpc('RetrieveUserQuotaSummary', { forceRefresh: true }, 6000);
if (res?.response?.groups) {
quotaSummaryCache = { ts: now, data: res.response, error: null };
const payload = res?.response || res;
if (Array.isArray(payload?.groups) || Array.isArray(payload?.buckets)) {
quotaSummaryCache = {
ts: now,
accountName: quotaSummaryCache.accountName || '',
data: payload,
error: null,
};
return {
data: res.response,
data: payload,
fetchedAtMs: now,
isStale: false,
refreshFailed: false,
@@ -232,6 +242,106 @@ function inferFamilyFromProviderOrKey(rawModelKey = '', modelId = '', apiProvide
return 'Other';
}
function isArgonModelIdentifier(...parts) {
return /argon|MODEL_PLACEHOLDER_M41[789]\b/i.test(parts.filter(Boolean).join(' '));
}
function normalizeQuotaFraction(rawObj) {
if (!rawObj || typeof rawObj !== 'object') return null;
let remFrac = null;
if (rawObj.disabled === true) {
remFrac = 0;
} else if (
rawObj.remainingFraction !== undefined &&
rawObj.remainingFraction !== null &&
Number.isFinite(Number(rawObj.remainingFraction))
) {
remFrac = Math.max(0, Math.min(1, Number(rawObj.remainingFraction)));
} else if (typeof rawObj.resetTime === 'string' && rawObj.resetTime.trim().length > 0) {
// Proto3 omits numeric 0.0 default values when a quota bucket is completely exhausted.
remFrac = 0;
}
if (remFrac === null) return null;
const usedFrac = Math.max(0, Math.min(1, 1 - remFrac));
return {
remainingFraction: remFrac,
remainingPct: +(remFrac * 100).toFixed(1),
remainingIntPct: Math.floor(remFrac * 100 + 1e-6),
usedPct: +(usedFrac * 100).toFixed(1),
resetTime: rawObj.resetTime || null,
description: rawObj.description || '',
};
}
function classifyOfficialBucketWindow(bucket, groupBucketCount = 1, nowMs = Date.now()) {
const w = String(bucket?.window || '').trim().toLowerCase();
const idAndName = `${bucket?.bucketId || ''} ${bucket?.displayName || ''}`.toLowerCase();
if (
w === '5h' ||
/(?:^|[-_\s])5h(?:$|[-_\s])|five[-_\s]?hour/.test(w) ||
/(?:^|[-_\s])5h(?:$|[-_\s])|five[-_\s]?hour/.test(idAndName)
) {
return '5h';
}
if (w === 'weekly' || w === '7d' || /week/.test(w) || /week/.test(idAndName)) {
return 'weekly';
}
const resetMs = parseIsoMs(bucket?.resetTime);
if (resetMs > nowMs + 6 * 3600 * 1000 || groupBucketCount === 1) {
return 'weekly';
}
return '5h';
}
function classifyQuotaPoolIdentity({ groupName = '', groupDesc = '', bucketId = '', bucketName = '' }) {
const bId = String(bucketId || '');
const bName = String(bucketName || '');
const gName = String(groupName || '');
const gDesc = String(groupDesc || '');
if (
/argon/i.test(bId) ||
/argon/i.test(bName) ||
/argon/i.test(gName) ||
(/\bargon\b/i.test(gDesc) && !/\bflash\b/i.test(gDesc) && !/^gemini models$/i.test(gName.trim()))
) {
return {
poolKey: 'Argon',
poolLabel: 'Gemini 4 Argon',
poolName: 'Gemini 4 Argon 模型池',
};
}
if (/gemini/i.test(`${bId} ${bName} ${gName} ${gDesc}`)) {
return {
poolKey: 'Gemini',
poolLabel: 'Gemini',
poolName: 'Gemini 模型池',
};
}
if (/3p|claude|gpt|sonnet|opus|haiku|third[-_\s]?party/i.test(`${bId} ${gName} ${gDesc}`)) {
return {
poolKey: 'Claude & GPT',
poolLabel: 'Claude & GPT',
poolName: 'Claude & GPT 模型池',
};
}
const cleanLabel = (gName || bId || 'Other').trim();
return {
poolKey: cleanLabel,
poolLabel: cleanLabel,
poolName: `${cleanLabel} 模型池`,
};
}
function quotaFractionsMatch(a, b) {
if (!a || !b) return false;
if (Math.abs(a.remainingFraction - b.remainingFraction) > 0.015) return false;
if (a.resetTime && b.resetTime) {
const diffMs = Math.abs(parseIsoMs(a.resetTime) - parseIsoMs(b.resetTime));
if (diffMs > 120_000) return false;
}
return true;
}
function getBaseModelLabel(label = '') {
return String(label || '')
.replace(/\s*\((?:High|Medium|Low|Thinking|Extra Low)\)\s*$/i, '')
@@ -600,43 +710,89 @@ async function buildTelemetryPayloadInternal(
filterOpts = {}
) {
const settings = loadSettings();
const [userStatusRes, allTrajRes, officialQuotaInfo] = await Promise.all([
const [userStatusRes, allTrajRes, initialOfficialQuotaInfo] = await Promise.all([
callLsRpc('GetUserStatus', {}).catch(() => ({})),
callLsRpc('GetAllCascadeTrajectories', {}).catch(() => ({})),
getOfficialQuotaSummary(forceQuotaRefresh),
]);
const officialQuota = officialQuotaInfo?.data || null;
const userStatus = userStatusRes?.userStatus || {};
const currentAccountName = userStatus?.email || userStatus?.name || '';
let officialQuotaInfo = initialOfficialQuotaInfo;
if (
currentAccountName &&
quotaSummaryCache.accountName &&
quotaSummaryCache.accountName !== currentAccountName
) {
officialQuotaInfo = await getOfficialQuotaSummary(true);
}
if (currentAccountName && officialQuotaInfo?.data) {
quotaSummaryCache.accountName = currentAccountName;
}
const officialQuota = officialQuotaInfo?.data || null;
const clientConfigs = userStatus?.cascadeModelConfigData?.clientModelConfigs || [];
const dynamicModelMap = new Map();
// Extract official real-time buckets from RetrieveUserQuotaSummary if available
// Extract official real-time buckets & dynamic pools from RetrieveUserQuotaSummary
const nowForQuotaMs = Date.now();
const officialBuckets = new Map();
for (const grp of officialQuota?.groups || []) {
for (const b of grp?.buckets || []) {
if (b?.bucketId && b.remainingFraction !== undefined && b.remainingFraction !== null) {
const remFrac = Number(b.remainingFraction);
const usedFrac = Math.max(0, Math.min(1, 1 - remFrac));
officialBuckets.set(b.bucketId, {
bucketId: b.bucketId,
groupName: grp.displayName,
remainingFraction: remFrac,
remainingPct: +(remFrac * 100).toFixed(1),
remainingIntPct: Math.floor(remFrac * 100 + 1e-6),
usedPct: +(usedFrac * 100).toFixed(1),
resetTime: b.resetTime || null,
description: b.description || '',
});
const poolBuilders = new Map();
function ensurePoolBuilder({ poolKey, poolLabel, poolName }) {
if (!poolBuilders.has(poolKey)) {
poolBuilders.set(poolKey, {
poolKey,
poolLabel,
poolName,
bucket5h: null,
bucketWeekly: null,
fallback5h: null,
models: [],
});
}
return poolBuilders.get(poolKey);
}
const rawGroups = Array.isArray(officialQuota?.groups) ? [...officialQuota.groups] : [];
if (Array.isArray(officialQuota?.buckets) && officialQuota.buckets.length > 0 && rawGroups.length === 0) {
rawGroups.push({ displayName: '', description: '', buckets: officialQuota.buckets });
}
for (const grp of rawGroups) {
const grpBuckets = Array.isArray(grp?.buckets) ? grp.buckets : [];
for (const b of grpBuckets) {
const norm = normalizeQuotaFraction(b);
if (!norm) continue;
const ident = classifyQuotaPoolIdentity({
groupName: grp?.displayName,
groupDesc: grp?.description,
bucketId: b?.bucketId,
bucketName: b?.displayName,
});
const win = classifyOfficialBucketWindow(b, grpBuckets.length, nowForQuotaMs);
const entry = {
...norm,
bucketId: b?.bucketId || '',
groupName: grp?.displayName || ident.poolLabel,
window: win,
};
if (b?.bucketId) {
officialBuckets.set(b.bucketId, entry);
}
const builder = ensurePoolBuilder(ident);
if (win === '5h' && !builder.bucket5h) {
builder.bucket5h = entry;
} else if (win === 'weekly' && !builder.bucketWeekly) {
builder.bucketWeekly = entry;
} else if (!builder.bucketWeekly) {
builder.bucketWeekly = entry;
}
}
}
// Group 5h quotas by model pool
const quotaPoolsMap = new Map();
const modelQuotas = [];
const modelQuotaByKey = new Map();
// Register dynamic model map and inspect per-model quotaInfo from GetUserStatus
let sampleArgonCfgQuota = null;
let sampleStdGeminiCfgQuota = null;
for (const cfg of clientConfigs) {
const rawKey = cfg?.modelOrAlias?.model;
@@ -648,78 +804,125 @@ async function buildTelemetryPayloadInternal(
});
}
const info = resolveModelInfo(rawKey, dynamicModelMap);
const cfgQuota = normalizeQuotaFraction(cfg?.quotaInfo);
if (!cfgQuota || info.family !== 'Gemini') continue;
if (isArgonModelIdentifier(rawKey, cfg?.modelId, cfg?.label, info.modelId)) {
if (!sampleArgonCfgQuota) sampleArgonCfgQuota = cfgQuota;
} else if (!sampleStdGeminiCfgQuota) {
sampleStdGeminiCfgQuota = cfgQuota;
}
}
// Fallback Pro Argon detection: if RetrieveUserQuotaSummary did not emit a separate Argon
// group/bucket, check whether GetUserStatus reports an independent quotaInfo for Argon models
// that diverges from standard Gemini (Flash/Pro) and shared Gemini buckets.
if (!poolBuilders.has('Argon') && sampleArgonCfgQuota) {
const geminiBuilder = poolBuilders.get('Gemini');
const hasGeminiBaseline = Boolean(
sampleStdGeminiCfgQuota || geminiBuilder?.bucket5h || geminiBuilder?.bucketWeekly
);
const matchesSharedGemini =
quotaFractionsMatch(sampleArgonCfgQuota, sampleStdGeminiCfgQuota) ||
quotaFractionsMatch(sampleArgonCfgQuota, geminiBuilder?.bucket5h) ||
quotaFractionsMatch(sampleArgonCfgQuota, geminiBuilder?.bucketWeekly);
if (hasGeminiBaseline && !matchesSharedGemini) {
const argonBuilder = ensurePoolBuilder({
poolKey: 'Argon',
poolLabel: 'Gemini 4 Argon',
poolName: 'Gemini 4 Argon 模型池',
});
argonBuilder.bucketWeekly = {
...sampleArgonCfgQuota,
bucketId: 'argon-weekly-inferred',
groupName: 'Gemini 4 Argon',
window: 'weekly',
};
}
}
const hasDedicatedArgonPool = poolBuilders.has('Argon');
const modelQuotas = [];
const modelQuotaByKey = new Map();
for (const cfg of clientConfigs) {
const rawKey = cfg?.modelOrAlias?.model;
const info = resolveModelInfo(rawKey, dynamicModelMap);
const isArgon = isArgonModelIdentifier(rawKey, cfg?.modelId, cfg?.label, info.modelId);
const isGemini = info.family === 'Gemini';
const live5h = officialBuckets.get(isGemini ? 'gemini-5h' : '3p-5h');
const liveWeekly = officialBuckets.get(isGemini ? 'gemini-weekly' : '3p-weekly');
const targetIdent =
isArgon && hasDedicatedArgonPool
? { poolKey: 'Argon', poolLabel: 'Gemini 4 Argon', poolName: 'Gemini 4 Argon 模型池' }
: isGemini
? { poolKey: 'Gemini', poolLabel: 'Gemini', poolName: 'Gemini 模型池' }
: { poolKey: 'Claude & GPT', poolLabel: 'Claude & GPT', poolName: 'Claude & GPT 模型池' };
const rawRemFrac = live5h?.remainingFraction ?? cfg?.quotaInfo?.remainingFraction ?? null;
const hasValid5h = rawRemFrac !== null && rawRemFrac !== undefined && Number.isFinite(Number(rawRemFrac));
const remFrac = hasValid5h ? Number(rawRemFrac) : null;
const usedFrac = hasValid5h ? Math.max(0, Math.min(1, 1 - remFrac)) : null;
const resetTime = live5h?.resetTime || cfg?.quotaInfo?.resetTime || null;
const builder = ensurePoolBuilder(targetIdent);
if (cfg?.label && !builder.models.includes(cfg.label)) {
builder.models.push(cfg.label);
}
const cfgQuota = normalizeQuotaFraction(cfg?.quotaInfo);
if (!builder.bucket5h && !builder.bucketWeekly && !builder.fallback5h && cfgQuota) {
if (targetIdent.poolKey === 'Argon') {
builder.bucketWeekly = cfgQuota;
} else {
builder.fallback5h = cfgQuota;
}
}
const eff5h = builder.bucket5h || (!builder.bucketWeekly ? cfgQuota : null);
const effWk = builder.bucketWeekly;
const hasValid5h = Boolean(eff5h);
const quotaItem = {
label: cfg.label,
modelId: cfg.modelId,
rawKey,
family: info.family,
isAvailable: hasValid5h,
remainingPct: hasValid5h ? +(remFrac * 100).toFixed(1) : null,
remainingIntPct: hasValid5h ? Math.floor(remFrac * 100 + 1e-6) : null,
usedPct: hasValid5h ? +(usedFrac * 100).toFixed(1) : null,
resetTime,
weeklyRemainingPct: liveWeekly?.remainingPct ?? null,
weeklyRemainingIntPct: liveWeekly?.remainingIntPct ?? null,
weeklyUsedPct: liveWeekly?.usedPct ?? null,
weeklyResetTime: liveWeekly?.resetTime ?? null,
family: targetIdent.poolKey,
isAvailable: Boolean(eff5h || effWk || cfgQuota),
remainingPct: hasValid5h ? eff5h.remainingPct : null,
remainingIntPct: hasValid5h ? eff5h.remainingIntPct : null,
usedPct: hasValid5h ? eff5h.usedPct : null,
resetTime: hasValid5h ? eff5h.resetTime : null,
weeklyRemainingPct: effWk?.remainingPct ?? null,
weeklyRemainingIntPct: effWk?.remainingIntPct ?? null,
weeklyUsedPct: effWk?.usedPct ?? null,
weeklyResetTime: effWk?.resetTime || null,
};
modelQuotas.push(quotaItem);
if (rawKey) modelQuotaByKey.set(rawKey, quotaItem);
const poolKey = isGemini ? 'Gemini' : 'Claude & GPT';
if (!quotaPoolsMap.has(poolKey)) {
quotaPoolsMap.set(poolKey, {
poolName: isGemini ? 'Gemini 模型池' : 'Claude & GPT 模型池',
family: poolKey,
isAvailable: quotaItem.isAvailable,
remainingPct: quotaItem.remainingPct,
remainingIntPct: quotaItem.remainingIntPct,
usedPct: quotaItem.usedPct,
resetTime,
weeklyRemainingPct: quotaItem.weeklyRemainingPct,
weeklyRemainingIntPct: quotaItem.weeklyRemainingIntPct,
weeklyUsedPct: quotaItem.weeklyUsedPct,
weeklyResetTime: quotaItem.weeklyResetTime,
models: [cfg.label],
});
} else {
const existingPool = quotaPoolsMap.get(poolKey);
existingPool.models.push(cfg.label);
}
}
for (const [poolKey, b5hKey, bWkKey, poolName] of [
['Gemini', 'gemini-5h', 'gemini-weekly', 'Gemini 模型池'],
['Claude & GPT', '3p-5h', '3p-weekly', 'Claude & GPT 模型池'],
]) {
if (!quotaPoolsMap.has(poolKey)) {
const b5h = officialBuckets.get(b5hKey);
const bWk = officialBuckets.get(bWkKey);
quotaPoolsMap.set(poolKey, {
poolName,
family: poolKey,
isAvailable: Boolean(b5h),
remainingPct: b5h?.remainingPct ?? null,
remainingIntPct: b5h?.remainingIntPct ?? null,
usedPct: b5h?.usedPct ?? null,
resetTime: b5h?.resetTime || null,
weeklyRemainingPct: bWk?.remainingPct ?? null,
weeklyRemainingIntPct: bWk?.remainingIntPct ?? null,
weeklyUsedPct: bWk?.usedPct ?? null,
weeklyResetTime: bWk?.resetTime || null,
models: [],
});
}
// Ensure baseline Gemini and Claude & GPT pools always exist
ensurePoolBuilder({ poolKey: 'Gemini', poolLabel: 'Gemini', poolName: 'Gemini 模型池' });
ensurePoolBuilder({
poolKey: 'Claude & GPT',
poolLabel: 'Claude & GPT',
poolName: 'Claude & GPT 模型池',
});
const quotaPoolsMap = new Map();
for (const [poolKey, builder] of poolBuilders.entries()) {
const b5h = builder.bucket5h || builder.fallback5h || null;
const bWk = builder.bucketWeekly || null;
quotaPoolsMap.set(poolKey, {
poolKey,
poolLabel: builder.poolLabel,
poolName: builder.poolName,
family: poolKey,
isAvailable: Boolean(b5h || bWk),
has5h: Boolean(b5h),
hasWeekly: Boolean(bWk),
remainingPct: b5h?.remainingPct ?? null,
remainingIntPct: b5h?.remainingIntPct ?? null,
usedPct: b5h?.usedPct ?? null,
resetTime: b5h?.resetTime || null,
weeklyRemainingPct: bWk?.remainingPct ?? null,
weeklyRemainingIntPct: bWk?.remainingIntPct ?? null,
weeklyUsedPct: bWk?.usedPct ?? null,
weeklyResetTime: bWk?.resetTime || null,
models: builder.models,
});
}
// Enumerate all conversations from LS + local disk + existing cache
@@ -1001,14 +1204,40 @@ async function buildTelemetryPayloadInternal(
sessionPromptTokens > 0 ? Math.round((sessionCacheReadTokens / sessionPromptTokens) * 100) : 0;
// Determine active pool and its official cycle anchors for time window alignment
const latestIsArgon = latestEnriched
? isArgonModelIdentifier(
latestEnriched.modelKey,
latestEnriched.responseModel,
latestEnriched.modelUpstream,
latestEnriched.modelLabel
)
: false;
const rawActiveFamily = latestEnriched?.family || 'Other';
const activePoolKey = rawActiveFamily === 'Gemini' ? 'Gemini'
: ['Claude', 'GPT'].includes(rawActiveFamily) ? 'Claude & GPT' : 'Unknown';
const activeLive5h = officialBuckets.get(activePoolKey === 'Gemini' ? 'gemini-5h'
: activePoolKey === 'Claude & GPT' ? '3p-5h' : null);
const activeLiveWeekly = officialBuckets.get(
activePoolKey === 'Gemini' ? 'gemini-weekly' : activePoolKey === 'Claude & GPT' ? '3p-weekly' : null
);
const activePoolKey =
latestIsArgon && quotaPoolsMap.has('Argon')
? 'Argon'
: rawActiveFamily === 'Gemini'
? 'Gemini'
: ['Claude', 'GPT'].includes(rawActiveFamily)
? 'Claude & GPT'
: 'Unknown';
const matchedActivePool = quotaPoolsMap.get(activePoolKey) || null;
const activeLive5h = matchedActivePool?.has5h
? {
remainingPct: matchedActivePool.remainingPct,
remainingIntPct: matchedActivePool.remainingIntPct,
usedPct: matchedActivePool.usedPct,
resetTime: matchedActivePool.resetTime,
}
: null;
const activeLiveWeekly = matchedActivePool?.hasWeekly
? {
remainingPct: matchedActivePool.weeklyRemainingPct,
remainingIntPct: matchedActivePool.weeklyRemainingIntPct,
usedPct: matchedActivePool.weeklyUsedPct,
resetTime: matchedActivePool.weeklyResetTime,
}
: null;
const cycleAnchors = {
fiveHourResetMs: parseIsoMs(activeLive5h?.resetTime),
weeklyResetMs: parseIsoMs(activeLiveWeekly?.resetTime),
@@ -1288,11 +1517,22 @@ async function buildTelemetryPayloadInternal(
const weekBucket = finalizedPresets.week.account;
const familyPoolQuota = quotaPoolsMap.get(activePoolKey);
const activePoolLabel = familyPoolQuota?.poolLabel || activePoolKey;
const activePoolQuota = familyPoolQuota || {
poolName: activePoolKey === 'Gemini' ? 'Gemini 模型池'
: activePoolKey === 'Claude & GPT' ? 'Claude & GPT 模型池' : '模型池未知',
poolKey: activePoolKey,
poolLabel: activePoolKey === 'Unknown' ? '未知' : activePoolKey,
poolName:
activePoolKey === 'Argon'
? 'Gemini 4 Argon 模型池'
: activePoolKey === 'Gemini'
? 'Gemini 模型池'
: activePoolKey === 'Claude & GPT'
? 'Claude & GPT 模型池'
: '模型池未知',
family: activePoolKey,
isAvailable: Boolean(activeLive5h),
isAvailable: Boolean(activeLive5h || activeLiveWeekly),
has5h: Boolean(activeLive5h),
hasWeekly: Boolean(activeLiveWeekly),
remainingPct: activeLive5h?.remainingPct ?? null,
remainingIntPct: activeLive5h?.remainingIntPct ?? null,
usedPct: activeLive5h?.usedPct ?? null,
@@ -1424,7 +1664,7 @@ async function buildTelemetryPayloadInternal(
},
activePool: activePoolQuota,
pools: Array.from(quotaPoolsMap.values()).sort((a, b) => {
const order = { Gemini: 0, 'Claude & GPT': 1 };
const order = { Gemini: 0, Argon: 1, 'Claude & GPT': 2 };
return (order[a.family] ?? 99) - (order[b.family] ?? 99);
}),
models: modelQuotas.sort((a, b) => String(a.label).localeCompare(String(b.label))),
@@ -1433,7 +1673,7 @@ async function buildTelemetryPayloadInternal(
poolFamily: activePoolKey,
title: isCustomWeeklyMode
? '每周限额 (自定义本机)'
: `每周限额 (${activePoolKey || '当前'})`,
: `每周限额 (${activePoolLabel && activePoolLabel !== 'Unknown' ? activePoolLabel : '当前'})`,
calls: weekBucket.calls,
tokens: weekBucket.totalTokens,
costUsd: weekBucket.costUsd,
@@ -118,11 +118,36 @@ function isEquivalentTelemetry(prev, next) {
}
}
if (prev.account?.tierName !== next.account?.tierName || prev.account?.planName !== next.account?.planName) {
return false;
}
const pQuot = prev.quotas?.activePool;
const nQuot = next.quotas?.activePool;
if (pQuot?.family !== nQuot?.family) return false;
if (pQuot?.usedPct !== nQuot?.usedPct) return false;
if (pQuot?.remainingPct !== nQuot?.remainingPct) return false;
if (pQuot?.weeklyUsedPct !== nQuot?.weeklyUsedPct) return false;
if (prev.quotas?.weekly?.usedPct !== next.quotas?.weekly?.usedPct) return false;
if (prev.quotas?.weekly?.remainingPct !== next.quotas?.weekly?.remainingPct) return false;
const pPools = prev.quotas?.pools || [];
const nPools = next.quotas?.pools || [];
if (pPools.length !== nPools.length) return false;
for (let i = 0; i < pPools.length; i++) {
if (
pPools[i]?.poolKey !== nPools[i]?.poolKey ||
pPools[i]?.poolLabel !== nPools[i]?.poolLabel ||
pPools[i]?.usedPct !== nPools[i]?.usedPct ||
pPools[i]?.remainingPct !== nPools[i]?.remainingPct ||
pPools[i]?.resetTime !== nPools[i]?.resetTime ||
pPools[i]?.weeklyUsedPct !== nPools[i]?.weeklyUsedPct ||
pPools[i]?.weeklyRemainingPct !== nPools[i]?.weeklyRemainingPct ||
pPools[i]?.weeklyResetTime !== nPools[i]?.weeklyResetTime
) {
return false;
}
}
if ((prev.conversations?.length || 0) !== (next.conversations?.length || 0)) return false;
+99 -63
View File
@@ -8,7 +8,9 @@
import { defineComponent } from '../core/component.js';
import {
h,
patchAttr,
patchClasses,
patchKeyedList,
patchStyleVar,
patchText,
} from '../core/domPatch.js';
@@ -141,38 +143,37 @@ export const LiveOverviewView = defineComponent({
]),
]);
// 3. Official 5h & Weekly Quotas Panel (Gemini Pool + Claude Pool)
// 3. Official 5h & Weekly Quotas Panel (Dynamic Pools: Gemini, Argon on Pro, Claude & GPT, etc.)
const tierBadge = h('span', { className: 'panel-meta', text: 'Google AI · Pro' });
const poolsListEl = h('div', { style: 'display: flex; flex-direction: column; gap: 0;' });
function createPoolQuotaBlock(poolLabel) {
const title5h = h('span', { text: `5h 限额 (${poolLabel})` });
function createPoolQuotaRow() {
const title5h = h('span', { text: '5h 限额' });
const meta5h = h('span', { className: 'panel-meta text-mono', text: '--' });
const fill5h = h('div', { className: 'progress-fill' });
const titleWk = h('span', { text: `每周限额 (${poolLabel})` });
const metaWk = h('span', { className: 'panel-meta text-mono', text: '--' });
const fillWk = h('div', { className: 'progress-fill' });
const el = h('div', { style: 'display: flex; flex-direction: column; gap: 8px;' }, [
h('div', { style: 'display: flex; flex-direction: column; gap: 4px;' }, [
h('div', { className: 'panel-header' }, [title5h, meta5h]),
h('div', { className: 'progress-track' }, [fill5h]),
]),
h('div', { style: 'display: flex; flex-direction: column; gap: 4px;' }, [
h('div', { className: 'panel-header' }, [titleWk, metaWk]),
h('div', { className: 'progress-track' }, [fillWk]),
]),
const row5h = h('div', { style: 'display: flex; flex-direction: column; gap: 4px;' }, [
h('div', { className: 'panel-header' }, [title5h, meta5h]),
h('div', { className: 'progress-track' }, [fill5h]),
]);
return { el, title5h, meta5h, fill5h, titleWk, metaWk, fillWk };
}
const titleWk = h('span', { text: '每周限额' });
const metaWk = h('span', { className: 'panel-meta text-mono', text: '--' });
const fillWk = h('div', { className: 'progress-fill' });
const rowWk = h('div', { style: 'display: flex; flex-direction: column; gap: 4px;' }, [
h('div', { className: 'panel-header' }, [titleWk, metaWk]),
h('div', { className: 'progress-track' }, [fillWk]),
]);
const geminiQuotaBlock = createPoolQuotaBlock('Gemini');
const claudeQuotaBlock = createPoolQuotaBlock('Claude & GPT');
claudeQuotaBlock.el.setAttribute(
'style',
'display: flex; flex-direction: column; gap: 8px; margin-top: 3px; padding-top: 10px; border-top: 1px solid var(--border-hairline);'
);
const el = h('div', { style: 'display: flex; flex-direction: column; gap: 8px;' }, [
row5h,
rowWk,
]);
return {
el,
refs: { row5h, title5h, meta5h, fill5h, rowWk, titleWk, metaWk, fillWk },
};
}
const wkFootLeft = h('span', { className: 'text-muted', text: '本周本机: 0 ($0.00)' });
const wkFootRight = h('span', { className: 'text-muted', text: '' });
@@ -185,8 +186,7 @@ export const LiveOverviewView = defineComponent({
]),
tierBadge,
]),
geminiQuotaBlock.el,
claudeQuotaBlock.el,
poolsListEl,
h('div', { className: 'panel-header', style: 'font-size: 11px; padding-top: 2px;' }, [
wkFootLeft,
wkFootRight,
@@ -205,46 +205,65 @@ export const LiveOverviewView = defineComponent({
className: 'view-pane',
});
function syncPoolQuotaBlock(block, poolLabel, poolData, fallbackWeekly, isActiveFamily) {
function syncPoolQuotaRow(refs, item, idx, rowEl) {
const { poolData, poolLabel, fallbackWeekly, isActivePool } = item;
patchAttr(
rowEl,
'style',
idx === 0
? 'display: flex; flex-direction: column; gap: 8px;'
: 'display: flex; flex-direction: column; gap: 8px; margin-top: 10px; padding-top: 10px; border-top: 1px solid var(--border-hairline);'
);
const has5h = poolData?.usedPct != null && poolData?.remainingPct != null;
const used5hVal = has5h ? Number(poolData.usedPct) : 0;
const rem5hVal = has5h ? Number(poolData.remainingPct) : 0;
patchText(block.title5h, `5h 限额 (${poolLabel})`);
patchText(
block.meta5h,
has5h
? `${formatCountdown(poolData.resetTime)} · 已用 ${used5hVal.toFixed(1)}% (余 ${rem5hVal.toFixed(1)}%)`
: '获取失败 (--%)'
);
patchStyleVar(block.fill5h, '--fill-w', `${Math.min(100, used5hVal)}%`);
patchClasses(block.fill5h, {
'tone-warn': used5hVal >= 60 && used5hVal < 85,
'tone-danger': used5hVal >= 85,
});
const wkUsedRaw =
poolData?.weeklyUsedPct ?? (isActiveFamily ? fallbackWeekly?.usedPct : null);
poolData?.weeklyUsedPct ?? (isActivePool ? fallbackWeekly?.usedPct : null);
const wkRemRaw =
poolData?.weeklyRemainingPct ?? (isActiveFamily ? fallbackWeekly?.remainingPct : null);
poolData?.weeklyRemainingPct ?? (isActivePool ? fallbackWeekly?.remainingPct : null);
const wkResetRaw =
poolData?.weeklyResetTime || (isActiveFamily ? fallbackWeekly?.resetTime : null);
poolData?.weeklyResetTime || (isActivePool ? fallbackWeekly?.resetTime : null);
const hasWk = wkUsedRaw != null && wkRemRaw != null;
const usedWkVal = hasWk ? Number(wkUsedRaw) : 0;
const remWkVal = hasWk ? Number(wkRemRaw) : 0;
// Hide non-applicable window on weekly-only pools (e.g. Pro Argon pool or Plus tier)
// or 5h-only pools, while still showing both rows with error state if both failed.
const hide5h = !has5h && hasWk;
const hideWk = !hasWk && has5h;
refs.row5h.hidden = hide5h;
refs.row5h.style.display = hide5h ? 'none' : 'flex';
refs.rowWk.hidden = hideWk;
refs.rowWk.style.display = hideWk ? 'none' : 'flex';
patchText(refs.title5h, `5h 限额 (${poolLabel})`);
patchText(
refs.meta5h,
has5h
? `${formatCountdown(poolData.resetTime)} · 已用 ${used5hVal.toFixed(1)}% (余 ${rem5hVal.toFixed(1)}%)`
: '获取失败 (--%)'
);
patchStyleVar(refs.fill5h, '--fill-w', `${Math.min(100, used5hVal)}%`);
patchClasses(refs.fill5h, {
'tone-warn': used5hVal >= 60 && used5hVal < 85,
'tone-danger': used5hVal >= 85,
});
const customTitle =
isActiveFamily && fallbackWeekly?.isOfficial === false && fallbackWeekly?.title
isActivePool && fallbackWeekly?.isOfficial === false && fallbackWeekly?.title
? fallbackWeekly.title
: `每周限额 (${poolLabel})`;
patchText(block.titleWk, customTitle);
patchText(refs.titleWk, customTitle);
patchText(
block.metaWk,
refs.metaWk,
hasWk
? `${formatCountdown(wkResetRaw)} · 已用 ${usedWkVal.toFixed(1)}% (余 ${remWkVal.toFixed(1)}%)`
: '获取失败 (--%)'
);
patchStyleVar(block.fillWk, '--fill-w', `${Math.min(100, usedWkVal)}%`);
patchClasses(block.fillWk, {
patchStyleVar(refs.fillWk, '--fill-w', `${Math.min(100, usedWkVal)}%`);
patchClasses(refs.fillWk, {
'tone-warn': usedWkVal >= 60 && usedWkVal < 85,
'tone-danger': usedWkVal >= 85,
});
@@ -298,28 +317,45 @@ export const LiveOverviewView = defineComponent({
patchText(bdSystemPrompt, formatTokens(ctx.systemPromptTokens || 0));
patchText(bdUserRules, formatTokens(ctx.userRulesTokens || 0));
// 3. Quotas (Gemini + Claude & GPT)
// 3. Quotas (Dynamic Pools: Gemini, Argon on Pro, Claude & GPT, etc.)
patchText(
tierBadge,
`${data.account?.tierName || 'Google AI'} · ${data.account?.planName || 'Pro'}`
);
const activePool = quotas.activePool || {};
const pools = quotas.pools || [];
const rawPools = Array.isArray(quotas.pools) && quotas.pools.length > 0
? quotas.pools
: [
{ poolKey: 'Gemini', poolLabel: 'Gemini', family: 'Gemini' },
{ poolKey: 'Claude & GPT', poolLabel: 'Claude & GPT', family: 'Claude & GPT' },
];
const weekly = quotas.weekly || {};
const minuteTick = Math.floor(Date.now() / 30000);
const poolItems = rawPools.map((p) => {
const key = p.poolKey || p.family || p.poolLabel || 'Other';
const poolLabel = p.poolLabel || p.family || key;
const isActivePool =
Boolean(activePool.family) &&
(activePool.poolKey === key ||
activePool.family === p.family ||
(key === 'Claude & GPT' && ['Claude', 'GPT'].includes(activePool.family)));
return {
key,
poolLabel,
poolData: p,
fallbackWeekly: weekly,
isActivePool,
minuteTick,
};
});
const geminiPool =
pools.find((p) => p.family === 'Gemini') ||
(activePool.family === 'Gemini' ? activePool : null) ||
{};
const claudePool =
pools.find((p) => p.family === 'Claude & GPT' || p.family === 'Claude') ||
(['Claude & GPT', 'Claude', 'GPT'].includes(activePool.family) ? activePool : null) ||
{};
const activeIsGemini = activePool.family === 'Gemini';
const activeIsThirdParty = ['Claude & GPT', 'Claude', 'GPT'].includes(activePool.family);
syncPoolQuotaBlock(geminiQuotaBlock, 'Gemini', geminiPool, weekly, activeIsGemini);
syncPoolQuotaBlock(claudeQuotaBlock, 'Claude & GPT', claudePool, weekly, activeIsThirdParty);
patchKeyedList(poolsListEl, poolItems, {
keyFn: (item) => item.key,
sigFn: (item, idx) =>
`${idx}:${item.poolLabel}:${item.isActivePool}:${item.minuteTick}:${item.poolData?.usedPct}:${item.poolData?.remainingPct}:${item.poolData?.resetTime}:${item.poolData?.weeklyUsedPct}:${item.poolData?.weeklyRemainingPct}:${item.poolData?.weeklyResetTime}:${item.fallbackWeekly?.isOfficial}:${item.fallbackWeekly?.usedPct}:${item.fallbackWeekly?.title}`,
createRow: createPoolQuotaRow,
updateRow: syncPoolQuotaRow,
});
patchText(
wkFootLeft,
+7 -3
View File
@@ -3,10 +3,10 @@ import path from 'node:path';
import vm from 'node:vm';
import * as metrics from '../speed-metrics.mjs';
export function backendHarness({cache={},settings={},trajectories={},summaries={},userStatus={},sourceText=null,metricsImplementation=metrics}={}) {
export function backendHarness({cache={},settings={},trajectories={},summaries={},userStatus={},quotaSummary={groups:[]},sourceText=null,metricsImplementation=metrics}={}) {
const source=(sourceText ?? fs.readFileSync(new URL('../main.mjs',import.meta.url),'utf8'))
.replace(/^import .*;\r?\n/gm,'').replaceAll('import.meta.url',JSON.stringify('file:///test/main.mjs'));
const state={calls:[],errors:[],saves:[],trajectories};
const state={calls:[],errors:[],saves:[],trajectories,userStatus,quotaSummary};
const ctx={
...metricsImplementation, URL, AbortSignal,
process:{env:{ANTIGRAVITY_EXECUTABLE_DATA_DIR:'/test-data',ANTIGRAVITY_LS_ADDRESS:'test.invalid',ANTIGRAVITY_CSRF_TOKEN:'test'}},
@@ -26,7 +26,11 @@ export function backendHarness({cache={},settings={},trajectories={},summaries={
if(data instanceof Error) throw data;
return {ok:true,json:async()=>data||{}};
}
const data={GetUserStatus:{userStatus},GetAllCascadeTrajectories:{trajectorySummaries:summaries},RetrieveUserQuotaSummary:{response:{groups:[]}}}[method];
if(method==='RetrieveUserQuotaSummary') {
if(state.quotaSummary instanceof Error) throw state.quotaSummary;
return {ok:true,json:async()=>({response:state.quotaSummary})};
}
const data={GetUserStatus:{userStatus:state.userStatus},GetAllCascadeTrajectories:{trajectorySummaries:summaries}}[method];
return {ok:true,json:async()=>data};
},
};
+397
View File
@@ -0,0 +1,397 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import vm from 'node:vm';
import { backendHarness } from './backend-harness.mjs';
const FLASH = 'MODEL_PLACEHOLDER_M318';
const ARGON = 'MODEL_PLACEHOLDER_M417';
const createdAtMs = Date.now() - 20_000;
function makeStep(index, model) {
return {
type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE',
status: 'CORTEX_STEP_STATUS_DONE',
metadata: {
sourceTrajectoryStepInfo: { stepIndex: index },
createdAt: new Date(createdAtMs).toISOString(),
completedAt: new Date(createdAtMs + 5_000).toISOString(),
modelUsage: {
model,
apiProvider: 'API_PROVIDER_GOOGLE_GEMINI',
inputTokens: '1000',
cacheReadTokens: '4000',
outputTokens: '500',
},
},
};
}
test('Ultra user: Argon and Flash sharing Gemini Models remain a single Gemini pool', async () => {
const sharedReset = new Date(Date.now() + 18 * 3600_000).toISOString();
const fiveHourReset = new Date(Date.now() + 2 * 3600_000).toISOString();
const h = backendHarness({
summaries: { conv1: { stepCount: 1 } },
trajectories: { conv1: { trajectory: { steps: [makeStep(1, ARGON)] } } },
userStatus: {
userTier: { id: 'g1-ultra-lite-tier', name: 'Google AI Ultra' },
planStatus: { planInfo: { planName: 'Pro' } },
cascadeModelConfigData: {
clientModelConfigs: [
{
label: 'Gemini 4 Argon (High)',
modelId: 'gemini-4-argon-high',
modelOrAlias: { model: ARGON },
quotaInfo: { remainingFraction: 0.087, resetTime: sharedReset },
},
{
label: 'Gemini 3.8 Flash (High)',
modelId: 'gemini-3.8-flash-high',
modelOrAlias: { model: FLASH },
quotaInfo: { remainingFraction: 0.087, resetTime: sharedReset },
},
],
},
},
quotaSummary: {
groups: [
{
displayName: 'Gemini Models',
description: 'Models within this group: Gemini Flash, Gemini Pro',
buckets: [
{ bucketId: 'gemini-5h', window: '5h', remainingFraction: 0.99, resetTime: fiveHourReset },
{ bucketId: 'gemini-weekly', window: 'weekly', remainingFraction: 0.0868, resetTime: sharedReset },
],
},
{
displayName: 'Claude and GPT models',
buckets: [
{ bucketId: '3p-5h', window: '5h', remainingFraction: 1, resetTime: fiveHourReset },
{ bucketId: '3p-weekly', window: 'weekly', remainingFraction: 1, resetTime: sharedReset },
],
},
],
},
});
const p = await h.buildTelemetryPayloadInternal('conv1');
assert.deepEqual(
Array.from(p.quotas.pools, (pool) => pool.poolKey),
['Gemini', 'Claude & GPT']
);
assert.equal(p.quotas.activePool.family, 'Gemini');
assert.equal(p.quotas.activePool.weeklyRemainingPct, 8.7);
assert.equal(p.quotas.weekly.poolFamily, 'Gemini');
assert.equal(p.quotas.weekly.title, '每周限额 (Gemini)');
});
test('Pro user Shape 1: dedicated weekly-only Argon group in RetrieveUserQuotaSummary', async () => {
const geminiWkReset = new Date(Date.now() + 48 * 3600_000).toISOString();
const argonWkReset = new Date(Date.now() + 72 * 3600_000).toISOString();
const fiveHourReset = new Date(Date.now() + 3 * 3600_000).toISOString();
const h = backendHarness({
summaries: { argonConv: { stepCount: 1 }, flashConv: { stepCount: 1 } },
trajectories: {
argonConv: { trajectory: { steps: [makeStep(1, ARGON)] } },
flashConv: { trajectory: { steps: [makeStep(1, FLASH)] } },
},
userStatus: {
userTier: { id: 'g1-pro-tier', name: 'Google AI Pro' },
planStatus: { planInfo: { planName: 'Pro' } },
cascadeModelConfigData: {
clientModelConfigs: [
{
label: 'Gemini 4 Argon (High)',
modelId: 'gemini-4-argon-high',
modelOrAlias: { model: ARGON },
quotaInfo: { remainingFraction: 0.35, resetTime: argonWkReset },
},
{
label: 'Gemini 3.8 Flash (High)',
modelId: 'gemini-3.8-flash-high',
modelOrAlias: { model: FLASH },
quotaInfo: { remainingFraction: 0.9, resetTime: geminiWkReset },
},
],
},
},
quotaSummary: {
groups: [
{
displayName: 'Gemini Models',
description: 'Models within this group: Gemini Flash, Gemini Pro',
buckets: [
{ bucketId: 'gemini-5h', window: '5h', remainingFraction: 0.95, resetTime: fiveHourReset },
{ bucketId: 'gemini-weekly', window: 'weekly', remainingFraction: 0.9, resetTime: geminiWkReset },
],
},
{
displayName: 'Gemini 4 Argon',
description:
'For paid Pro plans, Argon quota is separate. Higher Argon quota (included as part of the larger Gemini quota bucket) is available on Ultra plans.',
buckets: [
{
bucketId: 'gemini-argon-wtu-weekly',
displayName: 'Gemini 4 Argon Weekly Limit',
description: 'You have used some of your weekly limit, it will fully refresh in 3 days, 22 hours.',
window: 'weekly',
remainingFraction: 0.35,
resetTime: argonWkReset,
},
],
},
{
displayName: 'Claude and GPT models',
buckets: [
{ bucketId: '3p-5h', window: '5h', remainingFraction: 1, resetTime: fiveHourReset },
{ bucketId: '3p-weekly', window: 'weekly', remainingFraction: 0.8, resetTime: geminiWkReset },
],
},
],
},
});
const argonPayload = await h.buildTelemetryPayloadInternal('argonConv');
assert.deepEqual(
Array.from(argonPayload.quotas.pools, (pool) => pool.poolKey),
['Gemini', 'Argon', 'Claude & GPT']
);
const argonPool = argonPayload.quotas.pools.find((pool) => pool.poolKey === 'Argon');
assert.equal(argonPool.poolLabel, 'Gemini 4 Argon');
assert.equal(argonPool.isAvailable, true);
assert.equal(argonPool.has5h, false);
assert.equal(argonPool.hasWeekly, true);
assert.equal(argonPool.remainingPct, null);
assert.equal(argonPool.weeklyRemainingPct, 35);
assert.equal(argonPool.weeklyUsedPct, 65);
assert.deepEqual(Array.from(argonPool.models), ['Gemini 4 Argon (High)']);
// Active Argon conversation binds to Argon pool
assert.equal(argonPayload.quotas.activePool.family, 'Argon');
assert.equal(argonPayload.quotas.weekly.poolFamily, 'Argon');
assert.equal(argonPayload.quotas.weekly.title, '每周限额 (Gemini 4 Argon)');
assert.equal(argonPayload.quotas.weekly.remainingPct, 35);
// Active Flash conversation binds to Gemini pool
const flashPayload = await h.buildTelemetryPayloadInternal('flashConv');
assert.equal(flashPayload.quotas.activePool.family, 'Gemini');
assert.equal(flashPayload.quotas.weekly.poolFamily, 'Gemini');
assert.equal(flashPayload.quotas.weekly.title, '每周限额 (Gemini)');
assert.equal(flashPayload.quotas.weekly.remainingPct, 90);
});
test('Pro user Shape 2: argon-weekly bucket nested inside Gemini Models group splits into Argon pool', async () => {
const wkReset = new Date(Date.now() + 60 * 3600_000).toISOString();
const h = backendHarness({
quotaSummary: {
groups: [
{
displayName: 'Gemini Models',
buckets: [
{ bucketId: 'gemini-5h', window: '5h', remainingFraction: 1, resetTime: wkReset },
{ bucketId: 'gemini-weekly', window: 'weekly', remainingFraction: 0.88, resetTime: wkReset },
{ bucketId: 'argon-weekly', window: 'weekly', remainingFraction: 0.42, resetTime: wkReset },
],
},
],
},
});
const p = await h.buildTelemetryPayloadInternal('none');
const argonPool = p.quotas.pools.find((pool) => pool.poolKey === 'Argon');
const geminiPool = p.quotas.pools.find((pool) => pool.poolKey === 'Gemini');
assert.ok(argonPool);
assert.equal(argonPool.weeklyRemainingPct, 42);
assert.equal(argonPool.has5h, false);
assert.equal(geminiPool.weeklyRemainingPct, 88);
assert.equal(geminiPool.has5h, true);
});
test('Pro user Shape 3: divergent Argon quotaInfo in GetUserStatus synthesizes Argon pool when absent from summary', async () => {
const geminiWkReset = new Date(Date.now() + 50 * 3600_000).toISOString();
const argonWkReset = new Date(Date.now() + 90 * 3600_000).toISOString();
const fiveHourReset = new Date(Date.now() + 2 * 3600_000).toISOString();
const h = backendHarness({
summaries: { argonConv: { stepCount: 1 } },
trajectories: { argonConv: { trajectory: { steps: [makeStep(1, ARGON)] } } },
userStatus: {
userTier: { id: 'g1-pro-tier', name: 'Google AI Pro' },
cascadeModelConfigData: {
clientModelConfigs: [
{
label: 'Gemini 4 Argon (High)',
modelId: 'gemini-4-argon-high',
modelOrAlias: { model: ARGON },
quotaInfo: { remainingFraction: 0.25, resetTime: argonWkReset },
},
{
label: 'Gemini 3.8 Flash (High)',
modelId: 'gemini-3.8-flash-high',
modelOrAlias: { model: FLASH },
quotaInfo: { remainingFraction: 0.85, resetTime: geminiWkReset },
},
],
},
},
quotaSummary: {
groups: [
{
displayName: 'Gemini Models',
buckets: [
{ bucketId: 'gemini-5h', window: '5h', remainingFraction: 0.95, resetTime: fiveHourReset },
{ bucketId: 'gemini-weekly', window: 'weekly', remainingFraction: 0.85, resetTime: geminiWkReset },
],
},
],
},
});
const p = await h.buildTelemetryPayloadInternal('argonConv');
const argonPool = p.quotas.pools.find((pool) => pool.poolKey === 'Argon');
assert.ok(argonPool, 'synthesizes Argon pool from divergent clientModelConfigs.quotaInfo');
assert.equal(argonPool.has5h, false);
assert.equal(argonPool.hasWeekly, true);
assert.equal(argonPool.weeklyRemainingPct, 25);
assert.equal(argonPool.weeklyUsedPct, 75);
assert.equal(p.quotas.activePool.family, 'Argon');
assert.equal(p.quotas.weekly.remainingPct, 25);
});
test('exhausted 0% bucket omitting remainingFraction in proto3 is reported as 100% used, not unavailable', async () => {
const argonWkReset = new Date(Date.now() + 30 * 3600_000).toISOString();
const h = backendHarness({
quotaSummary: {
groups: [
{
displayName: 'Gemini 4 Argon',
buckets: [
// Proto3 omits remainingFraction when it equals 0
{ bucketId: 'argon-weekly', window: 'weekly', resetTime: argonWkReset },
],
},
],
},
});
const p = await h.buildTelemetryPayloadInternal('none');
const argonPool = p.quotas.pools.find((pool) => pool.poolKey === 'Argon');
assert.ok(argonPool);
assert.equal(argonPool.isAvailable, true);
assert.equal(argonPool.weeklyRemainingPct, 0);
assert.equal(argonPool.weeklyUsedPct, 100);
});
test('telemetryStore isEquivalentTelemetry detects quota changes in non-active pools', () => {
const source = fs.readFileSync(new URL('../src/store/telemetryStore.js', import.meta.url), 'utf8');
const fn = source.slice(
source.indexOf('function isEquivalentTelemetry'),
source.indexOf('export async function fetchTelemetry')
);
const ctx = {};
vm.runInNewContext(fn + '\nglobalThis.compare=isEquivalentTelemetry;', ctx);
const a = {
account: { tierName: 'Google AI Pro', planName: 'Pro' },
quotas: {
activePool: { family: 'Gemini', usedPct: 10, remainingPct: 90, weeklyUsedPct: 20 },
weekly: { usedPct: 20, remainingPct: 80 },
pools: [
{ poolKey: 'Gemini', poolLabel: 'Gemini', usedPct: 10, remainingPct: 90, weeklyUsedPct: 20, weeklyRemainingPct: 80 },
{ poolKey: 'Argon', poolLabel: 'Gemini 4 Argon', usedPct: null, remainingPct: null, weeklyUsedPct: 40, weeklyRemainingPct: 60 },
],
},
};
const b = structuredClone(a);
b.quotas.pools[1].weeklyUsedPct = 55;
b.quotas.pools[1].weeklyRemainingPct = 45;
assert.equal(ctx.compare(a, b), false);
assert.equal(ctx.compare(a, structuredClone(a)), true);
});
test('switching accounts within 10s immediately invalidates quotaSummaryCache', async () => {
const proReset = '2026-11-03T10:24:10Z';
const ultraReset = '2026-11-05T16:02:44Z';
const h = backendHarness({
userStatus: {
email: 'pro-user@example.com',
userTier: { id: 'g1-pro-tier', name: 'Google AI Pro' },
},
quotaSummary: {
groups: [
{
displayName: 'Gemini Models',
description: 'Models within this group: Gemini Flash, Gemini Pro',
buckets: [
{ bucketId: 'gemini-weekly', window: 'weekly', remainingFraction: 0.9990884, resetTime: ultraReset },
{ bucketId: 'gemini-5h', window: '5h', remainingFraction: 1, resetTime: '2026-10-30T17:21:07Z' },
],
},
{
displayName: 'Claude and GPT models',
description: 'Models within this group: Claude Opus, Claude Sonnet, GPT-OSS',
buckets: [
{ bucketId: '3p-weekly', window: 'weekly', remainingFraction: 1, resetTime: '2026-11-06T03:55:10Z' },
{ bucketId: '3p-5h', window: '5h', remainingFraction: 1, resetTime: '2026-10-30T17:21:07Z' },
],
},
{
displayName: 'Gemini 4 Argon',
description:
'For paid Pro plans, Argon quota is separate. Higher Argon quota (included as part of the larger Gemini quota bucket) is available on Ultra plans.',
buckets: [
{
bucketId: 'gemini-argon-wtu-weekly',
displayName: 'Gemini 4 Argon Weekly Limit',
window: 'weekly',
remainingFraction: 0.6623139,
resetTime: proReset,
},
],
},
],
},
});
const first = await h.buildTelemetryPayloadInternal('none');
assert.deepEqual(
Array.from(first.quotas.pools, (pool) => pool.poolKey),
['Gemini', 'Argon', 'Claude & GPT']
);
const argonPool = first.quotas.pools.find((pool) => pool.poolKey === 'Argon');
assert.equal(argonPool.weeklyRemainingPct, 66.2);
assert.equal(argonPool.weeklyUsedPct, 33.8);
// Switch account to Ultra immediately (within the 10-second local cache window)
h.state.userStatus = {
email: 'ultra-user@example.com',
userTier: { id: 'g1-ultra-lite-tier', name: 'Google AI Ultra' },
};
h.state.quotaSummary = {
groups: [
{
displayName: 'Gemini Models',
buckets: [
{ bucketId: 'gemini-weekly', window: 'weekly', remainingFraction: 0.087, resetTime: ultraReset },
{ bucketId: 'gemini-5h', window: '5h', remainingFraction: 0.99, resetTime: '2026-10-30T17:21:07Z' },
],
},
{
displayName: 'Claude and GPT models',
buckets: [
{ bucketId: '3p-weekly', window: 'weekly', remainingFraction: 1, resetTime: '2026-11-06T03:55:10Z' },
{ bucketId: '3p-5h', window: '5h', remainingFraction: 1, resetTime: '2026-10-30T17:21:07Z' },
],
},
],
};
const second = await h.buildTelemetryPayloadInternal('none');
assert.deepEqual(
Array.from(second.quotas.pools, (pool) => pool.poolKey),
['Gemini', 'Claude & GPT']
);
assert.equal(second.quotas.pools[0].weeklyRemainingPct, 8.7);
});