mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-26 17:09:28 +08:00
feat(panel): add single-line top models to client sources and fast scope=conversation session switching
This commit is contained in:
+371
-31
@@ -4411,7 +4411,7 @@ return { formatMetric, formatSpeedMetric, formatCachePct, getSpeedToneClass, get
|
||||
})();
|
||||
|
||||
// --- src/core/httpClient.js ---
|
||||
const { getWindowBridgeConfig, isWindowOverlayMode, deliverCdpBridgeResponses, callSidecarApi } = (() => {
|
||||
const { abortSidecarApiKey, getWindowBridgeConfig, isWindowOverlayMode, deliverCdpBridgeResponses, callSidecarApi } = (() => {
|
||||
/**
|
||||
* @fileoverview Async HTTP client with AbortController cancellation for stale
|
||||
* polling requests, concurrent GET deduplication, and dual-mode transport
|
||||
@@ -4422,6 +4422,15 @@ const { getWindowBridgeConfig, isWindowOverlayMode, deliverCdpBridgeResponses, c
|
||||
const inFlightGets = new Map();
|
||||
const activeControllers = new Map();
|
||||
|
||||
function abortSidecarApiKey(abortKey) {
|
||||
if (!abortKey) return;
|
||||
const prev = activeControllers.get(abortKey);
|
||||
if (prev) {
|
||||
activeControllers.delete(abortKey);
|
||||
prev.abort();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取主窗口双栖模式下注入的本地桥接配置(`port`、`token`、`bundleVersion`、`stylesCss`)。
|
||||
*
|
||||
@@ -4655,7 +4664,7 @@ async function callSidecarApi(path, { method = 'GET', body, abortKey = '', cdpTi
|
||||
}
|
||||
return promise;
|
||||
}
|
||||
return { getWindowBridgeConfig, isWindowOverlayMode, deliverCdpBridgeResponses, callSidecarApi };
|
||||
return { abortSidecarApiKey, getWindowBridgeConfig, isWindowOverlayMode, deliverCdpBridgeResponses, callSidecarApi };
|
||||
})();
|
||||
|
||||
// --- src/store/uiStore.js ---
|
||||
@@ -4691,7 +4700,7 @@ return { getViewTabs, uiStore, getVisibleMonitorView };
|
||||
})();
|
||||
|
||||
// --- src/store/telemetryStore.js ---
|
||||
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 } = (() => {
|
||||
const { extractHostRouteCascadeId, telemetryStore, clearConsumptionRangeCache, clearConversationViewCache, 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, selectConversation, 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.
|
||||
@@ -4787,9 +4796,11 @@ const telemetryStore = createReactiveStore({
|
||||
|
||||
let pollTimer = null;
|
||||
let feedbackTimer = null;
|
||||
let deferredConvSyncTimer = null;
|
||||
let activeBundleVersion = 0;
|
||||
let latestRequestSeq = 0;
|
||||
let latestConsumptionReqSeq = 0;
|
||||
let latestConversationSwitchSeq = 0;
|
||||
let activeForceCount = 0;
|
||||
let consecutivePollFailures = 0;
|
||||
let inFlightTelemetryPoll = null;
|
||||
@@ -4797,8 +4808,10 @@ let inFlightPresetsPrefetch = null;
|
||||
let lastPrefetchedUsageRevision = 0;
|
||||
let consumptionCacheScopeSig = '';
|
||||
const MAX_CONSUMPTION_RANGE_CACHE = 12;
|
||||
const MAX_CONVERSATION_VIEW_CACHE = 12;
|
||||
const CONSUMPTION_PRESET_KEYS = ['cycle', 'today', '24h', '7d', '14d', '30d', 'all'];
|
||||
const consumptionRangeCache = new Map();
|
||||
const conversationViewCache = new Map();
|
||||
let lastReceivedSteps = null;
|
||||
let loopActive = false;
|
||||
let loopIntervalMs = 2000;
|
||||
@@ -4830,6 +4843,14 @@ function clearConsumptionRangeCache() {
|
||||
inFlightPresetsPrefetch = null;
|
||||
}
|
||||
|
||||
function clearConversationViewCache() {
|
||||
conversationViewCache.clear();
|
||||
if (deferredConvSyncTimer) {
|
||||
clearTimeout(deferredConvSyncTimer);
|
||||
deferredConvSyncTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
function buildConsumptionScopeSig(payload) {
|
||||
if (!payload || typeof payload !== 'object') return '';
|
||||
const acct = payload.account || {};
|
||||
@@ -4843,10 +4864,112 @@ function syncConsumptionCacheScope(payload) {
|
||||
if (!nextSig) return;
|
||||
if (consumptionCacheScopeSig && consumptionCacheScopeSig !== nextSig) {
|
||||
clearConsumptionRangeCache();
|
||||
clearConversationViewCache();
|
||||
}
|
||||
consumptionCacheScopeSig = nextSig;
|
||||
}
|
||||
|
||||
function recordConversationViewToCache(payload) {
|
||||
const active = payload?.activeConversation;
|
||||
const cidLower = String(active?.cascadeId || '').trim().toLowerCase();
|
||||
if (!cidLower || !Array.isArray(active?.recentSteps)) return;
|
||||
const entry = {
|
||||
cascadeId: active.cascadeId,
|
||||
activeConversation: active,
|
||||
activePool: payload.quotas?.activePool || null,
|
||||
weekly: payload.quotas?.weekly || null,
|
||||
sessionConsumption: payload.consumption?.session || null,
|
||||
sessionPresets:
|
||||
payload.consumption?.sessionPresets ||
|
||||
(payload.consumption?.presets
|
||||
? Object.fromEntries(
|
||||
Object.entries(payload.consumption.presets).map(([k, v]) => [k, v?.session || null])
|
||||
)
|
||||
: null),
|
||||
stepRevision: String(payload.stepRevision || ''),
|
||||
cachedAtMs: Date.now(),
|
||||
};
|
||||
conversationViewCache.delete(cidLower);
|
||||
conversationViewCache.set(cidLower, entry);
|
||||
while (conversationViewCache.size > MAX_CONVERSATION_VIEW_CACHE) {
|
||||
conversationViewCache.delete(conversationViewCache.keys().next().value);
|
||||
}
|
||||
}
|
||||
|
||||
function resolveCachedConversationRootId(telemetry, effectiveConvId) {
|
||||
const target = String(effectiveConvId || '').trim();
|
||||
const convs = Array.isArray(telemetry?.conversations) ? telemetry.conversations : [];
|
||||
if (!target) {
|
||||
return String(convs[0]?.cascadeId || '').trim().toLowerCase();
|
||||
}
|
||||
const lower = target.toLowerCase();
|
||||
if (conversationViewCache.has(lower)) return lower;
|
||||
const matchedRoot = convs.find(
|
||||
(c) =>
|
||||
String(c?.cascadeId || '').toLowerCase() === lower ||
|
||||
(Array.isArray(c?.memberCascadeIds) &&
|
||||
c.memberCascadeIds.some((m) => String(m || '').toLowerCase() === lower))
|
||||
);
|
||||
return String(matchedRoot?.cascadeId || lower).trim().toLowerCase();
|
||||
}
|
||||
|
||||
function applyConversationSliceToTelemetry(baseTelemetry, slice) {
|
||||
if (!baseTelemetry || !slice?.activeConversation) return baseTelemetry;
|
||||
const activeCidLower = String(slice.activeConversation.cascadeId || '').toLowerCase();
|
||||
const prevQuotas = baseTelemetry.quotas || {};
|
||||
const nextQuotas =
|
||||
slice.activePool || slice.weekly
|
||||
? {
|
||||
...prevQuotas,
|
||||
...(slice.activePool ? { activePool: slice.activePool } : {}),
|
||||
...(slice.weekly ? { weekly: slice.weekly } : {}),
|
||||
}
|
||||
: prevQuotas;
|
||||
|
||||
const prevCons = baseTelemetry.consumption || {};
|
||||
let nextPresets = prevCons.presets;
|
||||
if (slice.sessionPresets && prevCons.presets && typeof prevCons.presets === 'object') {
|
||||
nextPresets = { ...prevCons.presets };
|
||||
for (const [k, sBucket] of Object.entries(slice.sessionPresets)) {
|
||||
if (sBucket && nextPresets[k]) {
|
||||
nextPresets[k] = { ...nextPresets[k], session: sBucket };
|
||||
}
|
||||
}
|
||||
}
|
||||
const nextCons =
|
||||
slice.sessionConsumption || nextPresets !== prevCons.presets
|
||||
? {
|
||||
...prevCons,
|
||||
...(slice.sessionConsumption ? { session: slice.sessionConsumption } : {}),
|
||||
...(nextPresets !== prevCons.presets ? { presets: nextPresets } : {}),
|
||||
}
|
||||
: prevCons;
|
||||
|
||||
const prevRunning = Array.isArray(baseTelemetry.runningConversations)
|
||||
? baseTelemetry.runningConversations
|
||||
: null;
|
||||
let nextRunning = prevRunning;
|
||||
if (prevRunning && prevRunning.length > 0 && activeCidLower) {
|
||||
let anyChanged = false;
|
||||
const mapped = prevRunning.map((item) => {
|
||||
const shouldSelect = String(item?.cascadeId || '').toLowerCase() === activeCidLower;
|
||||
if (Boolean(item?.isCurrentSelected) === shouldSelect) return item;
|
||||
anyChanged = true;
|
||||
return { ...item, isCurrentSelected: shouldSelect };
|
||||
});
|
||||
if (anyChanged) nextRunning = mapped;
|
||||
}
|
||||
|
||||
return {
|
||||
...baseTelemetry,
|
||||
...(slice.stepRevision ? { stepRevision: slice.stepRevision } : {}),
|
||||
activeConversation: slice.activeConversation,
|
||||
quotas: nextQuotas,
|
||||
consumption: nextCons,
|
||||
...(nextRunning ? { runningConversations: nextRunning } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function putConsumptionRangeCacheEntry(cacheKey, entry) {
|
||||
if (!cacheKey || !entry) return;
|
||||
consumptionRangeCache.delete(cacheKey);
|
||||
@@ -5660,6 +5783,7 @@ async function requestTelemetry(params, force) {
|
||||
|
||||
let resolvedPayload = reconcileIncomingTelemetrySettings(payload, reqSettingsRev);
|
||||
syncConsumptionCacheScope(resolvedPayload);
|
||||
recordConversationViewToCache(resolvedPayload);
|
||||
if (resolvedPayload?.consumption) {
|
||||
recordConsumptionSliceToCache(resolvedPayload.consumption, resolvedPayload.modelBreakdown, {
|
||||
customStartMs: reqStartMs,
|
||||
@@ -5846,6 +5970,162 @@ async function fetchConsumptionRangeSlice({
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 快速切换当前查看的会话:
|
||||
* - 命中前端 `conversationViewCache` 时,0ms 原子切换当前会话快照,并静默走轻量 `scope=conversation` 校准;
|
||||
* - 未命中缓存时直接走零 LS RPC、零全盘扫描的 `scope=conversation` 通道;
|
||||
* - 若后端提示该会话需要补读最新运行态或懒迁移字段(`needsBackgroundSync`),展示后再在后台静默补齐。
|
||||
*/
|
||||
async function selectConversation(
|
||||
nextConvId,
|
||||
{ hostRouteConversationId = undefined } = {}
|
||||
) {
|
||||
const switchSeq = ++latestConversationSwitchSeq;
|
||||
latestRequestSeq += 1;
|
||||
inFlightTelemetryPoll = null;
|
||||
abortSidecarApiKey('telemetry-poll');
|
||||
if (deferredConvSyncTimer) {
|
||||
clearTimeout(deferredConvSyncTimer);
|
||||
deferredConvSyncTimer = null;
|
||||
}
|
||||
|
||||
const targetSelectedId = String(nextConvId || '').trim();
|
||||
const prevSt = telemetryStore.getState();
|
||||
const nextHostRouteId =
|
||||
hostRouteConversationId !== undefined
|
||||
? String(hostRouteConversationId || '').trim()
|
||||
: prevSt.hostRouteConversationId;
|
||||
const effectiveConvId = targetSelectedId || nextHostRouteId || '';
|
||||
const statePatch = {
|
||||
selectedConversationId: targetSelectedId,
|
||||
...(hostRouteConversationId !== undefined ? { hostRouteConversationId: nextHostRouteId } : {}),
|
||||
};
|
||||
|
||||
const prevTelemetry = prevSt.telemetry;
|
||||
const lookupRootId = resolveCachedConversationRootId(prevTelemetry, effectiveConvId);
|
||||
const cachedEntry = lookupRootId ? conversationViewCache.get(lookupRootId) : null;
|
||||
const cachedSteps =
|
||||
cachedEntry && cachedEntry.stepRevision
|
||||
? readDisplaySteps({
|
||||
stepRevision: cachedEntry.stepRevision,
|
||||
activeConversation: cachedEntry.activeConversation,
|
||||
})
|
||||
: null;
|
||||
|
||||
if (cachedEntry && prevTelemetry) {
|
||||
const optimisticTelemetry = applyConversationSliceToTelemetry(prevTelemetry, cachedEntry);
|
||||
if (cachedSteps) {
|
||||
lastReceivedSteps = cachedSteps;
|
||||
}
|
||||
telemetryStore.setState({
|
||||
...statePatch,
|
||||
telemetry: optimisticTelemetry,
|
||||
});
|
||||
} else {
|
||||
telemetryStore.setState(statePatch);
|
||||
}
|
||||
|
||||
const current = telemetryStore.getState();
|
||||
const params = new URLSearchParams();
|
||||
if (effectiveConvId) params.set('conversationId', effectiveConvId);
|
||||
if (current.selectedTimeRange) params.set('range', current.selectedTimeRange);
|
||||
if (current.selectedTimeRange === 'custom') {
|
||||
if (current.customStartMs > 0) params.set('startMs', String(current.customStartMs));
|
||||
if (current.customEndMs > 0) params.set('endMs', String(current.customEndMs));
|
||||
}
|
||||
params.set('stepDetails', 'display');
|
||||
params.set('stepRevision', cachedSteps?.revision || '');
|
||||
params.set('scope', 'conversation');
|
||||
|
||||
const reqSettingsRev = settingsRevision;
|
||||
try {
|
||||
const payload = await callSidecarApi(`/api/telemetry?${params}`, {
|
||||
method: 'GET',
|
||||
abortKey: 'conversation-switch',
|
||||
});
|
||||
if (!payload || typeof payload !== 'object') return null;
|
||||
if (switchSeq !== latestConversationSwitchSeq) return payload;
|
||||
|
||||
const latestSt = telemetryStore.getState();
|
||||
const latestEffectiveId =
|
||||
String(latestSt.selectedConversationId || latestSt.hostRouteConversationId || '').trim();
|
||||
if (latestEffectiveId !== effectiveConvId) return payload;
|
||||
|
||||
const active = payload.activeConversation;
|
||||
if (payload.stepsUnchanged) {
|
||||
const stepsSource =
|
||||
(cachedSteps && payload.stepRevision === cachedSteps.revision ? cachedSteps : null) ||
|
||||
(lastReceivedSteps && payload.stepRevision === lastReceivedSteps.revision
|
||||
? lastReceivedSteps
|
||||
: null);
|
||||
if (!active || !stepsSource) {
|
||||
return fetchTelemetry({ force: false });
|
||||
}
|
||||
active.recentSteps = stepsSource.recentSteps;
|
||||
active.agents.forEach((agent, index) => {
|
||||
const steps = stepsSource.agentSteps[index];
|
||||
if (steps) agent.recentSteps = steps;
|
||||
});
|
||||
}
|
||||
|
||||
if (payload.scope === 'conversation' && active) {
|
||||
lastReceivedSteps = readDisplaySteps(payload) || lastReceivedSteps;
|
||||
recordConversationViewToCache(payload);
|
||||
const baseTelemetry = latestSt.telemetry;
|
||||
if (baseTelemetry) {
|
||||
const mergedTelemetry = applyConversationSliceToTelemetry(baseTelemetry, {
|
||||
activeConversation: active,
|
||||
activePool: payload.quotas?.activePool || null,
|
||||
weekly: payload.quotas?.weekly || null,
|
||||
sessionConsumption: payload.consumption?.session || null,
|
||||
sessionPresets: payload.consumption?.sessionPresets || null,
|
||||
stepRevision: payload.stepRevision || '',
|
||||
});
|
||||
if (!isEquivalentTelemetry(baseTelemetry, mergedTelemetry)) {
|
||||
telemetryStore.setState({
|
||||
telemetry: mergedTelemetry,
|
||||
minuteTick: Math.floor(Date.now() / 30000),
|
||||
});
|
||||
}
|
||||
} else {
|
||||
return fetchTelemetry({ force: false });
|
||||
}
|
||||
if (payload.needsBackgroundSync && loopActive && typeof setTimeout === 'function') {
|
||||
deferredConvSyncTimer = setTimeout(() => {
|
||||
deferredConvSyncTimer = null;
|
||||
if (switchSeq === latestConversationSwitchSeq && loopActive) {
|
||||
void fetchTelemetry({ force: false });
|
||||
}
|
||||
}, 35);
|
||||
}
|
||||
return payload;
|
||||
}
|
||||
|
||||
// 冷启动或全新未入缓存会话回退至完整载荷
|
||||
const resolvedPayload = reconcileIncomingTelemetrySettings(payload, reqSettingsRev);
|
||||
syncConsumptionCacheScope(resolvedPayload);
|
||||
lastReceivedSteps = readDisplaySteps(resolvedPayload) || lastReceivedSteps;
|
||||
recordConversationViewToCache(resolvedPayload);
|
||||
if (resolvedPayload?.consumption) {
|
||||
recordConsumptionSliceToCache(resolvedPayload.consumption, resolvedPayload.modelBreakdown, {
|
||||
customStartMs: Number(current.customStartMs || 0),
|
||||
customEndMs: Number(current.customEndMs || 0),
|
||||
});
|
||||
}
|
||||
if (!isEquivalentTelemetry(latestSt.telemetry, resolvedPayload)) {
|
||||
telemetryStore.setState({
|
||||
telemetry: resolvedPayload,
|
||||
minuteTick: Math.floor(Date.now() / 30000),
|
||||
syncState: latestSt.syncState === 'synced' ? 'synced' : 'idle',
|
||||
});
|
||||
}
|
||||
return resolvedPayload;
|
||||
} catch (err) {
|
||||
if (err?.name === 'AbortError' || switchSeq !== latestConversationSwitchSeq) return null;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换「用量统计」时间范围:
|
||||
* - 命中前端 rangeCache 时,在单次 setState 内 0ms 原子更新概览/趋势/模型/来源(若 usageRevision 一致则 0 次 HTTP 请求);
|
||||
@@ -6130,8 +6410,13 @@ async function saveSettingsPatch(patch) {
|
||||
}
|
||||
|
||||
const needsTelemetryRecompute = patchKeys.some((k) => TELEMETRY_RECOMPUTE_SETTING_KEYS.has(k));
|
||||
if (Object.prototype.hasOwnProperty.call(safePatch, 'weeklyLimitMode')) {
|
||||
if (
|
||||
Object.prototype.hasOwnProperty.call(safePatch, 'weeklyLimitMode') ||
|
||||
Object.prototype.hasOwnProperty.call(safePatch, 'weeklyTokenBudget') ||
|
||||
Object.prototype.hasOwnProperty.call(safePatch, 'weeklyCostBudget')
|
||||
) {
|
||||
clearConsumptionRangeCache();
|
||||
clearConversationViewCache();
|
||||
}
|
||||
if (needsTelemetryRecompute) {
|
||||
inFlightTelemetryPoll = null;
|
||||
@@ -6197,6 +6482,7 @@ async function resetAllSettings() {
|
||||
}
|
||||
inFlightTelemetryPoll = null;
|
||||
clearConsumptionRangeCache();
|
||||
clearConversationViewCache();
|
||||
void fetchTelemetry({ force: false });
|
||||
return res;
|
||||
}
|
||||
@@ -6204,6 +6490,7 @@ async function resetAllSettings() {
|
||||
async function rebuildTrajectoryCache() {
|
||||
const res = await callSidecarApi('/api/cache/rebuild', { method: 'POST', body: {} });
|
||||
clearConsumptionRangeCache();
|
||||
clearConversationViewCache();
|
||||
await fetchTelemetry({ force: true });
|
||||
return res;
|
||||
}
|
||||
@@ -6211,6 +6498,7 @@ async function rebuildTrajectoryCache() {
|
||||
async function triggerCloudSync() {
|
||||
const res = await callSidecarApi('/api/cloud-sync', { method: 'POST', body: {} });
|
||||
clearConsumptionRangeCache();
|
||||
clearConversationViewCache();
|
||||
await fetchTelemetry({ force: true });
|
||||
return res;
|
||||
}
|
||||
@@ -6284,6 +6572,10 @@ function stopAsyncTelemetryLoop() {
|
||||
clearTimeout(feedbackTimer);
|
||||
feedbackTimer = null;
|
||||
}
|
||||
if (deferredConvSyncTimer) {
|
||||
clearTimeout(deferredConvSyncTimer);
|
||||
deferredConvSyncTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6480,7 +6772,7 @@ function isMacHostPlatform(telemetry) {
|
||||
}
|
||||
return false;
|
||||
}
|
||||
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 };
|
||||
return { extractHostRouteCascadeId, telemetryStore, clearConsumptionRangeCache, clearConversationViewCache, 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, selectConversation, selectConsumptionTimeRange, prefetchConsumptionPresets, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveHostRouteMatch, resolveScopedConversation, isMacHostPlatform };
|
||||
})();
|
||||
|
||||
// --- src/components/ui/TopLongPillNav.js ---
|
||||
@@ -13685,8 +13977,7 @@ const LiveActivityWidget = defineComponent({
|
||||
onSelectSession(item.cascadeId);
|
||||
} else if (item.cascadeId && item.cascadeId !== 'current') {
|
||||
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
|
||||
telemetryStore.setState({ selectedConversationId: item.cascadeId });
|
||||
fetchTelemetry({ force: false });
|
||||
void selectConversation(item.cascadeId);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -20620,8 +20911,7 @@ const TopSessionHeader = defineComponent({
|
||||
options: [{ value: '', label: t('header.followLatest') }],
|
||||
onUpdateModelValue: (nextConvId) => {
|
||||
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
|
||||
telemetryStore.setState({ selectedConversationId: nextConvId });
|
||||
fetchTelemetry({ force: false });
|
||||
void selectConversation(nextConvId);
|
||||
},
|
||||
});
|
||||
|
||||
@@ -21795,8 +22085,23 @@ const ConsumptionView = defineComponent({
|
||||
return { el: segEl, refs: { segEl } };
|
||||
}
|
||||
|
||||
function createSourceTopModelItem() {
|
||||
const dotEl = h('span', { className: 'dot-swatch cons-model-dot cons-source-top-dot' });
|
||||
const nameEl = h('span', { className: 'cons-source-top-name' });
|
||||
const pctEl = h('strong', { className: 'cons-source-top-pct text-mono' });
|
||||
const itemEl = h('span', { className: 'cons-source-top-item' }, [dotEl, nameEl, pctEl]);
|
||||
return { el: itemEl, refs: { itemEl, dotEl, nameEl, pctEl } };
|
||||
}
|
||||
|
||||
function formatCompactSourceSharePct(pct) {
|
||||
const num = Number(pct || 0);
|
||||
if (!Number.isFinite(num) || num <= 0) return '0%';
|
||||
if (num >= 10) return `${Math.round(num)}%`;
|
||||
return `${num.toFixed(1)}%`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建客户端来源单行 DOM 结构(保留长尾合并分段配色进度条与右侧总调用数,悬停进度条弹出各模型明细浮层)。
|
||||
* 创建客户端来源单行 DOM 结构(保留长尾合并分段配色进度条、单行不换行的 Top 2-3 模型速览和右侧总调用数,悬停进度条或速览区弹出完整明细浮层)。
|
||||
*/
|
||||
function createSourceBreakdownRow() {
|
||||
const nameTextEl = h('span', { className: 'cons-row-title-text' });
|
||||
@@ -21806,26 +22111,39 @@ const ConsumptionView = defineComponent({
|
||||
const costEl = h('strong', { className: 'cons-row-cost text-mono' });
|
||||
const trackEl = h('div', { className: 'progress-track cons-seg-bar cons-source-model-bar' });
|
||||
const rowState = { hoverPayload: null };
|
||||
const bindPopoverHover = (targetEl) => ({
|
||||
onMouseEnter: (e) => {
|
||||
if (rowState.hoverPayload) {
|
||||
showBreakdownPopover(targetEl, rowState.hoverPayload, e?.clientX ?? null);
|
||||
}
|
||||
},
|
||||
onMouseMove: (e) => {
|
||||
if (rowState.hoverPayload && activeHoverTargetEl === targetEl) {
|
||||
positionBreakdownPopover(targetEl, e?.clientX ?? null);
|
||||
}
|
||||
},
|
||||
onMouseLeave: () => {
|
||||
if (activeHoverTargetEl === targetEl) hideBreakdownPopover();
|
||||
},
|
||||
});
|
||||
const barHitEl = h(
|
||||
'div',
|
||||
{
|
||||
className: 'cons-source-bar-hit',
|
||||
onMouseEnter: (e) => {
|
||||
if (rowState.hoverPayload) {
|
||||
showBreakdownPopover(barHitEl, rowState.hoverPayload, e?.clientX ?? null);
|
||||
}
|
||||
},
|
||||
onMouseMove: (e) => {
|
||||
if (rowState.hoverPayload && activeHoverTargetEl === barHitEl) {
|
||||
positionBreakdownPopover(barHitEl, e?.clientX ?? null);
|
||||
}
|
||||
},
|
||||
onMouseLeave: () => {
|
||||
if (activeHoverTargetEl === barHitEl) hideBreakdownPopover();
|
||||
},
|
||||
},
|
||||
[trackEl]
|
||||
);
|
||||
const barHandlers = bindPopoverHover(barHitEl);
|
||||
barHitEl.addEventListener('mouseenter', barHandlers.onMouseEnter);
|
||||
barHitEl.addEventListener('mousemove', barHandlers.onMouseMove);
|
||||
barHitEl.addEventListener('mouseleave', barHandlers.onMouseLeave);
|
||||
|
||||
const topModelsEl = h('div', { className: 'cons-source-top-models', hidden: true });
|
||||
const topHandlers = bindPopoverHover(topModelsEl);
|
||||
topModelsEl.addEventListener('mouseenter', topHandlers.onMouseEnter);
|
||||
topModelsEl.addEventListener('mousemove', topHandlers.onMouseMove);
|
||||
topModelsEl.addEventListener('mouseleave', topHandlers.onMouseLeave);
|
||||
|
||||
const callsLbl = h('span', { text: t('cons.footCalls') });
|
||||
const callsVal = h('strong', { className: 'text-mono' });
|
||||
|
||||
@@ -21840,6 +22158,7 @@ const ConsumptionView = defineComponent({
|
||||
]),
|
||||
barHitEl,
|
||||
h('div', { className: 'cons-item-foot cons-source-foot' }, [
|
||||
topModelsEl,
|
||||
h('span', { className: 'legend-left cons-calls-stat' }, [
|
||||
callsLbl,
|
||||
callsVal,
|
||||
@@ -21857,6 +22176,7 @@ const ConsumptionView = defineComponent({
|
||||
costEl,
|
||||
barHitEl,
|
||||
trackEl,
|
||||
topModelsEl,
|
||||
callsLbl,
|
||||
callsVal,
|
||||
rowState,
|
||||
@@ -21920,6 +22240,28 @@ const ConsumptionView = defineComponent({
|
||||
},
|
||||
});
|
||||
|
||||
const topModels = partitioned
|
||||
.filter((seg) => !seg.isOther)
|
||||
.slice(0, 3)
|
||||
.map((seg) => ({
|
||||
key: seg.key,
|
||||
label: seg.label,
|
||||
pctText: formatCompactSourceSharePct(seg.pct),
|
||||
color: seg.color,
|
||||
}));
|
||||
patchAttr(refs.topModelsEl, 'hidden', topModels.length === 0);
|
||||
patchKeyedList(refs.topModelsEl, topModels, {
|
||||
keyFn: (m) => m.key,
|
||||
sigFn: (m) => `${m.key}:${m.label}:${m.pctText}:${m.color}`,
|
||||
createRow: createSourceTopModelItem,
|
||||
updateRow: (mRefs, m) => {
|
||||
patchStyleVar(mRefs.dotEl, '--dot-color', m.color);
|
||||
patchText(mRefs.nameEl, m.label);
|
||||
patchText(mRefs.pctEl, m.pctText);
|
||||
patchAttr(mRefs.itemEl, 'title', `${m.label} (${m.pctText})`);
|
||||
},
|
||||
});
|
||||
|
||||
refs.rowState.hoverPayload =
|
||||
total > 0 || callsCount > 0
|
||||
? {
|
||||
@@ -25251,8 +25593,7 @@ function mountWindowOverlay() {
|
||||
selectedAgentScope: 'all',
|
||||
ctxInspectorAgentId: 'auto',
|
||||
});
|
||||
telemetryStore.setState({ selectedConversationId: cascadeId });
|
||||
void fetchTelemetry({ force: false });
|
||||
void selectConversation(cascadeId);
|
||||
setMultiOpen(false);
|
||||
setPopoverOpen(true);
|
||||
}
|
||||
@@ -26732,13 +27073,12 @@ function mountWindowOverlay() {
|
||||
if (currentRouteId === lastObservedRouteId) return;
|
||||
lastObservedRouteId = currentRouteId;
|
||||
const st = telemetryStore.getState();
|
||||
const patch = { hostRouteConversationId: currentRouteId };
|
||||
if (currentRouteId && st.selectedConversationId && st.selectedConversationId !== currentRouteId) {
|
||||
patch.selectedConversationId = '';
|
||||
}
|
||||
const nextSelectedId =
|
||||
currentRouteId && st.selectedConversationId && st.selectedConversationId !== currentRouteId
|
||||
? ''
|
||||
: st.selectedConversationId;
|
||||
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
|
||||
telemetryStore.setState(patch);
|
||||
void fetchTelemetry({ force: false });
|
||||
void selectConversation(nextSelectedId, { hostRouteConversationId: currentRouteId });
|
||||
}
|
||||
|
||||
const onDocMouseDown = (e) => {
|
||||
|
||||
@@ -198,7 +198,11 @@ export async function executeTelemetryAction(data, { onRestart = null } = {}) {
|
||||
}
|
||||
const rawScope = String(data?.scope || '').trim();
|
||||
const scope =
|
||||
rawScope === 'consumption' || rawScope === 'consumption-presets' ? rawScope : '';
|
||||
rawScope === 'consumption' ||
|
||||
rawScope === 'consumption-presets' ||
|
||||
rawScope === 'conversation'
|
||||
? rawScope
|
||||
: '';
|
||||
const filterOpts = {
|
||||
range: data?.range || 'all',
|
||||
startMs: sanitizePositiveFiniteMs(data?.startMs),
|
||||
|
||||
@@ -99,13 +99,20 @@ function discoverLocalConversationFiles() {
|
||||
|
||||
const annotationDirs = Array.isArray(ANNOTATION_DIRS) ? ANNOTATION_DIRS : [];
|
||||
if (annotationDirs.length > 0 && map.size > 0) {
|
||||
for (const [cascadeId, fileList] of map.entries()) {
|
||||
for (const annDir of annotationDirs) {
|
||||
if (!annDir) continue;
|
||||
const pbtxtPath = join(annDir, `${cascadeId}.pbtxt`);
|
||||
if (existsSync(pbtxtPath)) {
|
||||
fileList.push(pbtxtPath);
|
||||
for (const annDir of annotationDirs) {
|
||||
if (!annDir || !existsSync(annDir)) continue;
|
||||
try {
|
||||
for (const rawName of readdirSync(annDir)) {
|
||||
const name = String(rawName || '');
|
||||
if (!name.toLowerCase().endsWith('.pbtxt')) continue;
|
||||
const cascadeId = name.slice(0, -6).toLowerCase();
|
||||
const fileList = map.get(cascadeId);
|
||||
if (fileList) {
|
||||
fileList.push(join(annDir, name));
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 忽略注释目录读取异常
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -840,11 +840,158 @@ function sameUsageEntries(previous, current) {
|
||||
return previous.length === current.length && current.every((entry, index) => {
|
||||
const before = previous[index];
|
||||
return entry.steps === before.steps && entry.cascadeId === before.cascadeId &&
|
||||
entry.appSource === before.appSource && entry.accountName === before.accountName &&
|
||||
entry.isCurrentConv === before.isCurrentConv;
|
||||
entry.appSource === before.appSource && entry.accountName === before.accountName;
|
||||
});
|
||||
}
|
||||
|
||||
function buildFamilySig(familySet) {
|
||||
if (!(familySet instanceof Set) || familySet.size === 0) return '';
|
||||
return Array.from(familySet).sort().join(',');
|
||||
}
|
||||
|
||||
function computeFamilySessionBuckets({
|
||||
entries,
|
||||
familySet,
|
||||
presetKeys = [],
|
||||
presetWindows = {},
|
||||
selectedWindow,
|
||||
isCustomWeeklyMode = false,
|
||||
poolCycleBuckets = new Map(),
|
||||
normalizedQuotaAccount = '',
|
||||
nowMs = Date.now(),
|
||||
resolveStepModel,
|
||||
weekStartMs = 0,
|
||||
}) {
|
||||
const sessionBuckets = {};
|
||||
for (const k of presetKeys) {
|
||||
sessionBuckets[k] = createUsageBucket();
|
||||
}
|
||||
const selectedSessionBucket =
|
||||
(selectedWindow?.key && sessionBuckets[selectedWindow.key]) || createUsageBucket();
|
||||
if (!(familySet instanceof Set) || familySet.size === 0) {
|
||||
const sessionPresets = {};
|
||||
for (const k of presetKeys) {
|
||||
sessionPresets[k] = finalizeUsageBucket(sessionBuckets[k]);
|
||||
}
|
||||
return {
|
||||
finalizedSelectedSession: finalizeUsageBucket(selectedSessionBucket),
|
||||
sessionPresets,
|
||||
};
|
||||
}
|
||||
|
||||
const hasDedicatedCarbonPool = poolCycleBuckets.has('Carbon');
|
||||
const hasDedicatedArgonPool = poolCycleBuckets.has('Argon');
|
||||
const poolByModel = new Map();
|
||||
const effectiveWeekStartMs = weekStartMs || presetWindows.week?.startMs || 0;
|
||||
const cycleStartFallbackMs =
|
||||
presetWindows.cycle?.startMs ??
|
||||
(selectedWindow?.key === 'cycle' ? selectedWindow.startMs : 0);
|
||||
|
||||
for (const entry of entries || []) {
|
||||
const cidLower = String(entry?.cascadeId || '').toLowerCase();
|
||||
if (!cidLower || !familySet.has(cidLower)) continue;
|
||||
const entryOwner = normalizeOwnerAccount(entry.accountName);
|
||||
for (const st of entry.steps || []) {
|
||||
if (!st || typeof st !== 'object') continue;
|
||||
const stepOwner = normalizeOwnerAccount(st.accountName) || entryOwner;
|
||||
const includeInQuotaPools =
|
||||
normalizedQuotaAccount === null
|
||||
? false
|
||||
: normalizedQuotaAccount === ''
|
||||
? true
|
||||
: stepOwner === normalizedQuotaAccount;
|
||||
const mInfo = resolveStepModel(st);
|
||||
const inTok = safeTok(st.inputTokens);
|
||||
const cacheTok = safeTok(st.cacheReadTokens);
|
||||
const outTok = safeTok(st.outputTokens);
|
||||
const thinkTok = safeTok(st.thinkingTokens);
|
||||
const respTok =
|
||||
st.responseTokens !== undefined && st.responseTokens !== null
|
||||
? safeTok(st.responseTokens)
|
||||
: Math.max(0, outTok - thinkTok);
|
||||
const stepTotalTokens = inTok + cacheTok + outTok;
|
||||
const stepCost = computeStepCost(st, mInfo.pricing);
|
||||
const resolvedCost = Number.isFinite(stepCost) ? stepCost : 0;
|
||||
const unpriced = stepCost === null ? 1 : 0;
|
||||
const tMs = Number(st.createdAtMs) > 0 ? Number(st.createdAtMs) : 0;
|
||||
const savedCost = mInfo.pricing
|
||||
? (cacheTok / 1_000_000) * Math.max(0, mInfo.pricing.input - mInfo.pricing.cache)
|
||||
: 0;
|
||||
const stepUsage = {
|
||||
inTok,
|
||||
cacheTok,
|
||||
outTok,
|
||||
thinkTok,
|
||||
respTok,
|
||||
stepTotalTokens,
|
||||
resolvedCost,
|
||||
savedCost,
|
||||
unpriced,
|
||||
};
|
||||
|
||||
const poolBucketEntry =
|
||||
poolCycleBuckets.size > 0
|
||||
? resolvePoolBucketForStep(
|
||||
st,
|
||||
mInfo,
|
||||
poolCycleBuckets,
|
||||
poolByModel,
|
||||
hasDedicatedCarbonPool,
|
||||
hasDedicatedArgonPool
|
||||
)
|
||||
: null;
|
||||
|
||||
let inCurrentCycle = false;
|
||||
if (tMs > 0 && tMs <= nowMs) {
|
||||
if (isCustomWeeklyMode) {
|
||||
inCurrentCycle = tMs >= effectiveWeekStartMs;
|
||||
} else if (poolCycleBuckets.size > 0) {
|
||||
const effCycleStartMs = poolBucketEntry
|
||||
? poolBucketEntry.startWkMs
|
||||
: cycleStartFallbackMs;
|
||||
inCurrentCycle = includeInQuotaPools && tMs >= effCycleStartMs;
|
||||
} else {
|
||||
inCurrentCycle = includeInQuotaPools && tMs >= cycleStartFallbackMs;
|
||||
}
|
||||
}
|
||||
|
||||
for (const k of presetKeys) {
|
||||
const w = presetWindows[k];
|
||||
const matchesPreset =
|
||||
k === 'all'
|
||||
? true
|
||||
: k === 'cycle'
|
||||
? inCurrentCycle
|
||||
: tMs > 0 && tMs >= w.startMs && tMs <= w.endMs;
|
||||
if (matchesPreset) {
|
||||
accumulateStepIntoBucket(sessionBuckets[k], stepUsage, entry.cascadeId);
|
||||
}
|
||||
}
|
||||
|
||||
if (selectedWindow && (!sessionBuckets[selectedWindow.key] || selectedWindow.key === 'custom')) {
|
||||
const inSelectedWindow =
|
||||
selectedWindow.key === 'all'
|
||||
? true
|
||||
: selectedWindow.key === 'cycle'
|
||||
? inCurrentCycle
|
||||
: tMs > 0 && tMs >= selectedWindow.startMs && tMs <= selectedWindow.endMs;
|
||||
if (inSelectedWindow) {
|
||||
accumulateStepIntoBucket(selectedSessionBucket, stepUsage, entry.cascadeId);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const sessionPresets = {};
|
||||
for (const k of presetKeys) {
|
||||
sessionPresets[k] = finalizeUsageBucket(sessionBuckets[k]);
|
||||
}
|
||||
return {
|
||||
finalizedSelectedSession: finalizeUsageBucket(selectedSessionBucket),
|
||||
sessionPresets,
|
||||
};
|
||||
}
|
||||
|
||||
function sortedUsageTimestamps(entries) {
|
||||
const dates = new Float64Array(entries.reduce((sum, entry) => sum + entry.steps.length, 0));
|
||||
let count = 0;
|
||||
@@ -971,6 +1118,7 @@ export function aggregateMultiWindowUsage({
|
||||
|
||||
const perSourceStats = new Map();
|
||||
const allEntriesToAggregate = collectUsageEntriesToAggregate(familySet);
|
||||
const familySig = buildFamilySig(familySet);
|
||||
|
||||
const timeZone = modelInputs ? new Intl.DateTimeFormat().resolvedOptions().timeZone : '';
|
||||
const quotaWindows = Array.from(poolCycleBuckets, ([key, { start5hMs, startWkMs }]) => [
|
||||
@@ -1002,12 +1150,44 @@ export function aggregateMultiWindowUsage({
|
||||
) {
|
||||
snapshot.ranges.delete(selectedWindow.key);
|
||||
snapshot.ranges.set(selectedWindow.key, previous);
|
||||
if (previous.familySig === familySig) {
|
||||
return {
|
||||
...previous.result,
|
||||
usageRevision: snapshot.revision,
|
||||
selectedWindow: effectivePrevWin,
|
||||
trendStartMs: trend.start,
|
||||
trendEndMs: trend.end,
|
||||
};
|
||||
}
|
||||
const { finalizedSelectedSession: nextSelSession, sessionPresets } =
|
||||
computeFamilySessionBuckets({
|
||||
entries: allEntriesToAggregate,
|
||||
familySet,
|
||||
presetKeys,
|
||||
presetWindows,
|
||||
selectedWindow,
|
||||
isCustomWeeklyMode,
|
||||
poolCycleBuckets,
|
||||
normalizedQuotaAccount,
|
||||
nowMs,
|
||||
resolveStepModel,
|
||||
});
|
||||
const prevPresets = previous.result.finalizedPresets || {};
|
||||
const nextFinalizedPresets = {};
|
||||
for (const k of presetKeys) {
|
||||
nextFinalizedPresets[k] = {
|
||||
...(prevPresets[k] || { label: presetWindows[k].label }),
|
||||
session: sessionPresets[k],
|
||||
};
|
||||
}
|
||||
return {
|
||||
...previous.result,
|
||||
usageRevision: snapshot.revision,
|
||||
selectedWindow: effectivePrevWin,
|
||||
trendStartMs: trend.start,
|
||||
trendEndMs: trend.end,
|
||||
finalizedSelectedSession: nextSelSession,
|
||||
finalizedPresets: nextFinalizedPresets,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1324,6 +1504,7 @@ export function aggregateMultiWindowUsage({
|
||||
const { ranges } = lastUsageSnapshot;
|
||||
ranges.delete(selectedWindow.key);
|
||||
ranges.set(selectedWindow.key, {
|
||||
familySig,
|
||||
windows,
|
||||
selectedWindow,
|
||||
effectiveSelectedWindow,
|
||||
@@ -1387,6 +1568,7 @@ export function aggregateSelectedWindowUsage({
|
||||
const allEntriesToAggregate = Array.isArray(precollectedEntries)
|
||||
? precollectedEntries
|
||||
: collectUsageEntriesToAggregate(familySet);
|
||||
const familySig = buildFamilySig(familySet);
|
||||
const currentYear = new Date(nowMs).getFullYear();
|
||||
const timeZone = modelInputs ? new Intl.DateTimeFormat().resolvedOptions().timeZone : '';
|
||||
|
||||
@@ -1426,12 +1608,28 @@ export function aggregateSelectedWindowUsage({
|
||||
)
|
||||
) {
|
||||
const res = candidate.result;
|
||||
const resolvedSelectedSession =
|
||||
candidate.familySig === familySig
|
||||
? res.finalizedSelectedSession
|
||||
: computeFamilySessionBuckets({
|
||||
entries: allEntriesToAggregate,
|
||||
familySet,
|
||||
presetKeys: [],
|
||||
presetWindows: {},
|
||||
selectedWindow,
|
||||
isCustomWeeklyMode,
|
||||
poolCycleBuckets,
|
||||
normalizedQuotaAccount,
|
||||
nowMs,
|
||||
resolveStepModel,
|
||||
weekStartMs,
|
||||
}).finalizedSelectedSession;
|
||||
return {
|
||||
usageRevision: snapshot.revision,
|
||||
selectedWindow: effectivePrevWin,
|
||||
trendStartMs: trend.start,
|
||||
trendEndMs: trend.end,
|
||||
finalizedSelectedSession: res.finalizedSelectedSession,
|
||||
finalizedSelectedSession: resolvedSelectedSession,
|
||||
finalizedSelectedAccount: res.finalizedSelectedAccount,
|
||||
trendSeries: res.trendSeries,
|
||||
sourcesBreakdown: res.sourcesBreakdown,
|
||||
@@ -1658,6 +1856,7 @@ export function aggregateSelectedWindowUsage({
|
||||
snapshot.selectedRanges ??= new Map();
|
||||
snapshot.selectedRanges.delete(selectedWindow.key);
|
||||
snapshot.selectedRanges.set(selectedWindow.key, {
|
||||
familySig,
|
||||
selectedWindow,
|
||||
effectiveSelectedWindow,
|
||||
trend,
|
||||
@@ -1673,6 +1872,73 @@ export function aggregateSelectedWindowUsage({
|
||||
return sliceResult;
|
||||
}
|
||||
|
||||
/**
|
||||
* 轻量级单会话家族用量汇总(专为 `scope=conversation` 瞬切服务):
|
||||
* 仅遍历当前选中根会话及其子代理步骤,不触碰其余历史会话与全局账户聚合缓存。
|
||||
*/
|
||||
export function aggregateSessionUsageForFamily({
|
||||
filterOpts = {},
|
||||
cycleAnchors = {},
|
||||
isCustomWeeklyMode = false,
|
||||
currentAccountName = '',
|
||||
activeCascadeId = null,
|
||||
activeFamilyCascadeIds = null,
|
||||
resolveStepModel,
|
||||
quotaPoolsMap = null,
|
||||
}) {
|
||||
const rawFamilyIds =
|
||||
activeFamilyCascadeIds instanceof Set
|
||||
? Array.from(activeFamilyCascadeIds)
|
||||
: activeCascadeId
|
||||
? [activeCascadeId]
|
||||
: [];
|
||||
const familySet = new Set(rawFamilyIds.map((id) => String(id || '').toLowerCase()).filter(Boolean));
|
||||
const nowMs = Date.now();
|
||||
const selectedWindow = resolveTimeWindow(
|
||||
filterOpts.range || 'all',
|
||||
filterOpts.startMs,
|
||||
filterOpts.endMs,
|
||||
nowMs,
|
||||
cycleAnchors,
|
||||
isCustomWeeklyMode
|
||||
);
|
||||
const presetKeys = ['all', 'cycle', '5h', 'today', '24h', 'week', '7d', '14d', '30d'];
|
||||
const presetWindows = {};
|
||||
for (const k of presetKeys) {
|
||||
presetWindows[k] = resolveTimeWindow(k, 0, 0, nowMs, cycleAnchors, isCustomWeeklyMode);
|
||||
}
|
||||
const poolCycleBuckets = buildQuotaPoolCycleMap(quotaPoolsMap, nowMs);
|
||||
const normalizedQuotaAccount =
|
||||
currentAccountName === null ? null : normalizeOwnerAccount(currentAccountName);
|
||||
|
||||
const familyEntries = [];
|
||||
for (const [cid, entry] of listCachedTrajectoryEntries()) {
|
||||
if (!entry || !Array.isArray(entry.steps) || entry.steps.length === 0) continue;
|
||||
const cidLower = String(cid || '').toLowerCase();
|
||||
if (!familySet.has(cidLower)) continue;
|
||||
familyEntries.push({
|
||||
cascadeId: cid,
|
||||
appSource: entry.appSource || 'standalone',
|
||||
accountName: entry.accountName || '',
|
||||
steps: entry.steps,
|
||||
isCurrentConv: true,
|
||||
});
|
||||
}
|
||||
|
||||
return computeFamilySessionBuckets({
|
||||
entries: familyEntries,
|
||||
familySet,
|
||||
presetKeys,
|
||||
presetWindows,
|
||||
selectedWindow,
|
||||
isCustomWeeklyMode,
|
||||
poolCycleBuckets,
|
||||
normalizedQuotaAccount,
|
||||
nowMs,
|
||||
resolveStepModel,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量预聚合全部 7 个用量页预设区间(复用同一次条目收集与时间剪枝),供前端进入「用量统计」时静默预取实现 0ms 瞬切。
|
||||
*/
|
||||
|
||||
@@ -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=1795093491990">
|
||||
<link rel="stylesheet" href="/styles.css?v=1795097331072">
|
||||
<script src="/preload.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app-root"></div>
|
||||
<script src="/app.js?v=1795093491990"></script>
|
||||
<script src="/app.js?v=1795097331072"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
formatConversationMeta,
|
||||
normalizeClientUpdateMode,
|
||||
resolveHostRouteMatch,
|
||||
selectConversation,
|
||||
telemetryStore,
|
||||
triggerPluginUpdate,
|
||||
} from '../../store/telemetryStore.js';
|
||||
@@ -33,8 +34,7 @@ export const TopSessionHeader = defineComponent({
|
||||
options: [{ value: '', label: t('header.followLatest') }],
|
||||
onUpdateModelValue: (nextConvId) => {
|
||||
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
|
||||
telemetryStore.setState({ selectedConversationId: nextConvId });
|
||||
fetchTelemetry({ force: false });
|
||||
void selectConversation(nextConvId);
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -52,6 +52,7 @@ import {
|
||||
normalizeClientUpdateMode,
|
||||
normalizeClientWindowMountMode,
|
||||
resolveScopedConversation,
|
||||
selectConversation,
|
||||
startAsyncTelemetryLoop,
|
||||
stopAsyncTelemetryLoop,
|
||||
telemetryStore,
|
||||
@@ -1086,8 +1087,7 @@ export function mountWindowOverlay() {
|
||||
selectedAgentScope: 'all',
|
||||
ctxInspectorAgentId: 'auto',
|
||||
});
|
||||
telemetryStore.setState({ selectedConversationId: cascadeId });
|
||||
void fetchTelemetry({ force: false });
|
||||
void selectConversation(cascadeId);
|
||||
setMultiOpen(false);
|
||||
setPopoverOpen(true);
|
||||
}
|
||||
@@ -2567,13 +2567,12 @@ export function mountWindowOverlay() {
|
||||
if (currentRouteId === lastObservedRouteId) return;
|
||||
lastObservedRouteId = currentRouteId;
|
||||
const st = telemetryStore.getState();
|
||||
const patch = { hostRouteConversationId: currentRouteId };
|
||||
if (currentRouteId && st.selectedConversationId && st.selectedConversationId !== currentRouteId) {
|
||||
patch.selectedConversationId = '';
|
||||
}
|
||||
const nextSelectedId =
|
||||
currentRouteId && st.selectedConversationId && st.selectedConversationId !== currentRouteId
|
||||
? ''
|
||||
: st.selectedConversationId;
|
||||
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
|
||||
telemetryStore.setState(patch);
|
||||
void fetchTelemetry({ force: false });
|
||||
void selectConversation(nextSelectedId, { hostRouteConversationId: currentRouteId });
|
||||
}
|
||||
|
||||
const onDocMouseDown = (e) => {
|
||||
|
||||
@@ -25,8 +25,8 @@ import { createSvgIcon } from '../../icons/SvgIcon.js';
|
||||
import { getEffectiveLocale, t } from '../../i18n/index.js';
|
||||
import {
|
||||
extractHostRouteCascadeId,
|
||||
fetchTelemetry,
|
||||
resolveScopedConversation,
|
||||
selectConversation,
|
||||
telemetryStore,
|
||||
} from '../../store/telemetryStore.js';
|
||||
import { uiStore } from '../../store/uiStore.js';
|
||||
@@ -499,8 +499,7 @@ export const LiveActivityWidget = defineComponent({
|
||||
onSelectSession(item.cascadeId);
|
||||
} else if (item.cascadeId && item.cascadeId !== 'current') {
|
||||
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
|
||||
telemetryStore.setState({ selectedConversationId: item.cascadeId });
|
||||
fetchTelemetry({ force: false });
|
||||
void selectConversation(item.cascadeId);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@@ -9,6 +9,15 @@ import { readInjectedWindowBridge } from '../../shared/window-bridge-protocol.mj
|
||||
const inFlightGets = new Map();
|
||||
const activeControllers = new Map();
|
||||
|
||||
export function abortSidecarApiKey(abortKey) {
|
||||
if (!abortKey) return;
|
||||
const prev = activeControllers.get(abortKey);
|
||||
if (prev) {
|
||||
activeControllers.delete(abortKey);
|
||||
prev.abort();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取主窗口双栖模式下注入的本地桥接配置(`port`、`token`、`bundleVersion`、`stylesCss`)。
|
||||
*
|
||||
|
||||
@@ -4,7 +4,12 @@
|
||||
*/
|
||||
|
||||
import { createReactiveStore } from '../core/reactive.js';
|
||||
import { callSidecarApi, getWindowBridgeConfig, isWindowOverlayMode } from '../core/httpClient.js';
|
||||
import {
|
||||
abortSidecarApiKey,
|
||||
callSidecarApi,
|
||||
getWindowBridgeConfig,
|
||||
isWindowOverlayMode,
|
||||
} from '../core/httpClient.js';
|
||||
import {
|
||||
formatAgentBadgeText,
|
||||
formatAgentLabel,
|
||||
@@ -139,9 +144,11 @@ export const telemetryStore = createReactiveStore({
|
||||
|
||||
let pollTimer = null;
|
||||
let feedbackTimer = null;
|
||||
let deferredConvSyncTimer = null;
|
||||
let activeBundleVersion = 0;
|
||||
let latestRequestSeq = 0;
|
||||
let latestConsumptionReqSeq = 0;
|
||||
let latestConversationSwitchSeq = 0;
|
||||
let activeForceCount = 0;
|
||||
let consecutivePollFailures = 0;
|
||||
let inFlightTelemetryPoll = null;
|
||||
@@ -149,8 +156,10 @@ let inFlightPresetsPrefetch = null;
|
||||
let lastPrefetchedUsageRevision = 0;
|
||||
let consumptionCacheScopeSig = '';
|
||||
const MAX_CONSUMPTION_RANGE_CACHE = 12;
|
||||
const MAX_CONVERSATION_VIEW_CACHE = 12;
|
||||
const CONSUMPTION_PRESET_KEYS = ['cycle', 'today', '24h', '7d', '14d', '30d', 'all'];
|
||||
const consumptionRangeCache = new Map();
|
||||
const conversationViewCache = new Map();
|
||||
let lastReceivedSteps = null;
|
||||
let loopActive = false;
|
||||
let loopIntervalMs = 2000;
|
||||
@@ -182,6 +191,14 @@ export function clearConsumptionRangeCache() {
|
||||
inFlightPresetsPrefetch = null;
|
||||
}
|
||||
|
||||
export function clearConversationViewCache() {
|
||||
conversationViewCache.clear();
|
||||
if (deferredConvSyncTimer) {
|
||||
clearTimeout(deferredConvSyncTimer);
|
||||
deferredConvSyncTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
function buildConsumptionScopeSig(payload) {
|
||||
if (!payload || typeof payload !== 'object') return '';
|
||||
const acct = payload.account || {};
|
||||
@@ -195,10 +212,112 @@ function syncConsumptionCacheScope(payload) {
|
||||
if (!nextSig) return;
|
||||
if (consumptionCacheScopeSig && consumptionCacheScopeSig !== nextSig) {
|
||||
clearConsumptionRangeCache();
|
||||
clearConversationViewCache();
|
||||
}
|
||||
consumptionCacheScopeSig = nextSig;
|
||||
}
|
||||
|
||||
function recordConversationViewToCache(payload) {
|
||||
const active = payload?.activeConversation;
|
||||
const cidLower = String(active?.cascadeId || '').trim().toLowerCase();
|
||||
if (!cidLower || !Array.isArray(active?.recentSteps)) return;
|
||||
const entry = {
|
||||
cascadeId: active.cascadeId,
|
||||
activeConversation: active,
|
||||
activePool: payload.quotas?.activePool || null,
|
||||
weekly: payload.quotas?.weekly || null,
|
||||
sessionConsumption: payload.consumption?.session || null,
|
||||
sessionPresets:
|
||||
payload.consumption?.sessionPresets ||
|
||||
(payload.consumption?.presets
|
||||
? Object.fromEntries(
|
||||
Object.entries(payload.consumption.presets).map(([k, v]) => [k, v?.session || null])
|
||||
)
|
||||
: null),
|
||||
stepRevision: String(payload.stepRevision || ''),
|
||||
cachedAtMs: Date.now(),
|
||||
};
|
||||
conversationViewCache.delete(cidLower);
|
||||
conversationViewCache.set(cidLower, entry);
|
||||
while (conversationViewCache.size > MAX_CONVERSATION_VIEW_CACHE) {
|
||||
conversationViewCache.delete(conversationViewCache.keys().next().value);
|
||||
}
|
||||
}
|
||||
|
||||
function resolveCachedConversationRootId(telemetry, effectiveConvId) {
|
||||
const target = String(effectiveConvId || '').trim();
|
||||
const convs = Array.isArray(telemetry?.conversations) ? telemetry.conversations : [];
|
||||
if (!target) {
|
||||
return String(convs[0]?.cascadeId || '').trim().toLowerCase();
|
||||
}
|
||||
const lower = target.toLowerCase();
|
||||
if (conversationViewCache.has(lower)) return lower;
|
||||
const matchedRoot = convs.find(
|
||||
(c) =>
|
||||
String(c?.cascadeId || '').toLowerCase() === lower ||
|
||||
(Array.isArray(c?.memberCascadeIds) &&
|
||||
c.memberCascadeIds.some((m) => String(m || '').toLowerCase() === lower))
|
||||
);
|
||||
return String(matchedRoot?.cascadeId || lower).trim().toLowerCase();
|
||||
}
|
||||
|
||||
function applyConversationSliceToTelemetry(baseTelemetry, slice) {
|
||||
if (!baseTelemetry || !slice?.activeConversation) return baseTelemetry;
|
||||
const activeCidLower = String(slice.activeConversation.cascadeId || '').toLowerCase();
|
||||
const prevQuotas = baseTelemetry.quotas || {};
|
||||
const nextQuotas =
|
||||
slice.activePool || slice.weekly
|
||||
? {
|
||||
...prevQuotas,
|
||||
...(slice.activePool ? { activePool: slice.activePool } : {}),
|
||||
...(slice.weekly ? { weekly: slice.weekly } : {}),
|
||||
}
|
||||
: prevQuotas;
|
||||
|
||||
const prevCons = baseTelemetry.consumption || {};
|
||||
let nextPresets = prevCons.presets;
|
||||
if (slice.sessionPresets && prevCons.presets && typeof prevCons.presets === 'object') {
|
||||
nextPresets = { ...prevCons.presets };
|
||||
for (const [k, sBucket] of Object.entries(slice.sessionPresets)) {
|
||||
if (sBucket && nextPresets[k]) {
|
||||
nextPresets[k] = { ...nextPresets[k], session: sBucket };
|
||||
}
|
||||
}
|
||||
}
|
||||
const nextCons =
|
||||
slice.sessionConsumption || nextPresets !== prevCons.presets
|
||||
? {
|
||||
...prevCons,
|
||||
...(slice.sessionConsumption ? { session: slice.sessionConsumption } : {}),
|
||||
...(nextPresets !== prevCons.presets ? { presets: nextPresets } : {}),
|
||||
}
|
||||
: prevCons;
|
||||
|
||||
const prevRunning = Array.isArray(baseTelemetry.runningConversations)
|
||||
? baseTelemetry.runningConversations
|
||||
: null;
|
||||
let nextRunning = prevRunning;
|
||||
if (prevRunning && prevRunning.length > 0 && activeCidLower) {
|
||||
let anyChanged = false;
|
||||
const mapped = prevRunning.map((item) => {
|
||||
const shouldSelect = String(item?.cascadeId || '').toLowerCase() === activeCidLower;
|
||||
if (Boolean(item?.isCurrentSelected) === shouldSelect) return item;
|
||||
anyChanged = true;
|
||||
return { ...item, isCurrentSelected: shouldSelect };
|
||||
});
|
||||
if (anyChanged) nextRunning = mapped;
|
||||
}
|
||||
|
||||
return {
|
||||
...baseTelemetry,
|
||||
...(slice.stepRevision ? { stepRevision: slice.stepRevision } : {}),
|
||||
activeConversation: slice.activeConversation,
|
||||
quotas: nextQuotas,
|
||||
consumption: nextCons,
|
||||
...(nextRunning ? { runningConversations: nextRunning } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function putConsumptionRangeCacheEntry(cacheKey, entry) {
|
||||
if (!cacheKey || !entry) return;
|
||||
consumptionRangeCache.delete(cacheKey);
|
||||
@@ -1012,6 +1131,7 @@ async function requestTelemetry(params, force) {
|
||||
|
||||
let resolvedPayload = reconcileIncomingTelemetrySettings(payload, reqSettingsRev);
|
||||
syncConsumptionCacheScope(resolvedPayload);
|
||||
recordConversationViewToCache(resolvedPayload);
|
||||
if (resolvedPayload?.consumption) {
|
||||
recordConsumptionSliceToCache(resolvedPayload.consumption, resolvedPayload.modelBreakdown, {
|
||||
customStartMs: reqStartMs,
|
||||
@@ -1198,6 +1318,162 @@ async function fetchConsumptionRangeSlice({
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 快速切换当前查看的会话:
|
||||
* - 命中前端 `conversationViewCache` 时,0ms 原子切换当前会话快照,并静默走轻量 `scope=conversation` 校准;
|
||||
* - 未命中缓存时直接走零 LS RPC、零全盘扫描的 `scope=conversation` 通道;
|
||||
* - 若后端提示该会话需要补读最新运行态或懒迁移字段(`needsBackgroundSync`),展示后再在后台静默补齐。
|
||||
*/
|
||||
export async function selectConversation(
|
||||
nextConvId,
|
||||
{ hostRouteConversationId = undefined } = {}
|
||||
) {
|
||||
const switchSeq = ++latestConversationSwitchSeq;
|
||||
latestRequestSeq += 1;
|
||||
inFlightTelemetryPoll = null;
|
||||
abortSidecarApiKey('telemetry-poll');
|
||||
if (deferredConvSyncTimer) {
|
||||
clearTimeout(deferredConvSyncTimer);
|
||||
deferredConvSyncTimer = null;
|
||||
}
|
||||
|
||||
const targetSelectedId = String(nextConvId || '').trim();
|
||||
const prevSt = telemetryStore.getState();
|
||||
const nextHostRouteId =
|
||||
hostRouteConversationId !== undefined
|
||||
? String(hostRouteConversationId || '').trim()
|
||||
: prevSt.hostRouteConversationId;
|
||||
const effectiveConvId = targetSelectedId || nextHostRouteId || '';
|
||||
const statePatch = {
|
||||
selectedConversationId: targetSelectedId,
|
||||
...(hostRouteConversationId !== undefined ? { hostRouteConversationId: nextHostRouteId } : {}),
|
||||
};
|
||||
|
||||
const prevTelemetry = prevSt.telemetry;
|
||||
const lookupRootId = resolveCachedConversationRootId(prevTelemetry, effectiveConvId);
|
||||
const cachedEntry = lookupRootId ? conversationViewCache.get(lookupRootId) : null;
|
||||
const cachedSteps =
|
||||
cachedEntry && cachedEntry.stepRevision
|
||||
? readDisplaySteps({
|
||||
stepRevision: cachedEntry.stepRevision,
|
||||
activeConversation: cachedEntry.activeConversation,
|
||||
})
|
||||
: null;
|
||||
|
||||
if (cachedEntry && prevTelemetry) {
|
||||
const optimisticTelemetry = applyConversationSliceToTelemetry(prevTelemetry, cachedEntry);
|
||||
if (cachedSteps) {
|
||||
lastReceivedSteps = cachedSteps;
|
||||
}
|
||||
telemetryStore.setState({
|
||||
...statePatch,
|
||||
telemetry: optimisticTelemetry,
|
||||
});
|
||||
} else {
|
||||
telemetryStore.setState(statePatch);
|
||||
}
|
||||
|
||||
const current = telemetryStore.getState();
|
||||
const params = new URLSearchParams();
|
||||
if (effectiveConvId) params.set('conversationId', effectiveConvId);
|
||||
if (current.selectedTimeRange) params.set('range', current.selectedTimeRange);
|
||||
if (current.selectedTimeRange === 'custom') {
|
||||
if (current.customStartMs > 0) params.set('startMs', String(current.customStartMs));
|
||||
if (current.customEndMs > 0) params.set('endMs', String(current.customEndMs));
|
||||
}
|
||||
params.set('stepDetails', 'display');
|
||||
params.set('stepRevision', cachedSteps?.revision || '');
|
||||
params.set('scope', 'conversation');
|
||||
|
||||
const reqSettingsRev = settingsRevision;
|
||||
try {
|
||||
const payload = await callSidecarApi(`/api/telemetry?${params}`, {
|
||||
method: 'GET',
|
||||
abortKey: 'conversation-switch',
|
||||
});
|
||||
if (!payload || typeof payload !== 'object') return null;
|
||||
if (switchSeq !== latestConversationSwitchSeq) return payload;
|
||||
|
||||
const latestSt = telemetryStore.getState();
|
||||
const latestEffectiveId =
|
||||
String(latestSt.selectedConversationId || latestSt.hostRouteConversationId || '').trim();
|
||||
if (latestEffectiveId !== effectiveConvId) return payload;
|
||||
|
||||
const active = payload.activeConversation;
|
||||
if (payload.stepsUnchanged) {
|
||||
const stepsSource =
|
||||
(cachedSteps && payload.stepRevision === cachedSteps.revision ? cachedSteps : null) ||
|
||||
(lastReceivedSteps && payload.stepRevision === lastReceivedSteps.revision
|
||||
? lastReceivedSteps
|
||||
: null);
|
||||
if (!active || !stepsSource) {
|
||||
return fetchTelemetry({ force: false });
|
||||
}
|
||||
active.recentSteps = stepsSource.recentSteps;
|
||||
active.agents.forEach((agent, index) => {
|
||||
const steps = stepsSource.agentSteps[index];
|
||||
if (steps) agent.recentSteps = steps;
|
||||
});
|
||||
}
|
||||
|
||||
if (payload.scope === 'conversation' && active) {
|
||||
lastReceivedSteps = readDisplaySteps(payload) || lastReceivedSteps;
|
||||
recordConversationViewToCache(payload);
|
||||
const baseTelemetry = latestSt.telemetry;
|
||||
if (baseTelemetry) {
|
||||
const mergedTelemetry = applyConversationSliceToTelemetry(baseTelemetry, {
|
||||
activeConversation: active,
|
||||
activePool: payload.quotas?.activePool || null,
|
||||
weekly: payload.quotas?.weekly || null,
|
||||
sessionConsumption: payload.consumption?.session || null,
|
||||
sessionPresets: payload.consumption?.sessionPresets || null,
|
||||
stepRevision: payload.stepRevision || '',
|
||||
});
|
||||
if (!isEquivalentTelemetry(baseTelemetry, mergedTelemetry)) {
|
||||
telemetryStore.setState({
|
||||
telemetry: mergedTelemetry,
|
||||
minuteTick: Math.floor(Date.now() / 30000),
|
||||
});
|
||||
}
|
||||
} else {
|
||||
return fetchTelemetry({ force: false });
|
||||
}
|
||||
if (payload.needsBackgroundSync && loopActive && typeof setTimeout === 'function') {
|
||||
deferredConvSyncTimer = setTimeout(() => {
|
||||
deferredConvSyncTimer = null;
|
||||
if (switchSeq === latestConversationSwitchSeq && loopActive) {
|
||||
void fetchTelemetry({ force: false });
|
||||
}
|
||||
}, 35);
|
||||
}
|
||||
return payload;
|
||||
}
|
||||
|
||||
// 冷启动或全新未入缓存会话回退至完整载荷
|
||||
const resolvedPayload = reconcileIncomingTelemetrySettings(payload, reqSettingsRev);
|
||||
syncConsumptionCacheScope(resolvedPayload);
|
||||
lastReceivedSteps = readDisplaySteps(resolvedPayload) || lastReceivedSteps;
|
||||
recordConversationViewToCache(resolvedPayload);
|
||||
if (resolvedPayload?.consumption) {
|
||||
recordConsumptionSliceToCache(resolvedPayload.consumption, resolvedPayload.modelBreakdown, {
|
||||
customStartMs: Number(current.customStartMs || 0),
|
||||
customEndMs: Number(current.customEndMs || 0),
|
||||
});
|
||||
}
|
||||
if (!isEquivalentTelemetry(latestSt.telemetry, resolvedPayload)) {
|
||||
telemetryStore.setState({
|
||||
telemetry: resolvedPayload,
|
||||
minuteTick: Math.floor(Date.now() / 30000),
|
||||
syncState: latestSt.syncState === 'synced' ? 'synced' : 'idle',
|
||||
});
|
||||
}
|
||||
return resolvedPayload;
|
||||
} catch (err) {
|
||||
if (err?.name === 'AbortError' || switchSeq !== latestConversationSwitchSeq) return null;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换「用量统计」时间范围:
|
||||
* - 命中前端 rangeCache 时,在单次 setState 内 0ms 原子更新概览/趋势/模型/来源(若 usageRevision 一致则 0 次 HTTP 请求);
|
||||
@@ -1482,8 +1758,13 @@ export async function saveSettingsPatch(patch) {
|
||||
}
|
||||
|
||||
const needsTelemetryRecompute = patchKeys.some((k) => TELEMETRY_RECOMPUTE_SETTING_KEYS.has(k));
|
||||
if (Object.prototype.hasOwnProperty.call(safePatch, 'weeklyLimitMode')) {
|
||||
if (
|
||||
Object.prototype.hasOwnProperty.call(safePatch, 'weeklyLimitMode') ||
|
||||
Object.prototype.hasOwnProperty.call(safePatch, 'weeklyTokenBudget') ||
|
||||
Object.prototype.hasOwnProperty.call(safePatch, 'weeklyCostBudget')
|
||||
) {
|
||||
clearConsumptionRangeCache();
|
||||
clearConversationViewCache();
|
||||
}
|
||||
if (needsTelemetryRecompute) {
|
||||
inFlightTelemetryPoll = null;
|
||||
@@ -1549,6 +1830,7 @@ export async function resetAllSettings() {
|
||||
}
|
||||
inFlightTelemetryPoll = null;
|
||||
clearConsumptionRangeCache();
|
||||
clearConversationViewCache();
|
||||
void fetchTelemetry({ force: false });
|
||||
return res;
|
||||
}
|
||||
@@ -1556,6 +1838,7 @@ export async function resetAllSettings() {
|
||||
export async function rebuildTrajectoryCache() {
|
||||
const res = await callSidecarApi('/api/cache/rebuild', { method: 'POST', body: {} });
|
||||
clearConsumptionRangeCache();
|
||||
clearConversationViewCache();
|
||||
await fetchTelemetry({ force: true });
|
||||
return res;
|
||||
}
|
||||
@@ -1563,6 +1846,7 @@ export async function rebuildTrajectoryCache() {
|
||||
export async function triggerCloudSync() {
|
||||
const res = await callSidecarApi('/api/cloud-sync', { method: 'POST', body: {} });
|
||||
clearConsumptionRangeCache();
|
||||
clearConversationViewCache();
|
||||
await fetchTelemetry({ force: true });
|
||||
return res;
|
||||
}
|
||||
@@ -1636,6 +1920,10 @@ export function stopAsyncTelemetryLoop() {
|
||||
clearTimeout(feedbackTimer);
|
||||
feedbackTimer = null;
|
||||
}
|
||||
if (deferredConvSyncTimer) {
|
||||
clearTimeout(deferredConvSyncTimer);
|
||||
deferredConvSyncTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
export {
|
||||
|
||||
@@ -684,6 +684,8 @@
|
||||
|
||||
.cons-source-row {
|
||||
gap: 5px;
|
||||
width: 100%;
|
||||
container-type: inline-size;
|
||||
}
|
||||
|
||||
.cons-source-bar-hit {
|
||||
@@ -698,8 +700,90 @@
|
||||
}
|
||||
|
||||
.cons-source-foot {
|
||||
justify-content: flex-end;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
flex-wrap: nowrap;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
min-height: 16px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.cons-source-top-models {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: nowrap;
|
||||
gap: 8px;
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.cons-source-top-models[hidden] {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.cons-source-top-item {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
flex: 0 1 auto;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
line-height: 1.25;
|
||||
}
|
||||
|
||||
.cons-source-top-item:first-child {
|
||||
flex-shrink: 0.5;
|
||||
}
|
||||
|
||||
.cons-source-top-dot {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.cons-source-top-name {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
min-width: 0;
|
||||
color: var(--text-secondary);
|
||||
transition: color 120ms ease;
|
||||
}
|
||||
|
||||
.cons-source-top-models:hover .cons-source-top-name,
|
||||
.cons-source-top-models.is-hovered .cons-source-top-name {
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.cons-source-top-pct {
|
||||
flex-shrink: 0;
|
||||
white-space: nowrap;
|
||||
color: var(--text-primary);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.cons-source-foot > .cons-calls-stat {
|
||||
flex: 0 0 auto;
|
||||
white-space: nowrap;
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
@container (max-width: 340px) {
|
||||
.cons-source-top-item:nth-child(n + 3) {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
@container (max-width: 210px) {
|
||||
.cons-source-top-item:nth-child(n + 2) {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
.month-col.is-interactive {
|
||||
|
||||
@@ -730,8 +730,23 @@ export const ConsumptionView = defineComponent({
|
||||
return { el: segEl, refs: { segEl } };
|
||||
}
|
||||
|
||||
function createSourceTopModelItem() {
|
||||
const dotEl = h('span', { className: 'dot-swatch cons-model-dot cons-source-top-dot' });
|
||||
const nameEl = h('span', { className: 'cons-source-top-name' });
|
||||
const pctEl = h('strong', { className: 'cons-source-top-pct text-mono' });
|
||||
const itemEl = h('span', { className: 'cons-source-top-item' }, [dotEl, nameEl, pctEl]);
|
||||
return { el: itemEl, refs: { itemEl, dotEl, nameEl, pctEl } };
|
||||
}
|
||||
|
||||
function formatCompactSourceSharePct(pct) {
|
||||
const num = Number(pct || 0);
|
||||
if (!Number.isFinite(num) || num <= 0) return '0%';
|
||||
if (num >= 10) return `${Math.round(num)}%`;
|
||||
return `${num.toFixed(1)}%`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建客户端来源单行 DOM 结构(保留长尾合并分段配色进度条与右侧总调用数,悬停进度条弹出各模型明细浮层)。
|
||||
* 创建客户端来源单行 DOM 结构(保留长尾合并分段配色进度条、单行不换行的 Top 2-3 模型速览和右侧总调用数,悬停进度条或速览区弹出完整明细浮层)。
|
||||
*/
|
||||
function createSourceBreakdownRow() {
|
||||
const nameTextEl = h('span', { className: 'cons-row-title-text' });
|
||||
@@ -741,26 +756,39 @@ export const ConsumptionView = defineComponent({
|
||||
const costEl = h('strong', { className: 'cons-row-cost text-mono' });
|
||||
const trackEl = h('div', { className: 'progress-track cons-seg-bar cons-source-model-bar' });
|
||||
const rowState = { hoverPayload: null };
|
||||
const bindPopoverHover = (targetEl) => ({
|
||||
onMouseEnter: (e) => {
|
||||
if (rowState.hoverPayload) {
|
||||
showBreakdownPopover(targetEl, rowState.hoverPayload, e?.clientX ?? null);
|
||||
}
|
||||
},
|
||||
onMouseMove: (e) => {
|
||||
if (rowState.hoverPayload && activeHoverTargetEl === targetEl) {
|
||||
positionBreakdownPopover(targetEl, e?.clientX ?? null);
|
||||
}
|
||||
},
|
||||
onMouseLeave: () => {
|
||||
if (activeHoverTargetEl === targetEl) hideBreakdownPopover();
|
||||
},
|
||||
});
|
||||
const barHitEl = h(
|
||||
'div',
|
||||
{
|
||||
className: 'cons-source-bar-hit',
|
||||
onMouseEnter: (e) => {
|
||||
if (rowState.hoverPayload) {
|
||||
showBreakdownPopover(barHitEl, rowState.hoverPayload, e?.clientX ?? null);
|
||||
}
|
||||
},
|
||||
onMouseMove: (e) => {
|
||||
if (rowState.hoverPayload && activeHoverTargetEl === barHitEl) {
|
||||
positionBreakdownPopover(barHitEl, e?.clientX ?? null);
|
||||
}
|
||||
},
|
||||
onMouseLeave: () => {
|
||||
if (activeHoverTargetEl === barHitEl) hideBreakdownPopover();
|
||||
},
|
||||
},
|
||||
[trackEl]
|
||||
);
|
||||
const barHandlers = bindPopoverHover(barHitEl);
|
||||
barHitEl.addEventListener('mouseenter', barHandlers.onMouseEnter);
|
||||
barHitEl.addEventListener('mousemove', barHandlers.onMouseMove);
|
||||
barHitEl.addEventListener('mouseleave', barHandlers.onMouseLeave);
|
||||
|
||||
const topModelsEl = h('div', { className: 'cons-source-top-models', hidden: true });
|
||||
const topHandlers = bindPopoverHover(topModelsEl);
|
||||
topModelsEl.addEventListener('mouseenter', topHandlers.onMouseEnter);
|
||||
topModelsEl.addEventListener('mousemove', topHandlers.onMouseMove);
|
||||
topModelsEl.addEventListener('mouseleave', topHandlers.onMouseLeave);
|
||||
|
||||
const callsLbl = h('span', { text: t('cons.footCalls') });
|
||||
const callsVal = h('strong', { className: 'text-mono' });
|
||||
|
||||
@@ -775,6 +803,7 @@ export const ConsumptionView = defineComponent({
|
||||
]),
|
||||
barHitEl,
|
||||
h('div', { className: 'cons-item-foot cons-source-foot' }, [
|
||||
topModelsEl,
|
||||
h('span', { className: 'legend-left cons-calls-stat' }, [
|
||||
callsLbl,
|
||||
callsVal,
|
||||
@@ -792,6 +821,7 @@ export const ConsumptionView = defineComponent({
|
||||
costEl,
|
||||
barHitEl,
|
||||
trackEl,
|
||||
topModelsEl,
|
||||
callsLbl,
|
||||
callsVal,
|
||||
rowState,
|
||||
@@ -855,6 +885,28 @@ export const ConsumptionView = defineComponent({
|
||||
},
|
||||
});
|
||||
|
||||
const topModels = partitioned
|
||||
.filter((seg) => !seg.isOther)
|
||||
.slice(0, 3)
|
||||
.map((seg) => ({
|
||||
key: seg.key,
|
||||
label: seg.label,
|
||||
pctText: formatCompactSourceSharePct(seg.pct),
|
||||
color: seg.color,
|
||||
}));
|
||||
patchAttr(refs.topModelsEl, 'hidden', topModels.length === 0);
|
||||
patchKeyedList(refs.topModelsEl, topModels, {
|
||||
keyFn: (m) => m.key,
|
||||
sigFn: (m) => `${m.key}:${m.label}:${m.pctText}:${m.color}`,
|
||||
createRow: createSourceTopModelItem,
|
||||
updateRow: (mRefs, m) => {
|
||||
patchStyleVar(mRefs.dotEl, '--dot-color', m.color);
|
||||
patchText(mRefs.nameEl, m.label);
|
||||
patchText(mRefs.pctEl, m.pctText);
|
||||
patchAttr(mRefs.itemEl, 'title', `${m.label} (${m.pctText})`);
|
||||
},
|
||||
});
|
||||
|
||||
refs.rowState.hoverPayload =
|
||||
total > 0 || callsCount > 0
|
||||
? {
|
||||
|
||||
@@ -2698,6 +2698,8 @@ html[data-standalone="true"] .app-shell {
|
||||
|
||||
.cons-source-row {
|
||||
gap: 5px;
|
||||
width: 100%;
|
||||
container-type: inline-size;
|
||||
}
|
||||
|
||||
.cons-source-bar-hit {
|
||||
@@ -2712,8 +2714,90 @@ html[data-standalone="true"] .app-shell {
|
||||
}
|
||||
|
||||
.cons-source-foot {
|
||||
justify-content: flex-end;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
flex-wrap: nowrap;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
min-height: 16px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.cons-source-top-models {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: nowrap;
|
||||
gap: 8px;
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.cons-source-top-models[hidden] {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.cons-source-top-item {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
flex: 0 1 auto;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
line-height: 1.25;
|
||||
}
|
||||
|
||||
.cons-source-top-item:first-child {
|
||||
flex-shrink: 0.5;
|
||||
}
|
||||
|
||||
.cons-source-top-dot {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.cons-source-top-name {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
min-width: 0;
|
||||
color: var(--text-secondary);
|
||||
transition: color 120ms ease;
|
||||
}
|
||||
|
||||
.cons-source-top-models:hover .cons-source-top-name,
|
||||
.cons-source-top-models.is-hovered .cons-source-top-name {
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.cons-source-top-pct {
|
||||
flex-shrink: 0;
|
||||
white-space: nowrap;
|
||||
color: var(--text-primary);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.cons-source-foot > .cons-calls-stat {
|
||||
flex: 0 0 auto;
|
||||
white-space: nowrap;
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
@container (max-width: 340px) {
|
||||
.cons-source-top-item:nth-child(n + 3) {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
@container (max-width: 210px) {
|
||||
.cons-source-top-item:nth-child(n + 2) {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
.month-col.is-interactive {
|
||||
|
||||
@@ -2586,3 +2586,231 @@ test('scope=consumption and scope=consumption-presets bypass matchesConv, >30s i
|
||||
assert.doesNotMatch(requestedUrls[0], /force=1/);
|
||||
assert.doesNotMatch(requestedUrls[0], /fastRange=1/);
|
||||
});
|
||||
|
||||
test('scope=conversation switches sessions with zero LS RPCs, preserves usageRevision, reuses stepRevision/multi-agent cache, and powers 0ms client cache switching', async (t) => {
|
||||
const clockMs = Date.parse('2026-11-19T14:00:00.000Z');
|
||||
const mkStep = (idx, offsetMs, model, tok) => ({
|
||||
type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE',
|
||||
status: 'CORTEX_STEP_STATUS_DONE',
|
||||
metadata: {
|
||||
createdAt: new Date(clockMs - offsetMs).toISOString(),
|
||||
completedAt: new Date(clockMs - offsetMs + 1000).toISOString(),
|
||||
sourceTrajectoryStepInfo: { stepIndex: idx },
|
||||
modelUsage: {
|
||||
model,
|
||||
inputTokens: String(tok),
|
||||
cacheReadTokens: '0',
|
||||
outputTokens: '120',
|
||||
},
|
||||
},
|
||||
plannerResponse: { response: `step-${idx}` },
|
||||
});
|
||||
|
||||
const h = backendHarness({
|
||||
clock: () => clockMs,
|
||||
quotaSummary: {
|
||||
groups: [
|
||||
{
|
||||
displayName: 'Gemini',
|
||||
remainingFraction: 0.85,
|
||||
resetTime: new Date(clockMs + 3 * 3600_000).toISOString(),
|
||||
},
|
||||
{
|
||||
displayName: 'Claude & GPT',
|
||||
remainingFraction: 0.42,
|
||||
resetTime: new Date(clockMs + 4 * 3600_000).toISOString(),
|
||||
},
|
||||
],
|
||||
},
|
||||
trajectories: {
|
||||
'conv-claude': {
|
||||
trajectory: {
|
||||
steps: [
|
||||
mkStep(1, 30 * 60_000, 'MODEL_CLAUDE_4_5_SONNET', 1200),
|
||||
mkStep(2, 20 * 60_000, 'MODEL_CLAUDE_4_5_SONNET', 1800),
|
||||
],
|
||||
},
|
||||
},
|
||||
'conv-gemini': {
|
||||
trajectory: {
|
||||
steps: [
|
||||
mkStep(1, 10 * 60_000, 'MODEL_PLACEHOLDER_M37', 4000),
|
||||
],
|
||||
},
|
||||
},
|
||||
'conv-gemini-sub': {
|
||||
trajectory: {
|
||||
metadata: {
|
||||
parentConversationId: 'conv-gemini',
|
||||
rootConversationId: 'conv-gemini',
|
||||
subagentSpec: { typeName: 'research', role: 'Helper' },
|
||||
},
|
||||
steps: [
|
||||
mkStep(1, 9 * 60_000, 'MODEL_PLACEHOLDER_M37', 900),
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
summaries: {
|
||||
'conv-claude': {
|
||||
annotations: { title: 'Claude Session' },
|
||||
stepCount: 2,
|
||||
lastModifiedTime: new Date(clockMs - 20 * 60_000).toISOString(),
|
||||
status: 'CASCADE_RUN_STATUS_IDLE',
|
||||
},
|
||||
'conv-gemini': {
|
||||
annotations: { title: 'Gemini Swarm' },
|
||||
stepCount: 1,
|
||||
lastModifiedTime: new Date(clockMs - 10 * 60_000).toISOString(),
|
||||
status: 'CASCADE_RUN_STATUS_IDLE',
|
||||
},
|
||||
'conv-gemini-sub': {
|
||||
stepCount: 1,
|
||||
lastModifiedTime: new Date(clockMs - 9 * 60_000).toISOString(),
|
||||
status: 'CASCADE_RUN_STATUS_IDLE',
|
||||
trajectoryMetadata: {
|
||||
parentConversationId: 'conv-gemini',
|
||||
rootConversationId: 'conv-gemini',
|
||||
subagentSpec: { typeName: 'research', role: 'Helper' },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// 1. Initial full telemetry load on conv-gemini (multi-agent root)
|
||||
const initRes = JSON.parse(
|
||||
(
|
||||
await h.executeTelemetryAction({
|
||||
conversationId: 'conv-gemini',
|
||||
range: 'today',
|
||||
stepDetails: 'display',
|
||||
stepRevision: '',
|
||||
})
|
||||
).body
|
||||
);
|
||||
assert.equal(initRes.activeConversation.cascadeId, 'conv-gemini');
|
||||
assert.equal(initRes.activeConversation.subagentCount, 1);
|
||||
assert.equal(initRes.quotas.activePool.family, 'Gemini');
|
||||
const initialUsageRev = Number(initRes.consumption.revision);
|
||||
const rpcAfterInit = h.state.calls.length;
|
||||
|
||||
// 2. Fast switch to conv-claude via scope=conversation: ZERO LS RPCs!
|
||||
const switchClaude = JSON.parse(
|
||||
(
|
||||
await h.executeTelemetryAction({
|
||||
conversationId: 'conv-claude',
|
||||
range: 'today',
|
||||
stepDetails: 'display',
|
||||
stepRevision: '',
|
||||
scope: 'conversation',
|
||||
})
|
||||
).body
|
||||
);
|
||||
assert.equal(h.state.calls.length, rpcAfterInit, 'scope=conversation must make 0 LS RPC calls');
|
||||
assert.equal(switchClaude.scope, 'conversation');
|
||||
assert.equal(switchClaude.activeConversation.cascadeId, 'conv-claude');
|
||||
assert.equal(switchClaude.activeConversation.stepCount, 2);
|
||||
assert.equal(switchClaude.activeConversation.recentSteps.length, 2);
|
||||
assert.equal(switchClaude.quotas.activePool.family, 'Claude & GPT');
|
||||
assert.equal(switchClaude.consumption.session.calls, 2);
|
||||
assert.equal(switchClaude.needsBackgroundSync, false);
|
||||
assert.ok(switchClaude.stepRevision);
|
||||
|
||||
// 3. Fast switch back to conv-gemini with cached stepRevision -> stepsUnchanged=true & 0 RPCs
|
||||
const switchBackGemini = JSON.parse(
|
||||
(
|
||||
await h.executeTelemetryAction({
|
||||
conversationId: 'conv-gemini',
|
||||
range: 'today',
|
||||
stepDetails: 'display',
|
||||
stepRevision: initRes.stepRevision,
|
||||
scope: 'conversation',
|
||||
})
|
||||
).body
|
||||
);
|
||||
assert.equal(h.state.calls.length, rpcAfterInit);
|
||||
assert.equal(switchBackGemini.scope, 'conversation');
|
||||
assert.equal(switchBackGemini.stepsUnchanged, true);
|
||||
assert.equal(switchBackGemini.activeConversation.recentSteps, undefined);
|
||||
assert.equal(switchBackGemini.quotas.activePool.family, 'Gemini');
|
||||
|
||||
// 4. Subsequent full poll on conv-claude keeps usageRevision identical (decoupled from isCurrentConv!)
|
||||
const fullClaude = JSON.parse(
|
||||
(
|
||||
await h.executeTelemetryAction({
|
||||
conversationId: 'conv-claude',
|
||||
range: 'today',
|
||||
stepDetails: 'display',
|
||||
stepRevision: switchClaude.stepRevision,
|
||||
})
|
||||
).body
|
||||
);
|
||||
assert.equal(fullClaude.consumption.revision, initialUsageRev);
|
||||
assert.equal(fullClaude.stepsUnchanged, true);
|
||||
assert.equal(fullClaude.consumption.session.calls, 2);
|
||||
|
||||
// 5. Frontend selectConversation: first switch hits scope=conversation; repeat switch hits 0ms client cache + rehydrates stepsUnchanged
|
||||
const {
|
||||
clearConsumptionRangeCache,
|
||||
clearConversationViewCache,
|
||||
selectConversation,
|
||||
stopAsyncTelemetryLoop,
|
||||
telemetryStore,
|
||||
} = await import('../src/store/telemetryStore.js');
|
||||
const prevTel = telemetryStore.getState().telemetry;
|
||||
const prevSel = telemetryStore.getState().selectedConversationId;
|
||||
t.after(() => {
|
||||
stopAsyncTelemetryLoop();
|
||||
clearConsumptionRangeCache();
|
||||
clearConversationViewCache();
|
||||
telemetryStore.setState({ selectedConversationId: prevSel, telemetry: prevTel });
|
||||
});
|
||||
clearConversationViewCache();
|
||||
telemetryStore.setState({ selectedConversationId: 'conv-gemini', telemetry: initRes }, { sync: true });
|
||||
|
||||
const fetchedUrls = [];
|
||||
t.mock.method(globalThis, 'fetch', async (url) => {
|
||||
const u = String(url);
|
||||
fetchedUrls.push(u);
|
||||
const parsed = new URL(u, 'http://127.0.0.1');
|
||||
const q = Object.fromEntries(parsed.searchParams.entries());
|
||||
const out = await h.executeTelemetryAction(q);
|
||||
return { ok: true, json: async () => JSON.parse(out.body) };
|
||||
});
|
||||
|
||||
// Seed cache by visiting conv-claude first
|
||||
await selectConversation('conv-claude');
|
||||
assert.equal(fetchedUrls.length, 1);
|
||||
assert.match(fetchedUrls[0], /scope=conversation/);
|
||||
assert.match(fetchedUrls[0], /conversationId=conv-claude/);
|
||||
assert.equal(telemetryStore.getState().telemetry.activeConversation.cascadeId, 'conv-claude');
|
||||
assert.equal(telemetryStore.getState().telemetry.quotas.activePool.family, 'Claude & GPT');
|
||||
|
||||
// Visit conv-gemini (cached from initRes? Let's visit once to cache, then toggle back to conv-claude for 0ms hit!)
|
||||
await selectConversation('conv-gemini');
|
||||
assert.equal(telemetryStore.getState().telemetry.activeConversation.cascadeId, 'conv-gemini');
|
||||
|
||||
// Toggle back to conv-claude: store MUST update synchronously BEFORE fetch resolves!
|
||||
let releaseSecondFetch;
|
||||
t.mock.method(globalThis, 'fetch', async (url) => {
|
||||
fetchedUrls.push(String(url));
|
||||
await new Promise((resolve) => {
|
||||
releaseSecondFetch = resolve;
|
||||
});
|
||||
const parsed = new URL(String(url), 'http://127.0.0.1');
|
||||
const out = await h.executeTelemetryAction(Object.fromEntries(parsed.searchParams.entries()));
|
||||
return { ok: true, json: async () => JSON.parse(out.body) };
|
||||
});
|
||||
|
||||
const pendingSwitch = selectConversation('conv-claude');
|
||||
assert.equal(
|
||||
telemetryStore.getState().telemetry.activeConversation.cascadeId,
|
||||
'conv-claude',
|
||||
'Repeat conversation switch must update activeConversation synchronously in 0ms from client LRU cache'
|
||||
);
|
||||
assert.equal(telemetryStore.getState().telemetry.activeConversation.recentSteps.length, 2);
|
||||
assert.match(fetchedUrls[fetchedUrls.length - 1], new RegExp(`stepRevision=${switchClaude.stepRevision}`));
|
||||
releaseSecondFetch();
|
||||
await pendingSwitch;
|
||||
assert.equal(telemetryStore.getState().telemetry.activeConversation.recentSteps.length, 2);
|
||||
});
|
||||
|
||||
@@ -423,8 +423,18 @@ test('ConsumptionView: Top Models color dot + % bar, clutter-free Client Sources
|
||||
.reduce((s, el) => s + parsePctVar(el, '--seg-w'), 0);
|
||||
assert.ok(Math.abs(argonSegSum - 50) < 0.1, `Expected 50% width for 4-argon row, got ${argonSegSum}`);
|
||||
|
||||
// 2. Client Sources: NO bottom model list text dump; 3 tail models (<1.5%) fold into 1 neutral '__other__' segment!
|
||||
// 2. Client Sources: NO multi-line .cons-source-model-chip dump; renders single-line Top 2-3 models + 1 merged '__other__' segment on the bar!
|
||||
assert.equal(sourceRows[0].querySelectorAll('.cons-source-model-chip').length, 0);
|
||||
const appTopItems = sourceRows[0].querySelectorAll('.cons-source-top-item');
|
||||
assert.equal(appTopItems.length, 3, 'Should show top 3 non-other models in single-line footer');
|
||||
assert.equal(appTopItems[0].querySelector('.cons-source-top-name')?.textContent, '4-argon');
|
||||
assert.equal(appTopItems[0].querySelector('.cons-source-top-pct')?.textContent, '50%');
|
||||
assert.equal(appTopItems[0].querySelector('.cons-source-top-dot')?.style.getPropertyValue('--dot-color'), argonDotColor);
|
||||
assert.equal(appTopItems[1].querySelector('.cons-source-top-name')?.textContent, '4-carbon');
|
||||
assert.equal(appTopItems[1].querySelector('.cons-source-top-pct')?.textContent, '31%');
|
||||
assert.equal(appTopItems[2].querySelector('.cons-source-top-name')?.textContent, '3.8-flash-n');
|
||||
assert.equal(appTopItems[2].querySelector('.cons-source-top-pct')?.textContent, '16%');
|
||||
|
||||
const appSegs = sourceRows[0].querySelectorAll('.cons-model-seg');
|
||||
assert.equal(appSegs.length, 4, '3 main models + 1 merged other segment');
|
||||
assert.equal(appSegs[0].style.getPropertyValue('--seg-color'), argonDotColor);
|
||||
@@ -432,7 +442,7 @@ test('ConsumptionView: Top Models color dot + % bar, clutter-free Client Sources
|
||||
const appBarSum = appSegs.reduce((s, el) => s + parsePctVar(el, '--seg-w'), 0);
|
||||
assert.ok(Math.abs(appBarSum - 80) < 0.1);
|
||||
|
||||
// Hovering Client Source bar hit area opens shared popover with model details + '其他 (3)'
|
||||
// Hovering Client Source bar hit area OR top-models summary opens shared popover with model details + '其他 (3)'
|
||||
const popover = view.refs.breakdownPopoverEl;
|
||||
assert.equal(popover.hasAttribute('hidden'), true);
|
||||
const appBarHit = sourceRows[0].querySelector('.cons-source-bar-hit');
|
||||
@@ -448,6 +458,20 @@ test('ConsumptionView: Top Models color dot + % bar, clutter-free Client Sources
|
||||
appBarHit.dispatchEvent({ type: 'mouseleave' });
|
||||
assert.equal(popover.hasAttribute('hidden'), true);
|
||||
|
||||
const appTopModelsEl = sourceRows[0].querySelector('.cons-source-top-models');
|
||||
appTopModelsEl.dispatchEvent({ type: 'mouseenter', clientX: 90 });
|
||||
assert.equal(popover.hasAttribute('hidden'), false);
|
||||
assert.equal(popover.querySelector('.trend-tip-time')?.textContent, 'Antigravity App');
|
||||
appTopModelsEl.dispatchEvent({ type: 'mouseleave' });
|
||||
assert.equal(popover.hasAttribute('hidden'), true);
|
||||
|
||||
// Verify single-line non-wrapping CSS rules exist for client source top models
|
||||
const { readFileSync } = await import('node:fs');
|
||||
const consCss = readFileSync(new URL('../src/styles/views-consumption.css', import.meta.url), 'utf8');
|
||||
assert.match(consCss, /\.cons-source-foot\s*\{[\s\S]*flex-wrap:\s*nowrap/);
|
||||
assert.match(consCss, /\.cons-source-top-models\s*\{[\s\S]*flex-wrap:\s*nowrap/);
|
||||
assert.match(consCss, /@container\s*\(max-width:\s*340px\)\s*\{\s*\.cons-source-top-item:nth-child\(n\s*\+\s*3\)/);
|
||||
|
||||
// 3. Monthly Breakdown: old 4-channel legend removed; Nov column renders model-colored vertical segments & hover popover
|
||||
assert.equal(view.el.querySelectorAll('.monthly-legend').length, 0);
|
||||
const monthCols = view.el.querySelectorAll('.month-col');
|
||||
|
||||
Reference in New Issue
Block a user