feat(panel): add per-pool cycle filter and harden weekly reset anchors

- Add a compact inline quota-pool selector on ConsumptionView when Cycle is active, pre-bundling per-pool cycle slices for instant switching and scoping range labels in exports
- Classify >6h clientModelConfigs resetTime fallbacks as weekly anchors and advance usageRevision when official reset windows arrive or shift
- Deduplicate same-day and same-month date span badges (e.g. Nov 24, Nov 24 ~ 25)
This commit is contained in:
fish
2026-11-24 19:30:53 +09:00
parent 1692599fd8
commit 02237692f7
18 changed files with 1346 additions and 152 deletions
+304 -31
View File
@@ -1499,6 +1499,13 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({
// Consumption View // Consumption View
'cons.rangeCycle': '周期', 'cons.rangeCycle': '周期',
'cons.cyclePoolAll': '全部池',
'cons.cyclePoolAllShort': '全部',
'cons.cyclePoolAria': '当前周期配额池筛选',
'cons.cyclePoolRemMeta': '剩 {pct}',
'cons.currentCycle': '当前周期',
'cons.cycleFallbackWeek': '本周',
'cons.cycleFallbackWeekTip': '未获取官方周限重置时间,暂按自然本周一统计',
'cons.rangeToday': '今天', 'cons.rangeToday': '今天',
'cons.range24h': '1天', 'cons.range24h': '1天',
'cons.range7d': '7天', 'cons.range7d': '7天',
@@ -2398,6 +2405,13 @@ const I18N_MESSAGES_EN_US = Object.freeze({
// Consumption View // Consumption View
'cons.rangeCycle': 'Cycle', '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.rangeToday': 'Today',
'cons.range24h': '24h', 'cons.range24h': '24h',
'cons.range7d': '7d', 'cons.range7d': '7d',
@@ -4153,17 +4167,34 @@ function formatCnyApprox(usdAmount, rate = 7.2) {
function formatDateSpanBadge(startMs, endMs) { function formatDateSpanBadge(startMs, endMs) {
const s = startMs && Number.isFinite(startMs) ? new Date(startMs) : new Date(); const s = startMs && Number.isFinite(startMs) ? new Date(startMs) : new Date();
const e = endMs && Number.isFinite(endMs) ? new Date(endMs) : 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()) { if (isEnglishLocale()) {
const sMon = EN_MONTH_SHORT[s.getMonth()] || ''; const sMon = EN_MONTH_SHORT[s.getMonth()] || '';
const eMon = EN_MONTH_SHORT[e.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()}`; 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()}`; 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()}日`; 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()}日`; return `${s.getMonth() + 1}月${s.getDate()}日 ~ ${e.getMonth() + 1}月${e.getDate()}日`;
} }
@@ -6909,10 +6940,18 @@ function formatExportDate(ms) {
function resolveLocalizedRangeLabel(range, en) { function resolveLocalizedRangeLabel(range, en) {
const r = range || {}; const r = range || {};
const key = String(r.key || '').trim().toLowerCase(); const key = String(r.key || '').trim().toLowerCase();
const poolSuffix =
key === 'cycle' && r.pool && r.pool !== 'all' ? ` · ${r.poolLabel || r.pool}` : '';
if (en) { 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) { function resolveRangeSpanNote(range) {
@@ -8989,7 +9028,7 @@ return { revealExportedFile, exportTextFileWithFeedback, exportBinaryFileWithFee
})(); })();
// --- src/store/telemetryStore.js --- // --- 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 * @fileoverview Reactive telemetry store with async non-overlapping poll scheduler
* and granular slice updates. * and granular slice updates.
@@ -9076,6 +9115,7 @@ const telemetryStore = createReactiveStore({
selectedConversationId: initialConversationId, selectedConversationId: initialConversationId,
hostRouteConversationId: extractHostRouteCascadeId(), hostRouteConversationId: extractHostRouteCascadeId(),
selectedTimeRange: 'today', selectedTimeRange: 'today',
selectedCyclePool: 'all',
customStartMs: Date.now() - 24 * 3600 * 1000, customStartMs: Date.now() - 24 * 3600 * 1000,
customEndMs: Date.now(), customEndMs: Date.now(),
syncState: 'idle', // 'idle' | 'syncing' | 'synced' | 'error' syncState: 'idle', // 'idle' | 'syncing' | 'synced' | 'error'
@@ -9097,7 +9137,7 @@ let inFlightTelemetryPoll = null;
let inFlightPresetsPrefetch = null; let inFlightPresetsPrefetch = null;
let lastPrefetchedUsageRevision = 0; let lastPrefetchedUsageRevision = 0;
let consumptionCacheScopeSig = ''; let consumptionCacheScopeSig = '';
const MAX_CONSUMPTION_RANGE_CACHE = 12; const MAX_CONSUMPTION_RANGE_CACHE = 24;
const MAX_CONVERSATION_VIEW_CACHE = 12; const MAX_CONVERSATION_VIEW_CACHE = 12;
const CONSUMPTION_PRESET_KEYS = ['cycle', 'today', '24h', '7d', '14d', '30d', 'all']; const CONSUMPTION_PRESET_KEYS = ['cycle', 'today', '24h', '7d', '14d', '30d', 'all'];
const consumptionRangeCache = new Map(); const consumptionRangeCache = new Map();
@@ -9119,11 +9159,19 @@ const TELEMETRY_RECOMPUTE_SETTING_KEYS = new Set([
'enableWindowOverlay', 'enableWindowOverlay',
]); ]);
function makeConsumptionRangeCacheKey(range, customStartMs = 0, customEndMs = 0) { function makeConsumptionRangeCacheKey(
range,
customStartMs = 0,
customEndMs = 0,
cyclePool = 'all'
) {
const key = String(range || 'all'); const key = String(range || 'all');
if (key === 'custom') { if (key === 'custom') {
return `custom:${Number(customStartMs || 0)}:${Number(customEndMs || 0)}`; return `custom:${Number(customStartMs || 0)}:${Number(customEndMs || 0)}`;
} }
if (key === 'cycle' && cyclePool && cyclePool !== 'all') {
return `cycle:${String(cyclePool)}`;
}
return key; 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 || '')}`; 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) { function syncConsumptionCacheScope(payload) {
const nextSig = buildConsumptionScopeSig(payload); const nextSig = buildConsumptionScopeSig(payload);
if (!nextSig) return; if (!nextSig) return;
@@ -9158,6 +9217,7 @@ function syncConsumptionCacheScope(payload) {
clearConversationViewCache(); clearConversationViewCache();
} }
consumptionCacheScopeSig = nextSig; consumptionCacheScopeSig = nextSig;
reconcileSelectedCyclePool(payload);
} }
function recordConversationViewToCache(payload) { function recordConversationViewToCache(payload) {
@@ -9273,14 +9333,19 @@ function putConsumptionRangeCacheEntry(cacheKey, entry) {
function recordConsumptionSliceToCache( function recordConsumptionSliceToCache(
cons, cons,
modelBreakdown, modelBreakdown,
{ customStartMs = 0, customEndMs = 0, usageRevision = 0 } = {} { customStartMs = 0, customEndMs = 0, cyclePool = 'all', usageRevision = 0 } = {}
) { ) {
const rangeKey = String(cons?.selectedRange?.key || ''); const rangeKey = String(cons?.selectedRange?.key || '');
if (!rangeKey) return; if (!rangeKey) return;
const resolvedPool =
rangeKey === 'cycle'
? String(cons?.selectedRange?.pool || cyclePool || 'all')
: 'all';
const cacheKey = makeConsumptionRangeCacheKey( const cacheKey = makeConsumptionRangeCacheKey(
rangeKey, rangeKey,
rangeKey === 'custom' ? customStartMs || cons.selectedRange?.startMs || 0 : 0, 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, { putConsumptionRangeCacheEntry(cacheKey, {
revision: Number(cons.revision ?? usageRevision ?? 0), revision: Number(cons.revision ?? usageRevision ?? 0),
@@ -9828,11 +9893,14 @@ function isEquivalentTelemetry(prev, next) {
} }
} }
// 5. 比对消费统计所选时间区间、当前会话累计消费与账号全局累计消费 // 5. 比对消费统计所选时间区间、当前会话累计消费和账号全局累计消费
const pRange = prev.consumption?.selectedRange; const pRange = prev.consumption?.selectedRange;
const nRange = next.consumption?.selectedRange; const nRange = next.consumption?.selectedRange;
if (pRange?.key !== nRange?.key) return false; 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; if (pRange?.startMs !== nRange?.startMs || pRange?.endMs !== nRange?.endMs) return false;
} }
@@ -10159,6 +10227,13 @@ async function fetchTelemetry({ force = false } = {}) {
const params = new URLSearchParams(); const params = new URLSearchParams();
if (effectiveConvId) params.set('conversationId', effectiveConvId); if (effectiveConvId) params.set('conversationId', effectiveConvId);
if (current.selectedTimeRange) params.set('range', current.selectedTimeRange); 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.selectedTimeRange === 'custom') {
if (current.customStartMs > 0) params.set('startMs', String(current.customStartMs)); if (current.customStartMs > 0) params.set('startMs', String(current.customStartMs));
if (current.customEndMs > 0) params.set('endMs', String(current.customEndMs)); if (current.customEndMs > 0) params.set('endMs', String(current.customEndMs));
@@ -10206,6 +10281,7 @@ async function requestTelemetry(params, force) {
const reqSeq = ++latestRequestSeq; const reqSeq = ++latestRequestSeq;
const reqSettingsRev = settingsRevision; const reqSettingsRev = settingsRevision;
const reqRange = String(params.get('range') || ''); const reqRange = String(params.get('range') || '');
const reqPool = String(params.get('pool') || 'all');
const reqStartMs = Number(params.get('startMs') || 0); const reqStartMs = Number(params.get('startMs') || 0);
const reqEndMs = Number(params.get('endMs') || 0); const reqEndMs = Number(params.get('endMs') || 0);
const startMs = Date.now(); const startMs = Date.now();
@@ -10265,14 +10341,17 @@ async function requestTelemetry(params, force) {
recordConsumptionSliceToCache(resolvedPayload.consumption, resolvedPayload.modelBreakdown, { recordConsumptionSliceToCache(resolvedPayload.consumption, resolvedPayload.modelBreakdown, {
customStartMs: reqStartMs, customStartMs: reqStartMs,
customEndMs: reqEndMs, customEndMs: reqEndMs,
cyclePool: reqPool,
}); });
} }
const latestSt = telemetryStore.getState(); const latestSt = telemetryStore.getState();
const incomingRev = Number(resolvedPayload?.consumption?.revision || 0); const incomingRev = Number(resolvedPayload?.consumption?.revision || 0);
const activePoolPref = latestSt.selectedCyclePool || 'all';
const matchesCurrentRange = const matchesCurrentRange =
!reqRange || !reqRange ||
(reqRange === latestSt.selectedTimeRange && (reqRange === latestSt.selectedTimeRange &&
(reqRange !== 'cycle' || reqPool === activePoolPref) &&
(reqRange !== 'custom' || (reqRange !== 'custom' ||
(reqStartMs === Number(latestSt.customStartMs || 0) && (reqStartMs === Number(latestSt.customStartMs || 0) &&
reqEndMs === Number(latestSt.customEndMs || 0)))); reqEndMs === Number(latestSt.customEndMs || 0))));
@@ -10284,7 +10363,8 @@ async function requestTelemetry(params, force) {
const activeKey = makeConsumptionRangeCacheKey( const activeKey = makeConsumptionRangeCacheKey(
latestSt.selectedTimeRange, latestSt.selectedTimeRange,
latestSt.customStartMs, latestSt.customStartMs,
latestSt.customEndMs latestSt.customEndMs,
activePoolPref
); );
const cachedActive = consumptionRangeCache.get(activeKey); const cachedActive = consumptionRangeCache.get(activeKey);
if (cachedActive) { if (cachedActive) {
@@ -10293,7 +10373,9 @@ async function requestTelemetry(params, force) {
needsSilentRangeRevalidate = true; needsSilentRangeRevalidate = true;
} }
} else if ( } 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 = {
...resolvedPayload, ...resolvedPayload,
@@ -10345,6 +10427,7 @@ async function requestTelemetry(params, force) {
range: latestSt.selectedTimeRange, range: latestSt.selectedTimeRange,
customStartMs: latestSt.customStartMs, customStartMs: latestSt.customStartMs,
customEndMs: latestSt.customEndMs, customEndMs: latestSt.customEndMs,
cyclePool: latestSt.selectedCyclePool || 'all',
}); });
} }
return resolvedPayload; return resolvedPayload;
@@ -10370,15 +10453,20 @@ async function fetchConsumptionRangeSlice({
range, range,
customStartMs = 0, customStartMs = 0,
customEndMs = 0, customEndMs = 0,
cyclePool = 'all',
} = {}) { } = {}) {
const reqEpoch = endpointSwitchEpoch; const reqEpoch = endpointSwitchEpoch;
const reqSeq = ++latestConsumptionReqSeq; const reqSeq = ++latestConsumptionReqSeq;
const targetRange = String(range || 'today'); const targetRange = String(range || 'today');
const targetPool = targetRange === 'cycle' ? String(cyclePool || 'all') : 'all';
const current = telemetryStore.getState(); const current = telemetryStore.getState();
const effectiveConvId = current.selectedConversationId || current.hostRouteConversationId || ''; const effectiveConvId = current.selectedConversationId || current.hostRouteConversationId || '';
const params = new URLSearchParams(); const params = new URLSearchParams();
if (effectiveConvId) params.set('conversationId', effectiveConvId); if (effectiveConvId) params.set('conversationId', effectiveConvId);
params.set('range', targetRange); params.set('range', targetRange);
if (targetRange === 'cycle' && targetPool !== 'all') {
params.set('pool', targetPool);
}
if (targetRange === 'custom') { if (targetRange === 'custom') {
if (customStartMs > 0) params.set('startMs', String(customStartMs)); if (customStartMs > 0) params.set('startMs', String(customStartMs));
if (customEndMs > 0) params.set('endMs', String(customEndMs)); if (customEndMs > 0) params.set('endMs', String(customEndMs));
@@ -10397,6 +10485,7 @@ async function fetchConsumptionRangeSlice({
recordConsumptionSliceToCache(payload.consumption, payload.modelBreakdown, { recordConsumptionSliceToCache(payload.consumption, payload.modelBreakdown, {
customStartMs, customStartMs,
customEndMs, customEndMs,
cyclePool: targetPool,
usageRevision: usageRev, usageRevision: usageRev,
}); });
if (reqSeq !== latestConsumptionReqSeq) return payload; if (reqSeq !== latestConsumptionReqSeq) return payload;
@@ -10404,6 +10493,7 @@ async function fetchConsumptionRangeSlice({
const latestSt = telemetryStore.getState(); const latestSt = telemetryStore.getState();
const stillMatches = const stillMatches =
latestSt.selectedTimeRange === targetRange && latestSt.selectedTimeRange === targetRange &&
(targetRange !== 'cycle' || (latestSt.selectedCyclePool || 'all') === targetPool) &&
(targetRange !== 'custom' || (targetRange !== 'custom' ||
(Number(latestSt.customStartMs || 0) === Number(customStartMs || 0) && (Number(latestSt.customStartMs || 0) === Number(customStartMs || 0) &&
Number(latestSt.customEndMs || 0) === Number(customEndMs || 0))); Number(latestSt.customEndMs || 0) === Number(customEndMs || 0)));
@@ -10509,6 +10599,13 @@ async function selectConversation(
const params = new URLSearchParams(); const params = new URLSearchParams();
if (effectiveConvId) params.set('conversationId', effectiveConvId); if (effectiveConvId) params.set('conversationId', effectiveConvId);
if (current.selectedTimeRange) params.set('range', current.selectedTimeRange); 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.selectedTimeRange === 'custom') {
if (current.customStartMs > 0) params.set('startMs', String(current.customStartMs)); if (current.customStartMs > 0) params.set('startMs', String(current.customStartMs));
if (current.customEndMs > 0) params.set('endMs', String(current.customEndMs)); if (current.customEndMs > 0) params.set('endMs', String(current.customEndMs));
@@ -10615,7 +10712,7 @@ async function selectConversation(
*/ */
function selectConsumptionTimeRange( function selectConsumptionTimeRange(
nextRange, nextRange,
{ customStartMs = undefined, customEndMs = undefined } = {} { customStartMs = undefined, customEndMs = undefined, cyclePool = undefined } = {}
) { ) {
const targetRange = String(nextRange || 'today'); const targetRange = String(nextRange || 'today');
const prevSt = telemetryStore.getState(); const prevSt = telemetryStore.getState();
@@ -10627,14 +10724,26 @@ function selectConsumptionTimeRange(
targetRange === 'custom' targetRange === 'custom'
? Number(customEndMs !== undefined ? customEndMs : prevSt.customEndMs || 0) ? Number(customEndMs !== undefined ? customEndMs : prevSt.customEndMs || 0)
: prevSt.customEndMs; : prevSt.customEndMs;
const nextCyclePool =
targetRange === 'cycle'
? String(cyclePool !== undefined ? cyclePool || 'all' : prevSt.selectedCyclePool || 'all')
: prevSt.selectedCyclePool || 'all';
const statePatch = { selectedTimeRange: targetRange }; const statePatch = { selectedTimeRange: targetRange };
if (cyclePool !== undefined) {
statePatch.selectedCyclePool = nextCyclePool;
}
if (targetRange === 'custom') { if (targetRange === 'custom') {
statePatch.customStartMs = nextStartMs; statePatch.customStartMs = nextStartMs;
statePatch.customEndMs = nextEndMs; 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 cached = consumptionRangeCache.get(cacheKey);
const prevTelemetry = prevSt.telemetry; const prevTelemetry = prevSt.telemetry;
@@ -10653,6 +10762,7 @@ function selectConsumptionTimeRange(
range: targetRange, range: targetRange,
customStartMs: nextStartMs, customStartMs: nextStartMs,
customEndMs: nextEndMs, customEndMs: nextEndMs,
cyclePool: nextCyclePool,
}); });
} }
@@ -10661,9 +10771,14 @@ function selectConsumptionTimeRange(
range: targetRange, range: targetRange,
customStartMs: nextStartMs, customStartMs: nextStartMs,
customEndMs: nextEndMs, customEndMs: nextEndMs,
cyclePool: nextCyclePool,
}); });
} }
function selectConsumptionCyclePool(nextPool = 'all') {
return selectConsumptionTimeRange('cycle', { cyclePool: String(nextPool || 'all') });
}
/** /**
* 仅在进入「用量统计」视图时触发一次静默后台预取,拉齐全部 7 个预设区间到前端缓存以实现 0ms 瞬切。 * 仅在进入「用量统计」视图时触发一次静默后台预取,拉齐全部 7 个预设区间到前端缓存以实现 0ms 瞬切。
*/ */
@@ -11338,7 +11453,7 @@ function isMacHostPlatform(telemetry) {
} }
return false; 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 --- // --- src/components/ui/TopLongPillNav.js ---
@@ -12044,8 +12159,8 @@ const CustomSelect = defineComponent({
const fallbackText = modelValue const fallbackText = modelValue
? `${placeholder} (${String(modelValue).slice(0, 8)})` ? `${placeholder} (${String(modelValue).slice(0, 8)})`
: placeholder; : placeholder;
labelText = selectedOpt ? selectedOpt.label : fallbackText; labelText = selectedOpt ? selectedOpt.shortLabel || selectedOpt.label : fallbackText;
titleText = labelText; titleText = selectedOpt ? selectedOpt.title || selectedOpt.label : fallbackText;
} }
patchText(triggerLabel, labelText); patchText(triggerLabel, labelText);
@@ -30029,6 +30144,86 @@ function ceilToEndOfMinuteMs(ms) {
return d.getTime(); 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({ const ConsumptionView = defineComponent({
name: 'ConsumptionView', name: 'ConsumptionView',
setup({ onCleanup }) { setup({ onCleanup }) {
@@ -30134,6 +30329,16 @@ const ConsumptionView = defineComponent({
// --- Section 1: 用量概览矩阵 (上层 3 列核心总量 + 下层 3 列新输入/缓存读取/输出拆分 + 底部 4 段比例条) --- // --- Section 1: 用量概览矩阵 (上层 3 列核心总量 + 下层 3 列新输入/缓存读取/输出拆分 + 底部 4 段比例条) ---
const dateSpanBadge = h('span', { className: 'cons-badge text-mono', text: '-- ~ --' }); 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 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 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' }); 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' }, [ const overviewPanel = h('section', { className: 'panel' }, [
h('div', { className: 'panel-header cons-overview-head' }, [ h('div', { className: 'panel-header cons-overview-head' }, [
h('span', { className: 'panel-title' }, [ h('span', { className: 'panel-title cons-overview-title' }, [
dateSpanBadge, dateSpanBadge,
cyclePoolSelect.el,
]), ]),
h('div', { className: 'cons-overview-controls' }, [ h('div', { className: 'cons-overview-controls' }, [
timeFilterSwitch.el, timeFilterSwitch.el,
@@ -31725,7 +31931,7 @@ const ConsumptionView = defineComponent({
const cons = slice.consumption || {}; const cons = slice.consumption || {};
const rangeInfo = cons.selectedRange || {}; const rangeInfo = cons.selectedRange || {};
// 始终在 0ms 同步顶部时间段滑块与自定义日期条显隐,给予即刻交互反馈 // 始终在 0ms 同步顶部时间段滑块、周期池选择器及自定义日期条显隐,给予即刻交互反馈
timeFilterSwitch.setValue(slice.range); timeFilterSwitch.setValue(slice.range);
patchAttr(customRangeBar, 'hidden', slice.range !== 'custom'); patchAttr(customRangeBar, 'hidden', slice.range !== 'custom');
if (!hasUncommittedCustomDraft) { if (!hasUncommittedCustomDraft) {
@@ -31735,17 +31941,45 @@ const ConsumptionView = defineComponent({
endPicker.setValue(draftEndMs); 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; return;
} }
const preset = 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] ? cons.presets[slice.range]
: null; : null;
const acct = cons.account || preset?.account || {}; const acct = cons.account || preset?.account || {};
const dateSpan = formatDateSpanBadge(rangeInfo.startMs, rangeInfo.endMs); 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 now = new Date();
const currentMonthIdx = now.getMonth(); const currentMonthIdx = now.getMonth();
const monthlyYear = cons.monthlyYear || now.getFullYear(); const monthlyYear = cons.monthlyYear || now.getFullYear();
@@ -31753,6 +31987,9 @@ const ConsumptionView = defineComponent({
const renderTuple = [ const renderTuple = [
locale, locale,
slice.range, slice.range,
activePoolFilter,
cycleOptionsSig,
Boolean(rangeInfo.isFallbackWeek),
slice.customStartMs, slice.customStartMs,
slice.customEndMs, slice.customEndMs,
slice.modelDisplayMode, slice.modelDisplayMode,
@@ -31773,13 +32010,36 @@ const ConsumptionView = defineComponent({
cons.monthlySeries, cons.monthlySeries,
]; ];
if (isSameRenderTuple(lastRenderedTuple, renderTuple)) return; 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; lastRenderedTuple = renderTuple;
} }
function drawConsumptionData(slice, { cons, preset, acct, rangeInfo, dateSpan, currentMonthIdx, monthlyYear }) { function drawConsumptionData(
// 1. 同步用量概览矩阵与顶部 4 段比例条 slice,
{ cons, preset, acct, rangeInfo, activePoolFilter, dateSpan, currentMonthIdx, monthlyYear }
) {
// 1. 同步用量概览矩阵及顶部 4 段比例条
patchText(dateSpanBadge, dateSpan); 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 totalTokens = Number(acct.totalTokens || 0);
const inputTokens = Number(acct.inputTokens || 0); const inputTokens = Number(acct.inputTokens || 0);
const cacheTokens = Number(acct.cacheReadTokens || 0); const cacheTokens = Number(acct.cacheReadTokens || 0);
@@ -31970,11 +32230,18 @@ const ConsumptionView = defineComponent({
...allTrendMergedModels, ...allTrendMergedModels,
]); ]);
// 2. 同步历史趋势交互式 SVG 面积图 / 类 GitHub 每日热力图(>90天)与悬停分模型浮层 // 2. 同步历史趋势交互式 SVG 面积图 / 类 GitHub 每日热力图(>90天)及悬停分模型浮层
const rangeBadgeText = isEnglishLocale() const rangeBadgeText =
? getConsumptionTimeRangeOptions().find((o) => o.value === slice.range)?.label || slice.range === 'cycle'
t('cons.allTime') ? `${rangeInfo.isFallbackWeek || slice.weeklyLimitMode === 'custom_tokens' || slice.weeklyLimitMode === 'custom_cost' ? t('cons.cycleFallbackWeek') : t('cons.currentCycle')}${
: preset?.label || rangeInfo.label || t('cons.allTime'); 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); patchText(trendRangeBadge, rangeBadgeText);
const firstTrendSlot = rawTrendSeries[0] || null; const firstTrendSlot = rawTrendSeries[0] || null;
const isMinuteTrend = firstTrendSlot?.granularity === 'minute'; const isMinuteTrend = firstTrendSlot?.granularity === 'minute';
@@ -32134,7 +32401,7 @@ const ConsumptionView = defineComponent({
updateRow: (refs, s) => updateSourceBreakdownRow(refs, s, sourcesTotalTok, modelColorMap), 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 const nextRankingKey = showWorkspacesTab
? 'workspaces' ? 'workspaces'
: showSessionsTab : showSessionsTab
@@ -32270,8 +32537,11 @@ const ConsumptionView = defineComponent({
const unsub = telemetryStore.subscribe( const unsub = telemetryStore.subscribe(
(st) => ({ (st) => ({
range: st.selectedTimeRange, range: st.selectedTimeRange,
cyclePool: st.selectedCyclePool || 'all',
customStartMs: st.customStartMs, customStartMs: st.customStartMs,
customEndMs: st.customEndMs, customEndMs: st.customEndMs,
quotaPools: st.telemetry?.quotas?.pools,
weeklyLimitMode: st.telemetry?.settings?.weeklyLimitMode,
consumption: st.telemetry?.consumption, consumption: st.telemetry?.consumption,
modelBreakdown: st.telemetry?.modelBreakdown, modelBreakdown: st.telemetry?.modelBreakdown,
modelDisplayMode: normalizeModelDisplayMode( modelDisplayMode: normalizeModelDisplayMode(
@@ -32325,6 +32595,7 @@ const ConsumptionView = defineComponent({
ariaLabel: t('cons.rangeAria'), ariaLabel: t('cons.rangeAria'),
options: getConsumptionTimeRangeOptions(), options: getConsumptionTimeRangeOptions(),
}); });
patchAttr(cyclePoolSelect.refs.triggerBtn, 'aria-label', t('cons.cyclePoolAria'));
patchText(applyCustomBtnLabel, t('cons.applyFilter')); patchText(applyCustomBtnLabel, t('cons.applyFilter'));
patchText(rangeToSpan, t('cons.rangeTo')); patchText(rangeToSpan, t('cons.rangeTo'));
patchText(totalTokensLabel, t('cons.totalTokens')); patchText(totalTokensLabel, t('cons.totalTokens'));
@@ -32382,6 +32653,7 @@ const ConsumptionView = defineComponent({
unsubView(); unsubView();
unsubI18n(); unsubI18n();
consExportMenu.destroy(); consExportMenu.destroy();
cyclePoolSelect.destroy();
trendChart.destroy?.(); trendChart.destroy?.();
rankingTabSwitch.destroy(); rankingTabSwitch.destroy();
modelsSortSwitch.destroy(); modelsSortSwitch.destroy();
@@ -32396,6 +32668,7 @@ const ConsumptionView = defineComponent({
el: rootEl, el: rootEl,
refs: { refs: {
timeFilterSwitch, timeFilterSwitch,
cyclePoolSelect,
startPicker, startPicker,
endPicker, endPicker,
viewScrollbar, viewScrollbar,
+2
View File
@@ -258,8 +258,10 @@ export async function executeTelemetryAction(data, opts = {}) {
rawScope === 'conversation' rawScope === 'conversation'
? rawScope ? rawScope
: ''; : '';
const rawPool = typeof data?.pool === 'string' ? data.pool.trim().slice(0, 48) : '';
const filterOpts = { const filterOpts = {
range: data?.range || 'all', range: data?.range || 'all',
...(rawPool ? { pool: rawPool } : {}),
startMs: sanitizePositiveFiniteMs(data?.startMs), startMs: sanitizePositiveFiniteMs(data?.startMs),
endMs: sanitizePositiveFiniteMs(data?.endMs), endMs: sanitizePositiveFiniteMs(data?.endMs),
...(scope ? { scope } : {}), ...(scope ? { scope } : {}),
+7 -2
View File
@@ -370,9 +370,14 @@ export function buildOfficialQuotaPools(officialQuota, clientConfigs = []) {
} }
const cfgQuota = normalizeQuotaFraction(cfg?.quotaInfo, nowForQuotaMs); 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 (!builder.bucket5h && !builder.bucketWeekly && !builder.fallback5h && cfgQuota) {
if (targetIdent.poolKey === 'Argon' || targetIdent.poolKey === 'Carbon') { if (isCfgWeekly) {
builder.bucketWeekly = cfgQuota; builder.bucketWeekly = { ...cfgQuota, window: 'weekly' };
} else { } else {
builder.fallback5h = cfgQuota; builder.fallback5h = cfgQuota;
} }
+7 -1
View File
@@ -2382,6 +2382,9 @@ export async function buildTelemetryPayloadInternal(
revision: usageRevision, revision: usageRevision,
selectedRange: { selectedRange: {
key: selectedWindow.key, key: selectedWindow.key,
...(selectedWindow.pool ? { pool: selectedWindow.pool } : {}),
...(selectedWindow.poolLabel ? { poolLabel: selectedWindow.poolLabel } : {}),
...(selectedWindow.isFallbackWeek ? { isFallbackWeek: true } : {}),
label: selectedWindow.label, label: selectedWindow.label,
startMs: trendStartMs, startMs: trendStartMs,
endMs: trendEndMs, endMs: trendEndMs,
@@ -2802,6 +2805,9 @@ function tryBuildFastConsumptionPayload(filterOpts = {}) {
revision: agg.usageRevision, revision: agg.usageRevision,
selectedRange: { selectedRange: {
key: agg.selectedWindow.key, 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, label: agg.selectedWindow.label,
startMs: agg.trendStartMs, startMs: agg.trendStartMs,
endMs: agg.trendEndMs, 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}`; const key = `${endpointKey}::${requestedConvId || '__auto__'}::${forceQuotaRefresh ? 'force' : 'normal'}::${rangeSig}`;
if (inFlightRequests.has(key)) { if (inFlightRequests.has(key)) {
return inFlightRequests.get(key); return inFlightRequests.get(key);
+292 -86
View File
@@ -786,13 +786,14 @@ function buildQuotaPoolCycleMap(quotaPoolsMap, nowMs) {
? Math.min(nowMs, reset5hMs - 5 * 3600 * 1000) ? Math.min(nowMs, reset5hMs - 5 * 3600 * 1000)
: nowMs - 5 * 3600 * 1000; : nowMs - 5 * 3600 * 1000;
const resetWkMs = parseIsoMs(poolObj?.weeklyResetTime) || 0; const resetWkMs = parseIsoMs(poolObj?.weeklyResetTime) || 0;
const startWkMs = const hasOfficialWk = resetWkMs > nowMs;
resetWkMs > nowMs const startWkMs = hasOfficialWk
? Math.min(nowMs, resetWkMs - 7 * 24 * 3600 * 1000) ? Math.min(nowMs, resetWkMs - 7 * 24 * 3600 * 1000)
: weekFallbackStartMs; : weekFallbackStartMs;
poolCycleBuckets.set(poolKey, { poolCycleBuckets.set(poolKey, {
start5hMs, start5hMs,
startWkMs, startWkMs,
hasOfficialWk,
b5h: createUsageBucket(), b5h: createUsageBucket(),
bWk: createUsageBucket(), bWk: createUsageBucket(),
pricedTokens5h: 0, pricedTokens5h: 0,
@@ -809,7 +810,27 @@ function buildQuotaPoolCycleMap(quotaPoolsMap, nowMs) {
return poolCycleBuckets; 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, st,
mInfo, mInfo,
poolCycleBuckets, poolCycleBuckets,
@@ -817,7 +838,6 @@ function resolvePoolBucketForStep(
hasDedicatedCarbonPool, hasDedicatedCarbonPool,
hasDedicatedArgonPool hasDedicatedArgonPool
) { ) {
if (poolCycleBuckets.size === 0) return null;
let cachedPool = poolByModel.get(mInfo); let cachedPool = poolByModel.get(mInfo);
if ( if (
!cachedPool || !cachedPool ||
@@ -841,11 +861,68 @@ function resolvePoolBucketForStep(
key: st.modelKey, key: st.modelKey,
response: st.responseModel, response: st.responseModel,
displayName: st.modelDisplayName, displayName: st.modelDisplayName,
bucket: poolCycleBuckets.get(poolKey) || null, poolKey,
bucket: poolKey && poolCycleBuckets.size > 0 ? poolCycleBuckets.get(poolKey) || null : null,
}; };
poolByModel.set(mInfo, cachedPool); 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( function buildUsageTrendSeries(
@@ -1155,6 +1232,7 @@ function computeFamilySessionBuckets({
presetKeys = [], presetKeys = [],
presetWindows = {}, presetWindows = {},
selectedWindow, selectedWindow,
effectiveCyclePool = 'all',
isCustomWeeklyMode = false, isCustomWeeklyMode = false,
poolCycleBuckets = new Map(), poolCycleBuckets = new Map(),
normalizedQuotaAccount = '', normalizedQuotaAccount = '',
@@ -1166,8 +1244,11 @@ function computeFamilySessionBuckets({
for (const k of presetKeys) { for (const k of presetKeys) {
sessionBuckets[k] = createUsageBucket(); sessionBuckets[k] = createUsageBucket();
} }
const isScopedCyclePool = selectedWindow?.key === 'cycle' && effectiveCyclePool !== 'all';
const selectedSessionBucket = 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) { if (!(familySet instanceof Set) || familySet.size === 0) {
const sessionPresets = {}; const sessionPresets = {};
for (const k of presetKeys) { for (const k of presetKeys) {
@@ -1233,17 +1314,15 @@ function computeFamilySessionBuckets({
unpriced, unpriced,
}; };
const poolBucketEntry = const stepPool = resolveStepPoolAssignment(
poolCycleBuckets.size > 0 st,
? resolvePoolBucketForStep( mInfo,
st, poolCycleBuckets,
mInfo, poolByModel,
poolCycleBuckets, hasDedicatedCarbonPool,
poolByModel, hasDedicatedArgonPool
hasDedicatedCarbonPool, );
hasDedicatedArgonPool const poolBucketEntry = stepPool.bucket;
)
: null;
let inCurrentCycle = false; let inCurrentCycle = false;
if (qMs > 0 && qMs <= nowMs) { 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 = const selCmpMs =
selectedWindow.key === '5h' || selectedWindow.key === 'week' ? qMs : tMs; selectedWindow.key === '5h' || selectedWindow.key === 'week' ? qMs : tMs;
const inSelectedWindow = const inSelectedWindow =
selectedWindow.key === 'all' selectedWindow.key === 'all'
? true ? true
: selectedWindow.key === 'cycle' : selectedWindow.key === 'cycle'
? inCurrentCycle ? inCurrentCycle && (effectiveCyclePool === 'all' || stepPool.poolKey === effectiveCyclePool)
: selCmpMs > 0 && selCmpMs >= selectedWindow.startMs && selCmpMs <= selectedWindow.endMs; : selCmpMs > 0 && selCmpMs >= selectedWindow.startMs && selCmpMs <= selectedWindow.endMs;
if (inSelectedWindow) { if (inSelectedWindow) {
accumulateStepIntoBucket(selectedSessionBucket, stepUsage, entry.cascadeId); accumulateStepIntoBucket(selectedSessionBucket, stepUsage, entry.cascadeId);
@@ -1407,16 +1491,30 @@ export function aggregateMultiWindowUsage({
sessionBuckets[k] = createUsageBucket(); sessionBuckets[k] = createUsageBucket();
} }
// 为每个配额池建立独立的 5h 与周限周期统计桶(按各池自身的 resetTime / weeklyResetTime 截取窗口) // 为每个配额池建立独立的 5h 及周限周期统计桶(按各池自身的 resetTime / weeklyResetTime 截取窗口)
const poolCycleBuckets = buildQuotaPoolCycleMap(quotaPoolsMap, nowMs); 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 hasDedicatedCarbonPool = poolCycleBuckets.has('Carbon');
const hasDedicatedArgonPool = poolCycleBuckets.has('Argon'); const hasDedicatedArgonPool = poolCycleBuckets.has('Argon');
const poolByModel = new Map(); const poolByModel = new Map();
const quotaWeekBucket = createUsageBucket(); const quotaWeekBucket = createUsageBucket();
const normalizedQuotaAccount = const normalizedQuotaAccount =
currentAccountName === null ? null : normalizeOwnerAccount(currentAccountName); currentAccountName === null ? null : normalizeOwnerAccount(currentAccountName);
const selectedAccountBucket = accountBuckets[selectedWindow.key] || createUsageBucket(); const selectedAccountBucket =
const selectedSessionBucket = sessionBuckets[selectedWindow.key] || createUsageBucket(); !isScopedCyclePool && accountBuckets[selectedWindow.key]
? accountBuckets[selectedWindow.key]
: createUsageBucket();
const selectedSessionBucket =
!isScopedCyclePool && sessionBuckets[selectedWindow.key]
? sessionBuckets[selectedWindow.key]
: createUsageBucket();
const perModelStats = new Map(); const perModelStats = new Map();
const perConvStats = new Map(); const perConvStats = new Map();
const perWorkspaceStats = new Map(); const perWorkspaceStats = new Map();
@@ -1463,15 +1561,31 @@ export function aggregateMultiWindowUsage({
modelInputs.catalogRevision === snapshot.modelInputs.catalogRevision && modelInputs.catalogRevision === snapshot.modelInputs.catalogRevision &&
isDeepStrictEqual(modelInputs.dynamicModelMap, snapshot.modelInputs.dynamicModelMap) && isDeepStrictEqual(modelInputs.dynamicModelMap, snapshot.modelInputs.dynamicModelMap) &&
sameUsageEntries(snapshot.entries, allEntriesToAggregate); sameUsageEntries(snapshot.entries, allEntriesToAggregate);
const previous = sameSnapshot ? snapshot.ranges.get(selectedWindow.key) : null; const previous = sameSnapshot ? snapshot.ranges.get(selectedRangeCacheKey) : null;
if (previous) { if (previous) {
// 时钟继续前进,只有实际有步骤跨过窗口边界时才重新聚合。 // 时钟继续前进,只有实际有步骤跨过窗口边界时才重新聚合。
const probeEffectiveWin =
selectedWindow.key === 'cycle'
? resolveEffectiveSelectedCycleWindow({
selectedWindow,
effectiveCyclePool,
isCustomWeeklyMode,
cycleAnchors,
nowMs,
poolCycleBuckets,
quotaPoolsMap,
earliestActiveCyclePoolStartMs: previous.earliestActiveCyclePoolStartMs,
earliestSelectedStepMs: previous.earliest,
})
: selectedWindow;
const effectivePrevWin = const effectivePrevWin =
selectedWindow.key === 'cycle' && previous.effectiveSelectedWindow selectedWindow.key === 'cycle' && previous.effectiveSelectedWindow
? { ...previous.effectiveSelectedWindow, endMs: nowMs } ? { ...probeEffectiveWin, endMs: nowMs }
: selectedWindow; : selectedWindow;
const trend = planUsageTrend(effectivePrevWin, nowMs, previous.earliest, previous.latest); const trend = planUsageTrend(effectivePrevWin, nowMs, previous.earliest, previous.latest);
if ( if (
Boolean(effectivePrevWin.isFallbackWeek) ===
Boolean(previous.effectiveSelectedWindow?.isFallbackWeek) &&
trend.hourly === previous.trend.hourly && trend.hourly === previous.trend.hourly &&
trend.stepMs === previous.trend.stepMs && trend.stepMs === previous.trend.stepMs &&
trend.first === previous.trend.first && trend.first === previous.trend.first &&
@@ -1483,8 +1597,8 @@ export function aggregateMultiWindowUsage({
(snapshot.quotaDates ??= sortedQuotaBillingTimestamps(allEntriesToAggregate, nowMs)) (snapshot.quotaDates ??= sortedQuotaBillingTimestamps(allEntriesToAggregate, nowMs))
) )
) { ) {
snapshot.ranges.delete(selectedWindow.key); snapshot.ranges.delete(selectedRangeCacheKey);
snapshot.ranges.set(selectedWindow.key, previous); snapshot.ranges.set(selectedRangeCacheKey, previous);
if (previous.familySig === familySig) { if (previous.familySig === familySig) {
return { return {
...previous.result, ...previous.result,
@@ -1501,6 +1615,7 @@ export function aggregateMultiWindowUsage({
presetKeys, presetKeys,
presetWindows, presetWindows,
selectedWindow, selectedWindow,
effectiveCyclePool,
isCustomWeeklyMode, isCustomWeeklyMode,
poolCycleBuckets, poolCycleBuckets,
normalizedQuotaAccount, normalizedQuotaAccount,
@@ -1588,7 +1703,7 @@ export function aggregateMultiWindowUsage({
} }
} }
const poolBucketEntry = resolvePoolBucketForStep( const stepPool = resolveStepPoolAssignment(
st, st,
mInfo, mInfo,
poolCycleBuckets, poolCycleBuckets,
@@ -1596,6 +1711,7 @@ export function aggregateMultiWindowUsage({
hasDedicatedCarbonPool, hasDedicatedCarbonPool,
hasDedicatedArgonPool hasDedicatedArgonPool
); );
const poolBucketEntry = stepPool.bucket;
if (includeInQuotaPools && poolBucketEntry && qMs > 0 && qMs <= nowMs) { if (includeInQuotaPools && poolBucketEntry && qMs > 0 && qMs <= nowMs) {
if (qMs > poolBucketEntry.lastActivityMs) { if (qMs > poolBucketEntry.lastActivityMs) {
@@ -1691,7 +1807,7 @@ export function aggregateMultiWindowUsage({
selectedWindow.key === 'all' selectedWindow.key === 'all'
? true ? true
: selectedWindow.key === 'cycle' : selectedWindow.key === 'cycle'
? inCurrentCycle ? inCurrentCycle && (effectiveCyclePool === 'all' || stepPool.poolKey === effectiveCyclePool)
: selCmpMs > 0 && selCmpMs >= selectedWindow.startMs && selCmpMs <= selectedWindow.endMs; : selCmpMs > 0 && selCmpMs >= selectedWindow.startMs && selCmpMs <= selectedWindow.endMs;
if (inSelectedWindow) { if (inSelectedWindow) {
@@ -1703,7 +1819,7 @@ export function aggregateMultiWindowUsage({
) { ) {
earliestActiveCyclePoolStartMs = poolBucketEntry.startWkMs; earliestActiveCyclePoolStartMs = poolBucketEntry.startWkMs;
} }
if (selectedWindow.key === 'custom') { if (selectedWindow.key === 'custom' || isScopedCyclePool) {
accumulateStepIntoBucket(selectedAccountBucket, stepUsage, cascadeId); accumulateStepIntoBucket(selectedAccountBucket, stepUsage, cascadeId);
if (isCurrentConv) { if (isCurrentConv) {
accumulateStepIntoBucket(selectedSessionBucket, stepUsage, cascadeId); accumulateStepIntoBucket(selectedSessionBucket, stepUsage, cascadeId);
@@ -1785,15 +1901,17 @@ export function aggregateMultiWindowUsage({
); );
// 构建当前选定时间窗口的自适应自然整点/整日趋势序列 (trendSeries) // 构建当前选定时间窗口的自适应自然整点/整日趋势序列 (trendSeries)
const effectiveSelectedWindow = const effectiveSelectedWindow = resolveEffectiveSelectedCycleWindow({
selectedWindow.key === 'cycle' && selectedWindow,
Number.isFinite(earliestActiveCyclePoolStartMs) && effectiveCyclePool,
earliestActiveCyclePoolStartMs < Infinity isCustomWeeklyMode,
? { cycleAnchors,
...selectedWindow, nowMs,
startMs: Math.min(earliestActiveCyclePoolStartMs, earliestSelectedStepMs), poolCycleBuckets,
} quotaPoolsMap,
: selectedWindow; earliestActiveCyclePoolStartMs,
earliestSelectedStepMs,
});
const { trend, trendStartMs, trendEndMs, trendSeries } = buildUsageTrendSeries( const { trend, trendStartMs, trendEndMs, trendSeries } = buildUsageTrendSeries(
selectedWindow, selectedWindow,
effectiveSelectedWindow, effectiveSelectedWindow,
@@ -1929,6 +2047,11 @@ export function aggregateMultiWindowUsage({
if (oldestKey !== undefined) lastUsageSnapshotsByEndpoint.delete(oldestKey); if (oldestKey !== undefined) lastUsageSnapshotsByEndpoint.delete(oldestKey);
} }
lastUsageSnapshotsByEndpoint.set(endpointKey, activeSnap); lastUsageSnapshotsByEndpoint.set(endpointKey, activeSnap);
} else if (previous) {
resolvedUsageRevision = ++usageSnapshotRevisionSeq;
activeSnap.revision = resolvedUsageRevision;
activeSnap.ranges.clear();
activeSnap.selectedRanges?.clear?.();
} else { } else {
resolvedUsageRevision = activeSnap.revision; resolvedUsageRevision = activeSnap.revision;
} }
@@ -1959,19 +2082,20 @@ export function aggregateMultiWindowUsage({
}; };
if (modelInputs && activeSnap) { if (modelInputs && activeSnap) {
const { ranges } = activeSnap; const { ranges } = activeSnap;
ranges.delete(selectedWindow.key); ranges.delete(selectedRangeCacheKey);
ranges.set(selectedWindow.key, { ranges.set(selectedRangeCacheKey, {
familySig, familySig,
windows, windows,
selectedWindow, selectedWindow,
effectiveSelectedWindow, effectiveSelectedWindow,
earliestActiveCyclePoolStartMs,
trend, trend,
result, result,
earliest: earliestSelectedStepMs, earliest: earliestSelectedStepMs,
latest: latestSelectedStepMs, latest: latestSelectedStepMs,
}); });
// 缓存各时间窗口的完整多窗口聚合结果,同快照复用时亚毫秒命中。 // 缓存各时间窗口的完整多窗口聚合结果,同快照复用时亚毫秒命中。
if (ranges.size > 10) ranges.delete(ranges.keys().next().value); if (ranges.size > 16) ranges.delete(ranges.keys().next().value);
} }
return result; return result;
} }
@@ -2019,6 +2143,14 @@ export function aggregateSelectedWindowUsage({
: 0; : 0;
const poolCycleBuckets = const poolCycleBuckets =
selectedWindow.key === 'cycle' ? buildQuotaPoolCycleMap(quotaPoolsMap, nowMs) : new Map(); 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 hasDedicatedCarbonPool = poolCycleBuckets.has('Carbon');
const hasDedicatedArgonPool = poolCycleBuckets.has('Argon'); const hasDedicatedArgonPool = poolCycleBuckets.has('Argon');
const poolByModel = new Map(); const poolByModel = new Map();
@@ -2032,6 +2164,19 @@ export function aggregateSelectedWindowUsage({
const currentYear = new Date(nowMs).getFullYear(); const currentYear = new Date(nowMs).getFullYear();
const timeZone = modelInputs ? resolveCachedLocalTimeZone() : ''; 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 snapshot = lastUsageSnapshotsByEndpoint.get(endpointKey) || null;
const sameSnapshot = Boolean( const sameSnapshot = Boolean(
modelInputs && modelInputs &&
@@ -2047,24 +2192,45 @@ export function aggregateSelectedWindowUsage({
if (sameSnapshot) { if (sameSnapshot) {
snapshot.selectedRanges ??= new Map(); snapshot.selectedRanges ??= new Map();
const cachedFull = snapshot.ranges.get(selectedWindow.key); const cachedFull = snapshot.ranges.get(selectedRangeCacheKey);
const cachedLite = snapshot.selectedRanges.get(selectedWindow.key); const cachedLite = snapshot.selectedRanges.get(selectedRangeCacheKey);
const candidate = cachedFull || cachedLite; const candidate = cachedFull || cachedLite;
if (candidate) { if (candidate) {
const prevWin = candidate.selectedWindow || candidate.windows?.[0] || selectedWindow; 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 = const effectivePrevWin =
selectedWindow.key === 'cycle' && candidate.effectiveSelectedWindow selectedWindow.key === 'cycle' && candidate.effectiveSelectedWindow
? { ...candidate.effectiveSelectedWindow, endMs: nowMs } ? { ...probeEffectiveWin, endMs: nowMs }
: selectedWindow; : selectedWindow;
const trend = planUsageTrend(effectivePrevWin, nowMs, candidate.earliest, candidate.latest); const trend = planUsageTrend(effectivePrevWin, nowMs, candidate.earliest, candidate.latest);
const prevCheckWindows = candidate.checkWindows || [prevWin];
const compareNextWindows =
prevCheckWindows.length === currentCheckWindows.length
? currentCheckWindows
: [selectedWindow];
if ( if (
Boolean(effectivePrevWin.isFallbackWeek) ===
Boolean(candidate.effectiveSelectedWindow?.isFallbackWeek) &&
trend.hourly === candidate.trend.hourly && trend.hourly === candidate.trend.hourly &&
trend.stepMs === candidate.trend.stepMs && trend.stepMs === candidate.trend.stepMs &&
trend.first === candidate.trend.first && trend.first === candidate.trend.first &&
trend.last === candidate.trend.last && trend.last === candidate.trend.last &&
sameUsageWindows( sameUsageWindows(
[prevWin], prevCheckWindows.length === compareNextWindows.length ? prevCheckWindows : [prevWin],
[selectedWindow], compareNextWindows,
(snapshot.dates ??= sortedUsageTimestamps(allEntriesToAggregate)), (snapshot.dates ??= sortedUsageTimestamps(allEntriesToAggregate)),
(snapshot.quotaDates ??= sortedQuotaBillingTimestamps(allEntriesToAggregate, nowMs)) (snapshot.quotaDates ??= sortedQuotaBillingTimestamps(allEntriesToAggregate, nowMs))
) )
@@ -2079,6 +2245,7 @@ export function aggregateSelectedWindowUsage({
presetKeys: [], presetKeys: [],
presetWindows: {}, presetWindows: {},
selectedWindow, selectedWindow,
effectiveCyclePool,
isCustomWeeklyMode, isCustomWeeklyMode,
poolCycleBuckets, poolCycleBuckets,
normalizedQuotaAccount, normalizedQuotaAccount,
@@ -2100,6 +2267,9 @@ export function aggregateSelectedWindowUsage({
topWorkspaces: res.topWorkspaces || [], topWorkspaces: res.topWorkspaces || [],
}; };
} }
snapshot.revision = ++usageSnapshotRevisionSeq;
snapshot.ranges.clear();
snapshot.selectedRanges.clear();
} }
} }
@@ -2115,6 +2285,11 @@ export function aggregateSelectedWindowUsage({
maxCutoffMs = nowMs; maxCutoffMs = nowMs;
if (isCustomWeeklyMode) { if (isCustomWeeklyMode) {
minCutoffMs = weekStartMs; minCutoffMs = weekStartMs;
} else if (effectiveCyclePool !== 'all' && poolCycleBuckets.has(effectiveCyclePool)) {
minCutoffMs = Math.max(
0,
poolCycleBuckets.get(effectiveCyclePool).startWkMs - maxSettlementSlackMs
);
} else if (poolCycleBuckets.size > 0) { } else if (poolCycleBuckets.size > 0) {
minCutoffMs = selectedWindow.startMs; minCutoffMs = selectedWindow.startMs;
for (const entry of poolCycleBuckets.values()) { for (const entry of poolCycleBuckets.values()) {
@@ -2190,20 +2365,24 @@ export function aggregateSelectedWindowUsage({
: normalizedQuotaAccount === '' || stepOwner === '' : normalizedQuotaAccount === '' || stepOwner === ''
? true ? true
: stepOwner === normalizedQuotaAccount; : 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; let inCurrentCycle = false;
if (isCustomWeeklyMode) { if (isCustomWeeklyMode) {
inCurrentCycle = tMs >= weekStartMs; inCurrentCycle = tMs >= weekStartMs;
} else if (poolCycleBuckets.size > 0) { } else if (poolCycleBuckets.size > 0) {
if (!includeInQuotaPools) continue; if (!includeInQuotaPools) continue;
mInfo = resolveStepModel(st);
poolBucketEntry = resolvePoolBucketForStep(
st,
mInfo,
poolCycleBuckets,
poolByModel,
hasDedicatedCarbonPool,
hasDedicatedArgonPool
);
const effCycleStartMs = poolBucketEntry const effCycleStartMs = poolBucketEntry
? poolBucketEntry.startWkMs ? poolBucketEntry.startWkMs
: selectedWindow.startMs; : selectedWindow.startMs;
@@ -2320,15 +2499,17 @@ export function aggregateSelectedWindowUsage({
} }
} }
const effectiveSelectedWindow = const effectiveSelectedWindow = resolveEffectiveSelectedCycleWindow({
selectedWindow.key === 'cycle' && selectedWindow,
Number.isFinite(earliestActiveCyclePoolStartMs) && effectiveCyclePool,
earliestActiveCyclePoolStartMs < Infinity isCustomWeeklyMode,
? { cycleAnchors,
...selectedWindow, nowMs,
startMs: Math.min(earliestActiveCyclePoolStartMs, earliestSelectedStepMs), poolCycleBuckets,
} quotaPoolsMap,
: selectedWindow; earliestActiveCyclePoolStartMs,
earliestSelectedStepMs,
});
const { trend, trendStartMs, trendEndMs, trendSeries } = buildUsageTrendSeries( const { trend, trendStartMs, trendEndMs, trendSeries } = buildUsageTrendSeries(
selectedWindow, selectedWindow,
@@ -2369,17 +2550,19 @@ export function aggregateSelectedWindowUsage({
if (sameSnapshot) { if (sameSnapshot) {
snapshot.selectedRanges ??= new Map(); snapshot.selectedRanges ??= new Map();
snapshot.selectedRanges.delete(selectedWindow.key); snapshot.selectedRanges.delete(selectedRangeCacheKey);
snapshot.selectedRanges.set(selectedWindow.key, { snapshot.selectedRanges.set(selectedRangeCacheKey, {
familySig, familySig,
checkWindows: currentCheckWindows,
selectedWindow, selectedWindow,
effectiveSelectedWindow, effectiveSelectedWindow,
earliestActiveCyclePoolStartMs,
trend, trend,
result: sliceResult, result: sliceResult,
earliest: earliestSelectedStepMs, earliest: earliestSelectedStepMs,
latest: latestSelectedStepMs, latest: latestSelectedStepMs,
}); });
if (snapshot.selectedRanges.size > 12) { if (snapshot.selectedRanges.size > 16) {
snapshot.selectedRanges.delete(snapshot.selectedRanges.keys().next().value); snapshot.selectedRanges.delete(snapshot.selectedRanges.keys().next().value);
} }
} }
@@ -2426,6 +2609,10 @@ export function aggregateSessionUsageForFamily({
presetWindows[k] = resolveTimeWindow(k, 0, 0, nowMs, cycleAnchors, isCustomWeeklyMode); presetWindows[k] = resolveTimeWindow(k, 0, 0, nowMs, cycleAnchors, isCustomWeeklyMode);
} }
const poolCycleBuckets = buildQuotaPoolCycleMap(quotaPoolsMap, nowMs); const poolCycleBuckets = buildQuotaPoolCycleMap(quotaPoolsMap, nowMs);
const effectiveCyclePool =
selectedWindow.key === 'cycle'
? normalizeCyclePoolFilter(filterOpts.pool, poolCycleBuckets)
: 'all';
const normalizedQuotaAccount = const normalizedQuotaAccount =
currentAccountName === null ? null : normalizeOwnerAccount(currentAccountName); currentAccountName === null ? null : normalizeOwnerAccount(currentAccountName);
@@ -2464,6 +2651,7 @@ export function aggregateSessionUsageForFamily({
presetKeys, presetKeys,
presetWindows, presetWindows,
selectedWindow, selectedWindow,
effectiveCyclePool,
isCustomWeeklyMode, isCustomWeeklyMode,
poolCycleBuckets, poolCycleBuckets,
normalizedQuotaAccount, normalizedQuotaAccount,
@@ -2473,7 +2661,7 @@ export function aggregateSessionUsageForFamily({
} }
/** /**
* 批量预聚合全部 7 个用量页预设区间(复用同一次条目收集与时间剪枝),供前端进入「用量统计」时静默预取实现 0ms 瞬切。 * 批量预聚合全部 7 个用量页预设区间及各配额池独立周期(复用同一次条目收集和时间剪枝),供前端进入「用量统计」时静默预取实现 0ms 瞬切。
*/ */
export function aggregateConsumptionPresetBundle(params) { export function aggregateConsumptionPresetBundle(params) {
const { activeCascadeId = null, activeFamilyCascadeIds = null, endpoint = null } = params || {}; const { activeCascadeId = null, activeFamilyCascadeIds = null, endpoint = null } = params || {};
@@ -2488,6 +2676,25 @@ export function aggregateConsumptionPresetBundle(params) {
const ranges = {}; const ranges = {};
let usageRevision = usageSnapshotRevisionSeq; 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) { for (const rangeKey of CONSUMPTION_PRESET_RANGE_KEYS) {
const agg = aggregateSelectedWindowUsage({ const agg = aggregateSelectedWindowUsage({
...params, ...params,
@@ -2495,21 +2702,20 @@ export function aggregateConsumptionPresetBundle(params) {
precollectedEntries, precollectedEntries,
}); });
usageRevision = agg.usageRevision; usageRevision = agg.usageRevision;
ranges[rangeKey] = { ranges[rangeKey] = packSlice(agg);
selectedRange: { }
key: agg.selectedWindow.key,
label: agg.selectedWindow.label, if (params?.quotaPoolsMap instanceof Map) {
startMs: agg.trendStartMs, for (const poolKey of params.quotaPoolsMap.keys()) {
endMs: agg.trendEndMs, if (!poolKey || poolKey === 'all') continue;
}, const agg = aggregateSelectedWindowUsage({
session: agg.finalizedSelectedSession, ...params,
account: agg.finalizedSelectedAccount, filterOpts: { range: 'cycle', pool: poolKey },
trendSeries: agg.trendSeries, precollectedEntries,
sourcesBreakdown: agg.sourcesBreakdown, });
modelBreakdown: agg.modelBreakdown, usageRevision = agg.usageRevision;
topConversations: agg.topConversations || [], ranges[`cycle:${poolKey}`] = packSlice(agg);
topWorkspaces: agg.topWorkspaces || [], }
};
} }
return { usageRevision, ranges }; return { usageRevision, ranges };
+2 -2
View File
@@ -4,11 +4,11 @@
<meta charset="utf-8"> <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<title>用量监控</title> <title>用量监控</title>
<link rel="stylesheet" href="/styles.css?v=1795515788175"> <link rel="stylesheet" href="/styles.css?v=1795515995591">
<script src="/preload.js"></script> <script src="/preload.js"></script>
</head> </head>
<body> <body>
<div id="app-root"></div> <div id="app-root"></div>
<script src="/app.js?v=1795515788175"></script> <script src="/app.js?v=1795515995591"></script>
</body> </body>
</html> </html>
@@ -469,8 +469,8 @@ export const CustomSelect = defineComponent({
const fallbackText = modelValue const fallbackText = modelValue
? `${placeholder} (${String(modelValue).slice(0, 8)})` ? `${placeholder} (${String(modelValue).slice(0, 8)})`
: placeholder; : placeholder;
labelText = selectedOpt ? selectedOpt.label : fallbackText; labelText = selectedOpt ? selectedOpt.shortLabel || selectedOpt.label : fallbackText;
titleText = labelText; titleText = selectedOpt ? selectedOpt.title || selectedOpt.label : fallbackText;
} }
patchText(triggerLabel, labelText); patchText(triggerLabel, labelText);
+19 -2
View File
@@ -104,17 +104,34 @@ export function formatCnyApprox(usdAmount, rate = 7.2) {
export function formatDateSpanBadge(startMs, endMs) { export function formatDateSpanBadge(startMs, endMs) {
const s = startMs && Number.isFinite(startMs) ? new Date(startMs) : new Date(); const s = startMs && Number.isFinite(startMs) ? new Date(startMs) : new Date();
const e = endMs && Number.isFinite(endMs) ? new Date(endMs) : 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()) { if (isEnglishLocale()) {
const sMon = EN_MONTH_SHORT[s.getMonth()] || ''; const sMon = EN_MONTH_SHORT[s.getMonth()] || '';
const eMon = EN_MONTH_SHORT[e.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()}`; 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()}`; 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()}日`; 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()}日`; return `${s.getMonth() + 1}月${s.getDate()}日 ~ ${e.getMonth() + 1}月${e.getDate()}日`;
} }
+10 -2
View File
@@ -99,10 +99,18 @@ function formatExportDate(ms) {
function resolveLocalizedRangeLabel(range, en) { function resolveLocalizedRangeLabel(range, en) {
const r = range || {}; const r = range || {};
const key = String(r.key || '').trim().toLowerCase(); const key = String(r.key || '').trim().toLowerCase();
const poolSuffix =
key === 'cycle' && r.pool && r.pool !== 'all' ? ` · ${r.poolLabel || r.pool}` : '';
if (en) { 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) { function resolveRangeSpanNote(range) {
+7
View File
@@ -240,6 +240,13 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
// Consumption View // Consumption View
'cons.rangeCycle': 'Cycle', '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.rangeToday': 'Today',
'cons.range24h': '24h', 'cons.range24h': '24h',
'cons.range7d': '7d', 'cons.range7d': '7d',
+7
View File
@@ -240,6 +240,13 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
// Consumption View // Consumption View
'cons.rangeCycle': '周期', 'cons.rangeCycle': '周期',
'cons.cyclePoolAll': '全部池',
'cons.cyclePoolAllShort': '全部',
'cons.cyclePoolAria': '当前周期配额池筛选',
'cons.cyclePoolRemMeta': '剩 {pct}',
'cons.currentCycle': '当前周期',
'cons.cycleFallbackWeek': '本周',
'cons.cycleFallbackWeekTip': '未获取官方周限重置时间,暂按自然本周一统计',
'cons.rangeToday': '今天', 'cons.rangeToday': '今天',
'cons.range24h': '1天', 'cons.range24h': '1天',
'cons.range7d': '7天', 'cons.range7d': '7天',
+86 -10
View File
@@ -148,6 +148,7 @@ export const telemetryStore = createReactiveStore({
selectedConversationId: initialConversationId, selectedConversationId: initialConversationId,
hostRouteConversationId: extractHostRouteCascadeId(), hostRouteConversationId: extractHostRouteCascadeId(),
selectedTimeRange: 'today', selectedTimeRange: 'today',
selectedCyclePool: 'all',
customStartMs: Date.now() - 24 * 3600 * 1000, customStartMs: Date.now() - 24 * 3600 * 1000,
customEndMs: Date.now(), customEndMs: Date.now(),
syncState: 'idle', // 'idle' | 'syncing' | 'synced' | 'error' syncState: 'idle', // 'idle' | 'syncing' | 'synced' | 'error'
@@ -169,7 +170,7 @@ let inFlightTelemetryPoll = null;
let inFlightPresetsPrefetch = null; let inFlightPresetsPrefetch = null;
let lastPrefetchedUsageRevision = 0; let lastPrefetchedUsageRevision = 0;
let consumptionCacheScopeSig = ''; let consumptionCacheScopeSig = '';
const MAX_CONSUMPTION_RANGE_CACHE = 12; const MAX_CONSUMPTION_RANGE_CACHE = 24;
const MAX_CONVERSATION_VIEW_CACHE = 12; const MAX_CONVERSATION_VIEW_CACHE = 12;
const CONSUMPTION_PRESET_KEYS = ['cycle', 'today', '24h', '7d', '14d', '30d', 'all']; const CONSUMPTION_PRESET_KEYS = ['cycle', 'today', '24h', '7d', '14d', '30d', 'all'];
const consumptionRangeCache = new Map(); const consumptionRangeCache = new Map();
@@ -191,11 +192,19 @@ const TELEMETRY_RECOMPUTE_SETTING_KEYS = new Set([
'enableWindowOverlay', 'enableWindowOverlay',
]); ]);
function makeConsumptionRangeCacheKey(range, customStartMs = 0, customEndMs = 0) { function makeConsumptionRangeCacheKey(
range,
customStartMs = 0,
customEndMs = 0,
cyclePool = 'all'
) {
const key = String(range || 'all'); const key = String(range || 'all');
if (key === 'custom') { if (key === 'custom') {
return `custom:${Number(customStartMs || 0)}:${Number(customEndMs || 0)}`; return `custom:${Number(customStartMs || 0)}:${Number(customEndMs || 0)}`;
} }
if (key === 'cycle' && cyclePool && cyclePool !== 'all') {
return `cycle:${String(cyclePool)}`;
}
return key; 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 || '')}`; 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) { function syncConsumptionCacheScope(payload) {
const nextSig = buildConsumptionScopeSig(payload); const nextSig = buildConsumptionScopeSig(payload);
if (!nextSig) return; if (!nextSig) return;
@@ -230,6 +250,7 @@ function syncConsumptionCacheScope(payload) {
clearConversationViewCache(); clearConversationViewCache();
} }
consumptionCacheScopeSig = nextSig; consumptionCacheScopeSig = nextSig;
reconcileSelectedCyclePool(payload);
} }
function recordConversationViewToCache(payload) { function recordConversationViewToCache(payload) {
@@ -345,14 +366,19 @@ function putConsumptionRangeCacheEntry(cacheKey, entry) {
function recordConsumptionSliceToCache( function recordConsumptionSliceToCache(
cons, cons,
modelBreakdown, modelBreakdown,
{ customStartMs = 0, customEndMs = 0, usageRevision = 0 } = {} { customStartMs = 0, customEndMs = 0, cyclePool = 'all', usageRevision = 0 } = {}
) { ) {
const rangeKey = String(cons?.selectedRange?.key || ''); const rangeKey = String(cons?.selectedRange?.key || '');
if (!rangeKey) return; if (!rangeKey) return;
const resolvedPool =
rangeKey === 'cycle'
? String(cons?.selectedRange?.pool || cyclePool || 'all')
: 'all';
const cacheKey = makeConsumptionRangeCacheKey( const cacheKey = makeConsumptionRangeCacheKey(
rangeKey, rangeKey,
rangeKey === 'custom' ? customStartMs || cons.selectedRange?.startMs || 0 : 0, 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, { putConsumptionRangeCacheEntry(cacheKey, {
revision: Number(cons.revision ?? usageRevision ?? 0), revision: Number(cons.revision ?? usageRevision ?? 0),
@@ -900,11 +926,14 @@ export function isEquivalentTelemetry(prev, next) {
} }
} }
// 5. 比对消费统计所选时间区间、当前会话累计消费与账号全局累计消费 // 5. 比对消费统计所选时间区间、当前会话累计消费和账号全局累计消费
const pRange = prev.consumption?.selectedRange; const pRange = prev.consumption?.selectedRange;
const nRange = next.consumption?.selectedRange; const nRange = next.consumption?.selectedRange;
if (pRange?.key !== nRange?.key) return false; 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; 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(); const params = new URLSearchParams();
if (effectiveConvId) params.set('conversationId', effectiveConvId); if (effectiveConvId) params.set('conversationId', effectiveConvId);
if (current.selectedTimeRange) params.set('range', current.selectedTimeRange); 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.selectedTimeRange === 'custom') {
if (current.customStartMs > 0) params.set('startMs', String(current.customStartMs)); if (current.customStartMs > 0) params.set('startMs', String(current.customStartMs));
if (current.customEndMs > 0) params.set('endMs', String(current.customEndMs)); if (current.customEndMs > 0) params.set('endMs', String(current.customEndMs));
@@ -1278,6 +1314,7 @@ async function requestTelemetry(params, force) {
const reqSeq = ++latestRequestSeq; const reqSeq = ++latestRequestSeq;
const reqSettingsRev = settingsRevision; const reqSettingsRev = settingsRevision;
const reqRange = String(params.get('range') || ''); const reqRange = String(params.get('range') || '');
const reqPool = String(params.get('pool') || 'all');
const reqStartMs = Number(params.get('startMs') || 0); const reqStartMs = Number(params.get('startMs') || 0);
const reqEndMs = Number(params.get('endMs') || 0); const reqEndMs = Number(params.get('endMs') || 0);
const startMs = Date.now(); const startMs = Date.now();
@@ -1337,14 +1374,17 @@ async function requestTelemetry(params, force) {
recordConsumptionSliceToCache(resolvedPayload.consumption, resolvedPayload.modelBreakdown, { recordConsumptionSliceToCache(resolvedPayload.consumption, resolvedPayload.modelBreakdown, {
customStartMs: reqStartMs, customStartMs: reqStartMs,
customEndMs: reqEndMs, customEndMs: reqEndMs,
cyclePool: reqPool,
}); });
} }
const latestSt = telemetryStore.getState(); const latestSt = telemetryStore.getState();
const incomingRev = Number(resolvedPayload?.consumption?.revision || 0); const incomingRev = Number(resolvedPayload?.consumption?.revision || 0);
const activePoolPref = latestSt.selectedCyclePool || 'all';
const matchesCurrentRange = const matchesCurrentRange =
!reqRange || !reqRange ||
(reqRange === latestSt.selectedTimeRange && (reqRange === latestSt.selectedTimeRange &&
(reqRange !== 'cycle' || reqPool === activePoolPref) &&
(reqRange !== 'custom' || (reqRange !== 'custom' ||
(reqStartMs === Number(latestSt.customStartMs || 0) && (reqStartMs === Number(latestSt.customStartMs || 0) &&
reqEndMs === Number(latestSt.customEndMs || 0)))); reqEndMs === Number(latestSt.customEndMs || 0))));
@@ -1356,7 +1396,8 @@ async function requestTelemetry(params, force) {
const activeKey = makeConsumptionRangeCacheKey( const activeKey = makeConsumptionRangeCacheKey(
latestSt.selectedTimeRange, latestSt.selectedTimeRange,
latestSt.customStartMs, latestSt.customStartMs,
latestSt.customEndMs latestSt.customEndMs,
activePoolPref
); );
const cachedActive = consumptionRangeCache.get(activeKey); const cachedActive = consumptionRangeCache.get(activeKey);
if (cachedActive) { if (cachedActive) {
@@ -1365,7 +1406,9 @@ async function requestTelemetry(params, force) {
needsSilentRangeRevalidate = true; needsSilentRangeRevalidate = true;
} }
} else if ( } 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 = {
...resolvedPayload, ...resolvedPayload,
@@ -1417,6 +1460,7 @@ async function requestTelemetry(params, force) {
range: latestSt.selectedTimeRange, range: latestSt.selectedTimeRange,
customStartMs: latestSt.customStartMs, customStartMs: latestSt.customStartMs,
customEndMs: latestSt.customEndMs, customEndMs: latestSt.customEndMs,
cyclePool: latestSt.selectedCyclePool || 'all',
}); });
} }
return resolvedPayload; return resolvedPayload;
@@ -1442,15 +1486,20 @@ async function fetchConsumptionRangeSlice({
range, range,
customStartMs = 0, customStartMs = 0,
customEndMs = 0, customEndMs = 0,
cyclePool = 'all',
} = {}) { } = {}) {
const reqEpoch = endpointSwitchEpoch; const reqEpoch = endpointSwitchEpoch;
const reqSeq = ++latestConsumptionReqSeq; const reqSeq = ++latestConsumptionReqSeq;
const targetRange = String(range || 'today'); const targetRange = String(range || 'today');
const targetPool = targetRange === 'cycle' ? String(cyclePool || 'all') : 'all';
const current = telemetryStore.getState(); const current = telemetryStore.getState();
const effectiveConvId = current.selectedConversationId || current.hostRouteConversationId || ''; const effectiveConvId = current.selectedConversationId || current.hostRouteConversationId || '';
const params = new URLSearchParams(); const params = new URLSearchParams();
if (effectiveConvId) params.set('conversationId', effectiveConvId); if (effectiveConvId) params.set('conversationId', effectiveConvId);
params.set('range', targetRange); params.set('range', targetRange);
if (targetRange === 'cycle' && targetPool !== 'all') {
params.set('pool', targetPool);
}
if (targetRange === 'custom') { if (targetRange === 'custom') {
if (customStartMs > 0) params.set('startMs', String(customStartMs)); if (customStartMs > 0) params.set('startMs', String(customStartMs));
if (customEndMs > 0) params.set('endMs', String(customEndMs)); if (customEndMs > 0) params.set('endMs', String(customEndMs));
@@ -1469,6 +1518,7 @@ async function fetchConsumptionRangeSlice({
recordConsumptionSliceToCache(payload.consumption, payload.modelBreakdown, { recordConsumptionSliceToCache(payload.consumption, payload.modelBreakdown, {
customStartMs, customStartMs,
customEndMs, customEndMs,
cyclePool: targetPool,
usageRevision: usageRev, usageRevision: usageRev,
}); });
if (reqSeq !== latestConsumptionReqSeq) return payload; if (reqSeq !== latestConsumptionReqSeq) return payload;
@@ -1476,6 +1526,7 @@ async function fetchConsumptionRangeSlice({
const latestSt = telemetryStore.getState(); const latestSt = telemetryStore.getState();
const stillMatches = const stillMatches =
latestSt.selectedTimeRange === targetRange && latestSt.selectedTimeRange === targetRange &&
(targetRange !== 'cycle' || (latestSt.selectedCyclePool || 'all') === targetPool) &&
(targetRange !== 'custom' || (targetRange !== 'custom' ||
(Number(latestSt.customStartMs || 0) === Number(customStartMs || 0) && (Number(latestSt.customStartMs || 0) === Number(customStartMs || 0) &&
Number(latestSt.customEndMs || 0) === Number(customEndMs || 0))); Number(latestSt.customEndMs || 0) === Number(customEndMs || 0)));
@@ -1581,6 +1632,13 @@ export async function selectConversation(
const params = new URLSearchParams(); const params = new URLSearchParams();
if (effectiveConvId) params.set('conversationId', effectiveConvId); if (effectiveConvId) params.set('conversationId', effectiveConvId);
if (current.selectedTimeRange) params.set('range', current.selectedTimeRange); 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.selectedTimeRange === 'custom') {
if (current.customStartMs > 0) params.set('startMs', String(current.customStartMs)); if (current.customStartMs > 0) params.set('startMs', String(current.customStartMs));
if (current.customEndMs > 0) params.set('endMs', String(current.customEndMs)); if (current.customEndMs > 0) params.set('endMs', String(current.customEndMs));
@@ -1687,7 +1745,7 @@ export async function selectConversation(
*/ */
export function selectConsumptionTimeRange( export function selectConsumptionTimeRange(
nextRange, nextRange,
{ customStartMs = undefined, customEndMs = undefined } = {} { customStartMs = undefined, customEndMs = undefined, cyclePool = undefined } = {}
) { ) {
const targetRange = String(nextRange || 'today'); const targetRange = String(nextRange || 'today');
const prevSt = telemetryStore.getState(); const prevSt = telemetryStore.getState();
@@ -1699,14 +1757,26 @@ export function selectConsumptionTimeRange(
targetRange === 'custom' targetRange === 'custom'
? Number(customEndMs !== undefined ? customEndMs : prevSt.customEndMs || 0) ? Number(customEndMs !== undefined ? customEndMs : prevSt.customEndMs || 0)
: prevSt.customEndMs; : prevSt.customEndMs;
const nextCyclePool =
targetRange === 'cycle'
? String(cyclePool !== undefined ? cyclePool || 'all' : prevSt.selectedCyclePool || 'all')
: prevSt.selectedCyclePool || 'all';
const statePatch = { selectedTimeRange: targetRange }; const statePatch = { selectedTimeRange: targetRange };
if (cyclePool !== undefined) {
statePatch.selectedCyclePool = nextCyclePool;
}
if (targetRange === 'custom') { if (targetRange === 'custom') {
statePatch.customStartMs = nextStartMs; statePatch.customStartMs = nextStartMs;
statePatch.customEndMs = nextEndMs; 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 cached = consumptionRangeCache.get(cacheKey);
const prevTelemetry = prevSt.telemetry; const prevTelemetry = prevSt.telemetry;
@@ -1725,6 +1795,7 @@ export function selectConsumptionTimeRange(
range: targetRange, range: targetRange,
customStartMs: nextStartMs, customStartMs: nextStartMs,
customEndMs: nextEndMs, customEndMs: nextEndMs,
cyclePool: nextCyclePool,
}); });
} }
@@ -1733,9 +1804,14 @@ export function selectConsumptionTimeRange(
range: targetRange, range: targetRange,
customStartMs: nextStartMs, customStartMs: nextStartMs,
customEndMs: nextEndMs, customEndMs: nextEndMs,
cyclePool: nextCyclePool,
}); });
} }
export function selectConsumptionCyclePool(nextPool = 'all') {
return selectConsumptionTimeRange('cycle', { cyclePool: String(nextPool || 'all') });
}
/** /**
* 仅在进入「用量统计」视图时触发一次静默后台预取,拉齐全部 7 个预设区间到前端缓存以实现 0ms 瞬切。 * 仅在进入「用量统计」视图时触发一次静默后台预取,拉齐全部 7 个预设区间到前端缓存以实现 0ms 瞬切。
*/ */
+3
View File
@@ -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"] .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-scope-select .select-trigger,
[data-modern-ui="true"] .steps-inline-model-select .select-trigger, [data-modern-ui="true"] .steps-inline-model-select .select-trigger,
[data-modern-ui="true"] .sstep-fit-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"] .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-scope-select .select-trigger:hover,
[data-modern-ui="true"] .steps-inline-model-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 { [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"] .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-scope-select.is-open .select-trigger,
[data-modern-ui="true"] .steps-inline-model-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 { [data-modern-ui="true"] .sstep-fit-model-select.is-open .select-trigger {
@@ -14,6 +14,53 @@
gap: 6px; 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 { .cons-overview-controls {
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
+173 -13
View File
@@ -50,6 +50,7 @@ import { ActionMenu } from '../components/ui/ActionMenu.js';
import { import {
getDefaultCtxInspectorAgentId, getDefaultCtxInspectorAgentId,
prefetchConsumptionPresets, prefetchConsumptionPresets,
selectConsumptionCyclePool,
selectConsumptionTimeRange, selectConsumptionTimeRange,
selectConversation, selectConversation,
telemetryStore, telemetryStore,
@@ -61,6 +62,7 @@ import {
} from '../components/charts/TrendAreaChart.js'; } from '../components/charts/TrendAreaChart.js';
import { CustomDateTimePicker } from '../components/ui/CustomDateTimePicker.js'; import { CustomDateTimePicker } from '../components/ui/CustomDateTimePicker.js';
import { CustomScrollbar } from '../components/ui/CustomScrollbar.js'; import { CustomScrollbar } from '../components/ui/CustomScrollbar.js';
import { CustomSelect } from '../components/ui/CustomSelect.js';
import { createFourSegmentBar } from '../components/ui/FourSegmentBar.js'; import { createFourSegmentBar } from '../components/ui/FourSegmentBar.js';
import { createConsumptionBreakdownContent } from '../components/ui/ConsumptionTooltipContent.js'; import { createConsumptionBreakdownContent } from '../components/ui/ConsumptionTooltipContent.js';
import { SegmentedControl } from '../components/ui/SegmentedControl.js'; import { SegmentedControl } from '../components/ui/SegmentedControl.js';
@@ -95,6 +97,86 @@ function ceilToEndOfMinuteMs(ms) {
return d.getTime(); 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({ export const ConsumptionView = defineComponent({
name: 'ConsumptionView', name: 'ConsumptionView',
setup({ onCleanup }) { setup({ onCleanup }) {
@@ -200,6 +282,16 @@ export const ConsumptionView = defineComponent({
// --- Section 1: 用量概览矩阵 (上层 3 列核心总量 + 下层 3 列新输入/缓存读取/输出拆分 + 底部 4 段比例条) --- // --- Section 1: 用量概览矩阵 (上层 3 列核心总量 + 下层 3 列新输入/缓存读取/输出拆分 + 底部 4 段比例条) ---
const dateSpanBadge = h('span', { className: 'cons-badge text-mono', text: '-- ~ --' }); 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 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 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' }); 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' }, [ const overviewPanel = h('section', { className: 'panel' }, [
h('div', { className: 'panel-header cons-overview-head' }, [ h('div', { className: 'panel-header cons-overview-head' }, [
h('span', { className: 'panel-title' }, [ h('span', { className: 'panel-title cons-overview-title' }, [
dateSpanBadge, dateSpanBadge,
cyclePoolSelect.el,
]), ]),
h('div', { className: 'cons-overview-controls' }, [ h('div', { className: 'cons-overview-controls' }, [
timeFilterSwitch.el, timeFilterSwitch.el,
@@ -1791,7 +1884,7 @@ export const ConsumptionView = defineComponent({
const cons = slice.consumption || {}; const cons = slice.consumption || {};
const rangeInfo = cons.selectedRange || {}; const rangeInfo = cons.selectedRange || {};
// 始终在 0ms 同步顶部时间段滑块与自定义日期条显隐,给予即刻交互反馈 // 始终在 0ms 同步顶部时间段滑块、周期池选择器及自定义日期条显隐,给予即刻交互反馈
timeFilterSwitch.setValue(slice.range); timeFilterSwitch.setValue(slice.range);
patchAttr(customRangeBar, 'hidden', slice.range !== 'custom'); patchAttr(customRangeBar, 'hidden', slice.range !== 'custom');
if (!hasUncommittedCustomDraft) { if (!hasUncommittedCustomDraft) {
@@ -1801,17 +1894,45 @@ export const ConsumptionView = defineComponent({
endPicker.setValue(draftEndMs); 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; return;
} }
const preset = 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] ? cons.presets[slice.range]
: null; : null;
const acct = cons.account || preset?.account || {}; const acct = cons.account || preset?.account || {};
const dateSpan = formatDateSpanBadge(rangeInfo.startMs, rangeInfo.endMs); 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 now = new Date();
const currentMonthIdx = now.getMonth(); const currentMonthIdx = now.getMonth();
const monthlyYear = cons.monthlyYear || now.getFullYear(); const monthlyYear = cons.monthlyYear || now.getFullYear();
@@ -1819,6 +1940,9 @@ export const ConsumptionView = defineComponent({
const renderTuple = [ const renderTuple = [
locale, locale,
slice.range, slice.range,
activePoolFilter,
cycleOptionsSig,
Boolean(rangeInfo.isFallbackWeek),
slice.customStartMs, slice.customStartMs,
slice.customEndMs, slice.customEndMs,
slice.modelDisplayMode, slice.modelDisplayMode,
@@ -1839,13 +1963,36 @@ export const ConsumptionView = defineComponent({
cons.monthlySeries, cons.monthlySeries,
]; ];
if (isSameRenderTuple(lastRenderedTuple, renderTuple)) return; 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; lastRenderedTuple = renderTuple;
} }
function drawConsumptionData(slice, { cons, preset, acct, rangeInfo, dateSpan, currentMonthIdx, monthlyYear }) { function drawConsumptionData(
// 1. 同步用量概览矩阵与顶部 4 段比例条 slice,
{ cons, preset, acct, rangeInfo, activePoolFilter, dateSpan, currentMonthIdx, monthlyYear }
) {
// 1. 同步用量概览矩阵及顶部 4 段比例条
patchText(dateSpanBadge, dateSpan); 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 totalTokens = Number(acct.totalTokens || 0);
const inputTokens = Number(acct.inputTokens || 0); const inputTokens = Number(acct.inputTokens || 0);
const cacheTokens = Number(acct.cacheReadTokens || 0); const cacheTokens = Number(acct.cacheReadTokens || 0);
@@ -2036,11 +2183,18 @@ export const ConsumptionView = defineComponent({
...allTrendMergedModels, ...allTrendMergedModels,
]); ]);
// 2. 同步历史趋势交互式 SVG 面积图 / 类 GitHub 每日热力图(>90天)与悬停分模型浮层 // 2. 同步历史趋势交互式 SVG 面积图 / 类 GitHub 每日热力图(>90天)及悬停分模型浮层
const rangeBadgeText = isEnglishLocale() const rangeBadgeText =
? getConsumptionTimeRangeOptions().find((o) => o.value === slice.range)?.label || slice.range === 'cycle'
t('cons.allTime') ? `${rangeInfo.isFallbackWeek || slice.weeklyLimitMode === 'custom_tokens' || slice.weeklyLimitMode === 'custom_cost' ? t('cons.cycleFallbackWeek') : t('cons.currentCycle')}${
: preset?.label || rangeInfo.label || t('cons.allTime'); 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); patchText(trendRangeBadge, rangeBadgeText);
const firstTrendSlot = rawTrendSeries[0] || null; const firstTrendSlot = rawTrendSeries[0] || null;
const isMinuteTrend = firstTrendSlot?.granularity === 'minute'; const isMinuteTrend = firstTrendSlot?.granularity === 'minute';
@@ -2200,7 +2354,7 @@ export const ConsumptionView = defineComponent({
updateRow: (refs, s) => updateSourceBreakdownRow(refs, s, sourcesTotalTok, modelColorMap), 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 const nextRankingKey = showWorkspacesTab
? 'workspaces' ? 'workspaces'
: showSessionsTab : showSessionsTab
@@ -2336,8 +2490,11 @@ export const ConsumptionView = defineComponent({
const unsub = telemetryStore.subscribe( const unsub = telemetryStore.subscribe(
(st) => ({ (st) => ({
range: st.selectedTimeRange, range: st.selectedTimeRange,
cyclePool: st.selectedCyclePool || 'all',
customStartMs: st.customStartMs, customStartMs: st.customStartMs,
customEndMs: st.customEndMs, customEndMs: st.customEndMs,
quotaPools: st.telemetry?.quotas?.pools,
weeklyLimitMode: st.telemetry?.settings?.weeklyLimitMode,
consumption: st.telemetry?.consumption, consumption: st.telemetry?.consumption,
modelBreakdown: st.telemetry?.modelBreakdown, modelBreakdown: st.telemetry?.modelBreakdown,
modelDisplayMode: normalizeModelDisplayMode( modelDisplayMode: normalizeModelDisplayMode(
@@ -2391,6 +2548,7 @@ export const ConsumptionView = defineComponent({
ariaLabel: t('cons.rangeAria'), ariaLabel: t('cons.rangeAria'),
options: getConsumptionTimeRangeOptions(), options: getConsumptionTimeRangeOptions(),
}); });
patchAttr(cyclePoolSelect.refs.triggerBtn, 'aria-label', t('cons.cyclePoolAria'));
patchText(applyCustomBtnLabel, t('cons.applyFilter')); patchText(applyCustomBtnLabel, t('cons.applyFilter'));
patchText(rangeToSpan, t('cons.rangeTo')); patchText(rangeToSpan, t('cons.rangeTo'));
patchText(totalTokensLabel, t('cons.totalTokens')); patchText(totalTokensLabel, t('cons.totalTokens'));
@@ -2448,6 +2606,7 @@ export const ConsumptionView = defineComponent({
unsubView(); unsubView();
unsubI18n(); unsubI18n();
consExportMenu.destroy(); consExportMenu.destroy();
cyclePoolSelect.destroy();
trendChart.destroy?.(); trendChart.destroy?.();
rankingTabSwitch.destroy(); rankingTabSwitch.destroy();
modelsSortSwitch.destroy(); modelsSortSwitch.destroy();
@@ -2462,6 +2621,7 @@ export const ConsumptionView = defineComponent({
el: rootEl, el: rootEl,
refs: { refs: {
timeFilterSwitch, timeFilterSwitch,
cyclePoolSelect,
startPicker, startPicker,
endPicker, endPicker,
viewScrollbar, viewScrollbar,
+50
View File
@@ -2813,6 +2813,53 @@ html[data-standalone="true"] .app-shell {
gap: 6px; 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 { .cons-overview-controls {
display: inline-flex; display: inline-flex;
align-items: center; 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"] .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-scope-select .select-trigger,
[data-modern-ui="true"] .steps-inline-model-select .select-trigger, [data-modern-ui="true"] .steps-inline-model-select .select-trigger,
[data-modern-ui="true"] .sstep-fit-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"] .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-scope-select .select-trigger:hover,
[data-modern-ui="true"] .steps-inline-model-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 { [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"] .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-scope-select.is-open .select-trigger,
[data-modern-ui="true"] .steps-inline-model-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 { [data-modern-ui="true"] .sstep-fit-model-select.is-open .select-trigger {
@@ -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.length, firstGridCells.length);
assert.equal(secondGridCells[10], firstGridCells[10], 'Heatmap cell DOM node reused in-place'); 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(); view.destroy();
telemetryStore.setState(prevTelState, { sync: true }); telemetryStore.setState(prevTelState, { sync: true });
uiStore.setState(prevUiState, { sync: true }); uiStore.setState(prevUiState, { sync: true });
+270 -1
View File
@@ -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 () => { 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), '0');
assert.equal(formatPctNumber(0, { withSymbol: true }), '0%'); assert.equal(formatPctNumber(0, { withSymbol: true }), '0%');
assert.equal(formatPctNumber(0.04, { 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(1.0, { withSymbol: true }), '1.0%');
assert.equal(formatPctNumber(50.0, { withSymbol: true }), '50.0%'); assert.equal(formatPctNumber(50.0, { withSymbol: true }), '50.0%');
assert.equal(formatPctNumber(99.9, { withSymbol: true }), '99.9%'); 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:<poolKey> 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'
);
}); });