From 4fb7ec49582a90aa525380ecc63d04db16b9a998 Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Tue, 24 Nov 2026 11:24:45 +0900 Subject: [PATCH] feat(panel): add 3-tier weekly quota capacity and token estimates - Add a 3-tier pool burn-rate estimator (rolling median calibration, Theil-Sen net-burn slope, and solo cycle ratio) with cross-reset priced token density tracking to derive full-pool USD and token capacities plus account-wide weeklyCapacityEstimate - Render the Est. Weekly Quota summary banner, preliminary/partial badges, full-pool token equivalents, supplementary weekly fallback rows, and pool header capacity tooltips in QuotaPoolsWidget - Coalesce multi-pool state persistence across 5h/weekly buckets, suppress post-refund idle replica rebounds, and clamp externalUsedPct to physical local-spend bounds --- sidecars/panel/app.js | 325 ++++++- sidecars/panel/backend/quota-reservation.mjs | 774 ++++++++++++--- sidecars/panel/backend/telemetry-builder.mjs | 131 ++- sidecars/panel/backend/usage-aggregator.mjs | 36 + sidecars/panel/index.html | 4 +- .../components/widgets/QuotaPoolsWidget.js | 299 +++++- sidecars/panel/src/i18n/en-US.js | 10 +- sidecars/panel/src/i18n/zh-CN.js | 10 +- sidecars/panel/src/store/telemetryStore.js | 6 + sidecars/panel/src/styles/modern-ui.css | 2 + sidecars/panel/src/styles/views-overview.css | 73 +- sidecars/panel/styles.css | 75 +- .../panel/test/quota-reservation.test.mjs | 900 ++++++++++++++++++ 13 files changed, 2415 insertions(+), 230 deletions(-) diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index ee2e004..09fc263 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -1449,6 +1449,7 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'quota.cycle5hTitle': '当前 5h 周期累计 ({pool}):{tok} Tokens · {cost} · {calls} 次调用', 'quota.cycleWkCustomTitle': '本周自然周累计:{tok} Tokens · {cost} · {calls} 次调用', 'quota.cycleWkPoolTitle': '当前周限周期累计 ({pool}):{tok} Tokens · {cost} · {calls} 次调用', + 'quota.cycleFullSuffix': '满池约 {full}', 'quota.footTokensCustom': '本周累计: {tok} ({cost})', 'quota.footTokensCycle': '周期累计: {tok} ({cost})', 'quota.footCredits': 'AI 积分: {credits}', @@ -1460,13 +1461,18 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'quota.ratePopTitle': '实测倍率预估', 'quota.ratePopAccountScope': '{account}', 'quota.ratePopAccountCurrent': '当前账号', + 'quota.ratePopWkCapTitle': '预测周额度', + 'quota.ratePopWkCapPrelim': '· 初估', + 'quota.ratePopWkCapPartial': '· {ready}/{total} 池', 'quota.ratePopPoolFallback': '池综合均值', 'quota.ratePopEq5hLabel': '5h 满池', 'quota.ratePopEqWkLabel': '周限满池', 'quota.ratePopPerUsd': '{win} {rate}%/$', 'quota.ratePopSamples': '{n} 样本', - 'quota.ratePopEmpty': '暂未采集到足够的单模型干净样本(每模型需至少 3 次无抖动扣费),正常使用后自动生成。', - 'quota.ratePopNote': '按单模型纯净步实测折算,同池最省为 1x,按账号隔离。', + 'quota.ratePopPrelimSlope': '斜率初估', + 'quota.ratePopPrelimCycle': '周期初估', + 'quota.ratePopEmpty': '暂未采集到足够的单模型干净样本(周限满 2% 或单模型满 3 次无抖动扣费后自动生成)。', + 'quota.ratePopNote': '按净消耗及精确计价折算,同池最省为 1x,按账号隔离。', 'quota.ratePopSharedBadge': '共享活跃', 'quota.ratePopSharedBadgeTip': '最近 15 分钟内检测到同池外部消耗,新增预占将在二次验证后展示', 'quota.ratePopExternalDetail': '检测到家庭组 / 其他设备消耗(已排除约 {detail}),不计入预占', @@ -2343,6 +2349,7 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'quota.cycle5hTitle': 'Current 5h cycle ({pool}): {tok} Tokens · {cost} · {calls} calls', 'quota.cycleWkCustomTitle': 'Current calendar week: {tok} Tokens · {cost} · {calls} calls', 'quota.cycleWkPoolTitle': 'Current weekly cycle ({pool}): {tok} Tokens · {cost} · {calls} calls', + 'quota.cycleFullSuffix': 'Full ~{full}', 'quota.footTokensCustom': 'Week Total: {tok} ({cost})', 'quota.footTokensCycle': 'Cycle Total: {tok} ({cost})', 'quota.footCredits': 'AI Credits: {credits}', @@ -2354,13 +2361,18 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'quota.ratePopTitle': 'Estimated Burn Rates', 'quota.ratePopAccountScope': '{account}', 'quota.ratePopAccountCurrent': 'Current account', + 'quota.ratePopWkCapTitle': 'Est. Weekly Quota', + 'quota.ratePopWkCapPrelim': '· est.', + 'quota.ratePopWkCapPartial': '· {ready}/{total} pools', '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.', + 'quota.ratePopPrelimSlope': 'slope est.', + 'quota.ratePopPrelimCycle': 'cycle est.', + 'quota.ratePopEmpty': 'Not enough clean samples yet (unlocks at 2% weekly burn or 3 clean single-model steps).', + 'quota.ratePopNote': 'Measured from net burn & priced steps; lowest in pool = 1x. Account isolated.', 'quota.ratePopSharedBadge': 'Shared active', 'quota.ratePopSharedBadgeTip': 'External pool usage seen within 15 min; new reservations display after verification', 'quota.ratePopExternalDetail': 'Family group / other-device usage detected (~{detail} excluded from reservations)', @@ -9936,6 +9948,12 @@ function isEquivalentTelemetry(prev, next) { return false; } } + if ( + JSON.stringify(prev.quotas?.weeklyCapacityEstimate || null) !== + JSON.stringify(next.quotas?.weeklyCapacityEstimate || null) + ) { + return false; + } const pConvs = prev.conversations || []; const nConvs = next.conversations || []; @@ -19298,21 +19316,24 @@ function syncPoolQuotaRow(refs, item, idx, rowEl) { patchText(refs.title5h, `5h (${poolLabel})`); const c5h = poolData?.cycle5h; + const est = poolData?.rateEstimate; if (!isPending && has5h && c5h && (c5h.tokens != null || c5h.costUsd != null)) { const tok5h = formatTokens(c5h.tokens || 0); const cost5h = formatUsd(c5h.costUsd || 0); const calls5h = Number(c5h.calls || 0); + const full5hRef = formatPoolFullCapRef(est?.eqFull5hUsd, est?.eqFull5hTokens); + const baseTip5h = t('quota.cycle5hTitle', { + pool: poolLabel, + tok: tok5h, + cost: cost5h, + calls: calls5h, + }); refs.usage5h.hidden = false; patchText(refs.usage5h, `· ${tok5h} (${cost5h})`); patchAttr( refs.left5h, 'title', - t('quota.cycle5hTitle', { - pool: poolLabel, - tok: tok5h, - cost: cost5h, - calls: calls5h, - }) + full5hRef ? `${baseTip5h} · ${t('quota.cycleFullSuffix', { full: full5hRef })}` : baseTip5h ); } else { refs.usage5h.hidden = true; @@ -19345,19 +19366,23 @@ function syncPoolQuotaRow(refs, item, idx, rowEl) { const tokWk = formatTokens(cWk.tokens || 0); const costWk = formatUsd(cWk.costUsd || 0); const callsWk = Number(cWk.calls || 0); + const fullWkRef = !useCustomWeekly + ? formatPoolFullCapRef(est?.eqFullWeeklyUsd, est?.eqFullWeeklyTokens) + : ''; + const baseTipWk = useCustomWeekly + ? t('quota.cycleWkCustomTitle', { tok: tokWk, cost: costWk, calls: callsWk }) + : t('quota.cycleWkPoolTitle', { + pool: poolLabel, + tok: tokWk, + cost: costWk, + calls: callsWk, + }); refs.usageWk.hidden = false; patchText(refs.usageWk, `· ${tokWk} (${costWk})`); patchAttr( refs.leftWk, 'title', - useCustomWeekly - ? t('quota.cycleWkCustomTitle', { tok: tokWk, cost: costWk, calls: callsWk }) - : t('quota.cycleWkPoolTitle', { - pool: poolLabel, - tok: tokWk, - cost: costWk, - calls: callsWk, - }) + fullWkRef ? `${baseTipWk} · ${t('quota.cycleFullSuffix', { full: fullWkRef })}` : baseTipWk ); } else { refs.usageWk.hidden = true; @@ -19382,8 +19407,9 @@ function syncPoolQuotaRow(refs, item, idx, rowEl) { function quotaPoolRowSig(item, idx) { const c5h = item.poolData?.cycle5h; const cWk = item.poolData?.cycleWeekly; + const est = item.poolData?.rateEstimate; const fw = item.fallbackWeekly; - return `${getEffectiveLocale()}:${idx}:${item.poolLabel}:${item.isActivePool}:${Boolean(item.isPending)}:${Boolean(item.showReserved)}:${item.minuteTick}:${item.poolData?.usedPct}:${item.poolData?.remainingPct}:${item.poolData?.reservedPct}:${item.poolData?.reservedLeaseCount}:${item.poolData?.resetTime}:${item.poolData?.weeklyUsedPct}:${item.poolData?.weeklyRemainingPct}:${item.poolData?.weeklyReservedPct}:${item.poolData?.weeklyReservedLeaseCount}:${item.poolData?.weeklyResetTime}:${c5h?.tokens}:${c5h?.costUsd}:${c5h?.calls}:${cWk?.tokens}:${cWk?.costUsd}:${cWk?.calls}:${fw?.isOfficial}:${fw?.usedPct}:${fw?.remainingPct}:${fw?.resetTime}:${fw?.title}:${fw?.tokens}:${fw?.costUsd}:${fw?.calls}`; + return `${getEffectiveLocale()}:${idx}:${item.poolLabel}:${item.isActivePool}:${Boolean(item.isPending)}:${Boolean(item.showReserved)}:${item.minuteTick}:${item.poolData?.usedPct}:${item.poolData?.remainingPct}:${item.poolData?.reservedPct}:${item.poolData?.reservedLeaseCount}:${item.poolData?.resetTime}:${item.poolData?.weeklyUsedPct}:${item.poolData?.weeklyRemainingPct}:${item.poolData?.weeklyReservedPct}:${item.poolData?.weeklyReservedLeaseCount}:${item.poolData?.weeklyResetTime}:${c5h?.tokens}:${c5h?.costUsd}:${c5h?.calls}:${cWk?.tokens}:${cWk?.costUsd}:${cWk?.calls}:${est?.eqFull5hUsd}:${est?.eqFull5hTokens}:${est?.eqFullWeeklyUsd}:${est?.eqFullWeeklyTokens}:${fw?.isOfficial}:${fw?.usedPct}:${fw?.remainingPct}:${fw?.resetTime}:${fw?.title}:${fw?.tokens}:${fw?.costUsd}:${fw?.calls}`; } /** @@ -19459,6 +19485,99 @@ function formatRateEqUsd(val) { return `$${Number(num.toFixed(1))}`; } +function formatPoolFullCapRef(eqUsd, eqTok) { + const usdNum = Number(eqUsd); + if (!Number.isFinite(usdNum) || usdNum <= 0) return ''; + const usdStr = formatRateEqUsd(usdNum); + const tokNum = Number(eqTok); + if (Number.isFinite(tokNum) && tokNum > 0) { + return `${usdStr} (${formatTokens(tokNum)})`; + } + return usdStr; +} + +function resolveWeeklyCapacitySummary(quotas) { + if (!quotas || typeof quotas !== 'object') return null; + if (quotas.weekly?.isOfficial === false) return null; + const direct = quotas.weeklyCapacityEstimate; + if (direct && typeof direct === 'object') { + if ( + direct.status === 'custom_mode' || + !Number.isFinite(Number(direct.totalEqWeeklyUsd)) || + Number(direct.totalEqWeeklyUsd) <= 0 + ) { + return null; + } + return direct; + } + + const rawPools = Array.isArray(quotas.pools) ? quotas.pools : []; + const candidatePools = rawPools.filter( + (p) => + p && + (p.hasWeekly || + p.weeklyUsedPct != null || + Number.isFinite(p.rateEstimate?.eqFullWeeklyUsd)) + ); + const targetPools = candidatePools.length > 0 ? candidatePools : rawPools; + if (targetPools.length === 0) return null; + + let sumUsd = 0; + let sumTokens = 0; + let readyPoolCount = 0; + let tokenReadyPoolCount = 0; + let hasPreliminary = false; + + for (const p of targetPools) { + const est = p?.rateEstimate && typeof p.rateEstimate === 'object' ? p.rateEstimate : null; + let eqUsd = + Number.isFinite(est?.eqFullWeeklyUsd) && est.eqFullWeeklyUsd > 0 + ? Number(est.eqFullWeeklyUsd) + : null; + let eqTok = + Number.isFinite(est?.eqFullWeeklyTokens) && est.eqFullWeeklyTokens > 0 + ? Math.round(Number(est.eqFullWeeklyTokens)) + : null; + if (eqUsd === null && Array.isArray(est?.models) && est.models.length > 0) { + const wkModels = est.models.filter( + (m) => Number.isFinite(m?.eqFullWeeklyUsd) && m.eqFullWeeklyUsd > 0 + ); + if (wkModels.length > 0) { + eqUsd = + wkModels.reduce((acc, m) => acc + Number(m.eqFullWeeklyUsd), 0) / wkModels.length; + const tokModels = wkModels.filter( + (m) => Number.isFinite(m?.eqFullWeeklyTokens) && m.eqFullWeeklyTokens > 0 + ); + if (tokModels.length === wkModels.length) { + eqTok = Math.round( + tokModels.reduce((acc, m) => acc + Number(m.eqFullWeeklyTokens), 0) / tokModels.length + ); + } + } + } + if (eqUsd !== null) { + readyPoolCount += 1; + sumUsd += eqUsd; + if (est?.isPreliminaryWeekly) hasPreliminary = true; + if (eqTok !== null) { + tokenReadyPoolCount += 1; + sumTokens += eqTok; + } + } + } + + if (readyPoolCount === 0) return null; + const totalPoolCount = targetPools.length; + return { + status: readyPoolCount < totalPoolCount ? 'partial' : 'ready', + totalEqWeeklyUsd: +sumUsd.toFixed(1), + totalEqWeeklyTokens: tokenReadyPoolCount === readyPoolCount ? Math.round(sumTokens) : null, + readyPoolCount, + totalPoolCount, + hasPreliminary, + }; +} + function formatRatePerUsdValue(rate) { const num = Number(rate); if (!Number.isFinite(num) || num <= 0) return '--'; @@ -19480,7 +19599,11 @@ function createRateModelCard({ rateWeeklyPctPerUsd = null, eqFull5hUsd = null, eqFullWeeklyUsd = null, + eqFull5hTokens = null, + eqFullWeeklyTokens = null, samples = 0, + source = null, + isPreliminary = false, }) { const leftNodes = [ h('span', { @@ -19509,32 +19632,50 @@ function createRateModelCard({ }) ); } - if (Number(samples) > 0) { + if (isPreliminary) { + subParts.push( + source === 'anchor_slope' ? t('quota.ratePopPrelimSlope') : t('quota.ratePopPrelimCycle') + ); + } else 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') }), + const cell5hChildren = [ + h('span', { className: 'quota-rate-eq-k', text: t('quota.ratePopEq5hLabel') }), + h('span', { + className: 'quota-rate-eq-v text-mono', + text: `≈ ${formatRateEqUsd(eqFull5hUsd)}`, + }), + ]; + if (Number.isFinite(Number(eqFull5hTokens)) && Number(eqFull5hTokens) > 0) { + cell5hChildren.push( h('span', { - className: 'quota-rate-eq-v text-mono', - text: `≈ ${formatRateEqUsd(eqFull5hUsd)}`, - }), - ]) - ); + className: 'quota-rate-eq-tok text-mono', + text: `· ${formatTokens(Number(eqFull5hTokens))}`, + }) + ); + } + eqCells.push(h('div', { className: 'quota-rate-eq-cell' }, cell5hChildren)); } if (eqFullWeeklyUsd != null) { - eqCells.push( - h('div', { className: 'quota-rate-eq-cell' }, [ - h('span', { className: 'quota-rate-eq-k', text: t('quota.ratePopEqWkLabel') }), + const cellWkChildren = [ + h('span', { className: 'quota-rate-eq-k', text: t('quota.ratePopEqWkLabel') }), + h('span', { + className: 'quota-rate-eq-v text-mono', + text: `≈ ${formatRateEqUsd(eqFullWeeklyUsd)}`, + }), + ]; + if (Number.isFinite(Number(eqFullWeeklyTokens)) && Number(eqFullWeeklyTokens) > 0) { + cellWkChildren.push( h('span', { - className: 'quota-rate-eq-v text-mono', - text: `≈ ${formatRateEqUsd(eqFullWeeklyUsd)}`, - }), - ]) - ); + className: 'quota-rate-eq-tok text-mono', + text: `· ${formatTokens(Number(eqFullWeeklyTokens))}`, + }) + ); + } + eqCells.push(h('div', { className: 'quota-rate-eq-cell' }, cellWkChildren)); } const cardChildren = [ @@ -19561,11 +19702,13 @@ function createRateModelCard({ function buildRatePopoverSig(data) { const locale = getEffectiveLocale(); const acct = String(data?.account?.email || data?.account?.name || '').trim(); + const isOfficial = data?.quotas?.weekly?.isOfficial !== false; + const wkCapSig = JSON.stringify(data?.quotas?.weeklyCapacityEstimate || null); 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}`; + return `${locale}|${acct}|${isOfficial}|${wkCapSig}|${poolSig}`; } const QuotaPoolsWidget = defineComponent({ @@ -19583,6 +19726,27 @@ const QuotaPoolsWidget = defineComponent({ className: 'quota-rate-pop-account', text: t('quota.ratePopAccountCurrent'), }); + const ratePopWkLabelEl = h('span', { text: t('quota.ratePopWkCapTitle') }); + const ratePopWkSubEl = h('span', { + className: 'quota-rate-wk-sub', + hidden: true, + text: '', + }); + const ratePopWkUsdEl = h('span', { className: 'quota-rate-wk-usd text-mono', text: '--' }); + const ratePopWkTokEl = h('span', { + className: 'quota-rate-wk-tok text-mono', + hidden: true, + text: '', + }); + const ratePopWkSummaryEl = h( + 'div', + { className: 'quota-rate-wk-summary', hidden: true }, + [ + h('span', { className: 'quota-rate-wk-k' }, [ratePopWkLabelEl, ratePopWkSubEl]), + h('span', { className: 'quota-rate-wk-v' }, [ratePopWkUsdEl, ratePopWkTokEl]), + ] + ); + ratePopWkSummaryEl.hidden = true; const ratePopBodyEl = h('div', { className: 'quota-rate-pop-body' }); const ratePopNoteEl = h('div', { className: 'quota-rate-pop-note', @@ -19597,6 +19761,7 @@ const QuotaPoolsWidget = defineComponent({ }, [ h('div', { className: 'quota-rate-pop-head' }, [ratePopTitleEl, ratePopAccountEl]), + ratePopWkSummaryEl, ratePopBodyEl, ratePopNoteEl, ] @@ -19688,6 +19853,38 @@ const QuotaPoolsWidget = defineComponent({ ); patchAttr(ratePopAccountEl, 'title', acctMasked || null); + const wkCap = resolveWeeklyCapacitySummary(data?.quotas); + if (wkCap) { + ratePopWkSummaryEl.hidden = false; + patchAttr(ratePopWkSummaryEl, 'hidden', false); + patchText(ratePopWkLabelEl, t('quota.ratePopWkCapTitle')); + const wkSubText = + wkCap.status === 'partial' && Number(wkCap.totalPoolCount) > 0 + ? t('quota.ratePopWkCapPartial', { + ready: Number(wkCap.readyPoolCount) || 0, + total: Number(wkCap.totalPoolCount) || 0, + }) + : wkCap.hasPreliminary + ? t('quota.ratePopWkCapPrelim') + : ''; + ratePopWkSubEl.hidden = !wkSubText; + patchAttr(ratePopWkSubEl, 'hidden', !wkSubText); + patchText(ratePopWkSubEl, wkSubText); + patchText(ratePopWkUsdEl, `≈ ${formatRateEqUsd(wkCap.totalEqWeeklyUsd)}`); + const hasWkTok = + Number.isFinite(Number(wkCap.totalEqWeeklyTokens)) && + Number(wkCap.totalEqWeeklyTokens) > 0; + ratePopWkTokEl.hidden = !hasWkTok; + patchAttr(ratePopWkTokEl, 'hidden', !hasWkTok); + patchText( + ratePopWkTokEl, + hasWkTok ? `· ${formatTokens(Number(wkCap.totalEqWeeklyTokens))}` : '' + ); + } else { + ratePopWkSummaryEl.hidden = true; + patchAttr(ratePopWkSummaryEl, 'hidden', true); + } + while (ratePopBodyEl.firstChild) { ratePopBodyEl.removeChild(ratePopBodyEl.firstChild); } @@ -19706,19 +19903,45 @@ const QuotaPoolsWidget = defineComponent({ if (models.length === 0 && !hasPoolFallback && !ext) continue; const poolLabel = p.poolLabel || p.family || p.poolKey || 'Pool'; + const fallbackPrimaryIs5h = est.rate5hPctPerUsd != null; + const anyModelHasWeekly = models.some((m) => m?.eqFullWeeklyUsd != null); + const needsWeeklyFallbackRow = + models.length > 0 && + !anyModelHasWeekly && + Number.isFinite(est.rateWeeklyPctPerUsd) && + est.eqFullWeeklyUsd != null; 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, - }) - ) + ? [ + ...models.map((item) => + createRateModelCard({ + name: item.model, + multiplier: item.multiplier, + rate5hPctPerUsd: item.rate5hPctPerUsd, + rateWeeklyPctPerUsd: item.rateWeeklyPctPerUsd, + eqFull5hUsd: item.eqFull5hUsd, + eqFullWeeklyUsd: item.eqFullWeeklyUsd, + eqFull5hTokens: item.eqFull5hTokens, + eqFullWeeklyTokens: item.eqFullWeeklyTokens, + samples: item.samples, + }) + ), + ...(needsWeeklyFallbackRow + ? [ + createRateModelCard({ + name: t('quota.ratePopPoolFallback'), + isMutedName: true, + isFallback: true, + rateWeeklyPctPerUsd: est.rateWeeklyPctPerUsd, + eqFullWeeklyUsd: est.eqFullWeeklyUsd, + eqFullWeeklyTokens: est.eqFullWeeklyTokens, + samples: Number(est.samplesWeekly) || 0, + source: est.sourceWeekly || null, + isPreliminary: Boolean(est.isPreliminaryWeekly), + }), + ] + : []), + ] : hasPoolFallback ? [ createRateModelCard({ @@ -19729,7 +19952,13 @@ const QuotaPoolsWidget = defineComponent({ rateWeeklyPctPerUsd: est.rateWeeklyPctPerUsd, eqFull5hUsd: est.eqFull5hUsd, eqFullWeeklyUsd: est.eqFullWeeklyUsd, + eqFull5hTokens: est.eqFull5hTokens, + eqFullWeeklyTokens: est.eqFullWeeklyTokens, samples: Math.max(Number(est.samples5h) || 0, Number(est.samplesWeekly) || 0), + source: fallbackPrimaryIs5h ? est.source5h || null : est.sourceWeekly || null, + isPreliminary: fallbackPrimaryIs5h + ? Boolean(est.isPreliminary5h) + : Boolean(est.isPreliminaryWeekly), }), ] : []; diff --git a/sidecars/panel/backend/quota-reservation.mjs b/sidecars/panel/backend/quota-reservation.mjs index 127b26f..8c61c62 100644 --- a/sidecars/panel/backend/quota-reservation.mjs +++ b/sidecars/panel/backend/quota-reservation.mjs @@ -33,6 +33,7 @@ export const QR_IDLE_CONFIRM_REFUND_MS = 5 * 60 * 1000; export const QR_REFUND_CONFIRM_WINDOW_MS = 4 * 60 * 1000; export const QR_REFUND_CONFIRM_MIN_SAMPLES = 4; export const QR_RATE_BOUNCE_COOLDOWN_MS = 60 * 1000; +export const QR_REPLICA_BOUNCE_MEMORY_MS = 30 * 60 * 1000; export const QR_RATE_WINDOW_SIZE = 20; export const QR_RATE_OUTLIER_MIN_RATIO = 0.45; export const QR_RATE_OUTLIER_MAX_RATIO = 2.0; @@ -60,6 +61,21 @@ export const QR_TENTATIVE_LEASE_TTL_MS = 3 * 60 * 1000; const QR_MAX_MODELS_PER_BUCKET = 16; const QR_MAX_TRACKED_BUCKETS = 128; const QR_MAX_ACTIVE_LEASES = 16; +const QR_MAX_SLOPE_SAMPLES = 24; +const QR_SLOPE_MIN_DELTA_PCT = 0.25; +const QR_SLOPE_MIN_DELTA_COST_USD = 0.15; +const QR_SLOPE_UNLOCK_5H_PCT = 2.5; +const QR_SLOPE_UNLOCK_WK_PCT = 1.5; +const QR_SLOPE_UNLOCK_MIN_CALLS = 5; +const QR_COLD_RATIO_5H_PCT = 3.0; +const QR_COLD_RATIO_WK_PCT = 2.0; +const QR_COLD_RATIO_SOLO_PCT = 5.0; +const QR_COLD_RATIO_MIN_CALLS = 5; +const QR_COLD_RATIO_SOLO_MIN_CALLS = 3; +const QR_COLD_RATIO_5H_MIN_COST_USD = 0.15; +const QR_COLD_RATIO_WK_MIN_COST_USD = 0.25; +const QR_DENSITY_MIN_TOKENS = 10_000; +const QR_DENSITY_MIN_COST_USD = 0.05; const QR_MAX_EVENT_LOG = 500; const QR_PERSIST_MIN_INTERVAL_MS = 5000; const QR_STATE_SCHEMA_VERSION = 2; @@ -77,6 +93,172 @@ function qrClampRate(rate) { return qrClamp(rate, 0.005, 50); } +function qrClampUsdPerMTok(val) { + const num = Number(val); + if (!Number.isFinite(num) || num <= 0) return null; + return qrClamp(num, 0.02, 500); +} + +function qrBlendUsdPerMTok(prevDensity, costUsd, pricedTokens) { + const prev = qrClampUsdPerMTok(prevDensity); + const safeCost = Number(costUsd) || 0; + const safeTokens = Number(pricedTokens) || 0; + if (safeTokens < QR_DENSITY_MIN_TOKENS || safeCost < QR_DENSITY_MIN_COST_USD) { + return prev; + } + const curr = qrClampUsdPerMTok(safeCost / (safeTokens / 1_000_000)); + if (curr === null) return prev; + if (prev === null) return curr; + const w = safeCost / (safeCost + 1.0); + return qrClampUsdPerMTok(prev * (1 - w) + curr * w); +} + +function qrDeriveEqFullTokens(rawEqFullUsd, usdPerMTok) { + const usd = Number(rawEqFullUsd); + const density = qrClampUsdPerMTok(usdPerMTok); + if (!Number.isFinite(usd) || usd <= 0 || density === null) return null; + const tok = Math.round((usd / density) * 1_000_000); + return Number.isFinite(tok) && tok > 0 ? tok : null; +} + +function qrComputeTheilSenSlope(samples) { + if (!Array.isArray(samples) || samples.length < 2) return null; + if (samples.length === 2) { + const du = samples[1].u - samples[0].u; + const dc = samples[1].c - samples[0].c; + return dc >= 0.05 && du > 0 ? qrClampRate(du / dc) : null; + } + const slopes = []; + for (let i = 0; i < samples.length - 1; i += 1) { + for (let j = i + 1; j < samples.length; j += 1) { + const du = samples[j].u - samples[i].u; + const dc = samples[j].c - samples[i].c; + if (dc >= 0.05 && du > 0) { + const s = qrClampRate(du / dc); + if (s !== null) slopes.push(s); + } + } + } + return slopes.length > 0 ? qrClampRate(qrComputeMedian(slopes)) : null; +} + +function qrSanitizeSlopeSamples(raw) { + if (!Array.isArray(raw)) return []; + const out = []; + for (let i = 0; i < raw.length && out.length < QR_MAX_SLOPE_SAMPLES; i += 1) { + const item = raw[i]; + if (!item || typeof item !== 'object') continue; + const u = Number(item.u); + const c = Number(item.c); + const n = Math.floor(Number(item.n) || 0); + const unp = Math.max(0, Math.floor(Number(item.unp) || 0)); + if (!Number.isFinite(u) || u < 0 || !Number.isFinite(c) || c < 0 || n < 0) continue; + out.push({ u: qrClamp(u, 0, 100), c, n, ...(unp > 0 ? { unp } : {}) }); + } + return out; +} + +function qrSanitizeModelTokens(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 = Math.floor(Number(v) || 0); + if (cleanKey && Number.isFinite(num) && num > 0) { + out[cleanKey] = num; + } + } + return out; +} + +function qrRefreshBucketDensities(st, safeCost, safePricedTokens, safeModelCosts, safeModelTokens) { + if (!st || typeof st !== 'object') return; + const nextPoolDensity = qrBlendUsdPerMTok(st.priorUsdPerMTok, safeCost, safePricedTokens); + if (nextPoolDensity !== null) { + st.usdPerMTok = nextPoolDensity; + } + const priorModels = + st.priorModelUsdPerMTok && typeof st.priorModelUsdPerMTok === 'object' + ? st.priorModelUsdPerMTok + : {}; + const nextModels = { ...priorModels }; + if (safeModelCosts && safeModelTokens) { + for (const [mKey, mCost] of Object.entries(safeModelCosts)) { + const mTok = Number(safeModelTokens[mKey]) || 0; + const blended = qrBlendUsdPerMTok(priorModels[mKey] ?? null, mCost, mTok); + if (blended !== null) { + nextModels[mKey] = +blended.toFixed(4); + } + } + } + const entries = Object.entries(nextModels).slice(-QR_MAX_MODELS_PER_BUCKET); + st.modelUsdPerMTok = Object.fromEntries(entries); +} + +function qrComputeNetLocalUsedPct(st, officialUsedPct) { + const safeOfficial = qrClamp(Number(officialUsedPct) || 0, 0, 100); + if (!st || typeof st !== 'object') return safeOfficial; + const leaseSum = qrSumLeases(st.activeLeases || [], { includeTentative: true }); + const extPct = Math.max(0, Number(st.externalUsedPct) || 0); + return Math.max(0, safeOfficial - leaseSum - extPct); +} + +function qrSanitizeModelDensities(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, v] of entries) { + const cleanKey = String(k || '').trim(); + const clamped = qrClampUsdPerMTok(v); + if (cleanKey && clamped !== null) { + out[cleanKey] = +clamped.toFixed(4); + } + } + return out; +} + +function qrResetSlopeAnchor(st, netUsedPct, safeCost, safeCalls, safeUnpriced = 0) { + if (!st || typeof st !== 'object') return; + const calls = Math.max(0, Math.floor(Number(safeCalls) || 0)); + const unp = Math.max(0, Math.floor(Number(safeUnpriced) || 0)); + const u = qrClamp(Number(netUsedPct) || 0, 0, 100); + const c = Math.max(0, Number(safeCost) || 0); + st.slopeSamples = [{ u: +u.toFixed(4), c: +c.toFixed(6), n: calls, ...(unp > 0 ? { unp } : {}) }]; +} + +function qrUpdateSlopeSamples(st, netUsedPct, safeCost, safeCalls, safeUnpriced = 0) { + if (!st || st.pendingDrop !== null) return; + const calls = Math.max(0, Math.floor(Number(safeCalls) || 0)); + const unp = Math.max(0, Math.floor(Number(safeUnpriced) || 0)); + const u = qrClamp(Number(netUsedPct) || 0, 0, 100); + const c = Math.max(0, Number(safeCost) || 0); + const arr = Array.isArray(st.slopeSamples) ? st.slopeSamples : (st.slopeSamples = []); + if (arr.length === 0) { + arr.push({ u: +u.toFixed(4), c: +c.toFixed(6), n: calls, ...(unp > 0 ? { unp } : {}) }); + return; + } + const last = arr[arr.length - 1]; + const lastUnp = Math.max(0, Math.floor(Number(last.unp) || 0)); + if (u < last.u - 0.15 || c < last.c - 1e-4 || calls < last.n || unp !== lastUnp) { + st.slopeSamples = [{ u: +u.toFixed(4), c: +c.toFixed(6), n: calls, ...(unp > 0 ? { unp } : {}) }]; + return; + } + const du = u - last.u; + const dc = c - last.c; + const dn = calls - last.n; + if ( + dn > 0 && + ((du >= QR_SLOPE_MIN_DELTA_PCT && dc >= 0.02) || + (dc >= QR_SLOPE_MIN_DELTA_COST_USD && du > 1e-3)) + ) { + arr.push({ u: +u.toFixed(4), c: +c.toFixed(6), n: calls, ...(unp > 0 ? { unp } : {}) }); + if (arr.length > QR_MAX_SLOPE_SAMPLES) { + // 保留首锚点 arr[0] 以维持整周期跨度,淘汰最早的中间点 + arr.splice(1, arr.length - QR_MAX_SLOPE_SAMPLES); + } + } +} + function qrResolveExactUsedPct(poolObj, win) { const rawFrac = win === 'weekly' ? poolObj?.weeklyRemainingFraction : poolObj?.remainingFraction; @@ -184,8 +366,13 @@ function qrResolveEffectiveRate(state, officialUsedPct, cycleCostUsd) { if (state.ratePctPerUsd !== null && Number.isFinite(state.ratePctPerUsd)) { return state.ratePctPerUsd; } - // 一旦检测到同池存在家庭组 / 其他设备外部消耗,禁止用累计总占比 / 本机花费做冷启动反推 - if (!state.hasExternalUsage && cycleCostUsd >= 0.5 && officialUsedPct >= 0.3) { + // 一旦检测到同池存在家庭组 / 其他设备外部消耗或未计价调用,禁止用累计总占比 / 本机花费做冷启动反推 + if ( + !state.hasExternalUsage && + (state.lastUnpricedCalls || 0) === 0 && + cycleCostUsd >= 0.5 && + officialUsedPct >= 0.3 + ) { return qrClampRate(officialUsedPct / cycleCostUsd); } return null; @@ -396,17 +583,93 @@ function qrEstimateModelWeightedPct(st, deltaModelCosts, totalDeltaCostUsd, fall return weightedPct + unattributedCost * fallbackRate; } +function qrResolveBucketDisplayRate(st, win) { + if (!st || typeof st !== 'object') return null; + const cleanWin = Array.isArray(st.rateWindow) ? st.rateWindow : []; + const calibratedSamples = cleanWin.length > 0 ? cleanWin.length : st.rateSamples; + if (calibratedSamples >= QR_MODEL_RATE_MIN_UI_SAMPLES && Number.isFinite(st.ratePctPerUsd)) { + return { + rate: st.ratePctPerUsd, + source: 'calibrated', + isPreliminary: false, + samples: Math.max(cleanWin.length, st.rateSamples), + }; + } + + let tier2Rate = null; + const slopePts = Array.isArray(st.slopeSamples) ? st.slopeSamples : []; + if (slopePts.length >= 2) { + const first = slopePts[0]; + const last = slopePts[slopePts.length - 1]; + const spanPct = last.u - first.u; + const spanCost = last.c - first.c; + const spanCalls = last.n - first.n; + const minSpanPct = win === '5h' ? QR_SLOPE_UNLOCK_5H_PCT : QR_SLOPE_UNLOCK_WK_PCT; + if ( + spanPct >= minSpanPct && + spanCost >= QR_SLOPE_MIN_DELTA_COST_USD && + spanCalls >= QR_SLOPE_UNLOCK_MIN_CALLS + ) { + tier2Rate = qrComputeTheilSenSlope(slopePts); + } + } + + let tier3Rate = null; + if (!st.hasExternalUsage && (st.lastUnpricedCalls || 0) === 0 && st.lastOfficialUsedPct !== null) { + const out = qrFormatOutput(st, st.lastOfficialUsedPct); + const netUsedPct = Math.max( + 0, + st.lastOfficialUsedPct - out.reservedPct - (Number(st.externalUsedPct) || 0) + ); + const calls = Math.max(0, Number(st.lastCycleCalls) || 0); + const cost = Math.max(0, Number(st.lastCycleCostUsd) || 0); + const minCost = win === '5h' ? QR_COLD_RATIO_5H_MIN_COST_USD : QR_COLD_RATIO_WK_MIN_COST_USD; + const minPct = win === '5h' ? QR_COLD_RATIO_5H_PCT : QR_COLD_RATIO_WK_PCT; + const unlocked = + cost >= minCost && + ((netUsedPct >= minPct && calls >= QR_COLD_RATIO_MIN_CALLS) || + (netUsedPct >= QR_COLD_RATIO_SOLO_PCT && calls >= QR_COLD_RATIO_SOLO_MIN_CALLS)); + if (unlocked) { + tier3Rate = qrClampRate(netUsedPct / cost); + } + } + + const prelimRate = tier2Rate ?? tier3Rate; + if (prelimRate === null) return null; + const prelimSource = tier2Rate !== null ? 'anchor_slope' : 'cycle_ratio'; + if (cleanWin.length > 0) { + const cleanMed = qrComputeMedian(cleanWin); + if (cleanMed !== null) { + const w = cleanWin.length / (cleanWin.length + QR_MODEL_RATE_MIN_UI_SAMPLES); + const blended = qrClampRate(cleanMed * w + prelimRate * (1 - w)); + if (blended !== null) { + return { + rate: blended, + source: prelimSource, + isPreliminary: true, + samples: cleanWin.length, + }; + } + } + } + return { + rate: prelimRate, + source: prelimSource, + isPreliminary: true, + samples: 0, + }; +} + function qrBuildPoolRateEstimate(st5h, stWk, nowMs = Date.now()) { - 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 resolved5h = qrResolveBucketDisplayRate(st5h, '5h'); + const resolvedWk = qrResolveBucketDisplayRate(stWk, 'weekly'); + const raw5hPool = resolved5h ? resolved5h.rate : null; + const rawWkPool = resolvedWk ? resolvedWk.rate : null; const rate5hPool = raw5hPool !== null ? +raw5hPool.toFixed(4) : null; const rateWkPool = rawWkPool !== null ? +rawWkPool.toFixed(4) : null; + const fallbackPoolDensity = stWk?.usdPerMTok ?? st5h?.usdPerMTok ?? null; + const density5hPool = st5h?.usdPerMTok ?? fallbackPoolDensity; + const densityWkPool = stWk?.usdPerMTok ?? fallbackPoolDensity; const modelKeys = new Set([ ...Object.keys(st5h?.modelRates || {}), @@ -425,12 +688,22 @@ function qrBuildPoolRateEstimate(st5h, stWk, nowMs = Date.now()) { ? mw.ratePctPerUsd : null; if (rawR5 === null && rawRw === null) continue; + const rawEq5hUsd = rawR5 ? 100 / rawR5 : null; + const rawEqWkUsd = rawRw ? 100 / rawRw : null; + const modelDensity5h = + st5h?.modelUsdPerMTok?.[model] ?? stWk?.modelUsdPerMTok?.[model] ?? density5hPool; + const modelDensityWk = + stWk?.modelUsdPerMTok?.[model] ?? st5h?.modelUsdPerMTok?.[model] ?? densityWkPool; + const eq5hTok = qrDeriveEqFullTokens(rawEq5hUsd, modelDensity5h); + const eqWkTok = qrDeriveEqFullTokens(rawEqWkUsd, modelDensityWk); 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, + eqFull5hUsd: rawEq5hUsd ? +rawEq5hUsd.toFixed(1) : null, + eqFullWeeklyUsd: rawEqWkUsd ? +rawEqWkUsd.toFixed(1) : null, + ...(eq5hTok !== null ? { eqFull5hTokens: eq5hTok } : {}), + ...(eqWkTok !== null ? { eqFullWeeklyTokens: eqWkTok } : {}), multiplier: null, samples: Math.max(m5?.rateSamples || 0, mw?.rateSamples || 0), _rawR5: rawR5, @@ -493,13 +766,24 @@ function qrBuildPoolRateEstimate(st5h, stWk, nowMs = Date.now()) { return null; } + const rawPoolEq5hUsd = raw5hPool ? 100 / raw5hPool : null; + const rawPoolEqWkUsd = rawWkPool ? 100 / rawWkPool : null; + const poolEq5hTok = qrDeriveEqFullTokens(rawPoolEq5hUsd, density5hPool); + const poolEqWkTok = qrDeriveEqFullTokens(rawPoolEqWkUsd, densityWkPool); + 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, + eqFull5hUsd: rawPoolEq5hUsd ? +rawPoolEq5hUsd.toFixed(1) : null, + eqFullWeeklyUsd: rawPoolEqWkUsd ? +rawPoolEqWkUsd.toFixed(1) : null, + ...(poolEq5hTok !== null ? { eqFull5hTokens: poolEq5hTok } : {}), + ...(poolEqWkTok !== null ? { eqFullWeeklyTokens: poolEqWkTok } : {}), + samples5h: resolved5h ? resolved5h.samples : st5h?.rateSamples || 0, + samplesWeekly: resolvedWk ? resolvedWk.samples : stWk?.rateSamples || 0, + source5h: resolved5h ? resolved5h.source : null, + sourceWeekly: resolvedWk ? resolvedWk.source : null, + isPreliminary5h: Boolean(resolved5h?.isPreliminary), + isPreliminaryWeekly: Boolean(resolvedWk?.isPreliminary), models, ...(externalUsage ? { externalUsage } : {}), }; @@ -578,6 +862,50 @@ function qrDetectProportionalExternalJump(st5h, stWk, params5h, paramsWk) { return usdRatio >= QR_CO_MOVE_MIN_USD_RATIO && usdRatio <= QR_CO_MOVE_MAX_USD_RATIO; } +function qrReconcileExternalUsageBound(st, safeUsed, safeCost, safeModelCosts, nowMs) { + if (!st || (!st.hasExternalUsage && !(Number(st.externalUsedPct) > 0))) return false; + const leaseSum = qrSumLeases(st.activeLeases || [], { includeTentative: true }); + const cleanWin = Array.isArray(st.rateWindow) ? st.rateWindow : []; + const isCalibrated = + cleanWin.length >= QR_MODEL_RATE_MIN_UI_SAMPLES && + (st.lastUnpricedCalls || 0) === 0 && + Number.isFinite(st.ratePctPerUsd) && + st.ratePctPerUsd > 0; + const localExpectedPct = isCalibrated + ? qrEstimateModelWeightedPct(st, safeModelCosts, safeCost, st.ratePctPerUsd) + : 0; + // 本周期累计外部消耗物理上不可能超过(官方累计已用 - 活跃租约 - 已校准本机保守下界) + const localConservativeFloor = localExpectedPct * 0.9; + const maxExternalBound = Math.max(0, safeUsed - leaseSum - localConservativeFloor); + let mutated = false; + const curExtPct = Number(st.externalUsedPct) || 0; + if (curExtPct > maxExternalBound + 1e-3) { + const clamped = maxExternalBound < QR_MIN_DISPLAY_RESERVED_PCT ? 0 : maxExternalBound; + if (Math.abs(curExtPct - clamped) > 1e-3) { + st.externalUsedPct = clamped; + mutated = true; + } + } + const recentExt = + (Number(st.lastExternalUsageAtMs) || 0) > 0 && + nowMs >= st.lastExternalUsageAtMs && + nowMs - st.lastExternalUsageAtMs <= QR_EXTERNAL_ACTIVE_WINDOW_MS; + if ( + isCalibrated && + st.hasExternalUsage && + !recentExt && + (Number(st.externalUsedPct) || 0) === 0 && + safeUsed >= 0.05 && + maxExternalBound < QR_EXTERNAL_MIN_IDLE_DELTA_PCT + ) { + st.hasExternalUsage = false; + st.externalEvents = 0; + st.lastExternalUsageAtMs = 0; + mutated = true; + } + return mutated; +} + function qrSanitizePersistedBucket(raw, { preserveRate = true } = {}) { if (!raw || typeof raw !== 'object') return null; const lastOfficial = @@ -605,8 +933,20 @@ function qrSanitizePersistedBucket(raw, { preserveRate = true } = {}) { lastQuotaTs: Math.max(0, Number(raw.lastQuotaTs) || 0), lastOfficialUsedPct: lastOfficial, lastCycleCostUsd: Math.max(0, Number(raw.lastCycleCostUsd) || 0), + lastCycleCalls: Math.max(0, Math.floor(Number(raw.lastCycleCalls) || 0)), + lastPricedTokens: Math.max(0, Math.floor(Number(raw.lastPricedTokens) || 0)), lastModelCostsUsd: qrSanitizeModelCosts(raw.lastModelCostsUsd), lastUnpricedCalls: Math.max(0, Number(raw.lastUnpricedCalls) || 0), + usdPerMTok: preserveRate ? qrClampUsdPerMTok(raw.usdPerMTok) : null, + priorUsdPerMTok: preserveRate + ? qrClampUsdPerMTok(raw.priorUsdPerMTok ?? raw.usdPerMTok) + : null, + modelUsdPerMTok: qrSanitizeModelDensities(raw.modelUsdPerMTok, { preserveRate }), + priorModelUsdPerMTok: qrSanitizeModelDensities( + raw.priorModelUsdPerMTok ?? raw.modelUsdPerMTok, + { preserveRate } + ), + slopeSamples: preserveRate ? qrSanitizeSlopeSamples(raw.slopeSamples) : [], pendingCostUsd: 0, pendingCostAtMs: 0, pendingCostSinceMs: 0, @@ -622,6 +962,7 @@ function qrSanitizePersistedBucket(raw, { preserveRate = true } = {}) { lastBounceAtMs: Math.max(0, Number(raw.lastBounceAtMs) || 0), lastRefundAtMs: Math.max(0, Number(raw.lastRefundAtMs) || 0), lastRefundPct: Math.max(0, Number(raw.lastRefundPct) || 0), + lastRefundHighWaterPct: qrClamp(Math.max(0, Number(raw.lastRefundHighWaterPct) || 0), 0, 100), hasExternalUsage: raw.hasExternalUsage === true, lastExternalUsageAtMs: Math.max(0, Number(raw.lastExternalUsageAtMs) || 0), externalUsedPct: Math.max(0, Number(raw.externalUsedPct) || 0), @@ -639,6 +980,8 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu const eventLog = []; let hydrated = typeof loadState !== 'function'; let lastPersistMs = 0; + let batchingDepth = 0; + let batchPendingEvent = null; function ensureHydrated() { if (hydrated) return; @@ -686,8 +1029,25 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu lastQuotaTs: st.lastQuotaTs, lastOfficialUsedPct: st.lastOfficialUsedPct, lastCycleCostUsd: st.lastCycleCostUsd, + lastCycleCalls: st.lastCycleCalls || 0, + lastPricedTokens: st.lastPricedTokens || 0, lastModelCostsUsd: st.lastModelCostsUsd || {}, lastUnpricedCalls: st.lastUnpricedCalls, + ...(st.usdPerMTok !== null && Number.isFinite(st.usdPerMTok) + ? { usdPerMTok: +st.usdPerMTok.toFixed(4) } + : {}), + ...(st.priorUsdPerMTok !== null && Number.isFinite(st.priorUsdPerMTok) + ? { priorUsdPerMTok: +st.priorUsdPerMTok.toFixed(4) } + : {}), + ...(st.modelUsdPerMTok && Object.keys(st.modelUsdPerMTok).length > 0 + ? { modelUsdPerMTok: st.modelUsdPerMTok } + : {}), + ...(st.priorModelUsdPerMTok && Object.keys(st.priorModelUsdPerMTok).length > 0 + ? { priorModelUsdPerMTok: st.priorModelUsdPerMTok } + : {}), + ...(Array.isArray(st.slopeSamples) && st.slopeSamples.length > 0 + ? { slopeSamples: st.slopeSamples } + : {}), ratePctPerUsd: st.ratePctPerUsd, rateSamples: st.rateSamples, rateWindow: st.rateWindow, @@ -697,6 +1057,9 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu lastBounceAtMs: st.lastBounceAtMs, lastRefundAtMs: st.lastRefundAtMs, lastRefundPct: st.lastRefundPct, + ...(Number(st.lastRefundHighWaterPct) > 0 + ? { lastRefundHighWaterPct: +Number(st.lastRefundHighWaterPct).toFixed(4) } + : {}), hasExternalUsage: Boolean(st.hasExternalUsage), lastExternalUsageAtMs: st.lastExternalUsageAtMs || 0, externalUsedPct: +(Number(st.externalUsedPct) || 0).toFixed(3), @@ -730,6 +1093,12 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu eventKind === 'refund' || eventKind === 'reset' || eventKind === 'expire'; + if (batchingDepth > 0) { + if (isUrgent || !batchPendingEvent) { + batchPendingEvent = isUrgent ? 'lease' : eventKind; + } + return; + } if (!isUrgent && lastPersistMs > 0 && nowMs - lastPersistMs < QR_PERSIST_MIN_INTERVAL_MS) { return; } @@ -765,8 +1134,15 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu lastQuotaTs: 0, lastOfficialUsedPct: null, lastCycleCostUsd: 0, + lastCycleCalls: 0, + lastPricedTokens: 0, lastModelCostsUsd: {}, lastUnpricedCalls: 0, + usdPerMTok: null, + priorUsdPerMTok: null, + modelUsdPerMTok: {}, + priorModelUsdPerMTok: {}, + slopeSamples: [], pendingCostUsd: 0, pendingCostAtMs: 0, pendingCostSinceMs: 0, @@ -782,6 +1158,7 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu lastBounceAtMs: 0, lastRefundAtMs: 0, lastRefundPct: 0, + lastRefundHighWaterPct: 0, hasExternalUsage: false, lastExternalUsageAtMs: 0, externalUsedPct: 0, @@ -799,7 +1176,10 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu resetTimeMs = 0, quotaFetchedAtMs = 0, cycleCostUsd = 0, + cycleCalls = 0, + pricedTokens = 0, modelCostsUsd = null, + modelTokens = null, unpricedCalls = 0, poolLastActivityMs = 0, activeSessionCount10m = 0, @@ -815,7 +1195,10 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu ensureHydrated(); const safeUsed = qrClamp(Number(officialUsedPct), 0, 100); const safeCost = Math.max(0, Number(cycleCostUsd) || 0); + const safeCalls = Math.max(0, Math.floor(Number(cycleCalls) || 0)); + const safePricedTokens = Math.max(0, Math.floor(Number(pricedTokens) || 0)); const safeModelCosts = qrSanitizeModelCosts(modelCostsUsd); + const safeModelTokens = qrSanitizeModelTokens(modelTokens); const safeUnpriced = Math.max(0, Number(unpricedCalls) || 0); const safeResetMs = Number(resetTimeMs) > 0 ? Number(resetTimeMs) : 0; const safeFetchTs = Number(quotaFetchedAtMs) > 0 ? Number(quotaFetchedAtMs) : nowMs; @@ -868,33 +1251,57 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu st.lastQuotaTs = safeFetchTs; st.lastOfficialUsedPct = safeUsed; st.lastCycleCostUsd = safeCost; + st.lastCycleCalls = safeCalls; + st.lastPricedTokens = safePricedTokens; st.lastModelCostsUsd = safeModelCosts; st.lastUnpricedCalls = safeUnpriced; if (isIdleZeroDrift) { + qrRefreshBucketDensities(st, safeCost, safePricedTokens, safeModelCosts, safeModelTokens); return qrFormatOutput(st, safeUsed); } + if (st.usdPerMTok !== null && Number.isFinite(st.usdPerMTok)) { + st.priorUsdPerMTok = st.usdPerMTok; + } + if (st.modelUsdPerMTok && Object.keys(st.modelUsdPerMTok).length > 0) { + st.priorModelUsdPerMTok = { + ...(st.priorModelUsdPerMTok || {}), + ...st.modelUsdPerMTok, + }; + } + st.slopeSamples = []; st.pendingCostUsd = 0; st.pendingCostAtMs = 0; st.pendingCostSinceMs = 0; st.pendingModelCostsUsd = {}; st.activeLeases = []; st.pendingDrop = null; + st.lastRefundHighWaterPct = 0; st.hasExternalUsage = safeUsed >= QR_EXTERNAL_BASELINE_USED_PCT && safeCost < QR_EXTERNAL_BASELINE_MAX_LOCAL_COST_USD; st.externalUsedPct = 0; st.externalEvents = 0; + qrRefreshBucketDensities(st, safeCost, safePricedTokens, safeModelCosts, safeModelTokens); + qrUpdateSlopeSamples( + st, + qrComputeNetLocalUsedPct(st, safeUsed), + safeCost, + safeCalls, + safeUnpriced + ); const out = qrFormatOutput(st, safeUsed); recordLog('reset', { deltaOfficial: safeUsed - prevUsed, ...out }); return out; } - // 2. 首次观测:建立基线并按当前周期已有消耗做冷启动费率估计(检测到外部消耗时跳过累计比值反推) + // 2. 首次观测:建立基线并按当前周期已有消耗做冷启动费率估计(检测到外部消耗或未计价调用时跳过累计比值反推) if (st.lastOfficialUsedPct === null) { st.resetTimeMs = safeResetMs; st.lastQuotaTs = safeFetchTs; st.lastOfficialUsedPct = safeUsed; st.lastCycleCostUsd = safeCost; + st.lastCycleCalls = safeCalls; + st.lastPricedTokens = safePricedTokens; st.lastModelCostsUsd = safeModelCosts; st.lastUnpricedCalls = safeUnpriced; if ( @@ -902,10 +1309,23 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu safeCost < QR_EXTERNAL_BASELINE_MAX_LOCAL_COST_USD ) { st.hasExternalUsage = true; - } else if (!st.hasExternalUsage && safeCost >= 0.5 && safeUsed >= 0.3) { + } else if ( + !st.hasExternalUsage && + safeUnpriced === 0 && + safeCost >= 0.5 && + safeUsed >= 0.3 + ) { st.ratePctPerUsd = qrClampRate(safeUsed / safeCost); st.rateSamples = 1; } + qrRefreshBucketDensities(st, safeCost, safePricedTokens, safeModelCosts, safeModelTokens); + qrUpdateSlopeSamples( + st, + qrComputeNetLocalUsedPct(st, safeUsed), + safeCost, + safeCalls, + safeUnpriced + ); const out = qrFormatOutput(st, safeUsed); recordLog('baseline', out); return out; @@ -925,11 +1345,35 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu ) { st.lastModelCostsUsd = safeModelCosts; } + if (st.lastCycleCalls === 0 || Math.abs(safeCost - st.lastCycleCostUsd) <= 1e-4) { + st.lastCycleCalls = safeCalls; + } + st.lastPricedTokens = safePricedTokens; + const prevDensity = st.usdPerMTok; + qrRefreshBucketDensities(st, safeCost, safePricedTokens, safeModelCosts, safeModelTokens); + const extReconciled = qrReconcileExternalUsageBound( + st, + safeUsed, + st.lastCycleCostUsd, + st.lastModelCostsUsd, + nowMs + ); const beforeCachePrune = st.activeLeases.length; qrPruneExpiredLeases(st, nowMs); const out = qrFormatOutput(st, safeUsed); if (beforeCachePrune > st.activeLeases.length) { + qrResetSlopeAnchor( + st, + qrComputeNetLocalUsedPct(st, safeUsed), + st.lastCycleCostUsd, + st.lastCycleCalls, + st.lastUnpricedCalls + ); recordLog('expire', out); + } else if (extReconciled) { + persistIfNeeded('external_usage', nowMs); + } else if (prevDensity === null && st.usdPerMTok !== null) { + persistIfNeeded('normal', nowMs); } return out; } @@ -1018,10 +1462,27 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu st.pendingModelCostsUsd = {}; }; - const confirmRefund = (refundedPct, { keepPendingCost = false } = {}) => { + const confirmRefund = ( + refundedPct, + { keepPendingCost = false, preRefundHighPct = 0 } = {} + ) => { const amt = Math.max(0, Number(refundedPct) || 0); - if (amt > 0) { - qrConsumeLeasesFifo(st.activeLeases, amt); + const prevHighWater = + st.lastRefundAtMs > 0 && nowMs - st.lastRefundAtMs <= QR_REPLICA_BOUNCE_MEMORY_MS + ? Number(st.lastRefundHighWaterPct) || 0 + : 0; + st.lastRefundHighWaterPct = Math.max( + prevHighWater, + Number(preRefundHighPct) || 0, + Number(st.lastOfficialUsedPct) || 0 + ); + const leaseConsumed = amt > 0 ? qrConsumeLeasesFifo(st.activeLeases, amt) : 0; + const unbackedDrop = Math.max(0, amt - leaseConsumed); + if (unbackedDrop > 0 && (Number(st.externalUsedPct) || 0) > 0) { + st.externalUsedPct = Math.max(0, (Number(st.externalUsedPct) || 0) - unbackedDrop); + if (st.externalUsedPct < QR_MIN_DISPLAY_RESERVED_PCT) { + st.externalUsedPct = 0; + } } st.lastRefundAtMs = nowMs; st.lastRefundPct = amt; @@ -1049,7 +1510,7 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu clearPendingCost(); if (isIdleRefundReady) { - confirmRefund(totalDrop); + confirmRefund(totalDrop, { preRefundHighPct: prevHigh }); } else if (st.pendingDrop) { st.pendingDrop.preDropUsedPct = prevHigh; st.pendingDrop.lowestUsedPct = Math.min(st.pendingDrop.lowestUsedPct, safeUsed); @@ -1059,7 +1520,7 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu st.pendingDrop.lowSamples >= QR_REFUND_CONFIRM_MIN_SAMPLES && nowMs - st.pendingDrop.droppedAtMs >= QR_REFUND_CONFIRM_WINDOW_MS ) { - confirmRefund(st.pendingDrop.dropPct); + confirmRefund(st.pendingDrop.dropPct, { preRefundHighPct: prevHigh }); } else { eventKind = 'drop_pending'; } @@ -1141,6 +1602,7 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu const effectiveDrop = Math.max(0, pd.preDropUsedPct + expectedSinceDrop - safeUsed); confirmRefund(effectiveDrop > 0 ? Math.min(pd.dropPct, effectiveDrop) : pd.dropPct, { keepPendingCost: deltaOfficial <= 1e-3 && st.pendingCostUsd > 0, + preRefundHighPct: pd.preDropUsedPct, }); } else if (deltaOfficial > 1e-3) { clearPendingCost(); @@ -1154,9 +1616,19 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu } } } else if (deltaOfficial > 1e-3) { - // 4B. 官方已用比例上升:先筛除外部/家庭组消耗,再区分租约跳变、真实租约内消费及常规消耗 + // 4B. 官方已用比例上升:先筛除退还后多副本回弹及外部/家庭组消耗,再区分租约跳变、租约内消费及常规消耗 + const isPostRefundReplicaBounce = + !forceExternalJump && + !hasLocalPoolActivity && + st.lastRefundAtMs > 0 && + nowMs >= st.lastRefundAtMs && + nowMs - st.lastRefundAtMs <= QR_REPLICA_BOUNCE_MEMORY_MS && + (Number(st.lastRefundHighWaterPct) || 0) > 0 && + safeUsed <= (Number(st.lastRefundHighWaterPct) || 0) + QR_REFUND_EPSILON_PCT; const isIdleExternalUsage = - !hasLocalPoolActivity && deltaOfficial >= QR_EXTERNAL_MIN_IDLE_DELTA_PCT; + !isPostRefundReplicaBounce && + !hasLocalPoolActivity && + deltaOfficial >= QR_EXTERNAL_MIN_IDLE_DELTA_PCT; const detectedWithRate = rate !== null && excessPct >= QR_MIN_JUMP_EXCESS_PCT; const detectedColdStart = rate === null && @@ -1168,7 +1640,10 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu expectedDeltaPct > 0 && shortfall >= Math.max(QR_CONSUME_MIN_SHORTFALL_PCT, expectedDeltaPct * QR_CONSUME_SHORTFALL_RATIO); - if (forceExternalJump || isIdleExternalUsage) { + if (isPostRefundReplicaBounce) { + st.lastBounceAtMs = nowMs; + eventKind = 'replica_flip'; + } else if (forceExternalJump || isIdleExternalUsage) { const extAmt = forceExternalJump && excessPct > 0 ? excessPct : deltaOfficial; recordExternalDelta(extAmt); @@ -1323,16 +1798,35 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu st.lastQuotaTs = safeFetchTs; st.lastOfficialUsedPct = safeUsed; st.lastCycleCostUsd = safeCost; + st.lastCycleCalls = safeCalls; + st.lastPricedTokens = safePricedTokens; st.lastModelCostsUsd = safeModelCosts; st.lastUnpricedCalls = safeUnpriced; // 5. 租约 TTL 超时兜底(租约本身超过 60 分钟无实质扣减或满 90 分钟自动清理) const beforePrune = st.activeLeases.length; qrPruneExpiredLeases(st, nowMs); - if (beforePrune > st.activeLeases.length && eventKind === 'idle') { + const prunedExpiredLeases = beforePrune > st.activeLeases.length; + if (prunedExpiredLeases && eventKind === 'idle') { eventKind = 'expire'; } + const prevDensity = st.usdPerMTok; + qrRefreshBucketDensities(st, safeCost, safePricedTokens, safeModelCosts, safeModelTokens); + const extReconciled = qrReconcileExternalUsageBound( + st, + safeUsed, + safeCost, + safeModelCosts, + nowMs + ); + const netLocalUsed = qrComputeNetLocalUsedPct(st, safeUsed); + if (prunedExpiredLeases) { + qrResetSlopeAnchor(st, netLocalUsed, safeCost, safeCalls, safeUnpriced); + } else { + qrUpdateSlopeSamples(st, netLocalUsed, safeCost, safeCalls, safeUnpriced); + } + const out = qrFormatOutput(st, safeUsed); if (eventKind !== 'idle') { recordLog(eventKind, { @@ -1342,6 +1836,10 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu excessPct, ...out, }); + } else if (extReconciled) { + persistIfNeeded('external_usage', nowMs); + } else if (prevDensity === null && st.usdPerMTok !== null) { + persistIfNeeded('normal', nowMs); } return out; } @@ -1361,119 +1859,145 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu const normalizedAccountScope = String(accountScope || '').trim().toLowerCase(); const scopePrefix = `${String(endpointId || 'local')}::${normalizedAccountScope}`; - for (const [poolKey, poolObj] of quotaPoolsMap.entries()) { - if (!poolObj || typeof poolObj !== 'object') continue; - const pStats = poolCycleStats instanceof Map ? poolCycleStats.get(poolKey) : null; - const recent10m = pStats?.recent10m || null; - const poolLastActivityMs = Number(recent10m?.lastActivityMs) || 0; - const activeSessionCount10m = Number(recent10m?.activeSessionCount) || 0; - const recent10mCostUsd = Number(recent10m?.costUsd) || 0; - const hasRunningLocalSession = Boolean( - hasUnknownRunningPool || - (runningPoolKeys instanceof Set && runningPoolKeys.has(poolKey)) - ); + batchingDepth += 1; + try { + for (const [poolKey, poolObj] of quotaPoolsMap.entries()) { + if (!poolObj || typeof poolObj !== 'object') continue; + const pStats = poolCycleStats instanceof Map ? poolCycleStats.get(poolKey) : null; + const recent10m = pStats?.recent10m || null; + const poolLastActivityMs = Number(recent10m?.lastActivityMs) || 0; + const activeSessionCount10m = Number(recent10m?.activeSessionCount) || 0; + const recent10mCostUsd = Number(recent10m?.costUsd) || 0; + const hasRunningLocalSession = Boolean( + hasUnknownRunningPool || + (runningPoolKeys instanceof Set && runningPoolKeys.has(poolKey)) + ); - const key5h = `${scopePrefix}::${poolKey}::5h`; - const keyWk = `${scopePrefix}::${poolKey}::weekly`; - const used5hExact = poolObj.has5h ? qrResolveExactUsedPct(poolObj, '5h') : null; - const usedWkExact = poolObj.hasWeekly ? qrResolveExactUsedPct(poolObj, 'weekly') : null; - const reset5hMs = parseIsoMs(poolObj.resetTime); - const resetWkMs = parseIsoMs(poolObj.weeklyResetTime); - const cost5hUsd = pStats?.exactCost5hUsd ?? pStats?.cycle5h?.costUsd ?? 0; - const costWkUsd = pStats?.exactCostWeeklyUsd ?? pStats?.cycleWeekly?.costUsd ?? 0; - const modelCosts5h = pStats?.modelCosts5h || null; - const modelCostsWk = pStats?.modelCostsWeekly || null; + const key5h = `${scopePrefix}::${poolKey}::5h`; + const keyWk = `${scopePrefix}::${poolKey}::weekly`; + const used5hExact = poolObj.has5h ? qrResolveExactUsedPct(poolObj, '5h') : null; + const usedWkExact = poolObj.hasWeekly ? qrResolveExactUsedPct(poolObj, 'weekly') : null; + const reset5hMs = parseIsoMs(poolObj.resetTime); + const resetWkMs = parseIsoMs(poolObj.weeklyResetTime); + const cost5hUsd = pStats?.exactCost5hUsd ?? pStats?.cycle5h?.costUsd ?? 0; + const costWkUsd = pStats?.exactCostWeeklyUsd ?? pStats?.cycleWeekly?.costUsd ?? 0; + const calls5h = pStats?.cycle5h?.calls || 0; + const callsWk = pStats?.cycleWeekly?.calls || 0; + const unpriced5h = pStats?.cycle5h?.unpricedCalls || 0; + const unpricedWk = pStats?.cycleWeekly?.unpricedCalls || 0; + const pricedTokens5h = + pStats?.pricedTokens5h ?? (unpriced5h === 0 ? pStats?.cycle5h?.tokens || 0 : 0); + const pricedTokensWk = + pStats?.pricedTokensWeekly ?? (unpricedWk === 0 ? pStats?.cycleWeekly?.tokens || 0 : 0); + const modelCosts5h = pStats?.modelCosts5h || null; + const modelCostsWk = pStats?.modelCostsWeekly || null; + const modelTokens5h = pStats?.modelTokens5h || null; + const modelTokensWk = pStats?.modelTokensWeekly || null; - const prev5hSt = buckets.get(key5h) || null; - const prevWkSt = buckets.get(keyWk) || null; - const peerExtTs5h = Number(prevWkSt?.lastExternalUsageAtMs) || 0; - const peerExtTsWk = Number(prev5hSt?.lastExternalUsageAtMs) || 0; + const prev5hSt = buckets.get(key5h) || null; + const prevWkSt = buckets.get(keyWk) || null; + const peerExtTs5h = Number(prevWkSt?.lastExternalUsageAtMs) || 0; + const peerExtTsWk = Number(prev5hSt?.lastExternalUsageAtMs) || 0; - // 第 2 层:同一快照下 5h / 周限按已校准费率等比同涨 -> 判定为同一笔家庭组/外部真实消耗而非租约 - const isProportionalExternal = - used5hExact !== null && usedWkExact !== null - ? qrDetectProportionalExternalJump( - prev5hSt, - prevWkSt, - { + // 第 2 层:同一快照下 5h / 周限按已校准费率等比同涨 -> 判定为同一笔家庭组/外部真实消耗而非租约 + const isProportionalExternal = + used5hExact !== null && usedWkExact !== null + ? qrDetectProportionalExternalJump( + prev5hSt, + prevWkSt, + { + officialUsedPct: used5hExact, + resetTimeMs: reset5hMs, + quotaFetchedAtMs, + cycleCostUsd: cost5hUsd, + modelCostsUsd: modelCosts5h, + nowMs, + }, + { + officialUsedPct: usedWkExact, + resetTimeMs: resetWkMs, + quotaFetchedAtMs, + cycleCostUsd: costWkUsd, + modelCostsUsd: modelCostsWk, + nowMs, + } + ) + : false; + + const res5h = + used5hExact !== null + ? observeBucket({ + bucketKey: key5h, + poolKey, + win: '5h', officialUsedPct: used5hExact, resetTimeMs: reset5hMs, quotaFetchedAtMs, cycleCostUsd: cost5hUsd, + cycleCalls: calls5h, + pricedTokens: pricedTokens5h, modelCostsUsd: modelCosts5h, + modelTokens: modelTokens5h, + unpricedCalls: unpriced5h, + poolLastActivityMs, + activeSessionCount10m, + recent10mCostUsd, + hasRunningLocalSession, + forceExternalJump: isProportionalExternal, + peerLastExternalUsageAtMs: peerExtTs5h, nowMs, - }, - { + }) + : { reservedPct: 0, reservedLeaseCount: 0, reservedExpiresAtMs: null }; + + const updated5hExtTs = Math.max( + peerExtTsWk, + Number(buckets.get(key5h)?.lastExternalUsageAtMs) || 0 + ); + + const resWk = + usedWkExact !== null + ? observeBucket({ + bucketKey: keyWk, + poolKey, + win: 'weekly', officialUsedPct: usedWkExact, resetTimeMs: resetWkMs, quotaFetchedAtMs, cycleCostUsd: costWkUsd, + cycleCalls: callsWk, + pricedTokens: pricedTokensWk, modelCostsUsd: modelCostsWk, + modelTokens: modelTokensWk, + unpricedCalls: unpricedWk, + poolLastActivityMs, + activeSessionCount10m, + recent10mCostUsd, + hasRunningLocalSession, + forceExternalJump: isProportionalExternal, + peerLastExternalUsageAtMs: updated5hExtTs, nowMs, - } - ) - : false; + }) + : { reservedPct: 0, reservedLeaseCount: 0, reservedExpiresAtMs: null }; - const res5h = - used5hExact !== null - ? observeBucket({ - bucketKey: key5h, - poolKey, - win: '5h', - officialUsedPct: used5hExact, - resetTimeMs: reset5hMs, - quotaFetchedAtMs, - cycleCostUsd: cost5hUsd, - modelCostsUsd: modelCosts5h, - unpricedCalls: pStats?.cycle5h?.unpricedCalls || 0, - poolLastActivityMs, - activeSessionCount10m, - recent10mCostUsd, - hasRunningLocalSession, - forceExternalJump: isProportionalExternal, - peerLastExternalUsageAtMs: peerExtTs5h, - nowMs, - }) - : { reservedPct: 0, reservedLeaseCount: 0, reservedExpiresAtMs: null }; - - const updated5hExtTs = Math.max( - peerExtTsWk, - Number(buckets.get(key5h)?.lastExternalUsageAtMs) || 0 - ); - - const resWk = - usedWkExact !== null - ? observeBucket({ - bucketKey: keyWk, - poolKey, - win: 'weekly', - officialUsedPct: usedWkExact, - resetTimeMs: resetWkMs, - quotaFetchedAtMs, - cycleCostUsd: costWkUsd, - modelCostsUsd: modelCostsWk, - unpricedCalls: pStats?.cycleWeekly?.unpricedCalls || 0, - poolLastActivityMs, - activeSessionCount10m, - recent10mCostUsd, - hasRunningLocalSession, - forceExternalJump: isProportionalExternal, - peerLastExternalUsageAtMs: updated5hExtTs, - nowMs, - }) - : { reservedPct: 0, reservedLeaseCount: 0, reservedExpiresAtMs: null }; - - poolObj.reservedPct = res5h.reservedPct; - poolObj.reservedLeaseCount = res5h.reservedLeaseCount; - poolObj.reservedExpiresAtMs = res5h.reservedExpiresAtMs; - poolObj.weeklyReservedPct = resWk.reservedPct; - poolObj.weeklyReservedLeaseCount = resWk.reservedLeaseCount; - poolObj.weeklyReservedExpiresAtMs = resWk.reservedExpiresAtMs; - poolObj.rateEstimate = qrBuildPoolRateEstimate( - buckets.get(key5h) || null, - buckets.get(keyWk) || null, - nowMs - ); + poolObj.reservedPct = res5h.reservedPct; + poolObj.reservedLeaseCount = res5h.reservedLeaseCount; + poolObj.reservedExpiresAtMs = res5h.reservedExpiresAtMs; + poolObj.weeklyReservedPct = resWk.reservedPct; + poolObj.weeklyReservedLeaseCount = resWk.reservedLeaseCount; + poolObj.weeklyReservedExpiresAtMs = resWk.reservedExpiresAtMs; + poolObj.rateEstimate = qrBuildPoolRateEstimate( + buckets.get(key5h) || null, + buckets.get(keyWk) || null, + nowMs + ); + } + } finally { + batchingDepth = Math.max(0, batchingDepth - 1); + if (batchingDepth === 0 && batchPendingEvent) { + const pending = batchPendingEvent; + batchPendingEvent = null; + persistIfNeeded(pending, nowMs); + } } } @@ -1525,6 +2049,8 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu buckets.clear(); eventLog.length = 0; lastPersistMs = 0; + batchingDepth = 0; + batchPendingEvent = null; hydrated = true; } diff --git a/sidecars/panel/backend/telemetry-builder.mjs b/sidecars/panel/backend/telemetry-builder.mjs index ca4f86a..7a8d93e 100644 --- a/sidecars/panel/backend/telemetry-builder.mjs +++ b/sidecars/panel/backend/telemetry-builder.mjs @@ -2249,6 +2249,16 @@ export async function buildTelemetryPayloadInternal( }); } + const sortedQuotaPools = Array.from(quotaPoolsMap.values()).sort((a, b) => { + const order = { Gemini: 0, Argon: 1, Carbon: 2, 'Claude & GPT': 3 }; + return (order[a.family] ?? 99) - (order[b.family] ?? 99); + }); + const weeklyCapacityEstimate = buildWeeklyCapacityEstimate({ + sortedPools: sortedQuotaPools, + isCustomWeeklyMode, + hasOfficialData: Boolean(officialQuotaInfo?.data), + }); + const finalPayload = { timestamp: new Date().toISOString(), hostPlatform: process.platform || 'unknown', @@ -2356,11 +2366,9 @@ export async function buildTelemetryPayloadInternal( errorMessage: officialQuotaInfo?.error || null, }, activePool: activePoolQuota, - pools: Array.from(quotaPoolsMap.values()).sort((a, b) => { - const order = { Gemini: 0, Argon: 1, Carbon: 2, 'Claude & GPT': 3 }; - return (order[a.family] ?? 99) - (order[b.family] ?? 99); - }), + pools: sortedQuotaPools, weekly: weeklyQuota, + weeklyCapacityEstimate, }, modelBreakdown, }; @@ -2556,6 +2564,7 @@ function tryBuildFastConversationPayload(requestedConvId, filterOpts = {}) { quotas: { activePool: activePoolQuota, weekly: weeklyQuota, + weeklyCapacityEstimate: snap.basePayload.quotas?.weeklyCapacityEstimate || null, }, consumption: { session: sessionUsage.finalizedSelectedSession, @@ -2565,6 +2574,120 @@ function tryBuildFastConversationPayload(requestedConvId, filterOpts = {}) { }; } +function buildWeeklyCapacityEstimate({ + sortedPools = [], + isCustomWeeklyMode = false, + hasOfficialData = false, +} = {}) { + if (isCustomWeeklyMode) { + return { + status: 'custom_mode', + totalEqWeeklyUsd: null, + totalEqWeeklyTokens: null, + readyPoolCount: 0, + totalPoolCount: 0, + hasPreliminary: false, + pools: [], + }; + } + const rawPools = Array.isArray(sortedPools) ? sortedPools : []; + const candidatePools = rawPools.filter( + (p) => + p && + (p.hasWeekly || + p.weeklyUsedPct != null || + Number.isFinite(p.rateEstimate?.eqFullWeeklyUsd)) + ); + const targetPools = candidatePools.length > 0 ? candidatePools : rawPools; + if (!hasOfficialData && targetPools.length === 0) { + return { + status: 'unavailable', + totalEqWeeklyUsd: null, + totalEqWeeklyTokens: null, + readyPoolCount: 0, + totalPoolCount: 0, + hasPreliminary: false, + pools: [], + }; + } + + let sumUsd = 0; + let sumTokens = 0; + let readyPoolCount = 0; + let tokenReadyPoolCount = 0; + let hasPreliminary = false; + const pools = []; + + for (const p of targetPools) { + const est = p?.rateEstimate && typeof p.rateEstimate === 'object' ? p.rateEstimate : null; + let eqUsd = + Number.isFinite(est?.eqFullWeeklyUsd) && est.eqFullWeeklyUsd > 0 + ? Number(est.eqFullWeeklyUsd) + : null; + let eqTok = + Number.isFinite(est?.eqFullWeeklyTokens) && est.eqFullWeeklyTokens > 0 + ? Math.round(Number(est.eqFullWeeklyTokens)) + : null; + if (eqUsd === null && Array.isArray(est?.models) && est.models.length > 0) { + const wkModels = est.models.filter( + (m) => Number.isFinite(m?.eqFullWeeklyUsd) && m.eqFullWeeklyUsd > 0 + ); + if (wkModels.length > 0) { + eqUsd = + wkModels.reduce((acc, m) => acc + Number(m.eqFullWeeklyUsd), 0) / wkModels.length; + const tokModels = wkModels.filter( + (m) => Number.isFinite(m?.eqFullWeeklyTokens) && m.eqFullWeeklyTokens > 0 + ); + if (tokModels.length === wkModels.length) { + eqTok = Math.round( + tokModels.reduce((acc, m) => acc + Number(m.eqFullWeeklyTokens), 0) / tokModels.length + ); + } + } + } + + const isPrelim = Boolean(est?.isPreliminaryWeekly); + if (eqUsd !== null) { + readyPoolCount += 1; + sumUsd += eqUsd; + if (isPrelim) hasPreliminary = true; + if (eqTok !== null) { + tokenReadyPoolCount += 1; + sumTokens += eqTok; + } + } + + pools.push({ + poolKey: p.poolKey || p.family || '', + poolLabel: p.poolLabel || p.family || p.poolKey || 'Pool', + usedWeeklyPct: Number.isFinite(Number(p.weeklyUsedPct)) ? +Number(p.weeklyUsedPct).toFixed(1) : null, + eqFullWeeklyUsd: eqUsd !== null ? +eqUsd.toFixed(1) : null, + eqFullWeeklyTokens: eqTok, + source: est?.sourceWeekly || null, + isPreliminary: isPrelim, + }); + } + + const totalPoolCount = pools.length; + const status = + readyPoolCount === 0 + ? 'collecting' + : readyPoolCount < totalPoolCount + ? 'partial' + : 'ready'; + + return { + status, + totalEqWeeklyUsd: readyPoolCount > 0 ? +sumUsd.toFixed(1) : null, + totalEqWeeklyTokens: + readyPoolCount > 0 && tokenReadyPoolCount === readyPoolCount ? Math.round(sumTokens) : null, + readyPoolCount, + totalPoolCount, + hasPreliminary, + pools, + }; +} + function enrichTopConversationTitles(topList, convSummaries) { if (!Array.isArray(topList) || topList.length === 0) return []; const titleMap = new Map(); diff --git a/sidecars/panel/backend/usage-aggregator.mjs b/sidecars/panel/backend/usage-aggregator.mjs index 22d6655..60e4f6f 100644 --- a/sidecars/panel/backend/usage-aggregator.mjs +++ b/sidecars/panel/backend/usage-aggregator.mjs @@ -794,8 +794,12 @@ function buildQuotaPoolCycleMap(quotaPoolsMap, nowMs) { startWkMs, b5h: createUsageBucket(), bWk: createUsageBucket(), + pricedTokens5h: 0, + pricedTokensWk: 0, modelCosts5h: new Map(), modelCostsWk: new Map(), + modelTokens5h: new Map(), + modelTokensWk: new Map(), lastActivityMs: 0, recent10mSessions: new Map(), }); @@ -1610,20 +1614,38 @@ export function aggregateMultiWindowUsage({ const quotaModelKey = mInfo.baseLabel || mInfo.label || ''; if (qMs >= poolBucketEntry.start5hMs) { accumulateStepIntoBucket(poolBucketEntry.b5h, stepUsage, cascadeId); + if (stepUsage.resolvedCost > 0 && stepTotalTokens > 0) { + poolBucketEntry.pricedTokens5h += stepTotalTokens; + } if (quotaModelKey && stepUsage.resolvedCost > 0) { poolBucketEntry.modelCosts5h.set( quotaModelKey, (poolBucketEntry.modelCosts5h.get(quotaModelKey) || 0) + stepUsage.resolvedCost ); + if (stepTotalTokens > 0) { + poolBucketEntry.modelTokens5h.set( + quotaModelKey, + (poolBucketEntry.modelTokens5h.get(quotaModelKey) || 0) + stepTotalTokens + ); + } } } if (qMs >= poolBucketEntry.startWkMs) { accumulateStepIntoBucket(poolBucketEntry.bWk, stepUsage, cascadeId); + if (stepUsage.resolvedCost > 0 && stepTotalTokens > 0) { + poolBucketEntry.pricedTokensWk += stepTotalTokens; + } if (quotaModelKey && stepUsage.resolvedCost > 0) { poolBucketEntry.modelCostsWk.set( quotaModelKey, (poolBucketEntry.modelCostsWk.get(quotaModelKey) || 0) + stepUsage.resolvedCost ); + if (stepTotalTokens > 0) { + poolBucketEntry.modelTokensWk.set( + quotaModelKey, + (poolBucketEntry.modelTokensWk.get(quotaModelKey) || 0) + stepTotalTokens + ); + } } } } @@ -1836,6 +1858,16 @@ export function aggregateMultiWindowUsage({ } return out; }; + const serializeModelTokens = (mMap) => { + const out = {}; + if (!(mMap instanceof Map)) return out; + for (const [mKey, tokVal] of mMap.entries()) { + if (mKey && Number.isFinite(tokVal) && tokVal > 0) { + out[mKey] = Math.round(tokVal); + } + } + return out; + }; for (const [poolKey, entry] of poolCycleBuckets.entries()) { let recent10mCostUsd = 0; for (const sStat of entry.recent10mSessions.values()) { @@ -1844,10 +1876,14 @@ export function aggregateMultiWindowUsage({ poolCycleStats.set(poolKey, { cycle5h: formatCycleSummary(entry.b5h), cycleWeekly: formatCycleSummary(entry.bWk), + pricedTokens5h: Math.round(entry.pricedTokens5h || 0), + pricedTokensWeekly: Math.round(entry.pricedTokensWk || 0), exactCost5hUsd: +entry.b5h.costUsd.toFixed(6), exactCostWeeklyUsd: +entry.bWk.costUsd.toFixed(6), modelCosts5h: serializeModelCosts(entry.modelCosts5h), modelCostsWeekly: serializeModelCosts(entry.modelCostsWk), + modelTokens5h: serializeModelTokens(entry.modelTokens5h), + modelTokensWeekly: serializeModelTokens(entry.modelTokensWk), recent10m: { lastActivityMs: entry.lastActivityMs, activeSessionCount: entry.recent10mSessions.size, diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index 75d4058..7ca2a9b 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/src/components/widgets/QuotaPoolsWidget.js b/sidecars/panel/src/components/widgets/QuotaPoolsWidget.js index 2fcbd3a..157d4dc 100644 --- a/sidecars/panel/src/components/widgets/QuotaPoolsWidget.js +++ b/sidecars/panel/src/components/widgets/QuotaPoolsWidget.js @@ -244,21 +244,24 @@ export function syncPoolQuotaRow(refs, item, idx, rowEl) { patchText(refs.title5h, `5h (${poolLabel})`); const c5h = poolData?.cycle5h; + const est = poolData?.rateEstimate; if (!isPending && has5h && c5h && (c5h.tokens != null || c5h.costUsd != null)) { const tok5h = formatTokens(c5h.tokens || 0); const cost5h = formatUsd(c5h.costUsd || 0); const calls5h = Number(c5h.calls || 0); + const full5hRef = formatPoolFullCapRef(est?.eqFull5hUsd, est?.eqFull5hTokens); + const baseTip5h = t('quota.cycle5hTitle', { + pool: poolLabel, + tok: tok5h, + cost: cost5h, + calls: calls5h, + }); refs.usage5h.hidden = false; patchText(refs.usage5h, `· ${tok5h} (${cost5h})`); patchAttr( refs.left5h, 'title', - t('quota.cycle5hTitle', { - pool: poolLabel, - tok: tok5h, - cost: cost5h, - calls: calls5h, - }) + full5hRef ? `${baseTip5h} · ${t('quota.cycleFullSuffix', { full: full5hRef })}` : baseTip5h ); } else { refs.usage5h.hidden = true; @@ -291,19 +294,23 @@ export function syncPoolQuotaRow(refs, item, idx, rowEl) { const tokWk = formatTokens(cWk.tokens || 0); const costWk = formatUsd(cWk.costUsd || 0); const callsWk = Number(cWk.calls || 0); + const fullWkRef = !useCustomWeekly + ? formatPoolFullCapRef(est?.eqFullWeeklyUsd, est?.eqFullWeeklyTokens) + : ''; + const baseTipWk = useCustomWeekly + ? t('quota.cycleWkCustomTitle', { tok: tokWk, cost: costWk, calls: callsWk }) + : t('quota.cycleWkPoolTitle', { + pool: poolLabel, + tok: tokWk, + cost: costWk, + calls: callsWk, + }); refs.usageWk.hidden = false; patchText(refs.usageWk, `· ${tokWk} (${costWk})`); patchAttr( refs.leftWk, 'title', - useCustomWeekly - ? t('quota.cycleWkCustomTitle', { tok: tokWk, cost: costWk, calls: callsWk }) - : t('quota.cycleWkPoolTitle', { - pool: poolLabel, - tok: tokWk, - cost: costWk, - calls: callsWk, - }) + fullWkRef ? `${baseTipWk} · ${t('quota.cycleFullSuffix', { full: fullWkRef })}` : baseTipWk ); } else { refs.usageWk.hidden = true; @@ -328,8 +335,9 @@ export function syncPoolQuotaRow(refs, item, idx, rowEl) { export function quotaPoolRowSig(item, idx) { const c5h = item.poolData?.cycle5h; const cWk = item.poolData?.cycleWeekly; + const est = item.poolData?.rateEstimate; const fw = item.fallbackWeekly; - return `${getEffectiveLocale()}:${idx}:${item.poolLabel}:${item.isActivePool}:${Boolean(item.isPending)}:${Boolean(item.showReserved)}:${item.minuteTick}:${item.poolData?.usedPct}:${item.poolData?.remainingPct}:${item.poolData?.reservedPct}:${item.poolData?.reservedLeaseCount}:${item.poolData?.resetTime}:${item.poolData?.weeklyUsedPct}:${item.poolData?.weeklyRemainingPct}:${item.poolData?.weeklyReservedPct}:${item.poolData?.weeklyReservedLeaseCount}:${item.poolData?.weeklyResetTime}:${c5h?.tokens}:${c5h?.costUsd}:${c5h?.calls}:${cWk?.tokens}:${cWk?.costUsd}:${cWk?.calls}:${fw?.isOfficial}:${fw?.usedPct}:${fw?.remainingPct}:${fw?.resetTime}:${fw?.title}:${fw?.tokens}:${fw?.costUsd}:${fw?.calls}`; + return `${getEffectiveLocale()}:${idx}:${item.poolLabel}:${item.isActivePool}:${Boolean(item.isPending)}:${Boolean(item.showReserved)}:${item.minuteTick}:${item.poolData?.usedPct}:${item.poolData?.remainingPct}:${item.poolData?.reservedPct}:${item.poolData?.reservedLeaseCount}:${item.poolData?.resetTime}:${item.poolData?.weeklyUsedPct}:${item.poolData?.weeklyRemainingPct}:${item.poolData?.weeklyReservedPct}:${item.poolData?.weeklyReservedLeaseCount}:${item.poolData?.weeklyResetTime}:${c5h?.tokens}:${c5h?.costUsd}:${c5h?.calls}:${cWk?.tokens}:${cWk?.costUsd}:${cWk?.calls}:${est?.eqFull5hUsd}:${est?.eqFull5hTokens}:${est?.eqFullWeeklyUsd}:${est?.eqFullWeeklyTokens}:${fw?.isOfficial}:${fw?.usedPct}:${fw?.remainingPct}:${fw?.resetTime}:${fw?.title}:${fw?.tokens}:${fw?.costUsd}:${fw?.calls}`; } /** @@ -405,6 +413,99 @@ function formatRateEqUsd(val) { return `$${Number(num.toFixed(1))}`; } +function formatPoolFullCapRef(eqUsd, eqTok) { + const usdNum = Number(eqUsd); + if (!Number.isFinite(usdNum) || usdNum <= 0) return ''; + const usdStr = formatRateEqUsd(usdNum); + const tokNum = Number(eqTok); + if (Number.isFinite(tokNum) && tokNum > 0) { + return `${usdStr} (${formatTokens(tokNum)})`; + } + return usdStr; +} + +function resolveWeeklyCapacitySummary(quotas) { + if (!quotas || typeof quotas !== 'object') return null; + if (quotas.weekly?.isOfficial === false) return null; + const direct = quotas.weeklyCapacityEstimate; + if (direct && typeof direct === 'object') { + if ( + direct.status === 'custom_mode' || + !Number.isFinite(Number(direct.totalEqWeeklyUsd)) || + Number(direct.totalEqWeeklyUsd) <= 0 + ) { + return null; + } + return direct; + } + + const rawPools = Array.isArray(quotas.pools) ? quotas.pools : []; + const candidatePools = rawPools.filter( + (p) => + p && + (p.hasWeekly || + p.weeklyUsedPct != null || + Number.isFinite(p.rateEstimate?.eqFullWeeklyUsd)) + ); + const targetPools = candidatePools.length > 0 ? candidatePools : rawPools; + if (targetPools.length === 0) return null; + + let sumUsd = 0; + let sumTokens = 0; + let readyPoolCount = 0; + let tokenReadyPoolCount = 0; + let hasPreliminary = false; + + for (const p of targetPools) { + const est = p?.rateEstimate && typeof p.rateEstimate === 'object' ? p.rateEstimate : null; + let eqUsd = + Number.isFinite(est?.eqFullWeeklyUsd) && est.eqFullWeeklyUsd > 0 + ? Number(est.eqFullWeeklyUsd) + : null; + let eqTok = + Number.isFinite(est?.eqFullWeeklyTokens) && est.eqFullWeeklyTokens > 0 + ? Math.round(Number(est.eqFullWeeklyTokens)) + : null; + if (eqUsd === null && Array.isArray(est?.models) && est.models.length > 0) { + const wkModels = est.models.filter( + (m) => Number.isFinite(m?.eqFullWeeklyUsd) && m.eqFullWeeklyUsd > 0 + ); + if (wkModels.length > 0) { + eqUsd = + wkModels.reduce((acc, m) => acc + Number(m.eqFullWeeklyUsd), 0) / wkModels.length; + const tokModels = wkModels.filter( + (m) => Number.isFinite(m?.eqFullWeeklyTokens) && m.eqFullWeeklyTokens > 0 + ); + if (tokModels.length === wkModels.length) { + eqTok = Math.round( + tokModels.reduce((acc, m) => acc + Number(m.eqFullWeeklyTokens), 0) / tokModels.length + ); + } + } + } + if (eqUsd !== null) { + readyPoolCount += 1; + sumUsd += eqUsd; + if (est?.isPreliminaryWeekly) hasPreliminary = true; + if (eqTok !== null) { + tokenReadyPoolCount += 1; + sumTokens += eqTok; + } + } + } + + if (readyPoolCount === 0) return null; + const totalPoolCount = targetPools.length; + return { + status: readyPoolCount < totalPoolCount ? 'partial' : 'ready', + totalEqWeeklyUsd: +sumUsd.toFixed(1), + totalEqWeeklyTokens: tokenReadyPoolCount === readyPoolCount ? Math.round(sumTokens) : null, + readyPoolCount, + totalPoolCount, + hasPreliminary, + }; +} + function formatRatePerUsdValue(rate) { const num = Number(rate); if (!Number.isFinite(num) || num <= 0) return '--'; @@ -426,7 +527,11 @@ function createRateModelCard({ rateWeeklyPctPerUsd = null, eqFull5hUsd = null, eqFullWeeklyUsd = null, + eqFull5hTokens = null, + eqFullWeeklyTokens = null, samples = 0, + source = null, + isPreliminary = false, }) { const leftNodes = [ h('span', { @@ -455,32 +560,50 @@ function createRateModelCard({ }) ); } - if (Number(samples) > 0) { + if (isPreliminary) { + subParts.push( + source === 'anchor_slope' ? t('quota.ratePopPrelimSlope') : t('quota.ratePopPrelimCycle') + ); + } else 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') }), + const cell5hChildren = [ + h('span', { className: 'quota-rate-eq-k', text: t('quota.ratePopEq5hLabel') }), + h('span', { + className: 'quota-rate-eq-v text-mono', + text: `≈ ${formatRateEqUsd(eqFull5hUsd)}`, + }), + ]; + if (Number.isFinite(Number(eqFull5hTokens)) && Number(eqFull5hTokens) > 0) { + cell5hChildren.push( h('span', { - className: 'quota-rate-eq-v text-mono', - text: `≈ ${formatRateEqUsd(eqFull5hUsd)}`, - }), - ]) - ); + className: 'quota-rate-eq-tok text-mono', + text: `· ${formatTokens(Number(eqFull5hTokens))}`, + }) + ); + } + eqCells.push(h('div', { className: 'quota-rate-eq-cell' }, cell5hChildren)); } if (eqFullWeeklyUsd != null) { - eqCells.push( - h('div', { className: 'quota-rate-eq-cell' }, [ - h('span', { className: 'quota-rate-eq-k', text: t('quota.ratePopEqWkLabel') }), + const cellWkChildren = [ + h('span', { className: 'quota-rate-eq-k', text: t('quota.ratePopEqWkLabel') }), + h('span', { + className: 'quota-rate-eq-v text-mono', + text: `≈ ${formatRateEqUsd(eqFullWeeklyUsd)}`, + }), + ]; + if (Number.isFinite(Number(eqFullWeeklyTokens)) && Number(eqFullWeeklyTokens) > 0) { + cellWkChildren.push( h('span', { - className: 'quota-rate-eq-v text-mono', - text: `≈ ${formatRateEqUsd(eqFullWeeklyUsd)}`, - }), - ]) - ); + className: 'quota-rate-eq-tok text-mono', + text: `· ${formatTokens(Number(eqFullWeeklyTokens))}`, + }) + ); + } + eqCells.push(h('div', { className: 'quota-rate-eq-cell' }, cellWkChildren)); } const cardChildren = [ @@ -507,11 +630,13 @@ function createRateModelCard({ function buildRatePopoverSig(data) { const locale = getEffectiveLocale(); const acct = String(data?.account?.email || data?.account?.name || '').trim(); + const isOfficial = data?.quotas?.weekly?.isOfficial !== false; + const wkCapSig = JSON.stringify(data?.quotas?.weeklyCapacityEstimate || null); 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}`; + return `${locale}|${acct}|${isOfficial}|${wkCapSig}|${poolSig}`; } export const QuotaPoolsWidget = defineComponent({ @@ -529,6 +654,27 @@ export const QuotaPoolsWidget = defineComponent({ className: 'quota-rate-pop-account', text: t('quota.ratePopAccountCurrent'), }); + const ratePopWkLabelEl = h('span', { text: t('quota.ratePopWkCapTitle') }); + const ratePopWkSubEl = h('span', { + className: 'quota-rate-wk-sub', + hidden: true, + text: '', + }); + const ratePopWkUsdEl = h('span', { className: 'quota-rate-wk-usd text-mono', text: '--' }); + const ratePopWkTokEl = h('span', { + className: 'quota-rate-wk-tok text-mono', + hidden: true, + text: '', + }); + const ratePopWkSummaryEl = h( + 'div', + { className: 'quota-rate-wk-summary', hidden: true }, + [ + h('span', { className: 'quota-rate-wk-k' }, [ratePopWkLabelEl, ratePopWkSubEl]), + h('span', { className: 'quota-rate-wk-v' }, [ratePopWkUsdEl, ratePopWkTokEl]), + ] + ); + ratePopWkSummaryEl.hidden = true; const ratePopBodyEl = h('div', { className: 'quota-rate-pop-body' }); const ratePopNoteEl = h('div', { className: 'quota-rate-pop-note', @@ -543,6 +689,7 @@ export const QuotaPoolsWidget = defineComponent({ }, [ h('div', { className: 'quota-rate-pop-head' }, [ratePopTitleEl, ratePopAccountEl]), + ratePopWkSummaryEl, ratePopBodyEl, ratePopNoteEl, ] @@ -634,6 +781,38 @@ export const QuotaPoolsWidget = defineComponent({ ); patchAttr(ratePopAccountEl, 'title', acctMasked || null); + const wkCap = resolveWeeklyCapacitySummary(data?.quotas); + if (wkCap) { + ratePopWkSummaryEl.hidden = false; + patchAttr(ratePopWkSummaryEl, 'hidden', false); + patchText(ratePopWkLabelEl, t('quota.ratePopWkCapTitle')); + const wkSubText = + wkCap.status === 'partial' && Number(wkCap.totalPoolCount) > 0 + ? t('quota.ratePopWkCapPartial', { + ready: Number(wkCap.readyPoolCount) || 0, + total: Number(wkCap.totalPoolCount) || 0, + }) + : wkCap.hasPreliminary + ? t('quota.ratePopWkCapPrelim') + : ''; + ratePopWkSubEl.hidden = !wkSubText; + patchAttr(ratePopWkSubEl, 'hidden', !wkSubText); + patchText(ratePopWkSubEl, wkSubText); + patchText(ratePopWkUsdEl, `≈ ${formatRateEqUsd(wkCap.totalEqWeeklyUsd)}`); + const hasWkTok = + Number.isFinite(Number(wkCap.totalEqWeeklyTokens)) && + Number(wkCap.totalEqWeeklyTokens) > 0; + ratePopWkTokEl.hidden = !hasWkTok; + patchAttr(ratePopWkTokEl, 'hidden', !hasWkTok); + patchText( + ratePopWkTokEl, + hasWkTok ? `· ${formatTokens(Number(wkCap.totalEqWeeklyTokens))}` : '' + ); + } else { + ratePopWkSummaryEl.hidden = true; + patchAttr(ratePopWkSummaryEl, 'hidden', true); + } + while (ratePopBodyEl.firstChild) { ratePopBodyEl.removeChild(ratePopBodyEl.firstChild); } @@ -652,19 +831,45 @@ export const QuotaPoolsWidget = defineComponent({ if (models.length === 0 && !hasPoolFallback && !ext) continue; const poolLabel = p.poolLabel || p.family || p.poolKey || 'Pool'; + const fallbackPrimaryIs5h = est.rate5hPctPerUsd != null; + const anyModelHasWeekly = models.some((m) => m?.eqFullWeeklyUsd != null); + const needsWeeklyFallbackRow = + models.length > 0 && + !anyModelHasWeekly && + Number.isFinite(est.rateWeeklyPctPerUsd) && + est.eqFullWeeklyUsd != null; 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, - }) - ) + ? [ + ...models.map((item) => + createRateModelCard({ + name: item.model, + multiplier: item.multiplier, + rate5hPctPerUsd: item.rate5hPctPerUsd, + rateWeeklyPctPerUsd: item.rateWeeklyPctPerUsd, + eqFull5hUsd: item.eqFull5hUsd, + eqFullWeeklyUsd: item.eqFullWeeklyUsd, + eqFull5hTokens: item.eqFull5hTokens, + eqFullWeeklyTokens: item.eqFullWeeklyTokens, + samples: item.samples, + }) + ), + ...(needsWeeklyFallbackRow + ? [ + createRateModelCard({ + name: t('quota.ratePopPoolFallback'), + isMutedName: true, + isFallback: true, + rateWeeklyPctPerUsd: est.rateWeeklyPctPerUsd, + eqFullWeeklyUsd: est.eqFullWeeklyUsd, + eqFullWeeklyTokens: est.eqFullWeeklyTokens, + samples: Number(est.samplesWeekly) || 0, + source: est.sourceWeekly || null, + isPreliminary: Boolean(est.isPreliminaryWeekly), + }), + ] + : []), + ] : hasPoolFallback ? [ createRateModelCard({ @@ -675,7 +880,13 @@ export const QuotaPoolsWidget = defineComponent({ rateWeeklyPctPerUsd: est.rateWeeklyPctPerUsd, eqFull5hUsd: est.eqFull5hUsd, eqFullWeeklyUsd: est.eqFullWeeklyUsd, + eqFull5hTokens: est.eqFull5hTokens, + eqFullWeeklyTokens: est.eqFullWeeklyTokens, samples: Math.max(Number(est.samples5h) || 0, Number(est.samplesWeekly) || 0), + source: fallbackPrimaryIs5h ? est.source5h || null : est.sourceWeekly || null, + isPreliminary: fallbackPrimaryIs5h + ? Boolean(est.isPreliminary5h) + : Boolean(est.isPreliminaryWeekly), }), ] : []; diff --git a/sidecars/panel/src/i18n/en-US.js b/sidecars/panel/src/i18n/en-US.js index 7b356e0..6b8311f 100644 --- a/sidecars/panel/src/i18n/en-US.js +++ b/sidecars/panel/src/i18n/en-US.js @@ -190,6 +190,7 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'quota.cycle5hTitle': 'Current 5h cycle ({pool}): {tok} Tokens · {cost} · {calls} calls', 'quota.cycleWkCustomTitle': 'Current calendar week: {tok} Tokens · {cost} · {calls} calls', 'quota.cycleWkPoolTitle': 'Current weekly cycle ({pool}): {tok} Tokens · {cost} · {calls} calls', + 'quota.cycleFullSuffix': 'Full ~{full}', 'quota.footTokensCustom': 'Week Total: {tok} ({cost})', 'quota.footTokensCycle': 'Cycle Total: {tok} ({cost})', 'quota.footCredits': 'AI Credits: {credits}', @@ -201,13 +202,18 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'quota.ratePopTitle': 'Estimated Burn Rates', 'quota.ratePopAccountScope': '{account}', 'quota.ratePopAccountCurrent': 'Current account', + 'quota.ratePopWkCapTitle': 'Est. Weekly Quota', + 'quota.ratePopWkCapPrelim': '· est.', + 'quota.ratePopWkCapPartial': '· {ready}/{total} pools', '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.', + 'quota.ratePopPrelimSlope': 'slope est.', + 'quota.ratePopPrelimCycle': 'cycle est.', + 'quota.ratePopEmpty': 'Not enough clean samples yet (unlocks at 2% weekly burn or 3 clean single-model steps).', + 'quota.ratePopNote': 'Measured from net burn & priced steps; lowest in pool = 1x. Account isolated.', 'quota.ratePopSharedBadge': 'Shared active', 'quota.ratePopSharedBadgeTip': 'External pool usage seen within 15 min; new reservations display after verification', 'quota.ratePopExternalDetail': 'Family group / other-device usage detected (~{detail} excluded from reservations)', diff --git a/sidecars/panel/src/i18n/zh-CN.js b/sidecars/panel/src/i18n/zh-CN.js index e20bf78..58be7a0 100644 --- a/sidecars/panel/src/i18n/zh-CN.js +++ b/sidecars/panel/src/i18n/zh-CN.js @@ -190,6 +190,7 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'quota.cycle5hTitle': '当前 5h 周期累计 ({pool}):{tok} Tokens · {cost} · {calls} 次调用', 'quota.cycleWkCustomTitle': '本周自然周累计:{tok} Tokens · {cost} · {calls} 次调用', 'quota.cycleWkPoolTitle': '当前周限周期累计 ({pool}):{tok} Tokens · {cost} · {calls} 次调用', + 'quota.cycleFullSuffix': '满池约 {full}', 'quota.footTokensCustom': '本周累计: {tok} ({cost})', 'quota.footTokensCycle': '周期累计: {tok} ({cost})', 'quota.footCredits': 'AI 积分: {credits}', @@ -201,13 +202,18 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'quota.ratePopTitle': '实测倍率预估', 'quota.ratePopAccountScope': '{account}', 'quota.ratePopAccountCurrent': '当前账号', + 'quota.ratePopWkCapTitle': '预测周额度', + 'quota.ratePopWkCapPrelim': '· 初估', + 'quota.ratePopWkCapPartial': '· {ready}/{total} 池', 'quota.ratePopPoolFallback': '池综合均值', 'quota.ratePopEq5hLabel': '5h 满池', 'quota.ratePopEqWkLabel': '周限满池', 'quota.ratePopPerUsd': '{win} {rate}%/$', 'quota.ratePopSamples': '{n} 样本', - 'quota.ratePopEmpty': '暂未采集到足够的单模型干净样本(每模型需至少 3 次无抖动扣费),正常使用后自动生成。', - 'quota.ratePopNote': '按单模型纯净步实测折算,同池最省为 1x,按账号隔离。', + 'quota.ratePopPrelimSlope': '斜率初估', + 'quota.ratePopPrelimCycle': '周期初估', + 'quota.ratePopEmpty': '暂未采集到足够的单模型干净样本(周限满 2% 或单模型满 3 次无抖动扣费后自动生成)。', + 'quota.ratePopNote': '按净消耗及精确计价折算,同池最省为 1x,按账号隔离。', 'quota.ratePopSharedBadge': '共享活跃', 'quota.ratePopSharedBadgeTip': '最近 15 分钟内检测到同池外部消耗,新增预占将在二次验证后展示', 'quota.ratePopExternalDetail': '检测到家庭组 / 其他设备消耗(已排除约 {detail}),不计入预占', diff --git a/sidecars/panel/src/store/telemetryStore.js b/sidecars/panel/src/store/telemetryStore.js index 703ab12..02433a7 100644 --- a/sidecars/panel/src/store/telemetryStore.js +++ b/sidecars/panel/src/store/telemetryStore.js @@ -1114,6 +1114,12 @@ export function isEquivalentTelemetry(prev, next) { return false; } } + if ( + JSON.stringify(prev.quotas?.weeklyCapacityEstimate || null) !== + JSON.stringify(next.quotas?.weeklyCapacityEstimate || null) + ) { + return false; + } const pConvs = prev.conversations || []; const nConvs = next.conversations || []; diff --git a/sidecars/panel/src/styles/modern-ui.css b/sidecars/panel/src/styles/modern-ui.css index 16b07de..2aa2d83 100644 --- a/sidecars/panel/src/styles/modern-ui.css +++ b/sidecars/panel/src/styles/modern-ui.css @@ -842,10 +842,12 @@ 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-hint, [data-modern-ui="true"] .quota-rate-pop-head, +[data-modern-ui="true"] .quota-rate-wk-summary, [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-wk-summary, :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 { diff --git a/sidecars/panel/src/styles/views-overview.css b/sidecars/panel/src/styles/views-overview.css index 929c862..32c9de0 100644 --- a/sidecars/panel/src/styles/views-overview.css +++ b/sidecars/panel/src/styles/views-overview.css @@ -676,7 +676,7 @@ position: absolute; top: 38px; left: 12px; - width: min(332px, calc(100% - 24px)); + width: min(352px, calc(100% - 24px)); z-index: 45; display: flex; flex-direction: column; @@ -721,10 +721,69 @@ min-width: 0; } +.quota-rate-wk-summary { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 8px; + min-width: 0; + padding-bottom: 7px; + border-bottom: 1px solid var(--border-hairline); +} + +.quota-rate-wk-summary[hidden] { + display: none; +} + +.quota-rate-wk-k { + display: inline-flex; + align-items: baseline; + gap: 5px; + min-width: 0; + font-size: var(--fs-sm); + font-weight: 500; + color: var(--text-secondary); + white-space: nowrap; +} + +.quota-rate-wk-sub { + font-family: var(--font-mono); + font-variant-numeric: tabular-nums; + font-size: var(--fs-2xs); + font-weight: 400; + color: var(--text-muted); +} + +.quota-rate-wk-v { + display: inline-flex; + align-items: baseline; + gap: 4px; + font-family: var(--font-mono); + font-variant-numeric: tabular-nums; + white-space: nowrap; + flex-shrink: 0; +} + +.quota-rate-wk-usd { + font-size: var(--fs-md); + font-weight: 600; + color: var(--text-primary); +} + +.quota-rate-wk-tok { + font-size: var(--fs-xs); + font-weight: 400; + color: var(--text-muted); +} + .quota-rate-pop-body { display: flex; flex-direction: column; gap: 8px; + max-height: min(300px, 58vh); + overflow-x: hidden; + overflow-y: auto; + overscroll-behavior: contain; } .quota-rate-pool-group { @@ -855,9 +914,11 @@ .quota-rate-eq-grid { display: flex; + flex-wrap: wrap; align-items: baseline; justify-content: space-between; - gap: 12px; + column-gap: 10px; + row-gap: 3px; } .quota-rate-eq-grid.is-single { @@ -885,6 +946,14 @@ white-space: nowrap; } +.quota-rate-eq-tok { + font-size: var(--fs-xs); + font-weight: 400; + font-variant-numeric: tabular-nums; + color: var(--text-muted); + white-space: nowrap; +} + .quota-rate-pop-empty { font-size: var(--fs-sm); line-height: 1.5; diff --git a/sidecars/panel/styles.css b/sidecars/panel/styles.css index d2d28ce..235a641 100644 --- a/sidecars/panel/styles.css +++ b/sidecars/panel/styles.css @@ -2394,7 +2394,7 @@ html[data-standalone="true"] .app-shell { position: absolute; top: 38px; left: 12px; - width: min(332px, calc(100% - 24px)); + width: min(352px, calc(100% - 24px)); z-index: 45; display: flex; flex-direction: column; @@ -2439,10 +2439,69 @@ html[data-standalone="true"] .app-shell { min-width: 0; } +.quota-rate-wk-summary { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 8px; + min-width: 0; + padding-bottom: 7px; + border-bottom: 1px solid var(--border-hairline); +} + +.quota-rate-wk-summary[hidden] { + display: none; +} + +.quota-rate-wk-k { + display: inline-flex; + align-items: baseline; + gap: 5px; + min-width: 0; + font-size: var(--fs-sm); + font-weight: 500; + color: var(--text-secondary); + white-space: nowrap; +} + +.quota-rate-wk-sub { + font-family: var(--font-mono); + font-variant-numeric: tabular-nums; + font-size: var(--fs-2xs); + font-weight: 400; + color: var(--text-muted); +} + +.quota-rate-wk-v { + display: inline-flex; + align-items: baseline; + gap: 4px; + font-family: var(--font-mono); + font-variant-numeric: tabular-nums; + white-space: nowrap; + flex-shrink: 0; +} + +.quota-rate-wk-usd { + font-size: var(--fs-md); + font-weight: 600; + color: var(--text-primary); +} + +.quota-rate-wk-tok { + font-size: var(--fs-xs); + font-weight: 400; + color: var(--text-muted); +} + .quota-rate-pop-body { display: flex; flex-direction: column; gap: 8px; + max-height: min(300px, 58vh); + overflow-x: hidden; + overflow-y: auto; + overscroll-behavior: contain; } .quota-rate-pool-group { @@ -2573,9 +2632,11 @@ html[data-standalone="true"] .app-shell { .quota-rate-eq-grid { display: flex; + flex-wrap: wrap; align-items: baseline; justify-content: space-between; - gap: 12px; + column-gap: 10px; + row-gap: 3px; } .quota-rate-eq-grid.is-single { @@ -2603,6 +2664,14 @@ html[data-standalone="true"] .app-shell { white-space: nowrap; } +.quota-rate-eq-tok { + font-size: var(--fs-xs); + font-weight: 400; + font-variant-numeric: tabular-nums; + color: var(--text-muted); + white-space: nowrap; +} + .quota-rate-pop-empty { font-size: var(--fs-sm); line-height: 1.5; @@ -8793,10 +8862,12 @@ 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-hint, [data-modern-ui="true"] .quota-rate-pop-head, +[data-modern-ui="true"] .quota-rate-wk-summary, [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-wk-summary, :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 { diff --git a/sidecars/panel/test/quota-reservation.test.mjs b/sidecars/panel/test/quota-reservation.test.mjs index 7d5e099..79f6bf6 100644 --- a/sidecars/panel/test/quota-reservation.test.mjs +++ b/sidecars/panel/test/quota-reservation.test.mjs @@ -1980,3 +1980,903 @@ test('QuotaPoolsWidget ? popover renders family-group/external usage banner and globalThis.window = origWindow; } }); + +test('quota-reservation: 3-tier hybrid estimator unlocks cycle_ratio & anchor_slope, derives full-pool tokens, and retains density across reset & restart', () => { + let storedPayload = null; + const tracker = createQuotaReservationTracker({ + saveState: (p) => { + storedPayload = JSON.parse(JSON.stringify(p)); + }, + }); + + const makePools = (used5h, usedWk, reset5h = RESET_5H, resetWk = RESET_WK) => + new Map([ + [ + 'Claude & GPT', + { + poolKey: 'Claude & GPT', + poolLabel: 'Claude & GPT', + family: 'Claude & GPT', + has5h: true, + hasWeekly: true, + remainingFraction: 1 - used5h / 100, + usedPct: used5h, + resetTime: new Date(reset5h).toISOString(), + weeklyRemainingFraction: 1 - usedWk / 100, + weeklyUsedPct: usedWk, + weeklyResetTime: new Date(resetWk).toISOString(), + }, + ], + ]); + + const makeStats = ({ + cost5h, + costWk, + calls5h, + callsWk, + tok5h, + tokWk, + modelCosts5h = {}, + modelCostsWk = {}, + modelTokens5h = {}, + modelTokensWk = {}, + ts = T0, + }) => + new Map([ + [ + 'Claude & GPT', + { + cycle5h: { costUsd: cost5h, calls: calls5h, tokens: tok5h, unpricedCalls: 0 }, + cycleWeekly: { costUsd: costWk, calls: callsWk, tokens: tokWk, unpricedCalls: 0 }, + pricedTokens5h: tok5h, + pricedTokensWeekly: tokWk, + exactCost5hUsd: cost5h, + exactCostWeeklyUsd: costWk, + modelCosts5h, + modelCostsWeekly: modelCostsWk, + modelTokens5h, + modelTokensWeekly: modelTokensWk, + recent10m: { lastActivityMs: ts, activeSessionCount: 1, costUsd: 0.2 }, + }, + ], + ]); + + // 1. Cold-start Tier 3 (cycle_ratio): solo account at 3.2% 5h / 2.4% weekly across 6 calls ($1.20, 300k tok -> $4/MTok) + // Unlocks immediately without waiting for 3 clean single-step diffs, while keeping reservedPct = 0 + const pCold = makePools(3.2, 2.4); + tracker.updatePools({ + endpointId: 'local', + accountScope: 'tier3@example.com', + quotaPoolsMap: pCold, + poolCycleStats: makeStats({ + cost5h: 1.6, + costWk: 1.2, + calls5h: 6, + callsWk: 6, + tok5h: 400_000, + tokWk: 300_000, + modelCosts5h: { 'Claude Sonnet 4.6': 1.6 }, + modelCostsWk: { 'Claude Sonnet 4.6': 1.2 }, + modelTokens5h: { 'Claude Sonnet 4.6': 400_000 }, + modelTokensWk: { 'Claude Sonnet 4.6': 300_000 }, + ts: T0, + }), + quotaFetchedAtMs: T0, + nowMs: T0, + }); + const coldPool = pCold.get('Claude & GPT'); + assert.equal(coldPool.reservedPct, 0); + assert.equal(coldPool.weeklyReservedPct, 0); + assert.equal(coldPool.rateEstimate?.source5h, 'cycle_ratio'); + assert.equal(coldPool.rateEstimate?.sourceWeekly, 'cycle_ratio'); + assert.equal(coldPool.rateEstimate?.isPreliminary5h, true); + assert.equal(coldPool.rateEstimate?.isPreliminaryWeekly, true); + assert.equal(coldPool.rateEstimate?.eqFull5hUsd, 50); + assert.equal(coldPool.rateEstimate?.eqFullWeeklyUsd, 50); + assert.equal(coldPool.rateEstimate?.eqFull5hTokens, 12_500_000); + assert.equal(coldPool.rateEstimate?.eqFullWeeklyTokens, 12_500_000); + + // 2. Mid-cycle / shared-account Tier 2 (anchor_slope + Theil-Sen): + // Baseline starts at 28% weekly with $0 local cost -> hasExternalUsage = true, Tier 3 blocked + let ts = T0; + let u5 = 15.0; + let uw = 28.0; + let c = 0; + let n = 0; + let tok = 0; + const pExt0 = makePools(u5, uw); + tracker.updatePools({ + endpointId: 'local', + accountScope: 'slope@example.com', + quotaPoolsMap: pExt0, + poolCycleStats: makeStats({ cost5h: 0, costWk: 0, calls5h: 0, callsWk: 0, tok5h: 0, tokWk: 0, ts }), + quotaFetchedAtMs: ts, + nowMs: ts, + }); + assert.equal(pExt0.get('Claude & GPT').rateEstimate?.eqFullWeeklyUsd, null, 'Tier 3 blocked on external baseline'); + + // Local runs 3 multi-model batched checkpoints (+0.6% weekly / +$0.30 / +2 calls each; total +1.8% >= 1.5%, +6 calls >= 5, $4/MTok) + // Note: delta5h = +0.6% (>= 0.35% lease jump threshold on uncalibrated or multi-step), so clean single-step rateSamples stays 0, + // proving Tier 2 anchor_slope independently recovers 2.0 %/$ -> $50 full weekly! + let pSlope = null; + for (let step = 0; step < 3; step += 1) { + ts += 30_000; + c = +(c + 0.3).toFixed(4); + n += 2; + tok += 75_000; + u5 = +(u5 + 0.3).toFixed(4); + uw = +(uw + 0.6).toFixed(4); + pSlope = makePools(u5, uw); + tracker.updatePools({ + endpointId: 'local', + accountScope: 'slope@example.com', + quotaPoolsMap: pSlope, + poolCycleStats: makeStats({ + cost5h: c, + costWk: c, + calls5h: n, + callsWk: n, + tok5h: tok, + tokWk: tok, + modelCosts5h: { 'Claude Sonnet 4.6': c * 0.6, 'Claude Opus 4.6': c * 0.4 }, + modelCostsWk: { 'Claude Sonnet 4.6': c * 0.6, 'Claude Opus 4.6': c * 0.4 }, + modelTokens5h: { 'Claude Sonnet 4.6': Math.round(tok * 0.75), 'Claude Opus 4.6': Math.round(tok * 0.25) }, + modelTokensWk: { 'Claude Sonnet 4.6': Math.round(tok * 0.75), 'Claude Opus 4.6': Math.round(tok * 0.25) }, + ts, + }), + runningPoolKeys: new Set(['Claude & GPT']), + quotaFetchedAtMs: ts, + nowMs: ts, + }); + } + const slopeEst = pSlope.get('Claude & GPT').rateEstimate; + assert.equal(slopeEst?.sourceWeekly, 'anchor_slope'); + assert.equal(slopeEst?.isPreliminaryWeekly, true); + assert.equal(slopeEst?.eqFullWeeklyUsd, 50); + assert.equal(slopeEst?.eqFullWeeklyTokens, 12_500_000); + + // 3. Three clean single-model steps on Sonnet ($0.10 -> +0.2% weekly = 2.0 %/$) promote pool & model to Tier 1 calibrated + let sonnetExtraCost = 0; + let sonnetExtraTok = 0; + let pCal = null; + for (let i = 0; i < 3; i += 1) { + ts += 20_000; + c = +(c + 0.1).toFixed(4); + sonnetExtraCost = +(sonnetExtraCost + 0.1).toFixed(4); + sonnetExtraTok += 25_000; + n += 1; + tok += 25_000; + u5 = +(u5 + 0.2).toFixed(4); + uw = +(uw + 0.2).toFixed(4); + pCal = makePools(u5, uw); + tracker.updatePools({ + endpointId: 'local', + accountScope: 'slope@example.com', + quotaPoolsMap: pCal, + poolCycleStats: makeStats({ + cost5h: c, + costWk: c, + calls5h: n, + callsWk: n, + tok5h: tok, + tokWk: tok, + modelCosts5h: { 'Claude Sonnet 4.6': 0.54 + sonnetExtraCost, 'Claude Opus 4.6': 0.36 }, + modelCostsWk: { 'Claude Sonnet 4.6': 0.54 + sonnetExtraCost, 'Claude Opus 4.6': 0.36 }, + modelTokens5h: { 'Claude Sonnet 4.6': 168_750 + sonnetExtraTok, 'Claude Opus 4.6': 56_250 }, + modelTokensWk: { 'Claude Sonnet 4.6': 168_750 + sonnetExtraTok, 'Claude Opus 4.6': 56_250 }, + ts, + }), + runningPoolKeys: new Set(['Claude & GPT']), + quotaFetchedAtMs: ts, + nowMs: ts, + }); + } + const calEst = pCal.get('Claude & GPT').rateEstimate; + assert.equal(calEst?.sourceWeekly, 'calibrated'); + assert.equal(calEst?.isPreliminaryWeekly, false); + assert.equal(calEst?.eqFullWeeklyUsd, 50); + assert.equal(calEst?.eqFullWeeklyTokens, 12_500_000); + assert.ok(calEst?.models?.[0]?.eqFullWeeklyTokens > 10_000_000, 'per-model eqFullWeeklyTokens populated'); + + // 4. Weekly rollover reset back to 0% ($0 cost, 0 tokens) + reload from persisted v2 payload: + // priorUsdPerMTok preserves full-pool token capacity with zero Monday-reset amnesia! + ts += 7 * 24 * 3600 * 1000; + const pReset = makePools(0, 0, RESET_5H + 7 * 24 * 3600 * 1000, RESET_WK + 7 * 24 * 3600 * 1000); + tracker.updatePools({ + endpointId: 'local', + accountScope: 'slope@example.com', + quotaPoolsMap: pReset, + poolCycleStats: makeStats({ cost5h: 0, costWk: 0, calls5h: 0, callsWk: 0, tok5h: 0, tokWk: 0, ts }), + quotaFetchedAtMs: ts, + nowMs: ts, + }); + assert.equal(pReset.get('Claude & GPT').rateEstimate?.eqFullWeeklyUsd, 50); + assert.equal(pReset.get('Claude & GPT').rateEstimate?.eqFullWeeklyTokens, 12_500_000); + + assert.equal(storedPayload?.version, 2, 'keeps v2 schema version backward-compatible'); + const reloaded = createQuotaReservationTracker({ loadState: () => storedPayload }); + const pAfterRestart = makePools(0, 0, RESET_5H + 7 * 24 * 3600 * 1000, RESET_WK + 7 * 24 * 3600 * 1000); + reloaded.updatePools({ + endpointId: 'local', + accountScope: 'slope@example.com', + quotaPoolsMap: pAfterRestart, + poolCycleStats: makeStats({ cost5h: 0, costWk: 0, calls5h: 0, callsWk: 0, tok5h: 0, tokWk: 0, ts }), + quotaFetchedAtMs: ts, + nowMs: ts, + }); + assert.equal(pAfterRestart.get('Claude & GPT').rateEstimate?.eqFullWeeklyUsd, 50); + assert.equal(pAfterRestart.get('Claude & GPT').rateEstimate?.eqFullWeeklyTokens, 12_500_000); +}); + +test('QuotaPoolsWidget ? popover renders Est. Weekly Quota summary row, preliminary labels, and full-pool token references', 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 }] = await Promise.all([ + import('../src/i18n/index.js'), + import('../src/components/widgets/QuotaPoolsWidget.js'), + ]); + setI18nLanguage('zh-CN'); + + const widget = QuotaPoolsWidget(); + const popover = widget.refs.ratePopoverEl; + + // 1. Collecting state: top weekly summary hidden until at least 1 pool has a weekly capacity estimate + assert.equal(popover.querySelector('.quota-rate-wk-summary')?.hidden, true); + + // 2. Partial + Preliminary state (Claude ready via anchor_slope, Gemini still collecting) + widget.refs.update({ + data: { + account: { email: 'sjee80343@gmail.com', tierName: 'Google AI Pro' }, + quotas: { + pools: [ + { + poolKey: 'Claude & GPT', + poolLabel: 'Claude & GPT', + family: 'Claude & GPT', + has5h: true, + hasWeekly: true, + usedPct: 14, + remainingPct: 86, + weeklyUsedPct: 30, + weeklyRemainingPct: 70, + cycleWeekly: { tokens: 3_100_000, costUsd: 15, calls: 42 }, + rateEstimate: { + rate5hPctPerUsd: null, + rateWeeklyPctPerUsd: 2.0833, + eqFull5hUsd: null, + eqFullWeeklyUsd: 48, + eqFullWeeklyTokens: 9_900_000, + samples5h: 0, + samplesWeekly: 0, + sourceWeekly: 'anchor_slope', + isPreliminaryWeekly: true, + models: [], + }, + }, + { + poolKey: 'Gemini', + poolLabel: 'Gemini', + family: 'Gemini', + hasWeekly: true, + weeklyUsedPct: 0.4, + weeklyRemainingPct: 99.6, + rateEstimate: null, + }, + ], + weekly: { isOfficial: true }, + }, + }, + minuteTick: 1, + }); + + const wkSummary = popover.querySelector('.quota-rate-wk-summary'); + assert.equal(wkSummary.hidden, false); + assert.match(wkSummary.textContent, /预测周额度.*· 1\/2 池.*≈ \$48.*· 9\.9M/); + const fallbackRow = popover.querySelector('.quota-rate-model-row.is-fallback'); + assert.ok(fallbackRow); + assert.match(fallbackRow.textContent, /池综合均值/); + assert.match(fallbackRow.textContent, /周限 2\.08%\/\$ · 斜率初估/); + assert.match(fallbackRow.textContent, /周限满池≈ \$48· 9\.9M/); + + const wkRowLeft = widget.refs.poolsListEl.querySelectorAll('.quota-win-left')[1]; + assert.match(wkRowLeft.getAttribute('title') || '', /满池约 \$48 \(9\.9M\)/); + + // 3. All pools calibrated & ready: sums USD + Tokens cleanly ($50 + $35 = $85, 10.3M + 14.2M = 24.5M) + const allReadyData = { + account: { email: 'sjee80343@gmail.com', tierName: 'Google AI Pro' }, + quotas: { + pools: [ + { + poolKey: 'Claude & GPT', + poolLabel: 'Claude & GPT', + family: 'Claude & GPT', + has5h: true, + hasWeekly: true, + usedPct: 14, + remainingPct: 86, + weeklyUsedPct: 30, + weeklyRemainingPct: 70, + cycleWeekly: { tokens: 3_100_000, costUsd: 15, calls: 42 }, + rateEstimate: { + rate5hPctPerUsd: 2, + rateWeeklyPctPerUsd: 2, + eqFull5hUsd: 50, + eqFullWeeklyUsd: 50, + eqFull5hTokens: 10_300_000, + eqFullWeeklyTokens: 10_300_000, + samples5h: 8, + samplesWeekly: 8, + source5h: 'calibrated', + sourceWeekly: 'calibrated', + isPreliminary5h: false, + isPreliminaryWeekly: false, + models: [ + { + model: 'Claude Sonnet 4.6', + rate5hPctPerUsd: 2, + rateWeeklyPctPerUsd: 2, + eqFull5hUsd: 50, + eqFullWeeklyUsd: 50, + eqFull5hTokens: 10_300_000, + eqFullWeeklyTokens: 10_300_000, + multiplier: null, + samples: 8, + }, + ], + }, + }, + { + poolKey: 'Gemini', + poolLabel: 'Gemini', + family: 'Gemini', + has5h: true, + hasWeekly: true, + usedPct: 10, + remainingPct: 90, + weeklyUsedPct: 20, + weeklyRemainingPct: 80, + rateEstimate: { + rate5hPctPerUsd: 2.8571, + rateWeeklyPctPerUsd: 2.8571, + eqFull5hUsd: 35, + eqFullWeeklyUsd: 35, + eqFull5hTokens: 14_200_000, + eqFullWeeklyTokens: 14_200_000, + samples5h: 6, + samplesWeekly: 6, + source5h: 'calibrated', + sourceWeekly: 'calibrated', + isPreliminary5h: false, + isPreliminaryWeekly: false, + models: [], + }, + }, + ], + weekly: { isOfficial: true }, + }, + }; + widget.refs.update({ data: allReadyData, minuteTick: 2 }); + assert.equal(wkSummary.hidden, false); + assert.equal(wkSummary.querySelector('.quota-rate-wk-sub').hidden, true); + assert.match(wkSummary.textContent, /预测周额度≈ \$85· 24\.5M/); + + // 4. English locale switch updates weekly summary, model cards, and row title tooltip without reload + setI18nLanguage('en-US'); + widget.refs.update({ data: allReadyData, minuteTick: 3 }); + assert.match(wkSummary.textContent, /Est\. Weekly Quota≈ \$85· 24\.5M/); + assert.match( + widget.refs.poolsListEl.querySelectorAll('.quota-win-left')[1].getAttribute('title') || '', + /Full ~\$50 \(10\.3M\)/ + ); + + // 5. Custom local weekly budget mode hides official weekly capacity summary + widget.refs.update({ + data: { + ...allReadyData, + quotas: { + ...allReadyData.quotas, + weekly: { isOfficial: false }, + }, + }, + minuteTick: 4, + }); + assert.equal(wkSummary.hidden, true); + + // 6. Pool with 5h-only model card + pool-level preliminary weekly estimate renders supplementary weekly fallback row + setI18nLanguage('zh-CN'); + widget.refs.update({ + data: { + account: { email: 'sjee80343@gmail.com', tierName: 'Google AI Pro' }, + quotas: { + pools: [ + { + poolKey: 'Gemini', + poolLabel: 'Gemini', + family: 'Gemini', + has5h: true, + hasWeekly: true, + usedPct: 8, + remainingPct: 92, + weeklyUsedPct: 12, + weeklyRemainingPct: 88, + rateEstimate: { + rate5hPctPerUsd: 0.6667, + rateWeeklyPctPerUsd: 0.1667, + eqFull5hUsd: 150, + eqFullWeeklyUsd: 600, + eqFull5hTokens: 50_000_000, + eqFullWeeklyTokens: 200_000_000, + samples5h: 4, + samplesWeekly: 0, + source5h: 'calibrated', + sourceWeekly: 'anchor_slope', + isPreliminary5h: false, + isPreliminaryWeekly: true, + models: [ + { + model: 'Gemini 3.1 Pro', + rate5hPctPerUsd: 0.6667, + rateWeeklyPctPerUsd: null, + eqFull5hUsd: 150, + eqFullWeeklyUsd: null, + eqFull5hTokens: 50_000_000, + multiplier: null, + samples: 4, + }, + ], + }, + }, + ], + weekly: { isOfficial: true }, + }, + }, + minuteTick: 5, + }); + assert.equal(wkSummary.hidden, false); + assert.match(wkSummary.textContent, /预测周额度.*· 初估.*≈ \$600.*· 200\.0M/); + const mixedRows = popover.querySelectorAll('.quota-rate-model-row'); + assert.equal(mixedRows.length, 2, 'renders 5h model card + supplementary pool weekly fallback row'); + assert.match(mixedRows[0].textContent, /Gemini 3\.1 Pro.*5h 满池≈ \$150/); + assert.match(mixedRows[1].textContent, /池综合均值.*斜率初估.*周限满池≈ \$600· 200\.0M/); + + widget.destroy(); + } finally { + globalThis.document = origDocument; + globalThis.window = origWindow; + } +}); + +test('quota-reservation: batches multi-pool persistence and isolates slope/calibration from unpriced calls, lease expiry & cold-start', () => { + let saveCalls = 0; + let stored = null; + const tracker = createQuotaReservationTracker({ + saveState: (p) => { + saveCalls += 1; + stored = JSON.parse(JSON.stringify(p)); + }, + }); + + // 1. Batched persistence across multiple pools on non-urgent baseline/normal ticks: + // Both pools' 5h AND weekly buckets must be persisted in a single atomic save + let ts = T0; + const mkMultiPools = (c5, cw, g5, gw) => + new Map([ + [ + 'Claude & GPT', + { + poolKey: 'Claude & GPT', + poolLabel: 'Claude & GPT', + family: 'Claude & GPT', + has5h: true, + hasWeekly: true, + remainingFraction: 1 - c5 / 100, + usedPct: c5, + resetTime: new Date(RESET_5H).toISOString(), + weeklyRemainingFraction: 1 - cw / 100, + weeklyUsedPct: cw, + weeklyResetTime: new Date(RESET_WK).toISOString(), + }, + ], + [ + 'Gemini', + { + poolKey: 'Gemini', + poolLabel: 'Gemini', + family: 'Gemini', + has5h: true, + hasWeekly: true, + remainingFraction: 1 - g5 / 100, + usedPct: g5, + resetTime: new Date(RESET_5H).toISOString(), + weeklyRemainingFraction: 1 - gw / 100, + weeklyUsedPct: gw, + weeklyResetTime: new Date(RESET_WK).toISOString(), + }, + ], + ]); + + const mkMultiStats = (cc, gc, cCalls, gCalls, cUnp = 0) => + new Map([ + [ + 'Claude & GPT', + { + cycle5h: { costUsd: cc, calls: cCalls, tokens: 300_000, unpricedCalls: cUnp }, + cycleWeekly: { costUsd: cc, calls: cCalls, tokens: 300_000, unpricedCalls: cUnp }, + pricedTokens5h: 300_000, + pricedTokensWeekly: 300_000, + exactCost5hUsd: cc, + exactCostWeeklyUsd: cc, + modelCosts5h: { 'Claude Sonnet 4.6': cc }, + modelCostsWeekly: { 'Claude Sonnet 4.6': cc }, + modelTokens5h: { 'Claude Sonnet 4.6': 300_000 }, + modelTokensWeekly: { 'Claude Sonnet 4.6': 300_000 }, + recent10m: { lastActivityMs: ts, activeSessionCount: 1, costUsd: 0.1 }, + }, + ], + [ + 'Gemini', + { + cycle5h: { costUsd: gc, calls: gCalls, tokens: 500_000, unpricedCalls: 0 }, + cycleWeekly: { costUsd: gc, calls: gCalls, tokens: 500_000, unpricedCalls: 0 }, + pricedTokens5h: 500_000, + pricedTokensWeekly: 500_000, + exactCost5hUsd: gc, + exactCostWeeklyUsd: gc, + modelCosts5h: { 'Gemini 3.1 Pro': gc }, + modelCostsWeekly: { 'Gemini 3.1 Pro': gc }, + modelTokens5h: { 'Gemini 3.1 Pro': 500_000 }, + modelTokensWeekly: { 'Gemini 3.1 Pro': 500_000 }, + recent10m: { lastActivityMs: ts, activeSessionCount: 1, costUsd: 0.1 }, + }, + ], + ]); + + tracker.updatePools({ + endpointId: 'local', + accountScope: 'batch@example.com', + quotaPoolsMap: mkMultiPools(2.0, 2.0, 1.0, 1.0), + poolCycleStats: mkMultiStats(1.0, 2.0, 5, 5), + quotaFetchedAtMs: ts, + nowMs: ts, + }); + assert.equal(saveCalls, 1, 'updatePools coalesces multi-pool baseline into 1 disk write'); + assert.ok(stored?.buckets?.['local::batch@example.com::Claude & GPT::weekly'], 'Claude weekly persisted'); + assert.ok(stored?.buckets?.['local::batch@example.com::Gemini::weekly'], '2nd pool Gemini weekly persisted'); + assert.ok( + stored.buckets['local::batch@example.com::Gemini::weekly'].usdPerMTok > 0, + '2nd pool weekly token density persisted' + ); + + // 2. Cold-start seeded bucket (rateSamples = 1, rateWindow = []) requires 3 genuine clean steps before calibrated + for (let step = 1; step <= 2; step += 1) { + ts += 20_000; + const p2 = mkMultiPools(2.0 + step * 0.2, 2.0 + step * 0.2, 1.0, 1.0); + tracker.updatePools({ + endpointId: 'local', + accountScope: 'batch@example.com', + quotaPoolsMap: p2, + poolCycleStats: mkMultiStats(1.0 + step * 0.1, 2.0, 5 + step, 5), + runningPoolKeys: new Set(['Claude & GPT']), + quotaFetchedAtMs: ts, + nowMs: ts, + }); + const estStep = p2.get('Claude & GPT').rateEstimate; + assert.equal( + estStep?.isPreliminaryWeekly, + true, + `step ${step} (< 3 clean steps) stays preliminary despite cold-start seed` + ); + } + ts += 20_000; + const pStep3 = mkMultiPools(2.6, 2.6, 1.0, 1.0); + tracker.updatePools({ + endpointId: 'local', + accountScope: 'batch@example.com', + quotaPoolsMap: pStep3, + poolCycleStats: mkMultiStats(1.3, 2.0, 8, 5), + runningPoolKeys: new Set(['Claude & GPT']), + quotaFetchedAtMs: ts, + nowMs: ts, + }); + assert.equal(pStep3.get('Claude & GPT').rateEstimate?.isPreliminaryWeekly, false, '3rd genuine clean step promotes to calibrated'); + assert.equal(stored?.buckets?.['local::batch@example.com::Claude & GPT::weekly']?.rateWindow?.length, 3, 'normal tick persisted weekly rateWindow'); + + // 3. Unpriced calls & expired leases do NOT poison Tier 2 anchor_slope + ts = T0; + const makeWkPool = (uw) => + new Map([ + [ + 'Argon', + { + poolKey: 'Argon', + poolLabel: 'Argon', + family: 'Argon', + has5h: false, + hasWeekly: true, + weeklyRemainingFraction: 1 - uw / 100, + weeklyUsedPct: uw, + weeklyResetTime: new Date(RESET_WK).toISOString(), + }, + ], + ]); + const makeWkStats = (cost, calls, unp) => + new Map([ + [ + 'Argon', + { + cycle5h: { costUsd: 0, calls: 0, tokens: 0, unpricedCalls: 0 }, + cycleWeekly: { costUsd: cost, calls, tokens: 100_000, unpricedCalls: unp }, + pricedTokensWeekly: 100_000, + exactCostWeeklyUsd: cost, + recent10m: { lastActivityMs: ts, activeSessionCount: 2, costUsd: 0.1 }, + }, + ], + ]); + + // Baseline on shared pool (20% with $0 local -> Tier 3 blocked) + tracker.updatePools({ + endpointId: 'local', + accountScope: 'guard@example.com', + quotaPoolsMap: makeWkPool(20.0), + poolCycleStats: makeWkStats(0, 0, 0), + quotaFetchedAtMs: ts, + nowMs: ts, + }); + // Unpriced burst burns +3.0% alongside tiny $0.03 priced spend -> must reset slope anchor, NOT record 100 %/$ + ts += 30_000; + const pUnp = makeWkPool(23.0); + tracker.updatePools({ + endpointId: 'local', + accountScope: 'guard@example.com', + quotaPoolsMap: pUnp, + poolCycleStats: makeWkStats(0.03, 6, 5), + runningPoolKeys: new Set(['Argon']), + quotaFetchedAtMs: ts, + nowMs: ts, + }); + assert.equal(pUnp.get('Argon').rateEstimate?.eqFullWeeklyUsd ?? null, null, 'unpriced burst does not unlock poisoned slope'); + + // Subsequent priced multi-step burn (+1.6% across +$0.80, 6 calls, unp stays 5) cleanly calibrates 2.0 %/$ -> $50! + for (let k = 1; k <= 2; k += 1) { + ts += 30_000; + const pPriced = makeWkPool(23.0 + k * 0.8); + tracker.updatePools({ + endpointId: 'local', + accountScope: 'guard@example.com', + quotaPoolsMap: pPriced, + poolCycleStats: makeWkStats(0.03 + k * 0.4, 6 + k * 3, 5), + runningPoolKeys: new Set(['Argon']), + quotaFetchedAtMs: ts, + nowMs: ts, + }); + if (k === 2) { + assert.equal(pPriced.get('Argon').rateEstimate?.sourceWeekly, 'anchor_slope'); + assert.equal(pPriced.get('Argon').rateEstimate?.eqFullWeeklyUsd, 50); + } + } + + // Trigger a 2.0% cold-start/active lease jump, then let it expire after 91 minutes -> expiry jump must reset slope anchor + ts += 30_000; + tracker.updatePools({ + endpointId: 'local', + accountScope: 'guard@example.com', + quotaPoolsMap: makeWkPool(26.6), + poolCycleStats: makeWkStats(0.85, 13, 5), + runningPoolKeys: new Set(['Argon']), + quotaFetchedAtMs: ts, + nowMs: ts, + }); + const argonSt = tracker._buckets.get('local::guard@example.com::Argon::weekly'); + assert.ok(argonSt.activeLeases.length > 0, 'lease recorded before TTL expiry'); + ts += 91 * 60 * 1000; + const pExpired = makeWkPool(26.65); + tracker.updatePools({ + endpointId: 'local', + accountScope: 'guard@example.com', + quotaPoolsMap: pExpired, + poolCycleStats: makeWkStats(0.88, 14, 5), + quotaFetchedAtMs: ts, + nowMs: ts, + }); + assert.equal(argonSt.activeLeases.length, 0, 'lease expired'); + assert.equal(argonSt.slopeSamples.length, 1, 'slope anchor reset cleanly on lease TTL expiry'); +}); + +test('quota-reservation: suppresses post-refund idle replica ping-pong and self-heals false externalUsage while preserving real shared pools', () => { + const tracker = createQuotaReservationTracker(); + const keyWk = 'local::solo-bounce@example.com::Gemini::weekly'; + let ts = T0; + + // 1. Calibrate solo account cleanly at 0.125 %/$ ($800 full weekly): 3 clean steps + active lease up to 1.048% + tracker.observeBucket({ + bucketKey: keyWk, + officialUsedPct: 0.3, + resetTimeMs: RESET_WK, + quotaFetchedAtMs: ts, + cycleCostUsd: 2.4, + cycleCalls: 30, + poolLastActivityMs: ts, + activeSessionCount10m: 1, + nowMs: ts, + }); + for (let i = 1; i <= 3; i += 1) { + ts += 20_000; + tracker.observeBucket({ + bucketKey: keyWk, + officialUsedPct: +(0.3 + i * 0.025).toFixed(4), + resetTimeMs: RESET_WK, + quotaFetchedAtMs: ts, + cycleCostUsd: +(2.4 + i * 0.2).toFixed(4), + cycleCalls: 30 + i, + poolLastActivityMs: ts, + activeSessionCount10m: 1, + nowMs: ts, + }); + } + const lastActiveTs = ts; + // Active lease jumps 0.375% -> 1.048% + ts += 15_000; + tracker.observeBucket({ + bucketKey: keyWk, + officialUsedPct: 1.048, + resetTimeMs: RESET_WK, + quotaFetchedAtMs: ts, + cycleCostUsd: 3.0688, + cycleCalls: 34, + poolLastActivityMs: lastActiveTs, + activeSessionCount10m: 1, + nowMs: ts, + }); + + // User goes idle for 10 min -> upstream settles down to 0.356%, then multi-replica LB bounces 1.048% <-> 0.356% repeatedly + const bounceSchedule = [ + [10 * 60 * 1000, 0.356], + [15 * 60 * 1000, 1.048], + [12 * 60 * 1000, 0.356], + [11 * 1000, 1.048], + [7 * 60 * 1000, 0.356], + ]; + for (const [dt, pct] of bounceSchedule) { + ts += dt; + tracker.observeBucket({ + bucketKey: keyWk, + officialUsedPct: pct, + resetTimeMs: RESET_WK, + quotaFetchedAtMs: ts, + cycleCostUsd: 3.0688, + cycleCalls: 34, + poolLastActivityMs: lastActiveTs, + activeSessionCount10m: 0, + nowMs: ts, + }); + } + const stBounce = tracker._buckets.get(keyWk); + assert.equal(stBounce.hasExternalUsage, false, 'idle post-refund replica bounce must not flag external usage'); + assert.equal(stBounce.externalUsedPct, 0, 'ping-pong must never accumulate externalUsedPct'); + + // 2. Self-healing of already-polluted persisted state vs preservation of genuine shared state + let healedSaved = null; + const persisted = { + version: 2, + savedAt: new Date(T0).toISOString(), + buckets: { + 'local::polluted@example.com::Gemini::weekly': { + resetTimeMs: RESET_WK, + lastQuotaTs: T0, + lastOfficialUsedPct: 0.4012, + lastCycleCostUsd: 3.53, + lastCycleCalls: 44, + lastPricedTokens: 9_803_219, + lastUnpricedCalls: 0, + usdPerMTok: 0.36, + ratePctPerUsd: 0.125, + rateSamples: 20, + rateWindow: [0.125, 0.125, 0.125, 0.125], + hasExternalUsage: true, + lastExternalUsageAtMs: T0 - 3 * 3600 * 1000, + externalUsedPct: 2.018, + externalEvents: 4, + }, + 'local::shared@example.com::Gemini::weekly': { + resetTimeMs: RESET_WK, + lastQuotaTs: T0, + lastOfficialUsedPct: 49.82, + lastCycleCostUsd: 196.93, + lastCycleCalls: 120, + lastPricedTokens: 60_000_000, + lastUnpricedCalls: 0, + usdPerMTok: 3.28, + ratePctPerUsd: 0.1667, + rateSamples: 55, + rateWindow: [0.1667, 0.1667, 0.1667, 0.1667], + hasExternalUsage: true, + lastExternalUsageAtMs: T0 - 3 * 3600 * 1000, + externalUsedPct: 0.571, + externalEvents: 1, + }, + }, + events: [], + }; + const healer = createQuotaReservationTracker({ + loadState: () => persisted, + saveState: (p) => { + healedSaved = p; + }, + }); + const mkPollPools = (uw) => + new Map([ + [ + 'Gemini', + { + poolKey: 'Gemini', + poolLabel: 'Gemini', + family: 'Gemini', + has5h: false, + hasWeekly: true, + weeklyUsedPct: uw, + weeklyResetTime: new Date(RESET_WK).toISOString(), + }, + ], + ]); + const pPolluted = mkPollPools(0.4012); + healer.updatePools({ + endpointId: 'local', + accountScope: 'polluted@example.com', + quotaPoolsMap: pPolluted, + poolCycleStats: new Map([ + [ + 'Gemini', + { + cycleWeekly: { costUsd: 3.53, calls: 44, tokens: 9_803_219, unpricedCalls: 0 }, + pricedTokensWeekly: 9_803_219, + exactCostWeeklyUsd: 3.53, + }, + ], + ]), + quotaFetchedAtMs: T0, + nowMs: T0 + 60_000, + }); + assert.equal( + pPolluted.get('Gemini').rateEstimate?.externalUsage ?? null, + null, + 'polluted solo bucket self-heals false externalUsage banner immediately even on cached quota poll' + ); + assert.equal(healedSaved?.buckets?.['local::polluted@example.com::Gemini::weekly']?.hasExternalUsage, false); + assert.equal(healedSaved?.buckets?.['local::polluted@example.com::Gemini::weekly']?.externalUsedPct, 0); + + const pShared = mkPollPools(49.82); + healer.updatePools({ + endpointId: 'local', + accountScope: 'shared@example.com', + quotaPoolsMap: pShared, + poolCycleStats: new Map([ + [ + 'Gemini', + { + cycleWeekly: { costUsd: 196.93, calls: 120, tokens: 60_000_000, unpricedCalls: 0 }, + pricedTokensWeekly: 60_000_000, + exactCostWeeklyUsd: 196.93, + }, + ], + ]), + quotaFetchedAtMs: T0, + nowMs: T0 + 60_000, + }); + assert.equal( + pShared.get('Gemini').rateEstimate?.externalUsage?.detected, + true, + 'genuine shared pool with 17% unexplained burn retains externalUsage detection' + ); + assert.equal(pShared.get('Gemini').rateEstimate?.externalUsage?.usedWeeklyPct, 0.6); +});