mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-27 01:19:25 +08:00
perf(panel): instant consumption time-range switching via pruned scope API and client preset cache
This commit is contained in:
+458
-43
@@ -4269,7 +4269,7 @@ return { getViewTabs, uiStore, getVisibleMonitorView };
|
||||
})();
|
||||
|
||||
// --- src/store/telemetryStore.js ---
|
||||
const { extractHostRouteCascadeId, telemetryStore, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_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, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, fetchTelemetry, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform } = (() => {
|
||||
const { extractHostRouteCascadeId, telemetryStore, clearConsumptionRangeCache, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_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, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, fetchTelemetry, selectConsumptionTimeRange, prefetchConsumptionPresets, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform } = (() => {
|
||||
/**
|
||||
* @fileoverview Reactive telemetry store with async non-overlapping poll scheduler
|
||||
* and granular slice updates.
|
||||
@@ -4367,9 +4367,16 @@ let pollTimer = null;
|
||||
let feedbackTimer = null;
|
||||
let activeBundleVersion = 0;
|
||||
let latestRequestSeq = 0;
|
||||
let latestConsumptionReqSeq = 0;
|
||||
let activeForceCount = 0;
|
||||
let consecutivePollFailures = 0;
|
||||
let inFlightTelemetryPoll = null;
|
||||
let inFlightPresetsPrefetch = null;
|
||||
let lastPrefetchedUsageRevision = 0;
|
||||
let consumptionCacheScopeSig = '';
|
||||
const MAX_CONSUMPTION_RANGE_CACHE = 12;
|
||||
const CONSUMPTION_PRESET_KEYS = ['cycle', 'today', '24h', '7d', '14d', '30d', 'all'];
|
||||
const consumptionRangeCache = new Map();
|
||||
let lastReceivedSteps = null;
|
||||
let loopActive = false;
|
||||
let loopIntervalMs = 2000;
|
||||
@@ -4387,6 +4394,96 @@ const TELEMETRY_RECOMPUTE_SETTING_KEYS = new Set([
|
||||
'enableWindowOverlay',
|
||||
]);
|
||||
|
||||
function makeConsumptionRangeCacheKey(range, customStartMs = 0, customEndMs = 0) {
|
||||
const key = String(range || 'all');
|
||||
if (key === 'custom') {
|
||||
return `custom:${Number(customStartMs || 0)}:${Number(customEndMs || 0)}`;
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
function clearConsumptionRangeCache() {
|
||||
consumptionRangeCache.clear();
|
||||
lastPrefetchedUsageRevision = 0;
|
||||
inFlightPresetsPrefetch = null;
|
||||
}
|
||||
|
||||
function buildConsumptionScopeSig(payload) {
|
||||
if (!payload || typeof payload !== 'object') return '';
|
||||
const acct = payload.account || {};
|
||||
const set = payload.settings || {};
|
||||
const cloud = payload.cloudStatus || {};
|
||||
return `${String(acct.status || '')}|${String(acct.email || acct.name || '').toLowerCase()}|${String(set.weeklyLimitMode || '')}|${String(cloud.catalogVersion || '')}`;
|
||||
}
|
||||
|
||||
function syncConsumptionCacheScope(payload) {
|
||||
const nextSig = buildConsumptionScopeSig(payload);
|
||||
if (!nextSig) return;
|
||||
if (consumptionCacheScopeSig && consumptionCacheScopeSig !== nextSig) {
|
||||
clearConsumptionRangeCache();
|
||||
}
|
||||
consumptionCacheScopeSig = nextSig;
|
||||
}
|
||||
|
||||
function putConsumptionRangeCacheEntry(cacheKey, entry) {
|
||||
if (!cacheKey || !entry) return;
|
||||
consumptionRangeCache.delete(cacheKey);
|
||||
consumptionRangeCache.set(cacheKey, entry);
|
||||
while (consumptionRangeCache.size > MAX_CONSUMPTION_RANGE_CACHE) {
|
||||
consumptionRangeCache.delete(consumptionRangeCache.keys().next().value);
|
||||
}
|
||||
}
|
||||
|
||||
function recordConsumptionSliceToCache(
|
||||
cons,
|
||||
modelBreakdown,
|
||||
{ customStartMs = 0, customEndMs = 0, usageRevision = 0 } = {}
|
||||
) {
|
||||
const rangeKey = String(cons?.selectedRange?.key || '');
|
||||
if (!rangeKey) return;
|
||||
const cacheKey = makeConsumptionRangeCacheKey(
|
||||
rangeKey,
|
||||
rangeKey === 'custom' ? customStartMs || cons.selectedRange?.startMs || 0 : 0,
|
||||
rangeKey === 'custom' ? customEndMs || cons.selectedRange?.endMs || 0 : 0
|
||||
);
|
||||
putConsumptionRangeCacheEntry(cacheKey, {
|
||||
revision: Number(cons.revision ?? usageRevision ?? 0),
|
||||
selectedRange: cons.selectedRange,
|
||||
session: cons.session,
|
||||
account: cons.account,
|
||||
trendSeries: Array.isArray(cons.trendSeries) ? cons.trendSeries : [],
|
||||
sourcesBreakdown: Array.isArray(cons.sourcesBreakdown) ? cons.sourcesBreakdown : [],
|
||||
modelBreakdown: Array.isArray(modelBreakdown) ? modelBreakdown : [],
|
||||
});
|
||||
}
|
||||
|
||||
function applyCachedConsumptionSlice(baseTelemetry, cachedEntry, targetRevision = 0) {
|
||||
if (!baseTelemetry || !cachedEntry) return baseTelemetry;
|
||||
const prevCons = baseTelemetry.consumption || {};
|
||||
return {
|
||||
...baseTelemetry,
|
||||
consumption: {
|
||||
...prevCons,
|
||||
...(targetRevision > 0 ? { revision: targetRevision } : {}),
|
||||
selectedRange: cachedEntry.selectedRange,
|
||||
session: cachedEntry.session ?? prevCons.session,
|
||||
account: cachedEntry.account ?? prevCons.account,
|
||||
trendSeries: cachedEntry.trendSeries,
|
||||
sourcesBreakdown: cachedEntry.sourcesBreakdown,
|
||||
},
|
||||
modelBreakdown: cachedEntry.modelBreakdown,
|
||||
};
|
||||
}
|
||||
|
||||
function hasAllPresetRangesCached(expectedRevision) {
|
||||
for (const key of CONSUMPTION_PRESET_KEYS) {
|
||||
const entry = consumptionRangeCache.get(key);
|
||||
if (!entry) return false;
|
||||
if (expectedRevision > 0 && entry.revision !== expectedRevision) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function enqueueSettingsWrite(task) {
|
||||
const run = settingsWriteChain.then(task, task);
|
||||
settingsWriteChain = run.catch(() => {});
|
||||
@@ -5079,6 +5176,9 @@ function readDisplaySteps(payload) {
|
||||
async function requestTelemetry(params, force) {
|
||||
const reqSeq = ++latestRequestSeq;
|
||||
const reqSettingsRev = settingsRevision;
|
||||
const reqRange = String(params.get('range') || '');
|
||||
const reqStartMs = Number(params.get('startMs') || 0);
|
||||
const reqEndMs = Number(params.get('endMs') || 0);
|
||||
const startMs = Date.now();
|
||||
|
||||
if (force) {
|
||||
@@ -5129,8 +5229,57 @@ async function requestTelemetry(params, force) {
|
||||
}
|
||||
consecutivePollFailures = 0;
|
||||
|
||||
const resolvedPayload = reconcileIncomingTelemetrySettings(payload, reqSettingsRev);
|
||||
let resolvedPayload = reconcileIncomingTelemetrySettings(payload, reqSettingsRev);
|
||||
syncConsumptionCacheScope(resolvedPayload);
|
||||
if (resolvedPayload?.consumption) {
|
||||
recordConsumptionSliceToCache(resolvedPayload.consumption, resolvedPayload.modelBreakdown, {
|
||||
customStartMs: reqStartMs,
|
||||
customEndMs: reqEndMs,
|
||||
});
|
||||
}
|
||||
|
||||
const latestSt = telemetryStore.getState();
|
||||
const incomingRev = Number(resolvedPayload?.consumption?.revision || 0);
|
||||
const matchesCurrentRange =
|
||||
!reqRange ||
|
||||
(reqRange === latestSt.selectedTimeRange &&
|
||||
(reqRange !== 'custom' ||
|
||||
(reqStartMs === Number(latestSt.customStartMs || 0) &&
|
||||
reqEndMs === Number(latestSt.customEndMs || 0))));
|
||||
|
||||
// 常规 2 秒轮询在途期间若用户已通过前端缓存瞬切到其他时间段,保留用户当前选中的范围不回跳,
|
||||
// 若后端 usageRevision 已推进则静默补发一次轻量范围校准。
|
||||
let needsSilentRangeRevalidate = false;
|
||||
if (!force && !matchesCurrentRange && resolvedPayload?.consumption) {
|
||||
const activeKey = makeConsumptionRangeCacheKey(
|
||||
latestSt.selectedTimeRange,
|
||||
latestSt.customStartMs,
|
||||
latestSt.customEndMs
|
||||
);
|
||||
const cachedActive = consumptionRangeCache.get(activeKey);
|
||||
if (cachedActive) {
|
||||
resolvedPayload = applyCachedConsumptionSlice(resolvedPayload, cachedActive, incomingRev);
|
||||
if (incomingRev > 0 && cachedActive.revision !== incomingRev) {
|
||||
needsSilentRangeRevalidate = true;
|
||||
}
|
||||
} else if (
|
||||
latestSt.telemetry?.consumption?.selectedRange?.key === latestSt.selectedTimeRange
|
||||
) {
|
||||
resolvedPayload = {
|
||||
...resolvedPayload,
|
||||
consumption: {
|
||||
...resolvedPayload.consumption,
|
||||
selectedRange: latestSt.telemetry.consumption.selectedRange,
|
||||
session: latestSt.telemetry.consumption.session,
|
||||
account: latestSt.telemetry.consumption.account,
|
||||
trendSeries: latestSt.telemetry.consumption.trendSeries,
|
||||
sourcesBreakdown: latestSt.telemetry.consumption.sourcesBreakdown,
|
||||
},
|
||||
modelBreakdown: latestSt.telemetry.modelBreakdown,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (force) {
|
||||
const elapsed = Date.now() - startMs;
|
||||
if (elapsed < 220) {
|
||||
@@ -5159,6 +5308,13 @@ async function requestTelemetry(params, force) {
|
||||
minuteTick: Math.floor(Date.now() / 30000),
|
||||
syncState: latestSt.syncState === 'synced' ? 'synced' : 'idle',
|
||||
});
|
||||
if (needsSilentRangeRevalidate) {
|
||||
void fetchConsumptionRangeSlice({
|
||||
range: latestSt.selectedTimeRange,
|
||||
customStartMs: latestSt.customStartMs,
|
||||
customEndMs: latestSt.customEndMs,
|
||||
});
|
||||
}
|
||||
return resolvedPayload;
|
||||
}
|
||||
} catch (err) {
|
||||
@@ -5178,6 +5334,198 @@ async function requestTelemetry(params, force) {
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchConsumptionRangeSlice({
|
||||
range,
|
||||
customStartMs = 0,
|
||||
customEndMs = 0,
|
||||
} = {}) {
|
||||
const reqSeq = ++latestConsumptionReqSeq;
|
||||
const targetRange = String(range || 'today');
|
||||
const current = telemetryStore.getState();
|
||||
const effectiveConvId = current.selectedConversationId || current.hostRouteConversationId || '';
|
||||
const params = new URLSearchParams();
|
||||
if (effectiveConvId) params.set('conversationId', effectiveConvId);
|
||||
params.set('range', targetRange);
|
||||
if (targetRange === 'custom') {
|
||||
if (customStartMs > 0) params.set('startMs', String(customStartMs));
|
||||
if (customEndMs > 0) params.set('endMs', String(customEndMs));
|
||||
}
|
||||
params.set('scope', 'consumption');
|
||||
|
||||
try {
|
||||
const payload = await callSidecarApi(`/api/telemetry?${params}`, {
|
||||
method: 'GET',
|
||||
abortKey: 'consumption-range',
|
||||
});
|
||||
if (!payload || typeof payload !== 'object') return null;
|
||||
|
||||
if (payload.scope === 'consumption' && payload.consumption) {
|
||||
const usageRev = Number(payload.usageRevision ?? payload.consumption.revision ?? 0);
|
||||
recordConsumptionSliceToCache(payload.consumption, payload.modelBreakdown, {
|
||||
customStartMs,
|
||||
customEndMs,
|
||||
usageRevision: usageRev,
|
||||
});
|
||||
if (reqSeq !== latestConsumptionReqSeq) return payload;
|
||||
|
||||
const latestSt = telemetryStore.getState();
|
||||
const stillMatches =
|
||||
latestSt.selectedTimeRange === targetRange &&
|
||||
(targetRange !== 'custom' ||
|
||||
(Number(latestSt.customStartMs || 0) === Number(customStartMs || 0) &&
|
||||
Number(latestSt.customEndMs || 0) === Number(customEndMs || 0)));
|
||||
if (!stillMatches) return payload;
|
||||
|
||||
const prevTelemetry = latestSt.telemetry;
|
||||
if (prevTelemetry) {
|
||||
const nextTelemetry = {
|
||||
...prevTelemetry,
|
||||
consumption: {
|
||||
...(prevTelemetry.consumption || {}),
|
||||
...payload.consumption,
|
||||
...(usageRev > 0 ? { revision: usageRev } : {}),
|
||||
},
|
||||
modelBreakdown: Array.isArray(payload.modelBreakdown)
|
||||
? payload.modelBreakdown
|
||||
: prevTelemetry.modelBreakdown,
|
||||
};
|
||||
if (!isEquivalentTelemetry(prevTelemetry, nextTelemetry)) {
|
||||
telemetryStore.setState({ telemetry: nextTelemetry });
|
||||
}
|
||||
}
|
||||
return payload;
|
||||
}
|
||||
|
||||
// 冷启动阶段后端尚无基础快照时会回退返回完整 telemetry,直接平滑复用现有状态合并
|
||||
if (payload.consumption) {
|
||||
syncConsumptionCacheScope(payload);
|
||||
recordConsumptionSliceToCache(payload.consumption, payload.modelBreakdown, {
|
||||
customStartMs,
|
||||
customEndMs,
|
||||
});
|
||||
if (reqSeq === latestConsumptionReqSeq) {
|
||||
const latestSt = telemetryStore.getState();
|
||||
if (!isEquivalentTelemetry(latestSt.telemetry, payload)) {
|
||||
telemetryStore.setState({ telemetry: payload });
|
||||
}
|
||||
}
|
||||
}
|
||||
return payload;
|
||||
} catch (err) {
|
||||
if (err?.name === 'AbortError') return null;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换「用量统计」时间范围:
|
||||
* - 命中前端 rangeCache 时,在单次 setState 内 0ms 原子更新概览/趋势/模型/来源(若 usageRevision 一致则 0 次 HTTP 请求);
|
||||
* - 若后台数据已更新则先 0ms 展示缓存,再静默发起轻量 `scope=consumption` 校准;
|
||||
* - 未命中缓存(如自定义时段或进页首 20ms 抢点)则直接走 `<5ms` 的 `scope=consumption` 通道。
|
||||
*/
|
||||
function selectConsumptionTimeRange(
|
||||
nextRange,
|
||||
{ customStartMs = undefined, customEndMs = undefined } = {}
|
||||
) {
|
||||
const targetRange = String(nextRange || 'today');
|
||||
const prevSt = telemetryStore.getState();
|
||||
const nextStartMs =
|
||||
targetRange === 'custom'
|
||||
? Number(customStartMs !== undefined ? customStartMs : prevSt.customStartMs || 0)
|
||||
: prevSt.customStartMs;
|
||||
const nextEndMs =
|
||||
targetRange === 'custom'
|
||||
? Number(customEndMs !== undefined ? customEndMs : prevSt.customEndMs || 0)
|
||||
: prevSt.customEndMs;
|
||||
|
||||
const statePatch = { selectedTimeRange: targetRange };
|
||||
if (targetRange === 'custom') {
|
||||
statePatch.customStartMs = nextStartMs;
|
||||
statePatch.customEndMs = nextEndMs;
|
||||
}
|
||||
|
||||
const cacheKey = makeConsumptionRangeCacheKey(targetRange, nextStartMs, nextEndMs);
|
||||
const cached = consumptionRangeCache.get(cacheKey);
|
||||
const prevTelemetry = prevSt.telemetry;
|
||||
|
||||
if (cached && prevTelemetry) {
|
||||
const currentRev = Number(prevTelemetry.consumption?.revision || 0);
|
||||
const nextTelemetry = applyCachedConsumptionSlice(
|
||||
prevTelemetry,
|
||||
cached,
|
||||
currentRev > 0 ? currentRev : cached.revision
|
||||
);
|
||||
telemetryStore.setState({ ...statePatch, telemetry: nextTelemetry });
|
||||
if (currentRev > 0 && cached.revision === currentRev) {
|
||||
return Promise.resolve(nextTelemetry);
|
||||
}
|
||||
return fetchConsumptionRangeSlice({
|
||||
range: targetRange,
|
||||
customStartMs: nextStartMs,
|
||||
customEndMs: nextEndMs,
|
||||
});
|
||||
}
|
||||
|
||||
telemetryStore.setState(statePatch);
|
||||
return fetchConsumptionRangeSlice({
|
||||
range: targetRange,
|
||||
customStartMs: nextStartMs,
|
||||
customEndMs: nextEndMs,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 仅在进入「用量统计」视图时触发一次静默后台预取,拉齐全部 7 个预设区间到前端缓存以实现 0ms 瞬切。
|
||||
*/
|
||||
function prefetchConsumptionPresets() {
|
||||
const prevTelemetry = telemetryStore.getState().telemetry;
|
||||
const currentRev = Number(prevTelemetry?.consumption?.revision || 0);
|
||||
if (currentRev > 0 && lastPrefetchedUsageRevision === currentRev && hasAllPresetRangesCached(currentRev)) {
|
||||
return Promise.resolve(true);
|
||||
}
|
||||
if (inFlightPresetsPrefetch) {
|
||||
return inFlightPresetsPrefetch;
|
||||
}
|
||||
|
||||
const current = telemetryStore.getState();
|
||||
const effectiveConvId = current.selectedConversationId || current.hostRouteConversationId || '';
|
||||
const params = new URLSearchParams();
|
||||
if (effectiveConvId) params.set('conversationId', effectiveConvId);
|
||||
params.set('scope', 'consumption-presets');
|
||||
|
||||
const task = callSidecarApi(`/api/telemetry?${params}`, {
|
||||
method: 'GET',
|
||||
abortKey: 'consumption-presets',
|
||||
})
|
||||
.then((payload) => {
|
||||
if (payload?.scope === 'consumption-presets' && payload.ranges && typeof payload.ranges === 'object') {
|
||||
const rev = Number(payload.usageRevision || currentRev || 0);
|
||||
for (const [rangeKey, entry] of Object.entries(payload.ranges)) {
|
||||
if (!entry || typeof entry !== 'object') continue;
|
||||
recordConsumptionSliceToCache(
|
||||
{ ...entry, revision: rev },
|
||||
entry.modelBreakdown,
|
||||
{ usageRevision: rev }
|
||||
);
|
||||
}
|
||||
if (rev > 0) {
|
||||
lastPrefetchedUsageRevision = rev;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
})
|
||||
.catch(() => false)
|
||||
.finally(() => {
|
||||
if (inFlightPresetsPrefetch === task) {
|
||||
inFlightPresetsPrefetch = null;
|
||||
}
|
||||
});
|
||||
|
||||
inFlightPresetsPrefetch = task;
|
||||
return task;
|
||||
}
|
||||
|
||||
async function saveSettingsPatch(patch) {
|
||||
const safePatch = patch && typeof patch === 'object' ? { ...patch } : {};
|
||||
if (Object.prototype.hasOwnProperty.call(safePatch, 'language')) {
|
||||
@@ -5353,6 +5701,9 @@ async function saveSettingsPatch(patch) {
|
||||
}
|
||||
|
||||
const needsTelemetryRecompute = patchKeys.some((k) => TELEMETRY_RECOMPUTE_SETTING_KEYS.has(k));
|
||||
if (Object.prototype.hasOwnProperty.call(safePatch, 'weeklyLimitMode')) {
|
||||
clearConsumptionRangeCache();
|
||||
}
|
||||
if (needsTelemetryRecompute) {
|
||||
inFlightTelemetryPoll = null;
|
||||
void fetchTelemetry({ force: false });
|
||||
@@ -5416,18 +5767,21 @@ async function resetAllSettings() {
|
||||
});
|
||||
}
|
||||
inFlightTelemetryPoll = null;
|
||||
clearConsumptionRangeCache();
|
||||
void fetchTelemetry({ force: false });
|
||||
return res;
|
||||
}
|
||||
|
||||
async function rebuildTrajectoryCache() {
|
||||
const res = await callSidecarApi('/api/cache/rebuild', { method: 'POST', body: {} });
|
||||
clearConsumptionRangeCache();
|
||||
await fetchTelemetry({ force: true });
|
||||
return res;
|
||||
}
|
||||
|
||||
async function triggerCloudSync() {
|
||||
const res = await callSidecarApi('/api/cloud-sync', { method: 'POST', body: {} });
|
||||
clearConsumptionRangeCache();
|
||||
await fetchTelemetry({ force: true });
|
||||
return res;
|
||||
}
|
||||
@@ -5697,7 +6051,7 @@ function isMacHostPlatform(telemetry) {
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return { extractHostRouteCascadeId, telemetryStore, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_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, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, fetchTelemetry, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform };
|
||||
return { extractHostRouteCascadeId, telemetryStore, clearConsumptionRangeCache, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_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, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, fetchTelemetry, selectConsumptionTimeRange, prefetchConsumptionPresets, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform };
|
||||
})();
|
||||
|
||||
// --- src/components/ui/TopLongPillNav.js ---
|
||||
@@ -8026,13 +8380,18 @@ function createTrendAreaChart() {
|
||||
hmMonthsEl.appendChild(mEl);
|
||||
}
|
||||
|
||||
// 重建 7 行 × N 周列的每日小格子(一格一天)
|
||||
// 重建 7 行 × N 周列的每日小格子(一格一天),使用 DocumentFragment 一次性批量挂载减少重排
|
||||
while (hmGridEl.firstChild) hmGridEl.removeChild(hmGridEl.firstChild);
|
||||
hoveredCellEl = null;
|
||||
currentCellEls = new Array(slots.length);
|
||||
const gridFrag =
|
||||
typeof document !== 'undefined' && typeof document.createDocumentFragment === 'function'
|
||||
? document.createDocumentFragment()
|
||||
: null;
|
||||
const gridTarget = gridFrag || hmGridEl;
|
||||
|
||||
for (let pad = 0; pad < firstDow; pad++) {
|
||||
hmGridEl.appendChild(
|
||||
gridTarget.appendChild(
|
||||
h('span', { className: 'trend-hm-cell is-pad', 'aria-hidden': 'true' })
|
||||
);
|
||||
}
|
||||
@@ -8051,9 +8410,12 @@ function createTrendAreaChart() {
|
||||
'data-hm-row': String(row),
|
||||
role: 'gridcell',
|
||||
});
|
||||
hmGridEl.appendChild(cellEl);
|
||||
gridTarget.appendChild(cellEl);
|
||||
currentCellEls[i] = cellEl;
|
||||
}
|
||||
if (gridFrag) {
|
||||
hmGridEl.appendChild(gridFrag);
|
||||
}
|
||||
|
||||
if (typeof requestAnimationFrame === 'function') {
|
||||
requestAnimationFrame(() => {
|
||||
@@ -19902,8 +20264,7 @@ const ConsumptionView = defineComponent({
|
||||
} else {
|
||||
hasUncommittedCustomDraft = false;
|
||||
}
|
||||
telemetryStore.setState({ selectedTimeRange: nextRange });
|
||||
fetchTelemetry({ force: false });
|
||||
selectConsumptionTimeRange(nextRange);
|
||||
},
|
||||
});
|
||||
|
||||
@@ -19942,12 +20303,10 @@ const ConsumptionView = defineComponent({
|
||||
hasUncommittedCustomDraft = false;
|
||||
startPicker.setValue(minMs);
|
||||
endPicker.setValue(maxMs);
|
||||
telemetryStore.setState({
|
||||
selectedTimeRange: 'custom',
|
||||
selectConsumptionTimeRange('custom', {
|
||||
customStartMs: minMs,
|
||||
customEndMs: maxMs,
|
||||
});
|
||||
fetchTelemetry({ force: true });
|
||||
},
|
||||
},
|
||||
[createSvgIcon('check', { size: 12 }), applyCustomBtnLabel]
|
||||
@@ -20689,8 +21048,21 @@ const ConsumptionView = defineComponent({
|
||||
|
||||
let latestSlice = null;
|
||||
let isDirty = false;
|
||||
let prefetchedOnCurrentVisit = false;
|
||||
|
||||
let lastRenderedUsage = '';
|
||||
let lastRenderedTuple = null;
|
||||
let cachedMonthlySeriesRef = null;
|
||||
let cachedMonthlyDisplayKey = '';
|
||||
let cachedMonthsMergedModels = null;
|
||||
let cachedAllMonthMergedModels = null;
|
||||
|
||||
function isSameRenderTuple(prev, next) {
|
||||
if (!prev || prev.length !== next.length) return false;
|
||||
for (let i = 0; i < prev.length; i++) {
|
||||
if (!Object.is(prev[i], next[i])) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将遥测状态切片同步渲染至消费统计视图的 5 个子面板。
|
||||
@@ -20698,31 +21070,9 @@ const ConsumptionView = defineComponent({
|
||||
function renderConsumptionData(slice) {
|
||||
if (!slice) return;
|
||||
const cons = slice.consumption || {};
|
||||
const preset =
|
||||
slice.range !== 'custom' && cons.presets?.[slice.range]
|
||||
? cons.presets[slice.range]
|
||||
: null;
|
||||
const acct = preset?.account || cons.account || {};
|
||||
const rangeInfo = cons.selectedRange || {};
|
||||
const dateSpan = formatDateSpanBadge(rangeInfo.startMs, rangeInfo.endMs);
|
||||
const now = new Date();
|
||||
const currentMonthIdx = now.getMonth();
|
||||
const monthlyYear = cons.monthlyYear || now.getFullYear();
|
||||
const locale = i18nStore.getState().locale;
|
||||
// 额度与会话状态也会发布遥测更新,只对用量页实际展示的数据重绘。
|
||||
const signature = JSON.stringify([
|
||||
locale, slice.range, slice.customStartMs, slice.customEndMs, slice.modelDisplayMode,
|
||||
slice.showUpstreamModel, slice.orchestratorIdMode, dateSpan,
|
||||
preset?.label || rangeInfo.label, acct,
|
||||
cons.trendSeries, slice.modelBreakdown, cons.sourcesBreakdown,
|
||||
monthlyYear, currentMonthIdx, cons.monthlySeries,
|
||||
]);
|
||||
if (signature === lastRenderedUsage) return;
|
||||
drawConsumptionData(slice, { cons, preset, acct, rangeInfo, dateSpan, currentMonthIdx, monthlyYear });
|
||||
lastRenderedUsage = signature;
|
||||
}
|
||||
|
||||
function drawConsumptionData(slice, { cons, preset, acct, rangeInfo, dateSpan, currentMonthIdx, monthlyYear }) {
|
||||
// 始终在 0ms 同步顶部时间段滑块与自定义日期条显隐,给予即刻交互反馈
|
||||
timeFilterSwitch.setValue(slice.range);
|
||||
patchAttr(customRangeBar, 'hidden', slice.range !== 'custom');
|
||||
if (!hasUncommittedCustomDraft) {
|
||||
@@ -20732,6 +21082,45 @@ const ConsumptionView = defineComponent({
|
||||
endPicker.setValue(draftEndMs);
|
||||
}
|
||||
|
||||
// 极少数缓存未命中时(如自定义新区间或进页瞬间抢点),跳过用旧趋势/模型跑无效半更新重绘,待几毫秒后单帧原子绘制
|
||||
if (rangeInfo.key && slice.range && rangeInfo.key !== slice.range) {
|
||||
return;
|
||||
}
|
||||
|
||||
const preset =
|
||||
slice.range !== 'custom' && cons.presets?.[slice.range]
|
||||
? cons.presets[slice.range]
|
||||
: null;
|
||||
const acct = cons.account || preset?.account || {};
|
||||
const dateSpan = formatDateSpanBadge(rangeInfo.startMs, rangeInfo.endMs);
|
||||
const now = new Date();
|
||||
const currentMonthIdx = now.getMonth();
|
||||
const monthlyYear = cons.monthlyYear || now.getFullYear();
|
||||
const locale = i18nStore.getState().locale;
|
||||
const renderTuple = [
|
||||
locale,
|
||||
slice.range,
|
||||
slice.customStartMs,
|
||||
slice.customEndMs,
|
||||
slice.modelDisplayMode,
|
||||
slice.showUpstreamModel,
|
||||
slice.orchestratorIdMode,
|
||||
dateSpan,
|
||||
preset?.label || rangeInfo.label,
|
||||
acct,
|
||||
cons.trendSeries,
|
||||
slice.modelBreakdown,
|
||||
cons.sourcesBreakdown,
|
||||
monthlyYear,
|
||||
currentMonthIdx,
|
||||
cons.monthlySeries,
|
||||
];
|
||||
if (isSameRenderTuple(lastRenderedTuple, renderTuple)) return;
|
||||
drawConsumptionData(slice, { cons, preset, acct, rangeInfo, dateSpan, currentMonthIdx, monthlyYear });
|
||||
lastRenderedTuple = renderTuple;
|
||||
}
|
||||
|
||||
function drawConsumptionData(slice, { cons, preset, acct, rangeInfo, dateSpan, currentMonthIdx, monthlyYear }) {
|
||||
// 1. 同步用量概览矩阵与顶部 4 段比例条
|
||||
patchText(dateSpanBadge, dateSpan);
|
||||
const totalTokens = Number(acct.totalTokens || 0);
|
||||
@@ -20832,14 +21221,31 @@ const ConsumptionView = defineComponent({
|
||||
});
|
||||
|
||||
const monthlySeries = cons.monthlySeries || [];
|
||||
const allMonthMergedModels = [];
|
||||
const monthsMergedModels = Array.from({ length: 12 }, (_, idx) => {
|
||||
const merged = mergeAndSortBucketModels(monthlySeries[idx]?.models);
|
||||
for (const m of merged) {
|
||||
allMonthMergedModels.push(m);
|
||||
}
|
||||
return merged;
|
||||
});
|
||||
const monthlyDisplayKey = `${displaySettings.modelDisplayMode}|${displaySettings.showUpstreamModel ? 1 : 0}|${displaySettings.orchestratorIdMode}`;
|
||||
let monthsMergedModels;
|
||||
let allMonthMergedModels;
|
||||
if (
|
||||
cachedMonthlySeriesRef === monthlySeries &&
|
||||
cachedMonthlyDisplayKey === monthlyDisplayKey &&
|
||||
cachedMonthsMergedModels &&
|
||||
cachedAllMonthMergedModels
|
||||
) {
|
||||
monthsMergedModels = cachedMonthsMergedModels;
|
||||
allMonthMergedModels = cachedAllMonthMergedModels;
|
||||
} else {
|
||||
allMonthMergedModels = [];
|
||||
monthsMergedModels = Array.from({ length: 12 }, (_, idx) => {
|
||||
const merged = mergeAndSortBucketModels(monthlySeries[idx]?.models);
|
||||
for (const m of merged) {
|
||||
allMonthMergedModels.push(m);
|
||||
}
|
||||
return merged;
|
||||
});
|
||||
cachedMonthlySeriesRef = monthlySeries;
|
||||
cachedMonthlyDisplayKey = monthlyDisplayKey;
|
||||
cachedMonthsMergedModels = monthsMergedModels;
|
||||
cachedAllMonthMergedModels = allMonthMergedModels;
|
||||
}
|
||||
|
||||
const rawTrendSeries = cons.trendSeries || [];
|
||||
const allTrendMergedModels = [];
|
||||
@@ -21034,6 +21440,10 @@ const ConsumptionView = defineComponent({
|
||||
}
|
||||
isDirty = false;
|
||||
renderConsumptionData(slice);
|
||||
if (!prefetchedOnCurrentVisit && Number(slice?.consumption?.revision || 0) > 0) {
|
||||
prefetchedOnCurrentVisit = true;
|
||||
void prefetchConsumptionPresets();
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
@@ -21041,6 +21451,7 @@ const ConsumptionView = defineComponent({
|
||||
getVisibleMonitorView,
|
||||
(activeView) => {
|
||||
if (activeView !== 'consumption') {
|
||||
prefetchedOnCurrentVisit = false;
|
||||
hideBreakdownPopover();
|
||||
return;
|
||||
}
|
||||
@@ -21050,6 +21461,10 @@ const ConsumptionView = defineComponent({
|
||||
renderConsumptionData(latestSlice);
|
||||
}
|
||||
}
|
||||
if (!prefetchedOnCurrentVisit && Number(latestSlice?.consumption?.revision || 0) > 0) {
|
||||
prefetchedOnCurrentVisit = true;
|
||||
void prefetchConsumptionPresets();
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@ import {
|
||||
syncCloudCatalog,
|
||||
} from './plugin-updater.mjs';
|
||||
import { getCloudStatus } from './pricing-catalog.mjs';
|
||||
import { buildTelemetryPayload } from './telemetry-builder.mjs';
|
||||
import { buildTelemetryPayload, clearTelemetryBuilderMemo } from './telemetry-builder.mjs';
|
||||
import {
|
||||
ensureDesktopLaunchEntriesConfigured,
|
||||
triggerDesktopHostRelaunch,
|
||||
@@ -192,10 +192,14 @@ export async function executeTelemetryAction(data, { onRestart = null } = {}) {
|
||||
}
|
||||
}
|
||||
}
|
||||
const rawScope = String(data?.scope || '').trim();
|
||||
const scope =
|
||||
rawScope === 'consumption' || rawScope === 'consumption-presets' ? rawScope : '';
|
||||
const filterOpts = {
|
||||
range: data?.range || 'all',
|
||||
startMs: sanitizePositiveFiniteMs(data?.startMs),
|
||||
endMs: sanitizePositiveFiniteMs(data?.endMs),
|
||||
...(scope ? { scope } : {}),
|
||||
};
|
||||
let payload;
|
||||
try {
|
||||
@@ -216,7 +220,7 @@ export async function executeTelemetryAction(data, { onRestart = null } = {}) {
|
||||
}
|
||||
if (
|
||||
bootBundleVersion &&
|
||||
payload.uiBundleVersion &&
|
||||
payload?.uiBundleVersion &&
|
||||
String(payload.uiBundleVersion) !== String(bootBundleVersion)
|
||||
) {
|
||||
if (typeof onRestart === 'function') {
|
||||
@@ -225,9 +229,12 @@ export async function executeTelemetryAction(data, { onRestart = null } = {}) {
|
||||
scheduleSidecarRestart(150);
|
||||
}
|
||||
}
|
||||
const responsePayload = data?.stepDetails === 'display'
|
||||
? projectDisplayTelemetry(payload, data.stepRevision)
|
||||
: payload;
|
||||
const isScopedConsumptionPayload =
|
||||
payload?.scope === 'consumption' || payload?.scope === 'consumption-presets';
|
||||
const responsePayload =
|
||||
!isScopedConsumptionPayload && data?.stepDetails === 'display'
|
||||
? projectDisplayTelemetry(payload, data.stepRevision)
|
||||
: payload;
|
||||
return {
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
@@ -295,11 +302,20 @@ export function executeSettingsAction(data) {
|
||||
body: JSON.stringify({ ok: false, error: 'Failed to persist settings' }),
|
||||
};
|
||||
}
|
||||
inFlightRequests.clear();
|
||||
const prevMountMode = normalizeWindowMountMode(
|
||||
current.windowMountMode,
|
||||
current.enableWindowOverlay
|
||||
);
|
||||
const affectsBackendTelemetry =
|
||||
updated.weeklyLimitMode !== current.weeklyLimitMode ||
|
||||
updated.weeklyTokenBudget !== current.weeklyTokenBudget ||
|
||||
updated.weeklyCostBudget !== current.weeklyCostBudget ||
|
||||
updated.enableWindowOverlay !== (current.enableWindowOverlay !== false) ||
|
||||
updated.windowMountMode !== prevMountMode;
|
||||
inFlightRequests.clear();
|
||||
if (affectsBackendTelemetry) {
|
||||
clearTelemetryBuilderMemo();
|
||||
}
|
||||
if (
|
||||
updated.enableWindowOverlay !== (current.enableWindowOverlay !== false) ||
|
||||
updated.windowMountMode !== prevMountMode
|
||||
@@ -364,6 +380,7 @@ export async function executeModelContextWindowAction(data) {
|
||||
return respond(500, { error: 'Failed to persist model context window' });
|
||||
}
|
||||
inFlightRequests.clear();
|
||||
clearTelemetryBuilderMemo();
|
||||
void notifyModelContextWindowsChanged();
|
||||
return respond(200, { modelContextWindows: current.modelContextWindows });
|
||||
}
|
||||
@@ -381,6 +398,7 @@ export function executeResetSettingsAction() {
|
||||
};
|
||||
}
|
||||
inFlightRequests.clear();
|
||||
clearTelemetryBuilderMemo();
|
||||
const prevMountMode = normalizeWindowMountMode(
|
||||
current.windowMountMode,
|
||||
current.enableWindowOverlay
|
||||
@@ -429,6 +447,7 @@ export function executeRebuildCacheAction() {
|
||||
}
|
||||
displayStepsCache.clear();
|
||||
clearScannerRuntimeMemos();
|
||||
clearTelemetryBuilderMemo();
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
@@ -440,6 +459,7 @@ export function executeRebuildCacheAction() {
|
||||
|
||||
export async function executeCloudSyncAction() {
|
||||
const cloudStatus = await syncCloudCatalog({ force: true });
|
||||
clearTelemetryBuilderMemo();
|
||||
return {
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
@@ -460,6 +480,9 @@ export async function executePluginUpdateAction() {
|
||||
|
||||
export async function executeAccountCredentialAction(data) {
|
||||
const result = await handleAccountCredentialAction(data);
|
||||
if (data?.action === 'switch') {
|
||||
clearTelemetryBuilderMemo();
|
||||
}
|
||||
return {
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
|
||||
@@ -46,8 +46,11 @@ import { getCloudStatus, getPricingPhaseEpoch, pricingCatalogRevision } from './
|
||||
import { buildOfficialQuotaPools } from './quota-pools.mjs';
|
||||
import { getDefaultWindowBridgeStatus } from './window-bridge.mjs';
|
||||
import {
|
||||
aggregateConsumptionPresetBundle,
|
||||
aggregateMultiWindowUsage,
|
||||
aggregateSelectedWindowUsage,
|
||||
buildScopedModelBreakdown,
|
||||
clearUsageAggregatorMemo,
|
||||
getNextMondayResetIso,
|
||||
} from './usage-aggregator.mjs';
|
||||
|
||||
@@ -56,6 +59,13 @@ const POOL_PRIORITY_ORDER = ['Gemini', 'Argon', 'Carbon', 'Claude & GPT'];
|
||||
const inFlightTelemetrySources = new Map();
|
||||
const trajectoryModelFacts = new WeakMap();
|
||||
let lastMainPreparation = null;
|
||||
let lastCompletedTelemetrySnapshot = null;
|
||||
|
||||
export function clearTelemetryBuilderMemo() {
|
||||
lastMainPreparation = null;
|
||||
lastCompletedTelemetrySnapshot = null;
|
||||
clearUsageAggregatorMemo();
|
||||
}
|
||||
|
||||
function roundSessionCost(val) {
|
||||
if (!Number.isFinite(val) || val <= 0) return 0;
|
||||
@@ -1237,6 +1247,7 @@ export async function buildTelemetryPayloadInternal(
|
||||
|
||||
// 5. 多时间窗口聚合(预设窗口 + 当前选定窗口 + 趋势 + 月序列 + 来源与模型拆解 + 各配额池独立周期统计)
|
||||
const {
|
||||
usageRevision,
|
||||
selectedWindow,
|
||||
trendStartMs,
|
||||
trendEndMs,
|
||||
@@ -1816,6 +1827,7 @@ export async function buildTelemetryPayloadInternal(
|
||||
aggregated: aggregatedTelemetry,
|
||||
},
|
||||
consumption: {
|
||||
revision: usageRevision,
|
||||
selectedRange: {
|
||||
key: selectedWindow.key,
|
||||
label: selectedWindow.label,
|
||||
@@ -1883,6 +1895,24 @@ export async function buildTelemetryPayloadInternal(
|
||||
modelBreakdown,
|
||||
};
|
||||
|
||||
lastCompletedTelemetrySnapshot = {
|
||||
lsAddr: String(lsRuntimeEndpoint.addr || ''),
|
||||
weeklyLimitMode: settings.weeklyLimitMode,
|
||||
catalogRevision: modelInputs.catalogRevision,
|
||||
phaseEpoch: modelInputs.phaseEpoch,
|
||||
basePayload: finalPayload,
|
||||
aggContext: {
|
||||
cycleAnchors,
|
||||
isCustomWeeklyMode,
|
||||
currentAccountName: accountScope,
|
||||
activeCascadeId,
|
||||
activeFamilyCascadeIds,
|
||||
resolveStepModel,
|
||||
quotaPoolsMap,
|
||||
modelInputs,
|
||||
},
|
||||
};
|
||||
|
||||
if (lsRuntimeEndpoint.addr !== 'test.invalid') {
|
||||
try {
|
||||
saveJson(CLI_STATUS_SNAPSHOT_FILE, buildCliStatusSnapshot(finalPayload, Date.now()));
|
||||
@@ -1894,6 +1924,65 @@ export async function buildTelemetryPayloadInternal(
|
||||
return finalPayload;
|
||||
}
|
||||
|
||||
function resolveValidFastSnapshot() {
|
||||
const snap = lastCompletedTelemetrySnapshot;
|
||||
if (!snap || !snap.basePayload || !snap.aggContext) return null;
|
||||
if (snap.lsAddr !== String(lsRuntimeEndpoint.addr || '')) return null;
|
||||
if (
|
||||
snap.catalogRevision !== pricingCatalogRevision ||
|
||||
snap.phaseEpoch !== getPricingPhaseEpoch()
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const latestSettings = loadSettings();
|
||||
if (latestSettings.weeklyLimitMode !== snap.weeklyLimitMode) {
|
||||
return null;
|
||||
}
|
||||
return snap;
|
||||
}
|
||||
|
||||
function tryBuildFastConsumptionPayload(filterOpts = {}) {
|
||||
const snap = resolveValidFastSnapshot();
|
||||
if (!snap) return null;
|
||||
const agg = aggregateSelectedWindowUsage({
|
||||
filterOpts,
|
||||
...snap.aggContext,
|
||||
});
|
||||
return {
|
||||
scope: 'consumption',
|
||||
timestamp: new Date().toISOString(),
|
||||
uiBundleVersion: snap.basePayload.uiBundleVersion || computeRuntimeCodeVersion(),
|
||||
usageRevision: agg.usageRevision,
|
||||
consumption: {
|
||||
revision: agg.usageRevision,
|
||||
selectedRange: {
|
||||
key: agg.selectedWindow.key,
|
||||
label: agg.selectedWindow.label,
|
||||
startMs: agg.trendStartMs,
|
||||
endMs: agg.trendEndMs,
|
||||
},
|
||||
session: agg.finalizedSelectedSession,
|
||||
account: agg.finalizedSelectedAccount,
|
||||
trendSeries: agg.trendSeries,
|
||||
sourcesBreakdown: agg.sourcesBreakdown,
|
||||
},
|
||||
modelBreakdown: agg.modelBreakdown,
|
||||
};
|
||||
}
|
||||
|
||||
function tryBuildConsumptionPresetsPayload() {
|
||||
const snap = resolveValidFastSnapshot();
|
||||
if (!snap) return null;
|
||||
const bundle = aggregateConsumptionPresetBundle(snap.aggContext);
|
||||
return {
|
||||
scope: 'consumption-presets',
|
||||
timestamp: new Date().toISOString(),
|
||||
uiBundleVersion: snap.basePayload.uiBundleVersion || computeRuntimeCodeVersion(),
|
||||
usageRevision: bundle.usageRevision,
|
||||
ranges: bundle.ranges,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildCliStatusSnapshot(finalPayload, updatedAtMs = Date.now()) {
|
||||
const ac = finalPayload?.activeConversation || {};
|
||||
const capSource = ac.aggregated || ac;
|
||||
@@ -1938,7 +2027,7 @@ export function buildCliStatusSnapshot(finalPayload, updatedAtMs = Date.now()) {
|
||||
*
|
||||
* @param {string} requestedConvId
|
||||
* @param {boolean} [forceQuotaRefresh=false]
|
||||
* @param {{ range?: string, startMs?: number, endMs?: number }} [filterOpts={}]
|
||||
* @param {{ range?: string, startMs?: number, endMs?: number, scope?: string }} [filterOpts={}]
|
||||
* @returns {Promise<object>}
|
||||
*/
|
||||
export function buildTelemetryPayload(
|
||||
@@ -1946,6 +2035,31 @@ export function buildTelemetryPayload(
|
||||
forceQuotaRefresh = false,
|
||||
filterOpts = {}
|
||||
) {
|
||||
if (!forceQuotaRefresh) {
|
||||
if (filterOpts?.scope === 'consumption-presets') {
|
||||
const presetsPayload = tryBuildConsumptionPresetsPayload();
|
||||
if (presetsPayload) {
|
||||
return Promise.resolve(presetsPayload);
|
||||
}
|
||||
const key = `${requestedConvId || '__auto__'}::presets-cold`;
|
||||
if (inFlightRequests.has(key)) {
|
||||
return inFlightRequests.get(key);
|
||||
}
|
||||
const p = buildTelemetryPayloadInternal(requestedConvId, false, { range: 'today' })
|
||||
.then(() => tryBuildConsumptionPresetsPayload())
|
||||
.finally(() => {
|
||||
inFlightRequests.delete(key);
|
||||
});
|
||||
inFlightRequests.set(key, p);
|
||||
return p;
|
||||
}
|
||||
if (filterOpts?.scope === 'consumption') {
|
||||
const litePayload = tryBuildFastConsumptionPayload(filterOpts);
|
||||
if (litePayload) {
|
||||
return Promise.resolve(litePayload);
|
||||
}
|
||||
}
|
||||
}
|
||||
const rangeSig = `${filterOpts.range || 'all'}:${filterOpts.startMs || 0}:${filterOpts.endMs || 0}`;
|
||||
const key = `${requestedConvId || '__auto__'}::${forceQuotaRefresh ? 'force' : 'normal'}::${rangeSig}`;
|
||||
if (inFlightRequests.has(key)) {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -4,11 +4,11 @@
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>用量监控</title>
|
||||
<link rel="stylesheet" href="/styles.css?v=1795073698225">
|
||||
<link rel="stylesheet" href="/styles.css?v=1795085924190">
|
||||
<script src="/preload.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app-root"></div>
|
||||
<script src="/app.js?v=1795073698225"></script>
|
||||
<script src="/app.js?v=1795085924190"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -920,13 +920,18 @@ export function createTrendAreaChart() {
|
||||
hmMonthsEl.appendChild(mEl);
|
||||
}
|
||||
|
||||
// 重建 7 行 × N 周列的每日小格子(一格一天)
|
||||
// 重建 7 行 × N 周列的每日小格子(一格一天),使用 DocumentFragment 一次性批量挂载减少重排
|
||||
while (hmGridEl.firstChild) hmGridEl.removeChild(hmGridEl.firstChild);
|
||||
hoveredCellEl = null;
|
||||
currentCellEls = new Array(slots.length);
|
||||
const gridFrag =
|
||||
typeof document !== 'undefined' && typeof document.createDocumentFragment === 'function'
|
||||
? document.createDocumentFragment()
|
||||
: null;
|
||||
const gridTarget = gridFrag || hmGridEl;
|
||||
|
||||
for (let pad = 0; pad < firstDow; pad++) {
|
||||
hmGridEl.appendChild(
|
||||
gridTarget.appendChild(
|
||||
h('span', { className: 'trend-hm-cell is-pad', 'aria-hidden': 'true' })
|
||||
);
|
||||
}
|
||||
@@ -945,9 +950,12 @@ export function createTrendAreaChart() {
|
||||
'data-hm-row': String(row),
|
||||
role: 'gridcell',
|
||||
});
|
||||
hmGridEl.appendChild(cellEl);
|
||||
gridTarget.appendChild(cellEl);
|
||||
currentCellEls[i] = cellEl;
|
||||
}
|
||||
if (gridFrag) {
|
||||
hmGridEl.appendChild(gridFrag);
|
||||
}
|
||||
|
||||
if (typeof requestAnimationFrame === 'function') {
|
||||
requestAnimationFrame(() => {
|
||||
|
||||
@@ -141,9 +141,16 @@ let pollTimer = null;
|
||||
let feedbackTimer = null;
|
||||
let activeBundleVersion = 0;
|
||||
let latestRequestSeq = 0;
|
||||
let latestConsumptionReqSeq = 0;
|
||||
let activeForceCount = 0;
|
||||
let consecutivePollFailures = 0;
|
||||
let inFlightTelemetryPoll = null;
|
||||
let inFlightPresetsPrefetch = null;
|
||||
let lastPrefetchedUsageRevision = 0;
|
||||
let consumptionCacheScopeSig = '';
|
||||
const MAX_CONSUMPTION_RANGE_CACHE = 12;
|
||||
const CONSUMPTION_PRESET_KEYS = ['cycle', 'today', '24h', '7d', '14d', '30d', 'all'];
|
||||
const consumptionRangeCache = new Map();
|
||||
let lastReceivedSteps = null;
|
||||
let loopActive = false;
|
||||
let loopIntervalMs = 2000;
|
||||
@@ -161,6 +168,96 @@ const TELEMETRY_RECOMPUTE_SETTING_KEYS = new Set([
|
||||
'enableWindowOverlay',
|
||||
]);
|
||||
|
||||
function makeConsumptionRangeCacheKey(range, customStartMs = 0, customEndMs = 0) {
|
||||
const key = String(range || 'all');
|
||||
if (key === 'custom') {
|
||||
return `custom:${Number(customStartMs || 0)}:${Number(customEndMs || 0)}`;
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
export function clearConsumptionRangeCache() {
|
||||
consumptionRangeCache.clear();
|
||||
lastPrefetchedUsageRevision = 0;
|
||||
inFlightPresetsPrefetch = null;
|
||||
}
|
||||
|
||||
function buildConsumptionScopeSig(payload) {
|
||||
if (!payload || typeof payload !== 'object') return '';
|
||||
const acct = payload.account || {};
|
||||
const set = payload.settings || {};
|
||||
const cloud = payload.cloudStatus || {};
|
||||
return `${String(acct.status || '')}|${String(acct.email || acct.name || '').toLowerCase()}|${String(set.weeklyLimitMode || '')}|${String(cloud.catalogVersion || '')}`;
|
||||
}
|
||||
|
||||
function syncConsumptionCacheScope(payload) {
|
||||
const nextSig = buildConsumptionScopeSig(payload);
|
||||
if (!nextSig) return;
|
||||
if (consumptionCacheScopeSig && consumptionCacheScopeSig !== nextSig) {
|
||||
clearConsumptionRangeCache();
|
||||
}
|
||||
consumptionCacheScopeSig = nextSig;
|
||||
}
|
||||
|
||||
function putConsumptionRangeCacheEntry(cacheKey, entry) {
|
||||
if (!cacheKey || !entry) return;
|
||||
consumptionRangeCache.delete(cacheKey);
|
||||
consumptionRangeCache.set(cacheKey, entry);
|
||||
while (consumptionRangeCache.size > MAX_CONSUMPTION_RANGE_CACHE) {
|
||||
consumptionRangeCache.delete(consumptionRangeCache.keys().next().value);
|
||||
}
|
||||
}
|
||||
|
||||
function recordConsumptionSliceToCache(
|
||||
cons,
|
||||
modelBreakdown,
|
||||
{ customStartMs = 0, customEndMs = 0, usageRevision = 0 } = {}
|
||||
) {
|
||||
const rangeKey = String(cons?.selectedRange?.key || '');
|
||||
if (!rangeKey) return;
|
||||
const cacheKey = makeConsumptionRangeCacheKey(
|
||||
rangeKey,
|
||||
rangeKey === 'custom' ? customStartMs || cons.selectedRange?.startMs || 0 : 0,
|
||||
rangeKey === 'custom' ? customEndMs || cons.selectedRange?.endMs || 0 : 0
|
||||
);
|
||||
putConsumptionRangeCacheEntry(cacheKey, {
|
||||
revision: Number(cons.revision ?? usageRevision ?? 0),
|
||||
selectedRange: cons.selectedRange,
|
||||
session: cons.session,
|
||||
account: cons.account,
|
||||
trendSeries: Array.isArray(cons.trendSeries) ? cons.trendSeries : [],
|
||||
sourcesBreakdown: Array.isArray(cons.sourcesBreakdown) ? cons.sourcesBreakdown : [],
|
||||
modelBreakdown: Array.isArray(modelBreakdown) ? modelBreakdown : [],
|
||||
});
|
||||
}
|
||||
|
||||
function applyCachedConsumptionSlice(baseTelemetry, cachedEntry, targetRevision = 0) {
|
||||
if (!baseTelemetry || !cachedEntry) return baseTelemetry;
|
||||
const prevCons = baseTelemetry.consumption || {};
|
||||
return {
|
||||
...baseTelemetry,
|
||||
consumption: {
|
||||
...prevCons,
|
||||
...(targetRevision > 0 ? { revision: targetRevision } : {}),
|
||||
selectedRange: cachedEntry.selectedRange,
|
||||
session: cachedEntry.session ?? prevCons.session,
|
||||
account: cachedEntry.account ?? prevCons.account,
|
||||
trendSeries: cachedEntry.trendSeries,
|
||||
sourcesBreakdown: cachedEntry.sourcesBreakdown,
|
||||
},
|
||||
modelBreakdown: cachedEntry.modelBreakdown,
|
||||
};
|
||||
}
|
||||
|
||||
function hasAllPresetRangesCached(expectedRevision) {
|
||||
for (const key of CONSUMPTION_PRESET_KEYS) {
|
||||
const entry = consumptionRangeCache.get(key);
|
||||
if (!entry) return false;
|
||||
if (expectedRevision > 0 && entry.revision !== expectedRevision) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function enqueueSettingsWrite(task) {
|
||||
const run = settingsWriteChain.then(task, task);
|
||||
settingsWriteChain = run.catch(() => {});
|
||||
@@ -853,6 +950,9 @@ function readDisplaySteps(payload) {
|
||||
async function requestTelemetry(params, force) {
|
||||
const reqSeq = ++latestRequestSeq;
|
||||
const reqSettingsRev = settingsRevision;
|
||||
const reqRange = String(params.get('range') || '');
|
||||
const reqStartMs = Number(params.get('startMs') || 0);
|
||||
const reqEndMs = Number(params.get('endMs') || 0);
|
||||
const startMs = Date.now();
|
||||
|
||||
if (force) {
|
||||
@@ -903,8 +1003,57 @@ async function requestTelemetry(params, force) {
|
||||
}
|
||||
consecutivePollFailures = 0;
|
||||
|
||||
const resolvedPayload = reconcileIncomingTelemetrySettings(payload, reqSettingsRev);
|
||||
let resolvedPayload = reconcileIncomingTelemetrySettings(payload, reqSettingsRev);
|
||||
syncConsumptionCacheScope(resolvedPayload);
|
||||
if (resolvedPayload?.consumption) {
|
||||
recordConsumptionSliceToCache(resolvedPayload.consumption, resolvedPayload.modelBreakdown, {
|
||||
customStartMs: reqStartMs,
|
||||
customEndMs: reqEndMs,
|
||||
});
|
||||
}
|
||||
|
||||
const latestSt = telemetryStore.getState();
|
||||
const incomingRev = Number(resolvedPayload?.consumption?.revision || 0);
|
||||
const matchesCurrentRange =
|
||||
!reqRange ||
|
||||
(reqRange === latestSt.selectedTimeRange &&
|
||||
(reqRange !== 'custom' ||
|
||||
(reqStartMs === Number(latestSt.customStartMs || 0) &&
|
||||
reqEndMs === Number(latestSt.customEndMs || 0))));
|
||||
|
||||
// 常规 2 秒轮询在途期间若用户已通过前端缓存瞬切到其他时间段,保留用户当前选中的范围不回跳,
|
||||
// 若后端 usageRevision 已推进则静默补发一次轻量范围校准。
|
||||
let needsSilentRangeRevalidate = false;
|
||||
if (!force && !matchesCurrentRange && resolvedPayload?.consumption) {
|
||||
const activeKey = makeConsumptionRangeCacheKey(
|
||||
latestSt.selectedTimeRange,
|
||||
latestSt.customStartMs,
|
||||
latestSt.customEndMs
|
||||
);
|
||||
const cachedActive = consumptionRangeCache.get(activeKey);
|
||||
if (cachedActive) {
|
||||
resolvedPayload = applyCachedConsumptionSlice(resolvedPayload, cachedActive, incomingRev);
|
||||
if (incomingRev > 0 && cachedActive.revision !== incomingRev) {
|
||||
needsSilentRangeRevalidate = true;
|
||||
}
|
||||
} else if (
|
||||
latestSt.telemetry?.consumption?.selectedRange?.key === latestSt.selectedTimeRange
|
||||
) {
|
||||
resolvedPayload = {
|
||||
...resolvedPayload,
|
||||
consumption: {
|
||||
...resolvedPayload.consumption,
|
||||
selectedRange: latestSt.telemetry.consumption.selectedRange,
|
||||
session: latestSt.telemetry.consumption.session,
|
||||
account: latestSt.telemetry.consumption.account,
|
||||
trendSeries: latestSt.telemetry.consumption.trendSeries,
|
||||
sourcesBreakdown: latestSt.telemetry.consumption.sourcesBreakdown,
|
||||
},
|
||||
modelBreakdown: latestSt.telemetry.modelBreakdown,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (force) {
|
||||
const elapsed = Date.now() - startMs;
|
||||
if (elapsed < 220) {
|
||||
@@ -933,6 +1082,13 @@ async function requestTelemetry(params, force) {
|
||||
minuteTick: Math.floor(Date.now() / 30000),
|
||||
syncState: latestSt.syncState === 'synced' ? 'synced' : 'idle',
|
||||
});
|
||||
if (needsSilentRangeRevalidate) {
|
||||
void fetchConsumptionRangeSlice({
|
||||
range: latestSt.selectedTimeRange,
|
||||
customStartMs: latestSt.customStartMs,
|
||||
customEndMs: latestSt.customEndMs,
|
||||
});
|
||||
}
|
||||
return resolvedPayload;
|
||||
}
|
||||
} catch (err) {
|
||||
@@ -952,6 +1108,198 @@ async function requestTelemetry(params, force) {
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchConsumptionRangeSlice({
|
||||
range,
|
||||
customStartMs = 0,
|
||||
customEndMs = 0,
|
||||
} = {}) {
|
||||
const reqSeq = ++latestConsumptionReqSeq;
|
||||
const targetRange = String(range || 'today');
|
||||
const current = telemetryStore.getState();
|
||||
const effectiveConvId = current.selectedConversationId || current.hostRouteConversationId || '';
|
||||
const params = new URLSearchParams();
|
||||
if (effectiveConvId) params.set('conversationId', effectiveConvId);
|
||||
params.set('range', targetRange);
|
||||
if (targetRange === 'custom') {
|
||||
if (customStartMs > 0) params.set('startMs', String(customStartMs));
|
||||
if (customEndMs > 0) params.set('endMs', String(customEndMs));
|
||||
}
|
||||
params.set('scope', 'consumption');
|
||||
|
||||
try {
|
||||
const payload = await callSidecarApi(`/api/telemetry?${params}`, {
|
||||
method: 'GET',
|
||||
abortKey: 'consumption-range',
|
||||
});
|
||||
if (!payload || typeof payload !== 'object') return null;
|
||||
|
||||
if (payload.scope === 'consumption' && payload.consumption) {
|
||||
const usageRev = Number(payload.usageRevision ?? payload.consumption.revision ?? 0);
|
||||
recordConsumptionSliceToCache(payload.consumption, payload.modelBreakdown, {
|
||||
customStartMs,
|
||||
customEndMs,
|
||||
usageRevision: usageRev,
|
||||
});
|
||||
if (reqSeq !== latestConsumptionReqSeq) return payload;
|
||||
|
||||
const latestSt = telemetryStore.getState();
|
||||
const stillMatches =
|
||||
latestSt.selectedTimeRange === targetRange &&
|
||||
(targetRange !== 'custom' ||
|
||||
(Number(latestSt.customStartMs || 0) === Number(customStartMs || 0) &&
|
||||
Number(latestSt.customEndMs || 0) === Number(customEndMs || 0)));
|
||||
if (!stillMatches) return payload;
|
||||
|
||||
const prevTelemetry = latestSt.telemetry;
|
||||
if (prevTelemetry) {
|
||||
const nextTelemetry = {
|
||||
...prevTelemetry,
|
||||
consumption: {
|
||||
...(prevTelemetry.consumption || {}),
|
||||
...payload.consumption,
|
||||
...(usageRev > 0 ? { revision: usageRev } : {}),
|
||||
},
|
||||
modelBreakdown: Array.isArray(payload.modelBreakdown)
|
||||
? payload.modelBreakdown
|
||||
: prevTelemetry.modelBreakdown,
|
||||
};
|
||||
if (!isEquivalentTelemetry(prevTelemetry, nextTelemetry)) {
|
||||
telemetryStore.setState({ telemetry: nextTelemetry });
|
||||
}
|
||||
}
|
||||
return payload;
|
||||
}
|
||||
|
||||
// 冷启动阶段后端尚无基础快照时会回退返回完整 telemetry,直接平滑复用现有状态合并
|
||||
if (payload.consumption) {
|
||||
syncConsumptionCacheScope(payload);
|
||||
recordConsumptionSliceToCache(payload.consumption, payload.modelBreakdown, {
|
||||
customStartMs,
|
||||
customEndMs,
|
||||
});
|
||||
if (reqSeq === latestConsumptionReqSeq) {
|
||||
const latestSt = telemetryStore.getState();
|
||||
if (!isEquivalentTelemetry(latestSt.telemetry, payload)) {
|
||||
telemetryStore.setState({ telemetry: payload });
|
||||
}
|
||||
}
|
||||
}
|
||||
return payload;
|
||||
} catch (err) {
|
||||
if (err?.name === 'AbortError') return null;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换「用量统计」时间范围:
|
||||
* - 命中前端 rangeCache 时,在单次 setState 内 0ms 原子更新概览/趋势/模型/来源(若 usageRevision 一致则 0 次 HTTP 请求);
|
||||
* - 若后台数据已更新则先 0ms 展示缓存,再静默发起轻量 `scope=consumption` 校准;
|
||||
* - 未命中缓存(如自定义时段或进页首 20ms 抢点)则直接走 `<5ms` 的 `scope=consumption` 通道。
|
||||
*/
|
||||
export function selectConsumptionTimeRange(
|
||||
nextRange,
|
||||
{ customStartMs = undefined, customEndMs = undefined } = {}
|
||||
) {
|
||||
const targetRange = String(nextRange || 'today');
|
||||
const prevSt = telemetryStore.getState();
|
||||
const nextStartMs =
|
||||
targetRange === 'custom'
|
||||
? Number(customStartMs !== undefined ? customStartMs : prevSt.customStartMs || 0)
|
||||
: prevSt.customStartMs;
|
||||
const nextEndMs =
|
||||
targetRange === 'custom'
|
||||
? Number(customEndMs !== undefined ? customEndMs : prevSt.customEndMs || 0)
|
||||
: prevSt.customEndMs;
|
||||
|
||||
const statePatch = { selectedTimeRange: targetRange };
|
||||
if (targetRange === 'custom') {
|
||||
statePatch.customStartMs = nextStartMs;
|
||||
statePatch.customEndMs = nextEndMs;
|
||||
}
|
||||
|
||||
const cacheKey = makeConsumptionRangeCacheKey(targetRange, nextStartMs, nextEndMs);
|
||||
const cached = consumptionRangeCache.get(cacheKey);
|
||||
const prevTelemetry = prevSt.telemetry;
|
||||
|
||||
if (cached && prevTelemetry) {
|
||||
const currentRev = Number(prevTelemetry.consumption?.revision || 0);
|
||||
const nextTelemetry = applyCachedConsumptionSlice(
|
||||
prevTelemetry,
|
||||
cached,
|
||||
currentRev > 0 ? currentRev : cached.revision
|
||||
);
|
||||
telemetryStore.setState({ ...statePatch, telemetry: nextTelemetry });
|
||||
if (currentRev > 0 && cached.revision === currentRev) {
|
||||
return Promise.resolve(nextTelemetry);
|
||||
}
|
||||
return fetchConsumptionRangeSlice({
|
||||
range: targetRange,
|
||||
customStartMs: nextStartMs,
|
||||
customEndMs: nextEndMs,
|
||||
});
|
||||
}
|
||||
|
||||
telemetryStore.setState(statePatch);
|
||||
return fetchConsumptionRangeSlice({
|
||||
range: targetRange,
|
||||
customStartMs: nextStartMs,
|
||||
customEndMs: nextEndMs,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 仅在进入「用量统计」视图时触发一次静默后台预取,拉齐全部 7 个预设区间到前端缓存以实现 0ms 瞬切。
|
||||
*/
|
||||
export function prefetchConsumptionPresets() {
|
||||
const prevTelemetry = telemetryStore.getState().telemetry;
|
||||
const currentRev = Number(prevTelemetry?.consumption?.revision || 0);
|
||||
if (currentRev > 0 && lastPrefetchedUsageRevision === currentRev && hasAllPresetRangesCached(currentRev)) {
|
||||
return Promise.resolve(true);
|
||||
}
|
||||
if (inFlightPresetsPrefetch) {
|
||||
return inFlightPresetsPrefetch;
|
||||
}
|
||||
|
||||
const current = telemetryStore.getState();
|
||||
const effectiveConvId = current.selectedConversationId || current.hostRouteConversationId || '';
|
||||
const params = new URLSearchParams();
|
||||
if (effectiveConvId) params.set('conversationId', effectiveConvId);
|
||||
params.set('scope', 'consumption-presets');
|
||||
|
||||
const task = callSidecarApi(`/api/telemetry?${params}`, {
|
||||
method: 'GET',
|
||||
abortKey: 'consumption-presets',
|
||||
})
|
||||
.then((payload) => {
|
||||
if (payload?.scope === 'consumption-presets' && payload.ranges && typeof payload.ranges === 'object') {
|
||||
const rev = Number(payload.usageRevision || currentRev || 0);
|
||||
for (const [rangeKey, entry] of Object.entries(payload.ranges)) {
|
||||
if (!entry || typeof entry !== 'object') continue;
|
||||
recordConsumptionSliceToCache(
|
||||
{ ...entry, revision: rev },
|
||||
entry.modelBreakdown,
|
||||
{ usageRevision: rev }
|
||||
);
|
||||
}
|
||||
if (rev > 0) {
|
||||
lastPrefetchedUsageRevision = rev;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
})
|
||||
.catch(() => false)
|
||||
.finally(() => {
|
||||
if (inFlightPresetsPrefetch === task) {
|
||||
inFlightPresetsPrefetch = null;
|
||||
}
|
||||
});
|
||||
|
||||
inFlightPresetsPrefetch = task;
|
||||
return task;
|
||||
}
|
||||
|
||||
export async function saveSettingsPatch(patch) {
|
||||
const safePatch = patch && typeof patch === 'object' ? { ...patch } : {};
|
||||
if (Object.prototype.hasOwnProperty.call(safePatch, 'language')) {
|
||||
@@ -1127,6 +1475,9 @@ export async function saveSettingsPatch(patch) {
|
||||
}
|
||||
|
||||
const needsTelemetryRecompute = patchKeys.some((k) => TELEMETRY_RECOMPUTE_SETTING_KEYS.has(k));
|
||||
if (Object.prototype.hasOwnProperty.call(safePatch, 'weeklyLimitMode')) {
|
||||
clearConsumptionRangeCache();
|
||||
}
|
||||
if (needsTelemetryRecompute) {
|
||||
inFlightTelemetryPoll = null;
|
||||
void fetchTelemetry({ force: false });
|
||||
@@ -1190,18 +1541,21 @@ export async function resetAllSettings() {
|
||||
});
|
||||
}
|
||||
inFlightTelemetryPoll = null;
|
||||
clearConsumptionRangeCache();
|
||||
void fetchTelemetry({ force: false });
|
||||
return res;
|
||||
}
|
||||
|
||||
export async function rebuildTrajectoryCache() {
|
||||
const res = await callSidecarApi('/api/cache/rebuild', { method: 'POST', body: {} });
|
||||
clearConsumptionRangeCache();
|
||||
await fetchTelemetry({ force: true });
|
||||
return res;
|
||||
}
|
||||
|
||||
export async function triggerCloudSync() {
|
||||
const res = await callSidecarApi('/api/cloud-sync', { method: 'POST', body: {} });
|
||||
clearConsumptionRangeCache();
|
||||
await fetchTelemetry({ force: true });
|
||||
return res;
|
||||
}
|
||||
|
||||
@@ -33,7 +33,11 @@ import {
|
||||
import { scaleBucketsExact } from '../../shared/telemetry-display-rules.mjs';
|
||||
import { i18nStore, isEnglishLocale, t } from '../i18n/index.js';
|
||||
import { createSvgIcon } from '../icons/SvgIcon.js';
|
||||
import { fetchTelemetry, telemetryStore } from '../store/telemetryStore.js';
|
||||
import {
|
||||
prefetchConsumptionPresets,
|
||||
selectConsumptionTimeRange,
|
||||
telemetryStore,
|
||||
} from '../store/telemetryStore.js';
|
||||
import { getVisibleMonitorView, uiStore } from '../store/uiStore.js';
|
||||
import {
|
||||
createTrendAreaChart,
|
||||
@@ -81,8 +85,7 @@ export const ConsumptionView = defineComponent({
|
||||
} else {
|
||||
hasUncommittedCustomDraft = false;
|
||||
}
|
||||
telemetryStore.setState({ selectedTimeRange: nextRange });
|
||||
fetchTelemetry({ force: false });
|
||||
selectConsumptionTimeRange(nextRange);
|
||||
},
|
||||
});
|
||||
|
||||
@@ -121,12 +124,10 @@ export const ConsumptionView = defineComponent({
|
||||
hasUncommittedCustomDraft = false;
|
||||
startPicker.setValue(minMs);
|
||||
endPicker.setValue(maxMs);
|
||||
telemetryStore.setState({
|
||||
selectedTimeRange: 'custom',
|
||||
selectConsumptionTimeRange('custom', {
|
||||
customStartMs: minMs,
|
||||
customEndMs: maxMs,
|
||||
});
|
||||
fetchTelemetry({ force: true });
|
||||
},
|
||||
},
|
||||
[createSvgIcon('check', { size: 12 }), applyCustomBtnLabel]
|
||||
@@ -868,8 +869,21 @@ export const ConsumptionView = defineComponent({
|
||||
|
||||
let latestSlice = null;
|
||||
let isDirty = false;
|
||||
let prefetchedOnCurrentVisit = false;
|
||||
|
||||
let lastRenderedUsage = '';
|
||||
let lastRenderedTuple = null;
|
||||
let cachedMonthlySeriesRef = null;
|
||||
let cachedMonthlyDisplayKey = '';
|
||||
let cachedMonthsMergedModels = null;
|
||||
let cachedAllMonthMergedModels = null;
|
||||
|
||||
function isSameRenderTuple(prev, next) {
|
||||
if (!prev || prev.length !== next.length) return false;
|
||||
for (let i = 0; i < prev.length; i++) {
|
||||
if (!Object.is(prev[i], next[i])) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将遥测状态切片同步渲染至消费统计视图的 5 个子面板。
|
||||
@@ -877,31 +891,9 @@ export const ConsumptionView = defineComponent({
|
||||
function renderConsumptionData(slice) {
|
||||
if (!slice) return;
|
||||
const cons = slice.consumption || {};
|
||||
const preset =
|
||||
slice.range !== 'custom' && cons.presets?.[slice.range]
|
||||
? cons.presets[slice.range]
|
||||
: null;
|
||||
const acct = preset?.account || cons.account || {};
|
||||
const rangeInfo = cons.selectedRange || {};
|
||||
const dateSpan = formatDateSpanBadge(rangeInfo.startMs, rangeInfo.endMs);
|
||||
const now = new Date();
|
||||
const currentMonthIdx = now.getMonth();
|
||||
const monthlyYear = cons.monthlyYear || now.getFullYear();
|
||||
const locale = i18nStore.getState().locale;
|
||||
// 额度与会话状态也会发布遥测更新,只对用量页实际展示的数据重绘。
|
||||
const signature = JSON.stringify([
|
||||
locale, slice.range, slice.customStartMs, slice.customEndMs, slice.modelDisplayMode,
|
||||
slice.showUpstreamModel, slice.orchestratorIdMode, dateSpan,
|
||||
preset?.label || rangeInfo.label, acct,
|
||||
cons.trendSeries, slice.modelBreakdown, cons.sourcesBreakdown,
|
||||
monthlyYear, currentMonthIdx, cons.monthlySeries,
|
||||
]);
|
||||
if (signature === lastRenderedUsage) return;
|
||||
drawConsumptionData(slice, { cons, preset, acct, rangeInfo, dateSpan, currentMonthIdx, monthlyYear });
|
||||
lastRenderedUsage = signature;
|
||||
}
|
||||
|
||||
function drawConsumptionData(slice, { cons, preset, acct, rangeInfo, dateSpan, currentMonthIdx, monthlyYear }) {
|
||||
// 始终在 0ms 同步顶部时间段滑块与自定义日期条显隐,给予即刻交互反馈
|
||||
timeFilterSwitch.setValue(slice.range);
|
||||
patchAttr(customRangeBar, 'hidden', slice.range !== 'custom');
|
||||
if (!hasUncommittedCustomDraft) {
|
||||
@@ -911,6 +903,45 @@ export const ConsumptionView = defineComponent({
|
||||
endPicker.setValue(draftEndMs);
|
||||
}
|
||||
|
||||
// 极少数缓存未命中时(如自定义新区间或进页瞬间抢点),跳过用旧趋势/模型跑无效半更新重绘,待几毫秒后单帧原子绘制
|
||||
if (rangeInfo.key && slice.range && rangeInfo.key !== slice.range) {
|
||||
return;
|
||||
}
|
||||
|
||||
const preset =
|
||||
slice.range !== 'custom' && cons.presets?.[slice.range]
|
||||
? cons.presets[slice.range]
|
||||
: null;
|
||||
const acct = cons.account || preset?.account || {};
|
||||
const dateSpan = formatDateSpanBadge(rangeInfo.startMs, rangeInfo.endMs);
|
||||
const now = new Date();
|
||||
const currentMonthIdx = now.getMonth();
|
||||
const monthlyYear = cons.monthlyYear || now.getFullYear();
|
||||
const locale = i18nStore.getState().locale;
|
||||
const renderTuple = [
|
||||
locale,
|
||||
slice.range,
|
||||
slice.customStartMs,
|
||||
slice.customEndMs,
|
||||
slice.modelDisplayMode,
|
||||
slice.showUpstreamModel,
|
||||
slice.orchestratorIdMode,
|
||||
dateSpan,
|
||||
preset?.label || rangeInfo.label,
|
||||
acct,
|
||||
cons.trendSeries,
|
||||
slice.modelBreakdown,
|
||||
cons.sourcesBreakdown,
|
||||
monthlyYear,
|
||||
currentMonthIdx,
|
||||
cons.monthlySeries,
|
||||
];
|
||||
if (isSameRenderTuple(lastRenderedTuple, renderTuple)) return;
|
||||
drawConsumptionData(slice, { cons, preset, acct, rangeInfo, dateSpan, currentMonthIdx, monthlyYear });
|
||||
lastRenderedTuple = renderTuple;
|
||||
}
|
||||
|
||||
function drawConsumptionData(slice, { cons, preset, acct, rangeInfo, dateSpan, currentMonthIdx, monthlyYear }) {
|
||||
// 1. 同步用量概览矩阵与顶部 4 段比例条
|
||||
patchText(dateSpanBadge, dateSpan);
|
||||
const totalTokens = Number(acct.totalTokens || 0);
|
||||
@@ -1011,14 +1042,31 @@ export const ConsumptionView = defineComponent({
|
||||
});
|
||||
|
||||
const monthlySeries = cons.monthlySeries || [];
|
||||
const allMonthMergedModels = [];
|
||||
const monthsMergedModels = Array.from({ length: 12 }, (_, idx) => {
|
||||
const merged = mergeAndSortBucketModels(monthlySeries[idx]?.models);
|
||||
for (const m of merged) {
|
||||
allMonthMergedModels.push(m);
|
||||
}
|
||||
return merged;
|
||||
});
|
||||
const monthlyDisplayKey = `${displaySettings.modelDisplayMode}|${displaySettings.showUpstreamModel ? 1 : 0}|${displaySettings.orchestratorIdMode}`;
|
||||
let monthsMergedModels;
|
||||
let allMonthMergedModels;
|
||||
if (
|
||||
cachedMonthlySeriesRef === monthlySeries &&
|
||||
cachedMonthlyDisplayKey === monthlyDisplayKey &&
|
||||
cachedMonthsMergedModels &&
|
||||
cachedAllMonthMergedModels
|
||||
) {
|
||||
monthsMergedModels = cachedMonthsMergedModels;
|
||||
allMonthMergedModels = cachedAllMonthMergedModels;
|
||||
} else {
|
||||
allMonthMergedModels = [];
|
||||
monthsMergedModels = Array.from({ length: 12 }, (_, idx) => {
|
||||
const merged = mergeAndSortBucketModels(monthlySeries[idx]?.models);
|
||||
for (const m of merged) {
|
||||
allMonthMergedModels.push(m);
|
||||
}
|
||||
return merged;
|
||||
});
|
||||
cachedMonthlySeriesRef = monthlySeries;
|
||||
cachedMonthlyDisplayKey = monthlyDisplayKey;
|
||||
cachedMonthsMergedModels = monthsMergedModels;
|
||||
cachedAllMonthMergedModels = allMonthMergedModels;
|
||||
}
|
||||
|
||||
const rawTrendSeries = cons.trendSeries || [];
|
||||
const allTrendMergedModels = [];
|
||||
@@ -1213,6 +1261,10 @@ export const ConsumptionView = defineComponent({
|
||||
}
|
||||
isDirty = false;
|
||||
renderConsumptionData(slice);
|
||||
if (!prefetchedOnCurrentVisit && Number(slice?.consumption?.revision || 0) > 0) {
|
||||
prefetchedOnCurrentVisit = true;
|
||||
void prefetchConsumptionPresets();
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
@@ -1220,6 +1272,7 @@ export const ConsumptionView = defineComponent({
|
||||
getVisibleMonitorView,
|
||||
(activeView) => {
|
||||
if (activeView !== 'consumption') {
|
||||
prefetchedOnCurrentVisit = false;
|
||||
hideBreakdownPopover();
|
||||
return;
|
||||
}
|
||||
@@ -1229,6 +1282,10 @@ export const ConsumptionView = defineComponent({
|
||||
renderConsumptionData(latestSlice);
|
||||
}
|
||||
}
|
||||
if (!prefetchedOnCurrentVisit && Number(latestSlice?.consumption?.revision || 0) > 0) {
|
||||
prefetchedOnCurrentVisit = true;
|
||||
void prefetchConsumptionPresets();
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
|
||||
@@ -2423,3 +2423,166 @@ test('v1.5 feedback settings schema: custom token combo DSL, 3-way model display
|
||||
rmSync(workerTemp, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('scope=consumption and scope=consumption-presets bypass matchesConv, >30s idle, and visual settings, match full aggregation, and invalidate on weeklyLimitMode/cache rebuild', async (t) => {
|
||||
let clockMs = Date.parse('2026-11-19T12:00:00.000Z');
|
||||
const mkStep = (idx, offsetMs, tok) => ({
|
||||
type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE',
|
||||
status: 'CORTEX_STEP_STATUS_DONE',
|
||||
metadata: {
|
||||
...(offsetMs !== null
|
||||
? {
|
||||
createdAt: new Date(clockMs - offsetMs).toISOString(),
|
||||
completedAt: new Date(clockMs - offsetMs + 1200).toISOString(),
|
||||
}
|
||||
: {}),
|
||||
sourceTrajectoryStepInfo: { stepIndex: idx },
|
||||
modelUsage: {
|
||||
model: 'MODEL_CLAUDE_4_5_SONNET',
|
||||
inputTokens: String(tok),
|
||||
cacheReadTokens: '0',
|
||||
outputTokens: '0',
|
||||
},
|
||||
},
|
||||
plannerResponse: { response: `step-${idx}` },
|
||||
});
|
||||
|
||||
const h = backendHarness({
|
||||
clock: () => clockMs,
|
||||
trajectories: {
|
||||
'conv-old': {
|
||||
trajectory: {
|
||||
steps: [
|
||||
mkStep(1, 20 * 86400_000, 1000),
|
||||
mkStep(2, null, 250),
|
||||
],
|
||||
},
|
||||
},
|
||||
'conv-recent': {
|
||||
trajectory: {
|
||||
steps: [
|
||||
mkStep(1, 4 * 86400_000, 3000),
|
||||
mkStep(2, 2 * 3600_000, 500),
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
summaries: {
|
||||
'conv-old': {
|
||||
stepCount: 2,
|
||||
lastModifiedTime: new Date(clockMs - 20 * 86400_000).toISOString(),
|
||||
status: 'CASCADE_RUN_STATUS_IDLE',
|
||||
},
|
||||
'conv-recent': {
|
||||
stepCount: 2,
|
||||
lastModifiedTime: new Date(clockMs - 2 * 3600_000).toISOString(),
|
||||
status: 'CASCADE_RUN_STATUS_RUNNING',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const initBody = JSON.parse(
|
||||
(
|
||||
await h.executeTelemetryAction({
|
||||
conversationId: 'conv-recent',
|
||||
range: 'today',
|
||||
stepDetails: 'display',
|
||||
stepRevision: '',
|
||||
})
|
||||
).body
|
||||
);
|
||||
assert.ok(Number(initBody.consumption?.revision || 0) > 0);
|
||||
const rpcCallsAfterInit = h.state.calls.length;
|
||||
|
||||
// Advance clock by 2 minutes and toggle visual-only settings
|
||||
clockMs += 120_000;
|
||||
h.executeSettingsAction({ themeAccent: 'emerald', fontScale: 'lg' });
|
||||
|
||||
// Query from a DIFFERENT conversationId (simulating sidebar vs overlay mismatch)
|
||||
const presetsRes = JSON.parse(
|
||||
(
|
||||
await h.executeTelemetryAction({
|
||||
conversationId: 'conv-different-pane',
|
||||
scope: 'consumption-presets',
|
||||
})
|
||||
).body
|
||||
);
|
||||
assert.equal(presetsRes.scope, 'consumption-presets');
|
||||
assert.equal(presetsRes.activeConversation, undefined);
|
||||
assert.equal(presetsRes.quotas, undefined);
|
||||
assert.equal(presetsRes.ranges.today.account.totalTokens, 500);
|
||||
assert.equal(presetsRes.ranges['7d'].account.totalTokens, 3500);
|
||||
assert.equal(presetsRes.ranges['30d'].account.totalTokens, 4500);
|
||||
assert.equal(presetsRes.ranges.all.account.totalTokens, 4750);
|
||||
|
||||
const liteCustom = JSON.parse(
|
||||
(
|
||||
await h.executeTelemetryAction({
|
||||
conversationId: 'conv-different-pane',
|
||||
range: 'custom',
|
||||
startMs: String(clockMs - 6 * 86400_000),
|
||||
endMs: String(clockMs - 2 * 86400_000),
|
||||
scope: 'consumption',
|
||||
})
|
||||
).body
|
||||
);
|
||||
assert.equal(liteCustom.scope, 'consumption');
|
||||
assert.equal(liteCustom.activeConversation, undefined);
|
||||
assert.equal(liteCustom.consumption.account.totalTokens, 3000);
|
||||
assert.equal(
|
||||
h.state.calls.length,
|
||||
rpcCallsAfterInit,
|
||||
'scope=consumption / presets must skip LS RPCs across pane mismatch, >30s idle, and visual settings changes'
|
||||
);
|
||||
|
||||
// Changing weeklyLimitMode DOES invalidate snapshot and trigger fresh full build
|
||||
h.executeSettingsAction({ weeklyLimitMode: 'custom_tokens' });
|
||||
await h.executeTelemetryAction({
|
||||
conversationId: 'conv-recent',
|
||||
range: '7d',
|
||||
scope: 'consumption',
|
||||
});
|
||||
const rpcCallsAfterWeeklyChange = h.state.calls.length;
|
||||
assert.ok(
|
||||
rpcCallsAfterWeeklyChange > rpcCallsAfterInit,
|
||||
'Changing weeklyLimitMode must invalidate cached fast consumption snapshot'
|
||||
);
|
||||
|
||||
// Cache rebuild also invalidates snapshot and falls back to full RPC sync
|
||||
h.executeRebuildCacheAction();
|
||||
await h.executeTelemetryAction({
|
||||
conversationId: 'conv-recent',
|
||||
range: 'all',
|
||||
scope: 'consumption',
|
||||
});
|
||||
assert.ok(
|
||||
h.state.calls.length > rpcCallsAfterWeeklyChange,
|
||||
'Cache rebuild must invalidate cached fast consumption snapshot'
|
||||
);
|
||||
|
||||
// Verify frontend selectConsumptionTimeRange sends scope=consumption without force=1
|
||||
const {
|
||||
clearConsumptionRangeCache,
|
||||
selectConsumptionTimeRange,
|
||||
stopAsyncTelemetryLoop,
|
||||
telemetryStore,
|
||||
} = await import('../src/store/telemetryStore.js');
|
||||
const prevRange = telemetryStore.getState().selectedTimeRange;
|
||||
const requestedUrls = [];
|
||||
t.after(() => {
|
||||
stopAsyncTelemetryLoop();
|
||||
clearConsumptionRangeCache();
|
||||
telemetryStore.setState({ selectedTimeRange: prevRange });
|
||||
});
|
||||
clearConsumptionRangeCache();
|
||||
t.mock.method(globalThis, 'fetch', async (url) => {
|
||||
requestedUrls.push(String(url));
|
||||
return { ok: true, json: async () => liteCustom };
|
||||
});
|
||||
await selectConsumptionTimeRange('30d');
|
||||
assert.equal(requestedUrls.length, 1);
|
||||
assert.match(requestedUrls[0], /range=30d/);
|
||||
assert.match(requestedUrls[0], /scope=consumption/);
|
||||
assert.doesNotMatch(requestedUrls[0], /force=1/);
|
||||
assert.doesNotMatch(requestedUrls[0], /fastRange=1/);
|
||||
});
|
||||
|
||||
@@ -8,7 +8,16 @@ import {
|
||||
mergeModelsByDisplayName,
|
||||
resolveDeterministicModelColor,
|
||||
} from '../src/core/formatters.js';
|
||||
import { isEquivalentTelemetry, telemetryStore } from '../src/store/telemetryStore.js';
|
||||
import {
|
||||
clearConsumptionRangeCache,
|
||||
fetchTelemetry,
|
||||
isEquivalentTelemetry,
|
||||
prefetchConsumptionPresets,
|
||||
selectConsumptionTimeRange,
|
||||
stopAsyncTelemetryLoop,
|
||||
telemetryStore,
|
||||
} from '../src/store/telemetryStore.js';
|
||||
import { createTrendAreaChart } from '../src/components/charts/TrendAreaChart.js';
|
||||
import { uiStore } from '../src/store/uiStore.js';
|
||||
import { i18nStore, setI18nLanguage } from '../src/i18n/index.js';
|
||||
import { createFourSegmentBar } from '../src/components/ui/FourSegmentBar.js';
|
||||
@@ -472,3 +481,165 @@ test('ConsumptionView: Top Models color dot + % bar, clutter-free Client Sources
|
||||
);
|
||||
assert.equal(trendTipModelRows[3].querySelector('.cons-pop-model-name')?.textContent, '其他 (3)');
|
||||
});
|
||||
|
||||
test('selectConsumptionTimeRange serves prefetched presets with 0 network calls, blocks stale 2s poll overwrites, and TrendAreaChart heatmap batches via DocumentFragment', async (t) => {
|
||||
const prevTelState = { ...telemetryStore.getState() };
|
||||
const prevDoc = globalThis.document;
|
||||
t.after(() => {
|
||||
stopAsyncTelemetryLoop();
|
||||
clearConsumptionRangeCache();
|
||||
telemetryStore.setState(prevTelState, { sync: true });
|
||||
globalThis.document = prevDoc;
|
||||
});
|
||||
|
||||
clearConsumptionRangeCache();
|
||||
const mkSlice = (key, label, totalTokens, rev = 7) => ({
|
||||
revision: rev,
|
||||
selectedRange: { key, label, startMs: 1_700_000_000_000, endMs: 1_700_086_400_000 },
|
||||
session: { totalTokens },
|
||||
account: { totalTokens, calls: 2, inputTokens: totalTokens, cacheReadTokens: 0, outputTokens: 0, costUsd: 0.1, savedCostUsd: 0, cacheHitPct: 0 },
|
||||
trendSeries: [{ index: 0, label: '11/19', fullLabel: '11月19日', tokens: totalTokens, calls: 2, costUsd: 0.1 }],
|
||||
sourcesBreakdown: [{ name: 'Antigravity App', calls: 2, totalTokens, costUsd: 0.1, models: [] }],
|
||||
modelBreakdown: [{ label: 'Claude 4.5 Sonnet', shortName: 'Sonnet 4.5', calls: 2, totalTokens, costUsd: 0.1 }],
|
||||
});
|
||||
|
||||
const baseTelemetry = {
|
||||
account: { email: 'u@example.com', status: 'signedIn' },
|
||||
settings: { language: 'zh-CN', weeklyLimitMode: 'official' },
|
||||
cloudStatus: { catalogVersion: 'v1' },
|
||||
activeConversation: { cascadeId: 'c1', recentSteps: [], agents: [] },
|
||||
consumption: {
|
||||
...mkSlice('today', '今日', 1000, 7),
|
||||
presets: { today: { label: '今日', account: { totalTokens: 1000 } } },
|
||||
monthlyYear: 2026,
|
||||
monthlySeries: [],
|
||||
},
|
||||
modelBreakdown: mkSlice('today', '今日', 1000, 7).modelBreakdown,
|
||||
};
|
||||
telemetryStore.setState({ selectedTimeRange: 'today', telemetry: baseTelemetry }, { sync: true });
|
||||
|
||||
const requestedUrls = [];
|
||||
let resolveStalePoll = null;
|
||||
t.mock.method(globalThis, 'fetch', async (url) => {
|
||||
const u = String(url);
|
||||
requestedUrls.push(u);
|
||||
if (u.includes('scope=consumption-presets')) {
|
||||
return {
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
scope: 'consumption-presets',
|
||||
usageRevision: 7,
|
||||
ranges: {
|
||||
cycle: mkSlice('cycle', '当前周期', 4000, 7),
|
||||
today: mkSlice('today', '今日', 1000, 7),
|
||||
'24h': mkSlice('24h', '近 24 小时', 1500, 7),
|
||||
'7d': mkSlice('7d', '近 7 天', 7000, 7),
|
||||
'14d': mkSlice('14d', '近 14 天', 14000, 7),
|
||||
'30d': mkSlice('30d', '近 30 天', 30000, 7),
|
||||
all: mkSlice('all', '全部时间', 90000, 7),
|
||||
},
|
||||
}),
|
||||
};
|
||||
}
|
||||
if (u.includes('scope=consumption') && u.includes('range=30d')) {
|
||||
return {
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
scope: 'consumption',
|
||||
usageRevision: 8,
|
||||
consumption: mkSlice('30d', '近 30 天', 31000, 8),
|
||||
modelBreakdown: mkSlice('30d', '近 30 天', 31000, 8).modelBreakdown,
|
||||
}),
|
||||
};
|
||||
}
|
||||
// Simulated slow 2s background poll started on 'today' that resolves later with rev=8
|
||||
return {
|
||||
ok: true,
|
||||
json: async () =>
|
||||
new Promise((resolve) => {
|
||||
resolveStalePoll = () =>
|
||||
resolve({
|
||||
...baseTelemetry,
|
||||
consumption: {
|
||||
...baseTelemetry.consumption,
|
||||
...mkSlice('today', '今日', 1200, 8),
|
||||
},
|
||||
modelBreakdown: mkSlice('today', '今日', 1200, 8).modelBreakdown,
|
||||
});
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
// 1. Entering ConsumptionView prefetches all 7 presets once
|
||||
assert.equal(await prefetchConsumptionPresets(), true);
|
||||
assert.equal(requestedUrls.length, 1);
|
||||
assert.match(requestedUrls[0], /scope=consumption-presets/);
|
||||
|
||||
// 2. Switching across presets hits rangeCache with ZERO network requests and atomic state swap
|
||||
await selectConsumptionTimeRange('7d');
|
||||
assert.equal(requestedUrls.length, 1, 'Cached preset switch must issue 0 HTTP requests');
|
||||
assert.equal(telemetryStore.getState().selectedTimeRange, '7d');
|
||||
assert.equal(telemetryStore.getState().telemetry.consumption.selectedRange.key, '7d');
|
||||
assert.equal(telemetryStore.getState().telemetry.consumption.account.totalTokens, 7000);
|
||||
|
||||
await selectConsumptionTimeRange('today');
|
||||
assert.equal(requestedUrls.length, 1);
|
||||
|
||||
// 3. Stale in-flight 2s background poll ('today', rev=8) finishes AFTER user switched to '30d' locally:
|
||||
// must NOT overwrite view back to 'today', and should trigger silent background revalidation for '30d'
|
||||
const stalePollPromise = fetchTelemetry({ force: false });
|
||||
await Promise.resolve();
|
||||
await selectConsumptionTimeRange('30d');
|
||||
assert.equal(telemetryStore.getState().telemetry.consumption.selectedRange.key, '30d');
|
||||
assert.equal(telemetryStore.getState().telemetry.consumption.account.totalTokens, 30000);
|
||||
|
||||
assert.equal(typeof resolveStalePoll, 'function');
|
||||
resolveStalePoll();
|
||||
await stalePollPromise;
|
||||
// Wait microtasks for silent background scope=consumption revalidation of 30d
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
assert.equal(telemetryStore.getState().selectedTimeRange, '30d');
|
||||
assert.equal(telemetryStore.getState().telemetry.consumption.selectedRange.key, '30d');
|
||||
assert.equal(telemetryStore.getState().telemetry.consumption.account.totalTokens, 31000);
|
||||
|
||||
// 4. TrendAreaChart >90d heatmap builds all cells cleanly via DocumentFragment when available
|
||||
const { document } = createMockDom();
|
||||
let fragUsed = false;
|
||||
document.createDocumentFragment = () => {
|
||||
fragUsed = true;
|
||||
const holder = document.createElement('div');
|
||||
holder.isFragment = true;
|
||||
return holder;
|
||||
};
|
||||
const origAppend = Object.getPrototypeOf(document.createElement('div')).appendChild;
|
||||
globalThis.document = document;
|
||||
const chart = createTrendAreaChart();
|
||||
const hmGrid = chart.el.querySelector('.trend-hm-grid');
|
||||
hmGrid.appendChild = function (node) {
|
||||
if (node?.isFragment) {
|
||||
for (const child of [...(node.children || [])]) {
|
||||
origAppend.call(this, child);
|
||||
}
|
||||
return node;
|
||||
}
|
||||
return origAppend.call(this, node);
|
||||
};
|
||||
const startDay = Date.parse('2026-06-01T00:00:00.000Z');
|
||||
const slots = Array.from({ length: 100 }, (_, i) => ({
|
||||
index: i,
|
||||
granularity: 'day',
|
||||
startMs: startDay + i * 86400_000,
|
||||
label: `D${i}`,
|
||||
fullLabel: `Day ${i}`,
|
||||
tokens: (i % 5) * 1000,
|
||||
calls: i % 5,
|
||||
costUsd: 0.05,
|
||||
}));
|
||||
chart.update(slots);
|
||||
assert.equal(fragUsed, true);
|
||||
assert.equal(
|
||||
chart.el.querySelectorAll('.trend-hm-cell').filter((c) => !c.classList.contains('is-pad')).length,
|
||||
100
|
||||
);
|
||||
chart.destroy();
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user