mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-27 01:19:25 +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 ---
|
// --- src/core/httpClient.js ---
|
||||||
const { getWindowBridgeConfig, isWindowOverlayMode, deliverCdpBridgeResponses, callSidecarApi } = (() => {
|
const { abortSidecarApiKey, getWindowBridgeConfig, isWindowOverlayMode, deliverCdpBridgeResponses, callSidecarApi } = (() => {
|
||||||
/**
|
/**
|
||||||
* @fileoverview Async HTTP client with AbortController cancellation for stale
|
* @fileoverview Async HTTP client with AbortController cancellation for stale
|
||||||
* polling requests, concurrent GET deduplication, and dual-mode transport
|
* polling requests, concurrent GET deduplication, and dual-mode transport
|
||||||
@@ -4422,6 +4422,15 @@ const { getWindowBridgeConfig, isWindowOverlayMode, deliverCdpBridgeResponses, c
|
|||||||
const inFlightGets = new Map();
|
const inFlightGets = new Map();
|
||||||
const activeControllers = 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`)。
|
* 读取主窗口双栖模式下注入的本地桥接配置(`port`、`token`、`bundleVersion`、`stylesCss`)。
|
||||||
*
|
*
|
||||||
@@ -4655,7 +4664,7 @@ async function callSidecarApi(path, { method = 'GET', body, abortKey = '', cdpTi
|
|||||||
}
|
}
|
||||||
return promise;
|
return promise;
|
||||||
}
|
}
|
||||||
return { getWindowBridgeConfig, isWindowOverlayMode, deliverCdpBridgeResponses, callSidecarApi };
|
return { abortSidecarApiKey, getWindowBridgeConfig, isWindowOverlayMode, deliverCdpBridgeResponses, callSidecarApi };
|
||||||
})();
|
})();
|
||||||
|
|
||||||
// --- src/store/uiStore.js ---
|
// --- src/store/uiStore.js ---
|
||||||
@@ -4691,7 +4700,7 @@ return { getViewTabs, uiStore, getVisibleMonitorView };
|
|||||||
})();
|
})();
|
||||||
|
|
||||||
// --- src/store/telemetryStore.js ---
|
// --- 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
|
* @fileoverview Reactive telemetry store with async non-overlapping poll scheduler
|
||||||
* and granular slice updates.
|
* and granular slice updates.
|
||||||
@@ -4787,9 +4796,11 @@ const telemetryStore = createReactiveStore({
|
|||||||
|
|
||||||
let pollTimer = null;
|
let pollTimer = null;
|
||||||
let feedbackTimer = null;
|
let feedbackTimer = null;
|
||||||
|
let deferredConvSyncTimer = null;
|
||||||
let activeBundleVersion = 0;
|
let activeBundleVersion = 0;
|
||||||
let latestRequestSeq = 0;
|
let latestRequestSeq = 0;
|
||||||
let latestConsumptionReqSeq = 0;
|
let latestConsumptionReqSeq = 0;
|
||||||
|
let latestConversationSwitchSeq = 0;
|
||||||
let activeForceCount = 0;
|
let activeForceCount = 0;
|
||||||
let consecutivePollFailures = 0;
|
let consecutivePollFailures = 0;
|
||||||
let inFlightTelemetryPoll = null;
|
let inFlightTelemetryPoll = null;
|
||||||
@@ -4797,8 +4808,10 @@ let inFlightPresetsPrefetch = null;
|
|||||||
let lastPrefetchedUsageRevision = 0;
|
let lastPrefetchedUsageRevision = 0;
|
||||||
let consumptionCacheScopeSig = '';
|
let consumptionCacheScopeSig = '';
|
||||||
const MAX_CONSUMPTION_RANGE_CACHE = 12;
|
const MAX_CONSUMPTION_RANGE_CACHE = 12;
|
||||||
|
const MAX_CONVERSATION_VIEW_CACHE = 12;
|
||||||
const CONSUMPTION_PRESET_KEYS = ['cycle', 'today', '24h', '7d', '14d', '30d', 'all'];
|
const CONSUMPTION_PRESET_KEYS = ['cycle', 'today', '24h', '7d', '14d', '30d', 'all'];
|
||||||
const consumptionRangeCache = new Map();
|
const consumptionRangeCache = new Map();
|
||||||
|
const conversationViewCache = new Map();
|
||||||
let lastReceivedSteps = null;
|
let lastReceivedSteps = null;
|
||||||
let loopActive = false;
|
let loopActive = false;
|
||||||
let loopIntervalMs = 2000;
|
let loopIntervalMs = 2000;
|
||||||
@@ -4830,6 +4843,14 @@ function clearConsumptionRangeCache() {
|
|||||||
inFlightPresetsPrefetch = null;
|
inFlightPresetsPrefetch = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function clearConversationViewCache() {
|
||||||
|
conversationViewCache.clear();
|
||||||
|
if (deferredConvSyncTimer) {
|
||||||
|
clearTimeout(deferredConvSyncTimer);
|
||||||
|
deferredConvSyncTimer = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function buildConsumptionScopeSig(payload) {
|
function buildConsumptionScopeSig(payload) {
|
||||||
if (!payload || typeof payload !== 'object') return '';
|
if (!payload || typeof payload !== 'object') return '';
|
||||||
const acct = payload.account || {};
|
const acct = payload.account || {};
|
||||||
@@ -4843,10 +4864,112 @@ function syncConsumptionCacheScope(payload) {
|
|||||||
if (!nextSig) return;
|
if (!nextSig) return;
|
||||||
if (consumptionCacheScopeSig && consumptionCacheScopeSig !== nextSig) {
|
if (consumptionCacheScopeSig && consumptionCacheScopeSig !== nextSig) {
|
||||||
clearConsumptionRangeCache();
|
clearConsumptionRangeCache();
|
||||||
|
clearConversationViewCache();
|
||||||
}
|
}
|
||||||
consumptionCacheScopeSig = nextSig;
|
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) {
|
function putConsumptionRangeCacheEntry(cacheKey, entry) {
|
||||||
if (!cacheKey || !entry) return;
|
if (!cacheKey || !entry) return;
|
||||||
consumptionRangeCache.delete(cacheKey);
|
consumptionRangeCache.delete(cacheKey);
|
||||||
@@ -5660,6 +5783,7 @@ async function requestTelemetry(params, force) {
|
|||||||
|
|
||||||
let resolvedPayload = reconcileIncomingTelemetrySettings(payload, reqSettingsRev);
|
let resolvedPayload = reconcileIncomingTelemetrySettings(payload, reqSettingsRev);
|
||||||
syncConsumptionCacheScope(resolvedPayload);
|
syncConsumptionCacheScope(resolvedPayload);
|
||||||
|
recordConversationViewToCache(resolvedPayload);
|
||||||
if (resolvedPayload?.consumption) {
|
if (resolvedPayload?.consumption) {
|
||||||
recordConsumptionSliceToCache(resolvedPayload.consumption, resolvedPayload.modelBreakdown, {
|
recordConsumptionSliceToCache(resolvedPayload.consumption, resolvedPayload.modelBreakdown, {
|
||||||
customStartMs: reqStartMs,
|
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 请求);
|
* - 命中前端 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));
|
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();
|
clearConsumptionRangeCache();
|
||||||
|
clearConversationViewCache();
|
||||||
}
|
}
|
||||||
if (needsTelemetryRecompute) {
|
if (needsTelemetryRecompute) {
|
||||||
inFlightTelemetryPoll = null;
|
inFlightTelemetryPoll = null;
|
||||||
@@ -6197,6 +6482,7 @@ async function resetAllSettings() {
|
|||||||
}
|
}
|
||||||
inFlightTelemetryPoll = null;
|
inFlightTelemetryPoll = null;
|
||||||
clearConsumptionRangeCache();
|
clearConsumptionRangeCache();
|
||||||
|
clearConversationViewCache();
|
||||||
void fetchTelemetry({ force: false });
|
void fetchTelemetry({ force: false });
|
||||||
return res;
|
return res;
|
||||||
}
|
}
|
||||||
@@ -6204,6 +6490,7 @@ async function resetAllSettings() {
|
|||||||
async function rebuildTrajectoryCache() {
|
async function rebuildTrajectoryCache() {
|
||||||
const res = await callSidecarApi('/api/cache/rebuild', { method: 'POST', body: {} });
|
const res = await callSidecarApi('/api/cache/rebuild', { method: 'POST', body: {} });
|
||||||
clearConsumptionRangeCache();
|
clearConsumptionRangeCache();
|
||||||
|
clearConversationViewCache();
|
||||||
await fetchTelemetry({ force: true });
|
await fetchTelemetry({ force: true });
|
||||||
return res;
|
return res;
|
||||||
}
|
}
|
||||||
@@ -6211,6 +6498,7 @@ async function rebuildTrajectoryCache() {
|
|||||||
async function triggerCloudSync() {
|
async function triggerCloudSync() {
|
||||||
const res = await callSidecarApi('/api/cloud-sync', { method: 'POST', body: {} });
|
const res = await callSidecarApi('/api/cloud-sync', { method: 'POST', body: {} });
|
||||||
clearConsumptionRangeCache();
|
clearConsumptionRangeCache();
|
||||||
|
clearConversationViewCache();
|
||||||
await fetchTelemetry({ force: true });
|
await fetchTelemetry({ force: true });
|
||||||
return res;
|
return res;
|
||||||
}
|
}
|
||||||
@@ -6284,6 +6572,10 @@ function stopAsyncTelemetryLoop() {
|
|||||||
clearTimeout(feedbackTimer);
|
clearTimeout(feedbackTimer);
|
||||||
feedbackTimer = null;
|
feedbackTimer = null;
|
||||||
}
|
}
|
||||||
|
if (deferredConvSyncTimer) {
|
||||||
|
clearTimeout(deferredConvSyncTimer);
|
||||||
|
deferredConvSyncTimer = null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -6480,7 +6772,7 @@ function isMacHostPlatform(telemetry) {
|
|||||||
}
|
}
|
||||||
return false;
|
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 ---
|
// --- src/components/ui/TopLongPillNav.js ---
|
||||||
@@ -13685,8 +13977,7 @@ const LiveActivityWidget = defineComponent({
|
|||||||
onSelectSession(item.cascadeId);
|
onSelectSession(item.cascadeId);
|
||||||
} else if (item.cascadeId && item.cascadeId !== 'current') {
|
} else if (item.cascadeId && item.cascadeId !== 'current') {
|
||||||
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
|
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
|
||||||
telemetryStore.setState({ selectedConversationId: item.cascadeId });
|
void selectConversation(item.cascadeId);
|
||||||
fetchTelemetry({ force: false });
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -20620,8 +20911,7 @@ const TopSessionHeader = defineComponent({
|
|||||||
options: [{ value: '', label: t('header.followLatest') }],
|
options: [{ value: '', label: t('header.followLatest') }],
|
||||||
onUpdateModelValue: (nextConvId) => {
|
onUpdateModelValue: (nextConvId) => {
|
||||||
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
|
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
|
||||||
telemetryStore.setState({ selectedConversationId: nextConvId });
|
void selectConversation(nextConvId);
|
||||||
fetchTelemetry({ force: false });
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -21795,8 +22085,23 @@ const ConsumptionView = defineComponent({
|
|||||||
return { el: segEl, refs: { segEl } };
|
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() {
|
function createSourceBreakdownRow() {
|
||||||
const nameTextEl = h('span', { className: 'cons-row-title-text' });
|
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 costEl = h('strong', { className: 'cons-row-cost text-mono' });
|
||||||
const trackEl = h('div', { className: 'progress-track cons-seg-bar cons-source-model-bar' });
|
const trackEl = h('div', { className: 'progress-track cons-seg-bar cons-source-model-bar' });
|
||||||
const rowState = { hoverPayload: null };
|
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(
|
const barHitEl = h(
|
||||||
'div',
|
'div',
|
||||||
{
|
{
|
||||||
className: 'cons-source-bar-hit',
|
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]
|
[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 callsLbl = h('span', { text: t('cons.footCalls') });
|
||||||
const callsVal = h('strong', { className: 'text-mono' });
|
const callsVal = h('strong', { className: 'text-mono' });
|
||||||
|
|
||||||
@@ -21840,6 +22158,7 @@ const ConsumptionView = defineComponent({
|
|||||||
]),
|
]),
|
||||||
barHitEl,
|
barHitEl,
|
||||||
h('div', { className: 'cons-item-foot cons-source-foot' }, [
|
h('div', { className: 'cons-item-foot cons-source-foot' }, [
|
||||||
|
topModelsEl,
|
||||||
h('span', { className: 'legend-left cons-calls-stat' }, [
|
h('span', { className: 'legend-left cons-calls-stat' }, [
|
||||||
callsLbl,
|
callsLbl,
|
||||||
callsVal,
|
callsVal,
|
||||||
@@ -21857,6 +22176,7 @@ const ConsumptionView = defineComponent({
|
|||||||
costEl,
|
costEl,
|
||||||
barHitEl,
|
barHitEl,
|
||||||
trackEl,
|
trackEl,
|
||||||
|
topModelsEl,
|
||||||
callsLbl,
|
callsLbl,
|
||||||
callsVal,
|
callsVal,
|
||||||
rowState,
|
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 =
|
refs.rowState.hoverPayload =
|
||||||
total > 0 || callsCount > 0
|
total > 0 || callsCount > 0
|
||||||
? {
|
? {
|
||||||
@@ -25251,8 +25593,7 @@ function mountWindowOverlay() {
|
|||||||
selectedAgentScope: 'all',
|
selectedAgentScope: 'all',
|
||||||
ctxInspectorAgentId: 'auto',
|
ctxInspectorAgentId: 'auto',
|
||||||
});
|
});
|
||||||
telemetryStore.setState({ selectedConversationId: cascadeId });
|
void selectConversation(cascadeId);
|
||||||
void fetchTelemetry({ force: false });
|
|
||||||
setMultiOpen(false);
|
setMultiOpen(false);
|
||||||
setPopoverOpen(true);
|
setPopoverOpen(true);
|
||||||
}
|
}
|
||||||
@@ -26732,13 +27073,12 @@ function mountWindowOverlay() {
|
|||||||
if (currentRouteId === lastObservedRouteId) return;
|
if (currentRouteId === lastObservedRouteId) return;
|
||||||
lastObservedRouteId = currentRouteId;
|
lastObservedRouteId = currentRouteId;
|
||||||
const st = telemetryStore.getState();
|
const st = telemetryStore.getState();
|
||||||
const patch = { hostRouteConversationId: currentRouteId };
|
const nextSelectedId =
|
||||||
if (currentRouteId && st.selectedConversationId && st.selectedConversationId !== currentRouteId) {
|
currentRouteId && st.selectedConversationId && st.selectedConversationId !== currentRouteId
|
||||||
patch.selectedConversationId = '';
|
? ''
|
||||||
}
|
: st.selectedConversationId;
|
||||||
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
|
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
|
||||||
telemetryStore.setState(patch);
|
void selectConversation(nextSelectedId, { hostRouteConversationId: currentRouteId });
|
||||||
void fetchTelemetry({ force: false });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const onDocMouseDown = (e) => {
|
const onDocMouseDown = (e) => {
|
||||||
|
|||||||
@@ -198,7 +198,11 @@ export async function executeTelemetryAction(data, { onRestart = null } = {}) {
|
|||||||
}
|
}
|
||||||
const rawScope = String(data?.scope || '').trim();
|
const rawScope = String(data?.scope || '').trim();
|
||||||
const scope =
|
const scope =
|
||||||
rawScope === 'consumption' || rawScope === 'consumption-presets' ? rawScope : '';
|
rawScope === 'consumption' ||
|
||||||
|
rawScope === 'consumption-presets' ||
|
||||||
|
rawScope === 'conversation'
|
||||||
|
? rawScope
|
||||||
|
: '';
|
||||||
const filterOpts = {
|
const filterOpts = {
|
||||||
range: data?.range || 'all',
|
range: data?.range || 'all',
|
||||||
startMs: sanitizePositiveFiniteMs(data?.startMs),
|
startMs: sanitizePositiveFiniteMs(data?.startMs),
|
||||||
|
|||||||
@@ -99,14 +99,21 @@ function discoverLocalConversationFiles() {
|
|||||||
|
|
||||||
const annotationDirs = Array.isArray(ANNOTATION_DIRS) ? ANNOTATION_DIRS : [];
|
const annotationDirs = Array.isArray(ANNOTATION_DIRS) ? ANNOTATION_DIRS : [];
|
||||||
if (annotationDirs.length > 0 && map.size > 0) {
|
if (annotationDirs.length > 0 && map.size > 0) {
|
||||||
for (const [cascadeId, fileList] of map.entries()) {
|
|
||||||
for (const annDir of annotationDirs) {
|
for (const annDir of annotationDirs) {
|
||||||
if (!annDir) continue;
|
if (!annDir || !existsSync(annDir)) continue;
|
||||||
const pbtxtPath = join(annDir, `${cascadeId}.pbtxt`);
|
try {
|
||||||
if (existsSync(pbtxtPath)) {
|
for (const rawName of readdirSync(annDir)) {
|
||||||
fileList.push(pbtxtPath);
|
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 {
|
||||||
|
// 忽略注释目录读取异常
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return map;
|
return map;
|
||||||
|
|||||||
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) => {
|
return previous.length === current.length && current.every((entry, index) => {
|
||||||
const before = previous[index];
|
const before = previous[index];
|
||||||
return entry.steps === before.steps && entry.cascadeId === before.cascadeId &&
|
return entry.steps === before.steps && entry.cascadeId === before.cascadeId &&
|
||||||
entry.appSource === before.appSource && entry.accountName === before.accountName &&
|
entry.appSource === before.appSource && entry.accountName === before.accountName;
|
||||||
entry.isCurrentConv === before.isCurrentConv;
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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) {
|
function sortedUsageTimestamps(entries) {
|
||||||
const dates = new Float64Array(entries.reduce((sum, entry) => sum + entry.steps.length, 0));
|
const dates = new Float64Array(entries.reduce((sum, entry) => sum + entry.steps.length, 0));
|
||||||
let count = 0;
|
let count = 0;
|
||||||
@@ -971,6 +1118,7 @@ export function aggregateMultiWindowUsage({
|
|||||||
|
|
||||||
const perSourceStats = new Map();
|
const perSourceStats = new Map();
|
||||||
const allEntriesToAggregate = collectUsageEntriesToAggregate(familySet);
|
const allEntriesToAggregate = collectUsageEntriesToAggregate(familySet);
|
||||||
|
const familySig = buildFamilySig(familySet);
|
||||||
|
|
||||||
const timeZone = modelInputs ? new Intl.DateTimeFormat().resolvedOptions().timeZone : '';
|
const timeZone = modelInputs ? new Intl.DateTimeFormat().resolvedOptions().timeZone : '';
|
||||||
const quotaWindows = Array.from(poolCycleBuckets, ([key, { start5hMs, startWkMs }]) => [
|
const quotaWindows = Array.from(poolCycleBuckets, ([key, { start5hMs, startWkMs }]) => [
|
||||||
@@ -1002,6 +1150,7 @@ export function aggregateMultiWindowUsage({
|
|||||||
) {
|
) {
|
||||||
snapshot.ranges.delete(selectedWindow.key);
|
snapshot.ranges.delete(selectedWindow.key);
|
||||||
snapshot.ranges.set(selectedWindow.key, previous);
|
snapshot.ranges.set(selectedWindow.key, previous);
|
||||||
|
if (previous.familySig === familySig) {
|
||||||
return {
|
return {
|
||||||
...previous.result,
|
...previous.result,
|
||||||
usageRevision: snapshot.revision,
|
usageRevision: snapshot.revision,
|
||||||
@@ -1010,6 +1159,37 @@ export function aggregateMultiWindowUsage({
|
|||||||
trendEndMs: trend.end,
|
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,
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const entry of allEntriesToAggregate) {
|
for (const entry of allEntriesToAggregate) {
|
||||||
@@ -1324,6 +1504,7 @@ export function aggregateMultiWindowUsage({
|
|||||||
const { ranges } = lastUsageSnapshot;
|
const { ranges } = lastUsageSnapshot;
|
||||||
ranges.delete(selectedWindow.key);
|
ranges.delete(selectedWindow.key);
|
||||||
ranges.set(selectedWindow.key, {
|
ranges.set(selectedWindow.key, {
|
||||||
|
familySig,
|
||||||
windows,
|
windows,
|
||||||
selectedWindow,
|
selectedWindow,
|
||||||
effectiveSelectedWindow,
|
effectiveSelectedWindow,
|
||||||
@@ -1387,6 +1568,7 @@ export function aggregateSelectedWindowUsage({
|
|||||||
const allEntriesToAggregate = Array.isArray(precollectedEntries)
|
const allEntriesToAggregate = Array.isArray(precollectedEntries)
|
||||||
? precollectedEntries
|
? precollectedEntries
|
||||||
: collectUsageEntriesToAggregate(familySet);
|
: collectUsageEntriesToAggregate(familySet);
|
||||||
|
const familySig = buildFamilySig(familySet);
|
||||||
const currentYear = new Date(nowMs).getFullYear();
|
const currentYear = new Date(nowMs).getFullYear();
|
||||||
const timeZone = modelInputs ? new Intl.DateTimeFormat().resolvedOptions().timeZone : '';
|
const timeZone = modelInputs ? new Intl.DateTimeFormat().resolvedOptions().timeZone : '';
|
||||||
|
|
||||||
@@ -1426,12 +1608,28 @@ export function aggregateSelectedWindowUsage({
|
|||||||
)
|
)
|
||||||
) {
|
) {
|
||||||
const res = candidate.result;
|
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 {
|
return {
|
||||||
usageRevision: snapshot.revision,
|
usageRevision: snapshot.revision,
|
||||||
selectedWindow: effectivePrevWin,
|
selectedWindow: effectivePrevWin,
|
||||||
trendStartMs: trend.start,
|
trendStartMs: trend.start,
|
||||||
trendEndMs: trend.end,
|
trendEndMs: trend.end,
|
||||||
finalizedSelectedSession: res.finalizedSelectedSession,
|
finalizedSelectedSession: resolvedSelectedSession,
|
||||||
finalizedSelectedAccount: res.finalizedSelectedAccount,
|
finalizedSelectedAccount: res.finalizedSelectedAccount,
|
||||||
trendSeries: res.trendSeries,
|
trendSeries: res.trendSeries,
|
||||||
sourcesBreakdown: res.sourcesBreakdown,
|
sourcesBreakdown: res.sourcesBreakdown,
|
||||||
@@ -1658,6 +1856,7 @@ export function aggregateSelectedWindowUsage({
|
|||||||
snapshot.selectedRanges ??= new Map();
|
snapshot.selectedRanges ??= new Map();
|
||||||
snapshot.selectedRanges.delete(selectedWindow.key);
|
snapshot.selectedRanges.delete(selectedWindow.key);
|
||||||
snapshot.selectedRanges.set(selectedWindow.key, {
|
snapshot.selectedRanges.set(selectedWindow.key, {
|
||||||
|
familySig,
|
||||||
selectedWindow,
|
selectedWindow,
|
||||||
effectiveSelectedWindow,
|
effectiveSelectedWindow,
|
||||||
trend,
|
trend,
|
||||||
@@ -1673,6 +1872,73 @@ export function aggregateSelectedWindowUsage({
|
|||||||
return sliceResult;
|
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 瞬切。
|
* 批量预聚合全部 7 个用量页预设区间(复用同一次条目收集与时间剪枝),供前端进入「用量统计」时静默预取实现 0ms 瞬切。
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -4,11 +4,11 @@
|
|||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
<title>用量监控</title>
|
<title>用量监控</title>
|
||||||
<link rel="stylesheet" href="/styles.css?v=1795093491990">
|
<link rel="stylesheet" href="/styles.css?v=1795097331072">
|
||||||
<script src="/preload.js"></script>
|
<script src="/preload.js"></script>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="app-root"></div>
|
<div id="app-root"></div>
|
||||||
<script src="/app.js?v=1795093491990"></script>
|
<script src="/app.js?v=1795097331072"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import {
|
|||||||
formatConversationMeta,
|
formatConversationMeta,
|
||||||
normalizeClientUpdateMode,
|
normalizeClientUpdateMode,
|
||||||
resolveHostRouteMatch,
|
resolveHostRouteMatch,
|
||||||
|
selectConversation,
|
||||||
telemetryStore,
|
telemetryStore,
|
||||||
triggerPluginUpdate,
|
triggerPluginUpdate,
|
||||||
} from '../../store/telemetryStore.js';
|
} from '../../store/telemetryStore.js';
|
||||||
@@ -33,8 +34,7 @@ export const TopSessionHeader = defineComponent({
|
|||||||
options: [{ value: '', label: t('header.followLatest') }],
|
options: [{ value: '', label: t('header.followLatest') }],
|
||||||
onUpdateModelValue: (nextConvId) => {
|
onUpdateModelValue: (nextConvId) => {
|
||||||
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
|
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
|
||||||
telemetryStore.setState({ selectedConversationId: nextConvId });
|
void selectConversation(nextConvId);
|
||||||
fetchTelemetry({ force: false });
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -52,6 +52,7 @@ import {
|
|||||||
normalizeClientUpdateMode,
|
normalizeClientUpdateMode,
|
||||||
normalizeClientWindowMountMode,
|
normalizeClientWindowMountMode,
|
||||||
resolveScopedConversation,
|
resolveScopedConversation,
|
||||||
|
selectConversation,
|
||||||
startAsyncTelemetryLoop,
|
startAsyncTelemetryLoop,
|
||||||
stopAsyncTelemetryLoop,
|
stopAsyncTelemetryLoop,
|
||||||
telemetryStore,
|
telemetryStore,
|
||||||
@@ -1086,8 +1087,7 @@ export function mountWindowOverlay() {
|
|||||||
selectedAgentScope: 'all',
|
selectedAgentScope: 'all',
|
||||||
ctxInspectorAgentId: 'auto',
|
ctxInspectorAgentId: 'auto',
|
||||||
});
|
});
|
||||||
telemetryStore.setState({ selectedConversationId: cascadeId });
|
void selectConversation(cascadeId);
|
||||||
void fetchTelemetry({ force: false });
|
|
||||||
setMultiOpen(false);
|
setMultiOpen(false);
|
||||||
setPopoverOpen(true);
|
setPopoverOpen(true);
|
||||||
}
|
}
|
||||||
@@ -2567,13 +2567,12 @@ export function mountWindowOverlay() {
|
|||||||
if (currentRouteId === lastObservedRouteId) return;
|
if (currentRouteId === lastObservedRouteId) return;
|
||||||
lastObservedRouteId = currentRouteId;
|
lastObservedRouteId = currentRouteId;
|
||||||
const st = telemetryStore.getState();
|
const st = telemetryStore.getState();
|
||||||
const patch = { hostRouteConversationId: currentRouteId };
|
const nextSelectedId =
|
||||||
if (currentRouteId && st.selectedConversationId && st.selectedConversationId !== currentRouteId) {
|
currentRouteId && st.selectedConversationId && st.selectedConversationId !== currentRouteId
|
||||||
patch.selectedConversationId = '';
|
? ''
|
||||||
}
|
: st.selectedConversationId;
|
||||||
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
|
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
|
||||||
telemetryStore.setState(patch);
|
void selectConversation(nextSelectedId, { hostRouteConversationId: currentRouteId });
|
||||||
void fetchTelemetry({ force: false });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const onDocMouseDown = (e) => {
|
const onDocMouseDown = (e) => {
|
||||||
|
|||||||
@@ -25,8 +25,8 @@ import { createSvgIcon } from '../../icons/SvgIcon.js';
|
|||||||
import { getEffectiveLocale, t } from '../../i18n/index.js';
|
import { getEffectiveLocale, t } from '../../i18n/index.js';
|
||||||
import {
|
import {
|
||||||
extractHostRouteCascadeId,
|
extractHostRouteCascadeId,
|
||||||
fetchTelemetry,
|
|
||||||
resolveScopedConversation,
|
resolveScopedConversation,
|
||||||
|
selectConversation,
|
||||||
telemetryStore,
|
telemetryStore,
|
||||||
} from '../../store/telemetryStore.js';
|
} from '../../store/telemetryStore.js';
|
||||||
import { uiStore } from '../../store/uiStore.js';
|
import { uiStore } from '../../store/uiStore.js';
|
||||||
@@ -499,8 +499,7 @@ export const LiveActivityWidget = defineComponent({
|
|||||||
onSelectSession(item.cascadeId);
|
onSelectSession(item.cascadeId);
|
||||||
} else if (item.cascadeId && item.cascadeId !== 'current') {
|
} else if (item.cascadeId && item.cascadeId !== 'current') {
|
||||||
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
|
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
|
||||||
telemetryStore.setState({ selectedConversationId: item.cascadeId });
|
void selectConversation(item.cascadeId);
|
||||||
fetchTelemetry({ force: false });
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,6 +9,15 @@ import { readInjectedWindowBridge } from '../../shared/window-bridge-protocol.mj
|
|||||||
const inFlightGets = new Map();
|
const inFlightGets = new Map();
|
||||||
const activeControllers = 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`)。
|
* 读取主窗口双栖模式下注入的本地桥接配置(`port`、`token`、`bundleVersion`、`stylesCss`)。
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -4,7 +4,12 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { createReactiveStore } from '../core/reactive.js';
|
import { createReactiveStore } from '../core/reactive.js';
|
||||||
import { callSidecarApi, getWindowBridgeConfig, isWindowOverlayMode } from '../core/httpClient.js';
|
import {
|
||||||
|
abortSidecarApiKey,
|
||||||
|
callSidecarApi,
|
||||||
|
getWindowBridgeConfig,
|
||||||
|
isWindowOverlayMode,
|
||||||
|
} from '../core/httpClient.js';
|
||||||
import {
|
import {
|
||||||
formatAgentBadgeText,
|
formatAgentBadgeText,
|
||||||
formatAgentLabel,
|
formatAgentLabel,
|
||||||
@@ -139,9 +144,11 @@ export const telemetryStore = createReactiveStore({
|
|||||||
|
|
||||||
let pollTimer = null;
|
let pollTimer = null;
|
||||||
let feedbackTimer = null;
|
let feedbackTimer = null;
|
||||||
|
let deferredConvSyncTimer = null;
|
||||||
let activeBundleVersion = 0;
|
let activeBundleVersion = 0;
|
||||||
let latestRequestSeq = 0;
|
let latestRequestSeq = 0;
|
||||||
let latestConsumptionReqSeq = 0;
|
let latestConsumptionReqSeq = 0;
|
||||||
|
let latestConversationSwitchSeq = 0;
|
||||||
let activeForceCount = 0;
|
let activeForceCount = 0;
|
||||||
let consecutivePollFailures = 0;
|
let consecutivePollFailures = 0;
|
||||||
let inFlightTelemetryPoll = null;
|
let inFlightTelemetryPoll = null;
|
||||||
@@ -149,8 +156,10 @@ let inFlightPresetsPrefetch = null;
|
|||||||
let lastPrefetchedUsageRevision = 0;
|
let lastPrefetchedUsageRevision = 0;
|
||||||
let consumptionCacheScopeSig = '';
|
let consumptionCacheScopeSig = '';
|
||||||
const MAX_CONSUMPTION_RANGE_CACHE = 12;
|
const MAX_CONSUMPTION_RANGE_CACHE = 12;
|
||||||
|
const MAX_CONVERSATION_VIEW_CACHE = 12;
|
||||||
const CONSUMPTION_PRESET_KEYS = ['cycle', 'today', '24h', '7d', '14d', '30d', 'all'];
|
const CONSUMPTION_PRESET_KEYS = ['cycle', 'today', '24h', '7d', '14d', '30d', 'all'];
|
||||||
const consumptionRangeCache = new Map();
|
const consumptionRangeCache = new Map();
|
||||||
|
const conversationViewCache = new Map();
|
||||||
let lastReceivedSteps = null;
|
let lastReceivedSteps = null;
|
||||||
let loopActive = false;
|
let loopActive = false;
|
||||||
let loopIntervalMs = 2000;
|
let loopIntervalMs = 2000;
|
||||||
@@ -182,6 +191,14 @@ export function clearConsumptionRangeCache() {
|
|||||||
inFlightPresetsPrefetch = null;
|
inFlightPresetsPrefetch = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function clearConversationViewCache() {
|
||||||
|
conversationViewCache.clear();
|
||||||
|
if (deferredConvSyncTimer) {
|
||||||
|
clearTimeout(deferredConvSyncTimer);
|
||||||
|
deferredConvSyncTimer = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function buildConsumptionScopeSig(payload) {
|
function buildConsumptionScopeSig(payload) {
|
||||||
if (!payload || typeof payload !== 'object') return '';
|
if (!payload || typeof payload !== 'object') return '';
|
||||||
const acct = payload.account || {};
|
const acct = payload.account || {};
|
||||||
@@ -195,10 +212,112 @@ function syncConsumptionCacheScope(payload) {
|
|||||||
if (!nextSig) return;
|
if (!nextSig) return;
|
||||||
if (consumptionCacheScopeSig && consumptionCacheScopeSig !== nextSig) {
|
if (consumptionCacheScopeSig && consumptionCacheScopeSig !== nextSig) {
|
||||||
clearConsumptionRangeCache();
|
clearConsumptionRangeCache();
|
||||||
|
clearConversationViewCache();
|
||||||
}
|
}
|
||||||
consumptionCacheScopeSig = nextSig;
|
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) {
|
function putConsumptionRangeCacheEntry(cacheKey, entry) {
|
||||||
if (!cacheKey || !entry) return;
|
if (!cacheKey || !entry) return;
|
||||||
consumptionRangeCache.delete(cacheKey);
|
consumptionRangeCache.delete(cacheKey);
|
||||||
@@ -1012,6 +1131,7 @@ async function requestTelemetry(params, force) {
|
|||||||
|
|
||||||
let resolvedPayload = reconcileIncomingTelemetrySettings(payload, reqSettingsRev);
|
let resolvedPayload = reconcileIncomingTelemetrySettings(payload, reqSettingsRev);
|
||||||
syncConsumptionCacheScope(resolvedPayload);
|
syncConsumptionCacheScope(resolvedPayload);
|
||||||
|
recordConversationViewToCache(resolvedPayload);
|
||||||
if (resolvedPayload?.consumption) {
|
if (resolvedPayload?.consumption) {
|
||||||
recordConsumptionSliceToCache(resolvedPayload.consumption, resolvedPayload.modelBreakdown, {
|
recordConsumptionSliceToCache(resolvedPayload.consumption, resolvedPayload.modelBreakdown, {
|
||||||
customStartMs: reqStartMs,
|
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 请求);
|
* - 命中前端 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));
|
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();
|
clearConsumptionRangeCache();
|
||||||
|
clearConversationViewCache();
|
||||||
}
|
}
|
||||||
if (needsTelemetryRecompute) {
|
if (needsTelemetryRecompute) {
|
||||||
inFlightTelemetryPoll = null;
|
inFlightTelemetryPoll = null;
|
||||||
@@ -1549,6 +1830,7 @@ export async function resetAllSettings() {
|
|||||||
}
|
}
|
||||||
inFlightTelemetryPoll = null;
|
inFlightTelemetryPoll = null;
|
||||||
clearConsumptionRangeCache();
|
clearConsumptionRangeCache();
|
||||||
|
clearConversationViewCache();
|
||||||
void fetchTelemetry({ force: false });
|
void fetchTelemetry({ force: false });
|
||||||
return res;
|
return res;
|
||||||
}
|
}
|
||||||
@@ -1556,6 +1838,7 @@ export async function resetAllSettings() {
|
|||||||
export async function rebuildTrajectoryCache() {
|
export async function rebuildTrajectoryCache() {
|
||||||
const res = await callSidecarApi('/api/cache/rebuild', { method: 'POST', body: {} });
|
const res = await callSidecarApi('/api/cache/rebuild', { method: 'POST', body: {} });
|
||||||
clearConsumptionRangeCache();
|
clearConsumptionRangeCache();
|
||||||
|
clearConversationViewCache();
|
||||||
await fetchTelemetry({ force: true });
|
await fetchTelemetry({ force: true });
|
||||||
return res;
|
return res;
|
||||||
}
|
}
|
||||||
@@ -1563,6 +1846,7 @@ export async function rebuildTrajectoryCache() {
|
|||||||
export async function triggerCloudSync() {
|
export async function triggerCloudSync() {
|
||||||
const res = await callSidecarApi('/api/cloud-sync', { method: 'POST', body: {} });
|
const res = await callSidecarApi('/api/cloud-sync', { method: 'POST', body: {} });
|
||||||
clearConsumptionRangeCache();
|
clearConsumptionRangeCache();
|
||||||
|
clearConversationViewCache();
|
||||||
await fetchTelemetry({ force: true });
|
await fetchTelemetry({ force: true });
|
||||||
return res;
|
return res;
|
||||||
}
|
}
|
||||||
@@ -1636,6 +1920,10 @@ export function stopAsyncTelemetryLoop() {
|
|||||||
clearTimeout(feedbackTimer);
|
clearTimeout(feedbackTimer);
|
||||||
feedbackTimer = null;
|
feedbackTimer = null;
|
||||||
}
|
}
|
||||||
|
if (deferredConvSyncTimer) {
|
||||||
|
clearTimeout(deferredConvSyncTimer);
|
||||||
|
deferredConvSyncTimer = null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export {
|
export {
|
||||||
|
|||||||
@@ -684,6 +684,8 @@
|
|||||||
|
|
||||||
.cons-source-row {
|
.cons-source-row {
|
||||||
gap: 5px;
|
gap: 5px;
|
||||||
|
width: 100%;
|
||||||
|
container-type: inline-size;
|
||||||
}
|
}
|
||||||
|
|
||||||
.cons-source-bar-hit {
|
.cons-source-bar-hit {
|
||||||
@@ -698,8 +700,90 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.cons-source-foot {
|
.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;
|
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 {
|
.month-col.is-interactive {
|
||||||
|
|||||||
@@ -730,8 +730,23 @@ export const ConsumptionView = defineComponent({
|
|||||||
return { el: segEl, refs: { segEl } };
|
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() {
|
function createSourceBreakdownRow() {
|
||||||
const nameTextEl = h('span', { className: 'cons-row-title-text' });
|
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 costEl = h('strong', { className: 'cons-row-cost text-mono' });
|
||||||
const trackEl = h('div', { className: 'progress-track cons-seg-bar cons-source-model-bar' });
|
const trackEl = h('div', { className: 'progress-track cons-seg-bar cons-source-model-bar' });
|
||||||
const rowState = { hoverPayload: null };
|
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(
|
const barHitEl = h(
|
||||||
'div',
|
'div',
|
||||||
{
|
{
|
||||||
className: 'cons-source-bar-hit',
|
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]
|
[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 callsLbl = h('span', { text: t('cons.footCalls') });
|
||||||
const callsVal = h('strong', { className: 'text-mono' });
|
const callsVal = h('strong', { className: 'text-mono' });
|
||||||
|
|
||||||
@@ -775,6 +803,7 @@ export const ConsumptionView = defineComponent({
|
|||||||
]),
|
]),
|
||||||
barHitEl,
|
barHitEl,
|
||||||
h('div', { className: 'cons-item-foot cons-source-foot' }, [
|
h('div', { className: 'cons-item-foot cons-source-foot' }, [
|
||||||
|
topModelsEl,
|
||||||
h('span', { className: 'legend-left cons-calls-stat' }, [
|
h('span', { className: 'legend-left cons-calls-stat' }, [
|
||||||
callsLbl,
|
callsLbl,
|
||||||
callsVal,
|
callsVal,
|
||||||
@@ -792,6 +821,7 @@ export const ConsumptionView = defineComponent({
|
|||||||
costEl,
|
costEl,
|
||||||
barHitEl,
|
barHitEl,
|
||||||
trackEl,
|
trackEl,
|
||||||
|
topModelsEl,
|
||||||
callsLbl,
|
callsLbl,
|
||||||
callsVal,
|
callsVal,
|
||||||
rowState,
|
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 =
|
refs.rowState.hoverPayload =
|
||||||
total > 0 || callsCount > 0
|
total > 0 || callsCount > 0
|
||||||
? {
|
? {
|
||||||
|
|||||||
@@ -2698,6 +2698,8 @@ html[data-standalone="true"] .app-shell {
|
|||||||
|
|
||||||
.cons-source-row {
|
.cons-source-row {
|
||||||
gap: 5px;
|
gap: 5px;
|
||||||
|
width: 100%;
|
||||||
|
container-type: inline-size;
|
||||||
}
|
}
|
||||||
|
|
||||||
.cons-source-bar-hit {
|
.cons-source-bar-hit {
|
||||||
@@ -2712,8 +2714,90 @@ html[data-standalone="true"] .app-shell {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.cons-source-foot {
|
.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;
|
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 {
|
.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], /force=1/);
|
||||||
assert.doesNotMatch(requestedUrls[0], /fastRange=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);
|
.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}`);
|
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);
|
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');
|
const appSegs = sourceRows[0].querySelectorAll('.cons-model-seg');
|
||||||
assert.equal(appSegs.length, 4, '3 main models + 1 merged other segment');
|
assert.equal(appSegs.length, 4, '3 main models + 1 merged other segment');
|
||||||
assert.equal(appSegs[0].style.getPropertyValue('--seg-color'), argonDotColor);
|
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);
|
const appBarSum = appSegs.reduce((s, el) => s + parsePctVar(el, '--seg-w'), 0);
|
||||||
assert.ok(Math.abs(appBarSum - 80) < 0.1);
|
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;
|
const popover = view.refs.breakdownPopoverEl;
|
||||||
assert.equal(popover.hasAttribute('hidden'), true);
|
assert.equal(popover.hasAttribute('hidden'), true);
|
||||||
const appBarHit = sourceRows[0].querySelector('.cons-source-bar-hit');
|
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' });
|
appBarHit.dispatchEvent({ type: 'mouseleave' });
|
||||||
assert.equal(popover.hasAttribute('hidden'), true);
|
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
|
// 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);
|
assert.equal(view.el.querySelectorAll('.monthly-legend').length, 0);
|
||||||
const monthCols = view.el.querySelectorAll('.month-col');
|
const monthCols = view.el.querySelectorAll('.month-col');
|
||||||
|
|||||||
Reference in New Issue
Block a user