mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-27 01:19:25 +08:00
feat(panel): add account-isolated per-model quota burn-rate estimator and hover popover
This commit is contained in:
+359
-6
@@ -967,6 +967,11 @@ const SVG_ICON_DEFS = Object.freeze({
|
|||||||
{ tag: 'path', attrs: { d: 'M8 6.2v3.4' } },
|
{ tag: 'path', attrs: { d: 'M8 6.2v3.4' } },
|
||||||
{ tag: 'circle', attrs: { cx: '8', cy: '11.5', r: '0.6', fill: 'currentColor', stroke: 'none' } },
|
{ tag: 'circle', attrs: { cx: '8', cy: '11.5', r: '0.6', fill: 'currentColor', stroke: 'none' } },
|
||||||
],
|
],
|
||||||
|
'help-circle': [
|
||||||
|
{ tag: 'circle', attrs: { cx: '8', cy: '8', r: '6' } },
|
||||||
|
{ tag: 'path', attrs: { d: 'M6.2 6.3a1.9 1.9 0 0 1 3.6.7c0 1.15-1.8 1.35-1.8 2.5' } },
|
||||||
|
{ tag: 'circle', attrs: { cx: '8', cy: '11.8', r: '0.65', fill: 'currentColor', stroke: 'none' } },
|
||||||
|
],
|
||||||
'chevron-down': [
|
'chevron-down': [
|
||||||
{ tag: 'path', attrs: { d: 'M4 6.2l4 4 4-4' } },
|
{ tag: 'path', attrs: { d: 'M4 6.2l4 4 4-4' } },
|
||||||
],
|
],
|
||||||
@@ -1451,6 +1456,17 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({
|
|||||||
'quota.footCallsCycle': '周期调用: {calls} 次',
|
'quota.footCallsCycle': '周期调用: {calls} 次',
|
||||||
'quota.footTipCustom': '按本机自然周(周一 00:00 起)统计',
|
'quota.footTipCustom': '按本机自然周(周一 00:00 起)统计',
|
||||||
'quota.footTipCycle': '按各配额池独立周限重置周期分别统计并汇总',
|
'quota.footTipCycle': '按各配额池独立周限重置周期分别统计并汇总',
|
||||||
|
'quota.rateHelpAria': '查看当前账号实测倍率预估',
|
||||||
|
'quota.ratePopTitle': '实测倍率预估',
|
||||||
|
'quota.ratePopAccountScope': '{account}',
|
||||||
|
'quota.ratePopAccountCurrent': '当前账号',
|
||||||
|
'quota.ratePopPoolFallback': '池综合均值',
|
||||||
|
'quota.ratePopEq5hLabel': '5h 满池',
|
||||||
|
'quota.ratePopEqWkLabel': '周限满池',
|
||||||
|
'quota.ratePopPerUsd': '{win} {rate}%/$',
|
||||||
|
'quota.ratePopSamples': '{n} 样本',
|
||||||
|
'quota.ratePopEmpty': '暂未采集到足够的单模型干净样本(每模型需至少 3 次无抖动扣费),正常使用后自动生成。',
|
||||||
|
'quota.ratePopNote': '按单模型纯净步实测折算,同池最省为 1x,按账号隔离。',
|
||||||
|
|
||||||
// Live Activity Widget
|
// Live Activity Widget
|
||||||
'live.currentSession': '当前会话',
|
'live.currentSession': '当前会话',
|
||||||
@@ -2347,6 +2363,17 @@ const I18N_MESSAGES_EN_US = Object.freeze({
|
|||||||
'quota.footCallsCycle': 'Cycle Calls: {calls}',
|
'quota.footCallsCycle': 'Cycle Calls: {calls}',
|
||||||
'quota.footTipCustom': 'Counted since Monday 00:00 local time',
|
'quota.footTipCustom': 'Counted since Monday 00:00 local time',
|
||||||
'quota.footTipCycle': 'Summed across each quota pool weekly reset window',
|
'quota.footTipCycle': 'Summed across each quota pool weekly reset window',
|
||||||
|
'quota.rateHelpAria': 'View empirical burn-rate estimates for this account',
|
||||||
|
'quota.ratePopTitle': 'Estimated Burn Rates',
|
||||||
|
'quota.ratePopAccountScope': '{account}',
|
||||||
|
'quota.ratePopAccountCurrent': 'Current account',
|
||||||
|
'quota.ratePopPoolFallback': 'Pool average',
|
||||||
|
'quota.ratePopEq5hLabel': '5h full',
|
||||||
|
'quota.ratePopEqWkLabel': 'Weekly full',
|
||||||
|
'quota.ratePopPerUsd': '{win} {rate}%/$',
|
||||||
|
'quota.ratePopSamples': '{n} samples',
|
||||||
|
'quota.ratePopEmpty': 'Not enough clean single-model samples yet (at least 3 clean steps per model). Estimates appear automatically during use.',
|
||||||
|
'quota.ratePopNote': 'Measured from clean single-model steps; lowest burn in pool = 1x. Account isolated.',
|
||||||
|
|
||||||
// Live Activity Widget
|
// Live Activity Widget
|
||||||
'live.currentSession': 'Current Session',
|
'live.currentSession': 'Current Session',
|
||||||
@@ -9915,7 +9942,9 @@ function isEquivalentTelemetry(prev, next) {
|
|||||||
pPools[i]?.cycle5h?.calls !== nPools[i]?.cycle5h?.calls ||
|
pPools[i]?.cycle5h?.calls !== nPools[i]?.cycle5h?.calls ||
|
||||||
pPools[i]?.cycleWeekly?.tokens !== nPools[i]?.cycleWeekly?.tokens ||
|
pPools[i]?.cycleWeekly?.tokens !== nPools[i]?.cycleWeekly?.tokens ||
|
||||||
pPools[i]?.cycleWeekly?.costUsd !== nPools[i]?.cycleWeekly?.costUsd ||
|
pPools[i]?.cycleWeekly?.costUsd !== nPools[i]?.cycleWeekly?.costUsd ||
|
||||||
pPools[i]?.cycleWeekly?.calls !== nPools[i]?.cycleWeekly?.calls
|
pPools[i]?.cycleWeekly?.calls !== nPools[i]?.cycleWeekly?.calls ||
|
||||||
|
JSON.stringify(pPools[i]?.rateEstimate || null) !==
|
||||||
|
JSON.stringify(nPools[i]?.rateEstimate || null)
|
||||||
) {
|
) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -18657,7 +18686,7 @@ return { CTX_CHANNEL_DEFS, ContextWindowWidget };
|
|||||||
})();
|
})();
|
||||||
|
|
||||||
// --- src/components/widgets/QuotaPoolsWidget.js ---
|
// --- src/components/widgets/QuotaPoolsWidget.js ---
|
||||||
const { buildQuotaPoolItems, createPoolQuotaRow, formatQuotaSummaryFooter, syncPoolQuotaRow, quotaPoolRowSig, formatAccountTierBadge, QuotaPoolsWidget } = (() => {
|
const { buildQuotaPoolItems, createPoolQuotaRow, formatQuotaSummaryFooter, syncPoolQuotaRow, quotaPoolRowSig, formatAccountTierBadge, maskAccountLabel, QuotaPoolsWidget } = (() => {
|
||||||
/**
|
/**
|
||||||
* @fileoverview Standalone decoupled Quota Pools Widget (`QuotaPoolsWidget.js`).
|
* @fileoverview Standalone decoupled Quota Pools Widget (`QuotaPoolsWidget.js`).
|
||||||
* Renders dynamic multi-pool quota bars (Gemini, Argon/Carbon, Claude & GPT)
|
* Renders dynamic multi-pool quota bars (Gemini, Argon/Carbon, Claude & GPT)
|
||||||
@@ -19057,12 +19086,331 @@ function formatAccountTierBadge(account) {
|
|||||||
return `${tierName} · ${rawPlan}`;
|
return `${tierName} · ${rawPlan}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 对账号邮箱或名称做轻量隐私脱敏(如 `sjee80343@gmail.com` -> `sj***43@gmail.com`),
|
||||||
|
* 兼顾多账号辨识度及截图分享隐私安全。
|
||||||
|
*
|
||||||
|
* @param {string|null|undefined} raw
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
function maskAccountLabel(raw) {
|
||||||
|
const str = String(raw || '').trim();
|
||||||
|
if (!str) return '';
|
||||||
|
const atIdx = str.indexOf('@');
|
||||||
|
if (atIdx > 0 && atIdx < str.length - 1) {
|
||||||
|
const local = str.slice(0, atIdx);
|
||||||
|
const domain = str.slice(atIdx);
|
||||||
|
const chars = Array.from(local);
|
||||||
|
if (chars.length <= 1) return `*${domain}`;
|
||||||
|
if (chars.length === 2) return `${chars[0]}*${domain}`;
|
||||||
|
if (chars.length <= 4) return `${chars[0]}***${chars[chars.length - 1]}${domain}`;
|
||||||
|
return `${chars.slice(0, 2).join('')}***${chars.slice(-2).join('')}${domain}`;
|
||||||
|
}
|
||||||
|
const chars = Array.from(str);
|
||||||
|
if (chars.length <= 1) return '*';
|
||||||
|
if (chars.length === 2) return `${chars[0]}*`;
|
||||||
|
if (chars.length <= 4) return `${chars[0]}***${chars[chars.length - 1]}`;
|
||||||
|
return `${chars.slice(0, 2).join('')}***${chars[chars.length - 1]}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatRateEqUsd(val) {
|
||||||
|
const num = Number(val);
|
||||||
|
if (!Number.isFinite(num) || num <= 0) return '--';
|
||||||
|
if (num >= 10) return `$${Math.round(num)}`;
|
||||||
|
return `$${Number(num.toFixed(1))}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatRatePerUsdValue(rate) {
|
||||||
|
const num = Number(rate);
|
||||||
|
if (!Number.isFinite(num) || num <= 0) return '--';
|
||||||
|
return String(Number(num.toFixed(2)));
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatRateMultiplier(mult) {
|
||||||
|
const num = Number(mult);
|
||||||
|
if (!Number.isFinite(num) || num <= 0) return '';
|
||||||
|
return `${Number(num.toFixed(1))}x`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function createRateModelCard({
|
||||||
|
name,
|
||||||
|
isMutedName = false,
|
||||||
|
isFallback = false,
|
||||||
|
multiplier = null,
|
||||||
|
rate5hPctPerUsd = null,
|
||||||
|
rateWeeklyPctPerUsd = null,
|
||||||
|
eqFull5hUsd = null,
|
||||||
|
eqFullWeeklyUsd = null,
|
||||||
|
samples = 0,
|
||||||
|
}) {
|
||||||
|
const leftNodes = [
|
||||||
|
h('span', {
|
||||||
|
className: `quota-rate-model-name${isMutedName ? ' is-muted' : ''}`,
|
||||||
|
text: name,
|
||||||
|
}),
|
||||||
|
];
|
||||||
|
const multText = formatRateMultiplier(multiplier);
|
||||||
|
if (multText) {
|
||||||
|
leftNodes.push(
|
||||||
|
h('span', {
|
||||||
|
className: `quota-rate-mult-badge${Number(multiplier) >= 1.5 ? ' is-high' : ''}`,
|
||||||
|
text: multText,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const has5hRate = rate5hPctPerUsd != null;
|
||||||
|
const primaryRate = has5hRate ? rate5hPctPerUsd : rateWeeklyPctPerUsd;
|
||||||
|
const subParts = [];
|
||||||
|
if (primaryRate != null) {
|
||||||
|
subParts.push(
|
||||||
|
t('quota.ratePopPerUsd', {
|
||||||
|
win: has5hRate ? '5h' : t('quota.weeklyShort'),
|
||||||
|
rate: formatRatePerUsdValue(primaryRate),
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (Number(samples) > 0) {
|
||||||
|
subParts.push(t('quota.ratePopSamples', { n: Number(samples) }));
|
||||||
|
}
|
||||||
|
|
||||||
|
const eqCells = [];
|
||||||
|
if (eqFull5hUsd != null) {
|
||||||
|
eqCells.push(
|
||||||
|
h('div', { className: 'quota-rate-eq-cell' }, [
|
||||||
|
h('span', { className: 'quota-rate-eq-k', text: t('quota.ratePopEq5hLabel') }),
|
||||||
|
h('span', {
|
||||||
|
className: 'quota-rate-eq-v text-mono',
|
||||||
|
text: `≈ ${formatRateEqUsd(eqFull5hUsd)}`,
|
||||||
|
}),
|
||||||
|
])
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (eqFullWeeklyUsd != null) {
|
||||||
|
eqCells.push(
|
||||||
|
h('div', { className: 'quota-rate-eq-cell' }, [
|
||||||
|
h('span', { className: 'quota-rate-eq-k', text: t('quota.ratePopEqWkLabel') }),
|
||||||
|
h('span', {
|
||||||
|
className: 'quota-rate-eq-v text-mono',
|
||||||
|
text: `≈ ${formatRateEqUsd(eqFullWeeklyUsd)}`,
|
||||||
|
}),
|
||||||
|
])
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const cardChildren = [
|
||||||
|
h('div', { className: 'quota-rate-row-top' }, [
|
||||||
|
h('div', { className: 'quota-rate-model-left' }, leftNodes),
|
||||||
|
...(subParts.length > 0
|
||||||
|
? [h('span', { className: 'quota-rate-meta text-mono', text: subParts.join(' · ') })]
|
||||||
|
: []),
|
||||||
|
]),
|
||||||
|
];
|
||||||
|
if (eqCells.length > 0) {
|
||||||
|
cardChildren.push(
|
||||||
|
h(
|
||||||
|
'div',
|
||||||
|
{ className: `quota-rate-eq-grid${eqCells.length === 1 ? ' is-single' : ''}` },
|
||||||
|
eqCells
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return h('div', { className: `quota-rate-model-row${isFallback ? ' is-fallback' : ''}` }, cardChildren);
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildRatePopoverSig(data) {
|
||||||
|
const locale = getEffectiveLocale();
|
||||||
|
const acct = String(data?.account?.email || data?.account?.name || '').trim();
|
||||||
|
const pools = Array.isArray(data?.quotas?.pools) ? data.quotas.pools : [];
|
||||||
|
const poolSig = pools
|
||||||
|
.map((p) => `${p.poolKey || ''}:${p.poolLabel || ''}:${JSON.stringify(p.rateEstimate || null)}`)
|
||||||
|
.join('|');
|
||||||
|
return `${locale}|${acct}|${poolSig}`;
|
||||||
|
}
|
||||||
|
|
||||||
const QuotaPoolsWidget = defineComponent({
|
const QuotaPoolsWidget = defineComponent({
|
||||||
name: 'QuotaPoolsWidget',
|
name: 'QuotaPoolsWidget',
|
||||||
setup({ props }) {
|
setup({ props, onCleanup }) {
|
||||||
const compactHover = Boolean(props.compactHover);
|
const compactHover = Boolean(props.compactHover);
|
||||||
const titleTextEl = h('span', { text: t('module.quotas') });
|
const titleTextEl = h('span', { text: t('module.quotas') });
|
||||||
const tierBadge = h('span', { className: 'panel-meta', text: 'Google AI · Pro' });
|
const tierBadge = h('span', { className: 'panel-meta', text: 'Google AI · Pro' });
|
||||||
|
|
||||||
|
const ratePopTitleEl = h('span', {
|
||||||
|
className: 'quota-rate-pop-title',
|
||||||
|
text: t('quota.ratePopTitle'),
|
||||||
|
});
|
||||||
|
const ratePopAccountEl = h('span', {
|
||||||
|
className: 'quota-rate-pop-account',
|
||||||
|
text: t('quota.ratePopAccountCurrent'),
|
||||||
|
});
|
||||||
|
const ratePopBodyEl = h('div', { className: 'quota-rate-pop-body' });
|
||||||
|
const ratePopNoteEl = h('div', {
|
||||||
|
className: 'quota-rate-pop-note',
|
||||||
|
text: t('quota.ratePopNote'),
|
||||||
|
});
|
||||||
|
const ratePopoverEl = h(
|
||||||
|
'div',
|
||||||
|
{
|
||||||
|
className: 'quota-rate-popover',
|
||||||
|
role: 'tooltip',
|
||||||
|
hidden: true,
|
||||||
|
},
|
||||||
|
[
|
||||||
|
h('div', { className: 'quota-rate-pop-head' }, [ratePopTitleEl, ratePopAccountEl]),
|
||||||
|
ratePopBodyEl,
|
||||||
|
ratePopNoteEl,
|
||||||
|
]
|
||||||
|
);
|
||||||
|
ratePopoverEl.hidden = true;
|
||||||
|
|
||||||
|
let ratePopOpen = false;
|
||||||
|
let ratePopCloseTimer = null;
|
||||||
|
let lastRatePopSig = '';
|
||||||
|
|
||||||
|
const cancelRatePopClose = () => {
|
||||||
|
if (ratePopCloseTimer) {
|
||||||
|
clearTimeout(ratePopCloseTimer);
|
||||||
|
ratePopCloseTimer = null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const setRatePopOpen = (open) => {
|
||||||
|
const next = Boolean(open);
|
||||||
|
ratePopOpen = next;
|
||||||
|
ratePopoverEl.hidden = !next;
|
||||||
|
patchAttr(ratePopoverEl, 'hidden', !next);
|
||||||
|
patchAttr(rateHelpBtn, 'aria-expanded', next ? 'true' : 'false');
|
||||||
|
patchClasses(rateHelpBtn, { 'is-open': next });
|
||||||
|
};
|
||||||
|
|
||||||
|
const openRatePop = () => {
|
||||||
|
cancelRatePopClose();
|
||||||
|
if (!ratePopOpen) setRatePopOpen(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
const scheduleRatePopClose = () => {
|
||||||
|
cancelRatePopClose();
|
||||||
|
ratePopCloseTimer = setTimeout(() => {
|
||||||
|
ratePopCloseTimer = null;
|
||||||
|
setRatePopOpen(false);
|
||||||
|
}, 130);
|
||||||
|
};
|
||||||
|
|
||||||
|
const rateHelpBtn = h(
|
||||||
|
'button',
|
||||||
|
{
|
||||||
|
type: 'button',
|
||||||
|
className: 'quota-rate-help-btn',
|
||||||
|
'aria-label': t('quota.rateHelpAria'),
|
||||||
|
'aria-haspopup': 'true',
|
||||||
|
'aria-expanded': 'false',
|
||||||
|
onMouseenter: openRatePop,
|
||||||
|
onMouseleave: scheduleRatePopClose,
|
||||||
|
onFocus: openRatePop,
|
||||||
|
onBlur: scheduleRatePopClose,
|
||||||
|
onClick: (ev) => {
|
||||||
|
ev?.stopPropagation?.();
|
||||||
|
cancelRatePopClose();
|
||||||
|
setRatePopOpen(!ratePopOpen);
|
||||||
|
},
|
||||||
|
onKeydown: (ev) => {
|
||||||
|
if (ev?.key === 'Escape' && ratePopOpen) {
|
||||||
|
ev.stopPropagation?.();
|
||||||
|
cancelRatePopClose();
|
||||||
|
setRatePopOpen(false);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
[createSvgIcon('help-circle', { size: 13 })]
|
||||||
|
);
|
||||||
|
|
||||||
|
ratePopoverEl.addEventListener?.('mouseenter', openRatePop);
|
||||||
|
ratePopoverEl.addEventListener?.('mouseleave', scheduleRatePopClose);
|
||||||
|
onCleanup?.(() => {
|
||||||
|
cancelRatePopClose();
|
||||||
|
});
|
||||||
|
|
||||||
|
function syncRatePopoverContent(data) {
|
||||||
|
const sig = buildRatePopoverSig(data);
|
||||||
|
if (sig === lastRatePopSig) return;
|
||||||
|
lastRatePopSig = sig;
|
||||||
|
|
||||||
|
patchText(ratePopTitleEl, t('quota.ratePopTitle'));
|
||||||
|
patchText(ratePopNoteEl, t('quota.ratePopNote'));
|
||||||
|
patchAttr(rateHelpBtn, 'aria-label', t('quota.rateHelpAria'));
|
||||||
|
|
||||||
|
const acctMasked = maskAccountLabel(data?.account?.email || data?.account?.name || '');
|
||||||
|
patchText(
|
||||||
|
ratePopAccountEl,
|
||||||
|
acctMasked
|
||||||
|
? t('quota.ratePopAccountScope', { account: acctMasked })
|
||||||
|
: t('quota.ratePopAccountCurrent')
|
||||||
|
);
|
||||||
|
patchAttr(ratePopAccountEl, 'title', acctMasked || null);
|
||||||
|
|
||||||
|
while (ratePopBodyEl.firstChild) {
|
||||||
|
ratePopBodyEl.removeChild(ratePopBodyEl.firstChild);
|
||||||
|
}
|
||||||
|
|
||||||
|
const rawPools = Array.isArray(data?.quotas?.pools) ? data.quotas.pools : [];
|
||||||
|
const populatedGroups = [];
|
||||||
|
|
||||||
|
for (const p of rawPools) {
|
||||||
|
const est = p?.rateEstimate;
|
||||||
|
if (!est || typeof est !== 'object') continue;
|
||||||
|
const models = Array.isArray(est.models) ? est.models : [];
|
||||||
|
const hasPoolFallback =
|
||||||
|
models.length === 0 &&
|
||||||
|
(Number.isFinite(est.rate5hPctPerUsd) || Number.isFinite(est.rateWeeklyPctPerUsd));
|
||||||
|
if (models.length === 0 && !hasPoolFallback) continue;
|
||||||
|
|
||||||
|
const poolLabel = p.poolLabel || p.family || p.poolKey || 'Pool';
|
||||||
|
const rows =
|
||||||
|
models.length > 0
|
||||||
|
? models.map((item) =>
|
||||||
|
createRateModelCard({
|
||||||
|
name: item.model,
|
||||||
|
multiplier: item.multiplier,
|
||||||
|
rate5hPctPerUsd: item.rate5hPctPerUsd,
|
||||||
|
rateWeeklyPctPerUsd: item.rateWeeklyPctPerUsd,
|
||||||
|
eqFull5hUsd: item.eqFull5hUsd,
|
||||||
|
eqFullWeeklyUsd: item.eqFullWeeklyUsd,
|
||||||
|
samples: item.samples,
|
||||||
|
})
|
||||||
|
)
|
||||||
|
: [
|
||||||
|
createRateModelCard({
|
||||||
|
name: t('quota.ratePopPoolFallback'),
|
||||||
|
isMutedName: true,
|
||||||
|
isFallback: true,
|
||||||
|
rate5hPctPerUsd: est.rate5hPctPerUsd,
|
||||||
|
rateWeeklyPctPerUsd: est.rateWeeklyPctPerUsd,
|
||||||
|
eqFull5hUsd: est.eqFull5hUsd,
|
||||||
|
eqFullWeeklyUsd: est.eqFullWeeklyUsd,
|
||||||
|
samples: Math.max(Number(est.samples5h) || 0, Number(est.samplesWeekly) || 0),
|
||||||
|
}),
|
||||||
|
];
|
||||||
|
|
||||||
|
populatedGroups.push(
|
||||||
|
h('div', { className: 'quota-rate-pool-group' }, [
|
||||||
|
h('div', { className: 'quota-rate-pool-label', text: poolLabel }),
|
||||||
|
h('div', { className: 'quota-rate-model-list' }, rows),
|
||||||
|
])
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (populatedGroups.length === 0) {
|
||||||
|
ratePopBodyEl.appendChild(
|
||||||
|
h('div', { className: 'quota-rate-pop-empty', text: t('quota.ratePopEmpty') })
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
for (const grp of populatedGroups) {
|
||||||
|
ratePopBodyEl.appendChild(grp);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const poolsListEl = h(
|
const poolsListEl = h(
|
||||||
'div',
|
'div',
|
||||||
compactHover
|
compactHover
|
||||||
@@ -19096,22 +19444,27 @@ const QuotaPoolsWidget = defineComponent({
|
|||||||
]
|
]
|
||||||
);
|
);
|
||||||
|
|
||||||
const quotaPanel = h('section', { className: 'panel' }, [
|
const quotaPanel = h('section', { className: 'panel quota-panel' }, [
|
||||||
h('div', { className: 'panel-header' }, [
|
h('div', { className: 'panel-header' }, [
|
||||||
h('span', { className: 'panel-title' }, [
|
h('span', { className: 'panel-title' }, [
|
||||||
createSvgIcon('pulse', { size: 13 }),
|
createSvgIcon('pulse', { size: 13 }),
|
||||||
titleTextEl,
|
titleTextEl,
|
||||||
|
rateHelpBtn,
|
||||||
]),
|
]),
|
||||||
tierBadge,
|
tierBadge,
|
||||||
]),
|
]),
|
||||||
poolsListEl,
|
poolsListEl,
|
||||||
reserveLegendEl,
|
reserveLegendEl,
|
||||||
|
ratePopoverEl,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
syncRatePopoverContent(null);
|
||||||
|
|
||||||
function update({ data, minuteTick } = {}) {
|
function update({ data, minuteTick } = {}) {
|
||||||
patchText(titleTextEl, t('module.quotas'));
|
patchText(titleTextEl, t('module.quotas'));
|
||||||
patchText(legendActualTextEl, t('quota.legendActual'));
|
patchText(legendActualTextEl, t('quota.legendActual'));
|
||||||
patchText(legendReservedTextEl, t('quota.legendReserved'));
|
patchText(legendReservedTextEl, t('quota.legendReserved'));
|
||||||
|
syncRatePopoverContent(data);
|
||||||
if (!data) {
|
if (!data) {
|
||||||
reserveLegendEl.hidden = true;
|
reserveLegendEl.hidden = true;
|
||||||
if (compactHover) {
|
if (compactHover) {
|
||||||
@@ -19140,11 +19493,11 @@ const QuotaPoolsWidget = defineComponent({
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
el: quotaPanel,
|
el: quotaPanel,
|
||||||
refs: { update, poolsListEl },
|
refs: { update, poolsListEl, rateHelpBtn, ratePopoverEl },
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
return { buildQuotaPoolItems, createPoolQuotaRow, formatQuotaSummaryFooter, syncPoolQuotaRow, quotaPoolRowSig, formatAccountTierBadge, QuotaPoolsWidget };
|
return { buildQuotaPoolItems, createPoolQuotaRow, formatQuotaSummaryFooter, syncPoolQuotaRow, quotaPoolRowSig, formatAccountTierBadge, maskAccountLabel, QuotaPoolsWidget };
|
||||||
})();
|
})();
|
||||||
|
|
||||||
// --- src/components/widgets/LiveActivityWidget.js ---
|
// --- src/components/widgets/LiveActivityWidget.js ---
|
||||||
|
|||||||
@@ -39,6 +39,9 @@ export const QR_RATE_OUTLIER_MAX_RATIO = 2.0;
|
|||||||
export const QR_RATE_DRIFT_STREAK = 5;
|
export const QR_RATE_DRIFT_STREAK = 5;
|
||||||
export const QR_CONSUME_MIN_SHORTFALL_PCT = 0.03;
|
export const QR_CONSUME_MIN_SHORTFALL_PCT = 0.03;
|
||||||
export const QR_CONSUME_SHORTFALL_RATIO = 0.35;
|
export const QR_CONSUME_SHORTFALL_RATIO = 0.35;
|
||||||
|
export const QR_MODEL_RATE_MIN_UI_SAMPLES = 3;
|
||||||
|
export const QR_MODEL_SINGLE_DOMINANCE_RATIO = 0.95;
|
||||||
|
const QR_MAX_MODELS_PER_BUCKET = 16;
|
||||||
const QR_MAX_TRACKED_BUCKETS = 128;
|
const QR_MAX_TRACKED_BUCKETS = 128;
|
||||||
const QR_MAX_ACTIVE_LEASES = 16;
|
const QR_MAX_ACTIVE_LEASES = 16;
|
||||||
const QR_MAX_EVENT_LOG = 500;
|
const QR_MAX_EVENT_LOG = 500;
|
||||||
@@ -250,6 +253,193 @@ function qrSanitizePersistedPendingDrop(raw) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function qrSanitizeModelCosts(raw) {
|
||||||
|
const out = {};
|
||||||
|
if (!raw || typeof raw !== 'object') return out;
|
||||||
|
for (const [k, v] of Object.entries(raw)) {
|
||||||
|
const cleanKey = String(k || '').trim();
|
||||||
|
const num = Number(v);
|
||||||
|
if (cleanKey && Number.isFinite(num) && num > 0) {
|
||||||
|
out[cleanKey] = num;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function qrSanitizePersistedModelRates(raw, { preserveRate = true } = {}) {
|
||||||
|
const out = {};
|
||||||
|
if (!preserveRate || !raw || typeof raw !== 'object') return out;
|
||||||
|
const entries = Object.entries(raw).slice(-QR_MAX_MODELS_PER_BUCKET);
|
||||||
|
for (const [k, item] of entries) {
|
||||||
|
const cleanKey = String(k || '').trim();
|
||||||
|
if (!cleanKey || !item || typeof item !== 'object') continue;
|
||||||
|
const rateWindow = Array.isArray(item.rateWindow)
|
||||||
|
? item.rateWindow
|
||||||
|
.map((v) => qrClampRate(Number(v)))
|
||||||
|
.filter((v) => v !== null)
|
||||||
|
.slice(-QR_RATE_WINDOW_SIZE)
|
||||||
|
: [];
|
||||||
|
const rate =
|
||||||
|
rateWindow.length > 0
|
||||||
|
? qrClampRate(qrComputeMedian(rateWindow))
|
||||||
|
: item.ratePctPerUsd !== undefined && item.ratePctPerUsd !== null
|
||||||
|
? qrClampRate(Number(item.ratePctPerUsd))
|
||||||
|
: null;
|
||||||
|
if (rate === null) continue;
|
||||||
|
out[cleanKey] = {
|
||||||
|
ratePctPerUsd: rate,
|
||||||
|
rateSamples: Math.max(rateWindow.length, Math.floor(Number(item.rateSamples) || 0)),
|
||||||
|
rateWindow,
|
||||||
|
rateOutlierSide: 0,
|
||||||
|
rateOutlierBuf: [],
|
||||||
|
lastSeenMs: Math.max(0, Number(item.lastSeenMs) || 0),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function qrGetOrCreateModelRate(st, modelKey, nowMs) {
|
||||||
|
const map = st.modelRates && typeof st.modelRates === 'object' ? st.modelRates : (st.modelRates = {});
|
||||||
|
if (map[modelKey]) return map[modelKey];
|
||||||
|
const keys = Object.keys(map);
|
||||||
|
if (keys.length >= QR_MAX_MODELS_PER_BUCKET) {
|
||||||
|
let oldestKey = keys[0];
|
||||||
|
let oldestMs = Number(map[oldestKey]?.lastSeenMs || 0);
|
||||||
|
for (let i = 1; i < keys.length; i += 1) {
|
||||||
|
const candidateMs = Number(map[keys[i]]?.lastSeenMs || 0);
|
||||||
|
if (candidateMs < oldestMs) {
|
||||||
|
oldestMs = candidateMs;
|
||||||
|
oldestKey = keys[i];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (oldestKey) delete map[oldestKey];
|
||||||
|
}
|
||||||
|
const entry = {
|
||||||
|
ratePctPerUsd: null,
|
||||||
|
rateSamples: 0,
|
||||||
|
rateWindow: [],
|
||||||
|
rateOutlierSide: 0,
|
||||||
|
rateOutlierBuf: [],
|
||||||
|
lastSeenMs: nowMs,
|
||||||
|
};
|
||||||
|
map[modelKey] = entry;
|
||||||
|
return entry;
|
||||||
|
}
|
||||||
|
|
||||||
|
function qrEstimateModelWeightedPct(st, deltaModelCosts, totalDeltaCostUsd, fallbackRate) {
|
||||||
|
if (fallbackRate === null || !Number.isFinite(fallbackRate) || totalDeltaCostUsd <= 0) return 0;
|
||||||
|
const modelRates = st.modelRates && typeof st.modelRates === 'object' ? st.modelRates : null;
|
||||||
|
if (!modelRates || !deltaModelCosts || typeof deltaModelCosts !== 'object') {
|
||||||
|
return totalDeltaCostUsd * fallbackRate;
|
||||||
|
}
|
||||||
|
let attributedCost = 0;
|
||||||
|
let weightedPct = 0;
|
||||||
|
let usedPerModel = false;
|
||||||
|
for (const [mKey, costDelta] of Object.entries(deltaModelCosts)) {
|
||||||
|
if (!Number.isFinite(costDelta) || costDelta <= 0) continue;
|
||||||
|
attributedCost += costDelta;
|
||||||
|
const mr = modelRates[mKey];
|
||||||
|
if (mr && mr.rateSamples >= 2 && Number.isFinite(mr.ratePctPerUsd) && mr.ratePctPerUsd > 0) {
|
||||||
|
weightedPct += costDelta * mr.ratePctPerUsd;
|
||||||
|
usedPerModel = true;
|
||||||
|
} else {
|
||||||
|
weightedPct += costDelta * fallbackRate;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!usedPerModel || attributedCost <= 0) {
|
||||||
|
return totalDeltaCostUsd * fallbackRate;
|
||||||
|
}
|
||||||
|
const unattributedCost = Math.max(0, totalDeltaCostUsd - attributedCost);
|
||||||
|
return weightedPct + unattributedCost * fallbackRate;
|
||||||
|
}
|
||||||
|
|
||||||
|
function qrBuildPoolRateEstimate(st5h, stWk) {
|
||||||
|
const raw5hPool =
|
||||||
|
st5h && st5h.rateSamples >= QR_MODEL_RATE_MIN_UI_SAMPLES && Number.isFinite(st5h.ratePctPerUsd)
|
||||||
|
? st5h.ratePctPerUsd
|
||||||
|
: null;
|
||||||
|
const rawWkPool =
|
||||||
|
stWk && stWk.rateSamples >= QR_MODEL_RATE_MIN_UI_SAMPLES && Number.isFinite(stWk.ratePctPerUsd)
|
||||||
|
? stWk.ratePctPerUsd
|
||||||
|
: null;
|
||||||
|
const rate5hPool = raw5hPool !== null ? +raw5hPool.toFixed(4) : null;
|
||||||
|
const rateWkPool = rawWkPool !== null ? +rawWkPool.toFixed(4) : null;
|
||||||
|
|
||||||
|
const modelKeys = new Set([
|
||||||
|
...Object.keys(st5h?.modelRates || {}),
|
||||||
|
...Object.keys(stWk?.modelRates || {}),
|
||||||
|
]);
|
||||||
|
const models = [];
|
||||||
|
for (const model of modelKeys) {
|
||||||
|
const m5 = st5h?.modelRates?.[model] || null;
|
||||||
|
const mw = stWk?.modelRates?.[model] || null;
|
||||||
|
const rawR5 =
|
||||||
|
m5 && m5.rateSamples >= QR_MODEL_RATE_MIN_UI_SAMPLES && Number.isFinite(m5.ratePctPerUsd)
|
||||||
|
? m5.ratePctPerUsd
|
||||||
|
: null;
|
||||||
|
const rawRw =
|
||||||
|
mw && mw.rateSamples >= QR_MODEL_RATE_MIN_UI_SAMPLES && Number.isFinite(mw.ratePctPerUsd)
|
||||||
|
? mw.ratePctPerUsd
|
||||||
|
: null;
|
||||||
|
if (rawR5 === null && rawRw === null) continue;
|
||||||
|
models.push({
|
||||||
|
model,
|
||||||
|
rate5hPctPerUsd: rawR5 !== null ? +rawR5.toFixed(4) : null,
|
||||||
|
rateWeeklyPctPerUsd: rawRw !== null ? +rawRw.toFixed(4) : null,
|
||||||
|
eqFull5hUsd: rawR5 ? +(100 / rawR5).toFixed(1) : null,
|
||||||
|
eqFullWeeklyUsd: rawRw ? +(100 / rawRw).toFixed(1) : null,
|
||||||
|
multiplier: null,
|
||||||
|
samples: Math.max(m5?.rateSamples || 0, mw?.rateSamples || 0),
|
||||||
|
_rawR5: rawR5,
|
||||||
|
_rawRw: rawRw,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (models.length >= 2) {
|
||||||
|
const allHave5h = models.every((m) => m._rawR5 !== null);
|
||||||
|
const allHaveWk = models.every((m) => m._rawRw !== null);
|
||||||
|
const basisList = allHave5h
|
||||||
|
? models.map((m) => m._rawR5)
|
||||||
|
: allHaveWk
|
||||||
|
? models.map((m) => m._rawRw)
|
||||||
|
: null;
|
||||||
|
if (basisList) {
|
||||||
|
const minBasis = Math.min(...basisList);
|
||||||
|
if (minBasis > 0) {
|
||||||
|
for (let i = 0; i < models.length; i += 1) {
|
||||||
|
models[i].multiplier = +(basisList[i] / minBasis).toFixed(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
models.sort(
|
||||||
|
(a, b) =>
|
||||||
|
(b.multiplier ?? 0) - (a.multiplier ?? 0) ||
|
||||||
|
(b._rawR5 ?? b._rawRw ?? 0) - (a._rawR5 ?? a._rawRw ?? 0) ||
|
||||||
|
b.samples - a.samples ||
|
||||||
|
a.model.localeCompare(b.model)
|
||||||
|
);
|
||||||
|
for (const m of models) {
|
||||||
|
delete m._rawR5;
|
||||||
|
delete m._rawRw;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (models.length === 0 && rate5hPool === null && rateWkPool === null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
rate5hPctPerUsd: rate5hPool,
|
||||||
|
rateWeeklyPctPerUsd: rateWkPool,
|
||||||
|
eqFull5hUsd: raw5hPool ? +(100 / raw5hPool).toFixed(1) : null,
|
||||||
|
eqFullWeeklyUsd: rawWkPool ? +(100 / rawWkPool).toFixed(1) : null,
|
||||||
|
samples5h: st5h?.rateSamples || 0,
|
||||||
|
samplesWeekly: stWk?.rateSamples || 0,
|
||||||
|
models,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
function qrSanitizePersistedBucket(raw, { preserveRate = true } = {}) {
|
function qrSanitizePersistedBucket(raw, { preserveRate = true } = {}) {
|
||||||
if (!raw || typeof raw !== 'object') return null;
|
if (!raw || typeof raw !== 'object') return null;
|
||||||
const lastOfficial =
|
const lastOfficial =
|
||||||
@@ -277,15 +467,18 @@ function qrSanitizePersistedBucket(raw, { preserveRate = true } = {}) {
|
|||||||
lastQuotaTs: Math.max(0, Number(raw.lastQuotaTs) || 0),
|
lastQuotaTs: Math.max(0, Number(raw.lastQuotaTs) || 0),
|
||||||
lastOfficialUsedPct: lastOfficial,
|
lastOfficialUsedPct: lastOfficial,
|
||||||
lastCycleCostUsd: Math.max(0, Number(raw.lastCycleCostUsd) || 0),
|
lastCycleCostUsd: Math.max(0, Number(raw.lastCycleCostUsd) || 0),
|
||||||
|
lastModelCostsUsd: qrSanitizeModelCosts(raw.lastModelCostsUsd),
|
||||||
lastUnpricedCalls: Math.max(0, Number(raw.lastUnpricedCalls) || 0),
|
lastUnpricedCalls: Math.max(0, Number(raw.lastUnpricedCalls) || 0),
|
||||||
pendingCostUsd: 0,
|
pendingCostUsd: 0,
|
||||||
pendingCostAtMs: 0,
|
pendingCostAtMs: 0,
|
||||||
pendingCostSinceMs: 0,
|
pendingCostSinceMs: 0,
|
||||||
|
pendingModelCostsUsd: {},
|
||||||
ratePctPerUsd: rate,
|
ratePctPerUsd: rate,
|
||||||
rateSamples: preserveRate ? Math.max(rateWindow.length, Math.floor(Number(raw.rateSamples) || 0)) : 0,
|
rateSamples: preserveRate ? Math.max(rateWindow.length, Math.floor(Number(raw.rateSamples) || 0)) : 0,
|
||||||
rateWindow,
|
rateWindow,
|
||||||
rateOutlierSide: 0,
|
rateOutlierSide: 0,
|
||||||
rateOutlierBuf: [],
|
rateOutlierBuf: [],
|
||||||
|
modelRates: qrSanitizePersistedModelRates(raw.modelRates, { preserveRate }),
|
||||||
activeLeases: qrSanitizePersistedLeases(raw.activeLeases),
|
activeLeases: qrSanitizePersistedLeases(raw.activeLeases),
|
||||||
pendingDrop: preserveRate ? qrSanitizePersistedPendingDrop(raw.pendingDrop) : null,
|
pendingDrop: preserveRate ? qrSanitizePersistedPendingDrop(raw.pendingDrop) : null,
|
||||||
lastBounceAtMs: Math.max(0, Number(raw.lastBounceAtMs) || 0),
|
lastBounceAtMs: Math.max(0, Number(raw.lastBounceAtMs) || 0),
|
||||||
@@ -336,15 +529,27 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu
|
|||||||
function serializeState(nowMs = Date.now()) {
|
function serializeState(nowMs = Date.now()) {
|
||||||
const serializedBuckets = {};
|
const serializedBuckets = {};
|
||||||
for (const [k, st] of buckets.entries()) {
|
for (const [k, st] of buckets.entries()) {
|
||||||
|
const serializedModelRates = {};
|
||||||
|
for (const [mKey, mr] of Object.entries(st.modelRates || {})) {
|
||||||
|
if (!mr || mr.ratePctPerUsd === null) continue;
|
||||||
|
serializedModelRates[mKey] = {
|
||||||
|
ratePctPerUsd: mr.ratePctPerUsd,
|
||||||
|
rateSamples: mr.rateSamples,
|
||||||
|
rateWindow: mr.rateWindow,
|
||||||
|
lastSeenMs: mr.lastSeenMs,
|
||||||
|
};
|
||||||
|
}
|
||||||
serializedBuckets[k] = {
|
serializedBuckets[k] = {
|
||||||
resetTimeMs: st.resetTimeMs,
|
resetTimeMs: st.resetTimeMs,
|
||||||
lastQuotaTs: st.lastQuotaTs,
|
lastQuotaTs: st.lastQuotaTs,
|
||||||
lastOfficialUsedPct: st.lastOfficialUsedPct,
|
lastOfficialUsedPct: st.lastOfficialUsedPct,
|
||||||
lastCycleCostUsd: st.lastCycleCostUsd,
|
lastCycleCostUsd: st.lastCycleCostUsd,
|
||||||
|
lastModelCostsUsd: st.lastModelCostsUsd || {},
|
||||||
lastUnpricedCalls: st.lastUnpricedCalls,
|
lastUnpricedCalls: st.lastUnpricedCalls,
|
||||||
ratePctPerUsd: st.ratePctPerUsd,
|
ratePctPerUsd: st.ratePctPerUsd,
|
||||||
rateSamples: st.rateSamples,
|
rateSamples: st.rateSamples,
|
||||||
rateWindow: st.rateWindow,
|
rateWindow: st.rateWindow,
|
||||||
|
modelRates: serializedModelRates,
|
||||||
activeLeases: st.activeLeases,
|
activeLeases: st.activeLeases,
|
||||||
pendingDrop: st.pendingDrop,
|
pendingDrop: st.pendingDrop,
|
||||||
lastBounceAtMs: st.lastBounceAtMs,
|
lastBounceAtMs: st.lastBounceAtMs,
|
||||||
@@ -411,15 +616,18 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu
|
|||||||
lastQuotaTs: 0,
|
lastQuotaTs: 0,
|
||||||
lastOfficialUsedPct: null,
|
lastOfficialUsedPct: null,
|
||||||
lastCycleCostUsd: 0,
|
lastCycleCostUsd: 0,
|
||||||
|
lastModelCostsUsd: {},
|
||||||
lastUnpricedCalls: 0,
|
lastUnpricedCalls: 0,
|
||||||
pendingCostUsd: 0,
|
pendingCostUsd: 0,
|
||||||
pendingCostAtMs: 0,
|
pendingCostAtMs: 0,
|
||||||
pendingCostSinceMs: 0,
|
pendingCostSinceMs: 0,
|
||||||
|
pendingModelCostsUsd: {},
|
||||||
ratePctPerUsd: null,
|
ratePctPerUsd: null,
|
||||||
rateSamples: 0,
|
rateSamples: 0,
|
||||||
rateWindow: [],
|
rateWindow: [],
|
||||||
rateOutlierSide: 0,
|
rateOutlierSide: 0,
|
||||||
rateOutlierBuf: [],
|
rateOutlierBuf: [],
|
||||||
|
modelRates: {},
|
||||||
activeLeases: [],
|
activeLeases: [],
|
||||||
pendingDrop: null,
|
pendingDrop: null,
|
||||||
lastBounceAtMs: 0,
|
lastBounceAtMs: 0,
|
||||||
@@ -438,6 +646,7 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu
|
|||||||
resetTimeMs = 0,
|
resetTimeMs = 0,
|
||||||
quotaFetchedAtMs = 0,
|
quotaFetchedAtMs = 0,
|
||||||
cycleCostUsd = 0,
|
cycleCostUsd = 0,
|
||||||
|
modelCostsUsd = null,
|
||||||
unpricedCalls = 0,
|
unpricedCalls = 0,
|
||||||
poolLastActivityMs = 0,
|
poolLastActivityMs = 0,
|
||||||
activeSessionCount10m = 0,
|
activeSessionCount10m = 0,
|
||||||
@@ -450,6 +659,7 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu
|
|||||||
ensureHydrated();
|
ensureHydrated();
|
||||||
const safeUsed = qrClamp(Number(officialUsedPct), 0, 100);
|
const safeUsed = qrClamp(Number(officialUsedPct), 0, 100);
|
||||||
const safeCost = Math.max(0, Number(cycleCostUsd) || 0);
|
const safeCost = Math.max(0, Number(cycleCostUsd) || 0);
|
||||||
|
const safeModelCosts = qrSanitizeModelCosts(modelCostsUsd);
|
||||||
const safeUnpriced = Math.max(0, Number(unpricedCalls) || 0);
|
const safeUnpriced = Math.max(0, Number(unpricedCalls) || 0);
|
||||||
const safeResetMs = Number(resetTimeMs) > 0 ? Number(resetTimeMs) : 0;
|
const safeResetMs = Number(resetTimeMs) > 0 ? Number(resetTimeMs) : 0;
|
||||||
const safeFetchTs = Number(quotaFetchedAtMs) > 0 ? Number(quotaFetchedAtMs) : nowMs;
|
const safeFetchTs = Number(quotaFetchedAtMs) > 0 ? Number(quotaFetchedAtMs) : nowMs;
|
||||||
@@ -483,7 +693,7 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
// 1. 周期重置检测:静默忽略 0% 空闲池的滑动重置时间漂移;真正跨周期时清空租约但保留单桶费率
|
// 1. 周期重置检测:静默忽略 0% 空闲池的滑动重置时间漂移;真正跨周期时清空租约但保留单桶及单模型费率
|
||||||
const resetShifted =
|
const resetShifted =
|
||||||
safeResetMs > 0 &&
|
safeResetMs > 0 &&
|
||||||
st.resetTimeMs > 0 &&
|
st.resetTimeMs > 0 &&
|
||||||
@@ -502,6 +712,7 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu
|
|||||||
st.lastQuotaTs = safeFetchTs;
|
st.lastQuotaTs = safeFetchTs;
|
||||||
st.lastOfficialUsedPct = safeUsed;
|
st.lastOfficialUsedPct = safeUsed;
|
||||||
st.lastCycleCostUsd = safeCost;
|
st.lastCycleCostUsd = safeCost;
|
||||||
|
st.lastModelCostsUsd = safeModelCosts;
|
||||||
st.lastUnpricedCalls = safeUnpriced;
|
st.lastUnpricedCalls = safeUnpriced;
|
||||||
if (isIdleZeroDrift) {
|
if (isIdleZeroDrift) {
|
||||||
return qrFormatOutput(st, safeUsed);
|
return qrFormatOutput(st, safeUsed);
|
||||||
@@ -509,6 +720,7 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu
|
|||||||
st.pendingCostUsd = 0;
|
st.pendingCostUsd = 0;
|
||||||
st.pendingCostAtMs = 0;
|
st.pendingCostAtMs = 0;
|
||||||
st.pendingCostSinceMs = 0;
|
st.pendingCostSinceMs = 0;
|
||||||
|
st.pendingModelCostsUsd = {};
|
||||||
st.activeLeases = [];
|
st.activeLeases = [];
|
||||||
st.pendingDrop = null;
|
st.pendingDrop = null;
|
||||||
const out = qrFormatOutput(st, safeUsed);
|
const out = qrFormatOutput(st, safeUsed);
|
||||||
@@ -522,6 +734,7 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu
|
|||||||
st.lastQuotaTs = safeFetchTs;
|
st.lastQuotaTs = safeFetchTs;
|
||||||
st.lastOfficialUsedPct = safeUsed;
|
st.lastOfficialUsedPct = safeUsed;
|
||||||
st.lastCycleCostUsd = safeCost;
|
st.lastCycleCostUsd = safeCost;
|
||||||
|
st.lastModelCostsUsd = safeModelCosts;
|
||||||
st.lastUnpricedCalls = safeUnpriced;
|
st.lastUnpricedCalls = safeUnpriced;
|
||||||
if (safeCost >= 0.5 && safeUsed >= 0.3) {
|
if (safeCost >= 0.5 && safeUsed >= 0.3) {
|
||||||
st.ratePctPerUsd = qrClampRate(safeUsed / safeCost);
|
st.ratePctPerUsd = qrClampRate(safeUsed / safeCost);
|
||||||
@@ -536,10 +749,16 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu
|
|||||||
st.resetTimeMs = safeResetMs;
|
st.resetTimeMs = safeResetMs;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. 同一份缓存配额响应:跳过重复差分,仅检查租约超时清理
|
// 3. 同一份缓存配额响应:跳过重复差分,仅补齐缺失的单模型基线并检查租约超时清理
|
||||||
const isFreshSample =
|
const isFreshSample =
|
||||||
safeFetchTs !== st.lastQuotaTs || Math.abs(safeUsed - st.lastOfficialUsedPct) > 1e-4;
|
safeFetchTs !== st.lastQuotaTs || Math.abs(safeUsed - st.lastOfficialUsedPct) > 1e-4;
|
||||||
if (!isFreshSample) {
|
if (!isFreshSample) {
|
||||||
|
if (
|
||||||
|
Object.keys(st.lastModelCostsUsd || {}).length === 0 &&
|
||||||
|
Object.keys(safeModelCosts).length > 0
|
||||||
|
) {
|
||||||
|
st.lastModelCostsUsd = safeModelCosts;
|
||||||
|
}
|
||||||
const beforeCachePrune = st.activeLeases.length;
|
const beforeCachePrune = st.activeLeases.length;
|
||||||
qrPruneExpiredLeases(st, nowMs);
|
qrPruneExpiredLeases(st, nowMs);
|
||||||
const out = qrFormatOutput(st, safeUsed);
|
const out = qrFormatOutput(st, safeUsed);
|
||||||
@@ -551,12 +770,55 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu
|
|||||||
|
|
||||||
const deltaOfficial = safeUsed - st.lastOfficialUsedPct;
|
const deltaOfficial = safeUsed - st.lastOfficialUsedPct;
|
||||||
const rawDeltaCost = Math.max(0, safeCost - st.lastCycleCostUsd);
|
const rawDeltaCost = Math.max(0, safeCost - st.lastCycleCostUsd);
|
||||||
|
const prevModelCosts = st.lastModelCostsUsd && typeof st.lastModelCostsUsd === 'object' ? st.lastModelCostsUsd : {};
|
||||||
|
const hasValidPrevModelBaseline =
|
||||||
|
st.lastCycleCostUsd <= 1e-6 || Object.keys(prevModelCosts).length > 0;
|
||||||
|
const rawDeltaModelCosts = {};
|
||||||
|
let totalModelDeltaUsd = 0;
|
||||||
|
let dominantModelKey = '';
|
||||||
|
let dominantModelDeltaUsd = 0;
|
||||||
|
if (hasValidPrevModelBaseline) {
|
||||||
|
for (const [mKey, curModelCost] of Object.entries(safeModelCosts)) {
|
||||||
|
const prevModelCost = Number(prevModelCosts[mKey]) || 0;
|
||||||
|
const dModel = curModelCost - prevModelCost;
|
||||||
|
if (dModel > 1e-6) {
|
||||||
|
rawDeltaModelCosts[mKey] = dModel;
|
||||||
|
totalModelDeltaUsd += dModel;
|
||||||
|
if (dModel > dominantModelDeltaUsd) {
|
||||||
|
dominantModelDeltaUsd = dModel;
|
||||||
|
dominantModelKey = mKey;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const modelDeltaMatchesTotal =
|
||||||
|
totalModelDeltaUsd > 0 && totalModelDeltaUsd <= rawDeltaCost * 1.15 + 0.01;
|
||||||
|
const isPureSingleModelStep = Boolean(
|
||||||
|
hasValidPrevModelBaseline &&
|
||||||
|
modelDeltaMatchesTotal &&
|
||||||
|
dominantModelKey &&
|
||||||
|
dominantModelDeltaUsd / totalModelDeltaUsd >= QR_MODEL_SINGLE_DOMINANCE_RATIO &&
|
||||||
|
dominantModelDeltaUsd >= 0.04
|
||||||
|
);
|
||||||
const deltaUnpriced = Math.max(0, safeUnpriced - st.lastUnpricedCalls);
|
const deltaUnpriced = Math.max(0, safeUnpriced - st.lastUnpricedCalls);
|
||||||
const pendingValid =
|
const pendingValid =
|
||||||
st.pendingCostUsd > 0 && nowMs - st.pendingCostAtMs <= QR_PENDING_COST_TTL_MS;
|
st.pendingCostUsd > 0 && nowMs - st.pendingCostAtMs <= QR_PENDING_COST_TTL_MS;
|
||||||
const effectiveDeltaCost = rawDeltaCost + (pendingValid ? st.pendingCostUsd : 0);
|
const effectiveDeltaCost = rawDeltaCost + (pendingValid ? st.pendingCostUsd : 0);
|
||||||
|
const effectiveDeltaModelCosts = { ...rawDeltaModelCosts };
|
||||||
|
if (pendingValid && st.pendingModelCostsUsd && typeof st.pendingModelCostsUsd === 'object') {
|
||||||
|
for (const [mKey, pCost] of Object.entries(st.pendingModelCostsUsd)) {
|
||||||
|
if (Number.isFinite(pCost) && pCost > 0) {
|
||||||
|
effectiveDeltaModelCosts[mKey] = (effectiveDeltaModelCosts[mKey] || 0) + pCost;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
const rate = qrResolveEffectiveRate(st, safeUsed, safeCost);
|
const rate = qrResolveEffectiveRate(st, safeUsed, safeCost);
|
||||||
let expectedDeltaPct = rate !== null ? effectiveDeltaCost * rate : 0;
|
let expectedDeltaPct = qrEstimateModelWeightedPct(
|
||||||
|
st,
|
||||||
|
effectiveDeltaModelCosts,
|
||||||
|
effectiveDeltaCost,
|
||||||
|
rate
|
||||||
|
);
|
||||||
let excessPct = deltaOfficial - expectedDeltaPct;
|
let excessPct = deltaOfficial - expectedDeltaPct;
|
||||||
const isIdleRefundReady =
|
const isIdleRefundReady =
|
||||||
poolLastActivityMs > 0 && nowMs - poolLastActivityMs >= QR_IDLE_CONFIRM_REFUND_MS;
|
poolLastActivityMs > 0 && nowMs - poolLastActivityMs >= QR_IDLE_CONFIRM_REFUND_MS;
|
||||||
@@ -566,6 +828,7 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu
|
|||||||
st.pendingCostUsd = 0;
|
st.pendingCostUsd = 0;
|
||||||
st.pendingCostAtMs = 0;
|
st.pendingCostAtMs = 0;
|
||||||
st.pendingCostSinceMs = 0;
|
st.pendingCostSinceMs = 0;
|
||||||
|
st.pendingModelCostsUsd = {};
|
||||||
};
|
};
|
||||||
|
|
||||||
const confirmRefund = (refundedPct, { keepPendingCost = false } = {}) => {
|
const confirmRefund = (refundedPct, { keepPendingCost = false } = {}) => {
|
||||||
@@ -732,8 +995,13 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu
|
|||||||
deltaOfficial > 0.005 &&
|
deltaOfficial > 0.005 &&
|
||||||
deltaOfficial < QR_MIN_JUMP_EXCESS_PCT
|
deltaOfficial < QR_MIN_JUMP_EXCESS_PCT
|
||||||
) {
|
) {
|
||||||
// 纯净未租约且无近期副本抖动的单步消耗:进入滚动中位数费率校准池
|
// 纯净未租约且无近期副本抖动的单步消耗:进入滚动中位数费率校准池;纯单模型步同步校准该模型费率
|
||||||
qrRecordRateSample(st, deltaOfficial / rawDeltaCost);
|
qrRecordRateSample(st, deltaOfficial / rawDeltaCost);
|
||||||
|
if (isPureSingleModelStep) {
|
||||||
|
const mr = qrGetOrCreateModelRate(st, dominantModelKey, nowMs);
|
||||||
|
qrRecordRateSample(mr, deltaOfficial / dominantModelDeltaUsd);
|
||||||
|
mr.lastSeenMs = nowMs;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
eventKind = 'normal';
|
eventKind = 'normal';
|
||||||
}
|
}
|
||||||
@@ -743,9 +1011,17 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu
|
|||||||
const hasBufferedLeaseCost = st.pendingCostUsd > 0 && st.pendingCostSinceMs > 0;
|
const hasBufferedLeaseCost = st.pendingCostUsd > 0 && st.pendingCostSinceMs > 0;
|
||||||
if (st.activeLeases.length > 0) {
|
if (st.activeLeases.length > 0) {
|
||||||
const accCost = rawDeltaCost + (hasBufferedLeaseCost ? st.pendingCostUsd : 0);
|
const accCost = rawDeltaCost + (hasBufferedLeaseCost ? st.pendingCostUsd : 0);
|
||||||
|
const accModelCosts = { ...rawDeltaModelCosts };
|
||||||
|
if (hasBufferedLeaseCost && st.pendingModelCostsUsd && typeof st.pendingModelCostsUsd === 'object') {
|
||||||
|
for (const [mKey, pCost] of Object.entries(st.pendingModelCostsUsd)) {
|
||||||
|
if (Number.isFinite(pCost) && pCost > 0) {
|
||||||
|
accModelCosts[mKey] = (accModelCosts[mKey] || 0) + pCost;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
const sinceMs = hasBufferedLeaseCost ? st.pendingCostSinceMs : nowMs;
|
const sinceMs = hasBufferedLeaseCost ? st.pendingCostSinceMs : nowMs;
|
||||||
if (nowMs - sinceMs >= QR_CONSUME_LAG_GRACE_MS) {
|
if (nowMs - sinceMs >= QR_CONSUME_LAG_GRACE_MS) {
|
||||||
const consumedPct = rate !== null ? accCost * rate : 0;
|
const consumedPct = qrEstimateModelWeightedPct(st, accModelCosts, accCost, rate);
|
||||||
expectedDeltaPct = consumedPct;
|
expectedDeltaPct = consumedPct;
|
||||||
excessPct = deltaOfficial - expectedDeltaPct;
|
excessPct = deltaOfficial - expectedDeltaPct;
|
||||||
if (consumedPct > 0) {
|
if (consumedPct > 0) {
|
||||||
@@ -760,6 +1036,7 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu
|
|||||||
st.pendingCostUsd = accCost;
|
st.pendingCostUsd = accCost;
|
||||||
st.pendingCostAtMs = nowMs;
|
st.pendingCostAtMs = nowMs;
|
||||||
st.pendingCostSinceMs = sinceMs;
|
st.pendingCostSinceMs = sinceMs;
|
||||||
|
st.pendingModelCostsUsd = accModelCosts;
|
||||||
eventKind = 'lag_pending';
|
eventKind = 'lag_pending';
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@@ -768,6 +1045,7 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu
|
|||||||
st.pendingCostAtMs = nowMs;
|
st.pendingCostAtMs = nowMs;
|
||||||
st.pendingCostSinceMs =
|
st.pendingCostSinceMs =
|
||||||
pendingValid && st.pendingCostSinceMs > 0 ? st.pendingCostSinceMs : nowMs;
|
pendingValid && st.pendingCostSinceMs > 0 ? st.pendingCostSinceMs : nowMs;
|
||||||
|
st.pendingModelCostsUsd = effectiveDeltaModelCosts;
|
||||||
eventKind = 'lag_pending';
|
eventKind = 'lag_pending';
|
||||||
}
|
}
|
||||||
} else if (
|
} else if (
|
||||||
@@ -777,7 +1055,12 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu
|
|||||||
nowMs - st.pendingCostSinceMs >= QR_CONSUME_LAG_GRACE_MS
|
nowMs - st.pendingCostSinceMs >= QR_CONSUME_LAG_GRACE_MS
|
||||||
) {
|
) {
|
||||||
// 4C-2. 无新增花费但已跨过 25s 延迟观察窗且官方仍原地踏步:确认此前缓冲成本已在租约内消化
|
// 4C-2. 无新增花费但已跨过 25s 延迟观察窗且官方仍原地踏步:确认此前缓冲成本已在租约内消化
|
||||||
const consumedPct = rate !== null ? st.pendingCostUsd * rate : 0;
|
const consumedPct = qrEstimateModelWeightedPct(
|
||||||
|
st,
|
||||||
|
st.pendingModelCostsUsd,
|
||||||
|
st.pendingCostUsd,
|
||||||
|
rate
|
||||||
|
);
|
||||||
expectedDeltaPct = consumedPct;
|
expectedDeltaPct = consumedPct;
|
||||||
excessPct = deltaOfficial - expectedDeltaPct;
|
excessPct = deltaOfficial - expectedDeltaPct;
|
||||||
if (consumedPct > 0) {
|
if (consumedPct > 0) {
|
||||||
@@ -793,6 +1076,7 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu
|
|||||||
st.lastQuotaTs = safeFetchTs;
|
st.lastQuotaTs = safeFetchTs;
|
||||||
st.lastOfficialUsedPct = safeUsed;
|
st.lastOfficialUsedPct = safeUsed;
|
||||||
st.lastCycleCostUsd = safeCost;
|
st.lastCycleCostUsd = safeCost;
|
||||||
|
st.lastModelCostsUsd = safeModelCosts;
|
||||||
st.lastUnpricedCalls = safeUnpriced;
|
st.lastUnpricedCalls = safeUnpriced;
|
||||||
|
|
||||||
// 5. 租约 TTL 超时兜底(租约本身超过 60 分钟无实质扣减或满 90 分钟自动清理)
|
// 5. 租约 TTL 超时兜底(租约本身超过 60 分钟无实质扣减或满 90 分钟自动清理)
|
||||||
@@ -824,7 +1108,8 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu
|
|||||||
nowMs = Date.now(),
|
nowMs = Date.now(),
|
||||||
} = {}) {
|
} = {}) {
|
||||||
if (!(quotaPoolsMap instanceof Map) || quotaPoolsMap.size === 0) return;
|
if (!(quotaPoolsMap instanceof Map) || quotaPoolsMap.size === 0) return;
|
||||||
const scopePrefix = `${String(endpointId || 'local')}::${String(accountScope || '')}`;
|
const normalizedAccountScope = String(accountScope || '').trim().toLowerCase();
|
||||||
|
const scopePrefix = `${String(endpointId || 'local')}::${normalizedAccountScope}`;
|
||||||
|
|
||||||
for (const [poolKey, poolObj] of quotaPoolsMap.entries()) {
|
for (const [poolKey, poolObj] of quotaPoolsMap.entries()) {
|
||||||
if (!poolObj || typeof poolObj !== 'object') continue;
|
if (!poolObj || typeof poolObj !== 'object') continue;
|
||||||
@@ -834,17 +1119,19 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu
|
|||||||
const activeSessionCount10m = Number(recent10m?.activeSessionCount) || 0;
|
const activeSessionCount10m = Number(recent10m?.activeSessionCount) || 0;
|
||||||
const recent10mCostUsd = Number(recent10m?.costUsd) || 0;
|
const recent10mCostUsd = Number(recent10m?.costUsd) || 0;
|
||||||
|
|
||||||
|
const key5h = `${scopePrefix}::${poolKey}::5h`;
|
||||||
const used5hExact = poolObj.has5h ? qrResolveExactUsedPct(poolObj, '5h') : null;
|
const used5hExact = poolObj.has5h ? qrResolveExactUsedPct(poolObj, '5h') : null;
|
||||||
const res5h =
|
const res5h =
|
||||||
used5hExact !== null
|
used5hExact !== null
|
||||||
? observeBucket({
|
? observeBucket({
|
||||||
bucketKey: `${scopePrefix}::${poolKey}::5h`,
|
bucketKey: key5h,
|
||||||
poolKey,
|
poolKey,
|
||||||
win: '5h',
|
win: '5h',
|
||||||
officialUsedPct: used5hExact,
|
officialUsedPct: used5hExact,
|
||||||
resetTimeMs: parseIsoMs(poolObj.resetTime),
|
resetTimeMs: parseIsoMs(poolObj.resetTime),
|
||||||
quotaFetchedAtMs,
|
quotaFetchedAtMs,
|
||||||
cycleCostUsd: pStats?.exactCost5hUsd ?? pStats?.cycle5h?.costUsd ?? 0,
|
cycleCostUsd: pStats?.exactCost5hUsd ?? pStats?.cycle5h?.costUsd ?? 0,
|
||||||
|
modelCostsUsd: pStats?.modelCosts5h || null,
|
||||||
unpricedCalls: pStats?.cycle5h?.unpricedCalls || 0,
|
unpricedCalls: pStats?.cycle5h?.unpricedCalls || 0,
|
||||||
poolLastActivityMs,
|
poolLastActivityMs,
|
||||||
activeSessionCount10m,
|
activeSessionCount10m,
|
||||||
@@ -853,17 +1140,19 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu
|
|||||||
})
|
})
|
||||||
: { reservedPct: 0, reservedLeaseCount: 0, reservedExpiresAtMs: null };
|
: { reservedPct: 0, reservedLeaseCount: 0, reservedExpiresAtMs: null };
|
||||||
|
|
||||||
|
const keyWk = `${scopePrefix}::${poolKey}::weekly`;
|
||||||
const usedWkExact = poolObj.hasWeekly ? qrResolveExactUsedPct(poolObj, 'weekly') : null;
|
const usedWkExact = poolObj.hasWeekly ? qrResolveExactUsedPct(poolObj, 'weekly') : null;
|
||||||
const resWk =
|
const resWk =
|
||||||
usedWkExact !== null
|
usedWkExact !== null
|
||||||
? observeBucket({
|
? observeBucket({
|
||||||
bucketKey: `${scopePrefix}::${poolKey}::weekly`,
|
bucketKey: keyWk,
|
||||||
poolKey,
|
poolKey,
|
||||||
win: 'weekly',
|
win: 'weekly',
|
||||||
officialUsedPct: usedWkExact,
|
officialUsedPct: usedWkExact,
|
||||||
resetTimeMs: parseIsoMs(poolObj.weeklyResetTime),
|
resetTimeMs: parseIsoMs(poolObj.weeklyResetTime),
|
||||||
quotaFetchedAtMs,
|
quotaFetchedAtMs,
|
||||||
cycleCostUsd: pStats?.exactCostWeeklyUsd ?? pStats?.cycleWeekly?.costUsd ?? 0,
|
cycleCostUsd: pStats?.exactCostWeeklyUsd ?? pStats?.cycleWeekly?.costUsd ?? 0,
|
||||||
|
modelCostsUsd: pStats?.modelCostsWeekly || null,
|
||||||
unpricedCalls: pStats?.cycleWeekly?.unpricedCalls || 0,
|
unpricedCalls: pStats?.cycleWeekly?.unpricedCalls || 0,
|
||||||
poolLastActivityMs,
|
poolLastActivityMs,
|
||||||
activeSessionCount10m,
|
activeSessionCount10m,
|
||||||
@@ -878,6 +1167,7 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu
|
|||||||
poolObj.weeklyReservedPct = resWk.reservedPct;
|
poolObj.weeklyReservedPct = resWk.reservedPct;
|
||||||
poolObj.weeklyReservedLeaseCount = resWk.reservedLeaseCount;
|
poolObj.weeklyReservedLeaseCount = resWk.reservedLeaseCount;
|
||||||
poolObj.weeklyReservedExpiresAtMs = resWk.reservedExpiresAtMs;
|
poolObj.weeklyReservedExpiresAtMs = resWk.reservedExpiresAtMs;
|
||||||
|
poolObj.rateEstimate = qrBuildPoolRateEstimate(buckets.get(key5h) || null, buckets.get(keyWk) || null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -888,6 +1178,15 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu
|
|||||||
const parts = key.split('::');
|
const parts = key.split('::');
|
||||||
const usedPct = st.lastOfficialUsedPct ?? 0;
|
const usedPct = st.lastOfficialUsedPct ?? 0;
|
||||||
const out = qrFormatOutput(st, usedPct);
|
const out = qrFormatOutput(st, usedPct);
|
||||||
|
const byModel = {};
|
||||||
|
for (const [mKey, mr] of Object.entries(st.modelRates || {})) {
|
||||||
|
if (!mr || mr.ratePctPerUsd === null) continue;
|
||||||
|
byModel[mKey] = {
|
||||||
|
ratePctPerUsd: +mr.ratePctPerUsd.toFixed(4),
|
||||||
|
eqFullUsd: +(100 / mr.ratePctPerUsd).toFixed(1),
|
||||||
|
samples: mr.rateSamples,
|
||||||
|
};
|
||||||
|
}
|
||||||
bucketSummaries.push({
|
bucketSummaries.push({
|
||||||
pool: parts[2] || key,
|
pool: parts[2] || key,
|
||||||
win: parts[3] || '',
|
win: parts[3] || '',
|
||||||
@@ -897,6 +1196,7 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu
|
|||||||
rateSamples: st.rateSamples,
|
rateSamples: st.rateSamples,
|
||||||
reservedPct: out.reservedPct,
|
reservedPct: out.reservedPct,
|
||||||
leases: out.reservedLeaseCount,
|
leases: out.reservedLeaseCount,
|
||||||
|
...(Object.keys(byModel).length > 0 ? { byModel } : {}),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -794,6 +794,8 @@ function buildQuotaPoolCycleMap(quotaPoolsMap, nowMs) {
|
|||||||
startWkMs,
|
startWkMs,
|
||||||
b5h: createUsageBucket(),
|
b5h: createUsageBucket(),
|
||||||
bWk: createUsageBucket(),
|
bWk: createUsageBucket(),
|
||||||
|
modelCosts5h: new Map(),
|
||||||
|
modelCostsWk: new Map(),
|
||||||
lastActivityMs: 0,
|
lastActivityMs: 0,
|
||||||
recent10mSessions: new Map(),
|
recent10mSessions: new Map(),
|
||||||
});
|
});
|
||||||
@@ -1577,11 +1579,24 @@ export function aggregateMultiWindowUsage({
|
|||||||
sessStat.calls += 1;
|
sessStat.calls += 1;
|
||||||
if (qMs > sessStat.lastActivityMs) sessStat.lastActivityMs = qMs;
|
if (qMs > sessStat.lastActivityMs) sessStat.lastActivityMs = qMs;
|
||||||
}
|
}
|
||||||
|
const quotaModelKey = mInfo.baseLabel || mInfo.label || '';
|
||||||
if (qMs >= poolBucketEntry.start5hMs) {
|
if (qMs >= poolBucketEntry.start5hMs) {
|
||||||
accumulateStepIntoBucket(poolBucketEntry.b5h, stepUsage, cascadeId);
|
accumulateStepIntoBucket(poolBucketEntry.b5h, stepUsage, cascadeId);
|
||||||
|
if (quotaModelKey && stepUsage.resolvedCost > 0) {
|
||||||
|
poolBucketEntry.modelCosts5h.set(
|
||||||
|
quotaModelKey,
|
||||||
|
(poolBucketEntry.modelCosts5h.get(quotaModelKey) || 0) + stepUsage.resolvedCost
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (qMs >= poolBucketEntry.startWkMs) {
|
if (qMs >= poolBucketEntry.startWkMs) {
|
||||||
accumulateStepIntoBucket(poolBucketEntry.bWk, stepUsage, cascadeId);
|
accumulateStepIntoBucket(poolBucketEntry.bWk, stepUsage, cascadeId);
|
||||||
|
if (quotaModelKey && stepUsage.resolvedCost > 0) {
|
||||||
|
poolBucketEntry.modelCostsWk.set(
|
||||||
|
quotaModelKey,
|
||||||
|
(poolBucketEntry.modelCostsWk.get(quotaModelKey) || 0) + stepUsage.resolvedCost
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1783,6 +1798,16 @@ export function aggregateMultiWindowUsage({
|
|||||||
let rawPoolsWeeklyTokens = 0;
|
let rawPoolsWeeklyTokens = 0;
|
||||||
let rawPoolsWeeklyCostUsd = 0;
|
let rawPoolsWeeklyCostUsd = 0;
|
||||||
let rawPoolsWeeklyUnpricedCalls = 0;
|
let rawPoolsWeeklyUnpricedCalls = 0;
|
||||||
|
const serializeModelCosts = (mMap) => {
|
||||||
|
const out = {};
|
||||||
|
if (!(mMap instanceof Map)) return out;
|
||||||
|
for (const [mKey, costVal] of mMap.entries()) {
|
||||||
|
if (mKey && Number.isFinite(costVal) && costVal > 0) {
|
||||||
|
out[mKey] = +costVal.toFixed(6);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
};
|
||||||
for (const [poolKey, entry] of poolCycleBuckets.entries()) {
|
for (const [poolKey, entry] of poolCycleBuckets.entries()) {
|
||||||
let recent10mCostUsd = 0;
|
let recent10mCostUsd = 0;
|
||||||
for (const sStat of entry.recent10mSessions.values()) {
|
for (const sStat of entry.recent10mSessions.values()) {
|
||||||
@@ -1793,6 +1818,8 @@ export function aggregateMultiWindowUsage({
|
|||||||
cycleWeekly: formatCycleSummary(entry.bWk),
|
cycleWeekly: formatCycleSummary(entry.bWk),
|
||||||
exactCost5hUsd: +entry.b5h.costUsd.toFixed(6),
|
exactCost5hUsd: +entry.b5h.costUsd.toFixed(6),
|
||||||
exactCostWeeklyUsd: +entry.bWk.costUsd.toFixed(6),
|
exactCostWeeklyUsd: +entry.bWk.costUsd.toFixed(6),
|
||||||
|
modelCosts5h: serializeModelCosts(entry.modelCosts5h),
|
||||||
|
modelCostsWeekly: serializeModelCosts(entry.modelCostsWk),
|
||||||
recent10m: {
|
recent10m: {
|
||||||
lastActivityMs: entry.lastActivityMs,
|
lastActivityMs: entry.lastActivityMs,
|
||||||
activeSessionCount: entry.recent10mSessions.size,
|
activeSessionCount: entry.recent10mSessions.size,
|
||||||
|
|||||||
@@ -4,11 +4,11 @@
|
|||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
<title>用量监控</title>
|
<title>用量监控</title>
|
||||||
<link rel="stylesheet" href="/styles.css?v=1795400571874">
|
<link rel="stylesheet" href="/styles.css?v=1795418097398">
|
||||||
<script src="/preload.js"></script>
|
<script src="/preload.js"></script>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="app-root"></div>
|
<div id="app-root"></div>
|
||||||
<script src="/app.js?v=1795400571874"></script>
|
<script src="/app.js?v=1795418097398"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -414,12 +414,331 @@ export function formatAccountTierBadge(account) {
|
|||||||
return `${tierName} · ${rawPlan}`;
|
return `${tierName} · ${rawPlan}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 对账号邮箱或名称做轻量隐私脱敏(如 `sjee80343@gmail.com` -> `sj***43@gmail.com`),
|
||||||
|
* 兼顾多账号辨识度及截图分享隐私安全。
|
||||||
|
*
|
||||||
|
* @param {string|null|undefined} raw
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
export function maskAccountLabel(raw) {
|
||||||
|
const str = String(raw || '').trim();
|
||||||
|
if (!str) return '';
|
||||||
|
const atIdx = str.indexOf('@');
|
||||||
|
if (atIdx > 0 && atIdx < str.length - 1) {
|
||||||
|
const local = str.slice(0, atIdx);
|
||||||
|
const domain = str.slice(atIdx);
|
||||||
|
const chars = Array.from(local);
|
||||||
|
if (chars.length <= 1) return `*${domain}`;
|
||||||
|
if (chars.length === 2) return `${chars[0]}*${domain}`;
|
||||||
|
if (chars.length <= 4) return `${chars[0]}***${chars[chars.length - 1]}${domain}`;
|
||||||
|
return `${chars.slice(0, 2).join('')}***${chars.slice(-2).join('')}${domain}`;
|
||||||
|
}
|
||||||
|
const chars = Array.from(str);
|
||||||
|
if (chars.length <= 1) return '*';
|
||||||
|
if (chars.length === 2) return `${chars[0]}*`;
|
||||||
|
if (chars.length <= 4) return `${chars[0]}***${chars[chars.length - 1]}`;
|
||||||
|
return `${chars.slice(0, 2).join('')}***${chars[chars.length - 1]}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatRateEqUsd(val) {
|
||||||
|
const num = Number(val);
|
||||||
|
if (!Number.isFinite(num) || num <= 0) return '--';
|
||||||
|
if (num >= 10) return `$${Math.round(num)}`;
|
||||||
|
return `$${Number(num.toFixed(1))}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatRatePerUsdValue(rate) {
|
||||||
|
const num = Number(rate);
|
||||||
|
if (!Number.isFinite(num) || num <= 0) return '--';
|
||||||
|
return String(Number(num.toFixed(2)));
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatRateMultiplier(mult) {
|
||||||
|
const num = Number(mult);
|
||||||
|
if (!Number.isFinite(num) || num <= 0) return '';
|
||||||
|
return `${Number(num.toFixed(1))}x`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function createRateModelCard({
|
||||||
|
name,
|
||||||
|
isMutedName = false,
|
||||||
|
isFallback = false,
|
||||||
|
multiplier = null,
|
||||||
|
rate5hPctPerUsd = null,
|
||||||
|
rateWeeklyPctPerUsd = null,
|
||||||
|
eqFull5hUsd = null,
|
||||||
|
eqFullWeeklyUsd = null,
|
||||||
|
samples = 0,
|
||||||
|
}) {
|
||||||
|
const leftNodes = [
|
||||||
|
h('span', {
|
||||||
|
className: `quota-rate-model-name${isMutedName ? ' is-muted' : ''}`,
|
||||||
|
text: name,
|
||||||
|
}),
|
||||||
|
];
|
||||||
|
const multText = formatRateMultiplier(multiplier);
|
||||||
|
if (multText) {
|
||||||
|
leftNodes.push(
|
||||||
|
h('span', {
|
||||||
|
className: `quota-rate-mult-badge${Number(multiplier) >= 1.5 ? ' is-high' : ''}`,
|
||||||
|
text: multText,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const has5hRate = rate5hPctPerUsd != null;
|
||||||
|
const primaryRate = has5hRate ? rate5hPctPerUsd : rateWeeklyPctPerUsd;
|
||||||
|
const subParts = [];
|
||||||
|
if (primaryRate != null) {
|
||||||
|
subParts.push(
|
||||||
|
t('quota.ratePopPerUsd', {
|
||||||
|
win: has5hRate ? '5h' : t('quota.weeklyShort'),
|
||||||
|
rate: formatRatePerUsdValue(primaryRate),
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (Number(samples) > 0) {
|
||||||
|
subParts.push(t('quota.ratePopSamples', { n: Number(samples) }));
|
||||||
|
}
|
||||||
|
|
||||||
|
const eqCells = [];
|
||||||
|
if (eqFull5hUsd != null) {
|
||||||
|
eqCells.push(
|
||||||
|
h('div', { className: 'quota-rate-eq-cell' }, [
|
||||||
|
h('span', { className: 'quota-rate-eq-k', text: t('quota.ratePopEq5hLabel') }),
|
||||||
|
h('span', {
|
||||||
|
className: 'quota-rate-eq-v text-mono',
|
||||||
|
text: `≈ ${formatRateEqUsd(eqFull5hUsd)}`,
|
||||||
|
}),
|
||||||
|
])
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (eqFullWeeklyUsd != null) {
|
||||||
|
eqCells.push(
|
||||||
|
h('div', { className: 'quota-rate-eq-cell' }, [
|
||||||
|
h('span', { className: 'quota-rate-eq-k', text: t('quota.ratePopEqWkLabel') }),
|
||||||
|
h('span', {
|
||||||
|
className: 'quota-rate-eq-v text-mono',
|
||||||
|
text: `≈ ${formatRateEqUsd(eqFullWeeklyUsd)}`,
|
||||||
|
}),
|
||||||
|
])
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const cardChildren = [
|
||||||
|
h('div', { className: 'quota-rate-row-top' }, [
|
||||||
|
h('div', { className: 'quota-rate-model-left' }, leftNodes),
|
||||||
|
...(subParts.length > 0
|
||||||
|
? [h('span', { className: 'quota-rate-meta text-mono', text: subParts.join(' · ') })]
|
||||||
|
: []),
|
||||||
|
]),
|
||||||
|
];
|
||||||
|
if (eqCells.length > 0) {
|
||||||
|
cardChildren.push(
|
||||||
|
h(
|
||||||
|
'div',
|
||||||
|
{ className: `quota-rate-eq-grid${eqCells.length === 1 ? ' is-single' : ''}` },
|
||||||
|
eqCells
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return h('div', { className: `quota-rate-model-row${isFallback ? ' is-fallback' : ''}` }, cardChildren);
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildRatePopoverSig(data) {
|
||||||
|
const locale = getEffectiveLocale();
|
||||||
|
const acct = String(data?.account?.email || data?.account?.name || '').trim();
|
||||||
|
const pools = Array.isArray(data?.quotas?.pools) ? data.quotas.pools : [];
|
||||||
|
const poolSig = pools
|
||||||
|
.map((p) => `${p.poolKey || ''}:${p.poolLabel || ''}:${JSON.stringify(p.rateEstimate || null)}`)
|
||||||
|
.join('|');
|
||||||
|
return `${locale}|${acct}|${poolSig}`;
|
||||||
|
}
|
||||||
|
|
||||||
export const QuotaPoolsWidget = defineComponent({
|
export const QuotaPoolsWidget = defineComponent({
|
||||||
name: 'QuotaPoolsWidget',
|
name: 'QuotaPoolsWidget',
|
||||||
setup({ props }) {
|
setup({ props, onCleanup }) {
|
||||||
const compactHover = Boolean(props.compactHover);
|
const compactHover = Boolean(props.compactHover);
|
||||||
const titleTextEl = h('span', { text: t('module.quotas') });
|
const titleTextEl = h('span', { text: t('module.quotas') });
|
||||||
const tierBadge = h('span', { className: 'panel-meta', text: 'Google AI · Pro' });
|
const tierBadge = h('span', { className: 'panel-meta', text: 'Google AI · Pro' });
|
||||||
|
|
||||||
|
const ratePopTitleEl = h('span', {
|
||||||
|
className: 'quota-rate-pop-title',
|
||||||
|
text: t('quota.ratePopTitle'),
|
||||||
|
});
|
||||||
|
const ratePopAccountEl = h('span', {
|
||||||
|
className: 'quota-rate-pop-account',
|
||||||
|
text: t('quota.ratePopAccountCurrent'),
|
||||||
|
});
|
||||||
|
const ratePopBodyEl = h('div', { className: 'quota-rate-pop-body' });
|
||||||
|
const ratePopNoteEl = h('div', {
|
||||||
|
className: 'quota-rate-pop-note',
|
||||||
|
text: t('quota.ratePopNote'),
|
||||||
|
});
|
||||||
|
const ratePopoverEl = h(
|
||||||
|
'div',
|
||||||
|
{
|
||||||
|
className: 'quota-rate-popover',
|
||||||
|
role: 'tooltip',
|
||||||
|
hidden: true,
|
||||||
|
},
|
||||||
|
[
|
||||||
|
h('div', { className: 'quota-rate-pop-head' }, [ratePopTitleEl, ratePopAccountEl]),
|
||||||
|
ratePopBodyEl,
|
||||||
|
ratePopNoteEl,
|
||||||
|
]
|
||||||
|
);
|
||||||
|
ratePopoverEl.hidden = true;
|
||||||
|
|
||||||
|
let ratePopOpen = false;
|
||||||
|
let ratePopCloseTimer = null;
|
||||||
|
let lastRatePopSig = '';
|
||||||
|
|
||||||
|
const cancelRatePopClose = () => {
|
||||||
|
if (ratePopCloseTimer) {
|
||||||
|
clearTimeout(ratePopCloseTimer);
|
||||||
|
ratePopCloseTimer = null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const setRatePopOpen = (open) => {
|
||||||
|
const next = Boolean(open);
|
||||||
|
ratePopOpen = next;
|
||||||
|
ratePopoverEl.hidden = !next;
|
||||||
|
patchAttr(ratePopoverEl, 'hidden', !next);
|
||||||
|
patchAttr(rateHelpBtn, 'aria-expanded', next ? 'true' : 'false');
|
||||||
|
patchClasses(rateHelpBtn, { 'is-open': next });
|
||||||
|
};
|
||||||
|
|
||||||
|
const openRatePop = () => {
|
||||||
|
cancelRatePopClose();
|
||||||
|
if (!ratePopOpen) setRatePopOpen(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
const scheduleRatePopClose = () => {
|
||||||
|
cancelRatePopClose();
|
||||||
|
ratePopCloseTimer = setTimeout(() => {
|
||||||
|
ratePopCloseTimer = null;
|
||||||
|
setRatePopOpen(false);
|
||||||
|
}, 130);
|
||||||
|
};
|
||||||
|
|
||||||
|
const rateHelpBtn = h(
|
||||||
|
'button',
|
||||||
|
{
|
||||||
|
type: 'button',
|
||||||
|
className: 'quota-rate-help-btn',
|
||||||
|
'aria-label': t('quota.rateHelpAria'),
|
||||||
|
'aria-haspopup': 'true',
|
||||||
|
'aria-expanded': 'false',
|
||||||
|
onMouseenter: openRatePop,
|
||||||
|
onMouseleave: scheduleRatePopClose,
|
||||||
|
onFocus: openRatePop,
|
||||||
|
onBlur: scheduleRatePopClose,
|
||||||
|
onClick: (ev) => {
|
||||||
|
ev?.stopPropagation?.();
|
||||||
|
cancelRatePopClose();
|
||||||
|
setRatePopOpen(!ratePopOpen);
|
||||||
|
},
|
||||||
|
onKeydown: (ev) => {
|
||||||
|
if (ev?.key === 'Escape' && ratePopOpen) {
|
||||||
|
ev.stopPropagation?.();
|
||||||
|
cancelRatePopClose();
|
||||||
|
setRatePopOpen(false);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
[createSvgIcon('help-circle', { size: 13 })]
|
||||||
|
);
|
||||||
|
|
||||||
|
ratePopoverEl.addEventListener?.('mouseenter', openRatePop);
|
||||||
|
ratePopoverEl.addEventListener?.('mouseleave', scheduleRatePopClose);
|
||||||
|
onCleanup?.(() => {
|
||||||
|
cancelRatePopClose();
|
||||||
|
});
|
||||||
|
|
||||||
|
function syncRatePopoverContent(data) {
|
||||||
|
const sig = buildRatePopoverSig(data);
|
||||||
|
if (sig === lastRatePopSig) return;
|
||||||
|
lastRatePopSig = sig;
|
||||||
|
|
||||||
|
patchText(ratePopTitleEl, t('quota.ratePopTitle'));
|
||||||
|
patchText(ratePopNoteEl, t('quota.ratePopNote'));
|
||||||
|
patchAttr(rateHelpBtn, 'aria-label', t('quota.rateHelpAria'));
|
||||||
|
|
||||||
|
const acctMasked = maskAccountLabel(data?.account?.email || data?.account?.name || '');
|
||||||
|
patchText(
|
||||||
|
ratePopAccountEl,
|
||||||
|
acctMasked
|
||||||
|
? t('quota.ratePopAccountScope', { account: acctMasked })
|
||||||
|
: t('quota.ratePopAccountCurrent')
|
||||||
|
);
|
||||||
|
patchAttr(ratePopAccountEl, 'title', acctMasked || null);
|
||||||
|
|
||||||
|
while (ratePopBodyEl.firstChild) {
|
||||||
|
ratePopBodyEl.removeChild(ratePopBodyEl.firstChild);
|
||||||
|
}
|
||||||
|
|
||||||
|
const rawPools = Array.isArray(data?.quotas?.pools) ? data.quotas.pools : [];
|
||||||
|
const populatedGroups = [];
|
||||||
|
|
||||||
|
for (const p of rawPools) {
|
||||||
|
const est = p?.rateEstimate;
|
||||||
|
if (!est || typeof est !== 'object') continue;
|
||||||
|
const models = Array.isArray(est.models) ? est.models : [];
|
||||||
|
const hasPoolFallback =
|
||||||
|
models.length === 0 &&
|
||||||
|
(Number.isFinite(est.rate5hPctPerUsd) || Number.isFinite(est.rateWeeklyPctPerUsd));
|
||||||
|
if (models.length === 0 && !hasPoolFallback) continue;
|
||||||
|
|
||||||
|
const poolLabel = p.poolLabel || p.family || p.poolKey || 'Pool';
|
||||||
|
const rows =
|
||||||
|
models.length > 0
|
||||||
|
? models.map((item) =>
|
||||||
|
createRateModelCard({
|
||||||
|
name: item.model,
|
||||||
|
multiplier: item.multiplier,
|
||||||
|
rate5hPctPerUsd: item.rate5hPctPerUsd,
|
||||||
|
rateWeeklyPctPerUsd: item.rateWeeklyPctPerUsd,
|
||||||
|
eqFull5hUsd: item.eqFull5hUsd,
|
||||||
|
eqFullWeeklyUsd: item.eqFullWeeklyUsd,
|
||||||
|
samples: item.samples,
|
||||||
|
})
|
||||||
|
)
|
||||||
|
: [
|
||||||
|
createRateModelCard({
|
||||||
|
name: t('quota.ratePopPoolFallback'),
|
||||||
|
isMutedName: true,
|
||||||
|
isFallback: true,
|
||||||
|
rate5hPctPerUsd: est.rate5hPctPerUsd,
|
||||||
|
rateWeeklyPctPerUsd: est.rateWeeklyPctPerUsd,
|
||||||
|
eqFull5hUsd: est.eqFull5hUsd,
|
||||||
|
eqFullWeeklyUsd: est.eqFullWeeklyUsd,
|
||||||
|
samples: Math.max(Number(est.samples5h) || 0, Number(est.samplesWeekly) || 0),
|
||||||
|
}),
|
||||||
|
];
|
||||||
|
|
||||||
|
populatedGroups.push(
|
||||||
|
h('div', { className: 'quota-rate-pool-group' }, [
|
||||||
|
h('div', { className: 'quota-rate-pool-label', text: poolLabel }),
|
||||||
|
h('div', { className: 'quota-rate-model-list' }, rows),
|
||||||
|
])
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (populatedGroups.length === 0) {
|
||||||
|
ratePopBodyEl.appendChild(
|
||||||
|
h('div', { className: 'quota-rate-pop-empty', text: t('quota.ratePopEmpty') })
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
for (const grp of populatedGroups) {
|
||||||
|
ratePopBodyEl.appendChild(grp);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const poolsListEl = h(
|
const poolsListEl = h(
|
||||||
'div',
|
'div',
|
||||||
compactHover
|
compactHover
|
||||||
@@ -453,22 +772,27 @@ export const QuotaPoolsWidget = defineComponent({
|
|||||||
]
|
]
|
||||||
);
|
);
|
||||||
|
|
||||||
const quotaPanel = h('section', { className: 'panel' }, [
|
const quotaPanel = h('section', { className: 'panel quota-panel' }, [
|
||||||
h('div', { className: 'panel-header' }, [
|
h('div', { className: 'panel-header' }, [
|
||||||
h('span', { className: 'panel-title' }, [
|
h('span', { className: 'panel-title' }, [
|
||||||
createSvgIcon('pulse', { size: 13 }),
|
createSvgIcon('pulse', { size: 13 }),
|
||||||
titleTextEl,
|
titleTextEl,
|
||||||
|
rateHelpBtn,
|
||||||
]),
|
]),
|
||||||
tierBadge,
|
tierBadge,
|
||||||
]),
|
]),
|
||||||
poolsListEl,
|
poolsListEl,
|
||||||
reserveLegendEl,
|
reserveLegendEl,
|
||||||
|
ratePopoverEl,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
syncRatePopoverContent(null);
|
||||||
|
|
||||||
function update({ data, minuteTick } = {}) {
|
function update({ data, minuteTick } = {}) {
|
||||||
patchText(titleTextEl, t('module.quotas'));
|
patchText(titleTextEl, t('module.quotas'));
|
||||||
patchText(legendActualTextEl, t('quota.legendActual'));
|
patchText(legendActualTextEl, t('quota.legendActual'));
|
||||||
patchText(legendReservedTextEl, t('quota.legendReserved'));
|
patchText(legendReservedTextEl, t('quota.legendReserved'));
|
||||||
|
syncRatePopoverContent(data);
|
||||||
if (!data) {
|
if (!data) {
|
||||||
reserveLegendEl.hidden = true;
|
reserveLegendEl.hidden = true;
|
||||||
if (compactHover) {
|
if (compactHover) {
|
||||||
@@ -497,7 +821,7 @@ export const QuotaPoolsWidget = defineComponent({
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
el: quotaPanel,
|
el: quotaPanel,
|
||||||
refs: { update, poolsListEl },
|
refs: { update, poolsListEl, rateHelpBtn, ratePopoverEl },
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -200,6 +200,17 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
|
|||||||
'quota.footCallsCycle': 'Cycle Calls: {calls}',
|
'quota.footCallsCycle': 'Cycle Calls: {calls}',
|
||||||
'quota.footTipCustom': 'Counted since Monday 00:00 local time',
|
'quota.footTipCustom': 'Counted since Monday 00:00 local time',
|
||||||
'quota.footTipCycle': 'Summed across each quota pool weekly reset window',
|
'quota.footTipCycle': 'Summed across each quota pool weekly reset window',
|
||||||
|
'quota.rateHelpAria': 'View empirical burn-rate estimates for this account',
|
||||||
|
'quota.ratePopTitle': 'Estimated Burn Rates',
|
||||||
|
'quota.ratePopAccountScope': '{account}',
|
||||||
|
'quota.ratePopAccountCurrent': 'Current account',
|
||||||
|
'quota.ratePopPoolFallback': 'Pool average',
|
||||||
|
'quota.ratePopEq5hLabel': '5h full',
|
||||||
|
'quota.ratePopEqWkLabel': 'Weekly full',
|
||||||
|
'quota.ratePopPerUsd': '{win} {rate}%/$',
|
||||||
|
'quota.ratePopSamples': '{n} samples',
|
||||||
|
'quota.ratePopEmpty': 'Not enough clean single-model samples yet (at least 3 clean steps per model). Estimates appear automatically during use.',
|
||||||
|
'quota.ratePopNote': 'Measured from clean single-model steps; lowest burn in pool = 1x. Account isolated.',
|
||||||
|
|
||||||
// Live Activity Widget
|
// Live Activity Widget
|
||||||
'live.currentSession': 'Current Session',
|
'live.currentSession': 'Current Session',
|
||||||
|
|||||||
@@ -200,6 +200,17 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
|
|||||||
'quota.footCallsCycle': '周期调用: {calls} 次',
|
'quota.footCallsCycle': '周期调用: {calls} 次',
|
||||||
'quota.footTipCustom': '按本机自然周(周一 00:00 起)统计',
|
'quota.footTipCustom': '按本机自然周(周一 00:00 起)统计',
|
||||||
'quota.footTipCycle': '按各配额池独立周限重置周期分别统计并汇总',
|
'quota.footTipCycle': '按各配额池独立周限重置周期分别统计并汇总',
|
||||||
|
'quota.rateHelpAria': '查看当前账号实测倍率预估',
|
||||||
|
'quota.ratePopTitle': '实测倍率预估',
|
||||||
|
'quota.ratePopAccountScope': '{account}',
|
||||||
|
'quota.ratePopAccountCurrent': '当前账号',
|
||||||
|
'quota.ratePopPoolFallback': '池综合均值',
|
||||||
|
'quota.ratePopEq5hLabel': '5h 满池',
|
||||||
|
'quota.ratePopEqWkLabel': '周限满池',
|
||||||
|
'quota.ratePopPerUsd': '{win} {rate}%/$',
|
||||||
|
'quota.ratePopSamples': '{n} 样本',
|
||||||
|
'quota.ratePopEmpty': '暂未采集到足够的单模型干净样本(每模型需至少 3 次无抖动扣费),正常使用后自动生成。',
|
||||||
|
'quota.ratePopNote': '按单模型纯净步实测折算,同池最省为 1x,按账号隔离。',
|
||||||
|
|
||||||
// Live Activity Widget
|
// Live Activity Widget
|
||||||
'live.currentSession': '当前会话',
|
'live.currentSession': '当前会话',
|
||||||
|
|||||||
@@ -22,6 +22,11 @@ export const SVG_ICON_DEFS = Object.freeze({
|
|||||||
{ tag: 'path', attrs: { d: 'M8 6.2v3.4' } },
|
{ tag: 'path', attrs: { d: 'M8 6.2v3.4' } },
|
||||||
{ tag: 'circle', attrs: { cx: '8', cy: '11.5', r: '0.6', fill: 'currentColor', stroke: 'none' } },
|
{ tag: 'circle', attrs: { cx: '8', cy: '11.5', r: '0.6', fill: 'currentColor', stroke: 'none' } },
|
||||||
],
|
],
|
||||||
|
'help-circle': [
|
||||||
|
{ tag: 'circle', attrs: { cx: '8', cy: '8', r: '6' } },
|
||||||
|
{ tag: 'path', attrs: { d: 'M6.2 6.3a1.9 1.9 0 0 1 3.6.7c0 1.15-1.8 1.35-1.8 2.5' } },
|
||||||
|
{ tag: 'circle', attrs: { cx: '8', cy: '11.8', r: '0.65', fill: 'currentColor', stroke: 'none' } },
|
||||||
|
],
|
||||||
'chevron-down': [
|
'chevron-down': [
|
||||||
{ tag: 'path', attrs: { d: 'M4 6.2l4 4 4-4' } },
|
{ tag: 'path', attrs: { d: 'M4 6.2l4 4 4-4' } },
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -1105,7 +1105,9 @@ export function isEquivalentTelemetry(prev, next) {
|
|||||||
pPools[i]?.cycle5h?.calls !== nPools[i]?.cycle5h?.calls ||
|
pPools[i]?.cycle5h?.calls !== nPools[i]?.cycle5h?.calls ||
|
||||||
pPools[i]?.cycleWeekly?.tokens !== nPools[i]?.cycleWeekly?.tokens ||
|
pPools[i]?.cycleWeekly?.tokens !== nPools[i]?.cycleWeekly?.tokens ||
|
||||||
pPools[i]?.cycleWeekly?.costUsd !== nPools[i]?.cycleWeekly?.costUsd ||
|
pPools[i]?.cycleWeekly?.costUsd !== nPools[i]?.cycleWeekly?.costUsd ||
|
||||||
pPools[i]?.cycleWeekly?.calls !== nPools[i]?.cycleWeekly?.calls
|
pPools[i]?.cycleWeekly?.calls !== nPools[i]?.cycleWeekly?.calls ||
|
||||||
|
JSON.stringify(pPools[i]?.rateEstimate || null) !==
|
||||||
|
JSON.stringify(nPools[i]?.rateEstimate || null)
|
||||||
) {
|
) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -813,7 +813,9 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
|
|||||||
[data-modern-ui="true"] .trend-tooltip,
|
[data-modern-ui="true"] .trend-tooltip,
|
||||||
[data-modern-ui="true"] .cons-breakdown-popover,
|
[data-modern-ui="true"] .cons-breakdown-popover,
|
||||||
[data-modern-ui="true"] .turn-prompt-tip,
|
[data-modern-ui="true"] .turn-prompt-tip,
|
||||||
[data-modern-ui="true"] .step-anomaly-tip {
|
[data-modern-ui="true"] .step-anomaly-tip,
|
||||||
|
[data-modern-ui="true"] .quota-rate-popover,
|
||||||
|
:host([data-modern-ui="true"]) .quota-rate-popover {
|
||||||
border: none;
|
border: none;
|
||||||
background: var(--modern-surface-card);
|
background: var(--modern-surface-card);
|
||||||
box-shadow: var(--shadow-popover);
|
box-shadow: var(--shadow-popover);
|
||||||
@@ -821,8 +823,16 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
|
|||||||
}
|
}
|
||||||
|
|
||||||
[data-modern-ui="true"] .step-anomaly-tip-list,
|
[data-modern-ui="true"] .step-anomaly-tip-list,
|
||||||
[data-modern-ui="true"] .step-anomaly-tip-hint {
|
[data-modern-ui="true"] .step-anomaly-tip-hint,
|
||||||
border-top-color: var(--modern-surface-hover);
|
[data-modern-ui="true"] .quota-rate-pop-head,
|
||||||
|
[data-modern-ui="true"] .quota-rate-pool-group + .quota-rate-pool-group,
|
||||||
|
[data-modern-ui="true"] .quota-rate-model-row + .quota-rate-model-row,
|
||||||
|
[data-modern-ui="true"] .quota-rate-pop-note,
|
||||||
|
:host([data-modern-ui="true"]) .quota-rate-pop-head,
|
||||||
|
:host([data-modern-ui="true"]) .quota-rate-pool-group + .quota-rate-pool-group,
|
||||||
|
:host([data-modern-ui="true"]) .quota-rate-model-row + .quota-rate-model-row,
|
||||||
|
:host([data-modern-ui="true"]) .quota-rate-pop-note {
|
||||||
|
border-color: var(--modern-surface-hover);
|
||||||
}
|
}
|
||||||
|
|
||||||
[data-modern-ui="true"] .trend-tooltip:not(.is-hm-top):not(.is-hm-bottom) {
|
[data-modern-ui="true"] .trend-tooltip:not(.is-hm-top):not(.is-hm-bottom) {
|
||||||
|
|||||||
@@ -645,6 +645,226 @@
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* 可用额度标题旁圈问号触发器及实测倍率预估悬浮卡片 */
|
||||||
|
.quota-panel {
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-help-btn {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
width: 18px;
|
||||||
|
height: 18px;
|
||||||
|
padding: 0;
|
||||||
|
margin-left: -1px;
|
||||||
|
border: none;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: transparent;
|
||||||
|
color: var(--text-muted);
|
||||||
|
cursor: help;
|
||||||
|
flex-shrink: 0;
|
||||||
|
transition:
|
||||||
|
color var(--dur-instant) var(--ease-fast),
|
||||||
|
background-color var(--dur-instant) var(--ease-fast);
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-help-btn:hover,
|
||||||
|
.quota-rate-help-btn:focus-visible,
|
||||||
|
.quota-rate-help-btn.is-open {
|
||||||
|
color: var(--accent-primary);
|
||||||
|
background: var(--accent-primary-soft);
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-popover {
|
||||||
|
position: absolute;
|
||||||
|
top: 38px;
|
||||||
|
left: 12px;
|
||||||
|
width: min(332px, calc(100% - 24px));
|
||||||
|
z-index: 45;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 8px;
|
||||||
|
padding: 10px 12px;
|
||||||
|
background: var(--surface-panel);
|
||||||
|
border: 1px solid var(--border-strong);
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
box-shadow: var(--shadow-popover);
|
||||||
|
color: var(--text-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-popover[hidden] {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-pop-head {
|
||||||
|
display: flex;
|
||||||
|
align-items: baseline;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 10px;
|
||||||
|
min-width: 0;
|
||||||
|
padding-bottom: 6px;
|
||||||
|
border-bottom: 1px solid var(--border-hairline);
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-pop-title {
|
||||||
|
font-size: var(--fs-base-sm);
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--text-primary);
|
||||||
|
white-space: nowrap;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-pop-account {
|
||||||
|
font-family: var(--font-mono);
|
||||||
|
font-size: var(--fs-xs);
|
||||||
|
color: var(--text-muted);
|
||||||
|
white-space: nowrap;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-pop-body {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-pool-group {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-pool-group + .quota-rate-pool-group {
|
||||||
|
padding-top: 7px;
|
||||||
|
border-top: 1px solid var(--border-hairline);
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-pool-label {
|
||||||
|
font-size: var(--fs-2xs);
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-model-list {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 7px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-model-row {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 3px;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-model-row + .quota-rate-model-row {
|
||||||
|
padding-top: 7px;
|
||||||
|
border-top: 1px solid var(--border-hairline);
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-row-top {
|
||||||
|
display: flex;
|
||||||
|
align-items: baseline;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 8px;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-model-left {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: baseline;
|
||||||
|
gap: 6px;
|
||||||
|
min-width: 0;
|
||||||
|
flex: 1 1 auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-model-name {
|
||||||
|
font-size: var(--fs-sm);
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--text-primary);
|
||||||
|
white-space: nowrap;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-model-name.is-muted {
|
||||||
|
color: var(--text-secondary);
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-mult-badge {
|
||||||
|
font-family: var(--font-mono);
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
font-size: var(--fs-xs);
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--text-muted);
|
||||||
|
white-space: nowrap;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-mult-badge.is-high {
|
||||||
|
color: var(--metric-warn);
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-meta {
|
||||||
|
font-size: var(--fs-2xs);
|
||||||
|
color: var(--text-muted);
|
||||||
|
white-space: nowrap;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-eq-grid {
|
||||||
|
display: flex;
|
||||||
|
align-items: baseline;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-eq-grid.is-single {
|
||||||
|
justify-content: flex-start;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-eq-cell {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: baseline;
|
||||||
|
gap: 5px;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-eq-k {
|
||||||
|
font-size: var(--fs-xs);
|
||||||
|
color: var(--text-muted);
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-eq-v {
|
||||||
|
font-size: var(--fs-sm);
|
||||||
|
font-weight: 600;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
color: var(--text-primary);
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-pop-empty {
|
||||||
|
font-size: var(--fs-sm);
|
||||||
|
line-height: 1.5;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-pop-note {
|
||||||
|
padding-top: 6px;
|
||||||
|
border-top: 1px solid var(--border-hairline);
|
||||||
|
font-size: var(--fs-2xs);
|
||||||
|
line-height: 1.45;
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
/* --- 4. 上下文双列图例网格 (Context 10-Channel Legend Grid) --- */
|
/* --- 4. 上下文双列图例网格 (Context 10-Channel Legend Grid) --- */
|
||||||
.ctx-legend-grid {
|
.ctx-legend-grid {
|
||||||
display: grid;
|
display: grid;
|
||||||
|
|||||||
+233
-3
@@ -2363,6 +2363,226 @@ html[data-standalone="true"] .app-shell {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* 可用额度标题旁圈问号触发器及实测倍率预估悬浮卡片 */
|
||||||
|
.quota-panel {
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-help-btn {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
width: 18px;
|
||||||
|
height: 18px;
|
||||||
|
padding: 0;
|
||||||
|
margin-left: -1px;
|
||||||
|
border: none;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: transparent;
|
||||||
|
color: var(--text-muted);
|
||||||
|
cursor: help;
|
||||||
|
flex-shrink: 0;
|
||||||
|
transition:
|
||||||
|
color var(--dur-instant) var(--ease-fast),
|
||||||
|
background-color var(--dur-instant) var(--ease-fast);
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-help-btn:hover,
|
||||||
|
.quota-rate-help-btn:focus-visible,
|
||||||
|
.quota-rate-help-btn.is-open {
|
||||||
|
color: var(--accent-primary);
|
||||||
|
background: var(--accent-primary-soft);
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-popover {
|
||||||
|
position: absolute;
|
||||||
|
top: 38px;
|
||||||
|
left: 12px;
|
||||||
|
width: min(332px, calc(100% - 24px));
|
||||||
|
z-index: 45;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 8px;
|
||||||
|
padding: 10px 12px;
|
||||||
|
background: var(--surface-panel);
|
||||||
|
border: 1px solid var(--border-strong);
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
box-shadow: var(--shadow-popover);
|
||||||
|
color: var(--text-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-popover[hidden] {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-pop-head {
|
||||||
|
display: flex;
|
||||||
|
align-items: baseline;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 10px;
|
||||||
|
min-width: 0;
|
||||||
|
padding-bottom: 6px;
|
||||||
|
border-bottom: 1px solid var(--border-hairline);
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-pop-title {
|
||||||
|
font-size: var(--fs-base-sm);
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--text-primary);
|
||||||
|
white-space: nowrap;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-pop-account {
|
||||||
|
font-family: var(--font-mono);
|
||||||
|
font-size: var(--fs-xs);
|
||||||
|
color: var(--text-muted);
|
||||||
|
white-space: nowrap;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-pop-body {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-pool-group {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-pool-group + .quota-rate-pool-group {
|
||||||
|
padding-top: 7px;
|
||||||
|
border-top: 1px solid var(--border-hairline);
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-pool-label {
|
||||||
|
font-size: var(--fs-2xs);
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-model-list {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 7px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-model-row {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 3px;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-model-row + .quota-rate-model-row {
|
||||||
|
padding-top: 7px;
|
||||||
|
border-top: 1px solid var(--border-hairline);
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-row-top {
|
||||||
|
display: flex;
|
||||||
|
align-items: baseline;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 8px;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-model-left {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: baseline;
|
||||||
|
gap: 6px;
|
||||||
|
min-width: 0;
|
||||||
|
flex: 1 1 auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-model-name {
|
||||||
|
font-size: var(--fs-sm);
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--text-primary);
|
||||||
|
white-space: nowrap;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-model-name.is-muted {
|
||||||
|
color: var(--text-secondary);
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-mult-badge {
|
||||||
|
font-family: var(--font-mono);
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
font-size: var(--fs-xs);
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--text-muted);
|
||||||
|
white-space: nowrap;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-mult-badge.is-high {
|
||||||
|
color: var(--metric-warn);
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-meta {
|
||||||
|
font-size: var(--fs-2xs);
|
||||||
|
color: var(--text-muted);
|
||||||
|
white-space: nowrap;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-eq-grid {
|
||||||
|
display: flex;
|
||||||
|
align-items: baseline;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-eq-grid.is-single {
|
||||||
|
justify-content: flex-start;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-eq-cell {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: baseline;
|
||||||
|
gap: 5px;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-eq-k {
|
||||||
|
font-size: var(--fs-xs);
|
||||||
|
color: var(--text-muted);
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-eq-v {
|
||||||
|
font-size: var(--fs-sm);
|
||||||
|
font-weight: 600;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
color: var(--text-primary);
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-pop-empty {
|
||||||
|
font-size: var(--fs-sm);
|
||||||
|
line-height: 1.5;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.quota-rate-pop-note {
|
||||||
|
padding-top: 6px;
|
||||||
|
border-top: 1px solid var(--border-hairline);
|
||||||
|
font-size: var(--fs-2xs);
|
||||||
|
line-height: 1.45;
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
/* --- 4. 上下文双列图例网格 (Context 10-Channel Legend Grid) --- */
|
/* --- 4. 上下文双列图例网格 (Context 10-Channel Legend Grid) --- */
|
||||||
.ctx-legend-grid {
|
.ctx-legend-grid {
|
||||||
display: grid;
|
display: grid;
|
||||||
@@ -8601,7 +8821,9 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
|
|||||||
[data-modern-ui="true"] .trend-tooltip,
|
[data-modern-ui="true"] .trend-tooltip,
|
||||||
[data-modern-ui="true"] .cons-breakdown-popover,
|
[data-modern-ui="true"] .cons-breakdown-popover,
|
||||||
[data-modern-ui="true"] .turn-prompt-tip,
|
[data-modern-ui="true"] .turn-prompt-tip,
|
||||||
[data-modern-ui="true"] .step-anomaly-tip {
|
[data-modern-ui="true"] .step-anomaly-tip,
|
||||||
|
[data-modern-ui="true"] .quota-rate-popover,
|
||||||
|
:host([data-modern-ui="true"]) .quota-rate-popover {
|
||||||
border: none;
|
border: none;
|
||||||
background: var(--modern-surface-card);
|
background: var(--modern-surface-card);
|
||||||
box-shadow: var(--shadow-popover);
|
box-shadow: var(--shadow-popover);
|
||||||
@@ -8609,8 +8831,16 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
|
|||||||
}
|
}
|
||||||
|
|
||||||
[data-modern-ui="true"] .step-anomaly-tip-list,
|
[data-modern-ui="true"] .step-anomaly-tip-list,
|
||||||
[data-modern-ui="true"] .step-anomaly-tip-hint {
|
[data-modern-ui="true"] .step-anomaly-tip-hint,
|
||||||
border-top-color: var(--modern-surface-hover);
|
[data-modern-ui="true"] .quota-rate-pop-head,
|
||||||
|
[data-modern-ui="true"] .quota-rate-pool-group + .quota-rate-pool-group,
|
||||||
|
[data-modern-ui="true"] .quota-rate-model-row + .quota-rate-model-row,
|
||||||
|
[data-modern-ui="true"] .quota-rate-pop-note,
|
||||||
|
:host([data-modern-ui="true"]) .quota-rate-pop-head,
|
||||||
|
:host([data-modern-ui="true"]) .quota-rate-pool-group + .quota-rate-pool-group,
|
||||||
|
:host([data-modern-ui="true"]) .quota-rate-model-row + .quota-rate-model-row,
|
||||||
|
:host([data-modern-ui="true"]) .quota-rate-pop-note {
|
||||||
|
border-color: var(--modern-surface-hover);
|
||||||
}
|
}
|
||||||
|
|
||||||
[data-modern-ui="true"] .trend-tooltip:not(.is-hm-top):not(.is-hm-bottom) {
|
[data-modern-ui="true"] .trend-tooltip:not(.is-hm-top):not(.is-hm-bottom) {
|
||||||
|
|||||||
@@ -312,6 +312,27 @@ test('telemetryStore isEquivalentTelemetry detects quota changes in non-active p
|
|||||||
const d = structuredClone(a);
|
const d = structuredClone(a);
|
||||||
d.quotas.pools[0].cycle5h = { tokens: 50_000, costUsd: 0.15, calls: 2 };
|
d.quotas.pools[0].cycle5h = { tokens: 50_000, costUsd: 0.15, calls: 2 };
|
||||||
assert.equal(ctx.compare(a, d), false, 'Pool cycle5h change must trigger store update');
|
assert.equal(ctx.compare(a, d), false, 'Pool cycle5h change must trigger store update');
|
||||||
|
const e = structuredClone(a);
|
||||||
|
e.quotas.pools[0].rateEstimate = {
|
||||||
|
rate5hPctPerUsd: 2,
|
||||||
|
rateWeeklyPctPerUsd: 0.5,
|
||||||
|
eqFull5hUsd: 50,
|
||||||
|
eqFullWeeklyUsd: 200,
|
||||||
|
samples5h: 6,
|
||||||
|
samplesWeekly: 6,
|
||||||
|
models: [
|
||||||
|
{
|
||||||
|
model: 'Gemini 4 Carbon',
|
||||||
|
rate5hPctPerUsd: 2,
|
||||||
|
rateWeeklyPctPerUsd: 0.5,
|
||||||
|
eqFull5hUsd: 50,
|
||||||
|
eqFullWeeklyUsd: 200,
|
||||||
|
multiplier: 3,
|
||||||
|
samples: 6,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
assert.equal(ctx.compare(a, e), false, 'Pool rateEstimate change must trigger store update');
|
||||||
assert.equal(ctx.compare(a, structuredClone(a)), true);
|
assert.equal(ctx.compare(a, structuredClone(a)), true);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1028,3 +1028,446 @@ test('QuotaPoolsWidget & SettingsOtherTab render experimental reservation bar/te
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('quota-reservation: learns per-model burn rates & 3x/1x multipliers with strict account isolation and persistence', () => {
|
||||||
|
let storedPayload = null;
|
||||||
|
const tracker = createQuotaReservationTracker({
|
||||||
|
loadState: () => storedPayload,
|
||||||
|
saveState: (payload) => {
|
||||||
|
storedPayload = JSON.parse(JSON.stringify(payload));
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const makePools = (used5h, usedWk) =>
|
||||||
|
new Map([
|
||||||
|
[
|
||||||
|
'Gemini',
|
||||||
|
{
|
||||||
|
poolKey: 'Gemini',
|
||||||
|
has5h: true,
|
||||||
|
hasWeekly: true,
|
||||||
|
remainingFraction: 1 - used5h / 100,
|
||||||
|
usedPct: used5h,
|
||||||
|
resetTime: new Date(RESET_5H).toISOString(),
|
||||||
|
weeklyRemainingFraction: 1 - usedWk / 100,
|
||||||
|
weeklyUsedPct: usedWk,
|
||||||
|
weeklyResetTime: new Date(RESET_WK).toISOString(),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
]);
|
||||||
|
|
||||||
|
const makeStats = (cost5h, costWk, modelCosts5h, modelCostsWeekly, ts) =>
|
||||||
|
new Map([
|
||||||
|
[
|
||||||
|
'Gemini',
|
||||||
|
{
|
||||||
|
cycle5h: { costUsd: cost5h, unpricedCalls: 0 },
|
||||||
|
cycleWeekly: { costUsd: costWk, unpricedCalls: 0 },
|
||||||
|
exactCost5hUsd: cost5h,
|
||||||
|
exactCostWeeklyUsd: costWk,
|
||||||
|
modelCosts5h,
|
||||||
|
modelCostsWeekly,
|
||||||
|
recent10m: { lastActivityMs: ts, activeSessionCount: 1, costUsd: 0.1 },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
]);
|
||||||
|
|
||||||
|
let ts = T0;
|
||||||
|
let u5 = 10.0;
|
||||||
|
let uw = 20.0;
|
||||||
|
let carbonCost = 1.0;
|
||||||
|
let neonCost = 0.0;
|
||||||
|
|
||||||
|
// Baseline for Account A
|
||||||
|
const p0 = makePools(u5, uw);
|
||||||
|
tracker.updatePools({
|
||||||
|
endpointId: 'local',
|
||||||
|
accountScope: 'alice@example.com',
|
||||||
|
quotaPoolsMap: p0,
|
||||||
|
poolCycleStats: makeStats(
|
||||||
|
carbonCost,
|
||||||
|
carbonCost,
|
||||||
|
{ 'Gemini 4 Carbon': carbonCost },
|
||||||
|
{ 'Gemini 4 Carbon': carbonCost },
|
||||||
|
ts
|
||||||
|
),
|
||||||
|
quotaFetchedAtMs: ts,
|
||||||
|
nowMs: ts,
|
||||||
|
});
|
||||||
|
assert.equal(p0.get('Gemini').rateEstimate, null);
|
||||||
|
|
||||||
|
// 3 clean single-model steps on Carbon: 2.0 %/$ (5h), 0.5 %/$ (weekly)
|
||||||
|
let latestPool = null;
|
||||||
|
for (let i = 0; i < 3; i += 1) {
|
||||||
|
ts += 15_000;
|
||||||
|
carbonCost = +(carbonCost + 0.1).toFixed(6);
|
||||||
|
u5 = +(u5 + 0.2).toFixed(6);
|
||||||
|
uw = +(uw + 0.05).toFixed(6);
|
||||||
|
latestPool = makePools(u5, uw);
|
||||||
|
tracker.updatePools({
|
||||||
|
endpointId: 'local',
|
||||||
|
accountScope: 'alice@example.com',
|
||||||
|
quotaPoolsMap: latestPool,
|
||||||
|
poolCycleStats: makeStats(
|
||||||
|
carbonCost,
|
||||||
|
carbonCost,
|
||||||
|
{ 'Gemini 4 Carbon': carbonCost },
|
||||||
|
{ 'Gemini 4 Carbon': carbonCost },
|
||||||
|
ts
|
||||||
|
),
|
||||||
|
quotaFetchedAtMs: ts,
|
||||||
|
nowMs: ts,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const estCarbonOnly = latestPool.get('Gemini').rateEstimate;
|
||||||
|
assert.ok(estCarbonOnly, 'rateEstimate appears once 3 clean single-model steps are recorded');
|
||||||
|
assert.equal(estCarbonOnly.models.length, 1);
|
||||||
|
assert.equal(estCarbonOnly.models[0].model, 'Gemini 4 Carbon');
|
||||||
|
assert.equal(estCarbonOnly.models[0].rate5hPctPerUsd, 2);
|
||||||
|
assert.equal(estCarbonOnly.models[0].rateWeeklyPctPerUsd, 0.5);
|
||||||
|
assert.equal(estCarbonOnly.models[0].eqFull5hUsd, 50);
|
||||||
|
assert.equal(estCarbonOnly.models[0].eqFullWeeklyUsd, 200);
|
||||||
|
assert.equal(estCarbonOnly.models[0].multiplier, null, 'single model does not emit relative multiplier');
|
||||||
|
assert.equal(estCarbonOnly.models[0].samples, 3);
|
||||||
|
|
||||||
|
// 3 clean single-model steps on Neon: 0.6667 %/$ (5h), 0.1667 %/$ (weekly) -> 1:3 relative ratio
|
||||||
|
for (let i = 0; i < 3; i += 1) {
|
||||||
|
ts += 15_000;
|
||||||
|
neonCost = +(neonCost + 0.15).toFixed(6);
|
||||||
|
u5 = +(u5 + 0.1).toFixed(6);
|
||||||
|
uw = +(uw + 0.025).toFixed(6);
|
||||||
|
latestPool = makePools(u5, uw);
|
||||||
|
tracker.updatePools({
|
||||||
|
endpointId: 'local',
|
||||||
|
accountScope: 'alice@example.com',
|
||||||
|
quotaPoolsMap: latestPool,
|
||||||
|
poolCycleStats: makeStats(
|
||||||
|
carbonCost + neonCost,
|
||||||
|
carbonCost + neonCost,
|
||||||
|
{ 'Gemini 4 Carbon': carbonCost, 'Gemini 4 Neon': neonCost },
|
||||||
|
{ 'Gemini 4 Carbon': carbonCost, 'Gemini 4 Neon': neonCost },
|
||||||
|
ts
|
||||||
|
),
|
||||||
|
quotaFetchedAtMs: ts,
|
||||||
|
nowMs: ts,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const estDual = latestPool.get('Gemini').rateEstimate;
|
||||||
|
assert.equal(estDual.models.length, 2);
|
||||||
|
assert.equal(estDual.models[0].model, 'Gemini 4 Carbon');
|
||||||
|
assert.equal(estDual.models[0].multiplier, 3);
|
||||||
|
assert.equal(estDual.models[0].eqFull5hUsd, 50);
|
||||||
|
assert.equal(estDual.models[0].eqFullWeeklyUsd, 200);
|
||||||
|
assert.equal(estDual.models[1].model, 'Gemini 4 Neon');
|
||||||
|
assert.equal(estDual.models[1].multiplier, 1);
|
||||||
|
assert.equal(estDual.models[1].eqFull5hUsd, 150);
|
||||||
|
assert.equal(estDual.models[1].eqFullWeeklyUsd, 600);
|
||||||
|
|
||||||
|
// Mixed-model step ($0.10 Carbon + $0.15 Neon -> +0.30% 5h, +0.075% weekly):
|
||||||
|
// weighted expected matches official (no false lease) and does not pollute per-model sample counts
|
||||||
|
ts += 15_000;
|
||||||
|
carbonCost = +(carbonCost + 0.1).toFixed(6);
|
||||||
|
neonCost = +(neonCost + 0.15).toFixed(6);
|
||||||
|
u5 = +(u5 + 0.3).toFixed(6);
|
||||||
|
uw = +(uw + 0.075).toFixed(6);
|
||||||
|
const pMixed = makePools(u5, uw);
|
||||||
|
tracker.updatePools({
|
||||||
|
endpointId: 'local',
|
||||||
|
accountScope: 'alice@example.com',
|
||||||
|
quotaPoolsMap: pMixed,
|
||||||
|
poolCycleStats: makeStats(
|
||||||
|
carbonCost + neonCost,
|
||||||
|
carbonCost + neonCost,
|
||||||
|
{ 'Gemini 4 Carbon': carbonCost, 'Gemini 4 Neon': neonCost },
|
||||||
|
{ 'Gemini 4 Carbon': carbonCost, 'Gemini 4 Neon': neonCost },
|
||||||
|
ts
|
||||||
|
),
|
||||||
|
quotaFetchedAtMs: ts,
|
||||||
|
nowMs: ts,
|
||||||
|
});
|
||||||
|
assert.equal(pMixed.get('Gemini').reservedPct, 0);
|
||||||
|
assert.equal(pMixed.get('Gemini').rateEstimate.models[0].samples, 3);
|
||||||
|
assert.equal(pMixed.get('Gemini').rateEstimate.models[1].samples, 3);
|
||||||
|
|
||||||
|
// Strict account isolation: Account B sees null (no cross-account leakage);
|
||||||
|
// case-insensitive Account A lookup still sees its own calibrated estimates
|
||||||
|
ts += 15_000;
|
||||||
|
const pBob = makePools(5.0, 10.0);
|
||||||
|
tracker.updatePools({
|
||||||
|
endpointId: 'local',
|
||||||
|
accountScope: 'bob@example.com',
|
||||||
|
quotaPoolsMap: pBob,
|
||||||
|
poolCycleStats: makeStats(0.5, 0.5, { 'Gemini 4 Carbon': 0.5 }, { 'Gemini 4 Carbon': 0.5 }, ts),
|
||||||
|
quotaFetchedAtMs: ts,
|
||||||
|
nowMs: ts,
|
||||||
|
});
|
||||||
|
assert.equal(pBob.get('Gemini').rateEstimate, null, 'other account must not inherit Alice rates');
|
||||||
|
|
||||||
|
// Force a persist tick past QR_PERSIST_MIN_INTERVAL_MS and test reload across restart
|
||||||
|
ts += 40_000;
|
||||||
|
carbonCost = +(carbonCost + 0.1).toFixed(6);
|
||||||
|
u5 = +(u5 + 0.2).toFixed(6);
|
||||||
|
uw = +(uw + 0.05).toFixed(6);
|
||||||
|
const pAliceCase = makePools(u5, uw);
|
||||||
|
tracker.updatePools({
|
||||||
|
endpointId: 'local',
|
||||||
|
accountScope: 'ALICE@EXAMPLE.COM',
|
||||||
|
quotaPoolsMap: pAliceCase,
|
||||||
|
poolCycleStats: makeStats(
|
||||||
|
carbonCost + neonCost,
|
||||||
|
carbonCost + neonCost,
|
||||||
|
{ 'Gemini 4 Carbon': carbonCost, 'Gemini 4 Neon': neonCost },
|
||||||
|
{ 'Gemini 4 Carbon': carbonCost, 'Gemini 4 Neon': neonCost },
|
||||||
|
ts
|
||||||
|
),
|
||||||
|
quotaFetchedAtMs: ts,
|
||||||
|
nowMs: ts,
|
||||||
|
});
|
||||||
|
assert.equal(pAliceCase.get('Gemini').rateEstimate.models[0].samples, 4);
|
||||||
|
|
||||||
|
const reloaded = createQuotaReservationTracker({ loadState: () => storedPayload });
|
||||||
|
const pReloadAlice = makePools(u5, uw);
|
||||||
|
reloaded.updatePools({
|
||||||
|
endpointId: 'local',
|
||||||
|
accountScope: 'alice@example.com',
|
||||||
|
quotaPoolsMap: pReloadAlice,
|
||||||
|
poolCycleStats: makeStats(
|
||||||
|
carbonCost + neonCost,
|
||||||
|
carbonCost + neonCost,
|
||||||
|
{ 'Gemini 4 Carbon': carbonCost, 'Gemini 4 Neon': neonCost },
|
||||||
|
{ 'Gemini 4 Carbon': carbonCost, 'Gemini 4 Neon': neonCost },
|
||||||
|
ts
|
||||||
|
),
|
||||||
|
quotaFetchedAtMs: ts,
|
||||||
|
nowMs: ts,
|
||||||
|
});
|
||||||
|
assert.equal(pReloadAlice.get('Gemini').rateEstimate.models.length, 2);
|
||||||
|
assert.equal(pReloadAlice.get('Gemini').rateEstimate.models[0].multiplier, 3);
|
||||||
|
assert.equal(pReloadAlice.get('Gemini').rateEstimate.models[1].multiplier, 1);
|
||||||
|
|
||||||
|
const snap = reloaded.getLogSnapshot();
|
||||||
|
const alice5h = snap.buckets.find((b) => b.pool === 'Gemini' && b.win === '5h' && b.byModel);
|
||||||
|
assert.ok(alice5h?.byModel?.['Gemini 4 Carbon'], 'snapshot exposes per-model summary');
|
||||||
|
assert.equal(alice5h.byModel['Gemini 4 Carbon'].eqFullUsd, 50);
|
||||||
|
|
||||||
|
const pReloadBob = makePools(5.0, 10.0);
|
||||||
|
reloaded.updatePools({
|
||||||
|
endpointId: 'local',
|
||||||
|
accountScope: 'bob@example.com',
|
||||||
|
quotaPoolsMap: pReloadBob,
|
||||||
|
poolCycleStats: makeStats(0.5, 0.5, { 'Gemini 4 Carbon': 0.5 }, { 'Gemini 4 Carbon': 0.5 }, ts),
|
||||||
|
quotaFetchedAtMs: ts,
|
||||||
|
nowMs: ts,
|
||||||
|
});
|
||||||
|
assert.equal(pReloadBob.get('Gemini').rateEstimate, null, 'account isolation preserved after restart');
|
||||||
|
|
||||||
|
// Legacy v2 persisted bucket missing lastModelCostsUsd must not pollute modelRates on first upgrade tick
|
||||||
|
const legacyV2 = createQuotaReservationTracker({
|
||||||
|
loadState: () => ({
|
||||||
|
version: 2,
|
||||||
|
savedAt: new Date(T0).toISOString(),
|
||||||
|
buckets: {
|
||||||
|
'local::legacy@example.com::Gemini::5h': {
|
||||||
|
resetTimeMs: RESET_5H,
|
||||||
|
lastQuotaTs: T0,
|
||||||
|
lastOfficialUsedPct: 12.0,
|
||||||
|
lastCycleCostUsd: 18.0,
|
||||||
|
ratePctPerUsd: 0.6667,
|
||||||
|
rateSamples: 10,
|
||||||
|
rateWindow: [0.6667, 0.6667, 0.6667],
|
||||||
|
activeLeases: [],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
events: [],
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
const tUp = T0 + 15_000;
|
||||||
|
const pUp = makePools(12.2, 20.0);
|
||||||
|
legacyV2.updatePools({
|
||||||
|
endpointId: 'local',
|
||||||
|
accountScope: 'legacy@example.com',
|
||||||
|
quotaPoolsMap: pUp,
|
||||||
|
poolCycleStats: makeStats(18.1, 18.1, { 'Gemini 4 Carbon': 18.1 }, { 'Gemini 4 Carbon': 18.1 }, tUp),
|
||||||
|
quotaFetchedAtMs: tUp,
|
||||||
|
nowMs: tUp,
|
||||||
|
});
|
||||||
|
const legacySt = legacyV2._buckets.get('local::legacy@example.com::Gemini::5h');
|
||||||
|
assert.deepEqual(legacySt.modelRates, {}, 'first upgrade tick backfills baseline without recording polluted cumulative delta');
|
||||||
|
assert.equal(legacySt.lastModelCostsUsd['Gemini 4 Carbon'], 18.1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('QuotaPoolsWidget renders circle-? hover popover for account-isolated model burn rates', async () => {
|
||||||
|
const { document } = createMockDom();
|
||||||
|
const origDocument = globalThis.document;
|
||||||
|
const origWindow = globalThis.window;
|
||||||
|
globalThis.document = document;
|
||||||
|
globalThis.window = {
|
||||||
|
innerWidth: 960,
|
||||||
|
innerHeight: 720,
|
||||||
|
addEventListener() {},
|
||||||
|
removeEventListener() {},
|
||||||
|
location: { origin: 'http://127.0.0.1:0', href: 'http://127.0.0.1:0/' },
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
const [{ setI18nLanguage }, { QuotaPoolsWidget, maskAccountLabel }] = await Promise.all([
|
||||||
|
import('../src/i18n/index.js'),
|
||||||
|
import('../src/components/widgets/QuotaPoolsWidget.js'),
|
||||||
|
]);
|
||||||
|
setI18nLanguage('zh-CN');
|
||||||
|
|
||||||
|
// Account privacy masking
|
||||||
|
assert.equal(maskAccountLabel('sjee80343@gmail.com'), 'sj***43@gmail.com');
|
||||||
|
assert.equal(maskAccountLabel('alice@example.com'), 'al***ce@example.com');
|
||||||
|
assert.equal(maskAccountLabel('bob@example.com'), 'b***b@example.com');
|
||||||
|
assert.equal(maskAccountLabel('ab@example.com'), 'a*@example.com');
|
||||||
|
assert.equal(maskAccountLabel('Tester'), 'Te***r');
|
||||||
|
assert.equal(maskAccountLabel(''), '');
|
||||||
|
|
||||||
|
const widget = QuotaPoolsWidget();
|
||||||
|
const helpBtn = widget.refs.rateHelpBtn;
|
||||||
|
const popover = widget.refs.ratePopoverEl;
|
||||||
|
assert.ok(helpBtn, 'circle-? help button mounted');
|
||||||
|
assert.ok(popover, 'rate popover mounted');
|
||||||
|
assert.equal(popover.hidden, true);
|
||||||
|
assert.equal(helpBtn.getAttribute('aria-expanded'), 'false');
|
||||||
|
|
||||||
|
// Hover opens empty collecting hint before samples accumulate
|
||||||
|
helpBtn.dispatchEvent({ type: 'mouseenter' });
|
||||||
|
assert.equal(popover.hidden, false);
|
||||||
|
assert.equal(helpBtn.getAttribute('aria-expanded'), 'true');
|
||||||
|
assert.match(popover.textContent, /暂未采集到足够的单模型干净样本/);
|
||||||
|
|
||||||
|
// Populated multi-model rateEstimate for current account
|
||||||
|
const dualData = {
|
||||||
|
account: { email: 'sjee80343@gmail.com', tierName: 'Google AI Ultra', tierMultiplier: '5x' },
|
||||||
|
quotas: {
|
||||||
|
pools: [
|
||||||
|
{
|
||||||
|
poolKey: 'Gemini',
|
||||||
|
poolLabel: 'Gemini',
|
||||||
|
family: 'Gemini',
|
||||||
|
usedPct: 30,
|
||||||
|
remainingPct: 70,
|
||||||
|
weeklyUsedPct: 37,
|
||||||
|
weeklyRemainingPct: 63,
|
||||||
|
rateEstimate: {
|
||||||
|
rate5hPctPerUsd: 2,
|
||||||
|
rateWeeklyPctPerUsd: 0.5,
|
||||||
|
eqFull5hUsd: 50,
|
||||||
|
eqFullWeeklyUsd: 200,
|
||||||
|
samples5h: 26,
|
||||||
|
samplesWeekly: 32,
|
||||||
|
models: [
|
||||||
|
{
|
||||||
|
model: 'Gemini 4 Carbon',
|
||||||
|
rate5hPctPerUsd: 2,
|
||||||
|
rateWeeklyPctPerUsd: 0.5,
|
||||||
|
eqFull5hUsd: 50,
|
||||||
|
eqFullWeeklyUsd: 200,
|
||||||
|
multiplier: 3,
|
||||||
|
samples: 26,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
model: 'Gemini 4 Neon',
|
||||||
|
rate5hPctPerUsd: 0.6667,
|
||||||
|
rateWeeklyPctPerUsd: 0.1667,
|
||||||
|
eqFull5hUsd: 150,
|
||||||
|
eqFullWeeklyUsd: 600,
|
||||||
|
multiplier: 1,
|
||||||
|
samples: 12,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
weekly: { isOfficial: true },
|
||||||
|
},
|
||||||
|
};
|
||||||
|
widget.refs.update({ data: dualData, minuteTick: 1 });
|
||||||
|
const acctPill = popover.querySelector('.quota-rate-pop-account');
|
||||||
|
assert.equal(acctPill.textContent, 'sj***43@gmail.com');
|
||||||
|
assert.equal(acctPill.getAttribute('title'), 'sj***43@gmail.com');
|
||||||
|
assert.equal(popover.textContent.includes('sjee80343'), false, 'raw email never leaks in popover');
|
||||||
|
const rows = popover.querySelectorAll('.quota-rate-model-row');
|
||||||
|
assert.equal(rows.length, 2);
|
||||||
|
assert.match(rows[0].textContent, /Gemini 4 Carbon/);
|
||||||
|
assert.match(rows[0].textContent, /3x/);
|
||||||
|
assert.match(rows[0].textContent, /5h 满池≈ \$50/);
|
||||||
|
assert.match(rows[0].textContent, /周限满池≈ \$200/);
|
||||||
|
assert.match(rows[0].textContent, /5h 2%\/\$ · 26 样本/);
|
||||||
|
assert.equal(rows[0].querySelector('.quota-rate-mult-badge').classList.contains('is-high'), true);
|
||||||
|
assert.equal(rows[0].querySelector('.quota-rate-eq-grid').classList.contains('is-single'), false);
|
||||||
|
|
||||||
|
assert.match(rows[1].textContent, /Gemini 4 Neon/);
|
||||||
|
assert.match(rows[1].textContent, /1x/);
|
||||||
|
assert.match(rows[1].textContent, /5h 满池≈ \$150/);
|
||||||
|
assert.match(rows[1].textContent, /周限满池≈ \$600/);
|
||||||
|
assert.match(rows[1].textContent, /5h 0\.67%\/\$ · 12 样本/);
|
||||||
|
assert.equal(rows[1].querySelector('.quota-rate-mult-badge').classList.contains('is-high'), false);
|
||||||
|
|
||||||
|
// Switching to another account with pool-average-only fallback refreshes popover cleanly
|
||||||
|
widget.refs.update({
|
||||||
|
data: {
|
||||||
|
account: { email: 'bob@example.com', tierName: 'Google AI Pro' },
|
||||||
|
quotas: {
|
||||||
|
pools: [
|
||||||
|
{
|
||||||
|
poolKey: 'Argon',
|
||||||
|
poolLabel: 'Gemini 4 Argon',
|
||||||
|
family: 'Argon',
|
||||||
|
weeklyUsedPct: 40,
|
||||||
|
weeklyRemainingPct: 60,
|
||||||
|
rateEstimate: {
|
||||||
|
rate5hPctPerUsd: null,
|
||||||
|
rateWeeklyPctPerUsd: 0.5,
|
||||||
|
eqFull5hUsd: null,
|
||||||
|
eqFullWeeklyUsd: 200,
|
||||||
|
samples5h: 0,
|
||||||
|
samplesWeekly: 8,
|
||||||
|
models: [],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
weekly: { isOfficial: true },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
minuteTick: 2,
|
||||||
|
});
|
||||||
|
assert.equal(acctPill.textContent, 'b***b@example.com');
|
||||||
|
const fallbackRow = popover.querySelector('.quota-rate-model-row.is-fallback');
|
||||||
|
assert.ok(fallbackRow, 'renders pool-average fallback before per-model reaches 3 samples');
|
||||||
|
assert.match(fallbackRow.textContent, /池综合均值/);
|
||||||
|
assert.match(fallbackRow.textContent, /周限满池≈ \$200/);
|
||||||
|
assert.match(fallbackRow.textContent, /周限 0\.5%\/\$ · 8 样本/);
|
||||||
|
assert.equal(fallbackRow.querySelector('.quota-rate-eq-grid').classList.contains('is-single'), true);
|
||||||
|
|
||||||
|
// Locale switch renders English copy
|
||||||
|
setI18nLanguage('en-US');
|
||||||
|
widget.refs.update({ data: dualData, minuteTick: 3 });
|
||||||
|
assert.match(popover.textContent, /Estimated Burn Rates/);
|
||||||
|
assert.equal(acctPill.textContent, 'sj***43@gmail.com');
|
||||||
|
assert.match(popover.textContent, /5h full≈ \$50/);
|
||||||
|
assert.match(popover.textContent, /Weekly full≈ \$200/);
|
||||||
|
|
||||||
|
// Escape closes popover; click toggles open/close; mouseleave closes after grace delay
|
||||||
|
helpBtn.dispatchEvent({ type: 'keydown', key: 'Escape', stopPropagation() {} });
|
||||||
|
assert.equal(popover.hidden, true);
|
||||||
|
helpBtn.dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||||
|
assert.equal(popover.hidden, false);
|
||||||
|
helpBtn.dispatchEvent({ type: 'mouseleave' });
|
||||||
|
popover.dispatchEvent({ type: 'mouseenter' });
|
||||||
|
await new Promise((r) => setTimeout(r, 160));
|
||||||
|
assert.equal(popover.hidden, false, 'moving pointer into popover cancels close');
|
||||||
|
popover.dispatchEvent({ type: 'mouseleave' });
|
||||||
|
await new Promise((r) => setTimeout(r, 170));
|
||||||
|
assert.equal(popover.hidden, true, 'leaving popover closes after grace delay');
|
||||||
|
|
||||||
|
widget.destroy();
|
||||||
|
} finally {
|
||||||
|
globalThis.document = origDocument;
|
||||||
|
globalThis.window = origWindow;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user