From 6da6c75390fa5e651b1cc1a0848a705b23c28c41 Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Sun, 22 Nov 2026 20:59:02 +0900 Subject: [PATCH] feat(panel): refine quota reservation estimator, tier 5x/20x badge, conditional argon_weekly slot, and chart markers --- sidecars/panel/app.js | 416 +++++++++----- .../panel/backend/cli-statusline-config.mjs | 11 +- sidecars/panel/backend/config.mjs | 1 + sidecars/panel/backend/quota-reservation.mjs | 533 +++++++++++++++--- sidecars/panel/backend/telemetry-builder.mjs | 40 +- sidecars/panel/index.html | 4 +- .../panel/shared/settings-normalization.mjs | 1 + .../panel/shared/telemetry-display-rules.mjs | 64 ++- .../components/charts/SessionStepCharts.js | 75 ++- .../src/components/charts/TrendAreaChart.js | 27 +- .../settings/structurePreviewMock.js | 25 +- .../components/widgets/QuotaPoolsWidget.js | 70 ++- sidecars/panel/src/i18n/en-US.js | 9 +- sidecars/panel/src/i18n/zh-CN.js | 9 +- .../panel/src/registries/metricRegistry.js | 60 +- sidecars/panel/src/store/telemetryStore.js | 2 + sidecars/panel/src/styles/modern-ui.css | 5 - sidecars/panel/src/styles/views-overview.css | 57 +- sidecars/panel/src/styles/views-tables.css | 25 +- sidecars/panel/src/views/SettingsView.js | 3 +- .../views/settings/SettingsStructureTab.js | 72 ++- sidecars/panel/styles.css | 87 ++- sidecars/panel/test/quota-pools.test.mjs | 138 +++++ .../panel/test/quota-reservation.test.mjs | 320 ++++++++++- sidecars/panel/test/step-anomalies.test.mjs | 7 +- sidecars/panel/test/window-bridge.test.mjs | 4 +- 26 files changed, 1673 insertions(+), 392 deletions(-) diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index 2f7bb22..53f2bda 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -33,6 +33,7 @@ const TOPBAR_SLOT_KEYS = Object.freeze([ 'quota_auto', 'gemini_5h', 'gemini_weekly', + 'argon_weekly', 'claude_5h', 'claude_weekly', ]); @@ -592,7 +593,7 @@ return { SUPPORTED_LANGUAGES, THEME_ACCENT_KEYS, FONT_SCALE_KEYS, TOPBAR_SLOT_KE })(); // --- shared/telemetry-display-rules.mjs --- -const { THIRD_PARTY_POOL_RE, isThirdPartyPoolText, classifySpeedTier, classifyCacheTier, classifyStepCostTier, classifyTtftTier, formatCompactTokens, formatCompactCapsuleCost, formatCompactCapsuleTtft, resolveCapsuleQuotaSlotPct, scaleBucketsExact } = (() => { +const { THIRD_PARTY_POOL_RE, isThirdPartyPoolText, classifySpeedTier, classifyCacheTier, classifyStepCostTier, classifyTtftTier, formatCompactTokens, formatCompactCapsuleCost, formatCompactCapsuleTtft, hasArgonWeeklyQuotaPool, resolveCapsuleQuotaSlotPct, scaleBucketsExact } = (() => { /** * @fileoverview 跨 Backend / Frontend / CLI 共用的纯展示阈值、紧凑格式化、第三方配额分池与精确整数缩放规则。 */ @@ -691,8 +692,40 @@ function formatCompactCapsuleTtft(ttftSec) { return `${Math.round(val)}s`; } +function readPoolWeeklyRemainingPct(pool) { + if (!pool || typeof pool !== 'object') return null; + const raw = pool.weeklyRemainingPct ?? pool.remainingWeeklyPct; + return raw != null && Number.isFinite(Number(raw)) ? Number(raw) : null; +} + +function isArgonPoolObject(pool) { + if (!pool || typeof pool !== 'object') return false; + if (pool.poolKey === 'Argon' || pool.family === 'Argon') return true; + return /\bargon\b/i.test(String(pool.poolKey || pool.poolLabel || pool.family || '')); +} + /** - * 解析胶囊指定配额槽位(`quota_auto` / `gemini_5h` / `gemini_weekly` / `claude_5h` / `claude_weekly`)的整数剩余百分比。 + * 判断当前配额摘要中是否存在独立的 Argon 周限配额池(如 Google AI Pro 账号)。 + * + * @param {object|null|undefined} quotas + * @returns {boolean} + */ +function hasArgonWeeklyQuotaPool(quotas) { + if (!quotas || typeof quotas !== 'object') return false; + const pools = Array.isArray(quotas.pools) ? quotas.pools : []; + const argonPool = pools.find(isArgonPoolObject); + if (argonPool && readPoolWeeklyRemainingPct(argonPool) != null) { + return true; + } + const activePool = quotas.activePool; + if (activePool && isArgonPoolObject(activePool) && readPoolWeeklyRemainingPct(activePool) != null) { + return true; + } + return false; +} + +/** + * 解析胶囊指定配额槽位(`quota_auto` / `gemini_5h` / `gemini_weekly` / `argon_weekly` / `claude_5h` / `claude_weekly`)的整数剩余百分比。 * * @param {object|null|undefined} quotas * @param {string} slotKey @@ -709,8 +742,9 @@ function resolveCapsuleQuotaSlotPct(quotas, slotKey) { if (activePool && Number.isFinite(Number(activePool.remainingPct))) { candidates.push(Number(activePool.remainingPct)); } - if (activePool && Number.isFinite(Number(activePool.weeklyRemainingPct))) { - candidates.push(Number(activePool.weeklyRemainingPct)); + const activeWk = readPoolWeeklyRemainingPct(activePool); + if (activeWk != null) { + candidates.push(activeWk); } if (!candidates.length && weekly && Number.isFinite(Number(weekly.remainingPct))) { candidates.push(Number(weekly.remainingPct)); @@ -718,15 +752,24 @@ function resolveCapsuleQuotaSlotPct(quotas, slotKey) { if (!candidates.length && pools.length > 0) { for (const p of pools) { if (p && Number.isFinite(Number(p.remainingPct))) candidates.push(Number(p.remainingPct)); - if (p && Number.isFinite(Number(p.weeklyRemainingPct))) { - candidates.push(Number(p.weeklyRemainingPct)); - } + const pWk = readPoolWeeklyRemainingPct(p); + if (pWk != null) candidates.push(pWk); } } if (!candidates.length) return null; return Math.max(0, Math.min(100, Math.round(Math.min(...candidates)))); } + if (slotKey === 'argon_weekly') { + const argonPool = pools.find(isArgonPoolObject); + let argonPct = readPoolWeeklyRemainingPct(argonPool); + if (argonPct == null && isArgonPoolObject(activePool)) { + argonPct = readPoolWeeklyRemainingPct(activePool); + } + if (argonPct == null || !Number.isFinite(argonPct)) return null; + return Math.max(0, Math.min(100, Math.round(argonPct))); + } + const isClaude = slotKey.startsWith('claude_'); const isWeekly = slotKey.endsWith('_weekly'); let rawPct = null; @@ -735,11 +778,11 @@ function resolveCapsuleQuotaSlotPct(quotas, slotKey) { const claudePool = pools.find((p) => p?.poolKey === 'Claude & GPT') || pools.find((p) => isThirdPartyPoolText(p?.poolKey || p?.poolLabel || '')); - const cand = isWeekly ? claudePool?.weeklyRemainingPct : claudePool?.remainingPct; + const cand = isWeekly ? readPoolWeeklyRemainingPct(claudePool) : claudePool?.remainingPct; if (cand != null && Number.isFinite(Number(cand))) { rawPct = Number(cand); } else if (activePool && isThirdPartyPoolText(activePool.family || activePool.poolLabel || '')) { - const fb = isWeekly ? activePool.weeklyRemainingPct : activePool.remainingPct; + const fb = isWeekly ? readPoolWeeklyRemainingPct(activePool) : activePool.remainingPct; if (fb != null && Number.isFinite(Number(fb))) rawPct = Number(fb); } } else { @@ -753,12 +796,12 @@ function resolveCapsuleQuotaSlotPct(quotas, slotKey) { const geminiFamilyPools = pools.filter((p) => /gemini|carbon|argon/i.test(String(p?.poolKey || p?.poolLabel || '')) ); - const primaryCand = isWeekly ? stdGemini?.weeklyRemainingPct : stdGemini?.remainingPct; + const primaryCand = isWeekly ? readPoolWeeklyRemainingPct(stdGemini) : stdGemini?.remainingPct; if (primaryCand != null && Number.isFinite(Number(primaryCand))) { rawPct = Number(primaryCand); } else { const familyVals = geminiFamilyPools - .map((p) => (isWeekly ? p?.weeklyRemainingPct : p?.remainingPct)) + .map((p) => (isWeekly ? readPoolWeeklyRemainingPct(p) : p?.remainingPct)) .filter((v) => v != null && Number.isFinite(Number(v))) .map(Number); if (familyVals.length > 0) { @@ -767,7 +810,7 @@ function resolveCapsuleQuotaSlotPct(quotas, slotKey) { activePool && !isThirdPartyPoolText(activePool.family || activePool.poolLabel || '') ) { - const fb = isWeekly ? activePool.weeklyRemainingPct : activePool.remainingPct; + const fb = isWeekly ? readPoolWeeklyRemainingPct(activePool) : activePool.remainingPct; if (fb != null && Number.isFinite(Number(fb))) rawPct = Number(fb); } if ( @@ -836,7 +879,7 @@ function scaleBucketsExact(buckets, keys, targetTotal) { } return out; } -return { THIRD_PARTY_POOL_RE, isThirdPartyPoolText, classifySpeedTier, classifyCacheTier, classifyStepCostTier, classifyTtftTier, formatCompactTokens, formatCompactCapsuleCost, formatCompactCapsuleTtft, resolveCapsuleQuotaSlotPct, scaleBucketsExact }; +return { THIRD_PARTY_POOL_RE, isThirdPartyPoolText, classifySpeedTier, classifyCacheTier, classifyStepCostTier, classifyTtftTier, formatCompactTokens, formatCompactCapsuleCost, formatCompactCapsuleTtft, hasArgonWeeklyQuotaPool, resolveCapsuleQuotaSlotPct, scaleBucketsExact }; })(); // --- shared/window-bridge-protocol.mjs --- @@ -1333,6 +1376,7 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'capMetric.quota_auto': '自动紧俏额度', 'capMetric.gemini_5h': 'Gemini 5h 额度', 'capMetric.gemini_weekly': 'Gemini 周额度', + 'capMetric.argon_weekly': 'Argon 周额度', 'capMetric.claude_5h': 'Claude 5h 额度', 'capMetric.claude_weekly': 'Claude 周额度', @@ -1395,6 +1439,8 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'quota.usedAfterReserved': ' · 余 {rem}%)', 'quota.reservedTip': '预占估算(试验性):约 {rsv}%(实际已用约 {actual}%),静默约 10 分钟后未用差额自动退还', 'quota.reservedTipMulti': '预占估算(试验性):约 {rsv}%(检测到 {leases} 笔叠加租约,实际已用约 {actual}%),静默约 10 分钟后未用差额自动退还', + 'quota.legendActual': '实占', + 'quota.legendReserved': '预占', 'quota.cycle5hTitle': '当前 5h 周期累计 ({pool}):{tok} Tokens · {cost} · {calls} 次调用', 'quota.cycleWkCustomTitle': '本周自然周累计:{tok} Tokens · {cost} · {calls} 次调用', 'quota.cycleWkPoolTitle': '当前周限周期累计 ({pool}):{tok} Tokens · {cost} · {calls} 次调用', @@ -1899,7 +1945,7 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.oth.quotaReserveLabel': '配额预占估算', 'settings.oth.quotaReserveDesc': '在可用额度中估算 5h / 周限的 0.5% / 1% 租约预占,并用紫色标注占比及进度条段', 'settings.oth.quotaReserveLogLabel': '预占观测日志', - 'settings.oth.quotaReserveLogDesc': '将内存中的配额跳变及退还记录复制到剪贴板,便于分析触发阈值', + 'settings.oth.quotaReserveLogDesc': '将配额跳变及退还观测记录复制到剪贴板,重启后自动保留,便于分析触发阈值', 'settings.oth.exportReserveLogBtn': '导出预占日志', 'settings.oth.exportReserveLogCopied': '已复制 {count} 条观测日志到剪贴板', 'settings.oth.exportReserveLogEmpty': '暂无跳变记录,已复制当前摘要到剪贴板', @@ -1939,7 +1985,7 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.oth.resettingBtn': '重置中…', 'settings.oth.resetAllDone': '已恢复全部默认设置', 'settings.oth.backupLabel': '配置备份及恢复', - 'settings.oth.backupDesc': '导出或导入外观、胶囊、列配置等便携偏好 JSON(不含账号凭证)', + 'settings.oth.backupDesc': '导出或导入外观、胶囊、列配置等便携偏好 JSON', 'settings.oth.exportJsonBtn': '导出 JSON', 'settings.oth.importJsonBtn': '导入 JSON', 'settings.oth.exportDone': '配置 JSON 已导出', @@ -1953,7 +1999,7 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.oth.migModeLabel': '迁移方式', 'settings.oth.migModeMove': '完整迁移(推荐)', 'settings.oth.migModeClone': '克隆副本', - 'settings.oth.migModeMoveHint': '分配目标端独立会话 ID 并完整保留全部历史步序明细,备份后移出源端(零重复计费;迁移前建议先关闭源端该会话)', + 'settings.oth.migModeMoveHint': '分配目标端独立会话 ID 并完整保留全部历史步序明细,备份后移出源端', 'settings.oth.migModeCloneHint': '保留源会话并生成新 ID,新副本仅统计迁入后的新步骤', 'settings.oth.migProjectLabel': '绑定目标项目', 'settings.oth.migProjectOutside': '独立会话(无所属项目)', @@ -2208,6 +2254,7 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'capMetric.quota_auto': 'Auto Tightest Quota', 'capMetric.gemini_5h': 'Gemini 5h Quota', 'capMetric.gemini_weekly': 'Gemini Weekly Quota', + 'capMetric.argon_weekly': 'Argon Weekly Quota', 'capMetric.claude_5h': 'Claude 5h Quota', 'capMetric.claude_weekly': 'Claude Weekly Quota', @@ -2270,6 +2317,8 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'quota.usedAfterReserved': ' · {rem}% left)', 'quota.reservedTip': 'Estimated lease reservation (Experimental): ~{rsv}% (~{actual}% actual used); unused share refunds after ~10 min idle', 'quota.reservedTipMulti': 'Estimated lease reservation (Experimental): ~{rsv}% ({leases} stacked leases, ~{actual}% actual used); unused share refunds after ~10 min idle', + 'quota.legendActual': 'Actual', + 'quota.legendReserved': 'Reserved', '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', @@ -2774,7 +2823,7 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'settings.oth.quotaReserveLabel': 'Quota Reservation Estimate', 'settings.oth.quotaReserveDesc': 'Estimate 0.5% / 1% 5h & weekly lease holds in Available Quotas and highlight the reserved share in violet', 'settings.oth.quotaReserveLogLabel': 'Reservation Observation Log', - 'settings.oth.quotaReserveLogDesc': 'Copy in-memory quota jump & refund events to clipboard for threshold tuning', + 'settings.oth.quotaReserveLogDesc': 'Copy persisted quota jump & refund observations to clipboard (retained across restarts)', 'settings.oth.exportReserveLogBtn': 'Export Reserve Log', 'settings.oth.exportReserveLogCopied': 'Copied {count} log entries to clipboard', 'settings.oth.exportReserveLogEmpty': 'No events yet; copied current summary to clipboard', @@ -2814,7 +2863,7 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'settings.oth.resettingBtn': 'Resetting…', 'settings.oth.resetAllDone': 'All preferences restored to defaults', 'settings.oth.backupLabel': 'Preferences Backup & Restore', - 'settings.oth.backupDesc': 'Export or import portable UI, capsule, and table preferences as JSON (excludes credentials)', + 'settings.oth.backupDesc': 'Export or import portable UI, capsule, and table preferences as JSON', 'settings.oth.exportJsonBtn': 'Export JSON', 'settings.oth.importJsonBtn': 'Import JSON', 'settings.oth.exportDone': 'Preferences JSON exported', @@ -2828,7 +2877,7 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'settings.oth.migModeLabel': 'Migration Mode', 'settings.oth.migModeMove': 'Full Move (Recommended)', 'settings.oth.migModeClone': 'Clone Copy', - 'settings.oth.migModeMoveHint': 'Assigns an isolated target ID while preserving all historical steps/details; archives source backup before moving (close source session first)', + 'settings.oth.migModeMoveHint': 'Assigns an isolated target ID while preserving all historical steps/details; archives source backup before moving', 'settings.oth.migModeCloneHint': 'Keeps source intact with a fresh UUID; only counts new steps generated after cloning', 'settings.oth.migProjectLabel': 'Target Project', 'settings.oth.migProjectOutside': 'Standalone (No Project)', @@ -9660,7 +9709,9 @@ function isEquivalentTelemetry(prev, next) { prev.account?.email !== next.account?.email || prev.account?.name !== next.account?.name || prev.account?.status !== next.account?.status || + prev.account?.tierId !== next.account?.tierId || prev.account?.tierName !== next.account?.tierName || + prev.account?.tierMultiplier !== next.account?.tierMultiplier || prev.account?.planName !== next.account?.planName || prev.account?.aiCredits !== next.account?.aiCredits ) { @@ -13349,16 +13400,7 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { linePath.setAttribute('fill', 'none'); svg.appendChild(linePath); - const dotsGroup = document.createElementNS(SVG_NS, 'g'); - dotsGroup.setAttribute('class', 'trend-dots-group'); - svg.appendChild(dotsGroup); - - const peakDot = document.createElementNS(SVG_NS, 'circle'); - peakDot.setAttribute('r', '3'); - peakDot.setAttribute('class', 'trend-peak-dot'); - svg.appendChild(peakDot); - - // 悬停十字准星与焦点圆点 + // 悬停十字准星及焦点圆点 const hoverLine = document.createElementNS(SVG_NS, 'line'); hoverLine.setAttribute('class', 'trend-hover-line'); hoverLine.setAttribute('y1', '12'); @@ -14197,25 +14239,9 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) { xAxisEl.appendChild(tickEl); tickElsByIdx.set(tIdx, tickEl); } - - // 渲染采样点小圆点(当点数 <= 36 时展示,突出有消耗的整点/日期) - while (dotsGroup.firstChild) dotsGroup.removeChild(dotsGroup.firstChild); - if (pts.length <= 36) { - for (let i = 0; i < pts.length; i++) { - if (pts[i].tokens <= 0) continue; - const dot = document.createElementNS(SVG_NS, 'circle'); - dot.setAttribute('cx', pts[i].x.toFixed(1)); - dot.setAttribute('cy', pts[i].y.toFixed(1)); - dot.setAttribute('r', '2'); - dot.setAttribute('class', 'trend-node-dot'); - dotsGroup.appendChild(dot); - } - } } const peakPt = pts[peakIdx] || { x: viewW / 2, y: BOTTOM_Y }; - patchAttr(peakDot, 'cx', peakPt.x.toFixed(1)); - patchAttr(peakDot, 'cy', peakPt.y.toFixed(1)); const peakSlot = slots[peakIdx]; const peakText = @@ -15542,16 +15568,15 @@ function createSessionLineChart() { patchStyleVar(mLine, '--sstep-fit-accent', seriesColor); multiLineGroup.appendChild(mLine); - if (seriesPts.length <= 36) { - for (const pt of seriesPts) { - const dot = document.createElementNS(SVG_NS, 'circle'); - dot.setAttribute('cx', pt.x.toFixed(1)); - dot.setAttribute('cy', pt.y.toFixed(1)); - dot.setAttribute('r', seriesPts.length > 20 ? '1.7' : '2.1'); - dot.setAttribute('class', 'sstep-node-dot'); - patchStyleVar(dot, '--dot-stroke', seriesColor); - dotsGroup.appendChild(dot); - } + if (seriesPts.length === 1) { + const pt = seriesPts[0]; + const dot = document.createElementNS(SVG_NS, 'circle'); + dot.setAttribute('cx', pt.x.toFixed(1)); + dot.setAttribute('cy', pt.y.toFixed(1)); + dot.setAttribute('r', '2.1'); + dot.setAttribute('class', 'sstep-node-dot'); + patchStyleVar(dot, '--dot-stroke', seriesColor); + dotsGroup.appendChild(dot); } } } @@ -15575,40 +15600,30 @@ function createSessionLineChart() { patchAttr(linePath, 'd', lineD); patchAttr(areaPath, 'd', `${lineD} L ${lastX} ${BOTTOM_Y} L ${firstX} ${BOTTOM_Y} Z`); } - - if (points.length <= 64) { - for (const pt of points) { - const dot = document.createElementNS(SVG_NS, 'circle'); - dot.setAttribute('cx', pt.x.toFixed(1)); - dot.setAttribute('cy', pt.y.toFixed(1)); - if (pt.valid) { - dot.setAttribute('r', points.length > 36 ? '1.8' : '2.3'); - dot.setAttribute('class', 'sstep-node-dot'); - patchStyleVar( - dot, - '--dot-stroke', - modelColorMap.size > 1 ? pt.dotColor : accentColor - ); - } else { - dot.setAttribute('r', '1.6'); - dot.setAttribute('class', 'sstep-node-dot is-skipped'); - } - dotsGroup.appendChild(dot); - } - } } + const anomalyTicks = []; for (const pt of points) { if (!pt.valid || !pt.anomalySummary) continue; - const aDot = document.createElementNS(SVG_NS, 'circle'); - aDot.setAttribute('cx', pt.x.toFixed(1)); - aDot.setAttribute('cy', pt.y.toFixed(1)); - aDot.setAttribute('r', '2.9'); - aDot.setAttribute( + anomalyTicks.push(pt); + } + anomalyTicks.sort((a, b) => + a.anomalySeverity === 'danger' ? 1 : b.anomalySeverity === 'danger' ? -1 : 0 + ); + const tickTopY = (BOTTOM_Y - 5).toFixed(1); + const tickBotY = BOTTOM_Y.toFixed(1); + for (const pt of anomalyTicks) { + const xStr = pt.x.toFixed(1); + const aTick = document.createElementNS(SVG_NS, 'line'); + aTick.setAttribute('x1', xStr); + aTick.setAttribute('x2', xStr); + aTick.setAttribute('y1', tickTopY); + aTick.setAttribute('y2', tickBotY); + aTick.setAttribute( 'class', - `sstep-anomaly-dot${pt.anomalySeverity === 'danger' ? ' is-danger' : ''}` + `sstep-anomaly-dot sstep-anomaly-tick${pt.anomalySeverity === 'danger' ? ' is-danger' : ''}` ); - anomalyDotsGroup.appendChild(aDot); + anomalyDotsGroup.appendChild(aTick); } const tickIndices = computeStepTickIndices(points.length); @@ -16519,11 +16534,14 @@ function createModelFitChart() { multiCurveGroup.appendChild(curveEl); } } + anomalyOverlayDots.sort((a, b) => + a.anomalySeverity === 'danger' ? 1 : b.anomalySeverity === 'danger' ? -1 : 0 + ); for (const sp of anomalyOverlayDots) { const aDot = document.createElementNS(SVG_NS, 'circle'); aDot.setAttribute('cx', sp.x.toFixed(1)); aDot.setAttribute('cy', sp.rawY.toFixed(1)); - aDot.setAttribute('r', '2.9'); + aDot.setAttribute('r', dotRadius); aDot.setAttribute( 'class', `sstep-scatter-dot is-anomaly${sp.anomalySeverity === 'danger' ? ' is-danger' : ''}` @@ -16693,11 +16711,14 @@ function createModelFitChart() { dot.setAttribute('class', 'sstep-scatter-dot'); scatterTarget.appendChild(dot); } + singleAnomalyDots.sort((a, b) => + a.anomalySeverity === 'danger' ? 1 : b.anomalySeverity === 'danger' ? -1 : 0 + ); for (const s of singleAnomalyDots) { const aDot = document.createElementNS(SVG_NS, 'circle'); aDot.setAttribute('cx', s.x.toFixed(1)); aDot.setAttribute('cy', s.rawY.toFixed(1)); - aDot.setAttribute('r', '2.9'); + aDot.setAttribute('r', dotRadius); aDot.setAttribute( 'class', `sstep-scatter-dot is-anomaly${s.anomalySeverity === 'danger' ? ' is-danger' : ''}` @@ -16803,11 +16824,16 @@ const { CAPSULE_METRIC_KEYS, getCapsuleMetricOptions, getOverviewMetricOptions, const CAPSULE_METRIC_KEYS = TOPBAR_SLOT_KEYS; -function getCapsuleMetricOptions() { - return CAPSULE_METRIC_KEYS.map((key) => ({ - value: key, - label: t(`capMetric.${key}`), - })); +function getCapsuleMetricOptions({ quotas = null, selectedSlots = [] } = {}) { + const showArgonWeekly = + hasArgonWeeklyQuotaPool(quotas) || + (Array.isArray(selectedSlots) && selectedSlots.includes('argon_weekly')); + return CAPSULE_METRIC_KEYS.filter((key) => key !== 'argon_weekly' || showArgonWeekly).map( + (key) => ({ + value: key, + label: t(`capMetric.${key}`), + }) + ); } function getOverviewMetricOptions() { @@ -16870,17 +16896,21 @@ function resolveQuotaCapsuleSummary(quotas) { : `${tightest.label} ${tightest.windowTag} · ${runnerUp.label} ${runnerUp.windowTag} ${runnerPct}%` : `${tightest.label} · ${tightest.windowTag}`; const tightestIsClaude = /claude|gpt|fable|oss|third/i.test(String(tightest.label || '')); - const tightestIsGemini = !tightestIsClaude && /gemini|argon|carbon|neon|flash|pro/i.test(String(tightest.label || '')); + const tightestIsArgon = !tightestIsClaude && /\bargon\b/i.test(String(tightest.label || '')); + const tightestIsGemini = + !tightestIsClaude && !tightestIsArgon && /gemini|carbon|neon|flash|pro/i.test(String(tightest.label || '')); const tightestWinShort = tightest.windowTag === '5h' ? '5h' : isEnglishLocale() ? 'w' : '周'; const poolPrefix = tightestIsClaude ? `C${tightestWinShort}` - : tightestIsGemini - ? `G${tightestWinShort}` - : tightest.windowTag === '5h' - ? '5h' - : isEnglishLocale() - ? 'Wk' - : '周'; + : tightestIsArgon + ? `A${tightestWinShort}` + : tightestIsGemini + ? `G${tightestWinShort}` + : tightest.windowTag === '5h' + ? '5h' + : isEnglishLocale() + ? 'Wk' + : '周'; return { roundedPct: rounded, shortText: t('capsule.quotaLeft', { pct: rounded }), @@ -16899,6 +16929,7 @@ function resolveQuotaCapsulePrefix(metricKey, quotaSum) { const isEn = isEnglishLocale(); if (metricKey === 'gemini_5h') return 'G5h'; if (metricKey === 'gemini_weekly') return isEn ? 'Gw' : 'G周'; + if (metricKey === 'argon_weekly') return isEn ? 'Aw' : 'A周'; if (metricKey === 'claude_5h') return 'C5h'; if (metricKey === 'claude_weekly') return isEn ? 'Cw' : 'C周'; if (quotaSum?.poolPrefix) return quotaSum.poolPrefix; @@ -17119,6 +17150,22 @@ function resolveCapsuleMetricPresentation(metricKey, slotCtx, ringCircumference) }; } + if (metricKey === 'argon_weekly' && slotCtx.hasTelemetry && !hasArgonWeeklyQuotaPool(slotCtx.quotas)) { + return { + hidden: true, + metric: 'none', + segClass: 'wm-cap-slot', + textClass: 'wm-slot-text', + showRing: false, + dashOffset: ringCircumference, + text: '', + toneClass: '', + running: false, + warn: false, + danger: false, + }; + } + const quotaSum = !slotCtx.hasTelemetry ? null : metricKey === 'quota_auto' @@ -18092,7 +18139,7 @@ return { CTX_CHANNEL_DEFS, ContextWindowWidget }; })(); // --- src/components/widgets/QuotaPoolsWidget.js --- -const { buildQuotaPoolItems, createPoolQuotaRow, formatQuotaSummaryFooter, syncPoolQuotaRow, quotaPoolRowSig, QuotaPoolsWidget } = (() => { +const { buildQuotaPoolItems, createPoolQuotaRow, formatQuotaSummaryFooter, syncPoolQuotaRow, quotaPoolRowSig, formatAccountTierBadge, QuotaPoolsWidget } = (() => { /** * @fileoverview Standalone decoupled Quota Pools Widget (`QuotaPoolsWidget.js`). * Renders dynamic multi-pool quota bars (Gemini, Argon/Carbon, Claude & GPT) @@ -18293,7 +18340,7 @@ function syncQuotaWindowMeter({ const rsvWidth = +Math.min(Math.max(0, 100 - actualWidth), rsvVal).toFixed(2); patchStyleVar(fillEl, '--fill-w', `${actualWidth}%`); patchStyleVar(fillReservedEl, '--reserved-w', `${rsvWidth}%`); - patchClasses(fillReservedEl, { 'is-active': true }); + patchClasses(fillReservedEl, { 'is-active': true, 'has-sep': actualWidth > 0 }); } else { patchText( metaBeforeEl, @@ -18313,7 +18360,7 @@ function syncQuotaWindowMeter({ patchAttr(trackEl, 'title', null); patchStyleVar(fillEl, '--fill-w', `${Math.min(100, usedVal)}%`); patchStyleVar(fillReservedEl, '--reserved-w', '0%'); - patchClasses(fillReservedEl, { 'is-active': false }); + patchClasses(fillReservedEl, { 'is-active': false, 'has-sep': false }); } patchClasses(fillEl, { @@ -18453,6 +18500,45 @@ function quotaPoolRowSig(item, idx) { 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}`; } +/** + * 格式化可用额度面板右上角的账号订阅徽章(区分 Ultra 5x / 20x,并对 Pro / Free 去重)。 + * + * @param {object|null|undefined} account + * @returns {string} + */ +function formatAccountTierBadge(account) { + const tierName = String(account?.tierName || '').trim() || 'Google AI'; + const tierId = String(account?.tierId || '').trim().toLowerCase(); + const explicitMult = String(account?.tierMultiplier || '').trim(); + const inferredMult = + explicitMult || + (/(?:^|[-_\s])5x(?:$|[-_\s])|ultra[-_]?lite/i.test(`${tierId} ${tierName}`) + ? '5x' + : /(?:^|[-_\s])20x(?:$|[-_\s])/i.test(`${tierId} ${tierName}`) || tierId === 'g1-ultra-tier' + ? '20x' + : ''); + const rawPlan = String(account?.planName || '').trim(); + const isUltra = /\bultra\b/i.test(tierName) || /ultra/i.test(tierId); + + if (isUltra) { + if (inferredMult) { + const hasMultInTier = new RegExp(`(?:^|\\s|·)${inferredMult}(?:$|\\s)`, 'i').test(tierName); + return hasMultInTier ? tierName : `${tierName} · ${inferredMult}`; + } + if (rawPlan && !/^(?:pro|ultra)$/i.test(rawPlan)) { + return `${tierName} · ${rawPlan}`; + } + return tierName; + } + + if (!rawPlan) return tierName; + const escapedPlan = rawPlan.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + if (new RegExp(`(?:^|\\s|·)${escapedPlan}(?:$|\\s)`, 'i').test(tierName)) { + return tierName; + } + return `${tierName} · ${rawPlan}`; +} + const QuotaPoolsWidget = defineComponent({ name: 'QuotaPoolsWidget', setup({ props }) { @@ -18475,6 +18561,23 @@ const QuotaPoolsWidget = defineComponent({ }); } + const legendActualTextEl = h('span', { text: t('quota.legendActual') }); + const legendReservedTextEl = h('span', { text: t('quota.legendReserved') }); + const reserveLegendEl = h( + 'div', + { className: 'quota-reserve-legend', hidden: true }, + [ + h('span', { className: 'quota-legend-item' }, [ + h('span', { className: 'quota-legend-line is-actual', 'aria-hidden': 'true' }), + legendActualTextEl, + ]), + h('span', { className: 'quota-legend-item' }, [ + h('span', { className: 'quota-legend-line is-reserved', 'aria-hidden': 'true' }), + legendReservedTextEl, + ]), + ] + ); + const quotaPanel = h('section', { className: 'panel' }, [ h('div', { className: 'panel-header' }, [ h('span', { className: 'panel-title' }, [ @@ -18484,11 +18587,15 @@ const QuotaPoolsWidget = defineComponent({ tierBadge, ]), poolsListEl, + reserveLegendEl, ]); function update({ data, minuteTick } = {}) { patchText(titleTextEl, t('module.quotas')); + patchText(legendActualTextEl, t('quota.legendActual')); + patchText(legendReservedTextEl, t('quota.legendReserved')); if (!data) { + reserveLegendEl.hidden = true; if (compactHover) { patchKeyedList(poolsListEl, buildQuotaPoolItems(null, 0, { isPending: true }), { keyFn: (item) => item.key, @@ -18502,11 +18609,9 @@ const QuotaPoolsWidget = defineComponent({ const quotas = data.quotas || {}; const showReserved = data.settings?.experimentalQuotaReservation === true; + reserveLegendEl.hidden = !showReserved; const effTick = Number.isFinite(minuteTick) ? minuteTick : Math.floor(Date.now() / 30000); - patchText( - tierBadge, - `${data.account?.tierName || 'Google AI'} · ${data.account?.planName || 'Pro'}` - ); + patchText(tierBadge, formatAccountTierBadge(data.account)); patchKeyedList(poolsListEl, buildQuotaPoolItems(quotas, effTick, { showReserved }), { keyFn: (item) => item.key, sigFn: quotaPoolRowSig, @@ -18521,7 +18626,7 @@ const QuotaPoolsWidget = defineComponent({ }; }, }); -return { buildQuotaPoolItems, createPoolQuotaRow, formatQuotaSummaryFooter, syncPoolQuotaRow, quotaPoolRowSig, QuotaPoolsWidget }; +return { buildQuotaPoolItems, createPoolQuotaRow, formatQuotaSummaryFooter, syncPoolQuotaRow, quotaPoolRowSig, formatAccountTierBadge, QuotaPoolsWidget }; })(); // --- src/components/widgets/LiveActivityWidget.js --- @@ -22453,7 +22558,11 @@ const { buildStructurePreviewTelemetry } = (() => { */ -function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides = {}) { +function buildStructurePreviewTelemetry( + baseSettings = {}, + draftOverrides = {}, + { includeArgonPool = false } = {} +) { const anchorMinMs = Math.floor(Date.now() / 60000) * 60000; const reset5hIso = new Date(anchorMinMs + (2 * 60 + 42) * 60000).toISOString(); const resetWkIso = new Date(anchorMinMs + (4 * 24 * 60 + 180) * 60000).toISOString(); @@ -22807,8 +22916,10 @@ function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides = {}) return { settings: mergedSettings, account: { + tierId: 'g1-ultra-lite-tier', tierName: 'Google AI Ultra', - planName: 'Pro', + tierMultiplier: '5x', + planName: '5x', aiCredits: 0, }, quotas: { @@ -22846,6 +22957,21 @@ function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides = {}) cycle5h: { tokens: 1754800, costUsd: 1.28, calls: 24 }, cycleWeekly: { tokens: 14200000, costUsd: 11.4, calls: 186 }, }, + ...(includeArgonPool + ? [ + { + poolKey: 'Argon', + poolLabel: 'Gemini 4 Argon', + family: 'Argon', + has5h: false, + hasWeekly: true, + weeklyUsedPct: 58, + weeklyRemainingPct: 42, + weeklyResetTime: resetWkIso, + cycleWeekly: { tokens: 4200000, costUsd: 6.4, calls: 48 }, + }, + ] + : []), { poolKey: 'Claude & GPT', poolLabel: 'Claude & GPT', @@ -25439,6 +25565,15 @@ function formatCliPreviewSlot(slotKey, slotCtx, isEn) { pillPct: pct, }; } + case 'argon_weekly': { + const pct = quotaPct('argon_weekly', 42); + return { + prefix: isEn ? 'Aw ' : 'A周 ', + text: `${pct}%`, + tone: 'good', + pillPct: pct, + }; + } case 'claude_5h': { const pct = quotaPct('claude_5h', 32); return { @@ -25498,6 +25633,7 @@ const SettingsStructureTab = defineComponent({ let latestWindowBridge = null; let latestCliStatusLine = null; let latestHostPlatform = 'win32'; + let latestQuotas = null; function getEffectiveDraftCliSlots() { return resolveEffectiveClientCliStatusLineSlots({ @@ -25512,25 +25648,34 @@ const SettingsStructureTab = defineComponent({ } function buildDraftTelemetry() { - return buildStructurePreviewTelemetry(latestSettings, { - windowMountMode: draftWindowMountMode, - enableWindowOverlay: draftWindowMountMode !== 'sidebar', - popoverWidthMode: draftPopoverWidthMode, - popoverWidth: draftPopoverWidth, - enableCliStatusLine: draftEnableCliStatusLine, - showTopbarMultiSession: draftShowTopbarMulti, - contextAgentMode: draftContextAgentMode, - topbarCapsuleSlots: draftTopbarSlots, - hoverModules: draftHoverModules, - overviewModules: draftOverviewModules, - overviewMetrics: draftOverviewMetrics, - showStepTurnRail: draftShowStepTurnRail, - showStepAgentBadge: draftShowStepAgentBadge, - showStepSpeedColor: draftShowStepSpeedColor, - showStepFilterToolbar: draftShowStepFilterToolbar, - stepTokenComboFormat: draftStepTokenComboFormat, - stepTableColumns: draftStepColumns, - }); + const effectiveCliSlots = getEffectiveDraftCliSlots(); + const includeArgonPool = + hasArgonWeeklyQuotaPool(latestQuotas) || + draftTopbarSlots.includes('argon_weekly') || + effectiveCliSlots.includes('argon_weekly'); + return buildStructurePreviewTelemetry( + latestSettings, + { + windowMountMode: draftWindowMountMode, + enableWindowOverlay: draftWindowMountMode !== 'sidebar', + popoverWidthMode: draftPopoverWidthMode, + popoverWidth: draftPopoverWidth, + enableCliStatusLine: draftEnableCliStatusLine, + showTopbarMultiSession: draftShowTopbarMulti, + contextAgentMode: draftContextAgentMode, + topbarCapsuleSlots: draftTopbarSlots, + hoverModules: draftHoverModules, + overviewModules: draftOverviewModules, + overviewMetrics: draftOverviewMetrics, + showStepTurnRail: draftShowStepTurnRail, + showStepAgentBadge: draftShowStepAgentBadge, + showStepSpeedColor: draftShowStepSpeedColor, + showStepFilterToolbar: draftShowStepFilterToolbar, + stepTokenComboFormat: draftStepTokenComboFormat, + stepTableColumns: draftStepColumns, + }, + { includeArgonPool } + ); } async function persistStructurePatch(sectionComp, patchObj, successKey = 'settings.saved') { @@ -26023,7 +26168,10 @@ const SettingsStructureTab = defineComponent({ const effectiveCliSlots = getEffectiveDraftCliSlots(); cliSlotsList.refs.setProps({ items: effectiveCliSlots, - options: getCapsuleMetricOptions(), + options: getCapsuleMetricOptions({ + quotas: latestQuotas, + selectedSlots: effectiveCliSlots, + }), addBtnTextFn: (count, max) => t('settings.str.addCliSlot', { count, max }), }); const preservedCustom = Boolean(latestCliStatusLine?.preservedCustom); @@ -26062,7 +26210,10 @@ const SettingsStructureTab = defineComponent({ refreshCliPreview(); topbarSlotsList.refs.setProps({ items: draftTopbarSlots, - options: getCapsuleMetricOptions(), + options: getCapsuleMetricOptions({ + quotas: latestQuotas, + selectedSlots: draftTopbarSlots, + }), addBtnTextFn: (count, max) => t('settings.str.addCapsuleSlot', { count, max }), }); mountSection.refs.setBadge( @@ -26674,13 +26825,15 @@ const SettingsStructureTab = defineComponent({ settings, windowBridge = latestWindowBridge, hostPlatform = latestHostPlatform, - cliStatusLine = latestCliStatusLine + cliStatusLine = latestCliStatusLine, + quotas = latestQuotas ) { if (!settings) return; latestSettings = settings; if (windowBridge !== undefined) latestWindowBridge = windowBridge; if (hostPlatform) latestHostPlatform = hostPlatform; if (cliStatusLine !== undefined) latestCliStatusLine = cliStatusLine; + if (quotas !== undefined) latestQuotas = quotas; draftWindowMountMode = normalizeClientWindowMountMode( settings.windowMountMode, settings.enableWindowOverlay @@ -32736,7 +32889,8 @@ const SettingsView = defineComponent({ settings, telemetry?.windowBridge, telemetry?.hostPlatform, - telemetry?.cliStatusLine + telemetry?.cliStatusLine, + telemetry?.quotas ); } } else if (settingsSubTab === 'other') { diff --git a/sidecars/panel/backend/cli-statusline-config.mjs b/sidecars/panel/backend/cli-statusline-config.mjs index 44f28c5..ebcc362 100644 --- a/sidecars/panel/backend/cli-statusline-config.mjs +++ b/sidecars/panel/backend/cli-statusline-config.mjs @@ -30,6 +30,7 @@ import { formatCompactCapsuleCost, formatCompactCapsuleTtft, formatCompactTokens, + hasArgonWeeklyQuotaPool, resolveCapsuleQuotaSlotPct, } from '../shared/telemetry-display-rules.mjs'; @@ -810,6 +811,7 @@ function cliBuildBarGauge(label, pct, { fillFg = SGR_FG_ACCENT, valFg = SGR_FG_B function cliResolveQuotaSlotPrefix(metricKey, isEn) { if (metricKey === 'gemini_5h') return 'G5h'; if (metricKey === 'gemini_weekly') return isEn ? 'Gw' : 'G周'; + if (metricKey === 'argon_weekly') return isEn ? 'Aw' : 'A周'; if (metricKey === 'claude_5h') return 'C5h'; if (metricKey === 'claude_weekly') return isEn ? 'Cw' : 'C周'; return isEn ? '5h' : '余'; @@ -1062,6 +1064,7 @@ const CLI_STATUS_SLOT_KEEP_PRIORITY = Object.freeze({ avg_tps: 45, session_tokens: 40, gemini_weekly: 35, + argon_weekly: 33, claude_weekly: 30, }); @@ -1163,8 +1166,14 @@ export function formatCliStatusLineCapsule(slotCtx = {}, options = {}) { // 新会话尚无任何完成步骤(stepCount === 0)时,隐藏纯占位性的 "--s" / "--" 槽位,避免刚启动显得满屏缺数据 let activeSlots = rawSlots; + if (slotCtx.hasTelemetry !== false && activeSlots.includes('argon_weekly') && !hasArgonWeeklyQuotaPool(slotCtx.quotas)) { + const withoutArgon = activeSlots.filter((key) => key !== 'argon_weekly'); + if (withoutArgon.length > 0) { + activeSlots = withoutArgon; + } + } if (slotCtx.stepCount === 0) { - const filtered = rawSlots.filter( + const filtered = activeSlots.filter( (key) => key === 'tps' || cliStatusHasRenderableValue(key, slotCtx) ); if (filtered.length > 0) { diff --git a/sidecars/panel/backend/config.mjs b/sidecars/panel/backend/config.mjs index 281f44b..d34275a 100644 --- a/sidecars/panel/backend/config.mjs +++ b/sidecars/panel/backend/config.mjs @@ -160,6 +160,7 @@ export const SETTINGS_FILE = join(DATA_DIR, 'settings.json'); export const CACHE_FILE = join(DATA_DIR, 'trajectory_usage_cache.json'); export const REMOTE_CATALOG_CACHE_FILE = join(DATA_DIR, 'remote_pricing_cache.json'); export const CLI_STATUS_SNAPSHOT_FILE = join(DATA_DIR, 'cli-status-snapshot.json'); +export const QUOTA_RESERVATION_STATE_FILE = join(DATA_DIR, 'quota_reservation_state.json'); /** * 本地对话记录目录、脑图日志目录、守护发现目录与跨端深层统计缓存路径候选列表(联合覆盖 Desktop / CLI / IDE)。 diff --git a/sidecars/panel/backend/quota-reservation.mjs b/sidecars/panel/backend/quota-reservation.mjs index b06a654..ff2a8c3 100644 --- a/sidecars/panel/backend/quota-reservation.mjs +++ b/sidecars/panel/backend/quota-reservation.mjs @@ -6,10 +6,16 @@ * 2. 多高消耗会话并发时支持多笔租约线性叠加(如 0.5% / 1.0% / 2.0%+); * 3. 在租约期内继续产生真实消耗时按单桶换算率扣减可退差额; * 4. 上游退还租约(同周期内 officialUsedPct 下降)时按 FIFO 精准核销并反向校准单桶费率; - * 5. 纯内存 O(1) 状态机,零额外 RPC、零额外磁盘写入。 + * 5. 轻量 O(1) 状态机 + DATA_DIR 节流持久化(保留最近 500 条事件,重启及热更新后自动恢复)。 */ import { parseIsoMs } from '../trajectory-metrics.mjs'; +import { + QUOTA_RESERVATION_STATE_FILE, + loadJson, + lsRuntimeEndpoint, + saveJson, +} from './config.mjs'; export const QR_LEASE_TTL_MS = 10 * 60 * 1000; export const QR_LEASE_GRACE_MS = 90 * 1000; @@ -22,9 +28,21 @@ export const QR_COLD_START_JUMP_PCT = 0.45; export const QR_COLD_START_MAX_COST_USD = 0.25; export const QR_REFUND_EPSILON_PCT = 0.04; export const QR_MIN_DISPLAY_RESERVED_PCT = 0.05; +export const QR_IDLE_CONFIRM_REFUND_MS = 5 * 60 * 1000; +export const QR_REFUND_CONFIRM_WINDOW_MS = 90 * 1000; +export const QR_REFUND_CONFIRM_MIN_SAMPLES = 3; +export const QR_RATE_BOUNCE_COOLDOWN_MS = 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; +export const QR_RATE_DRIFT_STREAK = 5; +export const QR_CONSUME_MIN_SHORTFALL_PCT = 0.03; +export const QR_CONSUME_SHORTFALL_RATIO = 0.35; const QR_MAX_TRACKED_BUCKETS = 128; const QR_MAX_ACTIVE_LEASES = 16; const QR_MAX_EVENT_LOG = 500; +const QR_PERSIST_MIN_INTERVAL_MS = 5000; +const QR_STATE_SCHEMA_VERSION = 2; function qrClamp(val, min, max) { return Math.max(min, Math.min(max, val)); @@ -79,18 +97,52 @@ function qrConsumeLeasesFifo(leases, amountPct) { return consumed; } -function qrUpdateRateEma(state, sampleRate) { +function qrComputeMedian(values) { + if (!Array.isArray(values) || values.length === 0) return null; + const sorted = values.slice().sort((a, b) => a - b); + const mid = sorted.length >> 1; + return sorted.length % 2 === 1 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2; +} + +function qrRecordRateSample(state, sampleRate) { const clamped = qrClampRate(sampleRate); - if (clamped === null) return; - if (state.ratePctPerUsd !== null && state.rateSamples >= 3) { - const bounded = qrClamp(clamped, state.ratePctPerUsd * 0.25, state.ratePctPerUsd * 4); - state.ratePctPerUsd = state.ratePctPerUsd * 0.8 + bounded * 0.2; - } else if (state.ratePctPerUsd !== null) { - state.ratePctPerUsd = state.ratePctPerUsd * 0.55 + clamped * 0.45; - } else { - state.ratePctPerUsd = clamped; + if (clamped === null) return false; + const win = Array.isArray(state.rateWindow) ? state.rateWindow : (state.rateWindow = []); + + if (win.length >= 4) { + const med = qrComputeMedian(win); + const lowBound = med * QR_RATE_OUTLIER_MIN_RATIO; + const highBound = med * QR_RATE_OUTLIER_MAX_RATIO; + if (clamped < lowBound || clamped > highBound) { + const side = clamped > highBound ? 1 : -1; + if (state.rateOutlierSide !== side) { + state.rateOutlierSide = side; + state.rateOutlierBuf = [clamped]; + } else { + state.rateOutlierBuf.push(clamped); + } + if (state.rateOutlierBuf.length >= QR_RATE_DRIFT_STREAK) { + // 连续多次干净同向偏移(如账号套餐倍率变化),重置中位数窗口 + state.rateWindow = state.rateOutlierBuf.slice(-QR_RATE_WINDOW_SIZE); + state.rateOutlierSide = 0; + state.rateOutlierBuf = []; + state.ratePctPerUsd = qrClampRate(qrComputeMedian(state.rateWindow)); + state.rateSamples += 1; + return true; + } + return false; + } } + + state.rateOutlierSide = 0; + state.rateOutlierBuf = []; + win.push(clamped); + if (win.length > QR_RATE_WINDOW_SIZE) { + win.splice(0, win.length - QR_RATE_WINDOW_SIZE); + } + state.ratePctPerUsd = qrClampRate(qrComputeMedian(win)); state.rateSamples += 1; + return true; } function qrResolveEffectiveRate(state, officialUsedPct, cycleCostUsd) { @@ -103,41 +155,35 @@ function qrResolveEffectiveRate(state, officialUsedPct, cycleCostUsd) { return null; } -function qrCalibrateFromSettled(state, officialUsedPct, cycleCostUsd, nowMs) { - if ( - state.lastSettledUsedPct !== null && - state.lastSettledCostUsd !== null && - cycleCostUsd > state.lastSettledCostUsd + 0.25 && - officialUsedPct > state.lastSettledUsedPct + 0.05 - ) { - const dUsed = officialUsedPct - state.lastSettledUsedPct; - const dCost = cycleCostUsd - state.lastSettledCostUsd; - qrUpdateRateEma(state, dUsed / dCost); - } - state.lastSettledUsedPct = officialUsedPct; - state.lastSettledCostUsd = cycleCostUsd; - state.lastSettledAtMs = nowMs; -} - -function qrPruneExpiredLeases(state, poolLastActivityMs, officialUsedPct, cycleCostUsd, nowMs) { +function qrPruneExpiredLeases(state, nowMs) { if (state.activeLeases.length === 0) return; - const beforeLen = state.activeLeases.length; for (let i = state.activeLeases.length - 1; i >= 0; i -= 1) { const lease = state.activeLeases[i]; - const lastActiveMs = Math.max(lease.lastTouchedMs || 0, poolLastActivityMs || 0); + const lastActiveMs = lease.lastTouchedMs || lease.createdAtMs || 0; const idleExpired = lastActiveMs > 0 && nowMs - lastActiveMs >= QR_LEASE_IDLE_EXPIRY_MS; const maxAgeExpired = nowMs - (lease.createdAtMs || 0) >= QR_LEASE_MAX_AGE_MS; if (idleExpired || maxAgeExpired) { state.activeLeases.splice(i, 1); } } - if (beforeLen > 0 && state.activeLeases.length === 0) { - qrCalibrateFromSettled(state, officialUsedPct, cycleCostUsd, nowMs); - } } function qrFormatOutput(state, officialUsedPct) { - const rawReserved = qrClamp(qrSumLeases(state.activeLeases), 0, officialUsedPct); + const rawSum = qrSumLeases(state.activeLeases); + let dropOffset = 0; + if (state.pendingDrop && Number.isFinite(state.pendingDrop.preDropUsedPct)) { + const costSinceDrop = Math.max( + 0, + Number(state.lastCycleCostUsd || 0) - Number(state.pendingDrop.preDropCostUsd || 0) + ); + const expectedSinceDrop = + state.ratePctPerUsd !== null && Number.isFinite(state.ratePctPerUsd) + ? costSinceDrop * state.ratePctPerUsd + : 0; + dropOffset = Math.max(0, state.pendingDrop.preDropUsedPct + expectedSinceDrop - officialUsedPct); + } + const visibleRaw = Math.max(0, rawSum - dropOffset); + const rawReserved = qrClamp(visibleRaw, 0, officialUsedPct); if (rawReserved < QR_MIN_DISPLAY_RESERVED_PCT) { return { reservedPct: 0, @@ -148,7 +194,9 @@ function qrFormatOutput(state, officialUsedPct) { const rounded = qrClamp(qrRound1(rawReserved), 0, qrRound1(officialUsedPct)); let earliestExpiresAtMs = null; for (let i = 0; i < state.activeLeases.length; i += 1) { - const exp = (state.activeLeases[i].lastTouchedMs || state.activeLeases[i].createdAtMs || 0) + QR_LEASE_TTL_MS; + const exp = + (state.activeLeases[i].lastTouchedMs || state.activeLeases[i].createdAtMs || 0) + + QR_LEASE_TTL_MS; if (exp > 0 && (earliestExpiresAtMs === null || exp < earliestExpiresAtMs)) { earliestExpiresAtMs = exp; } @@ -160,18 +208,189 @@ function qrFormatOutput(state, officialUsedPct) { }; } +function qrSanitizePersistedLeases(rawLeases) { + if (!Array.isArray(rawLeases)) return []; + const out = []; + for (let i = 0; i < rawLeases.length && out.length < QR_MAX_ACTIVE_LEASES; i += 1) { + const item = rawLeases[i]; + if (!item || typeof item !== 'object') continue; + const rem = Number(item.remainingPct); + const amt = Number(item.amountPct); + const createdAtMs = Number(item.createdAtMs) || 0; + const lastTouchedMs = Number(item.lastTouchedMs) || createdAtMs; + if (!Number.isFinite(rem) || rem <= 1e-4) continue; + out.push({ + amountPct: Number.isFinite(amt) && amt > 0 ? amt : rem, + remainingPct: rem, + createdAtMs, + lastTouchedMs, + sessionCount: Math.max(1, Number(item.sessionCount) || 1), + }); + } + return out; +} + +function qrSanitizePersistedPendingDrop(raw) { + if (!raw || typeof raw !== 'object') return null; + const preDropUsedPct = Number(raw.preDropUsedPct); + const lowestUsedPct = Number(raw.lowestUsedPct); + const dropPct = Number(raw.dropPct); + const droppedAtMs = Number(raw.droppedAtMs) || 0; + if (!Number.isFinite(preDropUsedPct) || !Number.isFinite(lowestUsedPct) || !Number.isFinite(dropPct) || dropPct <= 0 || droppedAtMs <= 0) { + return null; + } + return { + preDropUsedPct: qrClamp(preDropUsedPct, 0, 100), + preDropCostUsd: Math.max(0, Number(raw.preDropCostUsd) || 0), + dropPct: qrClamp(dropPct, 0, 100), + droppedAtMs, + lowSamples: Math.max(1, Math.floor(Number(raw.lowSamples) || 1)), + lowestUsedPct: qrClamp(lowestUsedPct, 0, 100), + }; +} + +function qrSanitizePersistedBucket(raw, { preserveRate = true } = {}) { + if (!raw || typeof raw !== 'object') return null; + const lastOfficial = + raw.lastOfficialUsedPct !== undefined && + raw.lastOfficialUsedPct !== null && + Number.isFinite(Number(raw.lastOfficialUsedPct)) + ? qrClamp(Number(raw.lastOfficialUsedPct), 0, 100) + : null; + const rateWindow = + preserveRate && Array.isArray(raw.rateWindow) + ? raw.rateWindow + .map((v) => qrClampRate(Number(v))) + .filter((v) => v !== null) + .slice(-QR_RATE_WINDOW_SIZE) + : []; + const rate = preserveRate + ? rateWindow.length > 0 + ? qrClampRate(qrComputeMedian(rateWindow)) + : raw.ratePctPerUsd !== undefined && raw.ratePctPerUsd !== null + ? qrClampRate(Number(raw.ratePctPerUsd)) + : null + : null; + return { + resetTimeMs: Math.max(0, Number(raw.resetTimeMs) || 0), + lastQuotaTs: Math.max(0, Number(raw.lastQuotaTs) || 0), + lastOfficialUsedPct: lastOfficial, + lastCycleCostUsd: Math.max(0, Number(raw.lastCycleCostUsd) || 0), + lastUnpricedCalls: Math.max(0, Number(raw.lastUnpricedCalls) || 0), + pendingCostUsd: 0, + pendingCostAtMs: 0, + ratePctPerUsd: rate, + rateSamples: preserveRate ? Math.max(rateWindow.length, Math.floor(Number(raw.rateSamples) || 0)) : 0, + rateWindow, + rateOutlierSide: 0, + rateOutlierBuf: [], + activeLeases: qrSanitizePersistedLeases(raw.activeLeases), + pendingDrop: preserveRate ? qrSanitizePersistedPendingDrop(raw.pendingDrop) : null, + lastBounceAtMs: Math.max(0, Number(raw.lastBounceAtMs) || 0), + lastRefundAtMs: Math.max(0, Number(raw.lastRefundAtMs) || 0), + lastRefundPct: Math.max(0, Number(raw.lastRefundPct) || 0), + }; +} + /** - * 创建独立的配额预占状态追踪器(支持单元测试隔离,同时后端提供全局默认实例)。 + * 创建独立的配额预占状态追踪器(支持可选持久化钩子及单元测试隔离)。 + * + * @param {{ loadState?: () => object|null, saveState?: (payload: object) => void }} [options] */ -export function createQuotaReservationTracker() { +export function createQuotaReservationTracker({ loadState = null, saveState = null } = {}) { const buckets = new Map(); const eventLog = []; + let hydrated = typeof loadState !== 'function'; + let lastPersistMs = 0; - function appendEventLog(entry) { + function ensureHydrated() { + if (hydrated) return; + hydrated = true; + try { + const persisted = loadState?.(); + if (!persisted || typeof persisted !== 'object') return; + const isCurrentSchema = Number(persisted.version) === QR_STATE_SCHEMA_VERSION; + if (persisted.buckets && typeof persisted.buckets === 'object') { + const entries = Object.entries(persisted.buckets).slice(-QR_MAX_TRACKED_BUCKETS); + for (const [k, rawSt] of entries) { + // 从 v1 升级到 v2 时丢弃旧版可能被双副本抖动污染的 EMA 费率,保留历史事件日志 + const clean = qrSanitizePersistedBucket(rawSt, { preserveRate: isCurrentSchema }); + if (k && clean) { + buckets.set(k, clean); + } + } + } + if (Array.isArray(persisted.events)) { + const recent = persisted.events + .filter((e) => e && typeof e === 'object' && typeof e.ts === 'string') + .slice(-QR_MAX_EVENT_LOG); + eventLog.push(...recent); + } + } catch { + // 忽略损坏的持久化状态,自动从空白基线重建 + } + } + + function serializeState(nowMs = Date.now()) { + const serializedBuckets = {}; + for (const [k, st] of buckets.entries()) { + serializedBuckets[k] = { + resetTimeMs: st.resetTimeMs, + lastQuotaTs: st.lastQuotaTs, + lastOfficialUsedPct: st.lastOfficialUsedPct, + lastCycleCostUsd: st.lastCycleCostUsd, + lastUnpricedCalls: st.lastUnpricedCalls, + ratePctPerUsd: st.ratePctPerUsd, + rateSamples: st.rateSamples, + rateWindow: st.rateWindow, + activeLeases: st.activeLeases, + pendingDrop: st.pendingDrop, + lastBounceAtMs: st.lastBounceAtMs, + lastRefundAtMs: st.lastRefundAtMs, + lastRefundPct: st.lastRefundPct, + }; + } + return { + version: QR_STATE_SCHEMA_VERSION, + savedAt: new Date(nowMs).toISOString(), + buckets: serializedBuckets, + events: eventLog.slice(-QR_MAX_EVENT_LOG), + }; + } + + function persistIfNeeded(eventKind, nowMs) { + if (typeof saveState !== 'function') return; + if ( + !eventKind || + eventKind === 'idle' || + eventKind === 'lag_pending' || + eventKind === 'drop_pending' || + eventKind === 'replica_flip' + ) { + return; + } + const isUrgent = + eventKind === 'lease' || + eventKind === 'refund' || + eventKind === 'reset' || + eventKind === 'expire'; + if (!isUrgent && lastPersistMs > 0 && nowMs - lastPersistMs < QR_PERSIST_MIN_INTERVAL_MS) { + return; + } + lastPersistMs = nowMs; + try { + saveState(serializeState(nowMs)); + } catch { + // 持久化失败不影响内存态主流程 + } + } + + function appendEventLog(entry, nowMs) { eventLog.push(entry); if (eventLog.length > QR_MAX_EVENT_LOG) { eventLog.splice(0, eventLog.length - QR_MAX_EVENT_LOG); } + persistIfNeeded(entry.event, nowMs); } function getOrCreateBucket(bucketKey) { @@ -195,10 +414,12 @@ export function createQuotaReservationTracker() { pendingCostAtMs: 0, ratePctPerUsd: null, rateSamples: 0, - lastSettledUsedPct: null, - lastSettledCostUsd: null, - lastSettledAtMs: 0, + rateWindow: [], + rateOutlierSide: 0, + rateOutlierBuf: [], activeLeases: [], + pendingDrop: null, + lastBounceAtMs: 0, lastRefundAtMs: 0, lastRefundPct: 0, }; @@ -223,6 +444,7 @@ export function createQuotaReservationTracker() { if (officialUsedPct === null || !Number.isFinite(officialUsedPct)) { return { reservedPct: 0, reservedLeaseCount: 0, reservedExpiresAtMs: null }; } + ensureHydrated(); const safeUsed = qrClamp(Number(officialUsedPct), 0, 100); const safeCost = Math.max(0, Number(cycleCostUsd) || 0); const safeUnpriced = Math.max(0, Number(unpricedCalls) || 0); @@ -236,26 +458,29 @@ export function createQuotaReservationTracker() { const st = getOrCreateBucket(bucketKey); const recordLog = (event, fields = {}) => { - appendEventLog({ - ts: new Date(nowMs).toISOString(), - pool: logPool, - win: logWin, - event, - usedPct: +safeUsed.toFixed(3), - dUsed: +(Number(fields.deltaOfficial) || 0).toFixed(3), - costUsd: +safeCost.toFixed(4), - dCost: +(Number(fields.rawDeltaCost) || 0).toFixed(4), - expPct: +(Number(fields.expectedDeltaPct) || 0).toFixed(3), - excessPct: +(Number(fields.excessPct) || 0).toFixed(3), - rate: st.ratePctPerUsd !== null ? +st.ratePctPerUsd.toFixed(4) : null, - rsvPct: Number(fields.reservedPct) || 0, - leases: Number(fields.reservedLeaseCount) || 0, - sess10m: safeSess10m, - cost10m: +safeCost10m.toFixed(4), - }); + appendEventLog( + { + ts: new Date(nowMs).toISOString(), + pool: logPool, + win: logWin, + event, + usedPct: +safeUsed.toFixed(3), + dUsed: +(Number(fields.deltaOfficial) || 0).toFixed(3), + costUsd: +safeCost.toFixed(4), + dCost: +(Number(fields.rawDeltaCost) || 0).toFixed(4), + expPct: +(Number(fields.expectedDeltaPct) || 0).toFixed(3), + excessPct: +(Number(fields.excessPct) || 0).toFixed(3), + rate: st.ratePctPerUsd !== null ? +st.ratePctPerUsd.toFixed(4) : null, + rsvPct: Number(fields.reservedPct) || 0, + leases: Number(fields.reservedLeaseCount) || 0, + sess10m: safeSess10m, + cost10m: +safeCost10m.toFixed(4), + }, + nowMs + ); }; - // 1. 周期重置检测:清空旧租约及待配对成本,保留已校准的单桶费率 + // 1. 周期重置检测:静默忽略 0% 空闲池的滑动重置时间漂移;真正跨周期时清空租约但保留单桶费率 const resetShifted = safeResetMs > 0 && st.resetTimeMs > 0 && @@ -264,23 +489,30 @@ export function createQuotaReservationTracker() { st.lastOfficialUsedPct !== null && st.lastOfficialUsedPct >= 5 && safeUsed < 1; if (resetShifted || rolloverDrop) { const prevUsed = st.lastOfficialUsedPct ?? 0; + const isIdleZeroDrift = + !rolloverDrop && + prevUsed < 0.05 && + safeUsed < 0.05 && + st.activeLeases.length === 0 && + st.pendingDrop === null; st.resetTimeMs = safeResetMs; st.lastQuotaTs = safeFetchTs; st.lastOfficialUsedPct = safeUsed; st.lastCycleCostUsd = safeCost; st.lastUnpricedCalls = safeUnpriced; + if (isIdleZeroDrift) { + return qrFormatOutput(st, safeUsed); + } st.pendingCostUsd = 0; st.pendingCostAtMs = 0; st.activeLeases = []; - st.lastSettledUsedPct = safeUsed; - st.lastSettledCostUsd = safeCost; - st.lastSettledAtMs = nowMs; + st.pendingDrop = null; 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; @@ -291,9 +523,6 @@ export function createQuotaReservationTracker() { st.ratePctPerUsd = qrClampRate(safeUsed / safeCost); st.rateSamples = 1; } - st.lastSettledUsedPct = safeUsed; - st.lastSettledCostUsd = safeCost; - st.lastSettledAtMs = nowMs; const out = qrFormatOutput(st, safeUsed); recordLog('baseline', out); return out; @@ -308,7 +537,7 @@ export function createQuotaReservationTracker() { safeFetchTs !== st.lastQuotaTs || Math.abs(safeUsed - st.lastOfficialUsedPct) > 1e-4; if (!isFreshSample) { const beforeCachePrune = st.activeLeases.length; - qrPruneExpiredLeases(st, poolLastActivityMs, safeUsed, safeCost, nowMs); + qrPruneExpiredLeases(st, nowMs); const out = qrFormatOutput(st, safeUsed); if (beforeCachePrune > st.activeLeases.length) { recordLog('expire', out); @@ -325,28 +554,136 @@ export function createQuotaReservationTracker() { const rate = qrResolveEffectiveRate(st, safeUsed, safeCost); const expectedDeltaPct = rate !== null ? effectiveDeltaCost * rate : 0; const excessPct = deltaOfficial - expectedDeltaPct; + const isIdleRefundReady = + poolLastActivityMs > 0 && nowMs - poolLastActivityMs >= QR_IDLE_CONFIRM_REFUND_MS; let eventKind = 'idle'; - if (deltaOfficial <= -QR_REFUND_EPSILON_PCT) { - // 4A. 同周期余额回升:上游租约到期退还差额(FIFO 核销 + 结算校准) - const refundedPct = -deltaOfficial; - qrConsumeLeasesFifo(st.activeLeases, refundedPct); + const confirmRefund = (refundedPct, { keepPendingCost = false } = {}) => { + const amt = Math.max(0, Number(refundedPct) || 0); + if (amt > 0) { + qrConsumeLeasesFifo(st.activeLeases, amt); + } st.lastRefundAtMs = nowMs; - st.lastRefundPct = refundedPct; - st.pendingCostUsd = 0; - st.pendingCostAtMs = 0; + st.lastRefundPct = amt; + st.lastBounceAtMs = nowMs; + st.pendingDrop = null; + if (!keepPendingCost) { + st.pendingCostUsd = 0; + st.pendingCostAtMs = 0; + } if (qrSumLeases(st.activeLeases) < QR_MIN_DISPLAY_RESERVED_PCT) { st.activeLeases = []; - qrCalibrateFromSettled(st, safeUsed, safeCost, nowMs); } eventKind = 'refund'; + }; + + if (deltaOfficial <= -QR_REFUND_EPSILON_PCT) { + // 4A. 同周期余额回升:区分「静默到期真退还」及「活跃期双副本回落待确认」 + const prevHigh = st.pendingDrop + ? Math.max(st.pendingDrop.preDropUsedPct, st.lastOfficialUsedPct) + : st.lastOfficialUsedPct; + const totalDrop = Math.max(0, prevHigh - safeUsed); + st.lastBounceAtMs = nowMs; + st.pendingCostUsd = 0; + st.pendingCostAtMs = 0; + + if (isIdleRefundReady && st.activeLeases.length > 0) { + confirmRefund(totalDrop); + } else if (st.pendingDrop) { + st.pendingDrop.preDropUsedPct = prevHigh; + st.pendingDrop.lowestUsedPct = Math.min(st.pendingDrop.lowestUsedPct, safeUsed); + st.pendingDrop.dropPct = Math.max(0, prevHigh - st.pendingDrop.lowestUsedPct); + st.pendingDrop.lowSamples += 1; + if ( + st.pendingDrop.lowSamples >= QR_REFUND_CONFIRM_MIN_SAMPLES && + nowMs - st.pendingDrop.droppedAtMs >= QR_REFUND_CONFIRM_WINDOW_MS + ) { + confirmRefund(st.pendingDrop.dropPct); + } else { + eventKind = 'drop_pending'; + } + } else { + st.pendingDrop = { + preDropUsedPct: st.lastOfficialUsedPct, + preDropCostUsd: st.lastCycleCostUsd, + dropPct: -deltaOfficial, + droppedAtMs: nowMs, + lowSamples: 1, + lowestUsedPct: safeUsed, + }; + eventKind = 'drop_pending'; + } + } else if (st.pendingDrop) { + // 4B-Pending. 当前处于回落观察窗内:判断是「弹回高副本」还是「持续低位确认退还」 + const pd = st.pendingDrop; + const costSinceDrop = Math.max(0, safeCost - pd.preDropCostUsd); + const expectedSinceDrop = rate !== null ? costSinceDrop * rate : 0; + const expectedOnTick = rate !== null ? rawDeltaCost * rate : 0; + const jumpAboveTickSpend = deltaOfficial - expectedOnTick; + const reboundFloor = pd.preDropUsedPct - Math.min(0.15, pd.dropPct * 0.35); + const isReplicaRebound = + deltaOfficial > 1e-3 && + jumpAboveTickSpend >= Math.max(QR_REFUND_EPSILON_PCT, pd.dropPct * 0.45) && + safeUsed >= reboundFloor; + + if (isReplicaRebound) { + const excessAboveHighWater = safeUsed - (pd.preDropUsedPct + expectedSinceDrop); + st.pendingDrop = null; + st.lastBounceAtMs = nowMs; + st.pendingCostUsd = 0; + st.pendingCostAtMs = 0; + if (rate !== null && excessAboveHighWater >= QR_MIN_JUMP_EXCESS_PCT) { + st.activeLeases.push({ + amountPct: excessAboveHighWater, + remainingPct: excessAboveHighWater, + createdAtMs: nowMs, + lastTouchedMs: nowMs, + sessionCount: Math.max(1, safeSess10m || 1), + }); + if (st.activeLeases.length > QR_MAX_ACTIVE_LEASES) { + st.activeLeases.splice(0, st.activeLeases.length - QR_MAX_ACTIVE_LEASES); + } + eventKind = 'lease'; + } else { + eventKind = 'replica_flip'; + } + } else { + pd.lowSamples += 1; + const sustainedLow = + isIdleRefundReady || + (pd.lowSamples >= QR_REFUND_CONFIRM_MIN_SAMPLES && + nowMs - pd.droppedAtMs >= QR_REFUND_CONFIRM_WINDOW_MS); + if (sustainedLow) { + if (rawDeltaCost > 0 && deltaOfficial <= 1e-3) { + st.pendingCostUsd = effectiveDeltaCost; + st.pendingCostAtMs = nowMs; + } + 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, + }); + } else if (deltaOfficial > 1e-3) { + st.pendingCostUsd = 0; + st.pendingCostAtMs = 0; + eventKind = 'drop_pending'; + } else if (rawDeltaCost > 0) { + st.pendingCostUsd = effectiveDeltaCost; + st.pendingCostAtMs = nowMs; + eventKind = 'lag_pending'; + } + } } else if (deltaOfficial > 1e-3) { - // 4B. 官方已用比例上升:区分租约跳变及常规消耗 + // 4B. 官方已用比例上升:区分租约跳变、真实租约内消费及常规消耗 const detectedWithRate = rate !== null && excessPct >= QR_MIN_JUMP_EXCESS_PCT; const detectedColdStart = rate === null && deltaOfficial >= QR_COLD_START_JUMP_PCT && effectiveDeltaCost <= QR_COLD_START_MAX_COST_USD; + const shortfall = expectedDeltaPct - deltaOfficial; + const isSignificantShortfall = + st.activeLeases.length > 0 && + expectedDeltaPct > 0 && + shortfall >= Math.max(QR_CONSUME_MIN_SHORTFALL_PCT, expectedDeltaPct * QR_CONSUME_SHORTFALL_RATIO); if (detectedWithRate || detectedColdStart) { const leaseRemaining = detectedWithRate ? excessPct : deltaOfficial; @@ -361,26 +698,27 @@ export function createQuotaReservationTracker() { st.activeLeases.splice(0, st.activeLeases.length - QR_MAX_ACTIVE_LEASES); } eventKind = 'lease'; - } else if (st.activeLeases.length > 0 && expectedDeltaPct > deltaOfficial) { - // 租约期内同时出现官方微增及本地消耗:超出官方增量的消耗计入当前租约内消费 - const shortfall = expectedDeltaPct - deltaOfficial; + } else if (isSignificantShortfall) { + // 租约期内出现明显低于预期的官方增量:仅把显著缺口计入当前租约内消费 qrConsumeLeasesFifo(st.activeLeases, shortfall); for (let i = 0; i < st.activeLeases.length; i += 1) { st.activeLeases[i].lastTouchedMs = nowMs; } eventKind = 'consume'; } else { + const outsideBounceCooldown = + st.lastBounceAtMs === 0 || nowMs - st.lastBounceAtMs >= QR_RATE_BOUNCE_COOLDOWN_MS; if ( st.activeLeases.length === 0 && - effectiveDeltaCost >= 0.05 && + outsideBounceCooldown && + !pendingValid && + rawDeltaCost >= 0.04 && deltaUnpriced === 0 && - deltaOfficial < QR_COLD_START_JUMP_PCT + deltaOfficial > 0.005 && + deltaOfficial < QR_MIN_JUMP_EXCESS_PCT ) { - // 纯净未租约消耗:平稳校准该桶 $/1% 换算率 - qrUpdateRateEma(st, deltaOfficial / effectiveDeltaCost); - st.lastSettledUsedPct = safeUsed; - st.lastSettledCostUsd = safeCost; - st.lastSettledAtMs = nowMs; + // 纯净未租约且无近期副本抖动的单步消耗:进入滚动中位数费率校准池 + qrRecordRateSample(st, deltaOfficial / rawDeltaCost); } eventKind = 'normal'; } @@ -413,9 +751,9 @@ export function createQuotaReservationTracker() { st.lastCycleCostUsd = safeCost; st.lastUnpricedCalls = safeUnpriced; - // 5. 租约 TTL 超时兜底(静默超过 11.5 分钟仍未退还,说明租约已在窗内耗尽) + // 5. 租约 TTL 超时兜底(租约本身超过 11.5 分钟无实质扣减或满 22 分钟自动清理) const beforePrune = st.activeLeases.length; - qrPruneExpiredLeases(st, poolLastActivityMs, safeUsed, safeCost, nowMs); + qrPruneExpiredLeases(st, nowMs); if (beforePrune > st.activeLeases.length && eventKind === 'idle') { eventKind = 'expire'; } @@ -500,6 +838,7 @@ export function createQuotaReservationTracker() { } function getLogSnapshot() { + ensureHydrated(); const bucketSummaries = []; for (const [key, st] of buckets.entries()) { const parts = key.split('::'); @@ -528,6 +867,8 @@ export function createQuotaReservationTracker() { function reset() { buckets.clear(); eventLog.length = 0; + lastPersistMs = 0; + hydrated = true; } return { @@ -539,7 +880,23 @@ export function createQuotaReservationTracker() { }; } -const defaultQuotaReservationTracker = createQuotaReservationTracker(); +function qrIsTestRuntime() { + return ( + lsRuntimeEndpoint?.addr === 'test.invalid' || + String(process?.env?.ANTIGRAVITY_LS_ADDRESS || '').trim() === 'test.invalid' + ); +} + +const defaultQuotaReservationTracker = createQuotaReservationTracker({ + loadState: () => { + if (qrIsTestRuntime()) return null; + return loadJson(QUOTA_RESERVATION_STATE_FILE, null); + }, + saveState: (payload) => { + if (qrIsTestRuntime()) return; + saveJson(QUOTA_RESERVATION_STATE_FILE, payload); + }, +}); /** * 使用全局默认追踪器为 `quotaPoolsMap` 中的所有配额池刷新 5h 及周限的实验性预占估算字段。 diff --git a/sidecars/panel/backend/telemetry-builder.mjs b/sidecars/panel/backend/telemetry-builder.mjs index 6a4309c..b1ab10d 100644 --- a/sidecars/panel/backend/telemetry-builder.mjs +++ b/sidecars/panel/backend/telemetry-builder.mjs @@ -1713,13 +1713,39 @@ export async function buildTelemetryPayloadInternal( const realAiCredits = Number(g1CreditEntry?.creditAmount || 0); const uiBundleVersion = computeRuntimeCodeVersion(); - const rawTierName = userStatus?.userTier?.name || ''; - const inferredPlanFallback = /\bfree\b/i.test(rawTierName) + const rawTierId = String(userStatus?.userTier?.id || '').trim(); + const rawTierName = String(userStatus?.userTier?.name || '').trim(); + const rawTierDesc = String(userStatus?.userTier?.description || '').trim(); + const rawPlanName = String(userStatus?.planStatus?.planInfo?.planName || '').trim(); + const tierIdLower = rawTierId.toLowerCase(); + const tierText = `${rawTierId} ${rawTierName} ${rawTierDesc}`; + const resolvedTierMultiplier = /(?:^|[-_\s])5x(?:$|[-_\s])|ultra[-_]?lite/i.test(tierText) + ? '5x' + : /(?:^|[-_\s])20x(?:$|[-_\s])/i.test(tierText) || + tierIdLower === 'g1-ultra-tier' || + (/^g1-ultra(?:-[a-z0-9]+)?-tier$/i.test(tierIdLower) && !/lite|5x/i.test(tierIdLower)) + ? '20x' + : ''; + const resolvedTierName = + rawTierName || + (/ultra/i.test(tierIdLower) + ? 'Google AI Ultra' + : /pro/i.test(tierIdLower) + ? 'Google AI Pro' + : /free|standard/i.test(tierIdLower) + ? 'Google AI Free' + : 'Google AI'); + const isUltraTier = /\bultra\b/i.test(resolvedTierName) || /ultra/i.test(tierIdLower); + const inferredPlanFallback = /\bfree\b/i.test(resolvedTierName) ? 'Free' - : /\bultra\b/i.test(rawTierName) - ? 'Ultra' + : isUltraTier + ? resolvedTierMultiplier || 'Ultra' : 'Pro'; - const resolvedPlanName = userStatus?.planStatus?.planInfo?.planName || inferredPlanFallback; + // Google 上游对 Ultra 订阅的 planStatus.planInfo.planName 仍会返回 "Pro",按 userTier.id 还原 5x / 20x + const resolvedPlanName = isUltraTier + ? resolvedTierMultiplier || + (rawPlanName && !/^pro$/i.test(rawPlanName) ? rawPlanName : 'Ultra') + : rawPlanName || inferredPlanFallback; // 预计算近期会话与运行中会话的轻量缓存速览指标(零额外 RPC 开销) const quickStatsMemo = new Map(); @@ -2100,7 +2126,9 @@ export async function buildTelemetryPayloadInternal( status: accountStatus, email: userStatus?.email || '', name: userStatus?.name || '', - tierName: rawTierName || 'Google AI', + tierId: rawTierId, + tierName: resolvedTierName, + tierMultiplier: resolvedTierMultiplier, planName: resolvedPlanName, aiCredits: realAiCredits > 0 ? realAiCredits : null, totalConversations: conversations.length, diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index 098b898..124feb7 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/shared/settings-normalization.mjs b/sidecars/panel/shared/settings-normalization.mjs index a8d8a18..889a52e 100644 --- a/sidecars/panel/shared/settings-normalization.mjs +++ b/sidecars/panel/shared/settings-normalization.mjs @@ -28,6 +28,7 @@ export const TOPBAR_SLOT_KEYS = Object.freeze([ 'quota_auto', 'gemini_5h', 'gemini_weekly', + 'argon_weekly', 'claude_5h', 'claude_weekly', ]); diff --git a/sidecars/panel/shared/telemetry-display-rules.mjs b/sidecars/panel/shared/telemetry-display-rules.mjs index cf6aa7d..75e3892 100644 --- a/sidecars/panel/shared/telemetry-display-rules.mjs +++ b/sidecars/panel/shared/telemetry-display-rules.mjs @@ -96,8 +96,40 @@ export function formatCompactCapsuleTtft(ttftSec) { return `${Math.round(val)}s`; } +function readPoolWeeklyRemainingPct(pool) { + if (!pool || typeof pool !== 'object') return null; + const raw = pool.weeklyRemainingPct ?? pool.remainingWeeklyPct; + return raw != null && Number.isFinite(Number(raw)) ? Number(raw) : null; +} + +function isArgonPoolObject(pool) { + if (!pool || typeof pool !== 'object') return false; + if (pool.poolKey === 'Argon' || pool.family === 'Argon') return true; + return /\bargon\b/i.test(String(pool.poolKey || pool.poolLabel || pool.family || '')); +} + /** - * 解析胶囊指定配额槽位(`quota_auto` / `gemini_5h` / `gemini_weekly` / `claude_5h` / `claude_weekly`)的整数剩余百分比。 + * 判断当前配额摘要中是否存在独立的 Argon 周限配额池(如 Google AI Pro 账号)。 + * + * @param {object|null|undefined} quotas + * @returns {boolean} + */ +export function hasArgonWeeklyQuotaPool(quotas) { + if (!quotas || typeof quotas !== 'object') return false; + const pools = Array.isArray(quotas.pools) ? quotas.pools : []; + const argonPool = pools.find(isArgonPoolObject); + if (argonPool && readPoolWeeklyRemainingPct(argonPool) != null) { + return true; + } + const activePool = quotas.activePool; + if (activePool && isArgonPoolObject(activePool) && readPoolWeeklyRemainingPct(activePool) != null) { + return true; + } + return false; +} + +/** + * 解析胶囊指定配额槽位(`quota_auto` / `gemini_5h` / `gemini_weekly` / `argon_weekly` / `claude_5h` / `claude_weekly`)的整数剩余百分比。 * * @param {object|null|undefined} quotas * @param {string} slotKey @@ -114,8 +146,9 @@ export function resolveCapsuleQuotaSlotPct(quotas, slotKey) { if (activePool && Number.isFinite(Number(activePool.remainingPct))) { candidates.push(Number(activePool.remainingPct)); } - if (activePool && Number.isFinite(Number(activePool.weeklyRemainingPct))) { - candidates.push(Number(activePool.weeklyRemainingPct)); + const activeWk = readPoolWeeklyRemainingPct(activePool); + if (activeWk != null) { + candidates.push(activeWk); } if (!candidates.length && weekly && Number.isFinite(Number(weekly.remainingPct))) { candidates.push(Number(weekly.remainingPct)); @@ -123,15 +156,24 @@ export function resolveCapsuleQuotaSlotPct(quotas, slotKey) { if (!candidates.length && pools.length > 0) { for (const p of pools) { if (p && Number.isFinite(Number(p.remainingPct))) candidates.push(Number(p.remainingPct)); - if (p && Number.isFinite(Number(p.weeklyRemainingPct))) { - candidates.push(Number(p.weeklyRemainingPct)); - } + const pWk = readPoolWeeklyRemainingPct(p); + if (pWk != null) candidates.push(pWk); } } if (!candidates.length) return null; return Math.max(0, Math.min(100, Math.round(Math.min(...candidates)))); } + if (slotKey === 'argon_weekly') { + const argonPool = pools.find(isArgonPoolObject); + let argonPct = readPoolWeeklyRemainingPct(argonPool); + if (argonPct == null && isArgonPoolObject(activePool)) { + argonPct = readPoolWeeklyRemainingPct(activePool); + } + if (argonPct == null || !Number.isFinite(argonPct)) return null; + return Math.max(0, Math.min(100, Math.round(argonPct))); + } + const isClaude = slotKey.startsWith('claude_'); const isWeekly = slotKey.endsWith('_weekly'); let rawPct = null; @@ -140,11 +182,11 @@ export function resolveCapsuleQuotaSlotPct(quotas, slotKey) { const claudePool = pools.find((p) => p?.poolKey === 'Claude & GPT') || pools.find((p) => isThirdPartyPoolText(p?.poolKey || p?.poolLabel || '')); - const cand = isWeekly ? claudePool?.weeklyRemainingPct : claudePool?.remainingPct; + const cand = isWeekly ? readPoolWeeklyRemainingPct(claudePool) : claudePool?.remainingPct; if (cand != null && Number.isFinite(Number(cand))) { rawPct = Number(cand); } else if (activePool && isThirdPartyPoolText(activePool.family || activePool.poolLabel || '')) { - const fb = isWeekly ? activePool.weeklyRemainingPct : activePool.remainingPct; + const fb = isWeekly ? readPoolWeeklyRemainingPct(activePool) : activePool.remainingPct; if (fb != null && Number.isFinite(Number(fb))) rawPct = Number(fb); } } else { @@ -158,12 +200,12 @@ export function resolveCapsuleQuotaSlotPct(quotas, slotKey) { const geminiFamilyPools = pools.filter((p) => /gemini|carbon|argon/i.test(String(p?.poolKey || p?.poolLabel || '')) ); - const primaryCand = isWeekly ? stdGemini?.weeklyRemainingPct : stdGemini?.remainingPct; + const primaryCand = isWeekly ? readPoolWeeklyRemainingPct(stdGemini) : stdGemini?.remainingPct; if (primaryCand != null && Number.isFinite(Number(primaryCand))) { rawPct = Number(primaryCand); } else { const familyVals = geminiFamilyPools - .map((p) => (isWeekly ? p?.weeklyRemainingPct : p?.remainingPct)) + .map((p) => (isWeekly ? readPoolWeeklyRemainingPct(p) : p?.remainingPct)) .filter((v) => v != null && Number.isFinite(Number(v))) .map(Number); if (familyVals.length > 0) { @@ -172,7 +214,7 @@ export function resolveCapsuleQuotaSlotPct(quotas, slotKey) { activePool && !isThirdPartyPoolText(activePool.family || activePool.poolLabel || '') ) { - const fb = isWeekly ? activePool.weeklyRemainingPct : activePool.remainingPct; + const fb = isWeekly ? readPoolWeeklyRemainingPct(activePool) : activePool.remainingPct; if (fb != null && Number.isFinite(Number(fb))) rawPct = Number(fb); } if ( diff --git a/sidecars/panel/src/components/charts/SessionStepCharts.js b/sidecars/panel/src/components/charts/SessionStepCharts.js index 232ec07..1af6fa6 100644 --- a/sidecars/panel/src/components/charts/SessionStepCharts.js +++ b/sidecars/panel/src/components/charts/SessionStepCharts.js @@ -1311,16 +1311,15 @@ export function createSessionLineChart() { patchStyleVar(mLine, '--sstep-fit-accent', seriesColor); multiLineGroup.appendChild(mLine); - if (seriesPts.length <= 36) { - for (const pt of seriesPts) { - const dot = document.createElementNS(SVG_NS, 'circle'); - dot.setAttribute('cx', pt.x.toFixed(1)); - dot.setAttribute('cy', pt.y.toFixed(1)); - dot.setAttribute('r', seriesPts.length > 20 ? '1.7' : '2.1'); - dot.setAttribute('class', 'sstep-node-dot'); - patchStyleVar(dot, '--dot-stroke', seriesColor); - dotsGroup.appendChild(dot); - } + if (seriesPts.length === 1) { + const pt = seriesPts[0]; + const dot = document.createElementNS(SVG_NS, 'circle'); + dot.setAttribute('cx', pt.x.toFixed(1)); + dot.setAttribute('cy', pt.y.toFixed(1)); + dot.setAttribute('r', '2.1'); + dot.setAttribute('class', 'sstep-node-dot'); + patchStyleVar(dot, '--dot-stroke', seriesColor); + dotsGroup.appendChild(dot); } } } @@ -1344,40 +1343,30 @@ export function createSessionLineChart() { patchAttr(linePath, 'd', lineD); patchAttr(areaPath, 'd', `${lineD} L ${lastX} ${BOTTOM_Y} L ${firstX} ${BOTTOM_Y} Z`); } - - if (points.length <= 64) { - for (const pt of points) { - const dot = document.createElementNS(SVG_NS, 'circle'); - dot.setAttribute('cx', pt.x.toFixed(1)); - dot.setAttribute('cy', pt.y.toFixed(1)); - if (pt.valid) { - dot.setAttribute('r', points.length > 36 ? '1.8' : '2.3'); - dot.setAttribute('class', 'sstep-node-dot'); - patchStyleVar( - dot, - '--dot-stroke', - modelColorMap.size > 1 ? pt.dotColor : accentColor - ); - } else { - dot.setAttribute('r', '1.6'); - dot.setAttribute('class', 'sstep-node-dot is-skipped'); - } - dotsGroup.appendChild(dot); - } - } } + const anomalyTicks = []; for (const pt of points) { if (!pt.valid || !pt.anomalySummary) continue; - const aDot = document.createElementNS(SVG_NS, 'circle'); - aDot.setAttribute('cx', pt.x.toFixed(1)); - aDot.setAttribute('cy', pt.y.toFixed(1)); - aDot.setAttribute('r', '2.9'); - aDot.setAttribute( + anomalyTicks.push(pt); + } + anomalyTicks.sort((a, b) => + a.anomalySeverity === 'danger' ? 1 : b.anomalySeverity === 'danger' ? -1 : 0 + ); + const tickTopY = (BOTTOM_Y - 5).toFixed(1); + const tickBotY = BOTTOM_Y.toFixed(1); + for (const pt of anomalyTicks) { + const xStr = pt.x.toFixed(1); + const aTick = document.createElementNS(SVG_NS, 'line'); + aTick.setAttribute('x1', xStr); + aTick.setAttribute('x2', xStr); + aTick.setAttribute('y1', tickTopY); + aTick.setAttribute('y2', tickBotY); + aTick.setAttribute( 'class', - `sstep-anomaly-dot${pt.anomalySeverity === 'danger' ? ' is-danger' : ''}` + `sstep-anomaly-dot sstep-anomaly-tick${pt.anomalySeverity === 'danger' ? ' is-danger' : ''}` ); - anomalyDotsGroup.appendChild(aDot); + anomalyDotsGroup.appendChild(aTick); } const tickIndices = computeStepTickIndices(points.length); @@ -2288,11 +2277,14 @@ export function createModelFitChart() { multiCurveGroup.appendChild(curveEl); } } + anomalyOverlayDots.sort((a, b) => + a.anomalySeverity === 'danger' ? 1 : b.anomalySeverity === 'danger' ? -1 : 0 + ); for (const sp of anomalyOverlayDots) { const aDot = document.createElementNS(SVG_NS, 'circle'); aDot.setAttribute('cx', sp.x.toFixed(1)); aDot.setAttribute('cy', sp.rawY.toFixed(1)); - aDot.setAttribute('r', '2.9'); + aDot.setAttribute('r', dotRadius); aDot.setAttribute( 'class', `sstep-scatter-dot is-anomaly${sp.anomalySeverity === 'danger' ? ' is-danger' : ''}` @@ -2462,11 +2454,14 @@ export function createModelFitChart() { dot.setAttribute('class', 'sstep-scatter-dot'); scatterTarget.appendChild(dot); } + singleAnomalyDots.sort((a, b) => + a.anomalySeverity === 'danger' ? 1 : b.anomalySeverity === 'danger' ? -1 : 0 + ); for (const s of singleAnomalyDots) { const aDot = document.createElementNS(SVG_NS, 'circle'); aDot.setAttribute('cx', s.x.toFixed(1)); aDot.setAttribute('cy', s.rawY.toFixed(1)); - aDot.setAttribute('r', '2.9'); + aDot.setAttribute('r', dotRadius); aDot.setAttribute( 'class', `sstep-scatter-dot is-anomaly${s.anomalySeverity === 'danger' ? ' is-danger' : ''}` diff --git a/sidecars/panel/src/components/charts/TrendAreaChart.js b/sidecars/panel/src/components/charts/TrendAreaChart.js index 8c4f461..321d99b 100644 --- a/sidecars/panel/src/components/charts/TrendAreaChart.js +++ b/sidecars/panel/src/components/charts/TrendAreaChart.js @@ -281,16 +281,7 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { linePath.setAttribute('fill', 'none'); svg.appendChild(linePath); - const dotsGroup = document.createElementNS(SVG_NS, 'g'); - dotsGroup.setAttribute('class', 'trend-dots-group'); - svg.appendChild(dotsGroup); - - const peakDot = document.createElementNS(SVG_NS, 'circle'); - peakDot.setAttribute('r', '3'); - peakDot.setAttribute('class', 'trend-peak-dot'); - svg.appendChild(peakDot); - - // 悬停十字准星与焦点圆点 + // 悬停十字准星及焦点圆点 const hoverLine = document.createElementNS(SVG_NS, 'line'); hoverLine.setAttribute('class', 'trend-hover-line'); hoverLine.setAttribute('y1', '12'); @@ -1129,25 +1120,9 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) { xAxisEl.appendChild(tickEl); tickElsByIdx.set(tIdx, tickEl); } - - // 渲染采样点小圆点(当点数 <= 36 时展示,突出有消耗的整点/日期) - while (dotsGroup.firstChild) dotsGroup.removeChild(dotsGroup.firstChild); - if (pts.length <= 36) { - for (let i = 0; i < pts.length; i++) { - if (pts[i].tokens <= 0) continue; - const dot = document.createElementNS(SVG_NS, 'circle'); - dot.setAttribute('cx', pts[i].x.toFixed(1)); - dot.setAttribute('cy', pts[i].y.toFixed(1)); - dot.setAttribute('r', '2'); - dot.setAttribute('class', 'trend-node-dot'); - dotsGroup.appendChild(dot); - } - } } const peakPt = pts[peakIdx] || { x: viewW / 2, y: BOTTOM_Y }; - patchAttr(peakDot, 'cx', peakPt.x.toFixed(1)); - patchAttr(peakDot, 'cy', peakPt.y.toFixed(1)); const peakSlot = slots[peakIdx]; const peakText = diff --git a/sidecars/panel/src/components/settings/structurePreviewMock.js b/sidecars/panel/src/components/settings/structurePreviewMock.js index 103f63d..e3b6708 100644 --- a/sidecars/panel/src/components/settings/structurePreviewMock.js +++ b/sidecars/panel/src/components/settings/structurePreviewMock.js @@ -7,7 +7,11 @@ import { t } from '../../i18n/index.js'; -export function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides = {}) { +export function buildStructurePreviewTelemetry( + baseSettings = {}, + draftOverrides = {}, + { includeArgonPool = false } = {} +) { const anchorMinMs = Math.floor(Date.now() / 60000) * 60000; const reset5hIso = new Date(anchorMinMs + (2 * 60 + 42) * 60000).toISOString(); const resetWkIso = new Date(anchorMinMs + (4 * 24 * 60 + 180) * 60000).toISOString(); @@ -361,8 +365,10 @@ export function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides return { settings: mergedSettings, account: { + tierId: 'g1-ultra-lite-tier', tierName: 'Google AI Ultra', - planName: 'Pro', + tierMultiplier: '5x', + planName: '5x', aiCredits: 0, }, quotas: { @@ -400,6 +406,21 @@ export function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides cycle5h: { tokens: 1754800, costUsd: 1.28, calls: 24 }, cycleWeekly: { tokens: 14200000, costUsd: 11.4, calls: 186 }, }, + ...(includeArgonPool + ? [ + { + poolKey: 'Argon', + poolLabel: 'Gemini 4 Argon', + family: 'Argon', + has5h: false, + hasWeekly: true, + weeklyUsedPct: 58, + weeklyRemainingPct: 42, + weeklyResetTime: resetWkIso, + cycleWeekly: { tokens: 4200000, costUsd: 6.4, calls: 48 }, + }, + ] + : []), { poolKey: 'Claude & GPT', poolLabel: 'Claude & GPT', diff --git a/sidecars/panel/src/components/widgets/QuotaPoolsWidget.js b/sidecars/panel/src/components/widgets/QuotaPoolsWidget.js index e40bee3..d9312e3 100644 --- a/sidecars/panel/src/components/widgets/QuotaPoolsWidget.js +++ b/sidecars/panel/src/components/widgets/QuotaPoolsWidget.js @@ -210,7 +210,7 @@ function syncQuotaWindowMeter({ const rsvWidth = +Math.min(Math.max(0, 100 - actualWidth), rsvVal).toFixed(2); patchStyleVar(fillEl, '--fill-w', `${actualWidth}%`); patchStyleVar(fillReservedEl, '--reserved-w', `${rsvWidth}%`); - patchClasses(fillReservedEl, { 'is-active': true }); + patchClasses(fillReservedEl, { 'is-active': true, 'has-sep': actualWidth > 0 }); } else { patchText( metaBeforeEl, @@ -230,7 +230,7 @@ function syncQuotaWindowMeter({ patchAttr(trackEl, 'title', null); patchStyleVar(fillEl, '--fill-w', `${Math.min(100, usedVal)}%`); patchStyleVar(fillReservedEl, '--reserved-w', '0%'); - patchClasses(fillReservedEl, { 'is-active': false }); + patchClasses(fillReservedEl, { 'is-active': false, 'has-sep': false }); } patchClasses(fillEl, { @@ -370,6 +370,45 @@ export function quotaPoolRowSig(item, idx) { 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}`; } +/** + * 格式化可用额度面板右上角的账号订阅徽章(区分 Ultra 5x / 20x,并对 Pro / Free 去重)。 + * + * @param {object|null|undefined} account + * @returns {string} + */ +export function formatAccountTierBadge(account) { + const tierName = String(account?.tierName || '').trim() || 'Google AI'; + const tierId = String(account?.tierId || '').trim().toLowerCase(); + const explicitMult = String(account?.tierMultiplier || '').trim(); + const inferredMult = + explicitMult || + (/(?:^|[-_\s])5x(?:$|[-_\s])|ultra[-_]?lite/i.test(`${tierId} ${tierName}`) + ? '5x' + : /(?:^|[-_\s])20x(?:$|[-_\s])/i.test(`${tierId} ${tierName}`) || tierId === 'g1-ultra-tier' + ? '20x' + : ''); + const rawPlan = String(account?.planName || '').trim(); + const isUltra = /\bultra\b/i.test(tierName) || /ultra/i.test(tierId); + + if (isUltra) { + if (inferredMult) { + const hasMultInTier = new RegExp(`(?:^|\\s|·)${inferredMult}(?:$|\\s)`, 'i').test(tierName); + return hasMultInTier ? tierName : `${tierName} · ${inferredMult}`; + } + if (rawPlan && !/^(?:pro|ultra)$/i.test(rawPlan)) { + return `${tierName} · ${rawPlan}`; + } + return tierName; + } + + if (!rawPlan) return tierName; + const escapedPlan = rawPlan.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + if (new RegExp(`(?:^|\\s|·)${escapedPlan}(?:$|\\s)`, 'i').test(tierName)) { + return tierName; + } + return `${tierName} · ${rawPlan}`; +} + export const QuotaPoolsWidget = defineComponent({ name: 'QuotaPoolsWidget', setup({ props }) { @@ -392,6 +431,23 @@ export const QuotaPoolsWidget = defineComponent({ }); } + const legendActualTextEl = h('span', { text: t('quota.legendActual') }); + const legendReservedTextEl = h('span', { text: t('quota.legendReserved') }); + const reserveLegendEl = h( + 'div', + { className: 'quota-reserve-legend', hidden: true }, + [ + h('span', { className: 'quota-legend-item' }, [ + h('span', { className: 'quota-legend-line is-actual', 'aria-hidden': 'true' }), + legendActualTextEl, + ]), + h('span', { className: 'quota-legend-item' }, [ + h('span', { className: 'quota-legend-line is-reserved', 'aria-hidden': 'true' }), + legendReservedTextEl, + ]), + ] + ); + const quotaPanel = h('section', { className: 'panel' }, [ h('div', { className: 'panel-header' }, [ h('span', { className: 'panel-title' }, [ @@ -401,11 +457,15 @@ export const QuotaPoolsWidget = defineComponent({ tierBadge, ]), poolsListEl, + reserveLegendEl, ]); function update({ data, minuteTick } = {}) { patchText(titleTextEl, t('module.quotas')); + patchText(legendActualTextEl, t('quota.legendActual')); + patchText(legendReservedTextEl, t('quota.legendReserved')); if (!data) { + reserveLegendEl.hidden = true; if (compactHover) { patchKeyedList(poolsListEl, buildQuotaPoolItems(null, 0, { isPending: true }), { keyFn: (item) => item.key, @@ -419,11 +479,9 @@ export const QuotaPoolsWidget = defineComponent({ const quotas = data.quotas || {}; const showReserved = data.settings?.experimentalQuotaReservation === true; + reserveLegendEl.hidden = !showReserved; const effTick = Number.isFinite(minuteTick) ? minuteTick : Math.floor(Date.now() / 30000); - patchText( - tierBadge, - `${data.account?.tierName || 'Google AI'} · ${data.account?.planName || 'Pro'}` - ); + patchText(tierBadge, formatAccountTierBadge(data.account)); patchKeyedList(poolsListEl, buildQuotaPoolItems(quotas, effTick, { showReserved }), { keyFn: (item) => item.key, sigFn: quotaPoolRowSig, diff --git a/sidecars/panel/src/i18n/en-US.js b/sidecars/panel/src/i18n/en-US.js index e82e194..2cbf819 100644 --- a/sidecars/panel/src/i18n/en-US.js +++ b/sidecars/panel/src/i18n/en-US.js @@ -125,6 +125,7 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'capMetric.quota_auto': 'Auto Tightest Quota', 'capMetric.gemini_5h': 'Gemini 5h Quota', 'capMetric.gemini_weekly': 'Gemini Weekly Quota', + 'capMetric.argon_weekly': 'Argon Weekly Quota', 'capMetric.claude_5h': 'Claude 5h Quota', 'capMetric.claude_weekly': 'Claude Weekly Quota', @@ -187,6 +188,8 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'quota.usedAfterReserved': ' · {rem}% left)', 'quota.reservedTip': 'Estimated lease reservation (Experimental): ~{rsv}% (~{actual}% actual used); unused share refunds after ~10 min idle', 'quota.reservedTipMulti': 'Estimated lease reservation (Experimental): ~{rsv}% ({leases} stacked leases, ~{actual}% actual used); unused share refunds after ~10 min idle', + 'quota.legendActual': 'Actual', + 'quota.legendReserved': 'Reserved', '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', @@ -691,7 +694,7 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'settings.oth.quotaReserveLabel': 'Quota Reservation Estimate', 'settings.oth.quotaReserveDesc': 'Estimate 0.5% / 1% 5h & weekly lease holds in Available Quotas and highlight the reserved share in violet', 'settings.oth.quotaReserveLogLabel': 'Reservation Observation Log', - 'settings.oth.quotaReserveLogDesc': 'Copy in-memory quota jump & refund events to clipboard for threshold tuning', + 'settings.oth.quotaReserveLogDesc': 'Copy persisted quota jump & refund observations to clipboard (retained across restarts)', 'settings.oth.exportReserveLogBtn': 'Export Reserve Log', 'settings.oth.exportReserveLogCopied': 'Copied {count} log entries to clipboard', 'settings.oth.exportReserveLogEmpty': 'No events yet; copied current summary to clipboard', @@ -731,7 +734,7 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'settings.oth.resettingBtn': 'Resetting…', 'settings.oth.resetAllDone': 'All preferences restored to defaults', 'settings.oth.backupLabel': 'Preferences Backup & Restore', - 'settings.oth.backupDesc': 'Export or import portable UI, capsule, and table preferences as JSON (excludes credentials)', + 'settings.oth.backupDesc': 'Export or import portable UI, capsule, and table preferences as JSON', 'settings.oth.exportJsonBtn': 'Export JSON', 'settings.oth.importJsonBtn': 'Import JSON', 'settings.oth.exportDone': 'Preferences JSON exported', @@ -745,7 +748,7 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'settings.oth.migModeLabel': 'Migration Mode', 'settings.oth.migModeMove': 'Full Move (Recommended)', 'settings.oth.migModeClone': 'Clone Copy', - 'settings.oth.migModeMoveHint': 'Assigns an isolated target ID while preserving all historical steps/details; archives source backup before moving (close source session first)', + 'settings.oth.migModeMoveHint': 'Assigns an isolated target ID while preserving all historical steps/details; archives source backup before moving', 'settings.oth.migModeCloneHint': 'Keeps source intact with a fresh UUID; only counts new steps generated after cloning', 'settings.oth.migProjectLabel': 'Target Project', 'settings.oth.migProjectOutside': 'Standalone (No Project)', diff --git a/sidecars/panel/src/i18n/zh-CN.js b/sidecars/panel/src/i18n/zh-CN.js index 5dd98c3..eb000cd 100644 --- a/sidecars/panel/src/i18n/zh-CN.js +++ b/sidecars/panel/src/i18n/zh-CN.js @@ -125,6 +125,7 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'capMetric.quota_auto': '自动紧俏额度', 'capMetric.gemini_5h': 'Gemini 5h 额度', 'capMetric.gemini_weekly': 'Gemini 周额度', + 'capMetric.argon_weekly': 'Argon 周额度', 'capMetric.claude_5h': 'Claude 5h 额度', 'capMetric.claude_weekly': 'Claude 周额度', @@ -187,6 +188,8 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'quota.usedAfterReserved': ' · 余 {rem}%)', 'quota.reservedTip': '预占估算(试验性):约 {rsv}%(实际已用约 {actual}%),静默约 10 分钟后未用差额自动退还', 'quota.reservedTipMulti': '预占估算(试验性):约 {rsv}%(检测到 {leases} 笔叠加租约,实际已用约 {actual}%),静默约 10 分钟后未用差额自动退还', + 'quota.legendActual': '实占', + 'quota.legendReserved': '预占', 'quota.cycle5hTitle': '当前 5h 周期累计 ({pool}):{tok} Tokens · {cost} · {calls} 次调用', 'quota.cycleWkCustomTitle': '本周自然周累计:{tok} Tokens · {cost} · {calls} 次调用', 'quota.cycleWkPoolTitle': '当前周限周期累计 ({pool}):{tok} Tokens · {cost} · {calls} 次调用', @@ -691,7 +694,7 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.oth.quotaReserveLabel': '配额预占估算', 'settings.oth.quotaReserveDesc': '在可用额度中估算 5h / 周限的 0.5% / 1% 租约预占,并用紫色标注占比及进度条段', 'settings.oth.quotaReserveLogLabel': '预占观测日志', - 'settings.oth.quotaReserveLogDesc': '将内存中的配额跳变及退还记录复制到剪贴板,便于分析触发阈值', + 'settings.oth.quotaReserveLogDesc': '将配额跳变及退还观测记录复制到剪贴板,重启后自动保留,便于分析触发阈值', 'settings.oth.exportReserveLogBtn': '导出预占日志', 'settings.oth.exportReserveLogCopied': '已复制 {count} 条观测日志到剪贴板', 'settings.oth.exportReserveLogEmpty': '暂无跳变记录,已复制当前摘要到剪贴板', @@ -731,7 +734,7 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.oth.resettingBtn': '重置中…', 'settings.oth.resetAllDone': '已恢复全部默认设置', 'settings.oth.backupLabel': '配置备份及恢复', - 'settings.oth.backupDesc': '导出或导入外观、胶囊、列配置等便携偏好 JSON(不含账号凭证)', + 'settings.oth.backupDesc': '导出或导入外观、胶囊、列配置等便携偏好 JSON', 'settings.oth.exportJsonBtn': '导出 JSON', 'settings.oth.importJsonBtn': '导入 JSON', 'settings.oth.exportDone': '配置 JSON 已导出', @@ -745,7 +748,7 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.oth.migModeLabel': '迁移方式', 'settings.oth.migModeMove': '完整迁移(推荐)', 'settings.oth.migModeClone': '克隆副本', - 'settings.oth.migModeMoveHint': '分配目标端独立会话 ID 并完整保留全部历史步序明细,备份后移出源端(零重复计费;迁移前建议先关闭源端该会话)', + 'settings.oth.migModeMoveHint': '分配目标端独立会话 ID 并完整保留全部历史步序明细,备份后移出源端', 'settings.oth.migModeCloneHint': '保留源会话并生成新 ID,新副本仅统计迁入后的新步骤', 'settings.oth.migProjectLabel': '绑定目标项目', 'settings.oth.migProjectOutside': '独立会话(无所属项目)', diff --git a/sidecars/panel/src/registries/metricRegistry.js b/sidecars/panel/src/registries/metricRegistry.js index 10a7f4c..26e44fc 100644 --- a/sidecars/panel/src/registries/metricRegistry.js +++ b/sidecars/panel/src/registries/metricRegistry.js @@ -24,17 +24,28 @@ import { OVERVIEW_METRIC_KEYS, TOPBAR_SLOT_KEYS } from '../../shared/settings-no import { formatCompactCapsuleCost, formatCompactCapsuleTtft, + hasArgonWeeklyQuotaPool, resolveCapsuleQuotaSlotPct, } from '../../shared/telemetry-display-rules.mjs'; -export { OVERVIEW_METRIC_KEYS, formatCompactCapsuleCost, formatCompactCapsuleTtft }; +export { + OVERVIEW_METRIC_KEYS, + formatCompactCapsuleCost, + formatCompactCapsuleTtft, + hasArgonWeeklyQuotaPool, +}; export const CAPSULE_METRIC_KEYS = TOPBAR_SLOT_KEYS; -export function getCapsuleMetricOptions() { - return CAPSULE_METRIC_KEYS.map((key) => ({ - value: key, - label: t(`capMetric.${key}`), - })); +export function getCapsuleMetricOptions({ quotas = null, selectedSlots = [] } = {}) { + const showArgonWeekly = + hasArgonWeeklyQuotaPool(quotas) || + (Array.isArray(selectedSlots) && selectedSlots.includes('argon_weekly')); + return CAPSULE_METRIC_KEYS.filter((key) => key !== 'argon_weekly' || showArgonWeekly).map( + (key) => ({ + value: key, + label: t(`capMetric.${key}`), + }) + ); } export function getOverviewMetricOptions() { @@ -97,17 +108,21 @@ export function resolveQuotaCapsuleSummary(quotas) { : `${tightest.label} ${tightest.windowTag} · ${runnerUp.label} ${runnerUp.windowTag} ${runnerPct}%` : `${tightest.label} · ${tightest.windowTag}`; const tightestIsClaude = /claude|gpt|fable|oss|third/i.test(String(tightest.label || '')); - const tightestIsGemini = !tightestIsClaude && /gemini|argon|carbon|neon|flash|pro/i.test(String(tightest.label || '')); + const tightestIsArgon = !tightestIsClaude && /\bargon\b/i.test(String(tightest.label || '')); + const tightestIsGemini = + !tightestIsClaude && !tightestIsArgon && /gemini|carbon|neon|flash|pro/i.test(String(tightest.label || '')); const tightestWinShort = tightest.windowTag === '5h' ? '5h' : isEnglishLocale() ? 'w' : '周'; const poolPrefix = tightestIsClaude ? `C${tightestWinShort}` - : tightestIsGemini - ? `G${tightestWinShort}` - : tightest.windowTag === '5h' - ? '5h' - : isEnglishLocale() - ? 'Wk' - : '周'; + : tightestIsArgon + ? `A${tightestWinShort}` + : tightestIsGemini + ? `G${tightestWinShort}` + : tightest.windowTag === '5h' + ? '5h' + : isEnglishLocale() + ? 'Wk' + : '周'; return { roundedPct: rounded, shortText: t('capsule.quotaLeft', { pct: rounded }), @@ -126,6 +141,7 @@ function resolveQuotaCapsulePrefix(metricKey, quotaSum) { const isEn = isEnglishLocale(); if (metricKey === 'gemini_5h') return 'G5h'; if (metricKey === 'gemini_weekly') return isEn ? 'Gw' : 'G周'; + if (metricKey === 'argon_weekly') return isEn ? 'Aw' : 'A周'; if (metricKey === 'claude_5h') return 'C5h'; if (metricKey === 'claude_weekly') return isEn ? 'Cw' : 'C周'; if (quotaSum?.poolPrefix) return quotaSum.poolPrefix; @@ -346,6 +362,22 @@ export function resolveCapsuleMetricPresentation(metricKey, slotCtx, ringCircumf }; } + if (metricKey === 'argon_weekly' && slotCtx.hasTelemetry && !hasArgonWeeklyQuotaPool(slotCtx.quotas)) { + return { + hidden: true, + metric: 'none', + segClass: 'wm-cap-slot', + textClass: 'wm-slot-text', + showRing: false, + dashOffset: ringCircumference, + text: '', + toneClass: '', + running: false, + warn: false, + danger: false, + }; + } + const quotaSum = !slotCtx.hasTelemetry ? null : metricKey === 'quota_auto' diff --git a/sidecars/panel/src/store/telemetryStore.js b/sidecars/panel/src/store/telemetryStore.js index 2eb3b01..1ff307d 100644 --- a/sidecars/panel/src/store/telemetryStore.js +++ b/sidecars/panel/src/store/telemetryStore.js @@ -1038,7 +1038,9 @@ export function isEquivalentTelemetry(prev, next) { prev.account?.email !== next.account?.email || prev.account?.name !== next.account?.name || prev.account?.status !== next.account?.status || + prev.account?.tierId !== next.account?.tierId || prev.account?.tierName !== next.account?.tierName || + prev.account?.tierMultiplier !== next.account?.tierMultiplier || prev.account?.planName !== next.account?.planName || prev.account?.aiCredits !== next.account?.aiCredits ) { diff --git a/sidecars/panel/src/styles/modern-ui.css b/sidecars/panel/src/styles/modern-ui.css index 20fbb75..db52cad 100644 --- a/sidecars/panel/src/styles/modern-ui.css +++ b/sidecars/panel/src/styles/modern-ui.css @@ -628,11 +628,6 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { margin: 4px 2px 2px; } -[data-modern-ui="true"] .sstep-anomaly-dot, -[data-modern-ui="true"] .sstep-scatter-dot.is-anomaly { - fill: var(--modern-surface-card); -} - /* --- 6. 设置表单、折叠面板、槽位排序与输入控件去边框 --- */ [data-modern-ui="true"] .collapsible-body, [data-modern-ui="true"] .settings-action-block + .settings-action-block, diff --git a/sidecars/panel/src/styles/views-overview.css b/sidecars/panel/src/styles/views-overview.css index 6ab2c6e..1de48f3 100644 --- a/sidecars/panel/src/styles/views-overview.css +++ b/sidecars/panel/src/styles/views-overview.css @@ -580,13 +580,23 @@ .progress-fill-reserved { height: 100%; width: var(--reserved-w, 0%); - background: var(--quota-reserved); - transition: width var(--dur-normal) var(--ease-fast); + background: repeating-linear-gradient( + -45deg, + color-mix(in srgb, var(--quota-reserved) 72%, transparent) 0 2px, + color-mix(in srgb, var(--quota-reserved) 26%, transparent) 2px 5px + ); + transition: + width var(--dur-normal) var(--ease-fast), + margin-left var(--dur-fast) var(--ease-fast); flex-shrink: 0; } .progress-fill-reserved.is-active { - min-width: 3px; + min-width: 5px; +} + +.progress-fill-reserved.is-active.has-sep { + margin-left: 1px; } .quota-reserved-pct { @@ -594,6 +604,47 @@ font-weight: 500; } +.quota-reserve-legend { + display: flex; + align-items: center; + gap: 12px; + margin-top: 2px; + padding-top: 2px; + font-size: var(--fs-xs); + color: var(--text-muted); +} + +.quota-reserve-legend[hidden] { + display: none; +} + +.quota-legend-item { + display: inline-flex; + align-items: center; + gap: 5px; + white-space: nowrap; +} + +.quota-legend-line { + display: inline-block; + width: 14px; + height: 2px; + border-radius: 1px; + flex-shrink: 0; +} + +.quota-legend-line.is-actual { + background: var(--accent-primary); +} + +.quota-legend-line.is-reserved { + background: repeating-linear-gradient( + 90deg, + var(--quota-reserved) 0 4px, + transparent 4px 6.5px + ); +} + /* --- 4. 上下文双列图例网格 (Context 10-Channel Legend Grid) --- */ .ctx-legend-grid { display: grid; diff --git a/sidecars/panel/src/styles/views-tables.css b/sidecars/panel/src/styles/views-tables.css index 4c90ee6..54bf4ef 100644 --- a/sidecars/panel/src/styles/views-tables.css +++ b/sidecars/panel/src/styles/views-tables.css @@ -896,18 +896,29 @@ stroke: var(--metric-danger); } -.sstep-anomaly-dot, -.sstep-scatter-dot.is-anomaly { - fill: var(--surface-panel); - fill-opacity: 1; +.sstep-anomaly-dot { stroke: var(--metric-warn); - stroke-width: 1.6; + stroke-width: 1.5; + stroke-opacity: 0.82; + stroke-linecap: round; pointer-events: none; } -.sstep-anomaly-dot.is-danger, -.sstep-scatter-dot.is-anomaly.is-danger { +.sstep-anomaly-dot.is-danger { stroke: var(--metric-danger); + stroke-opacity: 0.92; +} + +.sstep-scatter-dot.is-anomaly { + fill: var(--metric-warn); + fill-opacity: 0.88; + stroke: none; + pointer-events: none; +} + +.sstep-scatter-dot.is-anomaly.is-danger { + fill: var(--metric-danger); + fill-opacity: 0.92; } .trend-tip-anomaly { diff --git a/sidecars/panel/src/views/SettingsView.js b/sidecars/panel/src/views/SettingsView.js index 101752a..52bcba5 100644 --- a/sidecars/panel/src/views/SettingsView.js +++ b/sidecars/panel/src/views/SettingsView.js @@ -108,7 +108,8 @@ export const SettingsView = defineComponent({ settings, telemetry?.windowBridge, telemetry?.hostPlatform, - telemetry?.cliStatusLine + telemetry?.cliStatusLine, + telemetry?.quotas ); } } else if (settingsSubTab === 'other') { diff --git a/sidecars/panel/src/views/settings/SettingsStructureTab.js b/sidecars/panel/src/views/settings/SettingsStructureTab.js index f1b3311..4e681c7 100644 --- a/sidecars/panel/src/views/settings/SettingsStructureTab.js +++ b/sidecars/panel/src/views/settings/SettingsStructureTab.js @@ -14,6 +14,7 @@ import { createSvgIcon } from '../../icons/SvgIcon.js'; import { getCapsuleMetricOptions, getOverviewMetricOptions, + hasArgonWeeklyQuotaPool, resolveSpecificQuotaSlotSummary, } from '../../registries/metricRegistry.js'; import { getStepColumnOptions } from '../../registries/stepColumnRegistry.js'; @@ -196,6 +197,15 @@ function formatCliPreviewSlot(slotKey, slotCtx, isEn) { pillPct: pct, }; } + case 'argon_weekly': { + const pct = quotaPct('argon_weekly', 42); + return { + prefix: isEn ? 'Aw ' : 'A周 ', + text: `${pct}%`, + tone: 'good', + pillPct: pct, + }; + } case 'claude_5h': { const pct = quotaPct('claude_5h', 32); return { @@ -255,6 +265,7 @@ export const SettingsStructureTab = defineComponent({ let latestWindowBridge = null; let latestCliStatusLine = null; let latestHostPlatform = 'win32'; + let latestQuotas = null; function getEffectiveDraftCliSlots() { return resolveEffectiveClientCliStatusLineSlots({ @@ -269,25 +280,34 @@ export const SettingsStructureTab = defineComponent({ } function buildDraftTelemetry() { - return buildStructurePreviewTelemetry(latestSettings, { - windowMountMode: draftWindowMountMode, - enableWindowOverlay: draftWindowMountMode !== 'sidebar', - popoverWidthMode: draftPopoverWidthMode, - popoverWidth: draftPopoverWidth, - enableCliStatusLine: draftEnableCliStatusLine, - showTopbarMultiSession: draftShowTopbarMulti, - contextAgentMode: draftContextAgentMode, - topbarCapsuleSlots: draftTopbarSlots, - hoverModules: draftHoverModules, - overviewModules: draftOverviewModules, - overviewMetrics: draftOverviewMetrics, - showStepTurnRail: draftShowStepTurnRail, - showStepAgentBadge: draftShowStepAgentBadge, - showStepSpeedColor: draftShowStepSpeedColor, - showStepFilterToolbar: draftShowStepFilterToolbar, - stepTokenComboFormat: draftStepTokenComboFormat, - stepTableColumns: draftStepColumns, - }); + const effectiveCliSlots = getEffectiveDraftCliSlots(); + const includeArgonPool = + hasArgonWeeklyQuotaPool(latestQuotas) || + draftTopbarSlots.includes('argon_weekly') || + effectiveCliSlots.includes('argon_weekly'); + return buildStructurePreviewTelemetry( + latestSettings, + { + windowMountMode: draftWindowMountMode, + enableWindowOverlay: draftWindowMountMode !== 'sidebar', + popoverWidthMode: draftPopoverWidthMode, + popoverWidth: draftPopoverWidth, + enableCliStatusLine: draftEnableCliStatusLine, + showTopbarMultiSession: draftShowTopbarMulti, + contextAgentMode: draftContextAgentMode, + topbarCapsuleSlots: draftTopbarSlots, + hoverModules: draftHoverModules, + overviewModules: draftOverviewModules, + overviewMetrics: draftOverviewMetrics, + showStepTurnRail: draftShowStepTurnRail, + showStepAgentBadge: draftShowStepAgentBadge, + showStepSpeedColor: draftShowStepSpeedColor, + showStepFilterToolbar: draftShowStepFilterToolbar, + stepTokenComboFormat: draftStepTokenComboFormat, + stepTableColumns: draftStepColumns, + }, + { includeArgonPool } + ); } async function persistStructurePatch(sectionComp, patchObj, successKey = 'settings.saved') { @@ -780,7 +800,10 @@ export const SettingsStructureTab = defineComponent({ const effectiveCliSlots = getEffectiveDraftCliSlots(); cliSlotsList.refs.setProps({ items: effectiveCliSlots, - options: getCapsuleMetricOptions(), + options: getCapsuleMetricOptions({ + quotas: latestQuotas, + selectedSlots: effectiveCliSlots, + }), addBtnTextFn: (count, max) => t('settings.str.addCliSlot', { count, max }), }); const preservedCustom = Boolean(latestCliStatusLine?.preservedCustom); @@ -819,7 +842,10 @@ export const SettingsStructureTab = defineComponent({ refreshCliPreview(); topbarSlotsList.refs.setProps({ items: draftTopbarSlots, - options: getCapsuleMetricOptions(), + options: getCapsuleMetricOptions({ + quotas: latestQuotas, + selectedSlots: draftTopbarSlots, + }), addBtnTextFn: (count, max) => t('settings.str.addCapsuleSlot', { count, max }), }); mountSection.refs.setBadge( @@ -1431,13 +1457,15 @@ export const SettingsStructureTab = defineComponent({ settings, windowBridge = latestWindowBridge, hostPlatform = latestHostPlatform, - cliStatusLine = latestCliStatusLine + cliStatusLine = latestCliStatusLine, + quotas = latestQuotas ) { if (!settings) return; latestSettings = settings; if (windowBridge !== undefined) latestWindowBridge = windowBridge; if (hostPlatform) latestHostPlatform = hostPlatform; if (cliStatusLine !== undefined) latestCliStatusLine = cliStatusLine; + if (quotas !== undefined) latestQuotas = quotas; draftWindowMountMode = normalizeClientWindowMountMode( settings.windowMountMode, settings.enableWindowOverlay diff --git a/sidecars/panel/styles.css b/sidecars/panel/styles.css index d00858f..43513c3 100644 --- a/sidecars/panel/styles.css +++ b/sidecars/panel/styles.css @@ -2263,13 +2263,23 @@ html[data-standalone="true"] .app-shell { .progress-fill-reserved { height: 100%; width: var(--reserved-w, 0%); - background: var(--quota-reserved); - transition: width var(--dur-normal) var(--ease-fast); + background: repeating-linear-gradient( + -45deg, + color-mix(in srgb, var(--quota-reserved) 72%, transparent) 0 2px, + color-mix(in srgb, var(--quota-reserved) 26%, transparent) 2px 5px + ); + transition: + width var(--dur-normal) var(--ease-fast), + margin-left var(--dur-fast) var(--ease-fast); flex-shrink: 0; } .progress-fill-reserved.is-active { - min-width: 3px; + min-width: 5px; +} + +.progress-fill-reserved.is-active.has-sep { + margin-left: 1px; } .quota-reserved-pct { @@ -2277,6 +2287,47 @@ html[data-standalone="true"] .app-shell { font-weight: 500; } +.quota-reserve-legend { + display: flex; + align-items: center; + gap: 12px; + margin-top: 2px; + padding-top: 2px; + font-size: var(--fs-xs); + color: var(--text-muted); +} + +.quota-reserve-legend[hidden] { + display: none; +} + +.quota-legend-item { + display: inline-flex; + align-items: center; + gap: 5px; + white-space: nowrap; +} + +.quota-legend-line { + display: inline-block; + width: 14px; + height: 2px; + border-radius: 1px; + flex-shrink: 0; +} + +.quota-legend-line.is-actual { + background: var(--accent-primary); +} + +.quota-legend-line.is-reserved { + background: repeating-linear-gradient( + 90deg, + var(--quota-reserved) 0 4px, + transparent 4px 6.5px + ); +} + /* --- 4. 上下文双列图例网格 (Context 10-Channel Legend Grid) --- */ .ctx-legend-grid { display: grid; @@ -4683,18 +4734,29 @@ html[data-standalone="true"] .app-shell { stroke: var(--metric-danger); } -.sstep-anomaly-dot, -.sstep-scatter-dot.is-anomaly { - fill: var(--surface-panel); - fill-opacity: 1; +.sstep-anomaly-dot { stroke: var(--metric-warn); - stroke-width: 1.6; + stroke-width: 1.5; + stroke-opacity: 0.82; + stroke-linecap: round; pointer-events: none; } -.sstep-anomaly-dot.is-danger, -.sstep-scatter-dot.is-anomaly.is-danger { +.sstep-anomaly-dot.is-danger { stroke: var(--metric-danger); + stroke-opacity: 0.92; +} + +.sstep-scatter-dot.is-anomaly { + fill: var(--metric-warn); + fill-opacity: 0.88; + stroke: none; + pointer-events: none; +} + +.sstep-scatter-dot.is-anomaly.is-danger { + fill: var(--metric-danger); + fill-opacity: 0.92; } .trend-tip-anomaly { @@ -8486,11 +8548,6 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { margin: 4px 2px 2px; } -[data-modern-ui="true"] .sstep-anomaly-dot, -[data-modern-ui="true"] .sstep-scatter-dot.is-anomaly { - fill: var(--modern-surface-card); -} - /* --- 6. 设置表单、折叠面板、槽位排序与输入控件去边框 --- */ [data-modern-ui="true"] .collapsible-body, [data-modern-ui="true"] .settings-action-block + .settings-action-block, diff --git a/sidecars/panel/test/quota-pools.test.mjs b/sidecars/panel/test/quota-pools.test.mjs index ea372dc..10383ca 100644 --- a/sidecars/panel/test/quota-pools.test.mjs +++ b/sidecars/panel/test/quota-pools.test.mjs @@ -78,6 +78,10 @@ test('Ultra user: Argon and Flash sharing Gemini Models remain a single Gemini p Array.from(p.quotas.pools, (pool) => pool.poolKey), ['Gemini', 'Claude & GPT'] ); + assert.equal(p.account.tierId, 'g1-ultra-lite-tier'); + assert.equal(p.account.tierName, 'Google AI Ultra'); + assert.equal(p.account.tierMultiplier, '5x'); + assert.equal(p.account.planName, '5x'); assert.equal(p.quotas.activePool.family, 'Gemini'); assert.equal(p.quotas.activePool.weeklyRemainingPct, 8.7); assert.equal(p.quotas.weekly.poolFamily, 'Gemini'); @@ -663,3 +667,137 @@ test('per-pool cycle5h and cycleWeekly isolate each pool by its own reset window const cycleSourcesTok = pCycle.consumption.sourcesBreakdown.reduce((sum, s) => sum + s.totalTokens, 0); assert.equal(cycleSourcesTok, 155_000); }); + +test('account tier badge distinguishes Ultra 5x (g1-ultra-lite-tier) vs Ultra 20x (g1-ultra-tier) and deduplicates Pro/Free', async () => { + const { formatAccountTierBadge } = await import('../src/components/widgets/QuotaPoolsWidget.js'); + + const hUltra20 = backendHarness({ + userStatus: { + userTier: { id: 'g1-ultra-tier', name: 'Google AI Ultra' }, + planStatus: { planInfo: { planName: 'Pro' } }, + }, + }); + const p20 = await hUltra20.buildTelemetryPayloadInternal(null); + assert.equal(p20.account.tierMultiplier, '20x'); + assert.equal(p20.account.planName, '20x'); + assert.equal(formatAccountTierBadge(p20.account), 'Google AI Ultra · 20x'); + + const hUltra5 = backendHarness({ + userStatus: { + userTier: { id: 'g1-ultra-lite-tier', name: 'Google AI Ultra' }, + planStatus: { planInfo: { planName: 'Pro' } }, + }, + }); + const p5 = await hUltra5.buildTelemetryPayloadInternal(null); + assert.equal(p5.account.tierMultiplier, '5x'); + assert.equal(p5.account.planName, '5x'); + assert.equal(formatAccountTierBadge(p5.account), 'Google AI Ultra · 5x'); + + const hUltraNoId = backendHarness({ + userStatus: { + userTier: { name: 'Google AI Ultra' }, + planStatus: { planInfo: { planName: 'Pro' } }, + }, + }); + const pNoId = await hUltraNoId.buildTelemetryPayloadInternal(null); + assert.equal(pNoId.account.tierMultiplier, ''); + assert.equal(formatAccountTierBadge(pNoId.account), 'Google AI Ultra'); + + const hPro = backendHarness({ + userStatus: { + userTier: { id: 'g1-pro-tier', name: 'Google AI Pro' }, + planStatus: { planInfo: { planName: 'Pro' } }, + }, + }); + const pPro = await hPro.buildTelemetryPayloadInternal(null); + assert.equal(formatAccountTierBadge(pPro.account), 'Google AI Pro'); + + assert.equal( + formatAccountTierBadge({ tierName: 'Google AI Free', planName: 'Free' }), + 'Google AI Free' + ); + assert.equal( + formatAccountTierBadge({ tierName: 'Google AI', planName: 'Enterprise' }), + 'Google AI · Enterprise' + ); +}); + +test('argon_weekly capsule & CLI slot enables only when user has an Argon weekly pool and auto-hides otherwise', async () => { + const [ + { normalizeTopbarCapsuleSlots }, + { hasArgonWeeklyQuotaPool, resolveCapsuleQuotaSlotPct }, + { formatCliStatusLineCapsule }, + { getCapsuleMetricOptions, resolveCapsuleMetricPresentation }, + { setI18nLanguage }, + ] = await Promise.all([ + import('../shared/settings-normalization.mjs'), + import('../shared/telemetry-display-rules.mjs'), + import('../backend/cli-statusline-config.mjs'), + import('../src/registries/metricRegistry.js'), + import('../src/i18n/index.js'), + ]); + setI18nLanguage('zh-CN'); + + const slots = normalizeTopbarCapsuleSlots(['tps', 'argon_weekly', 'context']); + assert.deepEqual(slots, ['tps', 'argon_weekly', 'context']); + + const proQuotas = { + pools: [ + { poolKey: 'Gemini', remainingPct: 90, weeklyRemainingPct: 80 }, + { poolKey: 'Argon', poolLabel: 'Gemini 4 Argon', weeklyRemainingPct: 42 }, + { poolKey: 'Claude & GPT', remainingPct: 100, weeklyRemainingPct: 100 }, + ], + }; + const ultraQuotas = { + pools: [ + { poolKey: 'Gemini', remainingPct: 90, weeklyRemainingPct: 80 }, + { poolKey: 'Claude & GPT', remainingPct: 100, weeklyRemainingPct: 100 }, + ], + }; + + assert.equal(hasArgonWeeklyQuotaPool(proQuotas), true); + assert.equal(hasArgonWeeklyQuotaPool(ultraQuotas), false); + assert.equal(resolveCapsuleQuotaSlotPct(proQuotas, 'argon_weekly'), 42); + assert.equal(resolveCapsuleQuotaSlotPct(ultraQuotas, 'argon_weekly'), null); + + // Picker options show argon_weekly only for Argon pool users (or if already selected) + const optsPro = getCapsuleMetricOptions({ quotas: proQuotas }); + const optsUltra = getCapsuleMetricOptions({ quotas: ultraQuotas }); + const optsUltraSelected = getCapsuleMetricOptions({ + quotas: ultraQuotas, + selectedSlots: ['argon_weekly'], + }); + assert.equal(optsPro.some((o) => o.value === 'argon_weekly'), true); + assert.equal(optsUltra.some((o) => o.value === 'argon_weekly'), false); + assert.equal(optsUltraSelected.some((o) => o.value === 'argon_weekly'), true); + + // Topbar capsule presentation renders A周 42% for Pro and hides cleanly for Ultra + const presPro = resolveCapsuleMetricPresentation( + 'argon_weekly', + { hasTelemetry: true, quotas: proQuotas }, + 34.56 + ); + assert.equal(presPro.hidden, false); + assert.equal(presPro.prefix, 'A周'); + assert.equal(presPro.text, '42%'); + + const presUltra = resolveCapsuleMetricPresentation( + 'argon_weekly', + { hasTelemetry: true, quotas: ultraQuotas }, + 34.56 + ); + assert.equal(presUltra.hidden, true); + + // CLI status line renders A周 42% for Pro and omits argon_weekly cleanly for Ultra + const cliPro = formatCliStatusLineCapsule( + { hasTelemetry: true, stepCount: 3, tps: 50, usedPct: 30, quotas: proQuotas }, + { slots: ['tps', 'argon_weekly', 'context'], language: 'zh-CN', color: false } + ); + assert.match(cliPro, /A周 42%/); + + const cliUltra = formatCliStatusLineCapsule( + { hasTelemetry: true, stepCount: 3, tps: 50, usedPct: 30, quotas: ultraQuotas }, + { slots: ['tps', 'argon_weekly', 'context'], language: 'zh-CN', color: false } + ); + assert.doesNotMatch(cliUltra, /A周/); +}); diff --git a/sidecars/panel/test/quota-reservation.test.mjs b/sidecars/panel/test/quota-reservation.test.mjs index 81bbc7f..8c70bb5 100644 --- a/sidecars/panel/test/quota-reservation.test.mjs +++ b/sidecars/panel/test/quota-reservation.test.mjs @@ -2,6 +2,7 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { QR_LEASE_IDLE_EXPIRY_MS, + QR_REFUND_CONFIRM_WINDOW_MS, createQuotaReservationTracker, } from '../backend/quota-reservation.mjs'; import { normalizeFullSettings } from '../backend/settings-schema.mjs'; @@ -313,6 +314,311 @@ test('quota-reservation: avoids false positives on genuinely large steps, handle assert.ok(tracker._buckets.get(key).ratePctPerUsd > 0, 'calibrated rate preserved across reset'); }); +test('quota-reservation: persists log, calibrated rate, and active leases across plugin restarts', () => { + let storedPayload = null; + const trackerA = createQuotaReservationTracker({ + loadState: () => storedPayload, + saveState: (payload) => { + storedPayload = JSON.parse(JSON.stringify(payload)); + }, + }); + const key = 'local::u@example.com::Gemini::5h'; + + trackerA.observeBucket({ + bucketKey: key, + officialUsedPct: 4.0, + resetTimeMs: RESET_5H, + quotaFetchedAtMs: T0, + cycleCostUsd: 4.0, + poolLastActivityMs: T0, + nowMs: T0, + }); + + const t1 = T0 + 20_000; + trackerA.observeBucket({ + bucketKey: key, + officialUsedPct: 5.0, + resetTimeMs: RESET_5H, + quotaFetchedAtMs: t1, + cycleCostUsd: 4.05, + poolLastActivityMs: t1, + nowMs: t1, + }); + assert.ok(storedPayload && storedPayload.events.length === 2, 'baseline + lease persisted to disk'); + + // Simulate full plugin restart with a brand new tracker instance reading storedPayload + const trackerB = createQuotaReservationTracker({ + loadState: () => storedPayload, + saveState: (payload) => { + storedPayload = JSON.parse(JSON.stringify(payload)); + }, + }); + const snapBeforeAnyPoll = trackerB.getLogSnapshot(); + assert.equal(snapBeforeAnyPoll.count, 2, 'historical events immediately available after restart'); + assert.equal(snapBeforeAnyPoll.buckets[0].reservedPct, 1.0, 'active lease survives restart'); + assert.equal(snapBeforeAnyPoll.buckets[0].ratePctPerUsd, 1.0, 'calibrated rate survives restart'); + + // Refund arriving after restart cleanly reconciles against the hydrated lease + const t2 = t1 + 10 * 60 * 1000; + const rAfterRestart = trackerB.observeBucket({ + bucketKey: key, + officialUsedPct: 4.05, + resetTimeMs: RESET_5H, + quotaFetchedAtMs: t2, + cycleCostUsd: 4.05, + poolLastActivityMs: t1, + nowMs: t2, + }); + assert.equal(rAfterRestart.reservedPct, 0); + assert.equal(trackerB.getLogSnapshot().count, 3); +}); + +test('quota-reservation: suppresses replica ping-pong, keeps rolling median rate clean, and ignores 0% idle reset drift', () => { + const tracker = createQuotaReservationTracker(); + const key5h = 'local::u@example.com::Gemini::5h'; + const keyWk = 'local::u@example.com::Gemini::weekly'; + const keyIdle = 'local::u@example.com::Claude & GPT::5h'; + + let ts = T0; + let u5 = 13.0; + let uw = 18.0; + let c5 = 18.0; + let cw = 86.0; + + // Baseline + 8 clean steps at exact 0.6667 %/$ (5h) and 0.1667 %/$ (weekly) + tracker.observeBucket({ + bucketKey: key5h, + officialUsedPct: u5, + resetTimeMs: RESET_5H, + quotaFetchedAtMs: ts, + cycleCostUsd: c5, + poolLastActivityMs: ts, + nowMs: ts, + }); + tracker.observeBucket({ + bucketKey: keyWk, + officialUsedPct: uw, + resetTimeMs: RESET_WK, + quotaFetchedAtMs: ts, + cycleCostUsd: cw, + poolLastActivityMs: ts, + nowMs: ts, + }); + tracker.observeBucket({ + bucketKey: keyIdle, + officialUsedPct: 0, + resetTimeMs: RESET_5H, + quotaFetchedAtMs: ts, + cycleCostUsd: 0, + poolLastActivityMs: 0, + nowMs: ts, + }); + + for (let i = 0; i < 8; i += 1) { + ts += 15_000; + const dc = 0.09; + c5 += dc; + cw += dc; + u5 += dc * (2 / 3); + uw += dc * (1 / 6); + tracker.observeBucket({ + bucketKey: key5h, + officialUsedPct: u5, + resetTimeMs: RESET_5H, + quotaFetchedAtMs: ts, + cycleCostUsd: c5, + poolLastActivityMs: ts, + nowMs: ts, + }); + tracker.observeBucket({ + bucketKey: keyWk, + officialUsedPct: uw, + resetTimeMs: RESET_WK, + quotaFetchedAtMs: ts, + cycleCostUsd: cw, + poolLastActivityMs: ts, + nowMs: ts, + }); + } + + // Idle 0% pool resetTime drifts by 35 min -> silently absorbed (no spurious reset event) + tracker.observeBucket({ + bucketKey: keyIdle, + officialUsedPct: 0, + resetTimeMs: RESET_5H + 35 * 60 * 1000, + quotaFetchedAtMs: ts + 35 * 60 * 1000, + cycleCostUsd: 0, + poolLastActivityMs: 0, + nowMs: ts, + }); + assert.equal( + tracker.getLogSnapshot().events.some((e) => e.pool === 'Claude & GPT' && e.event === 'reset'), + false, + 'idle 0% pool drift must not emit reset' + ); + + // Weekly triggers a +0.9% lease on Cell B, then bounces Cell A <-> Cell B 5 times while 5h bounces +/-0.2% + ts += 10_000; + const wkBase = uw; + const wkHigh = uw + 0.9; + const rLease = tracker.observeBucket({ + bucketKey: keyWk, + officialUsedPct: wkHigh, + resetTimeMs: RESET_WK, + quotaFetchedAtMs: ts, + cycleCostUsd: cw, + poolLastActivityMs: ts, + nowMs: ts, + }); + assert.equal(rLease.reservedPct, 0.9); + assert.equal(rLease.reservedLeaseCount, 1); + + for (let i = 0; i < 5; i += 1) { + // Drop to Cell A (low replica) + ts += 10_000; + c5 += 0.06; + cw += 0.06; + const rLowWk = tracker.observeBucket({ + bucketKey: keyWk, + officialUsedPct: wkBase + (i + 1) * 0.01, + resetTimeMs: RESET_WK, + quotaFetchedAtMs: ts, + cycleCostUsd: cw, + poolLastActivityMs: ts, + nowMs: ts, + }); + assert.equal(rLowWk.reservedPct, 0, 'low replica hides lease portion so actual stays stable'); + + tracker.observeBucket({ + bucketKey: key5h, + officialUsedPct: u5 - 0.2 + i * 0.04, + resetTimeMs: RESET_5H, + quotaFetchedAtMs: ts, + cycleCostUsd: c5, + poolLastActivityMs: ts, + nowMs: ts, + }); + + // Bounce back to Cell B (high replica) + ts += 10_000; + c5 += 0.06; + cw += 0.06; + const rHighWk = tracker.observeBucket({ + bucketKey: keyWk, + officialUsedPct: wkHigh + (i + 1) * 0.02, + resetTimeMs: RESET_WK, + quotaFetchedAtMs: ts, + cycleCostUsd: cw, + poolLastActivityMs: ts, + nowMs: ts, + }); + assert.equal(rHighWk.reservedPct, 0.9, 'rebound restores same lease without duplicating'); + assert.equal(rHighWk.reservedLeaseCount, 1); + + tracker.observeBucket({ + bucketKey: key5h, + officialUsedPct: u5 + 0.08 + i * 0.08, + resetTimeMs: RESET_5H, + quotaFetchedAtMs: ts, + cycleCostUsd: c5, + poolLastActivityMs: ts, + nowMs: ts, + }); + } + + // Both rolling-median rates remain unpolluted near 0.6667 and 0.1667 + const snapMid = tracker.getLogSnapshot(); + const b5h = snapMid.buckets.find((b) => b.pool === 'Gemini' && b.win === '5h'); + const bWk = snapMid.buckets.find((b) => b.pool === 'Gemini' && b.win === 'weekly'); + assert.ok(Math.abs(b5h.ratePctPerUsd - 0.6667) < 0.02, `5h rate stays clean: ${b5h.ratePctPerUsd}`); + assert.ok(Math.abs(bWk.ratePctPerUsd - 0.1667) < 0.01, `weekly rate stays clean: ${bWk.ratePctPerUsd}`); + + // Sustained drop on weekly (stays low across >= 3 samples and >= 90s while active) confirms genuine refund + for (let i = 0; i < 4; i += 1) { + ts += Math.ceil(QR_REFUND_CONFIRM_WINDOW_MS / 3); + tracker.observeBucket({ + bucketKey: keyWk, + officialUsedPct: wkBase + 0.1, + resetTimeMs: RESET_WK, + quotaFetchedAtMs: ts, + cycleCostUsd: cw, + poolLastActivityMs: ts, + nowMs: ts, + }); + } + const bWkAfter = tracker.getLogSnapshot().buckets.find((b) => b.pool === 'Gemini' && b.win === 'weekly'); + assert.equal(bWkAfter.reservedPct, 0); + assert.equal(bWkAfter.leases, 0); +}); + +test('quota-reservation: ignores sub-epsilon shortfall noise and drops polluted v1 EMA rate on schema upgrade', () => { + // 1. Sub-epsilon rounding mismatch during normal spending must not keep stale leases alive + const tracker = createQuotaReservationTracker(); + const key = 'local::u@example.com::Gemini::5h'; + tracker.observeBucket({ + bucketKey: key, + officialUsedPct: 10.0, + resetTimeMs: RESET_5H, + quotaFetchedAtMs: T0, + cycleCostUsd: 15.0, + poolLastActivityMs: T0, + nowMs: T0, + }); + // Trigger +1.0% lease at t1 + const t1 = T0 + 15_000; + tracker.observeBucket({ + bucketKey: key, + officialUsedPct: 11.0, + resetTimeMs: RESET_5H, + quotaFetchedAtMs: t1, + cycleCostUsd: 15.0, + poolLastActivityMs: t1, + nowMs: t1, + }); + // Normal steps at ~0.666 %/$ (0.001% below cold-start 0.667) across 12 minutes -> lease expires normally + let u = 11.0; + let c = 15.0; + let now = t1; + for (let i = 0; i < 12; i += 1) { + now += 60_000; + c += 0.09; + u += 0.059; + tracker.observeBucket({ + bucketKey: key, + officialUsedPct: u, + resetTimeMs: RESET_5H, + quotaFetchedAtMs: now, + cycleCostUsd: c, + poolLastActivityMs: now, + nowMs: now, + }); + } + const snap = tracker.getLogSnapshot(); + assert.equal(snap.buckets[0].reservedPct, 0, 'normal billing does not infinitely renew stale lease'); + + // 2. Loading v1 persisted payload resets polluted EMA rate while preserving event log + const v1Payload = { + version: 1, + savedAt: new Date(T0).toISOString(), + buckets: { + [key]: { + resetTimeMs: RESET_5H, + lastQuotaTs: T0, + lastOfficialUsedPct: 30.0, + lastCycleCostUsd: 38.0, + ratePctPerUsd: 2.005, + rateSamples: 41, + activeLeases: [], + }, + }, + events: [{ ts: new Date(T0).toISOString(), pool: 'Gemini', win: '5h', event: 'normal' }], + }; + const migrated = createQuotaReservationTracker({ loadState: () => v1Payload }); + const migSnap = migrated.getLogSnapshot(); + assert.equal(migSnap.count, 1, 'v1 events preserved on upgrade'); + assert.equal(migSnap.buckets[0].ratePctPerUsd, null, 'polluted v1 rate cleared for clean recalibration'); +}); + test('experimentalQuotaReservation setting defaults false and round-trips through schema & backup', () => { const def = normalizeFullSettings({}); assert.equal(def.experimentalQuotaReservation, false); @@ -501,8 +807,11 @@ test('QuotaPoolsWidget & SettingsOtherTab render experimental reservation bar/te }, }; - // Toggle OFF: no reserved highlight + // Toggle OFF: no reserved highlight and legend hidden widget.refs.update({ data: baseData, minuteTick: 1 }); + const legendEl = widget.el.querySelector('.quota-reserve-legend'); + assert.ok(legendEl, 'quota reservation legend mounted'); + assert.equal(legendEl.hidden, true); const rsvTagsOff = widget.el.querySelectorAll('.quota-reserved-pct'); assert.equal(rsvTagsOff.length, 2); assert.equal(rsvTagsOff[0].hidden, true); @@ -510,11 +819,16 @@ test('QuotaPoolsWidget & SettingsOtherTab render experimental reservation bar/te const fillBarsOff = widget.el.querySelectorAll('.progress-fill'); assert.equal(fillBarsOff[0].style.getPropertyValue('--fill-w'), '4.1%'); - // Toggle ON: violet reserved bar segment + colored percentage tag + // Toggle ON: violet reserved bar segment + colored percentage tag + bottom solid/dashed legend widget.refs.update({ data: { ...baseData, settings: { experimentalQuotaReservation: true } }, minuteTick: 1, }); + assert.equal(legendEl.hidden, false); + assert.ok(legendEl.querySelector('.quota-legend-line.is-actual')); + assert.ok(legendEl.querySelector('.quota-legend-line.is-reserved')); + assert.match(legendEl.textContent, /实占/); + assert.match(legendEl.textContent, /预占/); const rsvTagsOn = widget.el.querySelectorAll('.quota-reserved-pct'); assert.equal(rsvTagsOn[0].hidden, false); assert.equal(rsvTagsOn[0].textContent, '预占 1.0%'); @@ -526,8 +840,10 @@ test('QuotaPoolsWidget & SettingsOtherTab render experimental reservation bar/te assert.equal(fillBarsOn[0].style.getPropertyValue('--fill-w'), '3.1%'); assert.equal(rsvBarsOn[0].style.getPropertyValue('--reserved-w'), '1%'); assert.equal(rsvBarsOn[0].classList.contains('is-active'), true); + assert.equal(rsvBarsOn[0].classList.contains('has-sep'), true); assert.equal(fillBarsOn[1].style.getPropertyValue('--fill-w'), '15.7%'); assert.equal(rsvBarsOn[1].style.getPropertyValue('--reserved-w'), '0.5%'); + assert.equal(rsvBarsOn[1].classList.contains('has-sep'), true); // SettingsOtherTab renders experimental badge and persists toggle click const othTab = SettingsOtherTab({ onLayoutChange: () => {} }); diff --git a/sidecars/panel/test/step-anomalies.test.mjs b/sidecars/panel/test/step-anomalies.test.mjs index 8c94862..e2411da 100644 --- a/sidecars/panel/test/step-anomalies.test.mjs +++ b/sidecars/panel/test/step-anomalies.test.mjs @@ -857,7 +857,9 @@ test('StepsDetailView total summary cards, session anomaly strip, click-to-filte metric: 'tps', }); const lineAnomalyDots = lineChart.el.querySelectorAll('.sstep-anomaly-dot'); - assert.equal(lineAnomalyDots.length, 1, 'Line chart renders anomaly ring marker even when steps > 64'); + assert.equal(lineAnomalyDots.length, 1, 'Line chart renders bottom rug tick marker even when steps > 64'); + assert.equal(lineAnomalyDots[0].tagName.toLowerCase(), 'line'); + assert.equal(lineAnomalyDots[0].classList.contains('sstep-anomaly-tick'), true); assert.equal(lineAnomalyDots[0].classList.contains('is-danger'), true); fitChart = createModelFitChart(); @@ -868,7 +870,8 @@ test('StepsDetailView total summary cards, session anomaly strip, click-to-filte metric: 'tps', }); const fitAnomalyDots = fitChart.el.querySelectorAll('.sstep-scatter-dot.is-anomaly'); - assert.equal(fitAnomalyDots.length, 1, 'Fit scatter chart renders anomaly ring overlay without overdraw drop'); + assert.equal(fitAnomalyDots.length, 1, 'Fit scatter chart renders solid matching-size anomaly dot without overdraw drop'); + assert.equal(fitAnomalyDots[0].getAttribute('r'), '2.1'); assert.equal(fitAnomalyDots[0].classList.contains('is-danger'), true); assert.ok(fitChart.el.querySelector('.trend-tip-anomaly'), 'Fit chart tooltip mounts linked anomaly diagnostic row'); } finally { diff --git a/sidecars/panel/test/window-bridge.test.mjs b/sidecars/panel/test/window-bridge.test.mjs index 4d42fea..ee78cb0 100644 --- a/sidecars/panel/test/window-bridge.test.mjs +++ b/sidecars/panel/test/window-bridge.test.mjs @@ -1854,8 +1854,8 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro assert.ok(previewCellSubs.includes('有效 23/24 步'), 'Preview Avg TPS card shows populated valid sample ratio'); assert.equal( overviewPreviewHostEl.children[2].querySelector('.panel-meta').textContent, - 'Google AI Ultra · Pro', - 'Preview quota badge matches real tier · plan format' + 'Google AI Ultra · 5x', + 'Preview quota badge displays Ultra 5x multiplier instead of legacy Pro' ); const [ovModWrap, ovMetricWrap] = sec2.querySelectorAll('.editable-slot-wrap');