mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-27 01:19:25 +08:00
perf(panel): add incremental step transport, memoized aggregation, atomic cache writes, and hidden-view gating
- Project display-only step fields in /api/telemetry, skip unchanged step payloads via stepRevision, coalesce identical client refreshes, and share in-flight backend trajectory scans across same-account requests - Reuse normalized step values and memoize up to two range aggregations in usage-aggregator gated by step timestamps, pricing revision, model overrides, timezone, and source identity; cache per-trajectory model facts and single-agent step preparation via WeakMap/WeakRef - Persist trajectory checkpoints atomically in trajectory-cache-file.mjs via chunked writevSync + renameSync while reusing serialized step byte slices for unchanged conversations - Render step turn-rail lines/dots via CSS pseudo-elements, allocate speed-reason nodes on demand, short-circuit unchanged table reconciliations, and cache per-series LOESS publication fits in SessionStepCharts - Gate DOM updates and timers across closed overlay panels, hover popups, inactive settings tabs, and unchanged ConsumptionView payloads - Distinguish canceled steps (CORTEX_STEP_STATUS_CANCELED) and untimed compaction steps from generic incomplete timing in speed-metrics and bilingual i18n labels
This commit is contained in:
@@ -8,6 +8,8 @@
|
||||
|
||||
import { readFileSync, promises as fsPromises } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { isDeepStrictEqual } from 'node:util';
|
||||
import { handleAccountCredentialAction } from './account-switch.mjs';
|
||||
import {
|
||||
HERE,
|
||||
@@ -110,6 +112,84 @@ function sanitizePositiveFiniteMs(val) {
|
||||
return Number.isFinite(num) && num > 0 && num <= MAX_SAFE_DATE_MS ? Math.floor(num) : 0;
|
||||
}
|
||||
|
||||
function projectDisplayStep(st) {
|
||||
const {
|
||||
stepIndex, createdAtMs, isCompactionStep, modelKey, modelShort, modelLabel,
|
||||
modelUpstream, responseModel, modelSource, tokPerSec, ttftSec, totalDurationSec,
|
||||
streamDurationSec, selectedSpeedReason, contextTokens, inputTokens, cacheReadTokens,
|
||||
outputTokens, thinkingTokens, responseTokens, cacheHitPct, costUsd, agentId,
|
||||
agentCascadeId, agentLabel, agentBadge, agentRole, agentIndex, isSubagent,
|
||||
turnIndex, isTurnStart, isLatestTurn, turnPrompt, rootTurnIndex, isRootTurnStart,
|
||||
isRootLatestTurn, rootTurnPrompt,
|
||||
} = st;
|
||||
return {
|
||||
stepIndex, createdAtMs, isCompactionStep, modelKey, modelShort, modelLabel,
|
||||
modelUpstream, responseModel, modelSource, tokPerSec, ttftSec, totalDurationSec,
|
||||
streamDurationSec, selectedSpeedReason, contextTokens, inputTokens, cacheReadTokens,
|
||||
outputTokens, thinkingTokens, responseTokens, cacheHitPct, costUsd, agentId,
|
||||
agentCascadeId, agentLabel, agentBadge, agentRole, agentIndex, isSubagent,
|
||||
turnIndex, isTurnStart, isLatestTurn, turnPrompt, rootTurnIndex, isRootTurnStart,
|
||||
isRootLatestTurn, rootTurnPrompt,
|
||||
};
|
||||
}
|
||||
|
||||
let lastDisplaySteps = null;
|
||||
const displayStepFields = Object.keys(projectDisplayStep({}));
|
||||
|
||||
function haveSameDisplaySteps(previous, current) {
|
||||
if (!previous || !current) return previous === current;
|
||||
if (previous.length !== current.length) return false;
|
||||
for (let i = 0; i < current.length; i++) {
|
||||
const before = previous[i];
|
||||
const after = current[i];
|
||||
for (const key of displayStepFields) {
|
||||
if (before[key] !== after[key]) return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function projectDisplayTelemetry(payload, requestedRevision) {
|
||||
const active = payload.activeConversation;
|
||||
const agents = active.agents;
|
||||
const sourceSteps = [active.recentSteps, ...agents.map((agent) => agent.recentSteps)];
|
||||
let projected;
|
||||
let revision;
|
||||
if (typeof requestedRevision === 'string') {
|
||||
const scope = [
|
||||
payload.account?.status,
|
||||
payload.account?.email || payload.account?.name || '',
|
||||
active.cascadeId,
|
||||
...agents.map((agent) => agent.agentId),
|
||||
];
|
||||
const previous = lastDisplaySteps;
|
||||
if (previous && isDeepStrictEqual(scope, previous.scope) &&
|
||||
sourceSteps.every((steps, index) => (steps && previous.sources[index]?.deref() === steps) ||
|
||||
haveSameDisplaySteps(previous.steps[index], steps))) {
|
||||
({ revision, steps: projected } = previous);
|
||||
previous.sources = sourceSteps.map((steps) => steps ? new WeakRef(steps) : undefined);
|
||||
} else {
|
||||
revision = randomUUID();
|
||||
projected = sourceSteps.map((steps) => steps?.map(projectDisplayStep));
|
||||
lastDisplaySteps = { scope, steps: projected, revision,
|
||||
sources: sourceSteps.map((steps) => steps ? new WeakRef(steps) : undefined) };
|
||||
}
|
||||
}
|
||||
projected ||= sourceSteps.map((steps) => steps?.map(projectDisplayStep));
|
||||
const stepsUnchanged = revision !== undefined && requestedRevision === revision;
|
||||
return {
|
||||
...payload,
|
||||
...(revision ? { stepRevision: revision, stepsUnchanged } : {}),
|
||||
activeConversation: {
|
||||
...active,
|
||||
recentSteps: stepsUnchanged ? undefined : projected[0],
|
||||
agents: agents.map((agent, index) => projected[index + 1]
|
||||
? { ...agent, recentSteps: stepsUnchanged ? undefined : projected[index + 1] }
|
||||
: agent),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function executeTelemetryAction(data, { onRestart = null } = {}) {
|
||||
const rawConvId = String(
|
||||
data?.conversationId || process.env.ANTIGRAVITY_CONVERSATION_ID || ''
|
||||
@@ -148,11 +228,14 @@ export async function executeTelemetryAction(data, { onRestart = null } = {}) {
|
||||
scheduleSidecarRestart(150);
|
||||
}
|
||||
}
|
||||
const responsePayload = data?.stepDetails === 'display'
|
||||
? projectDisplayTelemetry(payload, data.stepRevision)
|
||||
: payload;
|
||||
return {
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
headers: { 'Cache-Control': 'no-store' },
|
||||
body: JSON.stringify(payload),
|
||||
body: JSON.stringify(responsePayload),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ import { homedir } from 'node:os';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { inferCompactionStepModels, normalizeCachedStep } from '../speed-metrics.mjs';
|
||||
import { writeTrajectoryCacheFile } from './trajectory-cache-file.mjs';
|
||||
import {
|
||||
DEFAULT_HOVER_MODULES,
|
||||
DEFAULT_OVERVIEW_METRICS,
|
||||
@@ -227,9 +228,11 @@ export function loadJson(filePath, fallback) {
|
||||
export function saveJson(filePath, data) {
|
||||
try {
|
||||
mkdirSync(DATA_DIR, { recursive: true });
|
||||
const serialized =
|
||||
filePath === CACHE_FILE ? JSON.stringify(data) : JSON.stringify(data, null, 2);
|
||||
writeFileSync(filePath, serialized, 'utf8');
|
||||
if (filePath === CACHE_FILE) {
|
||||
writeTrajectoryCacheFile(filePath, data);
|
||||
} else {
|
||||
writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf8');
|
||||
}
|
||||
return true;
|
||||
} catch (err) {
|
||||
console.error(`Failed writing ${filePath}: ${err.message}`);
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
|
||||
import { closeSync, existsSync, openSync, readFileSync, readSync, readdirSync, statSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { isDeepStrictEqual } from 'node:util';
|
||||
import {
|
||||
extractLiveActivity,
|
||||
extractModelSteps,
|
||||
@@ -905,8 +906,9 @@ export async function enumerateAndSyncConversations({
|
||||
!prev.turnRailTelemetry ||
|
||||
!prev.contextGroupsTelemetry ||
|
||||
metaChanged ||
|
||||
JSON.stringify(prev.steps) !== JSON.stringify(steps);
|
||||
!isDeepStrictEqual(prev.steps, steps);
|
||||
|
||||
if (!stepsChanged) cacheEntry.steps = prev.steps;
|
||||
trajectoryCache[conv.cascadeId] = cacheEntry;
|
||||
if (stepsChanged) {
|
||||
cacheDirty = true;
|
||||
|
||||
@@ -288,11 +288,16 @@ export function createStepModelResolver(dynamicModelMap) {
|
||||
) {
|
||||
return resolveModelInfo(modelKey, dynamicModelMap, apiProvider, modelDisplayName, responseModel);
|
||||
}
|
||||
const key = JSON.stringify([modelKey, apiProvider, modelDisplayName, responseModel]);
|
||||
let info = models.get(key);
|
||||
let providers = models.get(modelKey);
|
||||
if (!providers) models.set(modelKey, (providers = new Map()));
|
||||
let names = providers.get(apiProvider);
|
||||
if (!names) providers.set(apiProvider, (names = new Map()));
|
||||
let responses = names.get(modelDisplayName);
|
||||
if (!responses) names.set(modelDisplayName, (responses = new Map()));
|
||||
let info = responses.get(responseModel);
|
||||
if (!info) {
|
||||
info = resolveModelInfo(modelKey, dynamicModelMap, apiProvider, modelDisplayName, responseModel);
|
||||
models.set(key, info);
|
||||
responses.set(responseModel, info);
|
||||
}
|
||||
return info;
|
||||
};
|
||||
|
||||
@@ -32,6 +32,7 @@ import {
|
||||
*/
|
||||
export const MODEL_PRICING = {};
|
||||
export const PLACEHOLDER_MAP = {};
|
||||
export let pricingCatalogRevision = 0;
|
||||
|
||||
/**
|
||||
* 校验字符串是否为合法的 SemVer 2.0 语义化版本号格式(支持 `-prerelease` 与 `+build` 元数据)。
|
||||
@@ -361,6 +362,7 @@ export function rebuildActiveCatalog() {
|
||||
|
||||
for (const k of Object.keys(PLACEHOLDER_MAP)) delete PLACEHOLDER_MAP[k];
|
||||
Object.assign(PLACEHOLDER_MAP, nextPlaceholders);
|
||||
pricingCatalogRevision += 1;
|
||||
|
||||
cloudSyncState.source = activeSource;
|
||||
cloudSyncState.catalogVersion = catalogVersion;
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
* 5. 调用 `aggregateMultiWindowUsage` 完成全量多窗口聚合,并组装精简的前端遥测 JSON。
|
||||
*/
|
||||
|
||||
import { isDeepStrictEqual } from 'node:util';
|
||||
import {
|
||||
extractLiveActivity,
|
||||
parseIsoMs,
|
||||
@@ -33,7 +34,7 @@ import {
|
||||
isArgonModelIdentifier,
|
||||
isCarbonModelIdentifier,
|
||||
} from './model-pricing.mjs';
|
||||
import { getCloudStatus } from './pricing-catalog.mjs';
|
||||
import { getCloudStatus, pricingCatalogRevision } from './pricing-catalog.mjs';
|
||||
import { buildOfficialQuotaPools } from './quota-pools.mjs';
|
||||
import {
|
||||
aggregateMultiWindowUsage,
|
||||
@@ -43,6 +44,9 @@ import {
|
||||
|
||||
const MAX_RECENT_CONVERSATIONS = 30;
|
||||
const POOL_PRIORITY_ORDER = ['Gemini', 'Argon', 'Carbon', 'Claude & GPT'];
|
||||
const inFlightTelemetrySources = new Map();
|
||||
const trajectoryModelFacts = new WeakMap();
|
||||
let lastMainPreparation = null;
|
||||
|
||||
function roundSessionCost(val) {
|
||||
if (!Number.isFinite(val) || val <= 0) return 0;
|
||||
@@ -59,24 +63,50 @@ function findTrajectoryCacheEntry(cascadeId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建全局 `modelKey -> responseModel` 已知映射表(单次轮询仅扫描一次 `trajectoryCache`)。
|
||||
*
|
||||
* @returns {Map<string, string>}
|
||||
*/
|
||||
function rememberModelContextLimit(limits, step) {
|
||||
const previous = limits.get(step.modelKey);
|
||||
if (!previous || step.createdAtMs > previous.at) {
|
||||
limits.set(step.modelKey, { tokens: step.reportedContextLimitTokens, at: step.createdAtMs });
|
||||
}
|
||||
}
|
||||
|
||||
function readTrajectoryModelFacts(steps) {
|
||||
const cached = trajectoryModelFacts.get(steps);
|
||||
if (cached) return cached;
|
||||
const upstream = new Map();
|
||||
const limits = new Map();
|
||||
let sortableLimits = true;
|
||||
for (const step of steps) {
|
||||
if (step?.modelKey && step.modelKey !== 'unknown' && step.responseModel) {
|
||||
upstream.set(step.modelKey, step.responseModel);
|
||||
}
|
||||
if (!step?.isCompactionStep && step?.reportedContextLimitTokens > 0) {
|
||||
sortableLimits &&= Number.isFinite(step.createdAtMs);
|
||||
rememberModelContextLimit(limits, step);
|
||||
}
|
||||
}
|
||||
const result = { upstream, limits: sortableLimits ? limits : null };
|
||||
trajectoryModelFacts.set(steps, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
/** 合并各会话的上游模型与上下文上限,步骤数组更新后重新提取对应会话的数据。 */
|
||||
function buildKnownUpstreamModelMap(contextLimits, currentAccountName) {
|
||||
const knownUpstreamByModelKey = new Map();
|
||||
for (const entry of Object.values(trajectoryCache)) {
|
||||
const trackContext = contextLimits && !entry.subagentSpec &&
|
||||
(!entry.accountName || entry.accountName === currentAccountName);
|
||||
for (const s of entry?.steps || []) {
|
||||
if (s?.modelKey && s.modelKey !== 'unknown' && s.responseModel) {
|
||||
knownUpstreamByModelKey.set(s.modelKey, s.responseModel);
|
||||
if (!entry?.steps?.length) continue;
|
||||
const facts = readTrajectoryModelFacts(entry.steps);
|
||||
for (const [key, model] of facts.upstream) knownUpstreamByModelKey.set(key, model);
|
||||
if (entry.subagentSpec || (entry.accountName && entry.accountName !== currentAccountName)) continue;
|
||||
if (facts.limits) {
|
||||
for (const [key, limit] of facts.limits) {
|
||||
const previous = contextLimits.get(key);
|
||||
if (!previous || limit.at > previous.at) contextLimits.set(key, limit);
|
||||
}
|
||||
if (trackContext && !s.isCompactionStep && s.reportedContextLimitTokens > 0) {
|
||||
const prev = contextLimits.get(s.modelKey);
|
||||
if (!prev || s.createdAtMs > prev.at) {
|
||||
contextLimits.set(s.modelKey, { tokens: s.reportedContextLimitTokens, at: s.createdAtMs });
|
||||
} else {
|
||||
for (const step of entry.steps) {
|
||||
if (!step?.isCompactionStep && step?.reportedContextLimitTokens > 0) {
|
||||
rememberModelContextLimit(contextLimits, step);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -90,12 +120,14 @@ function buildKnownUpstreamModelMap(contextLimits, currentAccountName) {
|
||||
*
|
||||
* @param {object[]} activeSteps 当前会话的原始缓存步骤
|
||||
* @param {ReturnType<typeof createStepModelResolver>} resolveStepModel 模型身份与价格解析器
|
||||
* @param {Map<string, string>} [sharedUpstreamMap=null] 预先构建的已知上游模型映射表
|
||||
* @param {Map<string, string>} sharedUpstreamMap 预先构建的已知上游模型映射表
|
||||
* @param {object} agentFields 步骤所属代理的标签和标识
|
||||
*/
|
||||
function enrichActiveConversationSteps(
|
||||
activeSteps,
|
||||
resolveStepModel,
|
||||
sharedUpstreamMap = null
|
||||
sharedUpstreamMap,
|
||||
agentFields
|
||||
) {
|
||||
const sessionSpeed = summarizeSpeed(activeSteps);
|
||||
const sessionTtft = summarizeTtft(activeSteps);
|
||||
@@ -105,13 +137,7 @@ function enrichActiveConversationSteps(
|
||||
let sessionCacheReadTokens = 0;
|
||||
let sessionOutputTokens = 0;
|
||||
|
||||
const knownUpstreamByModelKey = sharedUpstreamMap || buildKnownUpstreamModelMap();
|
||||
for (const s of activeSteps) {
|
||||
if (s?.modelKey && s.modelKey !== 'unknown' && s.responseModel) {
|
||||
knownUpstreamByModelKey.set(s.modelKey, s.responseModel);
|
||||
}
|
||||
}
|
||||
|
||||
const knownUpstreamByModelKey = sharedUpstreamMap;
|
||||
const enrichedActiveSteps = activeSteps.map((st) => {
|
||||
const mInfo = resolveStepModel(st);
|
||||
const costUsd = computeStepCost(st, mInfo.pricing);
|
||||
@@ -121,7 +147,8 @@ function enrichActiveConversationSteps(
|
||||
if (costUsd === null) sessionUnpricedCalls++;
|
||||
sessionInputTokens += st.inputTokens;
|
||||
sessionCacheReadTokens += st.cacheReadTokens;
|
||||
sessionOutputTokens += resolveStepOutputTokens(st);
|
||||
const outputTokens = resolveStepOutputTokens(st);
|
||||
sessionOutputTokens += outputTokens;
|
||||
|
||||
const tokPerSec = metric.value;
|
||||
const totalPrompt = st.inputTokens + st.cacheReadTokens;
|
||||
@@ -167,7 +194,8 @@ function enrichActiveConversationSteps(
|
||||
inCostUsd: inCostUsd === null ? null : +inCostUsd.toFixed(4),
|
||||
cacheCostUsd: cacheCostUsd === null ? null : +cacheCostUsd.toFixed(4),
|
||||
outCostUsd: outCostUsd === null ? null : +outCostUsd.toFixed(4),
|
||||
contextTokens: st.inputTokens + st.cacheReadTokens + resolveStepOutputTokens(st),
|
||||
contextTokens: totalPrompt + outputTokens,
|
||||
...agentFields,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -450,6 +478,30 @@ function extractActiveContextTelemetry(
|
||||
};
|
||||
}
|
||||
|
||||
function prepareAgentSteps(rawSteps, resolveStepModel, upstream, agentFields, reuseInputs) {
|
||||
for (const [key, model] of readTrajectoryModelFacts(rawSteps).upstream) upstream.set(key, model);
|
||||
const previous = lastMainPreparation;
|
||||
if (reuseInputs && previous?.rawSteps === rawSteps &&
|
||||
isDeepStrictEqual(previous.inputs, reuseInputs) && isDeepStrictEqual(previous.upstream, upstream)) {
|
||||
const prepared = previous.prepared.deref();
|
||||
if (prepared) return prepared;
|
||||
}
|
||||
const enrichedRes = enrichActiveConversationSteps(rawSteps, resolveStepModel, upstream, agentFields);
|
||||
const taggedSteps = enrichedRes.enrichedActiveSteps;
|
||||
const prepared = {
|
||||
enrichedRes,
|
||||
recentSteps: taggedSteps.slice().reverse(),
|
||||
ctxRes: extractActiveContextTelemetry(taggedSteps, enrichedRes.latestEnriched,
|
||||
enrichedRes.sessionInputTokens, enrichedRes.sessionCacheReadTokens),
|
||||
modelBreakdown: buildScopedModelBreakdown(taggedSteps, resolveStepModel),
|
||||
};
|
||||
// 单代理行可跨轮询复用。内存紧张时允许回收,运行状态仍单独实时组装。
|
||||
if (reuseInputs) {
|
||||
lastMainPreparation = { rawSteps, inputs: reuseInputs, upstream, prepared: new WeakRef(prepared) };
|
||||
}
|
||||
return prepared;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建单个代理(主代理或子代理)的标准遥测单元对象。
|
||||
*/
|
||||
@@ -470,29 +522,24 @@ function buildAgentUnitTelemetry({
|
||||
resolveStepModel,
|
||||
knownUpstreamByModelKey,
|
||||
includeRecentSteps = true,
|
||||
reuseInputs = null,
|
||||
}) {
|
||||
const enrichedRes = enrichActiveConversationSteps(
|
||||
const { enrichedRes, ctxRes, modelBreakdown, recentSteps } = prepareAgentSteps(
|
||||
rawSteps,
|
||||
resolveStepModel,
|
||||
knownUpstreamByModelKey
|
||||
knownUpstreamByModelKey,
|
||||
{
|
||||
agentId,
|
||||
agentCascadeId: cascadeId,
|
||||
agentLabel,
|
||||
agentBadge: badgeText,
|
||||
agentRole: role,
|
||||
agentIndex: index,
|
||||
isSubagent: !isMain,
|
||||
},
|
||||
reuseInputs
|
||||
);
|
||||
const taggedSteps = enrichedRes.enrichedActiveSteps.map((st) => ({
|
||||
...st,
|
||||
agentId,
|
||||
agentCascadeId: cascadeId,
|
||||
agentLabel,
|
||||
agentBadge: badgeText,
|
||||
agentRole: role,
|
||||
agentIndex: index,
|
||||
isSubagent: !isMain,
|
||||
}));
|
||||
const ctxRes = extractActiveContextTelemetry(
|
||||
taggedSteps,
|
||||
enrichedRes.latestEnriched,
|
||||
enrichedRes.sessionInputTokens,
|
||||
enrichedRes.sessionCacheReadTokens
|
||||
);
|
||||
const modelBreakdown = buildScopedModelBreakdown(taggedSteps, resolveStepModel);
|
||||
const taggedSteps = enrichedRes.enrichedActiveSteps;
|
||||
const lastModifiedMs =
|
||||
enrichedRes.latestEnriched?.createdAtMs || fallbackLastModMs || 0;
|
||||
const isRunning = status === 'CASCADE_RUN_STATUS_RUNNING';
|
||||
@@ -504,6 +551,7 @@ function buildAgentUnitTelemetry({
|
||||
return {
|
||||
enrichedRes,
|
||||
taggedSteps,
|
||||
recentSteps,
|
||||
ctxRes,
|
||||
telemetryUnit: {
|
||||
agentId,
|
||||
@@ -547,13 +595,44 @@ function buildAgentUnitTelemetry({
|
||||
enrichedRes.latestEnriched?.modelShort ||
|
||||
'模型未知',
|
||||
context: ctxRes.context,
|
||||
...(includeRecentSteps ? { recentSteps: taggedSteps.slice().reverse() } : {}),
|
||||
...(includeRecentSteps ? { recentSteps } : {}),
|
||||
modelBreakdown,
|
||||
lastModifiedMs,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function readTelemetrySources(requestedConvId, forceQuotaRefresh, currentAccountName, accountScope, userStatus) {
|
||||
const [allTrajRes, officialQuotaInfo, contextModelCatalog] = await Promise.all([
|
||||
callLsRpc('GetAllCascadeTrajectories', {}).catch(() => ({})),
|
||||
userStatus ? getOfficialQuotaSummary(forceQuotaRefresh, currentAccountName) : null,
|
||||
getContextModelCatalog(),
|
||||
]);
|
||||
|
||||
const sessions = await enumerateAndSyncConversations({
|
||||
summariesObj: allTrajRes?.trajectorySummaries || {},
|
||||
currentAccountName: accountScope,
|
||||
requestedConvId,
|
||||
forceRefresh: forceQuotaRefresh,
|
||||
});
|
||||
return { officialQuotaInfo, contextModelCatalog, sessions };
|
||||
}
|
||||
|
||||
function getTelemetrySources(requestedConvId, forceQuotaRefresh, currentAccountName, accountScope, userStatus) {
|
||||
const read = () => readTelemetrySources(
|
||||
requestedConvId, forceQuotaRefresh, currentAccountName, accountScope, userStatus
|
||||
);
|
||||
if (forceQuotaRefresh) return read();
|
||||
const key = JSON.stringify([requestedConvId || '', accountScope, Boolean(userStatus)]);
|
||||
const existing = inFlightTelemetrySources.get(key);
|
||||
if (existing) return existing;
|
||||
const pending = read().finally(() => {
|
||||
inFlightTelemetrySources.delete(key);
|
||||
});
|
||||
inFlightTelemetrySources.set(key, pending);
|
||||
return pending;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建完整的前端遥测载荷(核心内部实现,直接供单元测试沙箱调用)。
|
||||
*
|
||||
@@ -573,11 +652,10 @@ export async function buildTelemetryPayloadInternal(
|
||||
const accountStatus = currentAccountName ? 'signedIn' :
|
||||
userStatus && !userStatus.userTier && !userStatus.planStatus ? 'signedOut' : 'unknown';
|
||||
const accountScope = accountStatus === 'signedOut' ? null : currentAccountName;
|
||||
const [allTrajRes, officialQuotaInfo, contextModelCatalog] = await Promise.all([
|
||||
callLsRpc('GetAllCascadeTrajectories', {}).catch(() => ({})),
|
||||
userStatus ? getOfficialQuotaSummary(forceQuotaRefresh, currentAccountName) : null,
|
||||
getContextModelCatalog(),
|
||||
]);
|
||||
const { officialQuotaInfo, contextModelCatalog, sessions } = await getTelemetrySources(
|
||||
requestedConvId, forceQuotaRefresh, currentAccountName, accountScope, userStatus
|
||||
);
|
||||
const { conversations, activeConvSummary, activeCascadeId } = sessions;
|
||||
|
||||
const officialQuota = officialQuotaInfo?.data || null;
|
||||
const clientConfigs = userStatus?.cascadeModelConfigData?.clientModelConfigs || [];
|
||||
@@ -588,14 +666,6 @@ export async function buildTelemetryPayloadInternal(
|
||||
clientConfigs
|
||||
);
|
||||
|
||||
// 2. 枚举本地与 LS 会话,并增量同步历史轨迹步骤
|
||||
const { conversations, activeConvSummary, activeCascadeId } =
|
||||
await enumerateAndSyncConversations({
|
||||
summariesObj: allTrajRes?.trajectorySummaries || {},
|
||||
currentAccountName: accountScope,
|
||||
requestedConvId,
|
||||
forceRefresh: forceQuotaRefresh,
|
||||
});
|
||||
const resolveStepModel = createStepModelResolver(dynamicModelMap);
|
||||
|
||||
// 3. 计算当前活跃根会话及其子代理的步骤指标、10 通道上下文拆解与按模型汇总
|
||||
@@ -603,6 +673,9 @@ export async function buildTelemetryPayloadInternal(
|
||||
const knownUpstreamByModelKey = buildKnownUpstreamModelMap(reportedContextLimits, currentAccountName);
|
||||
const activeEntry = findTrajectoryCacheEntry(activeCascadeId);
|
||||
const activeSteps = activeEntry?.steps || [];
|
||||
const subagentSummaries = activeConvSummary?.subagents || [];
|
||||
if (subagentSummaries.length) lastMainPreparation = null;
|
||||
const modelInputs = { catalogRevision: pricingCatalogRevision, dynamicModelMap };
|
||||
const mainUnit = buildAgentUnitTelemetry({
|
||||
agentId: 'main',
|
||||
cascadeId: activeCascadeId,
|
||||
@@ -620,6 +693,7 @@ export async function buildTelemetryPayloadInternal(
|
||||
resolveStepModel,
|
||||
knownUpstreamByModelKey,
|
||||
includeRecentSteps: false,
|
||||
reuseInputs: subagentSummaries.length ? null : { ...modelInputs, activeCascadeId, accountScope },
|
||||
});
|
||||
|
||||
const enrichedActiveSteps = mainUnit.taggedSteps;
|
||||
@@ -638,11 +712,10 @@ export async function buildTelemetryPayloadInternal(
|
||||
const mainAgentTelemetry = mainUnit.telemetryUnit;
|
||||
const mainModelBreakdown = mainAgentTelemetry.modelBreakdown;
|
||||
|
||||
const subagentSummaries = activeConvSummary?.subagents || [];
|
||||
const activeFamilyCascadeIds = new Set(activeCascadeId ? [activeCascadeId.toLowerCase()] : []);
|
||||
const subAgentTelemetries = [];
|
||||
const allCombinedRawSteps = [...activeSteps];
|
||||
const allCombinedEnrichedSteps = [...enrichedActiveSteps];
|
||||
const allCombinedRawSteps = subagentSummaries.length ? activeSteps.slice() : [];
|
||||
const allCombinedEnrichedSteps = subagentSummaries.length ? enrichedActiveSteps.slice() : [];
|
||||
let totalRawSessionCostUsd = sessionCostUsd;
|
||||
let totalFamilyInputTokens = sessionInputTokens;
|
||||
let totalFamilyCacheReadTokens = sessionCacheReadTokens;
|
||||
@@ -654,7 +727,7 @@ export async function buildTelemetryPayloadInternal(
|
||||
activeFamilyCascadeIds.add(String(subCid || '').toLowerCase());
|
||||
const subEntry = findTrajectoryCacheEntry(subCid);
|
||||
const subRawSteps = subEntry?.steps || [];
|
||||
allCombinedRawSteps.push(...subRawSteps);
|
||||
for (const step of subRawSteps) allCombinedRawSteps.push(step);
|
||||
|
||||
const subSpec = subSum.subagentSpec || subEntry?.subagentSpec || null;
|
||||
const rawRole =
|
||||
@@ -684,7 +757,7 @@ export async function buildTelemetryPayloadInternal(
|
||||
includeRecentSteps: true,
|
||||
});
|
||||
|
||||
allCombinedEnrichedSteps.push(...subUnit.taggedSteps);
|
||||
for (const step of subUnit.taggedSteps) allCombinedEnrichedSteps.push(step);
|
||||
totalRawSessionCostUsd += subUnit.enrichedRes.sessionCostUsd;
|
||||
totalFamilyInputTokens += subUnit.enrichedRes.sessionInputTokens;
|
||||
totalFamilyCacheReadTokens += subUnit.enrichedRes.sessionCacheReadTokens;
|
||||
@@ -948,6 +1021,7 @@ export async function buildTelemetryPayloadInternal(
|
||||
activeFamilyCascadeIds,
|
||||
resolveStepModel,
|
||||
quotaPoolsMap,
|
||||
modelInputs,
|
||||
});
|
||||
|
||||
const emptyCycleSummary = () => ({
|
||||
@@ -1339,7 +1413,9 @@ export async function buildTelemetryPayloadInternal(
|
||||
stepCount: enrichedActiveSteps.length,
|
||||
hasSubagents: subAgentTelemetries.length > 0,
|
||||
subagentCount: subAgentTelemetries.length,
|
||||
totalStepsAllAgents: allCombinedEnrichedSteps.length,
|
||||
totalStepsAllAgents: subAgentTelemetries.length
|
||||
? allCombinedEnrichedSteps.length
|
||||
: enrichedActiveSteps.length,
|
||||
latestTokPerSec: latestEnriched?.tokPerSec ?? null,
|
||||
latestTtftSec: latestEnriched?.ttftSec ?? null,
|
||||
latestSpeedReason: latestEnriched?.selectedSpeedReason ?? null,
|
||||
@@ -1363,7 +1439,7 @@ export async function buildTelemetryPayloadInternal(
|
||||
activeModelUpstream:
|
||||
latestEnriched?.modelUpstream || latestEnriched?.modelShort || '模型未知',
|
||||
context,
|
||||
recentSteps: enrichedActiveSteps.slice().reverse(),
|
||||
recentSteps: mainUnit.recentSteps,
|
||||
modelBreakdown: mainModelBreakdown,
|
||||
agents: allAgents,
|
||||
aggregated: aggregatedTelemetry,
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import {
|
||||
closeSync, fstatSync, openSync, readFileSync, renameSync, statSync, unlinkSync, writevSync,
|
||||
} from 'node:fs';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
|
||||
let lastWrite = null;
|
||||
|
||||
function isSameFile(a, b) {
|
||||
return b.ino !== 0n && a.dev === b.dev && a.ino === b.ino &&
|
||||
a.size === b.size && a.mtimeNs === b.mtimeNs;
|
||||
}
|
||||
|
||||
function readReusableBytes(filePath, expected) {
|
||||
let fd;
|
||||
try {
|
||||
fd = openSync(filePath, 'r');
|
||||
const before = fstatSync(fd, { bigint: true });
|
||||
if (!isSameFile(before, expected) || before.ctimeNs !== expected.ctimeNs) return null;
|
||||
const bytes = readFileSync(fd);
|
||||
const after = fstatSync(fd, { bigint: true });
|
||||
return isSameFile(before, after) && before.ctimeNs === after.ctimeNs &&
|
||||
BigInt(bytes.length) === after.size ? bytes : null;
|
||||
} catch {
|
||||
return null;
|
||||
} finally {
|
||||
if (fd !== undefined) closeSync(fd);
|
||||
}
|
||||
}
|
||||
|
||||
// 只复用上次确认写入的步骤字节。扫描器用新数组替换变更步骤,每次仍重新序列化会话元数据。
|
||||
export function writeTrajectoryCacheFile(filePath, data) {
|
||||
const previous = lastWrite?.filePath === filePath ? lastWrite : null;
|
||||
const bytes = previous ? readReusableBytes(filePath, previous.file) : null;
|
||||
const ranges = new WeakMap();
|
||||
const parts = [];
|
||||
let position = 0;
|
||||
function append(part) {
|
||||
const buffer = typeof part === 'string' ? Buffer.from(part) : part;
|
||||
parts.push(buffer);
|
||||
position += buffer.length;
|
||||
}
|
||||
|
||||
append('{');
|
||||
let separator = '';
|
||||
for (const [id, entry] of Object.entries(data)) {
|
||||
const { steps, ...metadata } = entry;
|
||||
const header = JSON.stringify(metadata);
|
||||
append(`${separator}${JSON.stringify(id)}:${header.slice(0, -1)}${header === '{}' ? '' : ','}"steps":`);
|
||||
const range = bytes && previous.ranges.get(steps);
|
||||
const start = position;
|
||||
append(range ? bytes.subarray(range.start, range.end) : JSON.stringify(steps));
|
||||
ranges.set(steps, { start, end: position });
|
||||
append('}');
|
||||
separator = ',';
|
||||
}
|
||||
append('}');
|
||||
|
||||
const temporaryPath = `${filePath}.${randomUUID()}.tmp`;
|
||||
try {
|
||||
const fd = openSync(temporaryPath, 'wx');
|
||||
try {
|
||||
// 按块写入,避免再复制一份完整缓存到连续缓冲区。
|
||||
const batchSize = 256;
|
||||
for (let i = 0; i < parts.length; i += batchSize) {
|
||||
const batch = parts.slice(i, i + batchSize);
|
||||
const length = batch.reduce((sum, part) => sum + part.length, 0);
|
||||
if (writevSync(fd, batch) !== length) throw new Error('Incomplete cache write');
|
||||
}
|
||||
} finally {
|
||||
closeSync(fd);
|
||||
}
|
||||
const written = statSync(temporaryPath, { bigint: true });
|
||||
renameSync(temporaryPath, filePath);
|
||||
const file = statSync(filePath, { bigint: true });
|
||||
lastWrite = isSameFile(written, file) ? { filePath, file, ranges } : null;
|
||||
} finally {
|
||||
try { unlinkSync(temporaryPath); } catch {}
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@
|
||||
* 进行去重遍历聚合,输出前端消费分析与模型明细所需的完整统计结构。
|
||||
*/
|
||||
|
||||
import { isDeepStrictEqual } from 'node:util';
|
||||
import {
|
||||
MEASUREMENT_VERSION,
|
||||
accumulateSpeed,
|
||||
@@ -186,27 +187,13 @@ function createUsageBucket() {
|
||||
* 将单个模型步骤的 Token 与成本累加至目标统计桶。
|
||||
*
|
||||
* @param {ReturnType<typeof createUsageBucket>} bucket
|
||||
* @param {object} st 步骤对象
|
||||
* @param {ReturnType<StepModelResolver>} mInfo 模型信息
|
||||
* @param {number|null} stepCost 单步美元成本(未知时为 `null`)
|
||||
* @param {object} usage 已归一化的单步用量
|
||||
* @param {string} cascadeId 会话标识
|
||||
*/
|
||||
function accumulateStepIntoBucket(bucket, st, mInfo, stepCost, cascadeId) {
|
||||
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 savedCost = mInfo?.pricing
|
||||
? (cacheTok / 1_000_000) * Math.max(0, mInfo.pricing.input - mInfo.pricing.cache)
|
||||
: 0;
|
||||
if (stepCost === null) bucket.unpricedCalls = (bucket.unpricedCalls || 0) + 1;
|
||||
const resolvedCost = Number.isFinite(stepCost) ? stepCost : 0;
|
||||
function accumulateStepIntoBucket(bucket, usage, cascadeId) {
|
||||
const { inTok, cacheTok, outTok, thinkTok, respTok, stepTotalTokens,
|
||||
resolvedCost, savedCost, unpriced } = usage;
|
||||
if (unpriced) bucket.unpricedCalls = (bucket.unpricedCalls || 0) + 1;
|
||||
bucket.calls += 1;
|
||||
if (cascadeId) bucket.conversationsSet.add(cascadeId);
|
||||
bucket.inputTokens += inTok;
|
||||
@@ -383,6 +370,75 @@ export function buildScopedModelBreakdown(steps, resolveStepModel) {
|
||||
return finalizeModelBreakdownMap(perModelStats);
|
||||
}
|
||||
|
||||
let lastUsageSnapshot = null;
|
||||
const MAX_TREND_TIMESTAMP_MS = 8_640_000_000_000_000;
|
||||
|
||||
function planUsageTrend(window, nowMs, earliest, latest) {
|
||||
const safeMs = (value, fallback) =>
|
||||
Number.isFinite(value) && value > 0 && value <= MAX_TREND_TIMESTAMP_MS ? value : fallback;
|
||||
const end = Math.max(safeMs(window.endMs, Math.max(nowMs, latest || nowMs)), latest);
|
||||
const defaultStart = end - 24 * 3600 * 1000;
|
||||
const start = window.key === 'all'
|
||||
? Math.min(safeMs(earliest, defaultStart), end - 3600 * 1000)
|
||||
: Math.min(safeMs(window.startMs, defaultStart), end);
|
||||
const hourly = window.key === 'today' || window.key === '24h' || window.key === '5h' ||
|
||||
end - start <= 72 * 3600 * 1000;
|
||||
const first = new Date(start);
|
||||
const last = new Date(end);
|
||||
if (hourly) {
|
||||
first.setMinutes(0, 0, 0);
|
||||
last.setMinutes(0, 0, 0);
|
||||
} else {
|
||||
first.setHours(0, 0, 0, 0);
|
||||
last.setHours(0, 0, 0, 0);
|
||||
}
|
||||
return { start, end, hourly, first: first.getTime(), last: last.getTime() };
|
||||
}
|
||||
|
||||
function sameUsageEntries(previous, current) {
|
||||
return previous.length === current.length && current.every((entry, index) => {
|
||||
const before = previous[index];
|
||||
return entry.steps === before.steps && entry.cascadeId === before.cascadeId &&
|
||||
entry.appSource === before.appSource && entry.isCurrentConv === before.isCurrentConv;
|
||||
});
|
||||
}
|
||||
|
||||
function sortedUsageTimestamps(entries) {
|
||||
const dates = new Float64Array(entries.reduce((sum, entry) => sum + entry.steps.length, 0));
|
||||
let count = 0;
|
||||
for (const { steps } of entries) {
|
||||
for (const step of steps) {
|
||||
const date = Number(step?.createdAtMs);
|
||||
if (date > 0) dates[count++] = date;
|
||||
}
|
||||
}
|
||||
return dates.subarray(0, count).sort();
|
||||
}
|
||||
|
||||
function usageTimestampBoundary(dates, value, inclusive) {
|
||||
let start = 0;
|
||||
let end = dates.length;
|
||||
while (start < end) {
|
||||
const i = (start + end) >>> 1;
|
||||
if (dates[i] < value || (inclusive && dates[i] === value)) start = i + 1;
|
||||
else end = i;
|
||||
}
|
||||
return start;
|
||||
}
|
||||
|
||||
function sameUsageWindows(previous, current, dates) {
|
||||
return previous.length === current.length && current.every((window, index) => {
|
||||
const before = previous[index];
|
||||
return before.key === window.key && before.label === window.label &&
|
||||
(before.startMs === window.startMs ||
|
||||
usageTimestampBoundary(dates, before.startMs, false) ===
|
||||
usageTimestampBoundary(dates, window.startMs, false)) &&
|
||||
(before.endMs === window.endMs ||
|
||||
usageTimestampBoundary(dates, before.endMs, true) ===
|
||||
usageTimestampBoundary(dates, window.endMs, true));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 聚合所有预设时间窗口、当前选定窗口、趋势图、年度月序列、来源占比与分模型统计。
|
||||
*
|
||||
@@ -393,6 +449,7 @@ export function buildScopedModelBreakdown(steps, resolveStepModel) {
|
||||
* activeCascadeId?: string|null,
|
||||
* activeFamilyCascadeIds?: Set<string>|null,
|
||||
* resolveStepModel: StepModelResolver
|
||||
* modelInputs?: { catalogRevision: number, dynamicModelMap: Map }
|
||||
* }} params
|
||||
*/
|
||||
export function aggregateMultiWindowUsage({
|
||||
@@ -403,6 +460,7 @@ export function aggregateMultiWindowUsage({
|
||||
activeFamilyCascadeIds = null,
|
||||
resolveStepModel,
|
||||
quotaPoolsMap = null,
|
||||
modelInputs = null,
|
||||
}) {
|
||||
const rawFamilyIds =
|
||||
activeFamilyCascadeIds instanceof Set
|
||||
@@ -456,11 +514,13 @@ export function aggregateMultiWindowUsage({
|
||||
}
|
||||
const hasDedicatedCarbonPool = poolCycleBuckets.has('Carbon');
|
||||
const hasDedicatedArgonPool = poolCycleBuckets.has('Argon');
|
||||
const selectedAccountBucket = createUsageBucket();
|
||||
const selectedSessionBucket = createUsageBucket();
|
||||
const poolByModel = new Map();
|
||||
const selectedAccountBucket = accountBuckets[selectedWindow.key] || createUsageBucket();
|
||||
const selectedSessionBucket = sessionBuckets[selectedWindow.key] || createUsageBucket();
|
||||
const perModelStats = new Map();
|
||||
const selectedWindowSteps = [];
|
||||
let earliestSelectedStepMs = Infinity;
|
||||
let latestSelectedStepMs = 0;
|
||||
|
||||
const currentYear = new Date(nowMs).getFullYear();
|
||||
const monthlySeries = Array.from({ length: 12 }, (_, idx) => ({
|
||||
@@ -551,6 +611,33 @@ export function aggregateMultiWindowUsage({
|
||||
});
|
||||
}
|
||||
|
||||
const timeZone = modelInputs ? new Intl.DateTimeFormat().resolvedOptions().timeZone : '';
|
||||
const quotaWindows = Array.from(poolCycleBuckets, ([key, { start5hMs, startWkMs }]) => [
|
||||
{ key: `${key}:5h`, startMs: start5hMs, endMs: nowMs },
|
||||
{ key: `${key}:week`, startMs: startWkMs, endMs: nowMs },
|
||||
]).flat();
|
||||
const windows = [selectedWindow, ...Object.values(presetWindows), ...quotaWindows];
|
||||
const snapshot = lastUsageSnapshot;
|
||||
const sameSnapshot = modelInputs && snapshot && timeZone === snapshot.timeZone &&
|
||||
currentYear === snapshot.currentYear && modelInputs.catalogRevision === snapshot.modelInputs.catalogRevision &&
|
||||
isDeepStrictEqual(modelInputs.dynamicModelMap, snapshot.modelInputs.dynamicModelMap) &&
|
||||
sameUsageEntries(snapshot.entries, allEntriesToAggregate);
|
||||
const previous = sameSnapshot ? snapshot.ranges.get(selectedWindow.key) : null;
|
||||
if (previous) {
|
||||
// 时钟继续前进,只有实际有步骤跨过窗口边界时才重新聚合。
|
||||
const trend = planUsageTrend(selectedWindow, nowMs, previous.earliest, previous.latest);
|
||||
if (
|
||||
trend.hourly === previous.trend.hourly && trend.first === previous.trend.first &&
|
||||
trend.last === previous.trend.last &&
|
||||
sameUsageWindows(previous.windows, windows,
|
||||
snapshot.dates ??= sortedUsageTimestamps(allEntriesToAggregate))
|
||||
) {
|
||||
snapshot.ranges.delete(selectedWindow.key);
|
||||
snapshot.ranges.set(selectedWindow.key, previous);
|
||||
return { ...previous.result, selectedWindow, trendStartMs: trend.start, trendEndMs: trend.end };
|
||||
}
|
||||
}
|
||||
|
||||
for (const entry of allEntriesToAggregate) {
|
||||
const { cascadeId, isCurrentConv } = entry;
|
||||
const srcKey = entry.appSource || 'standalone';
|
||||
@@ -572,6 +659,11 @@ export function aggregateMultiWindowUsage({
|
||||
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 };
|
||||
|
||||
if (tMs > 0) {
|
||||
const stepDate = new Date(tMs);
|
||||
@@ -593,46 +685,36 @@ export function aggregateMultiWindowUsage({
|
||||
for (const k of presetKeys) {
|
||||
const w = presetWindows[k];
|
||||
if (k === 'all' || (tMs > 0 && tMs >= w.startMs && tMs <= w.endMs)) {
|
||||
accumulateStepIntoBucket(accountBuckets[k], st, mInfo, stepCost, cascadeId);
|
||||
accumulateStepIntoBucket(accountBuckets[k], stepUsage, cascadeId);
|
||||
if (isCurrentConv) {
|
||||
accumulateStepIntoBucket(sessionBuckets[k], st, mInfo, stepCost, cascadeId);
|
||||
accumulateStepIntoBucket(sessionBuckets[k], stepUsage, cascadeId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (poolCycleBuckets.size > 0 && tMs > 0 && tMs <= nowMs) {
|
||||
const stepPoolKey =
|
||||
hasDedicatedCarbonPool &&
|
||||
isCarbonModelIdentifier(
|
||||
st.modelKey,
|
||||
st.responseModel,
|
||||
mInfo.modelId,
|
||||
mInfo.label,
|
||||
st.modelDisplayName
|
||||
)
|
||||
? 'Carbon'
|
||||
: hasDedicatedArgonPool &&
|
||||
isArgonModelIdentifier(
|
||||
st.modelKey,
|
||||
st.responseModel,
|
||||
mInfo.modelId,
|
||||
mInfo.label,
|
||||
st.modelDisplayName
|
||||
)
|
||||
? 'Argon'
|
||||
: mInfo.family === 'Gemini' && poolCycleBuckets.has('Gemini')
|
||||
? 'Gemini'
|
||||
: ['Claude', 'GPT', 'Other'].includes(mInfo.family) &&
|
||||
poolCycleBuckets.has('Claude & GPT')
|
||||
? 'Claude & GPT'
|
||||
: null;
|
||||
const poolBucketEntry = stepPoolKey ? poolCycleBuckets.get(stepPoolKey) : null;
|
||||
let cachedPool = poolByModel.get(mInfo);
|
||||
if (!cachedPool || cachedPool.key !== st.modelKey ||
|
||||
cachedPool.response !== st.responseModel || cachedPool.displayName !== st.modelDisplayName) {
|
||||
const ids = [st.modelKey, st.responseModel, mInfo.modelId, mInfo.label, st.modelDisplayName];
|
||||
let poolKey = null;
|
||||
if (hasDedicatedCarbonPool && isCarbonModelIdentifier(...ids)) poolKey = 'Carbon';
|
||||
else if (hasDedicatedArgonPool && isArgonModelIdentifier(...ids)) poolKey = 'Argon';
|
||||
else if (mInfo.family === 'Gemini') poolKey = 'Gemini';
|
||||
else if (['Claude', 'GPT', 'Other'].includes(mInfo.family)) poolKey = 'Claude & GPT';
|
||||
cachedPool = {
|
||||
key: st.modelKey, response: st.responseModel, displayName: st.modelDisplayName,
|
||||
bucket: poolCycleBuckets.get(poolKey),
|
||||
};
|
||||
poolByModel.set(mInfo, cachedPool);
|
||||
}
|
||||
const poolBucketEntry = cachedPool.bucket;
|
||||
if (poolBucketEntry) {
|
||||
if (tMs >= poolBucketEntry.start5hMs) {
|
||||
accumulateStepIntoBucket(poolBucketEntry.b5h, st, mInfo, stepCost, cascadeId);
|
||||
accumulateStepIntoBucket(poolBucketEntry.b5h, stepUsage, cascadeId);
|
||||
}
|
||||
if (tMs >= poolBucketEntry.startWkMs) {
|
||||
accumulateStepIntoBucket(poolBucketEntry.bWk, st, mInfo, stepCost, cascadeId);
|
||||
accumulateStepIntoBucket(poolBucketEntry.bWk, stepUsage, cascadeId);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -642,12 +724,15 @@ export function aggregateMultiWindowUsage({
|
||||
(tMs > 0 && tMs >= selectedWindow.startMs && tMs <= selectedWindow.endMs);
|
||||
|
||||
if (inSelectedWindow) {
|
||||
accumulateStepIntoBucket(selectedAccountBucket, st, mInfo, stepCost, cascadeId);
|
||||
if (isCurrentConv) {
|
||||
accumulateStepIntoBucket(selectedSessionBucket, st, mInfo, stepCost, cascadeId);
|
||||
if (selectedWindow.key === 'custom') {
|
||||
accumulateStepIntoBucket(selectedAccountBucket, stepUsage, cascadeId);
|
||||
if (isCurrentConv) {
|
||||
accumulateStepIntoBucket(selectedSessionBucket, stepUsage, cascadeId);
|
||||
}
|
||||
}
|
||||
if (tMs > 0) {
|
||||
if (tMs < earliestSelectedStepMs) earliestSelectedStepMs = tMs;
|
||||
if (tMs > latestSelectedStepMs && tMs <= MAX_TREND_TIMESTAMP_MS) latestSelectedStepMs = tMs;
|
||||
selectedWindowSteps.push({
|
||||
tMs,
|
||||
tokens: stepTotalTokens,
|
||||
@@ -691,52 +776,15 @@ export function aggregateMultiWindowUsage({
|
||||
}
|
||||
|
||||
// 构建当前选定时间窗口的自适应自然整点/整日趋势序列 (trendSeries)
|
||||
const MAX_SAFE_MS = 8_640_000_000_000_000;
|
||||
const safeMs = (val, fallback) =>
|
||||
Number.isFinite(val) && val > 0 && val <= MAX_SAFE_MS ? val : fallback;
|
||||
let latestSelectedStepMs = 0;
|
||||
for (const item of selectedWindowSteps) {
|
||||
if (item.tMs > latestSelectedStepMs && item.tMs <= MAX_SAFE_MS) {
|
||||
latestSelectedStepMs = item.tMs;
|
||||
}
|
||||
}
|
||||
const baseEndMs = safeMs(selectedWindow.endMs, Math.max(nowMs, latestSelectedStepMs || nowMs));
|
||||
const trendEndMs = Math.max(baseEndMs, latestSelectedStepMs || 0);
|
||||
const rawTrendStartMs =
|
||||
selectedWindow.key === 'all'
|
||||
? safeMs(earliestSelectedStepMs, trendEndMs - 24 * 3600 * 1000)
|
||||
: safeMs(selectedWindow.startMs, trendEndMs - 24 * 3600 * 1000);
|
||||
const effectiveStartMs =
|
||||
selectedWindow.key === 'all'
|
||||
? Math.min(
|
||||
rawTrendStartMs,
|
||||
earliestSelectedStepMs < Infinity
|
||||
? safeMs(earliestSelectedStepMs, rawTrendStartMs)
|
||||
: rawTrendStartMs,
|
||||
trendEndMs - 3600 * 1000
|
||||
)
|
||||
: Math.min(rawTrendStartMs, trendEndMs);
|
||||
const trendStartMs = effectiveStartMs;
|
||||
const rawSpanMs = Math.max(3600 * 1000, trendEndMs - effectiveStartMs);
|
||||
const trend = planUsageTrend(selectedWindow, nowMs, earliestSelectedStepMs, latestSelectedStepMs);
|
||||
const { start: trendStartMs, end: trendEndMs, hourly: useHourly } = trend;
|
||||
const pad2 = (n) => String(n).padStart(2, '0');
|
||||
const WEEKDAY_NAMES = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
|
||||
|
||||
// 72 小时(3 天)以内按自然整点小时分桶;超过 72 小时按本地自然日分桶
|
||||
const useHourly =
|
||||
selectedWindow.key === 'today' ||
|
||||
selectedWindow.key === '24h' ||
|
||||
selectedWindow.key === '5h' ||
|
||||
rawSpanMs <= 72 * 3600 * 1000;
|
||||
|
||||
const trendSeries = [];
|
||||
if (useHourly) {
|
||||
const startHourD = new Date(effectiveStartMs);
|
||||
startHourD.setMinutes(0, 0, 0);
|
||||
const endHourD = new Date(trendEndMs);
|
||||
endHourD.setMinutes(0, 0, 0);
|
||||
|
||||
let firstHourMs = startHourD.getTime();
|
||||
let lastHourMs = endHourD.getTime();
|
||||
let firstHourMs = trend.first;
|
||||
let lastHourMs = trend.last;
|
||||
if (selectedWindow.key === 'today') {
|
||||
const minTodayEndMs = firstHourMs + 5 * 3600 * 1000;
|
||||
if (lastHourMs < minTodayEndMs) {
|
||||
@@ -786,8 +834,8 @@ export function aggregateMultiWindowUsage({
|
||||
});
|
||||
}
|
||||
} else {
|
||||
const firstDayMs = getStartOfLocalDayMs(effectiveStartMs);
|
||||
const lastDayMs = getStartOfLocalDayMs(trendEndMs);
|
||||
const firstDayMs = trend.first;
|
||||
const lastDayMs = trend.last;
|
||||
const dayStarts = [];
|
||||
const cursor = new Date(firstDayMs);
|
||||
cursor.setHours(0, 0, 0, 0);
|
||||
@@ -842,10 +890,14 @@ export function aggregateMultiWindowUsage({
|
||||
if (trendSeries.length > 0) {
|
||||
const firstBucketStart = trendSeries[0].startMs;
|
||||
const lastIdx = trendSeries.length - 1;
|
||||
let previousBucketIndex = 0;
|
||||
for (const item of selectedWindowSteps) {
|
||||
let targetIdx = lastIdx;
|
||||
const previousBucket = trendSeries[previousBucketIndex];
|
||||
if (item.tMs <= firstBucketStart) {
|
||||
targetIdx = 0;
|
||||
} else if (item.tMs >= previousBucket.startMs && item.tMs < previousBucket.endMs) {
|
||||
targetIdx = previousBucketIndex;
|
||||
} else {
|
||||
// 二分查找匹配的时间桶 [startMs, endMs)
|
||||
let lo = 0;
|
||||
@@ -863,6 +915,7 @@ export function aggregateMultiWindowUsage({
|
||||
}
|
||||
}
|
||||
}
|
||||
previousBucketIndex = targetIdx;
|
||||
const bucket = trendSeries[targetIdx];
|
||||
bucket.tokens += item.tokens;
|
||||
bucket.inputTokens += item.inputTokens || 0;
|
||||
@@ -939,7 +992,7 @@ export function aggregateMultiWindowUsage({
|
||||
}
|
||||
: null;
|
||||
|
||||
return {
|
||||
const result = {
|
||||
selectedWindow,
|
||||
trendStartMs,
|
||||
trendEndMs,
|
||||
@@ -956,4 +1009,19 @@ export function aggregateMultiWindowUsage({
|
||||
poolCycleStats,
|
||||
poolsWeeklySummary,
|
||||
};
|
||||
if (modelInputs) {
|
||||
if (!sameSnapshot) {
|
||||
lastUsageSnapshot = {
|
||||
timeZone, modelInputs, currentYear, entries: allEntriesToAggregate, dates: null, ranges: new Map(),
|
||||
};
|
||||
}
|
||||
const { ranges } = lastUsageSnapshot;
|
||||
ranges.delete(selectedWindow.key);
|
||||
ranges.set(selectedWindow.key, {
|
||||
windows, trend, result, earliest: earliestSelectedStepMs, latest: latestSelectedStepMs,
|
||||
});
|
||||
// 侧栏和悬浮窗可同时查看不同范围,共用时间索引并最多保留两份聚合结果。
|
||||
if (ranges.size > 2) ranges.delete(ranges.keys().next().value);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -1335,6 +1335,8 @@ export function createWindowBridgeController(options) {
|
||||
const initOut = await handleApiRequest('/api/telemetry', 'GET', {
|
||||
conversationId: targetConvId,
|
||||
range: 'today',
|
||||
stepDetails: 'display',
|
||||
stepRevision: '',
|
||||
});
|
||||
if (Number(initOut?.status || 200) === 200 && initOut?.body) {
|
||||
initialTelemetry = JSON.parse(initOut.body);
|
||||
|
||||
Reference in New Issue
Block a user