From df728450717f474a93bff5305bd708b165e60712 Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Mon, 23 Nov 2026 14:56:08 +0900 Subject: [PATCH] feat(panel): add account-isolated per-model quota burn-rate estimator and hover popover --- sidecars/panel/app.js | 365 ++++++++++++++- sidecars/panel/backend/quota-reservation.mjs | 318 ++++++++++++- sidecars/panel/backend/usage-aggregator.mjs | 27 ++ sidecars/panel/index.html | 4 +- .../components/widgets/QuotaPoolsWidget.js | 330 ++++++++++++- sidecars/panel/src/i18n/en-US.js | 11 + sidecars/panel/src/i18n/zh-CN.js | 11 + sidecars/panel/src/icons/svgRegistry.js | 5 + sidecars/panel/src/store/telemetryStore.js | 4 +- sidecars/panel/src/styles/modern-ui.css | 16 +- sidecars/panel/src/styles/views-overview.css | 220 +++++++++ sidecars/panel/styles.css | 236 +++++++++- sidecars/panel/test/quota-pools.test.mjs | 21 + .../panel/test/quota-reservation.test.mjs | 443 ++++++++++++++++++ 14 files changed, 1984 insertions(+), 27 deletions(-) diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index 140d209..ed502ff 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -967,6 +967,11 @@ const SVG_ICON_DEFS = Object.freeze({ { tag: 'path', attrs: { d: 'M8 6.2v3.4' } }, { tag: 'circle', attrs: { cx: '8', cy: '11.5', r: '0.6', fill: 'currentColor', stroke: 'none' } }, ], + 'help-circle': [ + { tag: 'circle', attrs: { cx: '8', cy: '8', r: '6' } }, + { tag: 'path', attrs: { d: 'M6.2 6.3a1.9 1.9 0 0 1 3.6.7c0 1.15-1.8 1.35-1.8 2.5' } }, + { tag: 'circle', attrs: { cx: '8', cy: '11.8', r: '0.65', fill: 'currentColor', stroke: 'none' } }, + ], 'chevron-down': [ { tag: 'path', attrs: { d: 'M4 6.2l4 4 4-4' } }, ], @@ -1451,6 +1456,17 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'quota.footCallsCycle': '周期调用: {calls} 次', 'quota.footTipCustom': '按本机自然周(周一 00:00 起)统计', 'quota.footTipCycle': '按各配额池独立周限重置周期分别统计并汇总', + 'quota.rateHelpAria': '查看当前账号实测倍率预估', + 'quota.ratePopTitle': '实测倍率预估', + 'quota.ratePopAccountScope': '{account}', + 'quota.ratePopAccountCurrent': '当前账号', + 'quota.ratePopPoolFallback': '池综合均值', + 'quota.ratePopEq5hLabel': '5h 满池', + 'quota.ratePopEqWkLabel': '周限满池', + 'quota.ratePopPerUsd': '{win} {rate}%/$', + 'quota.ratePopSamples': '{n} 样本', + 'quota.ratePopEmpty': '暂未采集到足够的单模型干净样本(每模型需至少 3 次无抖动扣费),正常使用后自动生成。', + 'quota.ratePopNote': '按单模型纯净步实测折算,同池最省为 1x,按账号隔离。', // Live Activity Widget 'live.currentSession': '当前会话', @@ -2347,6 +2363,17 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'quota.footCallsCycle': 'Cycle Calls: {calls}', 'quota.footTipCustom': 'Counted since Monday 00:00 local time', 'quota.footTipCycle': 'Summed across each quota pool weekly reset window', + 'quota.rateHelpAria': 'View empirical burn-rate estimates for this account', + 'quota.ratePopTitle': 'Estimated Burn Rates', + 'quota.ratePopAccountScope': '{account}', + 'quota.ratePopAccountCurrent': 'Current account', + 'quota.ratePopPoolFallback': 'Pool average', + 'quota.ratePopEq5hLabel': '5h full', + 'quota.ratePopEqWkLabel': 'Weekly full', + 'quota.ratePopPerUsd': '{win} {rate}%/$', + 'quota.ratePopSamples': '{n} samples', + 'quota.ratePopEmpty': 'Not enough clean single-model samples yet (at least 3 clean steps per model). Estimates appear automatically during use.', + 'quota.ratePopNote': 'Measured from clean single-model steps; lowest burn in pool = 1x. Account isolated.', // Live Activity Widget 'live.currentSession': 'Current Session', @@ -9915,7 +9942,9 @@ function isEquivalentTelemetry(prev, next) { pPools[i]?.cycle5h?.calls !== nPools[i]?.cycle5h?.calls || pPools[i]?.cycleWeekly?.tokens !== nPools[i]?.cycleWeekly?.tokens || pPools[i]?.cycleWeekly?.costUsd !== nPools[i]?.cycleWeekly?.costUsd || - pPools[i]?.cycleWeekly?.calls !== nPools[i]?.cycleWeekly?.calls + pPools[i]?.cycleWeekly?.calls !== nPools[i]?.cycleWeekly?.calls || + JSON.stringify(pPools[i]?.rateEstimate || null) !== + JSON.stringify(nPools[i]?.rateEstimate || null) ) { return false; } @@ -18657,7 +18686,7 @@ return { CTX_CHANNEL_DEFS, ContextWindowWidget }; })(); // --- src/components/widgets/QuotaPoolsWidget.js --- -const { buildQuotaPoolItems, createPoolQuotaRow, formatQuotaSummaryFooter, syncPoolQuotaRow, quotaPoolRowSig, formatAccountTierBadge, QuotaPoolsWidget } = (() => { +const { buildQuotaPoolItems, createPoolQuotaRow, formatQuotaSummaryFooter, syncPoolQuotaRow, quotaPoolRowSig, formatAccountTierBadge, maskAccountLabel, QuotaPoolsWidget } = (() => { /** * @fileoverview Standalone decoupled Quota Pools Widget (`QuotaPoolsWidget.js`). * Renders dynamic multi-pool quota bars (Gemini, Argon/Carbon, Claude & GPT) @@ -19057,12 +19086,331 @@ function formatAccountTierBadge(account) { return `${tierName} · ${rawPlan}`; } +/** + * 对账号邮箱或名称做轻量隐私脱敏(如 `sjee80343@gmail.com` -> `sj***43@gmail.com`), + * 兼顾多账号辨识度及截图分享隐私安全。 + * + * @param {string|null|undefined} raw + * @returns {string} + */ +function maskAccountLabel(raw) { + const str = String(raw || '').trim(); + if (!str) return ''; + const atIdx = str.indexOf('@'); + if (atIdx > 0 && atIdx < str.length - 1) { + const local = str.slice(0, atIdx); + const domain = str.slice(atIdx); + const chars = Array.from(local); + if (chars.length <= 1) return `*${domain}`; + if (chars.length === 2) return `${chars[0]}*${domain}`; + if (chars.length <= 4) return `${chars[0]}***${chars[chars.length - 1]}${domain}`; + return `${chars.slice(0, 2).join('')}***${chars.slice(-2).join('')}${domain}`; + } + const chars = Array.from(str); + if (chars.length <= 1) return '*'; + if (chars.length === 2) return `${chars[0]}*`; + if (chars.length <= 4) return `${chars[0]}***${chars[chars.length - 1]}`; + return `${chars.slice(0, 2).join('')}***${chars[chars.length - 1]}`; +} + +function formatRateEqUsd(val) { + const num = Number(val); + if (!Number.isFinite(num) || num <= 0) return '--'; + if (num >= 10) return `$${Math.round(num)}`; + return `$${Number(num.toFixed(1))}`; +} + +function formatRatePerUsdValue(rate) { + const num = Number(rate); + if (!Number.isFinite(num) || num <= 0) return '--'; + return String(Number(num.toFixed(2))); +} + +function formatRateMultiplier(mult) { + const num = Number(mult); + if (!Number.isFinite(num) || num <= 0) return ''; + return `${Number(num.toFixed(1))}x`; +} + +function createRateModelCard({ + name, + isMutedName = false, + isFallback = false, + multiplier = null, + rate5hPctPerUsd = null, + rateWeeklyPctPerUsd = null, + eqFull5hUsd = null, + eqFullWeeklyUsd = null, + samples = 0, +}) { + const leftNodes = [ + h('span', { + className: `quota-rate-model-name${isMutedName ? ' is-muted' : ''}`, + text: name, + }), + ]; + const multText = formatRateMultiplier(multiplier); + if (multText) { + leftNodes.push( + h('span', { + className: `quota-rate-mult-badge${Number(multiplier) >= 1.5 ? ' is-high' : ''}`, + text: multText, + }) + ); + } + + const has5hRate = rate5hPctPerUsd != null; + const primaryRate = has5hRate ? rate5hPctPerUsd : rateWeeklyPctPerUsd; + const subParts = []; + if (primaryRate != null) { + subParts.push( + t('quota.ratePopPerUsd', { + win: has5hRate ? '5h' : t('quota.weeklyShort'), + rate: formatRatePerUsdValue(primaryRate), + }) + ); + } + if (Number(samples) > 0) { + subParts.push(t('quota.ratePopSamples', { n: Number(samples) })); + } + + const eqCells = []; + if (eqFull5hUsd != null) { + eqCells.push( + h('div', { className: 'quota-rate-eq-cell' }, [ + h('span', { className: 'quota-rate-eq-k', text: t('quota.ratePopEq5hLabel') }), + h('span', { + className: 'quota-rate-eq-v text-mono', + text: `≈ ${formatRateEqUsd(eqFull5hUsd)}`, + }), + ]) + ); + } + if (eqFullWeeklyUsd != null) { + eqCells.push( + h('div', { className: 'quota-rate-eq-cell' }, [ + h('span', { className: 'quota-rate-eq-k', text: t('quota.ratePopEqWkLabel') }), + h('span', { + className: 'quota-rate-eq-v text-mono', + text: `≈ ${formatRateEqUsd(eqFullWeeklyUsd)}`, + }), + ]) + ); + } + + const cardChildren = [ + h('div', { className: 'quota-rate-row-top' }, [ + h('div', { className: 'quota-rate-model-left' }, leftNodes), + ...(subParts.length > 0 + ? [h('span', { className: 'quota-rate-meta text-mono', text: subParts.join(' · ') })] + : []), + ]), + ]; + if (eqCells.length > 0) { + cardChildren.push( + h( + 'div', + { className: `quota-rate-eq-grid${eqCells.length === 1 ? ' is-single' : ''}` }, + eqCells + ) + ); + } + + return h('div', { className: `quota-rate-model-row${isFallback ? ' is-fallback' : ''}` }, cardChildren); +} + +function buildRatePopoverSig(data) { + const locale = getEffectiveLocale(); + const acct = String(data?.account?.email || data?.account?.name || '').trim(); + const pools = Array.isArray(data?.quotas?.pools) ? data.quotas.pools : []; + const poolSig = pools + .map((p) => `${p.poolKey || ''}:${p.poolLabel || ''}:${JSON.stringify(p.rateEstimate || null)}`) + .join('|'); + return `${locale}|${acct}|${poolSig}`; +} + const QuotaPoolsWidget = defineComponent({ name: 'QuotaPoolsWidget', - setup({ props }) { + setup({ props, onCleanup }) { const compactHover = Boolean(props.compactHover); const titleTextEl = h('span', { text: t('module.quotas') }); const tierBadge = h('span', { className: 'panel-meta', text: 'Google AI · Pro' }); + + const ratePopTitleEl = h('span', { + className: 'quota-rate-pop-title', + text: t('quota.ratePopTitle'), + }); + const ratePopAccountEl = h('span', { + className: 'quota-rate-pop-account', + text: t('quota.ratePopAccountCurrent'), + }); + const ratePopBodyEl = h('div', { className: 'quota-rate-pop-body' }); + const ratePopNoteEl = h('div', { + className: 'quota-rate-pop-note', + text: t('quota.ratePopNote'), + }); + const ratePopoverEl = h( + 'div', + { + className: 'quota-rate-popover', + role: 'tooltip', + hidden: true, + }, + [ + h('div', { className: 'quota-rate-pop-head' }, [ratePopTitleEl, ratePopAccountEl]), + ratePopBodyEl, + ratePopNoteEl, + ] + ); + ratePopoverEl.hidden = true; + + let ratePopOpen = false; + let ratePopCloseTimer = null; + let lastRatePopSig = ''; + + const cancelRatePopClose = () => { + if (ratePopCloseTimer) { + clearTimeout(ratePopCloseTimer); + ratePopCloseTimer = null; + } + }; + + const setRatePopOpen = (open) => { + const next = Boolean(open); + ratePopOpen = next; + ratePopoverEl.hidden = !next; + patchAttr(ratePopoverEl, 'hidden', !next); + patchAttr(rateHelpBtn, 'aria-expanded', next ? 'true' : 'false'); + patchClasses(rateHelpBtn, { 'is-open': next }); + }; + + const openRatePop = () => { + cancelRatePopClose(); + if (!ratePopOpen) setRatePopOpen(true); + }; + + const scheduleRatePopClose = () => { + cancelRatePopClose(); + ratePopCloseTimer = setTimeout(() => { + ratePopCloseTimer = null; + setRatePopOpen(false); + }, 130); + }; + + const rateHelpBtn = h( + 'button', + { + type: 'button', + className: 'quota-rate-help-btn', + 'aria-label': t('quota.rateHelpAria'), + 'aria-haspopup': 'true', + 'aria-expanded': 'false', + onMouseenter: openRatePop, + onMouseleave: scheduleRatePopClose, + onFocus: openRatePop, + onBlur: scheduleRatePopClose, + onClick: (ev) => { + ev?.stopPropagation?.(); + cancelRatePopClose(); + setRatePopOpen(!ratePopOpen); + }, + onKeydown: (ev) => { + if (ev?.key === 'Escape' && ratePopOpen) { + ev.stopPropagation?.(); + cancelRatePopClose(); + setRatePopOpen(false); + } + }, + }, + [createSvgIcon('help-circle', { size: 13 })] + ); + + ratePopoverEl.addEventListener?.('mouseenter', openRatePop); + ratePopoverEl.addEventListener?.('mouseleave', scheduleRatePopClose); + onCleanup?.(() => { + cancelRatePopClose(); + }); + + function syncRatePopoverContent(data) { + const sig = buildRatePopoverSig(data); + if (sig === lastRatePopSig) return; + lastRatePopSig = sig; + + patchText(ratePopTitleEl, t('quota.ratePopTitle')); + patchText(ratePopNoteEl, t('quota.ratePopNote')); + patchAttr(rateHelpBtn, 'aria-label', t('quota.rateHelpAria')); + + const acctMasked = maskAccountLabel(data?.account?.email || data?.account?.name || ''); + patchText( + ratePopAccountEl, + acctMasked + ? t('quota.ratePopAccountScope', { account: acctMasked }) + : t('quota.ratePopAccountCurrent') + ); + patchAttr(ratePopAccountEl, 'title', acctMasked || null); + + while (ratePopBodyEl.firstChild) { + ratePopBodyEl.removeChild(ratePopBodyEl.firstChild); + } + + const rawPools = Array.isArray(data?.quotas?.pools) ? data.quotas.pools : []; + const populatedGroups = []; + + for (const p of rawPools) { + const est = p?.rateEstimate; + if (!est || typeof est !== 'object') continue; + const models = Array.isArray(est.models) ? est.models : []; + const hasPoolFallback = + models.length === 0 && + (Number.isFinite(est.rate5hPctPerUsd) || Number.isFinite(est.rateWeeklyPctPerUsd)); + if (models.length === 0 && !hasPoolFallback) continue; + + const poolLabel = p.poolLabel || p.family || p.poolKey || 'Pool'; + const rows = + models.length > 0 + ? models.map((item) => + createRateModelCard({ + name: item.model, + multiplier: item.multiplier, + rate5hPctPerUsd: item.rate5hPctPerUsd, + rateWeeklyPctPerUsd: item.rateWeeklyPctPerUsd, + eqFull5hUsd: item.eqFull5hUsd, + eqFullWeeklyUsd: item.eqFullWeeklyUsd, + samples: item.samples, + }) + ) + : [ + createRateModelCard({ + name: t('quota.ratePopPoolFallback'), + isMutedName: true, + isFallback: true, + rate5hPctPerUsd: est.rate5hPctPerUsd, + rateWeeklyPctPerUsd: est.rateWeeklyPctPerUsd, + eqFull5hUsd: est.eqFull5hUsd, + eqFullWeeklyUsd: est.eqFullWeeklyUsd, + samples: Math.max(Number(est.samples5h) || 0, Number(est.samplesWeekly) || 0), + }), + ]; + + populatedGroups.push( + h('div', { className: 'quota-rate-pool-group' }, [ + h('div', { className: 'quota-rate-pool-label', text: poolLabel }), + h('div', { className: 'quota-rate-model-list' }, rows), + ]) + ); + } + + if (populatedGroups.length === 0) { + ratePopBodyEl.appendChild( + h('div', { className: 'quota-rate-pop-empty', text: t('quota.ratePopEmpty') }) + ); + } else { + for (const grp of populatedGroups) { + ratePopBodyEl.appendChild(grp); + } + } + } + const poolsListEl = h( 'div', compactHover @@ -19096,22 +19444,27 @@ const QuotaPoolsWidget = defineComponent({ ] ); - const quotaPanel = h('section', { className: 'panel' }, [ + const quotaPanel = h('section', { className: 'panel quota-panel' }, [ h('div', { className: 'panel-header' }, [ h('span', { className: 'panel-title' }, [ createSvgIcon('pulse', { size: 13 }), titleTextEl, + rateHelpBtn, ]), tierBadge, ]), poolsListEl, reserveLegendEl, + ratePopoverEl, ]); + syncRatePopoverContent(null); + function update({ data, minuteTick } = {}) { patchText(titleTextEl, t('module.quotas')); patchText(legendActualTextEl, t('quota.legendActual')); patchText(legendReservedTextEl, t('quota.legendReserved')); + syncRatePopoverContent(data); if (!data) { reserveLegendEl.hidden = true; if (compactHover) { @@ -19140,11 +19493,11 @@ const QuotaPoolsWidget = defineComponent({ return { el: quotaPanel, - refs: { update, poolsListEl }, + refs: { update, poolsListEl, rateHelpBtn, ratePopoverEl }, }; }, }); -return { buildQuotaPoolItems, createPoolQuotaRow, formatQuotaSummaryFooter, syncPoolQuotaRow, quotaPoolRowSig, formatAccountTierBadge, QuotaPoolsWidget }; +return { buildQuotaPoolItems, createPoolQuotaRow, formatQuotaSummaryFooter, syncPoolQuotaRow, quotaPoolRowSig, formatAccountTierBadge, maskAccountLabel, QuotaPoolsWidget }; })(); // --- src/components/widgets/LiveActivityWidget.js --- diff --git a/sidecars/panel/backend/quota-reservation.mjs b/sidecars/panel/backend/quota-reservation.mjs index 99d7693..44f3ea2 100644 --- a/sidecars/panel/backend/quota-reservation.mjs +++ b/sidecars/panel/backend/quota-reservation.mjs @@ -39,6 +39,9 @@ export const QR_RATE_OUTLIER_MAX_RATIO = 2.0; export const QR_RATE_DRIFT_STREAK = 5; export const QR_CONSUME_MIN_SHORTFALL_PCT = 0.03; export const QR_CONSUME_SHORTFALL_RATIO = 0.35; +export const QR_MODEL_RATE_MIN_UI_SAMPLES = 3; +export const QR_MODEL_SINGLE_DOMINANCE_RATIO = 0.95; +const QR_MAX_MODELS_PER_BUCKET = 16; const QR_MAX_TRACKED_BUCKETS = 128; const QR_MAX_ACTIVE_LEASES = 16; const QR_MAX_EVENT_LOG = 500; @@ -250,6 +253,193 @@ function qrSanitizePersistedPendingDrop(raw) { }; } +function qrSanitizeModelCosts(raw) { + const out = {}; + if (!raw || typeof raw !== 'object') return out; + for (const [k, v] of Object.entries(raw)) { + const cleanKey = String(k || '').trim(); + const num = Number(v); + if (cleanKey && Number.isFinite(num) && num > 0) { + out[cleanKey] = num; + } + } + return out; +} + +function qrSanitizePersistedModelRates(raw, { preserveRate = true } = {}) { + const out = {}; + if (!preserveRate || !raw || typeof raw !== 'object') return out; + const entries = Object.entries(raw).slice(-QR_MAX_MODELS_PER_BUCKET); + for (const [k, item] of entries) { + const cleanKey = String(k || '').trim(); + if (!cleanKey || !item || typeof item !== 'object') continue; + const rateWindow = Array.isArray(item.rateWindow) + ? item.rateWindow + .map((v) => qrClampRate(Number(v))) + .filter((v) => v !== null) + .slice(-QR_RATE_WINDOW_SIZE) + : []; + const rate = + rateWindow.length > 0 + ? qrClampRate(qrComputeMedian(rateWindow)) + : item.ratePctPerUsd !== undefined && item.ratePctPerUsd !== null + ? qrClampRate(Number(item.ratePctPerUsd)) + : null; + if (rate === null) continue; + out[cleanKey] = { + ratePctPerUsd: rate, + rateSamples: Math.max(rateWindow.length, Math.floor(Number(item.rateSamples) || 0)), + rateWindow, + rateOutlierSide: 0, + rateOutlierBuf: [], + lastSeenMs: Math.max(0, Number(item.lastSeenMs) || 0), + }; + } + return out; +} + +function qrGetOrCreateModelRate(st, modelKey, nowMs) { + const map = st.modelRates && typeof st.modelRates === 'object' ? st.modelRates : (st.modelRates = {}); + if (map[modelKey]) return map[modelKey]; + const keys = Object.keys(map); + if (keys.length >= QR_MAX_MODELS_PER_BUCKET) { + let oldestKey = keys[0]; + let oldestMs = Number(map[oldestKey]?.lastSeenMs || 0); + for (let i = 1; i < keys.length; i += 1) { + const candidateMs = Number(map[keys[i]]?.lastSeenMs || 0); + if (candidateMs < oldestMs) { + oldestMs = candidateMs; + oldestKey = keys[i]; + } + } + if (oldestKey) delete map[oldestKey]; + } + const entry = { + ratePctPerUsd: null, + rateSamples: 0, + rateWindow: [], + rateOutlierSide: 0, + rateOutlierBuf: [], + lastSeenMs: nowMs, + }; + map[modelKey] = entry; + return entry; +} + +function qrEstimateModelWeightedPct(st, deltaModelCosts, totalDeltaCostUsd, fallbackRate) { + if (fallbackRate === null || !Number.isFinite(fallbackRate) || totalDeltaCostUsd <= 0) return 0; + const modelRates = st.modelRates && typeof st.modelRates === 'object' ? st.modelRates : null; + if (!modelRates || !deltaModelCosts || typeof deltaModelCosts !== 'object') { + return totalDeltaCostUsd * fallbackRate; + } + let attributedCost = 0; + let weightedPct = 0; + let usedPerModel = false; + for (const [mKey, costDelta] of Object.entries(deltaModelCosts)) { + if (!Number.isFinite(costDelta) || costDelta <= 0) continue; + attributedCost += costDelta; + const mr = modelRates[mKey]; + if (mr && mr.rateSamples >= 2 && Number.isFinite(mr.ratePctPerUsd) && mr.ratePctPerUsd > 0) { + weightedPct += costDelta * mr.ratePctPerUsd; + usedPerModel = true; + } else { + weightedPct += costDelta * fallbackRate; + } + } + if (!usedPerModel || attributedCost <= 0) { + return totalDeltaCostUsd * fallbackRate; + } + const unattributedCost = Math.max(0, totalDeltaCostUsd - attributedCost); + return weightedPct + unattributedCost * fallbackRate; +} + +function qrBuildPoolRateEstimate(st5h, stWk) { + const raw5hPool = + st5h && st5h.rateSamples >= QR_MODEL_RATE_MIN_UI_SAMPLES && Number.isFinite(st5h.ratePctPerUsd) + ? st5h.ratePctPerUsd + : null; + const rawWkPool = + stWk && stWk.rateSamples >= QR_MODEL_RATE_MIN_UI_SAMPLES && Number.isFinite(stWk.ratePctPerUsd) + ? stWk.ratePctPerUsd + : null; + const rate5hPool = raw5hPool !== null ? +raw5hPool.toFixed(4) : null; + const rateWkPool = rawWkPool !== null ? +rawWkPool.toFixed(4) : null; + + const modelKeys = new Set([ + ...Object.keys(st5h?.modelRates || {}), + ...Object.keys(stWk?.modelRates || {}), + ]); + const models = []; + for (const model of modelKeys) { + const m5 = st5h?.modelRates?.[model] || null; + const mw = stWk?.modelRates?.[model] || null; + const rawR5 = + m5 && m5.rateSamples >= QR_MODEL_RATE_MIN_UI_SAMPLES && Number.isFinite(m5.ratePctPerUsd) + ? m5.ratePctPerUsd + : null; + const rawRw = + mw && mw.rateSamples >= QR_MODEL_RATE_MIN_UI_SAMPLES && Number.isFinite(mw.ratePctPerUsd) + ? mw.ratePctPerUsd + : null; + if (rawR5 === null && rawRw === null) continue; + models.push({ + model, + rate5hPctPerUsd: rawR5 !== null ? +rawR5.toFixed(4) : null, + rateWeeklyPctPerUsd: rawRw !== null ? +rawRw.toFixed(4) : null, + eqFull5hUsd: rawR5 ? +(100 / rawR5).toFixed(1) : null, + eqFullWeeklyUsd: rawRw ? +(100 / rawRw).toFixed(1) : null, + multiplier: null, + samples: Math.max(m5?.rateSamples || 0, mw?.rateSamples || 0), + _rawR5: rawR5, + _rawRw: rawRw, + }); + } + + if (models.length >= 2) { + const allHave5h = models.every((m) => m._rawR5 !== null); + const allHaveWk = models.every((m) => m._rawRw !== null); + const basisList = allHave5h + ? models.map((m) => m._rawR5) + : allHaveWk + ? models.map((m) => m._rawRw) + : null; + if (basisList) { + const minBasis = Math.min(...basisList); + if (minBasis > 0) { + for (let i = 0; i < models.length; i += 1) { + models[i].multiplier = +(basisList[i] / minBasis).toFixed(1); + } + } + } + } + + models.sort( + (a, b) => + (b.multiplier ?? 0) - (a.multiplier ?? 0) || + (b._rawR5 ?? b._rawRw ?? 0) - (a._rawR5 ?? a._rawRw ?? 0) || + b.samples - a.samples || + a.model.localeCompare(b.model) + ); + for (const m of models) { + delete m._rawR5; + delete m._rawRw; + } + + if (models.length === 0 && rate5hPool === null && rateWkPool === null) { + return null; + } + + return { + rate5hPctPerUsd: rate5hPool, + rateWeeklyPctPerUsd: rateWkPool, + eqFull5hUsd: raw5hPool ? +(100 / raw5hPool).toFixed(1) : null, + eqFullWeeklyUsd: rawWkPool ? +(100 / rawWkPool).toFixed(1) : null, + samples5h: st5h?.rateSamples || 0, + samplesWeekly: stWk?.rateSamples || 0, + models, + }; +} + function qrSanitizePersistedBucket(raw, { preserveRate = true } = {}) { if (!raw || typeof raw !== 'object') return null; const lastOfficial = @@ -277,15 +467,18 @@ function qrSanitizePersistedBucket(raw, { preserveRate = true } = {}) { lastQuotaTs: Math.max(0, Number(raw.lastQuotaTs) || 0), lastOfficialUsedPct: lastOfficial, lastCycleCostUsd: Math.max(0, Number(raw.lastCycleCostUsd) || 0), + lastModelCostsUsd: qrSanitizeModelCosts(raw.lastModelCostsUsd), lastUnpricedCalls: Math.max(0, Number(raw.lastUnpricedCalls) || 0), pendingCostUsd: 0, pendingCostAtMs: 0, pendingCostSinceMs: 0, + pendingModelCostsUsd: {}, ratePctPerUsd: rate, rateSamples: preserveRate ? Math.max(rateWindow.length, Math.floor(Number(raw.rateSamples) || 0)) : 0, rateWindow, rateOutlierSide: 0, rateOutlierBuf: [], + modelRates: qrSanitizePersistedModelRates(raw.modelRates, { preserveRate }), activeLeases: qrSanitizePersistedLeases(raw.activeLeases), pendingDrop: preserveRate ? qrSanitizePersistedPendingDrop(raw.pendingDrop) : null, lastBounceAtMs: Math.max(0, Number(raw.lastBounceAtMs) || 0), @@ -336,15 +529,27 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu function serializeState(nowMs = Date.now()) { const serializedBuckets = {}; for (const [k, st] of buckets.entries()) { + const serializedModelRates = {}; + for (const [mKey, mr] of Object.entries(st.modelRates || {})) { + if (!mr || mr.ratePctPerUsd === null) continue; + serializedModelRates[mKey] = { + ratePctPerUsd: mr.ratePctPerUsd, + rateSamples: mr.rateSamples, + rateWindow: mr.rateWindow, + lastSeenMs: mr.lastSeenMs, + }; + } serializedBuckets[k] = { resetTimeMs: st.resetTimeMs, lastQuotaTs: st.lastQuotaTs, lastOfficialUsedPct: st.lastOfficialUsedPct, lastCycleCostUsd: st.lastCycleCostUsd, + lastModelCostsUsd: st.lastModelCostsUsd || {}, lastUnpricedCalls: st.lastUnpricedCalls, ratePctPerUsd: st.ratePctPerUsd, rateSamples: st.rateSamples, rateWindow: st.rateWindow, + modelRates: serializedModelRates, activeLeases: st.activeLeases, pendingDrop: st.pendingDrop, lastBounceAtMs: st.lastBounceAtMs, @@ -411,15 +616,18 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu lastQuotaTs: 0, lastOfficialUsedPct: null, lastCycleCostUsd: 0, + lastModelCostsUsd: {}, lastUnpricedCalls: 0, pendingCostUsd: 0, pendingCostAtMs: 0, pendingCostSinceMs: 0, + pendingModelCostsUsd: {}, ratePctPerUsd: null, rateSamples: 0, rateWindow: [], rateOutlierSide: 0, rateOutlierBuf: [], + modelRates: {}, activeLeases: [], pendingDrop: null, lastBounceAtMs: 0, @@ -438,6 +646,7 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu resetTimeMs = 0, quotaFetchedAtMs = 0, cycleCostUsd = 0, + modelCostsUsd = null, unpricedCalls = 0, poolLastActivityMs = 0, activeSessionCount10m = 0, @@ -450,6 +659,7 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu ensureHydrated(); const safeUsed = qrClamp(Number(officialUsedPct), 0, 100); const safeCost = Math.max(0, Number(cycleCostUsd) || 0); + const safeModelCosts = qrSanitizeModelCosts(modelCostsUsd); const safeUnpriced = Math.max(0, Number(unpricedCalls) || 0); const safeResetMs = Number(resetTimeMs) > 0 ? Number(resetTimeMs) : 0; const safeFetchTs = Number(quotaFetchedAtMs) > 0 ? Number(quotaFetchedAtMs) : nowMs; @@ -483,7 +693,7 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu ); }; - // 1. 周期重置检测:静默忽略 0% 空闲池的滑动重置时间漂移;真正跨周期时清空租约但保留单桶费率 + // 1. 周期重置检测:静默忽略 0% 空闲池的滑动重置时间漂移;真正跨周期时清空租约但保留单桶及单模型费率 const resetShifted = safeResetMs > 0 && st.resetTimeMs > 0 && @@ -502,6 +712,7 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu st.lastQuotaTs = safeFetchTs; st.lastOfficialUsedPct = safeUsed; st.lastCycleCostUsd = safeCost; + st.lastModelCostsUsd = safeModelCosts; st.lastUnpricedCalls = safeUnpriced; if (isIdleZeroDrift) { return qrFormatOutput(st, safeUsed); @@ -509,6 +720,7 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu st.pendingCostUsd = 0; st.pendingCostAtMs = 0; st.pendingCostSinceMs = 0; + st.pendingModelCostsUsd = {}; st.activeLeases = []; st.pendingDrop = null; const out = qrFormatOutput(st, safeUsed); @@ -522,6 +734,7 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu st.lastQuotaTs = safeFetchTs; st.lastOfficialUsedPct = safeUsed; st.lastCycleCostUsd = safeCost; + st.lastModelCostsUsd = safeModelCosts; st.lastUnpricedCalls = safeUnpriced; if (safeCost >= 0.5 && safeUsed >= 0.3) { st.ratePctPerUsd = qrClampRate(safeUsed / safeCost); @@ -536,10 +749,16 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu st.resetTimeMs = safeResetMs; } - // 3. 同一份缓存配额响应:跳过重复差分,仅检查租约超时清理 + // 3. 同一份缓存配额响应:跳过重复差分,仅补齐缺失的单模型基线并检查租约超时清理 const isFreshSample = safeFetchTs !== st.lastQuotaTs || Math.abs(safeUsed - st.lastOfficialUsedPct) > 1e-4; if (!isFreshSample) { + if ( + Object.keys(st.lastModelCostsUsd || {}).length === 0 && + Object.keys(safeModelCosts).length > 0 + ) { + st.lastModelCostsUsd = safeModelCosts; + } const beforeCachePrune = st.activeLeases.length; qrPruneExpiredLeases(st, nowMs); const out = qrFormatOutput(st, safeUsed); @@ -551,12 +770,55 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu const deltaOfficial = safeUsed - st.lastOfficialUsedPct; const rawDeltaCost = Math.max(0, safeCost - st.lastCycleCostUsd); + const prevModelCosts = st.lastModelCostsUsd && typeof st.lastModelCostsUsd === 'object' ? st.lastModelCostsUsd : {}; + const hasValidPrevModelBaseline = + st.lastCycleCostUsd <= 1e-6 || Object.keys(prevModelCosts).length > 0; + const rawDeltaModelCosts = {}; + let totalModelDeltaUsd = 0; + let dominantModelKey = ''; + let dominantModelDeltaUsd = 0; + if (hasValidPrevModelBaseline) { + for (const [mKey, curModelCost] of Object.entries(safeModelCosts)) { + const prevModelCost = Number(prevModelCosts[mKey]) || 0; + const dModel = curModelCost - prevModelCost; + if (dModel > 1e-6) { + rawDeltaModelCosts[mKey] = dModel; + totalModelDeltaUsd += dModel; + if (dModel > dominantModelDeltaUsd) { + dominantModelDeltaUsd = dModel; + dominantModelKey = mKey; + } + } + } + } + const modelDeltaMatchesTotal = + totalModelDeltaUsd > 0 && totalModelDeltaUsd <= rawDeltaCost * 1.15 + 0.01; + const isPureSingleModelStep = Boolean( + hasValidPrevModelBaseline && + modelDeltaMatchesTotal && + dominantModelKey && + dominantModelDeltaUsd / totalModelDeltaUsd >= QR_MODEL_SINGLE_DOMINANCE_RATIO && + dominantModelDeltaUsd >= 0.04 + ); const deltaUnpriced = Math.max(0, safeUnpriced - st.lastUnpricedCalls); const pendingValid = st.pendingCostUsd > 0 && nowMs - st.pendingCostAtMs <= QR_PENDING_COST_TTL_MS; const effectiveDeltaCost = rawDeltaCost + (pendingValid ? st.pendingCostUsd : 0); + const effectiveDeltaModelCosts = { ...rawDeltaModelCosts }; + if (pendingValid && st.pendingModelCostsUsd && typeof st.pendingModelCostsUsd === 'object') { + for (const [mKey, pCost] of Object.entries(st.pendingModelCostsUsd)) { + if (Number.isFinite(pCost) && pCost > 0) { + effectiveDeltaModelCosts[mKey] = (effectiveDeltaModelCosts[mKey] || 0) + pCost; + } + } + } const rate = qrResolveEffectiveRate(st, safeUsed, safeCost); - let expectedDeltaPct = rate !== null ? effectiveDeltaCost * rate : 0; + let expectedDeltaPct = qrEstimateModelWeightedPct( + st, + effectiveDeltaModelCosts, + effectiveDeltaCost, + rate + ); let excessPct = deltaOfficial - expectedDeltaPct; const isIdleRefundReady = poolLastActivityMs > 0 && nowMs - poolLastActivityMs >= QR_IDLE_CONFIRM_REFUND_MS; @@ -566,6 +828,7 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu st.pendingCostUsd = 0; st.pendingCostAtMs = 0; st.pendingCostSinceMs = 0; + st.pendingModelCostsUsd = {}; }; const confirmRefund = (refundedPct, { keepPendingCost = false } = {}) => { @@ -732,8 +995,13 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu deltaOfficial > 0.005 && deltaOfficial < QR_MIN_JUMP_EXCESS_PCT ) { - // 纯净未租约且无近期副本抖动的单步消耗:进入滚动中位数费率校准池 + // 纯净未租约且无近期副本抖动的单步消耗:进入滚动中位数费率校准池;纯单模型步同步校准该模型费率 qrRecordRateSample(st, deltaOfficial / rawDeltaCost); + if (isPureSingleModelStep) { + const mr = qrGetOrCreateModelRate(st, dominantModelKey, nowMs); + qrRecordRateSample(mr, deltaOfficial / dominantModelDeltaUsd); + mr.lastSeenMs = nowMs; + } } eventKind = 'normal'; } @@ -743,9 +1011,17 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu const hasBufferedLeaseCost = st.pendingCostUsd > 0 && st.pendingCostSinceMs > 0; if (st.activeLeases.length > 0) { const accCost = rawDeltaCost + (hasBufferedLeaseCost ? st.pendingCostUsd : 0); + const accModelCosts = { ...rawDeltaModelCosts }; + if (hasBufferedLeaseCost && st.pendingModelCostsUsd && typeof st.pendingModelCostsUsd === 'object') { + for (const [mKey, pCost] of Object.entries(st.pendingModelCostsUsd)) { + if (Number.isFinite(pCost) && pCost > 0) { + accModelCosts[mKey] = (accModelCosts[mKey] || 0) + pCost; + } + } + } const sinceMs = hasBufferedLeaseCost ? st.pendingCostSinceMs : nowMs; if (nowMs - sinceMs >= QR_CONSUME_LAG_GRACE_MS) { - const consumedPct = rate !== null ? accCost * rate : 0; + const consumedPct = qrEstimateModelWeightedPct(st, accModelCosts, accCost, rate); expectedDeltaPct = consumedPct; excessPct = deltaOfficial - expectedDeltaPct; if (consumedPct > 0) { @@ -760,6 +1036,7 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu st.pendingCostUsd = accCost; st.pendingCostAtMs = nowMs; st.pendingCostSinceMs = sinceMs; + st.pendingModelCostsUsd = accModelCosts; eventKind = 'lag_pending'; } } else { @@ -768,6 +1045,7 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu st.pendingCostAtMs = nowMs; st.pendingCostSinceMs = pendingValid && st.pendingCostSinceMs > 0 ? st.pendingCostSinceMs : nowMs; + st.pendingModelCostsUsd = effectiveDeltaModelCosts; eventKind = 'lag_pending'; } } else if ( @@ -777,7 +1055,12 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu nowMs - st.pendingCostSinceMs >= QR_CONSUME_LAG_GRACE_MS ) { // 4C-2. 无新增花费但已跨过 25s 延迟观察窗且官方仍原地踏步:确认此前缓冲成本已在租约内消化 - const consumedPct = rate !== null ? st.pendingCostUsd * rate : 0; + const consumedPct = qrEstimateModelWeightedPct( + st, + st.pendingModelCostsUsd, + st.pendingCostUsd, + rate + ); expectedDeltaPct = consumedPct; excessPct = deltaOfficial - expectedDeltaPct; if (consumedPct > 0) { @@ -793,6 +1076,7 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu st.lastQuotaTs = safeFetchTs; st.lastOfficialUsedPct = safeUsed; st.lastCycleCostUsd = safeCost; + st.lastModelCostsUsd = safeModelCosts; st.lastUnpricedCalls = safeUnpriced; // 5. 租约 TTL 超时兜底(租约本身超过 60 分钟无实质扣减或满 90 分钟自动清理) @@ -824,7 +1108,8 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu nowMs = Date.now(), } = {}) { if (!(quotaPoolsMap instanceof Map) || quotaPoolsMap.size === 0) return; - const scopePrefix = `${String(endpointId || 'local')}::${String(accountScope || '')}`; + const normalizedAccountScope = String(accountScope || '').trim().toLowerCase(); + const scopePrefix = `${String(endpointId || 'local')}::${normalizedAccountScope}`; for (const [poolKey, poolObj] of quotaPoolsMap.entries()) { if (!poolObj || typeof poolObj !== 'object') continue; @@ -834,17 +1119,19 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu const activeSessionCount10m = Number(recent10m?.activeSessionCount) || 0; const recent10mCostUsd = Number(recent10m?.costUsd) || 0; + const key5h = `${scopePrefix}::${poolKey}::5h`; const used5hExact = poolObj.has5h ? qrResolveExactUsedPct(poolObj, '5h') : null; const res5h = used5hExact !== null ? observeBucket({ - bucketKey: `${scopePrefix}::${poolKey}::5h`, + bucketKey: key5h, poolKey, win: '5h', officialUsedPct: used5hExact, resetTimeMs: parseIsoMs(poolObj.resetTime), quotaFetchedAtMs, cycleCostUsd: pStats?.exactCost5hUsd ?? pStats?.cycle5h?.costUsd ?? 0, + modelCostsUsd: pStats?.modelCosts5h || null, unpricedCalls: pStats?.cycle5h?.unpricedCalls || 0, poolLastActivityMs, activeSessionCount10m, @@ -853,17 +1140,19 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu }) : { reservedPct: 0, reservedLeaseCount: 0, reservedExpiresAtMs: null }; + const keyWk = `${scopePrefix}::${poolKey}::weekly`; const usedWkExact = poolObj.hasWeekly ? qrResolveExactUsedPct(poolObj, 'weekly') : null; const resWk = usedWkExact !== null ? observeBucket({ - bucketKey: `${scopePrefix}::${poolKey}::weekly`, + bucketKey: keyWk, poolKey, win: 'weekly', officialUsedPct: usedWkExact, resetTimeMs: parseIsoMs(poolObj.weeklyResetTime), quotaFetchedAtMs, cycleCostUsd: pStats?.exactCostWeeklyUsd ?? pStats?.cycleWeekly?.costUsd ?? 0, + modelCostsUsd: pStats?.modelCostsWeekly || null, unpricedCalls: pStats?.cycleWeekly?.unpricedCalls || 0, poolLastActivityMs, activeSessionCount10m, @@ -878,6 +1167,7 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu poolObj.weeklyReservedPct = resWk.reservedPct; poolObj.weeklyReservedLeaseCount = resWk.reservedLeaseCount; poolObj.weeklyReservedExpiresAtMs = resWk.reservedExpiresAtMs; + poolObj.rateEstimate = qrBuildPoolRateEstimate(buckets.get(key5h) || null, buckets.get(keyWk) || null); } } @@ -888,6 +1178,15 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu const parts = key.split('::'); const usedPct = st.lastOfficialUsedPct ?? 0; const out = qrFormatOutput(st, usedPct); + const byModel = {}; + for (const [mKey, mr] of Object.entries(st.modelRates || {})) { + if (!mr || mr.ratePctPerUsd === null) continue; + byModel[mKey] = { + ratePctPerUsd: +mr.ratePctPerUsd.toFixed(4), + eqFullUsd: +(100 / mr.ratePctPerUsd).toFixed(1), + samples: mr.rateSamples, + }; + } bucketSummaries.push({ pool: parts[2] || key, win: parts[3] || '', @@ -897,6 +1196,7 @@ export function createQuotaReservationTracker({ loadState = null, saveState = nu rateSamples: st.rateSamples, reservedPct: out.reservedPct, leases: out.reservedLeaseCount, + ...(Object.keys(byModel).length > 0 ? { byModel } : {}), }); } return { diff --git a/sidecars/panel/backend/usage-aggregator.mjs b/sidecars/panel/backend/usage-aggregator.mjs index c52049b..c991a62 100644 --- a/sidecars/panel/backend/usage-aggregator.mjs +++ b/sidecars/panel/backend/usage-aggregator.mjs @@ -794,6 +794,8 @@ function buildQuotaPoolCycleMap(quotaPoolsMap, nowMs) { startWkMs, b5h: createUsageBucket(), bWk: createUsageBucket(), + modelCosts5h: new Map(), + modelCostsWk: new Map(), lastActivityMs: 0, recent10mSessions: new Map(), }); @@ -1577,11 +1579,24 @@ export function aggregateMultiWindowUsage({ sessStat.calls += 1; if (qMs > sessStat.lastActivityMs) sessStat.lastActivityMs = qMs; } + const quotaModelKey = mInfo.baseLabel || mInfo.label || ''; if (qMs >= poolBucketEntry.start5hMs) { accumulateStepIntoBucket(poolBucketEntry.b5h, stepUsage, cascadeId); + if (quotaModelKey && stepUsage.resolvedCost > 0) { + poolBucketEntry.modelCosts5h.set( + quotaModelKey, + (poolBucketEntry.modelCosts5h.get(quotaModelKey) || 0) + stepUsage.resolvedCost + ); + } } if (qMs >= poolBucketEntry.startWkMs) { accumulateStepIntoBucket(poolBucketEntry.bWk, stepUsage, cascadeId); + if (quotaModelKey && stepUsage.resolvedCost > 0) { + poolBucketEntry.modelCostsWk.set( + quotaModelKey, + (poolBucketEntry.modelCostsWk.get(quotaModelKey) || 0) + stepUsage.resolvedCost + ); + } } } @@ -1783,6 +1798,16 @@ export function aggregateMultiWindowUsage({ let rawPoolsWeeklyTokens = 0; let rawPoolsWeeklyCostUsd = 0; let rawPoolsWeeklyUnpricedCalls = 0; + const serializeModelCosts = (mMap) => { + const out = {}; + if (!(mMap instanceof Map)) return out; + for (const [mKey, costVal] of mMap.entries()) { + if (mKey && Number.isFinite(costVal) && costVal > 0) { + out[mKey] = +costVal.toFixed(6); + } + } + return out; + }; for (const [poolKey, entry] of poolCycleBuckets.entries()) { let recent10mCostUsd = 0; for (const sStat of entry.recent10mSessions.values()) { @@ -1793,6 +1818,8 @@ export function aggregateMultiWindowUsage({ cycleWeekly: formatCycleSummary(entry.bWk), exactCost5hUsd: +entry.b5h.costUsd.toFixed(6), exactCostWeeklyUsd: +entry.bWk.costUsd.toFixed(6), + modelCosts5h: serializeModelCosts(entry.modelCosts5h), + modelCostsWeekly: serializeModelCosts(entry.modelCostsWk), recent10m: { lastActivityMs: entry.lastActivityMs, activeSessionCount: entry.recent10mSessions.size, diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index 1a90a0d..c05ece7 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@