diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index 126e59a..8782357 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -1499,6 +1499,13 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ // Consumption View 'cons.rangeCycle': '周期', + 'cons.cyclePoolAll': '全部池', + 'cons.cyclePoolAllShort': '全部', + 'cons.cyclePoolAria': '当前周期配额池筛选', + 'cons.cyclePoolRemMeta': '剩 {pct}', + 'cons.currentCycle': '当前周期', + 'cons.cycleFallbackWeek': '本周', + 'cons.cycleFallbackWeekTip': '未获取官方周限重置时间,暂按自然本周一统计', 'cons.rangeToday': '今天', 'cons.range24h': '1天', 'cons.range7d': '7天', @@ -2398,6 +2405,13 @@ const I18N_MESSAGES_EN_US = Object.freeze({ // Consumption View 'cons.rangeCycle': 'Cycle', + 'cons.cyclePoolAll': 'All Pools', + 'cons.cyclePoolAllShort': 'All', + 'cons.cyclePoolAria': 'Filter current cycle by quota pool', + 'cons.cyclePoolRemMeta': '{pct} left', + 'cons.currentCycle': 'Current Cycle', + 'cons.cycleFallbackWeek': 'This Week', + 'cons.cycleFallbackWeekTip': 'Official weekly reset time unavailable; using calendar week from Monday', 'cons.rangeToday': 'Today', 'cons.range24h': '24h', 'cons.range7d': '7d', @@ -4153,17 +4167,34 @@ function formatCnyApprox(usdAmount, rate = 7.2) { function formatDateSpanBadge(startMs, endMs) { const s = startMs && Number.isFinite(startMs) ? new Date(startMs) : new Date(); const e = endMs && Number.isFinite(endMs) ? new Date(endMs) : new Date(); + const sameYear = s.getFullYear() === e.getFullYear(); + const sameMonth = sameYear && s.getMonth() === e.getMonth(); + const sameDay = sameMonth && s.getDate() === e.getDate(); + if (isEnglishLocale()) { const sMon = EN_MONTH_SHORT[s.getMonth()] || ''; const eMon = EN_MONTH_SHORT[e.getMonth()] || ''; - if (s.getFullYear() !== e.getFullYear()) { + if (!sameYear) { return `${sMon} ${s.getDate()}, ${s.getFullYear()} ~ ${eMon} ${e.getDate()}, ${e.getFullYear()}`; } + if (sameDay) { + return `${sMon} ${s.getDate()}`; + } + if (sameMonth) { + return `${sMon} ${s.getDate()} ~ ${e.getDate()}`; + } return `${sMon} ${s.getDate()} ~ ${eMon} ${e.getDate()}`; } - if (s.getFullYear() !== e.getFullYear()) { + + if (!sameYear) { return `${s.getFullYear()}年${s.getMonth() + 1}月${s.getDate()}日 ~ ${e.getFullYear()}年${e.getMonth() + 1}月${e.getDate()}日`; } + if (sameDay) { + return `${s.getMonth() + 1}月${s.getDate()}日`; + } + if (sameMonth) { + return `${s.getMonth() + 1}月${s.getDate()}日 ~ ${e.getDate()}日`; + } return `${s.getMonth() + 1}月${s.getDate()}日 ~ ${e.getMonth() + 1}月${e.getDate()}日`; } @@ -6909,10 +6940,18 @@ function formatExportDate(ms) { function resolveLocalizedRangeLabel(range, en) { const r = range || {}; const key = String(r.key || '').trim().toLowerCase(); + const poolSuffix = + key === 'cycle' && r.pool && r.pool !== 'all' ? ` · ${r.poolLabel || r.pool}` : ''; if (en) { - return RANGE_LABELS_EN[key] || r.label || key || 'All Time'; + const baseEn = + key === 'cycle' && r.isFallbackWeek + ? 'This Week' + : RANGE_LABELS_EN[key] || r.label || key || 'All Time'; + return `${baseEn}${poolSuffix}`; } - return r.label || RANGE_LABELS_ZH[key] || key || '全部时间'; + if (r.label) return r.label; + const baseZh = RANGE_LABELS_ZH[key] || key || '全部时间'; + return `${baseZh}${poolSuffix}`; } function resolveRangeSpanNote(range) { @@ -8989,7 +9028,7 @@ return { revealExportedFile, exportTextFileWithFeedback, exportBinaryFileWithFee })(); // --- src/store/telemetryStore.js --- -const { extractHostRouteCascadeId, telemetryStore, clearConsumptionRangeCache, clearConversationViewCache, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_SLOTS, DEFAULT_CLIENT_CONTEXT_AGENT_MODE, CLIENT_CLI_STATUSLINE_PRESETS, DEFAULT_CLIENT_CLI_STATUSLINE_SLOTS, CLIENT_OVERVIEW_MODULE_KEYS, DEFAULT_CLIENT_OVERVIEW_MODULES, DEFAULT_CLIENT_HOVER_MODULES, CLIENT_OVERVIEW_METRIC_KEYS, DEFAULT_CLIENT_OVERVIEW_METRICS, CLIENT_STEP_COLUMN_KEYS, DEFAULT_CLIENT_STEP_COLUMNS, DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT, MIN_CLIENT_POPOVER_WIDTH, MAX_CLIENT_POPOVER_WIDTH, DEFAULT_CLIENT_POPOVER_WIDTH, parseClientStepTokenComboSegments, normalizeClientStepTokenComboFormat, normalizeClientPopoverWidthMode, normalizeClientPopoverWidth, normalizeClientModelDisplayMode, normalizeClientTopbarSlots, normalizeClientContextAgentMode, normalizeClientExperimentalQuotaReservation, normalizeClientCliStatusLineSlots, getDefaultCtxInspectorAgentId, resolveOverlayCtxInspectorAgentId, resolveEffectiveClientCliStatusLineSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, resetTelemetryForEndpointSwitch, fetchTelemetry, selectConversation, selectConsumptionTimeRange, prefetchConsumptionPresets, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerCliStatusLineAction, fetchSessionMigrationCatalog, fetchQuotaReservationLog, executeSessionMigration, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform } = (() => { +const { extractHostRouteCascadeId, telemetryStore, clearConsumptionRangeCache, clearConversationViewCache, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_SLOTS, DEFAULT_CLIENT_CONTEXT_AGENT_MODE, CLIENT_CLI_STATUSLINE_PRESETS, DEFAULT_CLIENT_CLI_STATUSLINE_SLOTS, CLIENT_OVERVIEW_MODULE_KEYS, DEFAULT_CLIENT_OVERVIEW_MODULES, DEFAULT_CLIENT_HOVER_MODULES, CLIENT_OVERVIEW_METRIC_KEYS, DEFAULT_CLIENT_OVERVIEW_METRICS, CLIENT_STEP_COLUMN_KEYS, DEFAULT_CLIENT_STEP_COLUMNS, DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT, MIN_CLIENT_POPOVER_WIDTH, MAX_CLIENT_POPOVER_WIDTH, DEFAULT_CLIENT_POPOVER_WIDTH, parseClientStepTokenComboSegments, normalizeClientStepTokenComboFormat, normalizeClientPopoverWidthMode, normalizeClientPopoverWidth, normalizeClientModelDisplayMode, normalizeClientTopbarSlots, normalizeClientContextAgentMode, normalizeClientExperimentalQuotaReservation, normalizeClientCliStatusLineSlots, getDefaultCtxInspectorAgentId, resolveOverlayCtxInspectorAgentId, resolveEffectiveClientCliStatusLineSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, resetTelemetryForEndpointSwitch, fetchTelemetry, selectConversation, selectConsumptionTimeRange, selectConsumptionCyclePool, prefetchConsumptionPresets, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerCliStatusLineAction, fetchSessionMigrationCatalog, fetchQuotaReservationLog, executeSessionMigration, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform } = (() => { /** * @fileoverview Reactive telemetry store with async non-overlapping poll scheduler * and granular slice updates. @@ -9076,6 +9115,7 @@ const telemetryStore = createReactiveStore({ selectedConversationId: initialConversationId, hostRouteConversationId: extractHostRouteCascadeId(), selectedTimeRange: 'today', + selectedCyclePool: 'all', customStartMs: Date.now() - 24 * 3600 * 1000, customEndMs: Date.now(), syncState: 'idle', // 'idle' | 'syncing' | 'synced' | 'error' @@ -9097,7 +9137,7 @@ let inFlightTelemetryPoll = null; let inFlightPresetsPrefetch = null; let lastPrefetchedUsageRevision = 0; let consumptionCacheScopeSig = ''; -const MAX_CONSUMPTION_RANGE_CACHE = 12; +const MAX_CONSUMPTION_RANGE_CACHE = 24; const MAX_CONVERSATION_VIEW_CACHE = 12; const CONSUMPTION_PRESET_KEYS = ['cycle', 'today', '24h', '7d', '14d', '30d', 'all']; const consumptionRangeCache = new Map(); @@ -9119,11 +9159,19 @@ const TELEMETRY_RECOMPUTE_SETTING_KEYS = new Set([ 'enableWindowOverlay', ]); -function makeConsumptionRangeCacheKey(range, customStartMs = 0, customEndMs = 0) { +function makeConsumptionRangeCacheKey( + range, + customStartMs = 0, + customEndMs = 0, + cyclePool = 'all' +) { const key = String(range || 'all'); if (key === 'custom') { return `custom:${Number(customStartMs || 0)}:${Number(customEndMs || 0)}`; } + if (key === 'cycle' && cyclePool && cyclePool !== 'all') { + return `cycle:${String(cyclePool)}`; + } return key; } @@ -9150,6 +9198,17 @@ function buildConsumptionScopeSig(payload) { return `${String(ep.id || LOCAL_ENDPOINT_ID)}|${String(acct.status || '')}|${String(acct.email || acct.name || '').toLowerCase()}|${String(set.weeklyLimitMode || '')}|${String(cloud.catalogVersion || '')}`; } +function reconcileSelectedCyclePool(payload) { + const curPool = telemetryStore.getState().selectedCyclePool || 'all'; + if (curPool === 'all') return; + const pools = payload?.quotas?.pools; + if (!Array.isArray(pools) || pools.length === 0) return; + const exists = pools.some((p) => String(p?.poolKey || p?.family || '') === curPool); + if (!exists) { + telemetryStore.setState({ selectedCyclePool: 'all' }); + } +} + function syncConsumptionCacheScope(payload) { const nextSig = buildConsumptionScopeSig(payload); if (!nextSig) return; @@ -9158,6 +9217,7 @@ function syncConsumptionCacheScope(payload) { clearConversationViewCache(); } consumptionCacheScopeSig = nextSig; + reconcileSelectedCyclePool(payload); } function recordConversationViewToCache(payload) { @@ -9273,14 +9333,19 @@ function putConsumptionRangeCacheEntry(cacheKey, entry) { function recordConsumptionSliceToCache( cons, modelBreakdown, - { customStartMs = 0, customEndMs = 0, usageRevision = 0 } = {} + { customStartMs = 0, customEndMs = 0, cyclePool = 'all', usageRevision = 0 } = {} ) { const rangeKey = String(cons?.selectedRange?.key || ''); if (!rangeKey) return; + const resolvedPool = + rangeKey === 'cycle' + ? String(cons?.selectedRange?.pool || cyclePool || 'all') + : 'all'; const cacheKey = makeConsumptionRangeCacheKey( rangeKey, rangeKey === 'custom' ? customStartMs || cons.selectedRange?.startMs || 0 : 0, - rangeKey === 'custom' ? customEndMs || cons.selectedRange?.endMs || 0 : 0 + rangeKey === 'custom' ? customEndMs || cons.selectedRange?.endMs || 0 : 0, + resolvedPool ); putConsumptionRangeCacheEntry(cacheKey, { revision: Number(cons.revision ?? usageRevision ?? 0), @@ -9828,11 +9893,14 @@ function isEquivalentTelemetry(prev, next) { } } - // 5. 比对消费统计所选时间区间、当前会话累计消费与账号全局累计消费 + // 5. 比对消费统计所选时间区间、当前会话累计消费和账号全局累计消费 const pRange = prev.consumption?.selectedRange; const nRange = next.consumption?.selectedRange; if (pRange?.key !== nRange?.key) return false; - if (nRange?.key === 'custom') { + if ((pRange?.pool || 'all') !== (nRange?.pool || 'all')) return false; + if ((pRange?.label || '') !== (nRange?.label || '')) return false; + if (Boolean(pRange?.isFallbackWeek) !== Boolean(nRange?.isFallbackWeek)) return false; + if (nRange?.key === 'custom' || nRange?.key === 'cycle') { if (pRange?.startMs !== nRange?.startMs || pRange?.endMs !== nRange?.endMs) return false; } @@ -10159,6 +10227,13 @@ async function fetchTelemetry({ force = false } = {}) { const params = new URLSearchParams(); if (effectiveConvId) params.set('conversationId', effectiveConvId); if (current.selectedTimeRange) params.set('range', current.selectedTimeRange); + if ( + current.selectedTimeRange === 'cycle' && + current.selectedCyclePool && + current.selectedCyclePool !== 'all' + ) { + params.set('pool', current.selectedCyclePool); + } if (current.selectedTimeRange === 'custom') { if (current.customStartMs > 0) params.set('startMs', String(current.customStartMs)); if (current.customEndMs > 0) params.set('endMs', String(current.customEndMs)); @@ -10206,6 +10281,7 @@ async function requestTelemetry(params, force) { const reqSeq = ++latestRequestSeq; const reqSettingsRev = settingsRevision; const reqRange = String(params.get('range') || ''); + const reqPool = String(params.get('pool') || 'all'); const reqStartMs = Number(params.get('startMs') || 0); const reqEndMs = Number(params.get('endMs') || 0); const startMs = Date.now(); @@ -10265,14 +10341,17 @@ async function requestTelemetry(params, force) { recordConsumptionSliceToCache(resolvedPayload.consumption, resolvedPayload.modelBreakdown, { customStartMs: reqStartMs, customEndMs: reqEndMs, + cyclePool: reqPool, }); } const latestSt = telemetryStore.getState(); const incomingRev = Number(resolvedPayload?.consumption?.revision || 0); + const activePoolPref = latestSt.selectedCyclePool || 'all'; const matchesCurrentRange = !reqRange || (reqRange === latestSt.selectedTimeRange && + (reqRange !== 'cycle' || reqPool === activePoolPref) && (reqRange !== 'custom' || (reqStartMs === Number(latestSt.customStartMs || 0) && reqEndMs === Number(latestSt.customEndMs || 0)))); @@ -10284,7 +10363,8 @@ async function requestTelemetry(params, force) { const activeKey = makeConsumptionRangeCacheKey( latestSt.selectedTimeRange, latestSt.customStartMs, - latestSt.customEndMs + latestSt.customEndMs, + activePoolPref ); const cachedActive = consumptionRangeCache.get(activeKey); if (cachedActive) { @@ -10293,7 +10373,9 @@ async function requestTelemetry(params, force) { needsSilentRangeRevalidate = true; } } else if ( - latestSt.telemetry?.consumption?.selectedRange?.key === latestSt.selectedTimeRange + latestSt.telemetry?.consumption?.selectedRange?.key === latestSt.selectedTimeRange && + (latestSt.selectedTimeRange !== 'cycle' || + (latestSt.telemetry?.consumption?.selectedRange?.pool || 'all') === activePoolPref) ) { resolvedPayload = { ...resolvedPayload, @@ -10345,6 +10427,7 @@ async function requestTelemetry(params, force) { range: latestSt.selectedTimeRange, customStartMs: latestSt.customStartMs, customEndMs: latestSt.customEndMs, + cyclePool: latestSt.selectedCyclePool || 'all', }); } return resolvedPayload; @@ -10370,15 +10453,20 @@ async function fetchConsumptionRangeSlice({ range, customStartMs = 0, customEndMs = 0, + cyclePool = 'all', } = {}) { const reqEpoch = endpointSwitchEpoch; const reqSeq = ++latestConsumptionReqSeq; const targetRange = String(range || 'today'); + const targetPool = targetRange === 'cycle' ? String(cyclePool || 'all') : 'all'; const current = telemetryStore.getState(); const effectiveConvId = current.selectedConversationId || current.hostRouteConversationId || ''; const params = new URLSearchParams(); if (effectiveConvId) params.set('conversationId', effectiveConvId); params.set('range', targetRange); + if (targetRange === 'cycle' && targetPool !== 'all') { + params.set('pool', targetPool); + } if (targetRange === 'custom') { if (customStartMs > 0) params.set('startMs', String(customStartMs)); if (customEndMs > 0) params.set('endMs', String(customEndMs)); @@ -10397,6 +10485,7 @@ async function fetchConsumptionRangeSlice({ recordConsumptionSliceToCache(payload.consumption, payload.modelBreakdown, { customStartMs, customEndMs, + cyclePool: targetPool, usageRevision: usageRev, }); if (reqSeq !== latestConsumptionReqSeq) return payload; @@ -10404,6 +10493,7 @@ async function fetchConsumptionRangeSlice({ const latestSt = telemetryStore.getState(); const stillMatches = latestSt.selectedTimeRange === targetRange && + (targetRange !== 'cycle' || (latestSt.selectedCyclePool || 'all') === targetPool) && (targetRange !== 'custom' || (Number(latestSt.customStartMs || 0) === Number(customStartMs || 0) && Number(latestSt.customEndMs || 0) === Number(customEndMs || 0))); @@ -10509,6 +10599,13 @@ async function selectConversation( const params = new URLSearchParams(); if (effectiveConvId) params.set('conversationId', effectiveConvId); if (current.selectedTimeRange) params.set('range', current.selectedTimeRange); + if ( + current.selectedTimeRange === 'cycle' && + current.selectedCyclePool && + current.selectedCyclePool !== 'all' + ) { + params.set('pool', current.selectedCyclePool); + } if (current.selectedTimeRange === 'custom') { if (current.customStartMs > 0) params.set('startMs', String(current.customStartMs)); if (current.customEndMs > 0) params.set('endMs', String(current.customEndMs)); @@ -10615,7 +10712,7 @@ async function selectConversation( */ function selectConsumptionTimeRange( nextRange, - { customStartMs = undefined, customEndMs = undefined } = {} + { customStartMs = undefined, customEndMs = undefined, cyclePool = undefined } = {} ) { const targetRange = String(nextRange || 'today'); const prevSt = telemetryStore.getState(); @@ -10627,14 +10724,26 @@ function selectConsumptionTimeRange( targetRange === 'custom' ? Number(customEndMs !== undefined ? customEndMs : prevSt.customEndMs || 0) : prevSt.customEndMs; + const nextCyclePool = + targetRange === 'cycle' + ? String(cyclePool !== undefined ? cyclePool || 'all' : prevSt.selectedCyclePool || 'all') + : prevSt.selectedCyclePool || 'all'; const statePatch = { selectedTimeRange: targetRange }; + if (cyclePool !== undefined) { + statePatch.selectedCyclePool = nextCyclePool; + } if (targetRange === 'custom') { statePatch.customStartMs = nextStartMs; statePatch.customEndMs = nextEndMs; } - const cacheKey = makeConsumptionRangeCacheKey(targetRange, nextStartMs, nextEndMs); + const cacheKey = makeConsumptionRangeCacheKey( + targetRange, + nextStartMs, + nextEndMs, + targetRange === 'cycle' ? nextCyclePool : 'all' + ); const cached = consumptionRangeCache.get(cacheKey); const prevTelemetry = prevSt.telemetry; @@ -10653,6 +10762,7 @@ function selectConsumptionTimeRange( range: targetRange, customStartMs: nextStartMs, customEndMs: nextEndMs, + cyclePool: nextCyclePool, }); } @@ -10661,9 +10771,14 @@ function selectConsumptionTimeRange( range: targetRange, customStartMs: nextStartMs, customEndMs: nextEndMs, + cyclePool: nextCyclePool, }); } +function selectConsumptionCyclePool(nextPool = 'all') { + return selectConsumptionTimeRange('cycle', { cyclePool: String(nextPool || 'all') }); +} + /** * 仅在进入「用量统计」视图时触发一次静默后台预取,拉齐全部 7 个预设区间到前端缓存以实现 0ms 瞬切。 */ @@ -11338,7 +11453,7 @@ function isMacHostPlatform(telemetry) { } return false; } -return { extractHostRouteCascadeId, telemetryStore, clearConsumptionRangeCache, clearConversationViewCache, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_SLOTS, DEFAULT_CLIENT_CONTEXT_AGENT_MODE, CLIENT_CLI_STATUSLINE_PRESETS, DEFAULT_CLIENT_CLI_STATUSLINE_SLOTS, CLIENT_OVERVIEW_MODULE_KEYS, DEFAULT_CLIENT_OVERVIEW_MODULES, DEFAULT_CLIENT_HOVER_MODULES, CLIENT_OVERVIEW_METRIC_KEYS, DEFAULT_CLIENT_OVERVIEW_METRICS, CLIENT_STEP_COLUMN_KEYS, DEFAULT_CLIENT_STEP_COLUMNS, DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT, MIN_CLIENT_POPOVER_WIDTH, MAX_CLIENT_POPOVER_WIDTH, DEFAULT_CLIENT_POPOVER_WIDTH, parseClientStepTokenComboSegments, normalizeClientStepTokenComboFormat, normalizeClientPopoverWidthMode, normalizeClientPopoverWidth, normalizeClientModelDisplayMode, normalizeClientTopbarSlots, normalizeClientContextAgentMode, normalizeClientExperimentalQuotaReservation, normalizeClientCliStatusLineSlots, getDefaultCtxInspectorAgentId, resolveOverlayCtxInspectorAgentId, resolveEffectiveClientCliStatusLineSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, resetTelemetryForEndpointSwitch, fetchTelemetry, selectConversation, selectConsumptionTimeRange, prefetchConsumptionPresets, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerCliStatusLineAction, fetchSessionMigrationCatalog, fetchQuotaReservationLog, executeSessionMigration, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform }; +return { extractHostRouteCascadeId, telemetryStore, clearConsumptionRangeCache, clearConversationViewCache, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_SLOTS, DEFAULT_CLIENT_CONTEXT_AGENT_MODE, CLIENT_CLI_STATUSLINE_PRESETS, DEFAULT_CLIENT_CLI_STATUSLINE_SLOTS, CLIENT_OVERVIEW_MODULE_KEYS, DEFAULT_CLIENT_OVERVIEW_MODULES, DEFAULT_CLIENT_HOVER_MODULES, CLIENT_OVERVIEW_METRIC_KEYS, DEFAULT_CLIENT_OVERVIEW_METRICS, CLIENT_STEP_COLUMN_KEYS, DEFAULT_CLIENT_STEP_COLUMNS, DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT, MIN_CLIENT_POPOVER_WIDTH, MAX_CLIENT_POPOVER_WIDTH, DEFAULT_CLIENT_POPOVER_WIDTH, parseClientStepTokenComboSegments, normalizeClientStepTokenComboFormat, normalizeClientPopoverWidthMode, normalizeClientPopoverWidth, normalizeClientModelDisplayMode, normalizeClientTopbarSlots, normalizeClientContextAgentMode, normalizeClientExperimentalQuotaReservation, normalizeClientCliStatusLineSlots, getDefaultCtxInspectorAgentId, resolveOverlayCtxInspectorAgentId, resolveEffectiveClientCliStatusLineSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, resetTelemetryForEndpointSwitch, fetchTelemetry, selectConversation, selectConsumptionTimeRange, selectConsumptionCyclePool, prefetchConsumptionPresets, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerCliStatusLineAction, fetchSessionMigrationCatalog, fetchQuotaReservationLog, executeSessionMigration, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform }; })(); // --- src/components/ui/TopLongPillNav.js --- @@ -12044,8 +12159,8 @@ const CustomSelect = defineComponent({ const fallbackText = modelValue ? `${placeholder} (${String(modelValue).slice(0, 8)})` : placeholder; - labelText = selectedOpt ? selectedOpt.label : fallbackText; - titleText = labelText; + labelText = selectedOpt ? selectedOpt.shortLabel || selectedOpt.label : fallbackText; + titleText = selectedOpt ? selectedOpt.title || selectedOpt.label : fallbackText; } patchText(triggerLabel, labelText); @@ -30029,6 +30144,86 @@ function ceilToEndOfMinuteMs(ms) { return d.getTime(); } +function formatCyclePoolShortLabel(poolKey, poolLabel) { + if (poolKey === 'Argon') return 'Argon'; + if (poolKey === 'Carbon') return 'Carbon'; + if (poolKey === 'Claude & GPT') return 'Claude/GPT'; + return poolLabel || poolKey; +} + +function buildCyclePoolSelectOptions(pools, isCustomWeeklyMode = false) { + const list = Array.isArray(pools) ? pools : []; + let sumCycleCost = 0; + let hasAnyCycleCost = false; + for (let i = 0; i < list.length; i++) { + const c = Number(list[i]?.cycleWeekly?.costUsd); + if (Number.isFinite(c) && c >= 0 && list[i]?.cycleWeekly) { + sumCycleCost += c; + hasAnyCycleCost = true; + } + } + const allLabel = t('cons.cyclePoolAll'); + const opts = [ + { + value: 'all', + label: allLabel, + shortLabel: t('cons.cyclePoolAllShort'), + meta: !isCustomWeeklyMode && hasAnyCycleCost ? formatUsd(sumCycleCost) : '', + title: allLabel, + }, + ]; + for (let i = 0; i < list.length; i++) { + const p = list[i]; + const key = String(p?.poolKey || p?.family || '').trim(); + if (!key || key === 'Unknown') continue; + const label = String(p?.poolLabel || key).trim(); + const shortLabel = formatCyclePoolShortLabel(key, label); + const metaParts = []; + if ( + !isCustomWeeklyMode && + p?.weeklyRemainingPct != null && + Number.isFinite(Number(p.weeklyRemainingPct)) + ) { + metaParts.push( + t('cons.cyclePoolRemMeta', { + pct: formatPctNumber(p.weeklyRemainingPct, { withSymbol: true }), + }) + ); + } + if (!isCustomWeeklyMode && p?.cycleWeekly && Number.isFinite(Number(p.cycleWeekly.costUsd))) { + metaParts.push(formatUsd(p.cycleWeekly.costUsd)); + } + const meta = metaParts.join(' · '); + opts.push({ + value: key, + label, + shortLabel, + meta, + title: meta ? `${label} (${meta})` : label, + }); + } + return opts; +} + +function formatCycleMinuteSpanTip(startMs, endMs, isFallbackWeek = false) { + const s = Number(startMs); + const e = Number(endMs); + if (!(s > 0 && e > 0 && Number.isFinite(s) && Number.isFinite(e))) return null; + const sd = new Date(s); + const ed = new Date(e); + const pad2 = (n) => String(n).padStart(2, '0'); + const sTime = `${pad2(sd.getHours())}:${pad2(sd.getMinutes())}`; + const eTime = `${pad2(ed.getHours())}:${pad2(ed.getMinutes())}`; + const sameDay = + sd.getFullYear() === ed.getFullYear() && + sd.getMonth() === ed.getMonth() && + sd.getDate() === ed.getDate(); + const sDate = `${sd.getMonth() + 1}/${pad2(sd.getDate())}`; + const eDate = `${ed.getMonth() + 1}/${pad2(ed.getDate())}`; + const base = sameDay ? `${sDate} ${sTime} ~ ${eTime}` : `${sDate} ${sTime} ~ ${eDate} ${eTime}`; + return isFallbackWeek ? `${base} · ${t('cons.cycleFallbackWeekTip')}` : base; +} + const ConsumptionView = defineComponent({ name: 'ConsumptionView', setup({ onCleanup }) { @@ -30134,6 +30329,16 @@ const ConsumptionView = defineComponent({ // --- Section 1: 用量概览矩阵 (上层 3 列核心总量 + 下层 3 列新输入/缓存读取/输出拆分 + 底部 4 段比例条) --- const dateSpanBadge = h('span', { className: 'cons-badge text-mono', text: '-- ~ --' }); + const cyclePoolSelect = CustomSelect({ + className: 'cons-cycle-pool-select', + modelValue: telemetryStore.getState().selectedCyclePool || 'all', + options: buildCyclePoolSelectOptions([]), + onUpdateModelValue: (nextPool) => { + selectConsumptionCyclePool(nextPool || 'all'); + }, + }); + patchAttr(cyclePoolSelect.el, 'hidden', true); + patchAttr(cyclePoolSelect.refs.triggerBtn, 'aria-label', t('cons.cyclePoolAria')); const heroTotalTokens = h('strong', { className: 'cons-hero-num text-mono', text: '0' }); const heroTotalCalls = h('span', { className: 'text-muted text-mono', style: 'font-size: var(--fs-md);', text: t('cons.callsCount', { calls: 0 }) }); const heroCostUsd = h('strong', { className: 'cons-hero-cost text-mono', text: '$0.00' }); @@ -30271,8 +30476,9 @@ const ConsumptionView = defineComponent({ const overviewPanel = h('section', { className: 'panel' }, [ h('div', { className: 'panel-header cons-overview-head' }, [ - h('span', { className: 'panel-title' }, [ + h('span', { className: 'panel-title cons-overview-title' }, [ dateSpanBadge, + cyclePoolSelect.el, ]), h('div', { className: 'cons-overview-controls' }, [ timeFilterSwitch.el, @@ -31725,7 +31931,7 @@ const ConsumptionView = defineComponent({ const cons = slice.consumption || {}; const rangeInfo = cons.selectedRange || {}; - // 始终在 0ms 同步顶部时间段滑块与自定义日期条显隐,给予即刻交互反馈 + // 始终在 0ms 同步顶部时间段滑块、周期池选择器及自定义日期条显隐,给予即刻交互反馈 timeFilterSwitch.setValue(slice.range); patchAttr(customRangeBar, 'hidden', slice.range !== 'custom'); if (!hasUncommittedCustomDraft) { @@ -31735,17 +31941,45 @@ const ConsumptionView = defineComponent({ endPicker.setValue(draftEndMs); } + const isCustomWeeklyMode = + slice.weeklyLimitMode === 'custom_tokens' || slice.weeklyLimitMode === 'custom_cost'; + const cyclePoolOptions = + slice.range === 'cycle' + ? buildCyclePoolSelectOptions(slice.quotaPools, isCustomWeeklyMode) + : []; + const activePoolFilter = slice.range === 'cycle' ? slice.cyclePool || 'all' : 'all'; + const showCyclePoolSelect = slice.range === 'cycle' && cyclePoolOptions.length > 2; + if (!showCyclePoolSelect) { + cyclePoolSelect.close?.(); + patchAttr(cyclePoolSelect.el, 'hidden', true); + } else { + cyclePoolSelect.setProps({ + modelValue: activePoolFilter, + options: cyclePoolOptions, + }); + patchAttr(cyclePoolSelect.el, 'hidden', false); + } + // 极少数缓存未命中时(如自定义新区间或进页瞬间抢点),跳过用旧趋势/模型跑无效半更新重绘,待几毫秒后单帧原子绘制 - if (rangeInfo.key && slice.range && rangeInfo.key !== slice.range) { + const payloadPool = rangeInfo.key === 'cycle' ? rangeInfo.pool || 'all' : 'all'; + if ( + (rangeInfo.key && slice.range && rangeInfo.key !== slice.range) || + (slice.range === 'cycle' && rangeInfo.pool && payloadPool !== activePoolFilter) + ) { return; } const preset = - slice.range !== 'custom' && cons.presets?.[slice.range] + slice.range !== 'custom' && + !(slice.range === 'cycle' && activePoolFilter !== 'all') && + cons.presets?.[slice.range] ? cons.presets[slice.range] : null; const acct = cons.account || preset?.account || {}; const dateSpan = formatDateSpanBadge(rangeInfo.startMs, rangeInfo.endMs); + const cycleOptionsSig = showCyclePoolSelect + ? cyclePoolOptions.map((o) => `${o.value}:${o.label}:${o.meta || ''}`).join('|') + : ''; const now = new Date(); const currentMonthIdx = now.getMonth(); const monthlyYear = cons.monthlyYear || now.getFullYear(); @@ -31753,6 +31987,9 @@ const ConsumptionView = defineComponent({ const renderTuple = [ locale, slice.range, + activePoolFilter, + cycleOptionsSig, + Boolean(rangeInfo.isFallbackWeek), slice.customStartMs, slice.customEndMs, slice.modelDisplayMode, @@ -31773,13 +32010,36 @@ const ConsumptionView = defineComponent({ cons.monthlySeries, ]; if (isSameRenderTuple(lastRenderedTuple, renderTuple)) return; - drawConsumptionData(slice, { cons, preset, acct, rangeInfo, dateSpan, currentMonthIdx, monthlyYear }); + drawConsumptionData(slice, { + cons, + preset, + acct, + rangeInfo, + activePoolFilter, + dateSpan, + currentMonthIdx, + monthlyYear, + }); lastRenderedTuple = renderTuple; } - function drawConsumptionData(slice, { cons, preset, acct, rangeInfo, dateSpan, currentMonthIdx, monthlyYear }) { - // 1. 同步用量概览矩阵与顶部 4 段比例条 + function drawConsumptionData( + slice, + { cons, preset, acct, rangeInfo, activePoolFilter, dateSpan, currentMonthIdx, monthlyYear } + ) { + // 1. 同步用量概览矩阵及顶部 4 段比例条 patchText(dateSpanBadge, dateSpan); + patchAttr( + dateSpanBadge, + 'title', + slice.range === 'cycle' + ? formatCycleMinuteSpanTip( + rangeInfo.startMs, + rangeInfo.endMs, + Boolean(rangeInfo.isFallbackWeek) + ) + : null + ); const totalTokens = Number(acct.totalTokens || 0); const inputTokens = Number(acct.inputTokens || 0); const cacheTokens = Number(acct.cacheReadTokens || 0); @@ -31970,11 +32230,18 @@ const ConsumptionView = defineComponent({ ...allTrendMergedModels, ]); - // 2. 同步历史趋势交互式 SVG 面积图 / 类 GitHub 每日热力图(>90天)与悬停分模型浮层 - const rangeBadgeText = isEnglishLocale() - ? getConsumptionTimeRangeOptions().find((o) => o.value === slice.range)?.label || - t('cons.allTime') - : preset?.label || rangeInfo.label || t('cons.allTime'); + // 2. 同步历史趋势交互式 SVG 面积图 / 类 GitHub 每日热力图(>90天)及悬停分模型浮层 + const rangeBadgeText = + slice.range === 'cycle' + ? `${rangeInfo.isFallbackWeek || slice.weeklyLimitMode === 'custom_tokens' || slice.weeklyLimitMode === 'custom_cost' ? t('cons.cycleFallbackWeek') : t('cons.currentCycle')}${ + activePoolFilter && activePoolFilter !== 'all' + ? ` · ${rangeInfo.poolLabel || activePoolFilter}` + : '' + }` + : isEnglishLocale() + ? getConsumptionTimeRangeOptions().find((o) => o.value === slice.range)?.label || + t('cons.allTime') + : preset?.label || rangeInfo.label || t('cons.allTime'); patchText(trendRangeBadge, rangeBadgeText); const firstTrendSlot = rawTrendSeries[0] || null; const isMinuteTrend = firstTrendSlot?.granularity === 'minute'; @@ -32134,7 +32401,7 @@ const ConsumptionView = defineComponent({ updateRow: (refs, s) => updateSourceBreakdownRow(refs, s, sourcesTotalTok, modelColorMap), }); - const nextRangeSig = `${slice.range || ''}:${slice.customStartMs || 0}:${slice.customEndMs || 0}`; + const nextRangeSig = `${slice.range || ''}:${activePoolFilter || 'all'}:${slice.customStartMs || 0}:${slice.customEndMs || 0}`; const nextRankingKey = showWorkspacesTab ? 'workspaces' : showSessionsTab @@ -32270,8 +32537,11 @@ const ConsumptionView = defineComponent({ const unsub = telemetryStore.subscribe( (st) => ({ range: st.selectedTimeRange, + cyclePool: st.selectedCyclePool || 'all', customStartMs: st.customStartMs, customEndMs: st.customEndMs, + quotaPools: st.telemetry?.quotas?.pools, + weeklyLimitMode: st.telemetry?.settings?.weeklyLimitMode, consumption: st.telemetry?.consumption, modelBreakdown: st.telemetry?.modelBreakdown, modelDisplayMode: normalizeModelDisplayMode( @@ -32325,6 +32595,7 @@ const ConsumptionView = defineComponent({ ariaLabel: t('cons.rangeAria'), options: getConsumptionTimeRangeOptions(), }); + patchAttr(cyclePoolSelect.refs.triggerBtn, 'aria-label', t('cons.cyclePoolAria')); patchText(applyCustomBtnLabel, t('cons.applyFilter')); patchText(rangeToSpan, t('cons.rangeTo')); patchText(totalTokensLabel, t('cons.totalTokens')); @@ -32382,6 +32653,7 @@ const ConsumptionView = defineComponent({ unsubView(); unsubI18n(); consExportMenu.destroy(); + cyclePoolSelect.destroy(); trendChart.destroy?.(); rankingTabSwitch.destroy(); modelsSortSwitch.destroy(); @@ -32396,6 +32668,7 @@ const ConsumptionView = defineComponent({ el: rootEl, refs: { timeFilterSwitch, + cyclePoolSelect, startPicker, endPicker, viewScrollbar, diff --git a/sidecars/panel/backend/api-actions.mjs b/sidecars/panel/backend/api-actions.mjs index 35b0c59..15d05fc 100644 --- a/sidecars/panel/backend/api-actions.mjs +++ b/sidecars/panel/backend/api-actions.mjs @@ -258,8 +258,10 @@ export async function executeTelemetryAction(data, opts = {}) { rawScope === 'conversation' ? rawScope : ''; + const rawPool = typeof data?.pool === 'string' ? data.pool.trim().slice(0, 48) : ''; const filterOpts = { range: data?.range || 'all', + ...(rawPool ? { pool: rawPool } : {}), startMs: sanitizePositiveFiniteMs(data?.startMs), endMs: sanitizePositiveFiniteMs(data?.endMs), ...(scope ? { scope } : {}), diff --git a/sidecars/panel/backend/quota-pools.mjs b/sidecars/panel/backend/quota-pools.mjs index c8dd7fe..11a7175 100644 --- a/sidecars/panel/backend/quota-pools.mjs +++ b/sidecars/panel/backend/quota-pools.mjs @@ -370,9 +370,14 @@ export function buildOfficialQuotaPools(officialQuota, clientConfigs = []) { } const cfgQuota = normalizeQuotaFraction(cfg?.quotaInfo, nowForQuotaMs); + const cfgResetMs = parseIsoMs(cfgQuota?.resetTime); + const isCfgWeekly = + targetIdent.poolKey === 'Argon' || + targetIdent.poolKey === 'Carbon' || + cfgResetMs > nowForQuotaMs + 6 * 3600 * 1000; if (!builder.bucket5h && !builder.bucketWeekly && !builder.fallback5h && cfgQuota) { - if (targetIdent.poolKey === 'Argon' || targetIdent.poolKey === 'Carbon') { - builder.bucketWeekly = cfgQuota; + if (isCfgWeekly) { + builder.bucketWeekly = { ...cfgQuota, window: 'weekly' }; } else { builder.fallback5h = cfgQuota; } diff --git a/sidecars/panel/backend/telemetry-builder.mjs b/sidecars/panel/backend/telemetry-builder.mjs index d1d0fa6..4be4357 100644 --- a/sidecars/panel/backend/telemetry-builder.mjs +++ b/sidecars/panel/backend/telemetry-builder.mjs @@ -2382,6 +2382,9 @@ export async function buildTelemetryPayloadInternal( revision: usageRevision, selectedRange: { key: selectedWindow.key, + ...(selectedWindow.pool ? { pool: selectedWindow.pool } : {}), + ...(selectedWindow.poolLabel ? { poolLabel: selectedWindow.poolLabel } : {}), + ...(selectedWindow.isFallbackWeek ? { isFallbackWeek: true } : {}), label: selectedWindow.label, startMs: trendStartMs, endMs: trendEndMs, @@ -2802,6 +2805,9 @@ function tryBuildFastConsumptionPayload(filterOpts = {}) { revision: agg.usageRevision, selectedRange: { key: agg.selectedWindow.key, + ...(agg.selectedWindow.pool ? { pool: agg.selectedWindow.pool } : {}), + ...(agg.selectedWindow.poolLabel ? { poolLabel: agg.selectedWindow.poolLabel } : {}), + ...(agg.selectedWindow.isFallbackWeek ? { isFallbackWeek: true } : {}), label: agg.selectedWindow.label, startMs: agg.trendStartMs, endMs: agg.trendEndMs, @@ -2969,7 +2975,7 @@ export function buildTelemetryPayload( } } } - const rangeSig = `${filterOpts.range || 'all'}:${filterOpts.startMs || 0}:${filterOpts.endMs || 0}`; + const rangeSig = `${filterOpts.range || 'all'}:${filterOpts.pool || 'all'}:${filterOpts.startMs || 0}:${filterOpts.endMs || 0}`; const key = `${endpointKey}::${requestedConvId || '__auto__'}::${forceQuotaRefresh ? 'force' : 'normal'}::${rangeSig}`; if (inFlightRequests.has(key)) { return inFlightRequests.get(key); diff --git a/sidecars/panel/backend/usage-aggregator.mjs b/sidecars/panel/backend/usage-aggregator.mjs index 8510c6b..a41686f 100644 --- a/sidecars/panel/backend/usage-aggregator.mjs +++ b/sidecars/panel/backend/usage-aggregator.mjs @@ -786,13 +786,14 @@ function buildQuotaPoolCycleMap(quotaPoolsMap, nowMs) { ? Math.min(nowMs, reset5hMs - 5 * 3600 * 1000) : nowMs - 5 * 3600 * 1000; const resetWkMs = parseIsoMs(poolObj?.weeklyResetTime) || 0; - const startWkMs = - resetWkMs > nowMs - ? Math.min(nowMs, resetWkMs - 7 * 24 * 3600 * 1000) - : weekFallbackStartMs; + const hasOfficialWk = resetWkMs > nowMs; + const startWkMs = hasOfficialWk + ? Math.min(nowMs, resetWkMs - 7 * 24 * 3600 * 1000) + : weekFallbackStartMs; poolCycleBuckets.set(poolKey, { start5hMs, startWkMs, + hasOfficialWk, b5h: createUsageBucket(), bWk: createUsageBucket(), pricedTokens5h: 0, @@ -809,7 +810,27 @@ function buildQuotaPoolCycleMap(quotaPoolsMap, nowMs) { return poolCycleBuckets; } -function resolvePoolBucketForStep( +export function normalizeCyclePoolFilter(rawPool, availablePoolKeys = null) { + const raw = typeof rawPool === 'string' ? rawPool.trim() : ''; + if (!raw || raw.toLowerCase() === 'all') return 'all'; + const lower = raw.toLowerCase(); + let canonical = raw; + if (lower === 'gemini') canonical = 'Gemini'; + else if (lower === 'argon' || lower === 'gemini 4 argon') canonical = 'Argon'; + else if (lower === 'carbon' || lower === 'gemini 4 carbon') canonical = 'Carbon'; + else if (lower === 'claude & gpt' || lower === 'claude' || lower === 'gpt') { + canonical = 'Claude & GPT'; + } + if (availablePoolKeys && availablePoolKeys.size > 0 && !availablePoolKeys.has(canonical)) { + for (const k of availablePoolKeys.keys()) { + if (String(k).toLowerCase() === lower) return k; + } + return 'all'; + } + return canonical; +} + +function resolveStepPoolAssignment( st, mInfo, poolCycleBuckets, @@ -817,7 +838,6 @@ function resolvePoolBucketForStep( hasDedicatedCarbonPool, hasDedicatedArgonPool ) { - if (poolCycleBuckets.size === 0) return null; let cachedPool = poolByModel.get(mInfo); if ( !cachedPool || @@ -841,11 +861,68 @@ function resolvePoolBucketForStep( key: st.modelKey, response: st.responseModel, displayName: st.modelDisplayName, - bucket: poolCycleBuckets.get(poolKey) || null, + poolKey, + bucket: poolKey && poolCycleBuckets.size > 0 ? poolCycleBuckets.get(poolKey) || null : null, }; poolByModel.set(mInfo, cachedPool); } - return cachedPool.bucket; + return cachedPool; +} + +function resolveEffectiveSelectedCycleWindow({ + selectedWindow, + effectiveCyclePool = 'all', + isCustomWeeklyMode = false, + cycleAnchors = {}, + nowMs = Date.now(), + poolCycleBuckets, + quotaPoolsMap = null, + earliestActiveCyclePoolStartMs = Infinity, + earliestSelectedStepMs = Infinity, +}) { + if (!selectedWindow || selectedWindow.key !== 'cycle') return selectedWindow; + if (effectiveCyclePool !== 'all') { + const poolBucket = poolCycleBuckets?.get?.(effectiveCyclePool) || null; + const poolMeta = quotaPoolsMap instanceof Map ? quotaPoolsMap.get(effectiveCyclePool) : null; + const poolLabel = poolMeta?.poolLabel || effectiveCyclePool; + const baseStartMs = + !isCustomWeeklyMode && poolBucket ? poolBucket.startWkMs : selectedWindow.startMs; + const startMs = + Number.isFinite(earliestSelectedStepMs) && earliestSelectedStepMs < Infinity + ? Math.min(baseStartMs, earliestSelectedStepMs) + : baseStartMs; + const isFallbackWeek = !isCustomWeeklyMode && !poolBucket?.hasOfficialWk; + return { + ...selectedWindow, + pool: effectiveCyclePool, + poolLabel, + isFallbackWeek, + label: `${isCustomWeeklyMode || isFallbackWeek ? '本周' : '当前周期'} · ${poolLabel}`, + startMs, + }; + } + let hasAnyOfficialWk = !isCustomWeeklyMode && (cycleAnchors?.weeklyResetMs || 0) > nowMs; + if (!hasAnyOfficialWk && poolCycleBuckets instanceof Map) { + for (const b of poolCycleBuckets.values()) { + if (b?.hasOfficialWk) { + hasAnyOfficialWk = true; + break; + } + } + } + const isFallbackWeek = !isCustomWeeklyMode && !hasAnyOfficialWk; + const startMs = + Number.isFinite(earliestActiveCyclePoolStartMs) && earliestActiveCyclePoolStartMs < Infinity + ? Math.min(earliestActiveCyclePoolStartMs, earliestSelectedStepMs) + : selectedWindow.startMs; + return { + ...selectedWindow, + pool: 'all', + poolLabel: '', + isFallbackWeek, + label: isCustomWeeklyMode || isFallbackWeek ? '本周' : '当前周期', + startMs, + }; } function buildUsageTrendSeries( @@ -1155,6 +1232,7 @@ function computeFamilySessionBuckets({ presetKeys = [], presetWindows = {}, selectedWindow, + effectiveCyclePool = 'all', isCustomWeeklyMode = false, poolCycleBuckets = new Map(), normalizedQuotaAccount = '', @@ -1166,8 +1244,11 @@ function computeFamilySessionBuckets({ for (const k of presetKeys) { sessionBuckets[k] = createUsageBucket(); } + const isScopedCyclePool = selectedWindow?.key === 'cycle' && effectiveCyclePool !== 'all'; const selectedSessionBucket = - (selectedWindow?.key && sessionBuckets[selectedWindow.key]) || createUsageBucket(); + selectedWindow?.key && !isScopedCyclePool && sessionBuckets[selectedWindow.key] + ? sessionBuckets[selectedWindow.key] + : createUsageBucket(); if (!(familySet instanceof Set) || familySet.size === 0) { const sessionPresets = {}; for (const k of presetKeys) { @@ -1233,17 +1314,15 @@ function computeFamilySessionBuckets({ unpriced, }; - const poolBucketEntry = - poolCycleBuckets.size > 0 - ? resolvePoolBucketForStep( - st, - mInfo, - poolCycleBuckets, - poolByModel, - hasDedicatedCarbonPool, - hasDedicatedArgonPool - ) - : null; + const stepPool = resolveStepPoolAssignment( + st, + mInfo, + poolCycleBuckets, + poolByModel, + hasDedicatedCarbonPool, + hasDedicatedArgonPool + ); + const poolBucketEntry = stepPool.bucket; let inCurrentCycle = false; if (qMs > 0 && qMs <= nowMs) { @@ -1273,14 +1352,19 @@ function computeFamilySessionBuckets({ } } - if (selectedWindow && (!sessionBuckets[selectedWindow.key] || selectedWindow.key === 'custom')) { + if ( + selectedWindow && + (!sessionBuckets[selectedWindow.key] || + selectedWindow.key === 'custom' || + isScopedCyclePool) + ) { const selCmpMs = selectedWindow.key === '5h' || selectedWindow.key === 'week' ? qMs : tMs; const inSelectedWindow = selectedWindow.key === 'all' ? true : selectedWindow.key === 'cycle' - ? inCurrentCycle + ? inCurrentCycle && (effectiveCyclePool === 'all' || stepPool.poolKey === effectiveCyclePool) : selCmpMs > 0 && selCmpMs >= selectedWindow.startMs && selCmpMs <= selectedWindow.endMs; if (inSelectedWindow) { accumulateStepIntoBucket(selectedSessionBucket, stepUsage, entry.cascadeId); @@ -1407,16 +1491,30 @@ export function aggregateMultiWindowUsage({ sessionBuckets[k] = createUsageBucket(); } - // 为每个配额池建立独立的 5h 与周限周期统计桶(按各池自身的 resetTime / weeklyResetTime 截取窗口) + // 为每个配额池建立独立的 5h 及周限周期统计桶(按各池自身的 resetTime / weeklyResetTime 截取窗口) const poolCycleBuckets = buildQuotaPoolCycleMap(quotaPoolsMap, nowMs); + const effectiveCyclePool = + selectedWindow.key === 'cycle' + ? normalizeCyclePoolFilter(filterOpts.pool, poolCycleBuckets) + : 'all'; + const isScopedCyclePool = selectedWindow.key === 'cycle' && effectiveCyclePool !== 'all'; + const selectedRangeCacheKey = isScopedCyclePool + ? `cycle:${effectiveCyclePool}` + : selectedWindow.key; const hasDedicatedCarbonPool = poolCycleBuckets.has('Carbon'); const hasDedicatedArgonPool = poolCycleBuckets.has('Argon'); const poolByModel = new Map(); const quotaWeekBucket = createUsageBucket(); const normalizedQuotaAccount = currentAccountName === null ? null : normalizeOwnerAccount(currentAccountName); - const selectedAccountBucket = accountBuckets[selectedWindow.key] || createUsageBucket(); - const selectedSessionBucket = sessionBuckets[selectedWindow.key] || createUsageBucket(); + const selectedAccountBucket = + !isScopedCyclePool && accountBuckets[selectedWindow.key] + ? accountBuckets[selectedWindow.key] + : createUsageBucket(); + const selectedSessionBucket = + !isScopedCyclePool && sessionBuckets[selectedWindow.key] + ? sessionBuckets[selectedWindow.key] + : createUsageBucket(); const perModelStats = new Map(); const perConvStats = new Map(); const perWorkspaceStats = new Map(); @@ -1463,15 +1561,31 @@ export function aggregateMultiWindowUsage({ modelInputs.catalogRevision === snapshot.modelInputs.catalogRevision && isDeepStrictEqual(modelInputs.dynamicModelMap, snapshot.modelInputs.dynamicModelMap) && sameUsageEntries(snapshot.entries, allEntriesToAggregate); - const previous = sameSnapshot ? snapshot.ranges.get(selectedWindow.key) : null; + const previous = sameSnapshot ? snapshot.ranges.get(selectedRangeCacheKey) : null; if (previous) { // 时钟继续前进,只有实际有步骤跨过窗口边界时才重新聚合。 + const probeEffectiveWin = + selectedWindow.key === 'cycle' + ? resolveEffectiveSelectedCycleWindow({ + selectedWindow, + effectiveCyclePool, + isCustomWeeklyMode, + cycleAnchors, + nowMs, + poolCycleBuckets, + quotaPoolsMap, + earliestActiveCyclePoolStartMs: previous.earliestActiveCyclePoolStartMs, + earliestSelectedStepMs: previous.earliest, + }) + : selectedWindow; const effectivePrevWin = selectedWindow.key === 'cycle' && previous.effectiveSelectedWindow - ? { ...previous.effectiveSelectedWindow, endMs: nowMs } + ? { ...probeEffectiveWin, endMs: nowMs } : selectedWindow; const trend = planUsageTrend(effectivePrevWin, nowMs, previous.earliest, previous.latest); if ( + Boolean(effectivePrevWin.isFallbackWeek) === + Boolean(previous.effectiveSelectedWindow?.isFallbackWeek) && trend.hourly === previous.trend.hourly && trend.stepMs === previous.trend.stepMs && trend.first === previous.trend.first && @@ -1483,8 +1597,8 @@ export function aggregateMultiWindowUsage({ (snapshot.quotaDates ??= sortedQuotaBillingTimestamps(allEntriesToAggregate, nowMs)) ) ) { - snapshot.ranges.delete(selectedWindow.key); - snapshot.ranges.set(selectedWindow.key, previous); + snapshot.ranges.delete(selectedRangeCacheKey); + snapshot.ranges.set(selectedRangeCacheKey, previous); if (previous.familySig === familySig) { return { ...previous.result, @@ -1501,6 +1615,7 @@ export function aggregateMultiWindowUsage({ presetKeys, presetWindows, selectedWindow, + effectiveCyclePool, isCustomWeeklyMode, poolCycleBuckets, normalizedQuotaAccount, @@ -1588,7 +1703,7 @@ export function aggregateMultiWindowUsage({ } } - const poolBucketEntry = resolvePoolBucketForStep( + const stepPool = resolveStepPoolAssignment( st, mInfo, poolCycleBuckets, @@ -1596,6 +1711,7 @@ export function aggregateMultiWindowUsage({ hasDedicatedCarbonPool, hasDedicatedArgonPool ); + const poolBucketEntry = stepPool.bucket; if (includeInQuotaPools && poolBucketEntry && qMs > 0 && qMs <= nowMs) { if (qMs > poolBucketEntry.lastActivityMs) { @@ -1691,7 +1807,7 @@ export function aggregateMultiWindowUsage({ selectedWindow.key === 'all' ? true : selectedWindow.key === 'cycle' - ? inCurrentCycle + ? inCurrentCycle && (effectiveCyclePool === 'all' || stepPool.poolKey === effectiveCyclePool) : selCmpMs > 0 && selCmpMs >= selectedWindow.startMs && selCmpMs <= selectedWindow.endMs; if (inSelectedWindow) { @@ -1703,7 +1819,7 @@ export function aggregateMultiWindowUsage({ ) { earliestActiveCyclePoolStartMs = poolBucketEntry.startWkMs; } - if (selectedWindow.key === 'custom') { + if (selectedWindow.key === 'custom' || isScopedCyclePool) { accumulateStepIntoBucket(selectedAccountBucket, stepUsage, cascadeId); if (isCurrentConv) { accumulateStepIntoBucket(selectedSessionBucket, stepUsage, cascadeId); @@ -1785,15 +1901,17 @@ export function aggregateMultiWindowUsage({ ); // 构建当前选定时间窗口的自适应自然整点/整日趋势序列 (trendSeries) - const effectiveSelectedWindow = - selectedWindow.key === 'cycle' && - Number.isFinite(earliestActiveCyclePoolStartMs) && - earliestActiveCyclePoolStartMs < Infinity - ? { - ...selectedWindow, - startMs: Math.min(earliestActiveCyclePoolStartMs, earliestSelectedStepMs), - } - : selectedWindow; + const effectiveSelectedWindow = resolveEffectiveSelectedCycleWindow({ + selectedWindow, + effectiveCyclePool, + isCustomWeeklyMode, + cycleAnchors, + nowMs, + poolCycleBuckets, + quotaPoolsMap, + earliestActiveCyclePoolStartMs, + earliestSelectedStepMs, + }); const { trend, trendStartMs, trendEndMs, trendSeries } = buildUsageTrendSeries( selectedWindow, effectiveSelectedWindow, @@ -1929,6 +2047,11 @@ export function aggregateMultiWindowUsage({ if (oldestKey !== undefined) lastUsageSnapshotsByEndpoint.delete(oldestKey); } lastUsageSnapshotsByEndpoint.set(endpointKey, activeSnap); + } else if (previous) { + resolvedUsageRevision = ++usageSnapshotRevisionSeq; + activeSnap.revision = resolvedUsageRevision; + activeSnap.ranges.clear(); + activeSnap.selectedRanges?.clear?.(); } else { resolvedUsageRevision = activeSnap.revision; } @@ -1959,19 +2082,20 @@ export function aggregateMultiWindowUsage({ }; if (modelInputs && activeSnap) { const { ranges } = activeSnap; - ranges.delete(selectedWindow.key); - ranges.set(selectedWindow.key, { + ranges.delete(selectedRangeCacheKey); + ranges.set(selectedRangeCacheKey, { familySig, windows, selectedWindow, effectiveSelectedWindow, + earliestActiveCyclePoolStartMs, trend, result, earliest: earliestSelectedStepMs, latest: latestSelectedStepMs, }); // 缓存各时间窗口的完整多窗口聚合结果,同快照复用时亚毫秒命中。 - if (ranges.size > 10) ranges.delete(ranges.keys().next().value); + if (ranges.size > 16) ranges.delete(ranges.keys().next().value); } return result; } @@ -2019,6 +2143,14 @@ export function aggregateSelectedWindowUsage({ : 0; const poolCycleBuckets = selectedWindow.key === 'cycle' ? buildQuotaPoolCycleMap(quotaPoolsMap, nowMs) : new Map(); + const effectiveCyclePool = + selectedWindow.key === 'cycle' + ? normalizeCyclePoolFilter(filterOpts.pool, poolCycleBuckets) + : 'all'; + const selectedRangeCacheKey = + selectedWindow.key === 'cycle' && effectiveCyclePool !== 'all' + ? `cycle:${effectiveCyclePool}` + : selectedWindow.key; const hasDedicatedCarbonPool = poolCycleBuckets.has('Carbon'); const hasDedicatedArgonPool = poolCycleBuckets.has('Argon'); const poolByModel = new Map(); @@ -2032,6 +2164,19 @@ export function aggregateSelectedWindowUsage({ const currentYear = new Date(nowMs).getFullYear(); const timeZone = modelInputs ? resolveCachedLocalTimeZone() : ''; + const currentCheckWindows = + selectedWindow.key === 'cycle' + ? [ + selectedWindow, + ...Array.from(poolCycleBuckets, ([key, { startWkMs }]) => ({ + key: `${key}:week`, + label: `${key}:week`, + startMs: startWkMs, + endMs: nowMs, + })), + ] + : [selectedWindow]; + const snapshot = lastUsageSnapshotsByEndpoint.get(endpointKey) || null; const sameSnapshot = Boolean( modelInputs && @@ -2047,24 +2192,45 @@ export function aggregateSelectedWindowUsage({ if (sameSnapshot) { snapshot.selectedRanges ??= new Map(); - const cachedFull = snapshot.ranges.get(selectedWindow.key); - const cachedLite = snapshot.selectedRanges.get(selectedWindow.key); + const cachedFull = snapshot.ranges.get(selectedRangeCacheKey); + const cachedLite = snapshot.selectedRanges.get(selectedRangeCacheKey); const candidate = cachedFull || cachedLite; if (candidate) { const prevWin = candidate.selectedWindow || candidate.windows?.[0] || selectedWindow; + const probeEffectiveWin = + selectedWindow.key === 'cycle' + ? resolveEffectiveSelectedCycleWindow({ + selectedWindow, + effectiveCyclePool, + isCustomWeeklyMode, + cycleAnchors, + nowMs, + poolCycleBuckets, + quotaPoolsMap, + earliestActiveCyclePoolStartMs: candidate.earliestActiveCyclePoolStartMs, + earliestSelectedStepMs: candidate.earliest, + }) + : selectedWindow; const effectivePrevWin = selectedWindow.key === 'cycle' && candidate.effectiveSelectedWindow - ? { ...candidate.effectiveSelectedWindow, endMs: nowMs } + ? { ...probeEffectiveWin, endMs: nowMs } : selectedWindow; const trend = planUsageTrend(effectivePrevWin, nowMs, candidate.earliest, candidate.latest); + const prevCheckWindows = candidate.checkWindows || [prevWin]; + const compareNextWindows = + prevCheckWindows.length === currentCheckWindows.length + ? currentCheckWindows + : [selectedWindow]; if ( + Boolean(effectivePrevWin.isFallbackWeek) === + Boolean(candidate.effectiveSelectedWindow?.isFallbackWeek) && trend.hourly === candidate.trend.hourly && trend.stepMs === candidate.trend.stepMs && trend.first === candidate.trend.first && trend.last === candidate.trend.last && sameUsageWindows( - [prevWin], - [selectedWindow], + prevCheckWindows.length === compareNextWindows.length ? prevCheckWindows : [prevWin], + compareNextWindows, (snapshot.dates ??= sortedUsageTimestamps(allEntriesToAggregate)), (snapshot.quotaDates ??= sortedQuotaBillingTimestamps(allEntriesToAggregate, nowMs)) ) @@ -2079,6 +2245,7 @@ export function aggregateSelectedWindowUsage({ presetKeys: [], presetWindows: {}, selectedWindow, + effectiveCyclePool, isCustomWeeklyMode, poolCycleBuckets, normalizedQuotaAccount, @@ -2100,6 +2267,9 @@ export function aggregateSelectedWindowUsage({ topWorkspaces: res.topWorkspaces || [], }; } + snapshot.revision = ++usageSnapshotRevisionSeq; + snapshot.ranges.clear(); + snapshot.selectedRanges.clear(); } } @@ -2115,6 +2285,11 @@ export function aggregateSelectedWindowUsage({ maxCutoffMs = nowMs; if (isCustomWeeklyMode) { minCutoffMs = weekStartMs; + } else if (effectiveCyclePool !== 'all' && poolCycleBuckets.has(effectiveCyclePool)) { + minCutoffMs = Math.max( + 0, + poolCycleBuckets.get(effectiveCyclePool).startWkMs - maxSettlementSlackMs + ); } else if (poolCycleBuckets.size > 0) { minCutoffMs = selectedWindow.startMs; for (const entry of poolCycleBuckets.values()) { @@ -2190,20 +2365,24 @@ export function aggregateSelectedWindowUsage({ : normalizedQuotaAccount === '' || stepOwner === '' ? true : stepOwner === normalizedQuotaAccount; + mInfo = resolveStepModel(st); + const stepPool = resolveStepPoolAssignment( + st, + mInfo, + poolCycleBuckets, + poolByModel, + hasDedicatedCarbonPool, + hasDedicatedArgonPool + ); + poolBucketEntry = stepPool.bucket; + if (effectiveCyclePool !== 'all' && stepPool.poolKey !== effectiveCyclePool) { + continue; + } let inCurrentCycle = false; if (isCustomWeeklyMode) { inCurrentCycle = tMs >= weekStartMs; } else if (poolCycleBuckets.size > 0) { if (!includeInQuotaPools) continue; - mInfo = resolveStepModel(st); - poolBucketEntry = resolvePoolBucketForStep( - st, - mInfo, - poolCycleBuckets, - poolByModel, - hasDedicatedCarbonPool, - hasDedicatedArgonPool - ); const effCycleStartMs = poolBucketEntry ? poolBucketEntry.startWkMs : selectedWindow.startMs; @@ -2320,15 +2499,17 @@ export function aggregateSelectedWindowUsage({ } } - const effectiveSelectedWindow = - selectedWindow.key === 'cycle' && - Number.isFinite(earliestActiveCyclePoolStartMs) && - earliestActiveCyclePoolStartMs < Infinity - ? { - ...selectedWindow, - startMs: Math.min(earliestActiveCyclePoolStartMs, earliestSelectedStepMs), - } - : selectedWindow; + const effectiveSelectedWindow = resolveEffectiveSelectedCycleWindow({ + selectedWindow, + effectiveCyclePool, + isCustomWeeklyMode, + cycleAnchors, + nowMs, + poolCycleBuckets, + quotaPoolsMap, + earliestActiveCyclePoolStartMs, + earliestSelectedStepMs, + }); const { trend, trendStartMs, trendEndMs, trendSeries } = buildUsageTrendSeries( selectedWindow, @@ -2369,17 +2550,19 @@ export function aggregateSelectedWindowUsage({ if (sameSnapshot) { snapshot.selectedRanges ??= new Map(); - snapshot.selectedRanges.delete(selectedWindow.key); - snapshot.selectedRanges.set(selectedWindow.key, { + snapshot.selectedRanges.delete(selectedRangeCacheKey); + snapshot.selectedRanges.set(selectedRangeCacheKey, { familySig, + checkWindows: currentCheckWindows, selectedWindow, effectiveSelectedWindow, + earliestActiveCyclePoolStartMs, trend, result: sliceResult, earliest: earliestSelectedStepMs, latest: latestSelectedStepMs, }); - if (snapshot.selectedRanges.size > 12) { + if (snapshot.selectedRanges.size > 16) { snapshot.selectedRanges.delete(snapshot.selectedRanges.keys().next().value); } } @@ -2426,6 +2609,10 @@ export function aggregateSessionUsageForFamily({ presetWindows[k] = resolveTimeWindow(k, 0, 0, nowMs, cycleAnchors, isCustomWeeklyMode); } const poolCycleBuckets = buildQuotaPoolCycleMap(quotaPoolsMap, nowMs); + const effectiveCyclePool = + selectedWindow.key === 'cycle' + ? normalizeCyclePoolFilter(filterOpts.pool, poolCycleBuckets) + : 'all'; const normalizedQuotaAccount = currentAccountName === null ? null : normalizeOwnerAccount(currentAccountName); @@ -2464,6 +2651,7 @@ export function aggregateSessionUsageForFamily({ presetKeys, presetWindows, selectedWindow, + effectiveCyclePool, isCustomWeeklyMode, poolCycleBuckets, normalizedQuotaAccount, @@ -2473,7 +2661,7 @@ export function aggregateSessionUsageForFamily({ } /** - * 批量预聚合全部 7 个用量页预设区间(复用同一次条目收集与时间剪枝),供前端进入「用量统计」时静默预取实现 0ms 瞬切。 + * 批量预聚合全部 7 个用量页预设区间及各配额池独立周期(复用同一次条目收集和时间剪枝),供前端进入「用量统计」时静默预取实现 0ms 瞬切。 */ export function aggregateConsumptionPresetBundle(params) { const { activeCascadeId = null, activeFamilyCascadeIds = null, endpoint = null } = params || {}; @@ -2488,6 +2676,25 @@ export function aggregateConsumptionPresetBundle(params) { const ranges = {}; let usageRevision = usageSnapshotRevisionSeq; + const packSlice = (agg) => ({ + selectedRange: { + key: agg.selectedWindow.key, + ...(agg.selectedWindow.pool ? { pool: agg.selectedWindow.pool } : {}), + ...(agg.selectedWindow.poolLabel ? { poolLabel: agg.selectedWindow.poolLabel } : {}), + ...(agg.selectedWindow.isFallbackWeek ? { isFallbackWeek: true } : {}), + label: agg.selectedWindow.label, + startMs: agg.trendStartMs, + endMs: agg.trendEndMs, + }, + session: agg.finalizedSelectedSession, + account: agg.finalizedSelectedAccount, + trendSeries: agg.trendSeries, + sourcesBreakdown: agg.sourcesBreakdown, + modelBreakdown: agg.modelBreakdown, + topConversations: agg.topConversations || [], + topWorkspaces: agg.topWorkspaces || [], + }); + for (const rangeKey of CONSUMPTION_PRESET_RANGE_KEYS) { const agg = aggregateSelectedWindowUsage({ ...params, @@ -2495,21 +2702,20 @@ export function aggregateConsumptionPresetBundle(params) { precollectedEntries, }); usageRevision = agg.usageRevision; - ranges[rangeKey] = { - selectedRange: { - key: agg.selectedWindow.key, - label: agg.selectedWindow.label, - startMs: agg.trendStartMs, - endMs: agg.trendEndMs, - }, - session: agg.finalizedSelectedSession, - account: agg.finalizedSelectedAccount, - trendSeries: agg.trendSeries, - sourcesBreakdown: agg.sourcesBreakdown, - modelBreakdown: agg.modelBreakdown, - topConversations: agg.topConversations || [], - topWorkspaces: agg.topWorkspaces || [], - }; + ranges[rangeKey] = packSlice(agg); + } + + if (params?.quotaPoolsMap instanceof Map) { + for (const poolKey of params.quotaPoolsMap.keys()) { + if (!poolKey || poolKey === 'all') continue; + const agg = aggregateSelectedWindowUsage({ + ...params, + filterOpts: { range: 'cycle', pool: poolKey }, + precollectedEntries, + }); + usageRevision = agg.usageRevision; + ranges[`cycle:${poolKey}`] = packSlice(agg); + } } return { usageRevision, ranges }; diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index f295268..9fef7dd 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/src/components/ui/CustomSelect.js b/sidecars/panel/src/components/ui/CustomSelect.js index bc83a23..bfcf8be 100644 --- a/sidecars/panel/src/components/ui/CustomSelect.js +++ b/sidecars/panel/src/components/ui/CustomSelect.js @@ -469,8 +469,8 @@ export const CustomSelect = defineComponent({ const fallbackText = modelValue ? `${placeholder} (${String(modelValue).slice(0, 8)})` : placeholder; - labelText = selectedOpt ? selectedOpt.label : fallbackText; - titleText = labelText; + labelText = selectedOpt ? selectedOpt.shortLabel || selectedOpt.label : fallbackText; + titleText = selectedOpt ? selectedOpt.title || selectedOpt.label : fallbackText; } patchText(triggerLabel, labelText); diff --git a/sidecars/panel/src/core/formatters.js b/sidecars/panel/src/core/formatters.js index 7749719..13c6ca5 100644 --- a/sidecars/panel/src/core/formatters.js +++ b/sidecars/panel/src/core/formatters.js @@ -104,17 +104,34 @@ export function formatCnyApprox(usdAmount, rate = 7.2) { export function formatDateSpanBadge(startMs, endMs) { const s = startMs && Number.isFinite(startMs) ? new Date(startMs) : new Date(); const e = endMs && Number.isFinite(endMs) ? new Date(endMs) : new Date(); + const sameYear = s.getFullYear() === e.getFullYear(); + const sameMonth = sameYear && s.getMonth() === e.getMonth(); + const sameDay = sameMonth && s.getDate() === e.getDate(); + if (isEnglishLocale()) { const sMon = EN_MONTH_SHORT[s.getMonth()] || ''; const eMon = EN_MONTH_SHORT[e.getMonth()] || ''; - if (s.getFullYear() !== e.getFullYear()) { + if (!sameYear) { return `${sMon} ${s.getDate()}, ${s.getFullYear()} ~ ${eMon} ${e.getDate()}, ${e.getFullYear()}`; } + if (sameDay) { + return `${sMon} ${s.getDate()}`; + } + if (sameMonth) { + return `${sMon} ${s.getDate()} ~ ${e.getDate()}`; + } return `${sMon} ${s.getDate()} ~ ${eMon} ${e.getDate()}`; } - if (s.getFullYear() !== e.getFullYear()) { + + if (!sameYear) { return `${s.getFullYear()}年${s.getMonth() + 1}月${s.getDate()}日 ~ ${e.getFullYear()}年${e.getMonth() + 1}月${e.getDate()}日`; } + if (sameDay) { + return `${s.getMonth() + 1}月${s.getDate()}日`; + } + if (sameMonth) { + return `${s.getMonth() + 1}月${s.getDate()}日 ~ ${e.getDate()}日`; + } return `${s.getMonth() + 1}月${s.getDate()}日 ~ ${e.getMonth() + 1}月${e.getDate()}日`; } diff --git a/sidecars/panel/src/core/reportExporter.js b/sidecars/panel/src/core/reportExporter.js index 9ecfb99..9ec25db 100644 --- a/sidecars/panel/src/core/reportExporter.js +++ b/sidecars/panel/src/core/reportExporter.js @@ -99,10 +99,18 @@ function formatExportDate(ms) { function resolveLocalizedRangeLabel(range, en) { const r = range || {}; const key = String(r.key || '').trim().toLowerCase(); + const poolSuffix = + key === 'cycle' && r.pool && r.pool !== 'all' ? ` · ${r.poolLabel || r.pool}` : ''; if (en) { - return RANGE_LABELS_EN[key] || r.label || key || 'All Time'; + const baseEn = + key === 'cycle' && r.isFallbackWeek + ? 'This Week' + : RANGE_LABELS_EN[key] || r.label || key || 'All Time'; + return `${baseEn}${poolSuffix}`; } - return r.label || RANGE_LABELS_ZH[key] || key || '全部时间'; + if (r.label) return r.label; + const baseZh = RANGE_LABELS_ZH[key] || key || '全部时间'; + return `${baseZh}${poolSuffix}`; } function resolveRangeSpanNote(range) { diff --git a/sidecars/panel/src/i18n/en-US.js b/sidecars/panel/src/i18n/en-US.js index faebf89..ff228e5 100644 --- a/sidecars/panel/src/i18n/en-US.js +++ b/sidecars/panel/src/i18n/en-US.js @@ -240,6 +240,13 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ // Consumption View 'cons.rangeCycle': 'Cycle', + 'cons.cyclePoolAll': 'All Pools', + 'cons.cyclePoolAllShort': 'All', + 'cons.cyclePoolAria': 'Filter current cycle by quota pool', + 'cons.cyclePoolRemMeta': '{pct} left', + 'cons.currentCycle': 'Current Cycle', + 'cons.cycleFallbackWeek': 'This Week', + 'cons.cycleFallbackWeekTip': 'Official weekly reset time unavailable; using calendar week from Monday', 'cons.rangeToday': 'Today', 'cons.range24h': '24h', 'cons.range7d': '7d', diff --git a/sidecars/panel/src/i18n/zh-CN.js b/sidecars/panel/src/i18n/zh-CN.js index 845f698..5860f14 100644 --- a/sidecars/panel/src/i18n/zh-CN.js +++ b/sidecars/panel/src/i18n/zh-CN.js @@ -240,6 +240,13 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ // Consumption View 'cons.rangeCycle': '周期', + 'cons.cyclePoolAll': '全部池', + 'cons.cyclePoolAllShort': '全部', + 'cons.cyclePoolAria': '当前周期配额池筛选', + 'cons.cyclePoolRemMeta': '剩 {pct}', + 'cons.currentCycle': '当前周期', + 'cons.cycleFallbackWeek': '本周', + 'cons.cycleFallbackWeekTip': '未获取官方周限重置时间,暂按自然本周一统计', 'cons.rangeToday': '今天', 'cons.range24h': '1天', 'cons.range7d': '7天', diff --git a/sidecars/panel/src/store/telemetryStore.js b/sidecars/panel/src/store/telemetryStore.js index 02433a7..7159175 100644 --- a/sidecars/panel/src/store/telemetryStore.js +++ b/sidecars/panel/src/store/telemetryStore.js @@ -148,6 +148,7 @@ export const telemetryStore = createReactiveStore({ selectedConversationId: initialConversationId, hostRouteConversationId: extractHostRouteCascadeId(), selectedTimeRange: 'today', + selectedCyclePool: 'all', customStartMs: Date.now() - 24 * 3600 * 1000, customEndMs: Date.now(), syncState: 'idle', // 'idle' | 'syncing' | 'synced' | 'error' @@ -169,7 +170,7 @@ let inFlightTelemetryPoll = null; let inFlightPresetsPrefetch = null; let lastPrefetchedUsageRevision = 0; let consumptionCacheScopeSig = ''; -const MAX_CONSUMPTION_RANGE_CACHE = 12; +const MAX_CONSUMPTION_RANGE_CACHE = 24; const MAX_CONVERSATION_VIEW_CACHE = 12; const CONSUMPTION_PRESET_KEYS = ['cycle', 'today', '24h', '7d', '14d', '30d', 'all']; const consumptionRangeCache = new Map(); @@ -191,11 +192,19 @@ const TELEMETRY_RECOMPUTE_SETTING_KEYS = new Set([ 'enableWindowOverlay', ]); -function makeConsumptionRangeCacheKey(range, customStartMs = 0, customEndMs = 0) { +function makeConsumptionRangeCacheKey( + range, + customStartMs = 0, + customEndMs = 0, + cyclePool = 'all' +) { const key = String(range || 'all'); if (key === 'custom') { return `custom:${Number(customStartMs || 0)}:${Number(customEndMs || 0)}`; } + if (key === 'cycle' && cyclePool && cyclePool !== 'all') { + return `cycle:${String(cyclePool)}`; + } return key; } @@ -222,6 +231,17 @@ function buildConsumptionScopeSig(payload) { return `${String(ep.id || LOCAL_ENDPOINT_ID)}|${String(acct.status || '')}|${String(acct.email || acct.name || '').toLowerCase()}|${String(set.weeklyLimitMode || '')}|${String(cloud.catalogVersion || '')}`; } +function reconcileSelectedCyclePool(payload) { + const curPool = telemetryStore.getState().selectedCyclePool || 'all'; + if (curPool === 'all') return; + const pools = payload?.quotas?.pools; + if (!Array.isArray(pools) || pools.length === 0) return; + const exists = pools.some((p) => String(p?.poolKey || p?.family || '') === curPool); + if (!exists) { + telemetryStore.setState({ selectedCyclePool: 'all' }); + } +} + function syncConsumptionCacheScope(payload) { const nextSig = buildConsumptionScopeSig(payload); if (!nextSig) return; @@ -230,6 +250,7 @@ function syncConsumptionCacheScope(payload) { clearConversationViewCache(); } consumptionCacheScopeSig = nextSig; + reconcileSelectedCyclePool(payload); } function recordConversationViewToCache(payload) { @@ -345,14 +366,19 @@ function putConsumptionRangeCacheEntry(cacheKey, entry) { function recordConsumptionSliceToCache( cons, modelBreakdown, - { customStartMs = 0, customEndMs = 0, usageRevision = 0 } = {} + { customStartMs = 0, customEndMs = 0, cyclePool = 'all', usageRevision = 0 } = {} ) { const rangeKey = String(cons?.selectedRange?.key || ''); if (!rangeKey) return; + const resolvedPool = + rangeKey === 'cycle' + ? String(cons?.selectedRange?.pool || cyclePool || 'all') + : 'all'; const cacheKey = makeConsumptionRangeCacheKey( rangeKey, rangeKey === 'custom' ? customStartMs || cons.selectedRange?.startMs || 0 : 0, - rangeKey === 'custom' ? customEndMs || cons.selectedRange?.endMs || 0 : 0 + rangeKey === 'custom' ? customEndMs || cons.selectedRange?.endMs || 0 : 0, + resolvedPool ); putConsumptionRangeCacheEntry(cacheKey, { revision: Number(cons.revision ?? usageRevision ?? 0), @@ -900,11 +926,14 @@ export function isEquivalentTelemetry(prev, next) { } } - // 5. 比对消费统计所选时间区间、当前会话累计消费与账号全局累计消费 + // 5. 比对消费统计所选时间区间、当前会话累计消费和账号全局累计消费 const pRange = prev.consumption?.selectedRange; const nRange = next.consumption?.selectedRange; if (pRange?.key !== nRange?.key) return false; - if (nRange?.key === 'custom') { + if ((pRange?.pool || 'all') !== (nRange?.pool || 'all')) return false; + if ((pRange?.label || '') !== (nRange?.label || '')) return false; + if (Boolean(pRange?.isFallbackWeek) !== Boolean(nRange?.isFallbackWeek)) return false; + if (nRange?.key === 'custom' || nRange?.key === 'cycle') { if (pRange?.startMs !== nRange?.startMs || pRange?.endMs !== nRange?.endMs) return false; } @@ -1231,6 +1260,13 @@ export async function fetchTelemetry({ force = false } = {}) { const params = new URLSearchParams(); if (effectiveConvId) params.set('conversationId', effectiveConvId); if (current.selectedTimeRange) params.set('range', current.selectedTimeRange); + if ( + current.selectedTimeRange === 'cycle' && + current.selectedCyclePool && + current.selectedCyclePool !== 'all' + ) { + params.set('pool', current.selectedCyclePool); + } if (current.selectedTimeRange === 'custom') { if (current.customStartMs > 0) params.set('startMs', String(current.customStartMs)); if (current.customEndMs > 0) params.set('endMs', String(current.customEndMs)); @@ -1278,6 +1314,7 @@ async function requestTelemetry(params, force) { const reqSeq = ++latestRequestSeq; const reqSettingsRev = settingsRevision; const reqRange = String(params.get('range') || ''); + const reqPool = String(params.get('pool') || 'all'); const reqStartMs = Number(params.get('startMs') || 0); const reqEndMs = Number(params.get('endMs') || 0); const startMs = Date.now(); @@ -1337,14 +1374,17 @@ async function requestTelemetry(params, force) { recordConsumptionSliceToCache(resolvedPayload.consumption, resolvedPayload.modelBreakdown, { customStartMs: reqStartMs, customEndMs: reqEndMs, + cyclePool: reqPool, }); } const latestSt = telemetryStore.getState(); const incomingRev = Number(resolvedPayload?.consumption?.revision || 0); + const activePoolPref = latestSt.selectedCyclePool || 'all'; const matchesCurrentRange = !reqRange || (reqRange === latestSt.selectedTimeRange && + (reqRange !== 'cycle' || reqPool === activePoolPref) && (reqRange !== 'custom' || (reqStartMs === Number(latestSt.customStartMs || 0) && reqEndMs === Number(latestSt.customEndMs || 0)))); @@ -1356,7 +1396,8 @@ async function requestTelemetry(params, force) { const activeKey = makeConsumptionRangeCacheKey( latestSt.selectedTimeRange, latestSt.customStartMs, - latestSt.customEndMs + latestSt.customEndMs, + activePoolPref ); const cachedActive = consumptionRangeCache.get(activeKey); if (cachedActive) { @@ -1365,7 +1406,9 @@ async function requestTelemetry(params, force) { needsSilentRangeRevalidate = true; } } else if ( - latestSt.telemetry?.consumption?.selectedRange?.key === latestSt.selectedTimeRange + latestSt.telemetry?.consumption?.selectedRange?.key === latestSt.selectedTimeRange && + (latestSt.selectedTimeRange !== 'cycle' || + (latestSt.telemetry?.consumption?.selectedRange?.pool || 'all') === activePoolPref) ) { resolvedPayload = { ...resolvedPayload, @@ -1417,6 +1460,7 @@ async function requestTelemetry(params, force) { range: latestSt.selectedTimeRange, customStartMs: latestSt.customStartMs, customEndMs: latestSt.customEndMs, + cyclePool: latestSt.selectedCyclePool || 'all', }); } return resolvedPayload; @@ -1442,15 +1486,20 @@ async function fetchConsumptionRangeSlice({ range, customStartMs = 0, customEndMs = 0, + cyclePool = 'all', } = {}) { const reqEpoch = endpointSwitchEpoch; const reqSeq = ++latestConsumptionReqSeq; const targetRange = String(range || 'today'); + const targetPool = targetRange === 'cycle' ? String(cyclePool || 'all') : 'all'; const current = telemetryStore.getState(); const effectiveConvId = current.selectedConversationId || current.hostRouteConversationId || ''; const params = new URLSearchParams(); if (effectiveConvId) params.set('conversationId', effectiveConvId); params.set('range', targetRange); + if (targetRange === 'cycle' && targetPool !== 'all') { + params.set('pool', targetPool); + } if (targetRange === 'custom') { if (customStartMs > 0) params.set('startMs', String(customStartMs)); if (customEndMs > 0) params.set('endMs', String(customEndMs)); @@ -1469,6 +1518,7 @@ async function fetchConsumptionRangeSlice({ recordConsumptionSliceToCache(payload.consumption, payload.modelBreakdown, { customStartMs, customEndMs, + cyclePool: targetPool, usageRevision: usageRev, }); if (reqSeq !== latestConsumptionReqSeq) return payload; @@ -1476,6 +1526,7 @@ async function fetchConsumptionRangeSlice({ const latestSt = telemetryStore.getState(); const stillMatches = latestSt.selectedTimeRange === targetRange && + (targetRange !== 'cycle' || (latestSt.selectedCyclePool || 'all') === targetPool) && (targetRange !== 'custom' || (Number(latestSt.customStartMs || 0) === Number(customStartMs || 0) && Number(latestSt.customEndMs || 0) === Number(customEndMs || 0))); @@ -1581,6 +1632,13 @@ export async function selectConversation( const params = new URLSearchParams(); if (effectiveConvId) params.set('conversationId', effectiveConvId); if (current.selectedTimeRange) params.set('range', current.selectedTimeRange); + if ( + current.selectedTimeRange === 'cycle' && + current.selectedCyclePool && + current.selectedCyclePool !== 'all' + ) { + params.set('pool', current.selectedCyclePool); + } if (current.selectedTimeRange === 'custom') { if (current.customStartMs > 0) params.set('startMs', String(current.customStartMs)); if (current.customEndMs > 0) params.set('endMs', String(current.customEndMs)); @@ -1687,7 +1745,7 @@ export async function selectConversation( */ export function selectConsumptionTimeRange( nextRange, - { customStartMs = undefined, customEndMs = undefined } = {} + { customStartMs = undefined, customEndMs = undefined, cyclePool = undefined } = {} ) { const targetRange = String(nextRange || 'today'); const prevSt = telemetryStore.getState(); @@ -1699,14 +1757,26 @@ export function selectConsumptionTimeRange( targetRange === 'custom' ? Number(customEndMs !== undefined ? customEndMs : prevSt.customEndMs || 0) : prevSt.customEndMs; + const nextCyclePool = + targetRange === 'cycle' + ? String(cyclePool !== undefined ? cyclePool || 'all' : prevSt.selectedCyclePool || 'all') + : prevSt.selectedCyclePool || 'all'; const statePatch = { selectedTimeRange: targetRange }; + if (cyclePool !== undefined) { + statePatch.selectedCyclePool = nextCyclePool; + } if (targetRange === 'custom') { statePatch.customStartMs = nextStartMs; statePatch.customEndMs = nextEndMs; } - const cacheKey = makeConsumptionRangeCacheKey(targetRange, nextStartMs, nextEndMs); + const cacheKey = makeConsumptionRangeCacheKey( + targetRange, + nextStartMs, + nextEndMs, + targetRange === 'cycle' ? nextCyclePool : 'all' + ); const cached = consumptionRangeCache.get(cacheKey); const prevTelemetry = prevSt.telemetry; @@ -1725,6 +1795,7 @@ export function selectConsumptionTimeRange( range: targetRange, customStartMs: nextStartMs, customEndMs: nextEndMs, + cyclePool: nextCyclePool, }); } @@ -1733,9 +1804,14 @@ export function selectConsumptionTimeRange( range: targetRange, customStartMs: nextStartMs, customEndMs: nextEndMs, + cyclePool: nextCyclePool, }); } +export function selectConsumptionCyclePool(nextPool = 'all') { + return selectConsumptionTimeRange('cycle', { cyclePool: String(nextPool || 'all') }); +} + /** * 仅在进入「用量统计」视图时触发一次静默后台预取,拉齐全部 7 个预设区间到前端缓存以实现 0ms 瞬切。 */ diff --git a/sidecars/panel/src/styles/modern-ui.css b/sidecars/panel/src/styles/modern-ui.css index ace339a..6cdd8fa 100644 --- a/sidecars/panel/src/styles/modern-ui.css +++ b/sidecars/panel/src/styles/modern-ui.css @@ -570,6 +570,7 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { } [data-modern-ui="true"] .form-row > .custom-select > .select-trigger, +[data-modern-ui="true"] .cons-cycle-pool-select .select-trigger, [data-modern-ui="true"] .steps-inline-scope-select .select-trigger, [data-modern-ui="true"] .steps-inline-model-select .select-trigger, [data-modern-ui="true"] .sstep-fit-model-select .select-trigger { @@ -580,6 +581,7 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { } [data-modern-ui="true"] .form-row > .custom-select > .select-trigger:hover, +[data-modern-ui="true"] .cons-cycle-pool-select .select-trigger:hover, [data-modern-ui="true"] .steps-inline-scope-select .select-trigger:hover, [data-modern-ui="true"] .steps-inline-model-select .select-trigger:hover, [data-modern-ui="true"] .sstep-fit-model-select .select-trigger:hover { @@ -587,6 +589,7 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { } [data-modern-ui="true"] .form-row > .custom-select.is-open > .select-trigger, +[data-modern-ui="true"] .cons-cycle-pool-select.is-open .select-trigger, [data-modern-ui="true"] .steps-inline-scope-select.is-open .select-trigger, [data-modern-ui="true"] .steps-inline-model-select.is-open .select-trigger, [data-modern-ui="true"] .sstep-fit-model-select.is-open .select-trigger { diff --git a/sidecars/panel/src/styles/views-consumption.css b/sidecars/panel/src/styles/views-consumption.css index 762d784..29c22ae 100644 --- a/sidecars/panel/src/styles/views-consumption.css +++ b/sidecars/panel/src/styles/views-consumption.css @@ -14,6 +14,53 @@ gap: 6px; } +.cons-overview-title { + display: inline-flex; + align-items: center; + gap: 6px; + min-width: 0; +} + +.cons-cycle-pool-select { + flex: 0 1 auto; + width: auto; + min-width: 0; + max-width: 112px; +} + +.cons-cycle-pool-select .select-trigger { + width: auto; + min-height: calc(20px * var(--ui-font-scale, 1)); + height: auto; + padding: 1px 7px; + gap: 4px; + font-size: var(--fs-sm); + line-height: 1.25; + border: none; + border-radius: var(--radius-pill); + background: color-mix(in srgb, var(--text-primary) 7.5%, var(--surface-panel)); +} + +.cons-cycle-pool-select .select-trigger:hover { + background: color-mix(in srgb, var(--text-primary) 11.5%, var(--surface-panel)); +} + +.cons-cycle-pool-select.is-open .select-trigger { + background: color-mix(in srgb, var(--text-primary) 14%, var(--surface-panel)); +} + +.cons-cycle-pool-select .select-trigger .svg-icon { + width: 11px; + height: 11px; +} + +.cons-cycle-pool-select .select-menu { + right: auto; + min-width: 224px; + width: max-content; + max-width: 280px; +} + .cons-overview-controls { display: inline-flex; align-items: center; diff --git a/sidecars/panel/src/views/ConsumptionView.js b/sidecars/panel/src/views/ConsumptionView.js index 50384bb..2cba9e5 100644 --- a/sidecars/panel/src/views/ConsumptionView.js +++ b/sidecars/panel/src/views/ConsumptionView.js @@ -50,6 +50,7 @@ import { ActionMenu } from '../components/ui/ActionMenu.js'; import { getDefaultCtxInspectorAgentId, prefetchConsumptionPresets, + selectConsumptionCyclePool, selectConsumptionTimeRange, selectConversation, telemetryStore, @@ -61,6 +62,7 @@ import { } from '../components/charts/TrendAreaChart.js'; import { CustomDateTimePicker } from '../components/ui/CustomDateTimePicker.js'; import { CustomScrollbar } from '../components/ui/CustomScrollbar.js'; +import { CustomSelect } from '../components/ui/CustomSelect.js'; import { createFourSegmentBar } from '../components/ui/FourSegmentBar.js'; import { createConsumptionBreakdownContent } from '../components/ui/ConsumptionTooltipContent.js'; import { SegmentedControl } from '../components/ui/SegmentedControl.js'; @@ -95,6 +97,86 @@ function ceilToEndOfMinuteMs(ms) { return d.getTime(); } +function formatCyclePoolShortLabel(poolKey, poolLabel) { + if (poolKey === 'Argon') return 'Argon'; + if (poolKey === 'Carbon') return 'Carbon'; + if (poolKey === 'Claude & GPT') return 'Claude/GPT'; + return poolLabel || poolKey; +} + +function buildCyclePoolSelectOptions(pools, isCustomWeeklyMode = false) { + const list = Array.isArray(pools) ? pools : []; + let sumCycleCost = 0; + let hasAnyCycleCost = false; + for (let i = 0; i < list.length; i++) { + const c = Number(list[i]?.cycleWeekly?.costUsd); + if (Number.isFinite(c) && c >= 0 && list[i]?.cycleWeekly) { + sumCycleCost += c; + hasAnyCycleCost = true; + } + } + const allLabel = t('cons.cyclePoolAll'); + const opts = [ + { + value: 'all', + label: allLabel, + shortLabel: t('cons.cyclePoolAllShort'), + meta: !isCustomWeeklyMode && hasAnyCycleCost ? formatUsd(sumCycleCost) : '', + title: allLabel, + }, + ]; + for (let i = 0; i < list.length; i++) { + const p = list[i]; + const key = String(p?.poolKey || p?.family || '').trim(); + if (!key || key === 'Unknown') continue; + const label = String(p?.poolLabel || key).trim(); + const shortLabel = formatCyclePoolShortLabel(key, label); + const metaParts = []; + if ( + !isCustomWeeklyMode && + p?.weeklyRemainingPct != null && + Number.isFinite(Number(p.weeklyRemainingPct)) + ) { + metaParts.push( + t('cons.cyclePoolRemMeta', { + pct: formatPctNumber(p.weeklyRemainingPct, { withSymbol: true }), + }) + ); + } + if (!isCustomWeeklyMode && p?.cycleWeekly && Number.isFinite(Number(p.cycleWeekly.costUsd))) { + metaParts.push(formatUsd(p.cycleWeekly.costUsd)); + } + const meta = metaParts.join(' · '); + opts.push({ + value: key, + label, + shortLabel, + meta, + title: meta ? `${label} (${meta})` : label, + }); + } + return opts; +} + +function formatCycleMinuteSpanTip(startMs, endMs, isFallbackWeek = false) { + const s = Number(startMs); + const e = Number(endMs); + if (!(s > 0 && e > 0 && Number.isFinite(s) && Number.isFinite(e))) return null; + const sd = new Date(s); + const ed = new Date(e); + const pad2 = (n) => String(n).padStart(2, '0'); + const sTime = `${pad2(sd.getHours())}:${pad2(sd.getMinutes())}`; + const eTime = `${pad2(ed.getHours())}:${pad2(ed.getMinutes())}`; + const sameDay = + sd.getFullYear() === ed.getFullYear() && + sd.getMonth() === ed.getMonth() && + sd.getDate() === ed.getDate(); + const sDate = `${sd.getMonth() + 1}/${pad2(sd.getDate())}`; + const eDate = `${ed.getMonth() + 1}/${pad2(ed.getDate())}`; + const base = sameDay ? `${sDate} ${sTime} ~ ${eTime}` : `${sDate} ${sTime} ~ ${eDate} ${eTime}`; + return isFallbackWeek ? `${base} · ${t('cons.cycleFallbackWeekTip')}` : base; +} + export const ConsumptionView = defineComponent({ name: 'ConsumptionView', setup({ onCleanup }) { @@ -200,6 +282,16 @@ export const ConsumptionView = defineComponent({ // --- Section 1: 用量概览矩阵 (上层 3 列核心总量 + 下层 3 列新输入/缓存读取/输出拆分 + 底部 4 段比例条) --- const dateSpanBadge = h('span', { className: 'cons-badge text-mono', text: '-- ~ --' }); + const cyclePoolSelect = CustomSelect({ + className: 'cons-cycle-pool-select', + modelValue: telemetryStore.getState().selectedCyclePool || 'all', + options: buildCyclePoolSelectOptions([]), + onUpdateModelValue: (nextPool) => { + selectConsumptionCyclePool(nextPool || 'all'); + }, + }); + patchAttr(cyclePoolSelect.el, 'hidden', true); + patchAttr(cyclePoolSelect.refs.triggerBtn, 'aria-label', t('cons.cyclePoolAria')); const heroTotalTokens = h('strong', { className: 'cons-hero-num text-mono', text: '0' }); const heroTotalCalls = h('span', { className: 'text-muted text-mono', style: 'font-size: var(--fs-md);', text: t('cons.callsCount', { calls: 0 }) }); const heroCostUsd = h('strong', { className: 'cons-hero-cost text-mono', text: '$0.00' }); @@ -337,8 +429,9 @@ export const ConsumptionView = defineComponent({ const overviewPanel = h('section', { className: 'panel' }, [ h('div', { className: 'panel-header cons-overview-head' }, [ - h('span', { className: 'panel-title' }, [ + h('span', { className: 'panel-title cons-overview-title' }, [ dateSpanBadge, + cyclePoolSelect.el, ]), h('div', { className: 'cons-overview-controls' }, [ timeFilterSwitch.el, @@ -1791,7 +1884,7 @@ export const ConsumptionView = defineComponent({ const cons = slice.consumption || {}; const rangeInfo = cons.selectedRange || {}; - // 始终在 0ms 同步顶部时间段滑块与自定义日期条显隐,给予即刻交互反馈 + // 始终在 0ms 同步顶部时间段滑块、周期池选择器及自定义日期条显隐,给予即刻交互反馈 timeFilterSwitch.setValue(slice.range); patchAttr(customRangeBar, 'hidden', slice.range !== 'custom'); if (!hasUncommittedCustomDraft) { @@ -1801,17 +1894,45 @@ export const ConsumptionView = defineComponent({ endPicker.setValue(draftEndMs); } + const isCustomWeeklyMode = + slice.weeklyLimitMode === 'custom_tokens' || slice.weeklyLimitMode === 'custom_cost'; + const cyclePoolOptions = + slice.range === 'cycle' + ? buildCyclePoolSelectOptions(slice.quotaPools, isCustomWeeklyMode) + : []; + const activePoolFilter = slice.range === 'cycle' ? slice.cyclePool || 'all' : 'all'; + const showCyclePoolSelect = slice.range === 'cycle' && cyclePoolOptions.length > 2; + if (!showCyclePoolSelect) { + cyclePoolSelect.close?.(); + patchAttr(cyclePoolSelect.el, 'hidden', true); + } else { + cyclePoolSelect.setProps({ + modelValue: activePoolFilter, + options: cyclePoolOptions, + }); + patchAttr(cyclePoolSelect.el, 'hidden', false); + } + // 极少数缓存未命中时(如自定义新区间或进页瞬间抢点),跳过用旧趋势/模型跑无效半更新重绘,待几毫秒后单帧原子绘制 - if (rangeInfo.key && slice.range && rangeInfo.key !== slice.range) { + const payloadPool = rangeInfo.key === 'cycle' ? rangeInfo.pool || 'all' : 'all'; + if ( + (rangeInfo.key && slice.range && rangeInfo.key !== slice.range) || + (slice.range === 'cycle' && rangeInfo.pool && payloadPool !== activePoolFilter) + ) { return; } const preset = - slice.range !== 'custom' && cons.presets?.[slice.range] + slice.range !== 'custom' && + !(slice.range === 'cycle' && activePoolFilter !== 'all') && + cons.presets?.[slice.range] ? cons.presets[slice.range] : null; const acct = cons.account || preset?.account || {}; const dateSpan = formatDateSpanBadge(rangeInfo.startMs, rangeInfo.endMs); + const cycleOptionsSig = showCyclePoolSelect + ? cyclePoolOptions.map((o) => `${o.value}:${o.label}:${o.meta || ''}`).join('|') + : ''; const now = new Date(); const currentMonthIdx = now.getMonth(); const monthlyYear = cons.monthlyYear || now.getFullYear(); @@ -1819,6 +1940,9 @@ export const ConsumptionView = defineComponent({ const renderTuple = [ locale, slice.range, + activePoolFilter, + cycleOptionsSig, + Boolean(rangeInfo.isFallbackWeek), slice.customStartMs, slice.customEndMs, slice.modelDisplayMode, @@ -1839,13 +1963,36 @@ export const ConsumptionView = defineComponent({ cons.monthlySeries, ]; if (isSameRenderTuple(lastRenderedTuple, renderTuple)) return; - drawConsumptionData(slice, { cons, preset, acct, rangeInfo, dateSpan, currentMonthIdx, monthlyYear }); + drawConsumptionData(slice, { + cons, + preset, + acct, + rangeInfo, + activePoolFilter, + dateSpan, + currentMonthIdx, + monthlyYear, + }); lastRenderedTuple = renderTuple; } - function drawConsumptionData(slice, { cons, preset, acct, rangeInfo, dateSpan, currentMonthIdx, monthlyYear }) { - // 1. 同步用量概览矩阵与顶部 4 段比例条 + function drawConsumptionData( + slice, + { cons, preset, acct, rangeInfo, activePoolFilter, dateSpan, currentMonthIdx, monthlyYear } + ) { + // 1. 同步用量概览矩阵及顶部 4 段比例条 patchText(dateSpanBadge, dateSpan); + patchAttr( + dateSpanBadge, + 'title', + slice.range === 'cycle' + ? formatCycleMinuteSpanTip( + rangeInfo.startMs, + rangeInfo.endMs, + Boolean(rangeInfo.isFallbackWeek) + ) + : null + ); const totalTokens = Number(acct.totalTokens || 0); const inputTokens = Number(acct.inputTokens || 0); const cacheTokens = Number(acct.cacheReadTokens || 0); @@ -2036,11 +2183,18 @@ export const ConsumptionView = defineComponent({ ...allTrendMergedModels, ]); - // 2. 同步历史趋势交互式 SVG 面积图 / 类 GitHub 每日热力图(>90天)与悬停分模型浮层 - const rangeBadgeText = isEnglishLocale() - ? getConsumptionTimeRangeOptions().find((o) => o.value === slice.range)?.label || - t('cons.allTime') - : preset?.label || rangeInfo.label || t('cons.allTime'); + // 2. 同步历史趋势交互式 SVG 面积图 / 类 GitHub 每日热力图(>90天)及悬停分模型浮层 + const rangeBadgeText = + slice.range === 'cycle' + ? `${rangeInfo.isFallbackWeek || slice.weeklyLimitMode === 'custom_tokens' || slice.weeklyLimitMode === 'custom_cost' ? t('cons.cycleFallbackWeek') : t('cons.currentCycle')}${ + activePoolFilter && activePoolFilter !== 'all' + ? ` · ${rangeInfo.poolLabel || activePoolFilter}` + : '' + }` + : isEnglishLocale() + ? getConsumptionTimeRangeOptions().find((o) => o.value === slice.range)?.label || + t('cons.allTime') + : preset?.label || rangeInfo.label || t('cons.allTime'); patchText(trendRangeBadge, rangeBadgeText); const firstTrendSlot = rawTrendSeries[0] || null; const isMinuteTrend = firstTrendSlot?.granularity === 'minute'; @@ -2200,7 +2354,7 @@ export const ConsumptionView = defineComponent({ updateRow: (refs, s) => updateSourceBreakdownRow(refs, s, sourcesTotalTok, modelColorMap), }); - const nextRangeSig = `${slice.range || ''}:${slice.customStartMs || 0}:${slice.customEndMs || 0}`; + const nextRangeSig = `${slice.range || ''}:${activePoolFilter || 'all'}:${slice.customStartMs || 0}:${slice.customEndMs || 0}`; const nextRankingKey = showWorkspacesTab ? 'workspaces' : showSessionsTab @@ -2336,8 +2490,11 @@ export const ConsumptionView = defineComponent({ const unsub = telemetryStore.subscribe( (st) => ({ range: st.selectedTimeRange, + cyclePool: st.selectedCyclePool || 'all', customStartMs: st.customStartMs, customEndMs: st.customEndMs, + quotaPools: st.telemetry?.quotas?.pools, + weeklyLimitMode: st.telemetry?.settings?.weeklyLimitMode, consumption: st.telemetry?.consumption, modelBreakdown: st.telemetry?.modelBreakdown, modelDisplayMode: normalizeModelDisplayMode( @@ -2391,6 +2548,7 @@ export const ConsumptionView = defineComponent({ ariaLabel: t('cons.rangeAria'), options: getConsumptionTimeRangeOptions(), }); + patchAttr(cyclePoolSelect.refs.triggerBtn, 'aria-label', t('cons.cyclePoolAria')); patchText(applyCustomBtnLabel, t('cons.applyFilter')); patchText(rangeToSpan, t('cons.rangeTo')); patchText(totalTokensLabel, t('cons.totalTokens')); @@ -2448,6 +2606,7 @@ export const ConsumptionView = defineComponent({ unsubView(); unsubI18n(); consExportMenu.destroy(); + cyclePoolSelect.destroy(); trendChart.destroy?.(); rankingTabSwitch.destroy(); modelsSortSwitch.destroy(); @@ -2462,6 +2621,7 @@ export const ConsumptionView = defineComponent({ el: rootEl, refs: { timeFilterSwitch, + cyclePoolSelect, startPicker, endPicker, viewScrollbar, diff --git a/sidecars/panel/styles.css b/sidecars/panel/styles.css index 4eac4b1..cc3e0d5 100644 --- a/sidecars/panel/styles.css +++ b/sidecars/panel/styles.css @@ -2813,6 +2813,53 @@ html[data-standalone="true"] .app-shell { gap: 6px; } +.cons-overview-title { + display: inline-flex; + align-items: center; + gap: 6px; + min-width: 0; +} + +.cons-cycle-pool-select { + flex: 0 1 auto; + width: auto; + min-width: 0; + max-width: 112px; +} + +.cons-cycle-pool-select .select-trigger { + width: auto; + min-height: calc(20px * var(--ui-font-scale, 1)); + height: auto; + padding: 1px 7px; + gap: 4px; + font-size: var(--fs-sm); + line-height: 1.25; + border: none; + border-radius: var(--radius-pill); + background: color-mix(in srgb, var(--text-primary) 7.5%, var(--surface-panel)); +} + +.cons-cycle-pool-select .select-trigger:hover { + background: color-mix(in srgb, var(--text-primary) 11.5%, var(--surface-panel)); +} + +.cons-cycle-pool-select.is-open .select-trigger { + background: color-mix(in srgb, var(--text-primary) 14%, var(--surface-panel)); +} + +.cons-cycle-pool-select .select-trigger .svg-icon { + width: 11px; + height: 11px; +} + +.cons-cycle-pool-select .select-menu { + right: auto; + min-width: 224px; + width: max-content; + max-width: 280px; +} + .cons-overview-controls { display: inline-flex; align-items: center; @@ -8458,6 +8505,7 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { } [data-modern-ui="true"] .form-row > .custom-select > .select-trigger, +[data-modern-ui="true"] .cons-cycle-pool-select .select-trigger, [data-modern-ui="true"] .steps-inline-scope-select .select-trigger, [data-modern-ui="true"] .steps-inline-model-select .select-trigger, [data-modern-ui="true"] .sstep-fit-model-select .select-trigger { @@ -8468,6 +8516,7 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { } [data-modern-ui="true"] .form-row > .custom-select > .select-trigger:hover, +[data-modern-ui="true"] .cons-cycle-pool-select .select-trigger:hover, [data-modern-ui="true"] .steps-inline-scope-select .select-trigger:hover, [data-modern-ui="true"] .steps-inline-model-select .select-trigger:hover, [data-modern-ui="true"] .sstep-fit-model-select .select-trigger:hover { @@ -8475,6 +8524,7 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell { } [data-modern-ui="true"] .form-row > .custom-select.is-open > .select-trigger, +[data-modern-ui="true"] .cons-cycle-pool-select.is-open .select-trigger, [data-modern-ui="true"] .steps-inline-scope-select.is-open .select-trigger, [data-modern-ui="true"] .steps-inline-model-select.is-open .select-trigger, [data-modern-ui="true"] .sstep-fit-model-select.is-open .select-trigger { diff --git a/sidecars/panel/test/cross-module-regressions.test.mjs b/sidecars/panel/test/cross-module-regressions.test.mjs index 0701578..a591a4f 100644 --- a/sidecars/panel/test/cross-module-regressions.test.mjs +++ b/sidecars/panel/test/cross-module-regressions.test.mjs @@ -1866,6 +1866,64 @@ test('ConsumptionView and TrendAreaChart patch text DOM nodes in-place without o assert.equal(secondGridCells.length, firstGridCells.length); assert.equal(secondGridCells[10], firstGridCells[10], 'Heatmap cell DOM node reused in-place'); + // Switch to 'cycle' with multiple quota pools -> compact inline pool selector becomes visible (and stays hidden on 'today'/'all') + assert.equal(view.refs.cyclePoolSelect.el.hasAttribute('hidden'), true, 'Hidden outside cycle range'); + const cyclePoolsFixture = [ + { + poolKey: 'Gemini', + poolLabel: 'Gemini', + weeklyRemainingPct: 99.7, + cycleWeekly: { calls: 12, tokens: 2_480_000, costUsd: 0.86 }, + }, + { + poolKey: 'Claude & GPT', + poolLabel: 'Claude & GPT', + weeklyRemainingPct: 38.0, + cycleWeekly: { calls: 690, tokens: 172_580_000, costUsd: 61.38 }, + }, + ]; + const baseCyclePayload = makeRangePayload('cycle', 2_480_000, ['12:00', '14:00', '16:00', '18:00']); + baseCyclePayload.quotas = { pools: cyclePoolsFixture }; + baseCyclePayload.consumption.selectedRange = { + key: 'cycle', + pool: 'Gemini', + poolLabel: 'Gemini', + label: '当前周期 · Gemini', + startMs: 1_760_040_000_000, + endMs: 1_760_061_600_000, + }; + telemetryStore.setState( + { + selectedTimeRange: 'cycle', + selectedCyclePool: 'Gemini', + telemetry: baseCyclePayload, + }, + { sync: true } + ); + assert.equal(view.refs.cyclePoolSelect.el.hasAttribute('hidden'), false, 'Shown on cycle with >=2 pools'); + assert.equal(view.refs.cyclePoolSelect.refs.triggerLabel.textContent, 'Gemini'); + const badges = view.el.querySelectorAll('.cons-badge'); + assert.match(badges[1]?.textContent || '', /当前周期 · Gemini/); + + // Open dropdown and verify localized pool metadata + switch back to 'today' hides dropdown + view.refs.cyclePoolSelect.open(); + const optTexts = [...view.refs.cyclePoolSelect.refs.optionsListEl.children].map( + (btn) => btn.textContent + ); + assert.equal(optTexts.length, 3); + assert.match(optTexts[0], /全部池.*\$62\.24/); + assert.match(optTexts[1], /Gemini.*剩 99\.7% · \$0\.86/); + assert.match(optTexts[2], /Claude & GPT.*剩 38\.0% · \$61\.38/); + + telemetryStore.setState( + { + selectedTimeRange: 'today', + telemetry: makeRangePayload('today', 100_000, ['00:00', '06:00', '12:00', '18:00']), + }, + { sync: true } + ); + assert.equal(view.refs.cyclePoolSelect.el.hasAttribute('hidden'), true, 'Re-hidden on today'); + view.destroy(); telemetryStore.setState(prevTelState, { sync: true }); uiStore.setState(prevUiState, { sync: true }); diff --git a/sidecars/panel/test/quota-pools.test.mjs b/sidecars/panel/test/quota-pools.test.mjs index 4ae9a9d..63b5bc2 100644 --- a/sidecars/panel/test/quota-pools.test.mjs +++ b/sidecars/panel/test/quota-pools.test.mjs @@ -824,7 +824,8 @@ test('argon_weekly capsule & CLI slot enables only when user has an Argon weekly }); test('formatPctNumber collapses boundary 0.0 -> 0 and 100.0 -> 100 while preserving intermediate decimals', async () => { - const { formatPctNumber } = await import('../src/core/formatters.js'); + const { formatDateSpanBadge, formatPctNumber } = await import('../src/core/formatters.js'); + const { setI18nLanguage } = await import('../src/i18n/index.js'); assert.equal(formatPctNumber(0), '0'); assert.equal(formatPctNumber(0, { withSymbol: true }), '0%'); assert.equal(formatPctNumber(0.04, { withSymbol: true }), '0%'); @@ -836,4 +837,272 @@ test('formatPctNumber collapses boundary 0.0 -> 0 and 100.0 -> 100 while preserv assert.equal(formatPctNumber(1.0, { withSymbol: true }), '1.0%'); assert.equal(formatPctNumber(50.0, { withSymbol: true }), '50.0%'); assert.equal(formatPctNumber(99.9, { withSymbol: true }), '99.9%'); + + const d24Morning = new Date(2026, 10, 24, 9, 0).getTime(); + const d24Evening = new Date(2026, 10, 24, 19, 30).getTime(); + const d25Evening = new Date(2026, 10, 25, 18, 0).getTime(); + const dOct28 = new Date(2026, 9, 28, 10, 0).getTime(); + const dPrevYear = new Date(2025, 11, 28, 10, 0).getTime(); + + setI18nLanguage('zh-CN'); + assert.equal(formatDateSpanBadge(d24Morning, d24Evening), '11月24日'); + assert.equal(formatDateSpanBadge(d24Morning, d25Evening), '11月24日 ~ 25日'); + assert.equal(formatDateSpanBadge(dOct28, d24Evening), '10月28日 ~ 11月24日'); + assert.equal(formatDateSpanBadge(dPrevYear, d24Evening), '2025年12月28日 ~ 2026年11月24日'); + + setI18nLanguage('en-US'); + assert.equal(formatDateSpanBadge(d24Morning, d24Evening), 'Nov 24'); + assert.equal(formatDateSpanBadge(d24Morning, d25Evening), 'Nov 24 ~ 25'); + assert.equal(formatDateSpanBadge(dOct28, d24Evening), 'Oct 28 ~ Nov 24'); + assert.equal(formatDateSpanBadge(dPrevYear, d24Evening), 'Dec 28, 2025 ~ Nov 24, 2026'); + setI18nLanguage('zh-CN'); +}); + +test('Consumption cycle pool filter isolates Gemini vs Claude & GPT vs Argon across full, consumption, and presets scopes', async () => { + const now = Date.now(); + const CLAUDE_SONNET = 'MODEL_CLAUDE_4_5_SONNET'; + // Gemini weekly cycle refreshed 6h ago (resets in +162h) + const geminiWkReset = new Date(now + 162 * 3600_000).toISOString(); + const gemini5hReset = new Date(now + 2 * 3600_000).toISOString(); + // Argon weekly cycle started 4d ago (resets in +72h) + const argonWkReset = new Date(now + 72 * 3600_000).toISOString(); + // Claude & GPT weekly cycle started 30h ago (resets in +138h) + const claudeWkReset = new Date(now + 138 * 3600_000).toISOString(); + + const makeTimedStep = (idx, model, ageMs, provider, tok) => { + const t = now - ageMs; + return { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + sourceTrajectoryStepInfo: { stepIndex: idx }, + createdAt: new Date(t).toISOString(), + completedAt: new Date(t + 2_000).toISOString(), + modelUsage: { + model, + apiProvider: provider, + inputTokens: String(tok), + cacheReadTokens: '0', + outputTokens: '1000', + }, + }, + }; + }; + + const h = backendHarness({ + summaries: { convPoolSplit: { stepCount: 4 } }, + trajectories: { + convPoolSplit: { + trajectory: { + steps: [ + // 1. Gemini 2h ago -> inside Gemini 6h weekly window (11,000 tok) + makeTimedStep(1, FLASH, 2 * 3600_000, 'API_PROVIDER_GOOGLE_GEMINI', 10_000), + // 2. Gemini 24h ago -> OUTSIDE Gemini 6h weekly window! + makeTimedStep(2, FLASH, 24 * 3600_000, 'API_PROVIDER_GOOGLE_GEMINI', 90_000), + // 3. Claude 24h ago -> INSIDE Claude 30h weekly window (51,000 tok) + makeTimedStep(3, CLAUDE_SONNET, 24 * 3600_000, 'API_PROVIDER_ANTHROPIC', 50_000), + // 4. Argon 48h ago -> INSIDE Argon 4d weekly window (31,000 tok) + makeTimedStep(4, ARGON, 48 * 3600_000, 'API_PROVIDER_GOOGLE_GEMINI', 30_000), + ], + }, + }, + }, + userStatus: { + userTier: { id: 'g1-pro-tier', name: 'Google AI Pro' }, + cascadeModelConfigData: { + clientModelConfigs: [ + { + label: 'Gemini 3.8 Flash (High)', + modelId: 'gemini-3.8-flash-high', + modelOrAlias: { model: FLASH }, + quotaInfo: { remainingFraction: 0.9968, resetTime: gemini5hReset }, + }, + { + label: 'Gemini 4 Argon (High)', + modelId: 'gemini-4-argon-high', + modelOrAlias: { model: ARGON }, + quotaInfo: { remainingFraction: 0.62, resetTime: argonWkReset }, + }, + { + label: 'Claude 4.5 Sonnet', + modelId: 'claude-sonnet-4-5', + modelOrAlias: { model: CLAUDE_SONNET }, + quotaInfo: { remainingFraction: 0.38, resetTime: claudeWkReset }, + }, + ], + }, + }, + quotaSummary: { + groups: [ + { + displayName: 'Gemini Models', + buckets: [ + { bucketId: 'gemini-5h', window: '5h', remainingFraction: 0.99, resetTime: gemini5hReset }, + { bucketId: 'gemini-weekly', window: 'weekly', remainingFraction: 0.9968, resetTime: geminiWkReset }, + ], + }, + { + displayName: 'Gemini 4 Argon', + buckets: [ + { bucketId: 'argon-weekly', window: 'weekly', remainingFraction: 0.62, resetTime: argonWkReset }, + ], + }, + { + displayName: 'Claude and GPT models', + buckets: [ + { bucketId: '3p-weekly', window: 'weekly', remainingFraction: 0.38, resetTime: claudeWkReset }, + ], + }, + ], + }, + }); + + // 1. All-pools cycle: includes step 1 (11k) + step 3 (51k) + step 4 (31k) = 93k + const allCycle = await h.buildTelemetryPayloadInternal('convPoolSplit', false, { range: 'cycle' }); + assert.equal(allCycle.consumption.selectedRange.key, 'cycle'); + assert.equal(allCycle.consumption.selectedRange.pool, 'all'); + assert.equal(allCycle.consumption.account.calls, 3); + assert.equal(allCycle.consumption.account.totalTokens, 93_000); + + // 2. Gemini-only cycle: strictly isolates Gemini post-reset window (11k, start anchored ~6h ago, NOT 30h/48h ago!) + const gemCycle = JSON.parse( + (await h.executeTelemetryAction({ conversationId: 'convPoolSplit', range: 'cycle', pool: 'Gemini', scope: 'consumption' })).body + ); + assert.equal(gemCycle.scope, 'consumption'); + assert.equal(gemCycle.consumption.selectedRange.pool, 'Gemini'); + assert.equal(gemCycle.consumption.selectedRange.poolLabel, 'Gemini'); + assert.equal(gemCycle.consumption.account.calls, 1); + assert.equal(gemCycle.consumption.account.totalTokens, 11_000); + assert.equal(gemCycle.modelBreakdown.length, 1); + assert.match(gemCycle.modelBreakdown[0].label, /Gemini/); + assert.ok( + gemCycle.consumption.selectedRange.startMs >= now - 7 * 3600_000, + 'Gemini cycle startMs must anchor to Gemini 6h-ago reset rather than Claude/Argon earlier cycles' + ); + + // 3. Claude & GPT cycle: strictly isolates Claude 30h window (51k) while global presets.cycle stays 93k on full payload + const claudeFull = await h.buildTelemetryPayloadInternal('convPoolSplit', false, { + range: 'cycle', + pool: 'Claude & GPT', + }); + assert.equal(claudeFull.consumption.selectedRange.pool, 'Claude & GPT'); + assert.equal(claudeFull.consumption.account.calls, 1); + assert.equal(claudeFull.consumption.account.totalTokens, 51_000); + assert.equal(claudeFull.consumption.presets.cycle.account.totalTokens, 93_000); + assert.equal(claudeFull.quotas.weekly.tokens, 93_000); + + // 4. Presets bundle pre-computes cycle: slices for 0ms frontend switching + const presetsBundle = JSON.parse( + (await h.executeTelemetryAction({ conversationId: 'convPoolSplit', scope: 'consumption-presets' })).body + ); + assert.equal(presetsBundle.scope, 'consumption-presets'); + assert.equal(presetsBundle.ranges.cycle.account.totalTokens, 93_000); + assert.equal(presetsBundle.ranges['cycle:Gemini'].account.totalTokens, 11_000); + assert.equal(presetsBundle.ranges['cycle:Argon'].account.totalTokens, 31_000); + assert.equal(presetsBundle.ranges['cycle:Claude & GPT'].account.totalTokens, 51_000); +}); + +test('GetUserStatus >6h weekly resetTime fallback and usageRevision bump when official weekly anchor arrives', async () => { + const now = Date.now(); + const wkResetIso = new Date(now + 161 * 3600_000).toISOString(); // refreshed 7h ago + const recentStepTs = now - 2 * 3600_000; + const preResetStepTs = now - 20 * 3600_000; + + const makeStepAt = (idx, ts, tok) => ({ + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + sourceTrajectoryStepInfo: { stepIndex: idx }, + createdAt: new Date(ts).toISOString(), + completedAt: new Date(ts + 2_000).toISOString(), + modelUsage: { + model: FLASH, + apiProvider: 'API_PROVIDER_GOOGLE_GEMINI', + inputTokens: String(tok), + cacheReadTokens: '0', + outputTokens: '500', + }, + }, + }); + + // Case A: RetrieveUserQuotaSummary failed (null), only GetUserStatus returned >6h weekly resetTime + const hFallback = backendHarness({ + summaries: { convFb: { stepCount: 2 } }, + trajectories: { + convFb: { + trajectory: { + steps: [ + makeStepAt(1, preResetStepTs, 80_000), + makeStepAt(2, recentStepTs, 10_000), + ], + }, + }, + }, + userStatus: { + email: 'cli-user@example.com', + userTier: { id: 'g1-ultra-tier', name: 'Google AI Ultra' }, + cascadeModelConfigData: { + clientModelConfigs: [ + { + label: 'Gemini 3.8 Flash (High)', + modelId: 'gemini-3.8-flash-high', + modelOrAlias: { model: FLASH }, + quotaInfo: { remainingFraction: 0.9968, resetTime: wkResetIso }, + }, + ], + }, + }, + quotaSummary: null, + }); + + const pFb = await hFallback.buildTelemetryPayloadInternal('convFb', false, { range: 'cycle' }); + const gemPoolFb = pFb.quotas.pools.find((p) => p.poolKey === 'Gemini'); + assert.equal(gemPoolFb.weeklyResetTime, wkResetIso, '>6h quotaInfo resetTime must classify as weeklyResetTime'); + assert.equal(gemPoolFb.has5h, false); + assert.equal(pFb.consumption.selectedRange.isFallbackWeek, undefined); + assert.equal(pFb.consumption.account.calls, 1, 'Excludes 20h-ago pre-reset step'); + assert.equal(pFb.consumption.account.totalTokens, 10_500); + + // Case B: Cold start without official weekly anchor -> later official quotaSummary arrives -> usageRevision advances + const hRev = backendHarness({ + summaries: { convRev: { stepCount: 2 } }, + trajectories: { + convRev: { + trajectory: { + steps: [ + makeStepAt(1, preResetStepTs, 80_000), + makeStepAt(2, recentStepTs, 10_000), + ], + }, + }, + }, + userStatus: { + email: 'rev-user@example.com', + userTier: { id: 'g1-ultra-tier', name: 'Google AI Ultra' }, + cascadeModelConfigData: { clientModelConfigs: [] }, + }, + quotaSummary: null, + }); + + const coldPayload = await hRev.buildTelemetryPayloadInternal('convRev', false, { range: 'cycle' }); + assert.equal(coldPayload.consumption.selectedRange.isFallbackWeek, true); + const revBefore = coldPayload.consumption.revision; + + hRev.state.quotaSummary = { + groups: [ + { + displayName: 'Gemini Models', + buckets: [ + { bucketId: 'gemini-weekly', window: 'weekly', remainingFraction: 0.9968, resetTime: wkResetIso }, + ], + }, + ], + }; + const warmPayload = await hRev.buildTelemetryPayloadInternal('convRev', true, { range: 'cycle' }); + assert.equal(warmPayload.consumption.selectedRange.isFallbackWeek, undefined); + assert.equal(warmPayload.consumption.account.calls, 1); + assert.ok( + warmPayload.consumption.revision > revBefore, + 'usageRevision must increment when official weekly reset anchor arrives and alters cycle window' + ); });