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:
fish
2026-11-15 23:33:08 +09:00
parent 03d3160ef0
commit 8968e03adb
33 changed files with 1692 additions and 920 deletions
+472 -353
View File
File diff suppressed because it is too large Load Diff
+84 -1
View File
@@ -8,6 +8,8 @@
import { readFileSync, promises as fsPromises } from 'node:fs'; import { readFileSync, promises as fsPromises } from 'node:fs';
import { join } from 'node:path'; import { join } from 'node:path';
import { randomUUID } from 'node:crypto';
import { isDeepStrictEqual } from 'node:util';
import { handleAccountCredentialAction } from './account-switch.mjs'; import { handleAccountCredentialAction } from './account-switch.mjs';
import { import {
HERE, HERE,
@@ -110,6 +112,84 @@ function sanitizePositiveFiniteMs(val) {
return Number.isFinite(num) && num > 0 && num <= MAX_SAFE_DATE_MS ? Math.floor(num) : 0; 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 } = {}) { export async function executeTelemetryAction(data, { onRestart = null } = {}) {
const rawConvId = String( const rawConvId = String(
data?.conversationId || process.env.ANTIGRAVITY_CONVERSATION_ID || '' data?.conversationId || process.env.ANTIGRAVITY_CONVERSATION_ID || ''
@@ -148,11 +228,14 @@ export async function executeTelemetryAction(data, { onRestart = null } = {}) {
scheduleSidecarRestart(150); scheduleSidecarRestart(150);
} }
} }
const responsePayload = data?.stepDetails === 'display'
? projectDisplayTelemetry(payload, data.stepRevision)
: payload;
return { return {
status: 200, status: 200,
contentType: 'application/json', contentType: 'application/json',
headers: { 'Cache-Control': 'no-store' }, headers: { 'Cache-Control': 'no-store' },
body: JSON.stringify(payload), body: JSON.stringify(responsePayload),
}; };
} }
+6 -3
View File
@@ -13,6 +13,7 @@ import { homedir } from 'node:os';
import { dirname, join } from 'node:path'; import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url'; import { fileURLToPath } from 'node:url';
import { inferCompactionStepModels, normalizeCachedStep } from '../speed-metrics.mjs'; import { inferCompactionStepModels, normalizeCachedStep } from '../speed-metrics.mjs';
import { writeTrajectoryCacheFile } from './trajectory-cache-file.mjs';
import { import {
DEFAULT_HOVER_MODULES, DEFAULT_HOVER_MODULES,
DEFAULT_OVERVIEW_METRICS, DEFAULT_OVERVIEW_METRICS,
@@ -227,9 +228,11 @@ export function loadJson(filePath, fallback) {
export function saveJson(filePath, data) { export function saveJson(filePath, data) {
try { try {
mkdirSync(DATA_DIR, { recursive: true }); mkdirSync(DATA_DIR, { recursive: true });
const serialized = if (filePath === CACHE_FILE) {
filePath === CACHE_FILE ? JSON.stringify(data) : JSON.stringify(data, null, 2); writeTrajectoryCacheFile(filePath, data);
writeFileSync(filePath, serialized, 'utf8'); } else {
writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf8');
}
return true; return true;
} catch (err) { } catch (err) {
console.error(`Failed writing ${filePath}: ${err.message}`); console.error(`Failed writing ${filePath}: ${err.message}`);
+3 -1
View File
@@ -10,6 +10,7 @@
import { closeSync, existsSync, openSync, readFileSync, readSync, readdirSync, statSync } from 'node:fs'; import { closeSync, existsSync, openSync, readFileSync, readSync, readdirSync, statSync } from 'node:fs';
import { join } from 'node:path'; import { join } from 'node:path';
import { isDeepStrictEqual } from 'node:util';
import { import {
extractLiveActivity, extractLiveActivity,
extractModelSteps, extractModelSteps,
@@ -905,8 +906,9 @@ export async function enumerateAndSyncConversations({
!prev.turnRailTelemetry || !prev.turnRailTelemetry ||
!prev.contextGroupsTelemetry || !prev.contextGroupsTelemetry ||
metaChanged || metaChanged ||
JSON.stringify(prev.steps) !== JSON.stringify(steps); !isDeepStrictEqual(prev.steps, steps);
if (!stepsChanged) cacheEntry.steps = prev.steps;
trajectoryCache[conv.cascadeId] = cacheEntry; trajectoryCache[conv.cascadeId] = cacheEntry;
if (stepsChanged) { if (stepsChanged) {
cacheDirty = true; cacheDirty = true;
+8 -3
View File
@@ -288,11 +288,16 @@ export function createStepModelResolver(dynamicModelMap) {
) { ) {
return resolveModelInfo(modelKey, dynamicModelMap, apiProvider, modelDisplayName, responseModel); return resolveModelInfo(modelKey, dynamicModelMap, apiProvider, modelDisplayName, responseModel);
} }
const key = JSON.stringify([modelKey, apiProvider, modelDisplayName, responseModel]); let providers = models.get(modelKey);
let info = models.get(key); 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) { if (!info) {
info = resolveModelInfo(modelKey, dynamicModelMap, apiProvider, modelDisplayName, responseModel); info = resolveModelInfo(modelKey, dynamicModelMap, apiProvider, modelDisplayName, responseModel);
models.set(key, info); responses.set(responseModel, info);
} }
return info; return info;
}; };
@@ -32,6 +32,7 @@ import {
*/ */
export const MODEL_PRICING = {}; export const MODEL_PRICING = {};
export const PLACEHOLDER_MAP = {}; export const PLACEHOLDER_MAP = {};
export let pricingCatalogRevision = 0;
/** /**
* 校验字符串是否为合法的 SemVer 2.0 语义化版本号格式(支持 `-prerelease` 与 `+build` 元数据)。 * 校验字符串是否为合法的 SemVer 2.0 语义化版本号格式(支持 `-prerelease` 与 `+build` 元数据)。
@@ -361,6 +362,7 @@ export function rebuildActiveCatalog() {
for (const k of Object.keys(PLACEHOLDER_MAP)) delete PLACEHOLDER_MAP[k]; for (const k of Object.keys(PLACEHOLDER_MAP)) delete PLACEHOLDER_MAP[k];
Object.assign(PLACEHOLDER_MAP, nextPlaceholders); Object.assign(PLACEHOLDER_MAP, nextPlaceholders);
pricingCatalogRevision += 1;
cloudSyncState.source = activeSource; cloudSyncState.source = activeSource;
cloudSyncState.catalogVersion = catalogVersion; cloudSyncState.catalogVersion = catalogVersion;
+142 -66
View File
@@ -9,6 +9,7 @@
* 5. 调用 `aggregateMultiWindowUsage` 完成全量多窗口聚合,并组装精简的前端遥测 JSON。 * 5. 调用 `aggregateMultiWindowUsage` 完成全量多窗口聚合,并组装精简的前端遥测 JSON。
*/ */
import { isDeepStrictEqual } from 'node:util';
import { import {
extractLiveActivity, extractLiveActivity,
parseIsoMs, parseIsoMs,
@@ -33,7 +34,7 @@ import {
isArgonModelIdentifier, isArgonModelIdentifier,
isCarbonModelIdentifier, isCarbonModelIdentifier,
} from './model-pricing.mjs'; } from './model-pricing.mjs';
import { getCloudStatus } from './pricing-catalog.mjs'; import { getCloudStatus, pricingCatalogRevision } from './pricing-catalog.mjs';
import { buildOfficialQuotaPools } from './quota-pools.mjs'; import { buildOfficialQuotaPools } from './quota-pools.mjs';
import { import {
aggregateMultiWindowUsage, aggregateMultiWindowUsage,
@@ -43,6 +44,9 @@ import {
const MAX_RECENT_CONVERSATIONS = 30; const MAX_RECENT_CONVERSATIONS = 30;
const POOL_PRIORITY_ORDER = ['Gemini', 'Argon', 'Carbon', 'Claude & GPT']; const POOL_PRIORITY_ORDER = ['Gemini', 'Argon', 'Carbon', 'Claude & GPT'];
const inFlightTelemetrySources = new Map();
const trajectoryModelFacts = new WeakMap();
let lastMainPreparation = null;
function roundSessionCost(val) { function roundSessionCost(val) {
if (!Number.isFinite(val) || val <= 0) return 0; if (!Number.isFinite(val) || val <= 0) return 0;
@@ -59,24 +63,50 @@ function findTrajectoryCacheEntry(cascadeId) {
return null; return null;
} }
/** function rememberModelContextLimit(limits, step) {
* 构建全局 `modelKey -> responseModel` 已知映射表(单次轮询仅扫描一次 `trajectoryCache`)。 const previous = limits.get(step.modelKey);
* if (!previous || step.createdAtMs > previous.at) {
* @returns {Map<string, string>} 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) { function buildKnownUpstreamModelMap(contextLimits, currentAccountName) {
const knownUpstreamByModelKey = new Map(); const knownUpstreamByModelKey = new Map();
for (const entry of Object.values(trajectoryCache)) { for (const entry of Object.values(trajectoryCache)) {
const trackContext = contextLimits && !entry.subagentSpec && if (!entry?.steps?.length) continue;
(!entry.accountName || entry.accountName === currentAccountName); const facts = readTrajectoryModelFacts(entry.steps);
for (const s of entry?.steps || []) { for (const [key, model] of facts.upstream) knownUpstreamByModelKey.set(key, model);
if (s?.modelKey && s.modelKey !== 'unknown' && s.responseModel) { if (entry.subagentSpec || (entry.accountName && entry.accountName !== currentAccountName)) continue;
knownUpstreamByModelKey.set(s.modelKey, s.responseModel); 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) { } else {
const prev = contextLimits.get(s.modelKey); for (const step of entry.steps) {
if (!prev || s.createdAtMs > prev.at) { if (!step?.isCompactionStep && step?.reportedContextLimitTokens > 0) {
contextLimits.set(s.modelKey, { tokens: s.reportedContextLimitTokens, at: s.createdAtMs }); rememberModelContextLimit(contextLimits, step);
} }
} }
} }
@@ -90,12 +120,14 @@ function buildKnownUpstreamModelMap(contextLimits, currentAccountName) {
* *
* @param {object[]} activeSteps 当前会话的原始缓存步骤 * @param {object[]} activeSteps 当前会话的原始缓存步骤
* @param {ReturnType<typeof createStepModelResolver>} resolveStepModel 模型身份与价格解析器 * @param {ReturnType<typeof createStepModelResolver>} resolveStepModel 模型身份与价格解析器
* @param {Map<string, string>} [sharedUpstreamMap=null] 预先构建的已知上游模型映射表 * @param {Map<string, string>} sharedUpstreamMap 预先构建的已知上游模型映射表
* @param {object} agentFields 步骤所属代理的标签和标识
*/ */
function enrichActiveConversationSteps( function enrichActiveConversationSteps(
activeSteps, activeSteps,
resolveStepModel, resolveStepModel,
sharedUpstreamMap = null sharedUpstreamMap,
agentFields
) { ) {
const sessionSpeed = summarizeSpeed(activeSteps); const sessionSpeed = summarizeSpeed(activeSteps);
const sessionTtft = summarizeTtft(activeSteps); const sessionTtft = summarizeTtft(activeSteps);
@@ -105,13 +137,7 @@ function enrichActiveConversationSteps(
let sessionCacheReadTokens = 0; let sessionCacheReadTokens = 0;
let sessionOutputTokens = 0; let sessionOutputTokens = 0;
const knownUpstreamByModelKey = sharedUpstreamMap || buildKnownUpstreamModelMap(); const knownUpstreamByModelKey = sharedUpstreamMap;
for (const s of activeSteps) {
if (s?.modelKey && s.modelKey !== 'unknown' && s.responseModel) {
knownUpstreamByModelKey.set(s.modelKey, s.responseModel);
}
}
const enrichedActiveSteps = activeSteps.map((st) => { const enrichedActiveSteps = activeSteps.map((st) => {
const mInfo = resolveStepModel(st); const mInfo = resolveStepModel(st);
const costUsd = computeStepCost(st, mInfo.pricing); const costUsd = computeStepCost(st, mInfo.pricing);
@@ -121,7 +147,8 @@ function enrichActiveConversationSteps(
if (costUsd === null) sessionUnpricedCalls++; if (costUsd === null) sessionUnpricedCalls++;
sessionInputTokens += st.inputTokens; sessionInputTokens += st.inputTokens;
sessionCacheReadTokens += st.cacheReadTokens; sessionCacheReadTokens += st.cacheReadTokens;
sessionOutputTokens += resolveStepOutputTokens(st); const outputTokens = resolveStepOutputTokens(st);
sessionOutputTokens += outputTokens;
const tokPerSec = metric.value; const tokPerSec = metric.value;
const totalPrompt = st.inputTokens + st.cacheReadTokens; const totalPrompt = st.inputTokens + st.cacheReadTokens;
@@ -167,7 +194,8 @@ function enrichActiveConversationSteps(
inCostUsd: inCostUsd === null ? null : +inCostUsd.toFixed(4), inCostUsd: inCostUsd === null ? null : +inCostUsd.toFixed(4),
cacheCostUsd: cacheCostUsd === null ? null : +cacheCostUsd.toFixed(4), cacheCostUsd: cacheCostUsd === null ? null : +cacheCostUsd.toFixed(4),
outCostUsd: outCostUsd === null ? null : +outCostUsd.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, resolveStepModel,
knownUpstreamByModelKey, knownUpstreamByModelKey,
includeRecentSteps = true, includeRecentSteps = true,
reuseInputs = null,
}) { }) {
const enrichedRes = enrichActiveConversationSteps( const { enrichedRes, ctxRes, modelBreakdown, recentSteps } = prepareAgentSteps(
rawSteps, rawSteps,
resolveStepModel, resolveStepModel,
knownUpstreamByModelKey knownUpstreamByModelKey,
{
agentId,
agentCascadeId: cascadeId,
agentLabel,
agentBadge: badgeText,
agentRole: role,
agentIndex: index,
isSubagent: !isMain,
},
reuseInputs
); );
const taggedSteps = enrichedRes.enrichedActiveSteps.map((st) => ({ const taggedSteps = enrichedRes.enrichedActiveSteps;
...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 lastModifiedMs = const lastModifiedMs =
enrichedRes.latestEnriched?.createdAtMs || fallbackLastModMs || 0; enrichedRes.latestEnriched?.createdAtMs || fallbackLastModMs || 0;
const isRunning = status === 'CASCADE_RUN_STATUS_RUNNING'; const isRunning = status === 'CASCADE_RUN_STATUS_RUNNING';
@@ -504,6 +551,7 @@ function buildAgentUnitTelemetry({
return { return {
enrichedRes, enrichedRes,
taggedSteps, taggedSteps,
recentSteps,
ctxRes, ctxRes,
telemetryUnit: { telemetryUnit: {
agentId, agentId,
@@ -547,13 +595,44 @@ function buildAgentUnitTelemetry({
enrichedRes.latestEnriched?.modelShort || enrichedRes.latestEnriched?.modelShort ||
'模型未知', '模型未知',
context: ctxRes.context, context: ctxRes.context,
...(includeRecentSteps ? { recentSteps: taggedSteps.slice().reverse() } : {}), ...(includeRecentSteps ? { recentSteps } : {}),
modelBreakdown, modelBreakdown,
lastModifiedMs, 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' : const accountStatus = currentAccountName ? 'signedIn' :
userStatus && !userStatus.userTier && !userStatus.planStatus ? 'signedOut' : 'unknown'; userStatus && !userStatus.userTier && !userStatus.planStatus ? 'signedOut' : 'unknown';
const accountScope = accountStatus === 'signedOut' ? null : currentAccountName; const accountScope = accountStatus === 'signedOut' ? null : currentAccountName;
const [allTrajRes, officialQuotaInfo, contextModelCatalog] = await Promise.all([ const { officialQuotaInfo, contextModelCatalog, sessions } = await getTelemetrySources(
callLsRpc('GetAllCascadeTrajectories', {}).catch(() => ({})), requestedConvId, forceQuotaRefresh, currentAccountName, accountScope, userStatus
userStatus ? getOfficialQuotaSummary(forceQuotaRefresh, currentAccountName) : null, );
getContextModelCatalog(), const { conversations, activeConvSummary, activeCascadeId } = sessions;
]);
const officialQuota = officialQuotaInfo?.data || null; const officialQuota = officialQuotaInfo?.data || null;
const clientConfigs = userStatus?.cascadeModelConfigData?.clientModelConfigs || []; const clientConfigs = userStatus?.cascadeModelConfigData?.clientModelConfigs || [];
@@ -588,14 +666,6 @@ export async function buildTelemetryPayloadInternal(
clientConfigs clientConfigs
); );
// 2. 枚举本地与 LS 会话,并增量同步历史轨迹步骤
const { conversations, activeConvSummary, activeCascadeId } =
await enumerateAndSyncConversations({
summariesObj: allTrajRes?.trajectorySummaries || {},
currentAccountName: accountScope,
requestedConvId,
forceRefresh: forceQuotaRefresh,
});
const resolveStepModel = createStepModelResolver(dynamicModelMap); const resolveStepModel = createStepModelResolver(dynamicModelMap);
// 3. 计算当前活跃根会话及其子代理的步骤指标、10 通道上下文拆解与按模型汇总 // 3. 计算当前活跃根会话及其子代理的步骤指标、10 通道上下文拆解与按模型汇总
@@ -603,6 +673,9 @@ export async function buildTelemetryPayloadInternal(
const knownUpstreamByModelKey = buildKnownUpstreamModelMap(reportedContextLimits, currentAccountName); const knownUpstreamByModelKey = buildKnownUpstreamModelMap(reportedContextLimits, currentAccountName);
const activeEntry = findTrajectoryCacheEntry(activeCascadeId); const activeEntry = findTrajectoryCacheEntry(activeCascadeId);
const activeSteps = activeEntry?.steps || []; const activeSteps = activeEntry?.steps || [];
const subagentSummaries = activeConvSummary?.subagents || [];
if (subagentSummaries.length) lastMainPreparation = null;
const modelInputs = { catalogRevision: pricingCatalogRevision, dynamicModelMap };
const mainUnit = buildAgentUnitTelemetry({ const mainUnit = buildAgentUnitTelemetry({
agentId: 'main', agentId: 'main',
cascadeId: activeCascadeId, cascadeId: activeCascadeId,
@@ -620,6 +693,7 @@ export async function buildTelemetryPayloadInternal(
resolveStepModel, resolveStepModel,
knownUpstreamByModelKey, knownUpstreamByModelKey,
includeRecentSteps: false, includeRecentSteps: false,
reuseInputs: subagentSummaries.length ? null : { ...modelInputs, activeCascadeId, accountScope },
}); });
const enrichedActiveSteps = mainUnit.taggedSteps; const enrichedActiveSteps = mainUnit.taggedSteps;
@@ -638,11 +712,10 @@ export async function buildTelemetryPayloadInternal(
const mainAgentTelemetry = mainUnit.telemetryUnit; const mainAgentTelemetry = mainUnit.telemetryUnit;
const mainModelBreakdown = mainAgentTelemetry.modelBreakdown; const mainModelBreakdown = mainAgentTelemetry.modelBreakdown;
const subagentSummaries = activeConvSummary?.subagents || [];
const activeFamilyCascadeIds = new Set(activeCascadeId ? [activeCascadeId.toLowerCase()] : []); const activeFamilyCascadeIds = new Set(activeCascadeId ? [activeCascadeId.toLowerCase()] : []);
const subAgentTelemetries = []; const subAgentTelemetries = [];
const allCombinedRawSteps = [...activeSteps]; const allCombinedRawSteps = subagentSummaries.length ? activeSteps.slice() : [];
const allCombinedEnrichedSteps = [...enrichedActiveSteps]; const allCombinedEnrichedSteps = subagentSummaries.length ? enrichedActiveSteps.slice() : [];
let totalRawSessionCostUsd = sessionCostUsd; let totalRawSessionCostUsd = sessionCostUsd;
let totalFamilyInputTokens = sessionInputTokens; let totalFamilyInputTokens = sessionInputTokens;
let totalFamilyCacheReadTokens = sessionCacheReadTokens; let totalFamilyCacheReadTokens = sessionCacheReadTokens;
@@ -654,7 +727,7 @@ export async function buildTelemetryPayloadInternal(
activeFamilyCascadeIds.add(String(subCid || '').toLowerCase()); activeFamilyCascadeIds.add(String(subCid || '').toLowerCase());
const subEntry = findTrajectoryCacheEntry(subCid); const subEntry = findTrajectoryCacheEntry(subCid);
const subRawSteps = subEntry?.steps || []; const subRawSteps = subEntry?.steps || [];
allCombinedRawSteps.push(...subRawSteps); for (const step of subRawSteps) allCombinedRawSteps.push(step);
const subSpec = subSum.subagentSpec || subEntry?.subagentSpec || null; const subSpec = subSum.subagentSpec || subEntry?.subagentSpec || null;
const rawRole = const rawRole =
@@ -684,7 +757,7 @@ export async function buildTelemetryPayloadInternal(
includeRecentSteps: true, includeRecentSteps: true,
}); });
allCombinedEnrichedSteps.push(...subUnit.taggedSteps); for (const step of subUnit.taggedSteps) allCombinedEnrichedSteps.push(step);
totalRawSessionCostUsd += subUnit.enrichedRes.sessionCostUsd; totalRawSessionCostUsd += subUnit.enrichedRes.sessionCostUsd;
totalFamilyInputTokens += subUnit.enrichedRes.sessionInputTokens; totalFamilyInputTokens += subUnit.enrichedRes.sessionInputTokens;
totalFamilyCacheReadTokens += subUnit.enrichedRes.sessionCacheReadTokens; totalFamilyCacheReadTokens += subUnit.enrichedRes.sessionCacheReadTokens;
@@ -948,6 +1021,7 @@ export async function buildTelemetryPayloadInternal(
activeFamilyCascadeIds, activeFamilyCascadeIds,
resolveStepModel, resolveStepModel,
quotaPoolsMap, quotaPoolsMap,
modelInputs,
}); });
const emptyCycleSummary = () => ({ const emptyCycleSummary = () => ({
@@ -1339,7 +1413,9 @@ export async function buildTelemetryPayloadInternal(
stepCount: enrichedActiveSteps.length, stepCount: enrichedActiveSteps.length,
hasSubagents: subAgentTelemetries.length > 0, hasSubagents: subAgentTelemetries.length > 0,
subagentCount: subAgentTelemetries.length, subagentCount: subAgentTelemetries.length,
totalStepsAllAgents: allCombinedEnrichedSteps.length, totalStepsAllAgents: subAgentTelemetries.length
? allCombinedEnrichedSteps.length
: enrichedActiveSteps.length,
latestTokPerSec: latestEnriched?.tokPerSec ?? null, latestTokPerSec: latestEnriched?.tokPerSec ?? null,
latestTtftSec: latestEnriched?.ttftSec ?? null, latestTtftSec: latestEnriched?.ttftSec ?? null,
latestSpeedReason: latestEnriched?.selectedSpeedReason ?? null, latestSpeedReason: latestEnriched?.selectedSpeedReason ?? null,
@@ -1363,7 +1439,7 @@ export async function buildTelemetryPayloadInternal(
activeModelUpstream: activeModelUpstream:
latestEnriched?.modelUpstream || latestEnriched?.modelShort || '模型未知', latestEnriched?.modelUpstream || latestEnriched?.modelShort || '模型未知',
context, context,
recentSteps: enrichedActiveSteps.slice().reverse(), recentSteps: mainUnit.recentSteps,
modelBreakdown: mainModelBreakdown, modelBreakdown: mainModelBreakdown,
agents: allAgents, agents: allAgents,
aggregated: aggregatedTelemetry, 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 {}
}
}
+166 -98
View File
@@ -6,6 +6,7 @@
* 进行去重遍历聚合,输出前端消费分析与模型明细所需的完整统计结构。 * 进行去重遍历聚合,输出前端消费分析与模型明细所需的完整统计结构。
*/ */
import { isDeepStrictEqual } from 'node:util';
import { import {
MEASUREMENT_VERSION, MEASUREMENT_VERSION,
accumulateSpeed, accumulateSpeed,
@@ -186,27 +187,13 @@ function createUsageBucket() {
* 将单个模型步骤的 Token 与成本累加至目标统计桶。 * 将单个模型步骤的 Token 与成本累加至目标统计桶。
* *
* @param {ReturnType<typeof createUsageBucket>} bucket * @param {ReturnType<typeof createUsageBucket>} bucket
* @param {object} st 步骤对象 * @param {object} usage 已归一化的单步用量
* @param {ReturnType<StepModelResolver>} mInfo 模型信息
* @param {number|null} stepCost 单步美元成本(未知时为 `null`)
* @param {string} cascadeId 会话标识 * @param {string} cascadeId 会话标识
*/ */
function accumulateStepIntoBucket(bucket, st, mInfo, stepCost, cascadeId) { function accumulateStepIntoBucket(bucket, usage, cascadeId) {
const inTok = safeTok(st?.inputTokens); const { inTok, cacheTok, outTok, thinkTok, respTok, stepTotalTokens,
const cacheTok = safeTok(st?.cacheReadTokens); resolvedCost, savedCost, unpriced } = usage;
const outTok = safeTok(st?.outputTokens); if (unpriced) bucket.unpricedCalls = (bucket.unpricedCalls || 0) + 1;
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;
bucket.calls += 1; bucket.calls += 1;
if (cascadeId) bucket.conversationsSet.add(cascadeId); if (cascadeId) bucket.conversationsSet.add(cascadeId);
bucket.inputTokens += inTok; bucket.inputTokens += inTok;
@@ -383,6 +370,75 @@ export function buildScopedModelBreakdown(steps, resolveStepModel) {
return finalizeModelBreakdownMap(perModelStats); 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, * activeCascadeId?: string|null,
* activeFamilyCascadeIds?: Set<string>|null, * activeFamilyCascadeIds?: Set<string>|null,
* resolveStepModel: StepModelResolver * resolveStepModel: StepModelResolver
* modelInputs?: { catalogRevision: number, dynamicModelMap: Map }
* }} params * }} params
*/ */
export function aggregateMultiWindowUsage({ export function aggregateMultiWindowUsage({
@@ -403,6 +460,7 @@ export function aggregateMultiWindowUsage({
activeFamilyCascadeIds = null, activeFamilyCascadeIds = null,
resolveStepModel, resolveStepModel,
quotaPoolsMap = null, quotaPoolsMap = null,
modelInputs = null,
}) { }) {
const rawFamilyIds = const rawFamilyIds =
activeFamilyCascadeIds instanceof Set activeFamilyCascadeIds instanceof Set
@@ -456,11 +514,13 @@ export function aggregateMultiWindowUsage({
} }
const hasDedicatedCarbonPool = poolCycleBuckets.has('Carbon'); const hasDedicatedCarbonPool = poolCycleBuckets.has('Carbon');
const hasDedicatedArgonPool = poolCycleBuckets.has('Argon'); const hasDedicatedArgonPool = poolCycleBuckets.has('Argon');
const selectedAccountBucket = createUsageBucket(); const poolByModel = new Map();
const selectedSessionBucket = createUsageBucket(); const selectedAccountBucket = accountBuckets[selectedWindow.key] || createUsageBucket();
const selectedSessionBucket = sessionBuckets[selectedWindow.key] || createUsageBucket();
const perModelStats = new Map(); const perModelStats = new Map();
const selectedWindowSteps = []; const selectedWindowSteps = [];
let earliestSelectedStepMs = Infinity; let earliestSelectedStepMs = Infinity;
let latestSelectedStepMs = 0;
const currentYear = new Date(nowMs).getFullYear(); const currentYear = new Date(nowMs).getFullYear();
const monthlySeries = Array.from({ length: 12 }, (_, idx) => ({ 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) { for (const entry of allEntriesToAggregate) {
const { cascadeId, isCurrentConv } = entry; const { cascadeId, isCurrentConv } = entry;
const srcKey = entry.appSource || 'standalone'; const srcKey = entry.appSource || 'standalone';
@@ -572,6 +659,11 @@ export function aggregateMultiWindowUsage({
const resolvedCost = Number.isFinite(stepCost) ? stepCost : 0; const resolvedCost = Number.isFinite(stepCost) ? stepCost : 0;
const unpriced = stepCost === null ? 1 : 0; const unpriced = stepCost === null ? 1 : 0;
const tMs = Number(st.createdAtMs) > 0 ? Number(st.createdAtMs) : 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) { if (tMs > 0) {
const stepDate = new Date(tMs); const stepDate = new Date(tMs);
@@ -593,46 +685,36 @@ export function aggregateMultiWindowUsage({
for (const k of presetKeys) { for (const k of presetKeys) {
const w = presetWindows[k]; const w = presetWindows[k];
if (k === 'all' || (tMs > 0 && tMs >= w.startMs && tMs <= w.endMs)) { 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) { if (isCurrentConv) {
accumulateStepIntoBucket(sessionBuckets[k], st, mInfo, stepCost, cascadeId); accumulateStepIntoBucket(sessionBuckets[k], stepUsage, cascadeId);
} }
} }
} }
if (poolCycleBuckets.size > 0 && tMs > 0 && tMs <= nowMs) { if (poolCycleBuckets.size > 0 && tMs > 0 && tMs <= nowMs) {
const stepPoolKey = let cachedPool = poolByModel.get(mInfo);
hasDedicatedCarbonPool && if (!cachedPool || cachedPool.key !== st.modelKey ||
isCarbonModelIdentifier( cachedPool.response !== st.responseModel || cachedPool.displayName !== st.modelDisplayName) {
st.modelKey, const ids = [st.modelKey, st.responseModel, mInfo.modelId, mInfo.label, st.modelDisplayName];
st.responseModel, let poolKey = null;
mInfo.modelId, if (hasDedicatedCarbonPool && isCarbonModelIdentifier(...ids)) poolKey = 'Carbon';
mInfo.label, else if (hasDedicatedArgonPool && isArgonModelIdentifier(...ids)) poolKey = 'Argon';
st.modelDisplayName else if (mInfo.family === 'Gemini') poolKey = 'Gemini';
) else if (['Claude', 'GPT', 'Other'].includes(mInfo.family)) poolKey = 'Claude & GPT';
? 'Carbon' cachedPool = {
: hasDedicatedArgonPool && key: st.modelKey, response: st.responseModel, displayName: st.modelDisplayName,
isArgonModelIdentifier( bucket: poolCycleBuckets.get(poolKey),
st.modelKey, };
st.responseModel, poolByModel.set(mInfo, cachedPool);
mInfo.modelId, }
mInfo.label, const poolBucketEntry = cachedPool.bucket;
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;
if (poolBucketEntry) { if (poolBucketEntry) {
if (tMs >= poolBucketEntry.start5hMs) { if (tMs >= poolBucketEntry.start5hMs) {
accumulateStepIntoBucket(poolBucketEntry.b5h, st, mInfo, stepCost, cascadeId); accumulateStepIntoBucket(poolBucketEntry.b5h, stepUsage, cascadeId);
} }
if (tMs >= poolBucketEntry.startWkMs) { 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); (tMs > 0 && tMs >= selectedWindow.startMs && tMs <= selectedWindow.endMs);
if (inSelectedWindow) { if (inSelectedWindow) {
accumulateStepIntoBucket(selectedAccountBucket, st, mInfo, stepCost, cascadeId); if (selectedWindow.key === 'custom') {
if (isCurrentConv) { accumulateStepIntoBucket(selectedAccountBucket, stepUsage, cascadeId);
accumulateStepIntoBucket(selectedSessionBucket, st, mInfo, stepCost, cascadeId); if (isCurrentConv) {
accumulateStepIntoBucket(selectedSessionBucket, stepUsage, cascadeId);
}
} }
if (tMs > 0) { if (tMs > 0) {
if (tMs < earliestSelectedStepMs) earliestSelectedStepMs = tMs; if (tMs < earliestSelectedStepMs) earliestSelectedStepMs = tMs;
if (tMs > latestSelectedStepMs && tMs <= MAX_TREND_TIMESTAMP_MS) latestSelectedStepMs = tMs;
selectedWindowSteps.push({ selectedWindowSteps.push({
tMs, tMs,
tokens: stepTotalTokens, tokens: stepTotalTokens,
@@ -691,52 +776,15 @@ export function aggregateMultiWindowUsage({
} }
// 构建当前选定时间窗口的自适应自然整点/整日趋势序列 (trendSeries) // 构建当前选定时间窗口的自适应自然整点/整日趋势序列 (trendSeries)
const MAX_SAFE_MS = 8_640_000_000_000_000; const trend = planUsageTrend(selectedWindow, nowMs, earliestSelectedStepMs, latestSelectedStepMs);
const safeMs = (val, fallback) => const { start: trendStartMs, end: trendEndMs, hourly: useHourly } = trend;
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 pad2 = (n) => String(n).padStart(2, '0'); const pad2 = (n) => String(n).padStart(2, '0');
const WEEKDAY_NAMES = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']; const WEEKDAY_NAMES = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
// 72 小时(3 天)以内按自然整点小时分桶;超过 72 小时按本地自然日分桶
const useHourly =
selectedWindow.key === 'today' ||
selectedWindow.key === '24h' ||
selectedWindow.key === '5h' ||
rawSpanMs <= 72 * 3600 * 1000;
const trendSeries = []; const trendSeries = [];
if (useHourly) { if (useHourly) {
const startHourD = new Date(effectiveStartMs); let firstHourMs = trend.first;
startHourD.setMinutes(0, 0, 0); let lastHourMs = trend.last;
const endHourD = new Date(trendEndMs);
endHourD.setMinutes(0, 0, 0);
let firstHourMs = startHourD.getTime();
let lastHourMs = endHourD.getTime();
if (selectedWindow.key === 'today') { if (selectedWindow.key === 'today') {
const minTodayEndMs = firstHourMs + 5 * 3600 * 1000; const minTodayEndMs = firstHourMs + 5 * 3600 * 1000;
if (lastHourMs < minTodayEndMs) { if (lastHourMs < minTodayEndMs) {
@@ -786,8 +834,8 @@ export function aggregateMultiWindowUsage({
}); });
} }
} else { } else {
const firstDayMs = getStartOfLocalDayMs(effectiveStartMs); const firstDayMs = trend.first;
const lastDayMs = getStartOfLocalDayMs(trendEndMs); const lastDayMs = trend.last;
const dayStarts = []; const dayStarts = [];
const cursor = new Date(firstDayMs); const cursor = new Date(firstDayMs);
cursor.setHours(0, 0, 0, 0); cursor.setHours(0, 0, 0, 0);
@@ -842,10 +890,14 @@ export function aggregateMultiWindowUsage({
if (trendSeries.length > 0) { if (trendSeries.length > 0) {
const firstBucketStart = trendSeries[0].startMs; const firstBucketStart = trendSeries[0].startMs;
const lastIdx = trendSeries.length - 1; const lastIdx = trendSeries.length - 1;
let previousBucketIndex = 0;
for (const item of selectedWindowSteps) { for (const item of selectedWindowSteps) {
let targetIdx = lastIdx; let targetIdx = lastIdx;
const previousBucket = trendSeries[previousBucketIndex];
if (item.tMs <= firstBucketStart) { if (item.tMs <= firstBucketStart) {
targetIdx = 0; targetIdx = 0;
} else if (item.tMs >= previousBucket.startMs && item.tMs < previousBucket.endMs) {
targetIdx = previousBucketIndex;
} else { } else {
// 二分查找匹配的时间桶 [startMs, endMs) // 二分查找匹配的时间桶 [startMs, endMs)
let lo = 0; let lo = 0;
@@ -863,6 +915,7 @@ export function aggregateMultiWindowUsage({
} }
} }
} }
previousBucketIndex = targetIdx;
const bucket = trendSeries[targetIdx]; const bucket = trendSeries[targetIdx];
bucket.tokens += item.tokens; bucket.tokens += item.tokens;
bucket.inputTokens += item.inputTokens || 0; bucket.inputTokens += item.inputTokens || 0;
@@ -939,7 +992,7 @@ export function aggregateMultiWindowUsage({
} }
: null; : null;
return { const result = {
selectedWindow, selectedWindow,
trendStartMs, trendStartMs,
trendEndMs, trendEndMs,
@@ -956,4 +1009,19 @@ export function aggregateMultiWindowUsage({
poolCycleStats, poolCycleStats,
poolsWeeklySummary, 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;
} }
+2
View File
@@ -1335,6 +1335,8 @@ export function createWindowBridgeController(options) {
const initOut = await handleApiRequest('/api/telemetry', 'GET', { const initOut = await handleApiRequest('/api/telemetry', 'GET', {
conversationId: targetConvId, conversationId: targetConvId,
range: 'today', range: 'today',
stepDetails: 'display',
stepRevision: '',
}); });
if (Number(initOut?.status || 200) === 200 && initOut?.body) { if (Number(initOut?.status || 200) === 200 && initOut?.body) {
initialTelemetry = JSON.parse(initOut.body); initialTelemetry = JSON.parse(initOut.body);
+2 -2
View File
@@ -4,11 +4,11 @@
<meta charset="utf-8"> <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<title>用量监控</title> <title>用量监控</title>
<link rel="stylesheet" href="/styles.css?v=1794740175626"> <link rel="stylesheet" href="/styles.css?v=1794752913974">
<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=1794740175626"></script> <script src="/app.js?v=1794752913974"></script>
</body> </body>
</html> </html>
+10 -4
View File
@@ -608,7 +608,8 @@ export function extractContextBreakdown(chat) {
* - 优先级 3:`chat.model`(`chatModel` 请求级模型标识) * - 优先级 3:`chat.model`(`chatModel` 请求级模型标识)
* - 优先级 4:`metadata.generatorModel`(步骤 `metadata` 顶层记录的生成模型) * - 优先级 4:`metadata.generatorModel`(步骤 `metadata` 顶层记录的生成模型)
* - 优先级 5:`chat.responseModel`(上游返回的具体响应模型名) * - 优先级 5:`chat.responseModel`(上游返回的具体响应模型名)
* 2. **5 种测速过滤与排除原因(`timingReason` / `speedReason`)**: * 2. **测速过滤与排除原因(`timingReason` / `speedReason`)**:
* - `'canceled'`:生成已取消,保留用量但不参与测速;
* - `'incomplete_or_invalid_timing'`:没有完成生成的证据,或总耗时 `totalDurationSec` 缺失/非正数; * - `'incomplete_or_invalid_timing'`:没有完成生成的证据,或总耗时 `totalDurationSec` 缺失/非正数;
* - `'invalid_output_tokens'`:`outputTokens` 不是合法的非负安全整数; * - `'invalid_output_tokens'`:`outputTokens` 不是合法的非负安全整数;
* - `'short_timing'`:请求总耗时低于 `MIN_SPEED_DURATION_SECONDS`(0.5s),易受计时器粒度噪声干扰; * - `'short_timing'`:请求总耗时低于 `MIN_SPEED_DURATION_SECONDS`(0.5s),易受计时器粒度噪声干扰;
@@ -806,9 +807,11 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
const nativeStreamSec = duration(chat?.streamingDuration); const nativeStreamSec = duration(chat?.streamingDuration);
const thinkingDurationSec = duration(p.thinkingDuration); const thinkingDurationSec = duration(p.thinkingDuration);
// 5 种测速过滤原因判定:先校验耗时与 Token 合法性(timingReason),再判定压缩步与短样本(speedReason) // 先校验状态、耗时与 Token 合法性,再判定压缩步与短样本。
let timingReason = null; let timingReason = null;
if (!complete || !(totalDurationSec > 0)) { if (s.status === 'CORTEX_STEP_STATUS_CANCELED') {
timingReason = 'canceled';
} else if (!complete || !(totalDurationSec > 0)) {
timingReason = 'incomplete_or_invalid_timing'; timingReason = 'incomplete_or_invalid_timing';
} else if (!validCount(u.outputTokens)) { } else if (!validCount(u.outputTokens)) {
timingReason = 'invalid_output_tokens'; timingReason = 'invalid_output_tokens';
@@ -1187,7 +1190,10 @@ export function speedMetric(step) {
!Number.isFinite(step.totalTokPerSec) || !Number.isFinite(step.totalTokPerSec) ||
!(step.totalDurationSec >= MIN_SPEED_DURATION_SECONDS) !(step.totalDurationSec >= MIN_SPEED_DURATION_SECONDS)
) { ) {
return missing(step.speedReason || 'incomplete_or_invalid_timing'); const reason = step.speedReason || 'incomplete_or_invalid_timing';
return missing(step.isCompactionStep && reason === 'incomplete_or_invalid_timing'
? 'compaction_timing_unavailable'
: reason);
} }
return { return {
@@ -317,7 +317,8 @@ export function computePublicationFit(
let swx = 0; let swx = 0;
for (let j = start; j < end; j++) { for (let j = start; j < end; j++) {
const u = Math.abs(xs[j] - x0) / maxDist; const u = Math.abs(xs[j] - x0) / maxDist;
const w = u >= 1 ? 0 : (1 - u * u * u) ** 3; const base = 1 - u * u * u;
const w = u >= 1 ? 0 : base * base * base;
wBuf[j] = w; wBuf[j] = w;
sw += w; sw += w;
swx += w * xs[j]; swx += w * xs[j];
@@ -339,6 +340,8 @@ export function computePublicationFit(
const dx0 = x0 - mx; const dx0 = x0 - mx;
const useSlope = sxxW > 1e-12; const useSlope = sxxW > 1e-12;
const inverseWeightSum = 1 / sw;
const slopeScale = useSlope ? dx0 / sxxW : 0;
let rawFit = 0; let rawFit = 0;
let leverageNormSq = 0; let leverageNormSq = 0;
let diagHat = 0; let diagHat = 0;
@@ -346,7 +349,7 @@ export function computePublicationFit(
for (let j = start; j < end; j++) { for (let j = start; j < end; j++) {
const w = wBuf[j]; const w = wBuf[j];
if (w <= 0) continue; if (w <= 0) continue;
const lj = w / sw + (useSlope ? (w * (xs[j] - mx) * dx0) / sxxW : 0); const lj = w * inverseWeightSum + (useSlope ? w * (xs[j] - mx) * slopeScale : 0);
rawFit += lj * ys[j]; rawFit += lj * ys[j];
leverageNormSq += lj * lj; leverageNormSq += lj * lj;
if (j === diagIdx) diagHat = lj; if (j === diagIdx) diagHat = lj;
@@ -1477,6 +1480,26 @@ export function createModelFitChart() {
let hoveredIdx = -1; let hoveredIdx = -1;
let lastSig = ''; let lastSig = '';
let lastUpdateParams = null; let lastUpdateParams = null;
let fitCacheMetric = '';
const fitCache = new Map();
function reusePublicationFit(key, xs, ys, maxVal, isMultiCompare) {
const previous = fitCache.get(key);
if (
previous && previous.xs.length === xs.length &&
xs.every((x, i) => x === previous.xs[i] && ys[i] === previous.ys[i])
) {
return previous.result;
}
const result = computePublicationFit(xs, ys, {
minVal: 0,
maxVal,
gridSize: isMultiCompare ? 56 : 64,
span: 0.5,
});
fitCache.set(key, { xs, ys, result });
return result;
}
function syncViewWidth() { function syncViewWidth() {
const measured = Math.round( const measured = Math.round(
@@ -1802,7 +1825,16 @@ export function createModelFitChart() {
} }
} }
if (fitCacheMetric !== metric) {
fitCache.clear();
fitCacheMetric = metric;
}
for (const key of fitCache.keys()) {
if (isMultiCompare ? !targetKeySet.has(key) : key !== null) fitCache.delete(key);
}
if (matchedItems.length === 0) { if (matchedItems.length === 0) {
fitCache.clear();
currentSamples = []; currentSamples = [];
lastSig = 'empty'; lastSig = 'empty';
patchAttr(ciBandPath, 'd', ''); patchAttr(ciBandPath, 'd', '');
@@ -1834,12 +1866,7 @@ export function createModelFitChart() {
if (items.length === 0) continue; if (items.length === 0) continue;
const xs = items.map((d) => d.xVal); const xs = items.map((d) => d.xVal);
const rawYs = items.map((d) => d.rawVal); const rawYs = items.map((d) => d.rawVal);
const pubFit = computePublicationFit(xs, rawYs, { const pubFit = reusePublicationFit(key, xs, rawYs, maxBound, true);
minVal: minBound,
maxVal: maxBound,
gridSize: 56,
span: 0.5,
});
const colorVar = const colorVar =
modelColorByGroup?.get(key) || MODEL_COLOR_VARS[kIdx % MODEL_COLOR_VARS.length]; modelColorByGroup?.get(key) || MODEL_COLOR_VARS[kIdx % MODEL_COLOR_VARS.length];
seriesList.push({ seriesList.push({
@@ -2067,12 +2094,7 @@ export function createModelFitChart() {
const filtered = matchedItems; const filtered = matchedItems;
const xs = filtered.map((d) => d.xVal); const xs = filtered.map((d) => d.xVal);
const rawYs = filtered.map((d) => d.rawVal); const rawYs = filtered.map((d) => d.rawVal);
const pubFit = computePublicationFit(xs, rawYs, { const pubFit = reusePublicationFit(null, xs, rawYs, maxBound, false);
minVal: minBound,
maxVal: maxBound,
gridSize: 64,
span: 0.5,
});
patchText(fitMethodLabelEl, pubFit.method === 'LOESS' ? 'LOESS 拟合' : 'OLS 回归'); patchText(fitMethodLabelEl, pubFit.method === 'LOESS' ? 'LOESS 拟合' : 'OLS 回归');
patchAttr(olsLegendWrapEl, 'hidden', filtered.length < 6); patchAttr(olsLegendWrapEl, 'hidden', filtered.length < 6);
@@ -120,6 +120,7 @@ export const TopSessionHeader = defineComponent({
} else if (currentCascadeId) { } else if (currentCascadeId) {
lastActiveCascadeId = currentCascadeId; lastActiveCascadeId = currentCascadeId;
} }
if (!uiSt.monitorVisible) return;
patchAttr(updateBtn, 'aria-label', t('header.ariaUpdate')); patchAttr(updateBtn, 'aria-label', t('header.ariaUpdate'));
patchAttr(refreshBtn, 'aria-label', t('header.ariaRefresh')); patchAttr(refreshBtn, 'aria-label', t('header.ariaRefresh'));
@@ -283,10 +284,18 @@ export const TopSessionHeader = defineComponent({
(st) => st.locale, (st) => st.locale,
() => renderHeaderState() () => renderHeaderState()
); );
const unsubVisibility = uiStore.subscribe(
(st) => st.monitorVisible,
(visible) => {
if (visible) renderHeaderState();
},
{ immediate: false }
);
onCleanup(() => { onCleanup(() => {
unsubTelemetry(); unsubTelemetry();
unsubI18n(); unsubI18n();
unsubVisibility();
convSelect.destroy(); convSelect.destroy();
}); });
@@ -1091,11 +1091,15 @@ export function mountWindowOverlay() {
} }
} }
function stopMultiLiveTicker() { function pauseMultiLiveTicker() {
if (multiLiveTickTimer) { if (multiLiveTickTimer) {
clearInterval(multiLiveTickTimer); clearInterval(multiLiveTickTimer);
multiLiveTickTimer = null; multiLiveTickTimer = null;
} }
}
function stopMultiLiveTicker() {
pauseMultiLiveTicker();
multiTimersMap.clear(); multiTimersMap.clear();
} }
@@ -1563,6 +1567,7 @@ export function mountWindowOverlay() {
); );
// 完整四标签悬浮容器 // 完整四标签悬浮容器
uiStore.setState({ monitorVisible: false });
const appInstance = App(); const appInstance = App();
const popoverEl = h( const popoverEl = h(
'div', 'div',
@@ -2238,10 +2243,13 @@ export function mountWindowOverlay() {
patchClasses(multiPanelEl, { 'is-instant': Boolean(instant && multiOpen) }); patchClasses(multiPanelEl, { 'is-instant': Boolean(instant && multiOpen) });
patchAttr(multiPanelEl, 'hidden', !multiOpen); patchAttr(multiPanelEl, 'hidden', !multiOpen);
if (multiOpen) { if (multiOpen) {
renderCapsuleTelemetry();
positionFloatingElements(); positionFloatingElements();
if (typeof requestAnimationFrame === 'function') { if (typeof requestAnimationFrame === 'function') {
requestAnimationFrame(() => positionFloatingElements()); requestAnimationFrame(() => positionFloatingElements());
} }
} else {
pauseMultiLiveTicker();
} }
} }
@@ -2272,6 +2280,7 @@ export function mountWindowOverlay() {
patchClasses(hoverTipEl, { 'is-instant': Boolean(instant && targetOpen) }); patchClasses(hoverTipEl, { 'is-instant': Boolean(instant && targetOpen) });
patchAttr(hoverTipEl, 'hidden', !tooltipOpen); patchAttr(hoverTipEl, 'hidden', !tooltipOpen);
if (tooltipOpen) { if (tooltipOpen) {
renderHoverWidgets();
hoverWidgetHost.resumeTickers(); hoverWidgetHost.resumeTickers();
positionFloatingElements(); positionFloatingElements();
if (typeof requestAnimationFrame === 'function') { if (typeof requestAnimationFrame === 'function') {
@@ -2296,6 +2305,7 @@ export function mountWindowOverlay() {
patchClasses(popoverEl, { 'is-instant': Boolean(instant && popoverOpen) }); patchClasses(popoverEl, { 'is-instant': Boolean(instant && popoverOpen) });
patchAttr(capsuleBtn, 'aria-expanded', popoverOpen ? 'true' : 'false'); patchAttr(capsuleBtn, 'aria-expanded', popoverOpen ? 'true' : 'false');
patchAttr(popoverEl, 'hidden', !popoverOpen); patchAttr(popoverEl, 'hidden', !popoverOpen);
uiStore.setState({ monitorVisible: popoverOpen && !document.hidden }, { sync: true });
if (popoverOpen) { if (popoverOpen) {
positionFloatingElements(); positionFloatingElements();
if (typeof requestAnimationFrame === 'function') { if (typeof requestAnimationFrame === 'function') {
@@ -2313,125 +2323,17 @@ export function mountWindowOverlay() {
syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, slotCtx); syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, slotCtx);
} }
// --- 4. 实时遥测状态绑定(双胶囊与多会话/动态组件浮层就地更新,零硬编码、零布局跳动) --- function renderMultiRunningPanel(rawRunningList, runningCount, runningSubCount, hostRouteConversationId) {
function renderCapsuleTelemetry() { if (manualSubExpandMap.size > 0) {
if (disposed) return; const runningIds = new Set(rawRunningList.map((item) => item.cascadeId));
const telSt = telemetryStore.getState(); for (const id of manualSubExpandMap.keys()) {
const uiSt = uiStore.getState(); if (!runningIds.has(id)) manualSubExpandMap.delete(id);
const telemetry = telSt.telemetry; }
setI18nLanguage(telemetry?.settings?.language);
applyAppearanceToRoot(capsuleHost, telemetry?.settings, { includeFontScale: false });
applyAppearanceToRoot(portalHost, telemetry?.settings, { includeFontScale: true });
const showMulti = telemetry?.settings?.showTopbarMultiSession !== false;
patchAttr(multiBtn, 'hidden', !showMulti);
patchAttr(capsuleHost, 'data-multi', showMulti ? 'on' : 'off');
if (!showMulti && multiOpen) {
setMultiOpen(false);
} }
if (!multiOpen || document.hidden) return;
const slotKeys = normalizeClientTopbarSlots(telemetry?.settings?.topbarCapsuleSlots);
const layoutInputsChanged =
showMulti !== lastShowMulti || slotKeys.length !== lastSlotCount;
if (layoutInputsChanged) {
lastShowMulti = showMulti;
lastSlotCount = slotKeys.length;
updateResponsiveLayout();
}
if (!telemetry) {
patchClasses(multiBtn, { 'is-running': false, 'is-waiting': false });
patchText(multiLabel, t('capsule.multiZero'));
patchText(multiRunningMetaEl, t('multi.loading'));
stopMultiLiveTicker();
applyCapsuleSlots(slotKeys, { hasTelemetry: false });
return;
}
const { agents, scopedConv: overviewScopedConv, ctxAgent, aggregated } =
resolveScopedConversation(telemetry, 'all', uiSt.ctxInspectorAgentId);
const { scopedConv: capsuleScopedConv } = resolveScopedConversation(
telemetry,
uiSt.selectedAgentScope,
uiSt.ctxInspectorAgentId
);
const activeConv = telemetry.activeConversation || {};
const overviewActive = overviewScopedConv || activeConv;
const ctx = ctxAgent?.context || overviewActive.context || activeConv.context || {};
const limitTokens = Number(ctx.compactionLimitTokens || ctx.limitTokens || 256000);
const totalTokens = Number(ctx.totalTokens || 0);
const usedPct =
limitTokens > 0 ? Math.min(100, +((totalTokens / limitTokens) * 100).toFixed(1)) : 0;
const dashOffset = +(
RING_CIRCUMFERENCE *
(1 - Math.max(0, Math.min(100, usedPct)) / 100)
).toFixed(2);
const localeKey = getEffectiveLocale(); const localeKey = getEffectiveLocale();
// --- 4a. 同步左侧多会话实时状态胶囊与浮层看板 ---
const rawRunningList =
Array.isArray(telemetry.runningConversations) && telemetry.runningConversations.length > 0
? telemetry.runningConversations
: activeConv.isRunning || aggregated?.isRunning
? [
{
cascadeId: activeConv.cascadeId || 'current',
title: activeConv.title || t('live.currentSession'),
isCurrentSelected: true,
isMainRunning: Boolean(activeConv.isRunning),
isRunning: true,
mainActivity: activeConv.liveActivity || aggregated?.liveActivity || null,
subagentCount: Math.max(0, (agents?.length || 1) - 1),
runningSubagentCount: (agents || []).filter((a) => !a.isMain && a.isRunning).length,
latestTokPerSec: overviewActive.latestTokPerSec ?? null,
contextUsedPct: usedPct,
subagents: (agents || [])
.filter((a) => !a.isMain)
.map((s, idx) => ({
cascadeId: s.cascadeId || s.agentId,
index: s.index || idx + 1,
badgeText: s.badgeText || t('fmt.subBadge', { index: idx + 1 }),
shortLabel: s.shortLabel || `${t('fmt.subAgent')} #${idx + 1}`,
role: s.role || `${t('fmt.subAgent')} #${idx + 1}`,
isRunning: Boolean(s.isRunning),
stepCount: Number(s.stepCount || 0),
lastModifiedMs: s.lastModifiedMs || 0,
liveActivity: s.liveActivity || {
phase: s.isRunning ? 'thinking' : 'done',
label: s.isRunning ? t('live.thinking') : t('live.done'),
detail: '',
stepProgress: '',
startedAtMs: s.lastModifiedMs || 0,
signature: `${s.agentId}:${s.stepCount || 0}`,
},
})),
},
]
: [];
const runningCount = rawRunningList.length;
const runningSubCount = rawRunningList.reduce(
(acc, item) => acc + Number(item.runningSubagentCount || 0),
0
);
const hasWaiting = rawRunningList.some((item) => item.mainActivity?.phase === 'waiting');
patchClasses(multiBtn, {
'is-running': runningCount > 0 && !hasWaiting,
'is-waiting': runningCount > 0 && hasWaiting,
});
const multiBtnText =
runningCount > 0
? runningSubCount > 0
? t('capsule.multiRunningWithSubs', { count: runningCount, subs: runningSubCount })
: t('capsule.multiRunning', { count: runningCount })
: t('capsule.multiZero');
patchText(multiLabel, multiBtnText);
const hostRouteLower = String( const hostRouteLower = String(
telSt.hostRouteConversationId || extractHostRouteCascadeId() || '' hostRouteConversationId || extractHostRouteCascadeId() || ''
).toLowerCase(); ).toLowerCase();
patchText( patchText(
@@ -2445,20 +2347,10 @@ export function mountWindowOverlay() {
patchAttr(multiEmptyEl, 'hidden', runningCount > 0); patchAttr(multiEmptyEl, 'hidden', runningCount > 0);
patchAttr(multiRunningListEl, 'hidden', runningCount === 0); patchAttr(multiRunningListEl, 'hidden', runningCount === 0);
const runningIdsLower = new Set(
rawRunningList.map((item) => String(item.cascadeId || '').toLowerCase())
);
if (runningCount === 0) { if (runningCount === 0) {
stopMultiLiveTicker(); stopMultiLiveTicker();
manualSubExpandMap.clear(); patchKeyedList(multiRunningListEl, [], {});
} else { } else {
for (const cid of [...manualSubExpandMap.keys()]) {
if (!runningIdsLower.has(String(cid || '').toLowerCase())) {
manualSubExpandMap.delete(cid);
}
}
const activeTimerKeys = new Set(); const activeTimerKeys = new Set();
for (const item of rawRunningList) { for (const item of rawRunningList) {
activeTimerKeys.add(`main:${item.cascadeId}`); activeTimerKeys.add(`main:${item.cascadeId}`);
@@ -2646,7 +2538,135 @@ export function mountWindowOverlay() {
} }
} }
ensureMultiLiveTicker(); ensureMultiLiveTicker();
tickMultiElapsedDisplay();
} }
}
function renderHoverWidgets() {
const { telemetry, minuteTick } = telemetryStore.getState();
hoverWidgetHost.update({
moduleKeys: normalizeClientHoverModules(telemetry?.settings?.hoverModules),
data: telemetry,
minuteTick: Number(minuteTick || Math.floor(Date.now() / 30000)),
});
}
// --- 4. 实时遥测状态绑定(双胶囊与多会话/动态组件浮层就地更新,零硬编码、零布局跳动) ---
function renderCapsuleTelemetry() {
if (disposed) return;
const telSt = telemetryStore.getState();
const uiSt = uiStore.getState();
const telemetry = telSt.telemetry;
setI18nLanguage(telemetry?.settings?.language);
applyAppearanceToRoot(capsuleHost, telemetry?.settings, { includeFontScale: false });
applyAppearanceToRoot(portalHost, telemetry?.settings, { includeFontScale: true });
const showMulti = telemetry?.settings?.showTopbarMultiSession !== false;
patchAttr(multiBtn, 'hidden', !showMulti);
patchAttr(capsuleHost, 'data-multi', showMulti ? 'on' : 'off');
if (!showMulti && multiOpen) {
setMultiOpen(false);
}
const slotKeys = normalizeClientTopbarSlots(telemetry?.settings?.topbarCapsuleSlots);
const layoutInputsChanged =
showMulti !== lastShowMulti || slotKeys.length !== lastSlotCount;
if (layoutInputsChanged) {
lastShowMulti = showMulti;
lastSlotCount = slotKeys.length;
updateResponsiveLayout();
}
if (!telemetry) {
patchClasses(multiBtn, { 'is-running': false, 'is-waiting': false });
patchText(multiLabel, t('capsule.multiZero'));
patchText(multiRunningMetaEl, t('multi.loading'));
stopMultiLiveTicker();
applyCapsuleSlots(slotKeys, { hasTelemetry: false });
return;
}
const { agents, scopedConv: overviewScopedConv, ctxAgent, aggregated } =
resolveScopedConversation(telemetry, 'all', uiSt.ctxInspectorAgentId);
const { scopedConv: capsuleScopedConv } = resolveScopedConversation(
telemetry,
uiSt.selectedAgentScope,
uiSt.ctxInspectorAgentId
);
const activeConv = telemetry.activeConversation || {};
const overviewActive = overviewScopedConv || activeConv;
const ctx = ctxAgent?.context || overviewActive.context || activeConv.context || {};
const limitTokens = Number(ctx.compactionLimitTokens || ctx.limitTokens || 256000);
const totalTokens = Number(ctx.totalTokens || 0);
const usedPct =
limitTokens > 0 ? Math.min(100, +((totalTokens / limitTokens) * 100).toFixed(1)) : 0;
const dashOffset = +(
RING_CIRCUMFERENCE *
(1 - Math.max(0, Math.min(100, usedPct)) / 100)
).toFixed(2);
// --- 4a. 同步左侧多会话实时状态胶囊与浮层看板 ---
const rawRunningList =
Array.isArray(telemetry.runningConversations) && telemetry.runningConversations.length > 0
? telemetry.runningConversations
: activeConv.isRunning || aggregated?.isRunning
? [
{
cascadeId: activeConv.cascadeId || 'current',
title: activeConv.title || t('live.currentSession'),
isCurrentSelected: true,
isMainRunning: Boolean(activeConv.isRunning),
isRunning: true,
mainActivity: activeConv.liveActivity || aggregated?.liveActivity || null,
subagentCount: Math.max(0, (agents?.length || 1) - 1),
runningSubagentCount: (agents || []).filter((a) => !a.isMain && a.isRunning).length,
latestTokPerSec: overviewActive.latestTokPerSec ?? null,
contextUsedPct: usedPct,
subagents: (agents || [])
.filter((a) => !a.isMain)
.map((s, idx) => ({
cascadeId: s.cascadeId || s.agentId,
index: s.index || idx + 1,
badgeText: s.badgeText || t('fmt.subBadge', { index: idx + 1 }),
shortLabel: s.shortLabel || `${t('fmt.subAgent')} #${idx + 1}`,
role: s.role || `${t('fmt.subAgent')} #${idx + 1}`,
isRunning: Boolean(s.isRunning),
stepCount: Number(s.stepCount || 0),
lastModifiedMs: s.lastModifiedMs || 0,
liveActivity: s.liveActivity || {
phase: s.isRunning ? 'thinking' : 'done',
label: s.isRunning ? t('live.thinking') : t('live.done'),
detail: '',
stepProgress: '',
startedAtMs: s.lastModifiedMs || 0,
signature: `${s.agentId}:${s.stepCount || 0}`,
},
})),
},
]
: [];
const runningCount = rawRunningList.length;
const runningSubCount = rawRunningList.reduce(
(acc, item) => acc + Number(item.runningSubagentCount || 0),
0
);
const hasWaiting = rawRunningList.some((item) => item.mainActivity?.phase === 'waiting');
patchClasses(multiBtn, {
'is-running': runningCount > 0 && !hasWaiting,
'is-waiting': runningCount > 0 && hasWaiting,
});
const multiBtnText =
runningCount > 0
? runningSubCount > 0
? t('capsule.multiRunningWithSubs', { count: runningCount, subs: runningSubCount })
: t('capsule.multiRunning', { count: runningCount })
: t('capsule.multiZero');
patchText(multiLabel, multiBtnText);
renderMultiRunningPanel(rawRunningList, runningCount, runningSubCount, telSt.hostRouteConversationId);
// --- 4b. 同步右侧 1..5 动态槽位胶囊与组件化悬停浮层 --- // --- 4b. 同步右侧 1..5 动态槽位胶囊与组件化悬停浮层 ---
const isRunning = Boolean(aggregated?.isRunning || activeConv.isRunning); const isRunning = Boolean(aggregated?.isRunning || activeConv.isRunning);
@@ -2752,13 +2772,8 @@ export function mountWindowOverlay() {
if (hoverModuleKeys.length === 0 && !showUpdatePrompt && tooltipOpen) { if (hoverModuleKeys.length === 0 && !showUpdatePrompt && tooltipOpen) {
setTooltipOpen(false); setTooltipOpen(false);
} }
const minuteTick = Number(telSt.minuteTick || Math.floor(Date.now() / 30000));
hoverWidgetHost.update({
moduleKeys: hoverModuleKeys,
data: telemetry,
minuteTick,
});
if (tooltipOpen) { if (tooltipOpen) {
renderHoverWidgets();
positionFloatingElements(); positionFloatingElements();
} }
} }
@@ -2867,6 +2882,8 @@ export function mountWindowOverlay() {
const onDocFocusIn = () => syncHostRouteIfChanged(); const onDocFocusIn = () => syncHostRouteIfChanged();
const onVisibilityChange = () => { const onVisibilityChange = () => {
if (document.hidden) { if (document.hidden) {
uiStore.setState({ monitorVisible: false });
pauseMultiLiveTicker();
hasPointerCoords = false; hasPointerCoords = false;
if (tooltipOpen) { if (tooltipOpen) {
setTooltipOpen(false); setTooltipOpen(false);
@@ -2877,6 +2894,8 @@ export function mountWindowOverlay() {
return; return;
} }
if (!document.hidden && !disposed) { if (!document.hidden && !disposed) {
uiStore.setState({ monitorVisible: popoverOpen });
if (multiOpen) renderCapsuleTelemetry();
syncHostRouteIfChanged(); syncHostRouteIfChanged();
void fetchTelemetry({ force: false }); void fetchTelemetry({ force: false });
} }
@@ -128,6 +128,34 @@ export const StepTableWidget = defineComponent({
stepsTablePane.addEventListener('scroll', hideTurnTip); stepsTablePane.addEventListener('scroll', hideTurnTip);
stepsTbody.addEventListener('mouseleave', hideTurnTip); stepsTbody.addEventListener('mouseleave', hideTurnTip);
const hoverRows = new WeakMap();
let lastRenderedRows = null;
let lastRenderOptions = '';
function enterStepCell(event) {
const { badge, prompt } = hoverRows.get(this);
if (event?.target === badge) hideTurnTip();
else showTurnTip(this, prompt);
}
function moveInStepCell(event) {
if (event?.target === hoverRows.get(this).badge) hideTurnTip();
}
function moveAlongTurnRail(event) {
const { badge, prompt } = hoverRows.get(this);
const rect = this.getBoundingClientRect?.();
const relX = rect ? (event?.clientX ?? 0) - rect.left : 0;
if (event?.target !== badge && relX <= 18) showTurnTip(this, prompt);
else hideTurnTip();
}
function clearCellHover(cell) {
if (!cell || !hoverRows.delete(cell)) return;
cell.onmouseenter = null;
cell.onmousemove = null;
cell.onmouseleave = null;
}
function renderStepTable( function renderStepTable(
tableSteps, tableSteps,
@@ -144,6 +172,16 @@ export const StepTableWidget = defineComponent({
} = {} } = {}
) { ) {
const colOrderSig = colKeys.join(','); const colOrderSig = colKeys.join(',');
const renderOptions = JSON.stringify([
cascadeId, locale, colOrderSig, effectiveScopes, hasSubagents, isMergedMultiAgents,
showStepTurnRail, showStepAgentBadge, displaySettings.showUpstreamModel,
displaySettings.orchestratorIdMode,
]);
if (lastRenderOptions === renderOptions && lastRenderedRows &&
(lastRenderedRows === tableSteps || (lastRenderedRows.length === tableSteps.length &&
tableSteps.every((step, i) => step === lastRenderedRows[i])))) {
return;
}
const wantedSet = new Set(colKeys); const wantedSet = new Set(colKeys);
syncTableHeaderColumns(colKeys); syncTableHeaderColumns(colKeys);
@@ -166,20 +204,23 @@ export const StepTableWidget = defineComponent({
Boolean(useRootTurn ? (st?.isRootLatestTurn ?? st?.isLatestTurn) : st?.isLatestTurn); Boolean(useRootTurn ? (st?.isRootLatestTurn ?? st?.isLatestTurn) : st?.isLatestTurn);
const getStepPrompt = (st) => const getStepPrompt = (st) =>
(useRootTurn ? (st?.rootTurnPrompt ?? st?.turnPrompt) : st?.turnPrompt) || ''; (useRootTurn ? (st?.rootTurnPrompt ?? st?.turnPrompt) : st?.turnPrompt) || '';
const turnKeyOf = (st) => { const turnKeys = showStepTurnRail ? tableSteps.map((st) => {
if (!showStepTurnRail) return '';
const tIdx = getStepTurnIdx(st); const tIdx = getStepTurnIdx(st);
if (!Number.isInteger(tIdx) || tIdx <= 0) return ''; if (!Number.isInteger(tIdx) || tIdx <= 0) return '';
return useRootTurn ? `root:${tIdx}` : `${st?.agentId || 'main'}:${tIdx}`; return useRootTurn ? `root:${tIdx}` : `${st?.agentId || 'main'}:${tIdx}`;
}; }) : [];
const formattedPrompts = new Map();
function formattedTurnPrompt(st) {
const raw = getStepPrompt(st);
if (!formattedPrompts.has(raw)) formattedPrompts.set(raw, formatTurnPromptText(raw));
return formattedPrompts.get(raw);
}
const decoratedSteps = tableSteps.map((st, idx) => { const decoratedSteps = tableSteps.map((st, idx) => {
const tKey = turnKeyOf(st); const tKey = turnKeys[idx];
const hasTurn = Boolean(tKey); const hasTurn = Boolean(tKey);
const hasUp = Boolean(hasTurn && idx > 0 && turnKeyOf(tableSteps[idx - 1]) === tKey); const hasUp = hasTurn && turnKeys[idx - 1] === tKey;
const hasDown = Boolean( const hasDown = hasTurn && turnKeys[idx + 1] === tKey;
hasTurn && idx + 1 < tableSteps.length && turnKeyOf(tableSteps[idx + 1]) === tKey
);
return { return {
st, st,
rowKey: `${st.agentCascadeId || cascadeId || 'conv'}-${st.stepIndex}`, rowKey: `${st.agentCascadeId || cascadeId || 'conv'}-${st.stepIndex}`,
@@ -188,7 +229,7 @@ export const StepTableWidget = defineComponent({
hasDown, hasDown,
isStart: Boolean(hasTurn && (getStepIsStart(st) || !hasDown)), isStart: Boolean(hasTurn && (getStepIsStart(st) || !hasDown)),
isLatest: hasTurn && getStepIsLatest(st), isLatest: hasTurn && getStepIsLatest(st),
prompt: hasTurn ? formatTurnPromptText(getStepPrompt(st)) : '', prompt: hasTurn ? formattedTurnPrompt(st) : '',
}; };
}); });
@@ -205,32 +246,20 @@ export const StepTableWidget = defineComponent({
const parts = colKeys const parts = colKeys
.map((colKey) => STEP_COLUMN_REGISTRY[colKey].sigPart(st, cellCtx)) .map((colKey) => STEP_COLUMN_REGISTRY[colKey].sigPart(st, cellCtx))
.join('|'); .join('|');
const badgeSig = `${showAgentBadge}:${interactiveBadges}:${cellCtx.scopeSigKey}:${st.agentId || 'main'}:${st.agentBadge || ''}:${st.agentLabel || ''}`; const badgeSig = showAgentBadge
? `${cellCtx.scopeSigKey}:${st.agentId || 'main'}:${st.agentBadge || ''}:${st.agentLabel || ''}`
: '';
return `${locale}:${colOrderSig}:${badgeSig}:${railActive}:${item.hasTurn}:${item.hasUp}:${item.hasDown}:${item.isStart}:${item.isLatest}:${item.prompt}:${parts}`; return `${locale}:${colOrderSig}:${badgeSig}:${railActive}:${item.hasTurn}:${item.hasUp}:${item.hasDown}:${item.isStart}:${item.isLatest}:${item.prompt}:${parts}`;
}, },
createRow: () => { createRow: () => {
const tr = h('tr'); const tr = h('tr');
const railLineEl = h('span', { className: 'turn-rail-line', hidden: true });
const railDotEl = h('span', { className: 'turn-rail-dot', hidden: true });
const railEl = h(
'span',
{ className: 'turn-rail', 'aria-hidden': 'true', hidden: true },
[railLineEl, railDotEl]
);
const agentBadgeEl = h('span', {
className: 'agent-badge',
hidden: true,
style: 'margin-right: 4px;',
});
return { return {
el: tr, el: tr,
refs: { refs: {
cellMap: new Map(), cellMap: new Map(),
colOrderSig: '', colOrderSig: '',
railEl, railEl: null,
railLineEl, agentBadgeEl: null,
railDotEl,
agentBadgeEl,
hoverTd: null, hoverTd: null,
}, },
}; };
@@ -240,17 +269,15 @@ export const StepTableWidget = defineComponent({
if (refs.colOrderSig !== colOrderSig) { if (refs.colOrderSig !== colOrderSig) {
if (refs.hoverTd) { if (refs.hoverTd) {
refs.hoverTd.onmouseenter = null; clearCellHover(refs.hoverTd);
refs.hoverTd.onmousemove = null;
refs.hoverTd.onmouseleave = null;
refs.hoverTd = null; refs.hoverTd = null;
} }
for (const [oldColKey, entry] of refs.cellMap) { for (const [oldColKey, entry] of refs.cellMap) {
if (!wantedSet.has(oldColKey)) { if (!wantedSet.has(oldColKey)) {
if (refs.railEl.parentNode === entry.td) { if (refs.railEl?.parentNode === entry.td) {
entry.td.removeChild(refs.railEl); entry.td.removeChild(refs.railEl);
} }
if (refs.agentBadgeEl.parentNode === entry.td) { if (refs.agentBadgeEl?.parentNode === entry.td) {
entry.td.removeChild(refs.agentBadgeEl); entry.td.removeChild(refs.agentBadgeEl);
} }
tr.removeChild(entry.td); tr.removeChild(entry.td);
@@ -258,14 +285,19 @@ export const StepTableWidget = defineComponent({
} }
} }
for (const [i, colKey] of colKeys.entries()) { const isNewRow = refs.colOrderSig === '';
if (!refs.cellMap.has(colKey)) { for (let i = 0; i < colKeys.length; i++) {
refs.cellMap.set(colKey, STEP_COLUMN_REGISTRY[colKey].createCell()); const colKey = colKeys[i];
let cell = refs.cellMap.get(colKey);
if (!cell) {
cell = STEP_COLUMN_REGISTRY[colKey].createCell();
refs.cellMap.set(colKey, cell);
} }
const targetTd = refs.cellMap.get(colKey).td; if (isNewRow) {
const currentTd = tr.children[i] || null; tr.appendChild(cell.td);
if (currentTd !== targetTd) { } else {
tr.insertBefore(targetTd, currentTd); const currentTd = tr.children[i] || null;
if (currentTd !== cell.td) tr.insertBefore(cell.td, currentTd);
} }
} }
refs.colOrderSig = colOrderSig; refs.colOrderSig = colOrderSig;
@@ -278,12 +310,22 @@ export const StepTableWidget = defineComponent({
const firstColKey = colKeys[0]; const firstColKey = colKeys[0];
const firstTd = firstColKey ? refs.cellMap.get(firstColKey)?.td || null : null; const firstTd = firstColKey ? refs.cellMap.get(firstColKey)?.td || null : null;
const showRowRail = Boolean(hasTurn && firstTd);
if (showRowRail && !refs.railEl) {
refs.railEl = h('span', { className: 'turn-rail', 'aria-hidden': 'true' });
}
if (showAgentBadge && firstTd && !refs.agentBadgeEl) {
refs.agentBadgeEl = h('span', { className: 'agent-badge', style: 'margin-right: 4px;' });
}
if (firstTd) { if (firstTd) {
if (refs.railEl.parentNode !== firstTd || firstTd.firstChild !== refs.railEl) { if (refs.railEl && (refs.railEl.parentNode !== firstTd || firstTd.firstChild !== refs.railEl)) {
firstTd.insertBefore(refs.railEl, firstTd.firstChild); firstTd.insertBefore(refs.railEl, firstTd.firstChild);
} }
const afterRail = refs.railEl.nextSibling ?? firstTd.children[1] ?? null; const afterRail = refs.railEl
if (refs.agentBadgeEl.parentNode !== firstTd || afterRail !== refs.agentBadgeEl) { ? refs.railEl.nextSibling ?? firstTd.children[1] ?? null
: firstTd.firstChild;
if (refs.agentBadgeEl &&
(refs.agentBadgeEl.parentNode !== firstTd || afterRail !== refs.agentBadgeEl)) {
firstTd.insertBefore(refs.agentBadgeEl, afterRail); firstTd.insertBefore(refs.agentBadgeEl, afterRail);
} }
} }
@@ -334,72 +376,29 @@ export const StepTableWidget = defineComponent({
patchAttr(refs.agentBadgeEl, 'title', null); patchAttr(refs.agentBadgeEl, 'title', null);
refs.agentBadgeEl.onclick = null; refs.agentBadgeEl.onclick = null;
} }
} else { } else if (refs.agentBadgeEl) {
refs.agentBadgeEl.onclick = null; refs.agentBadgeEl.onclick = null;
} }
const showRowRail = Boolean(railActive && hasTurn && firstTd);
patchAttr(refs.railEl, 'hidden', !showRowRail); patchAttr(refs.railEl, 'hidden', !showRowRail);
if (showRowRail) { if (showRowRail) {
patchClasses(refs.railEl, { const marker = isStart ? ' is-origin' : !hasUp && hasDown ? ' is-cap' : '';
'is-latest': isLatest, patchAttr(refs.railEl, 'class', `turn-rail${isLatest ? ' is-latest' : ''}${hasUp ? ' has-up' : ''}${hasDown ? ' has-down' : ''}${marker}`);
'has-up': hasUp,
'has-down': hasDown,
});
patchAttr(refs.railLineEl, 'hidden', !hasUp && !hasDown);
const showOrigin = isStart;
const showCap = !showOrigin && !hasUp && hasDown;
patchAttr(refs.railDotEl, 'hidden', !showOrigin && !showCap);
patchClasses(refs.railDotEl, {
'is-origin': showOrigin,
'is-cap': showCap,
});
} }
const targetHoverTd = firstTd; const hoverTd = showRowRail && prompt ? firstTd : null;
if (refs.hoverTd && refs.hoverTd !== targetHoverTd) { if (refs.hoverTd !== hoverTd) clearCellHover(refs.hoverTd);
refs.hoverTd.onmouseenter = null; refs.hoverTd = hoverTd;
refs.hoverTd.onmousemove = null; if (hoverTd) {
refs.hoverTd.onmouseleave = null; hoverRows.set(hoverTd, { badge: refs.agentBadgeEl, prompt });
} hoverTd.onmouseenter = firstColKey === 'step' ? enterStepCell : null;
refs.hoverTd = targetHoverTd; hoverTd.onmousemove = firstColKey === 'step' ? moveInStepCell : moveAlongTurnRail;
hoverTd.onmouseleave = hideTurnTip;
if (targetHoverTd) {
const badgeEl = refs.agentBadgeEl;
if (firstColKey === 'step') {
targetHoverTd.onmouseenter = (ev) => {
if (!showRowRail || !prompt || ev?.target === badgeEl) {
hideTurnTip();
return;
}
showTurnTip(targetHoverTd, prompt);
};
targetHoverTd.onmousemove = (ev) => {
if (!showRowRail || !prompt || ev?.target === badgeEl) {
hideTurnTip();
}
};
targetHoverTd.onmouseleave = hideTurnTip;
} else {
targetHoverTd.onmouseenter = null;
targetHoverTd.onmousemove = (ev) => {
if (!showRowRail || !prompt || ev?.target === badgeEl) {
hideTurnTip();
return;
}
const rect = targetHoverTd.getBoundingClientRect?.();
const relX = rect ? (ev?.clientX ?? 0) - rect.left : 0;
if (relX <= 18) {
showTurnTip(targetHoverTd, prompt);
} else {
hideTurnTip();
}
};
targetHoverTd.onmouseleave = hideTurnTip;
}
} }
}, },
}); });
lastRenderOptions = renderOptions;
lastRenderedRows = tableSteps;
} }
onCleanup(() => { onCleanup(() => {
+2
View File
@@ -115,6 +115,8 @@ export function formatUsd(amount, { precise = false } = {}) {
const SPEED_REASON_LABELS = { const SPEED_REASON_LABELS = {
__proto__: null, __proto__: null,
incomplete_or_invalid_timing: 'fmt.speedIncomplete', incomplete_or_invalid_timing: 'fmt.speedIncomplete',
canceled: 'fmt.speedCanceled',
compaction_timing_unavailable: 'fmt.speedCompactionTimingUnavailable',
invalid_output_tokens: 'fmt.speedInvalidOutput', invalid_output_tokens: 'fmt.speedInvalidOutput',
inconsistent_timing: 'fmt.speedInconsistent', inconsistent_timing: 'fmt.speedInconsistent',
short_timing: 'fmt.speedShort', short_timing: 'fmt.speedShort',
+2
View File
@@ -34,6 +34,8 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
// Formatters & Common Labels // Formatters & Common Labels
'fmt.pending': 'N/A', 'fmt.pending': 'N/A',
'fmt.speedIncomplete': 'Incomplete timing', 'fmt.speedIncomplete': 'Incomplete timing',
'fmt.speedCanceled': 'Canceled',
'fmt.speedCompactionTimingUnavailable': 'Untimed compaction',
'fmt.speedInvalidOutput': 'No valid output', 'fmt.speedInvalidOutput': 'No valid output',
'fmt.speedInconsistent': 'Invalid timing', 'fmt.speedInconsistent': 'Invalid timing',
'fmt.speedShort': 'Too brief (<0.5s)', 'fmt.speedShort': 'Too brief (<0.5s)',
+2
View File
@@ -34,6 +34,8 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
// Formatters & Common Labels // Formatters & Common Labels
'fmt.pending': '待定', 'fmt.pending': '待定',
'fmt.speedIncomplete': '计时不完整', 'fmt.speedIncomplete': '计时不完整',
'fmt.speedCanceled': '已取消',
'fmt.speedCompactionTimingUnavailable': '压缩无计时',
'fmt.speedInvalidOutput': '无有效输出', 'fmt.speedInvalidOutput': '无有效输出',
'fmt.speedInconsistent': '耗时数据异常', 'fmt.speedInconsistent': '耗时数据异常',
'fmt.speedShort': '耗时过短 (<0.5s)', 'fmt.speedShort': '耗时过短 (<0.5s)',
@@ -123,24 +123,29 @@ export const STEP_COLUMN_REGISTRY = Object.freeze({
className: 'cell-value tone-muted', className: 'cell-value tone-muted',
style: 'font-size: var(--fs-base-sm);', style: 'font-size: var(--fs-base-sm);',
}); });
const speedReason = h('div', {
className: 'text-muted',
style: 'font-size: var(--fs-2xs);',
});
const wrapEl = h( const wrapEl = h(
'span', 'span',
{ style: 'display: inline-block; vertical-align: middle;' }, { style: 'display: inline-block; vertical-align: middle;' },
[speedMain, speedReason] [speedMain]
); );
const td = h('td', {}, [wrapEl]); const td = h('td', {}, [wrapEl]);
return { td, refs: { td, speedMain, speedReason } }; return { td, refs: { wrapEl, speedMain, speedReason: null } };
}, },
updateCell: (refs, st) => { updateCell: (refs, st) => {
patchText(refs.speedMain, formatMetric(st.tokPerSec, ' tok/s')); patchText(refs.speedMain, formatMetric(st.tokPerSec, ' tok/s'));
patchAttr(refs.speedMain, 'class', `cell-value ${getSpeedToneClass(st.tokPerSec)}`); patchAttr(refs.speedMain, 'class', `cell-value ${getSpeedToneClass(st.tokPerSec)}`);
const reason = speedReasonText(st.selectedSpeedReason); const reason = speedReasonText(st.selectedSpeedReason);
patchText(refs.speedReason, reason); if (reason && !refs.speedReason) {
patchAttr(refs.speedReason, 'hidden', !reason); refs.speedReason = h('div', {
className: 'text-muted',
style: 'font-size: var(--fs-2xs);',
});
refs.wrapEl.appendChild(refs.speedReason);
}
if (refs.speedReason) {
patchText(refs.speedReason, reason);
patchAttr(refs.speedReason, 'hidden', !reason);
}
}, },
}, },
+89 -38
View File
@@ -4,7 +4,7 @@
*/ */
import { createReactiveStore } from '../core/reactive.js'; import { createReactiveStore } from '../core/reactive.js';
import { callSidecarApi, isWindowOverlayMode } from '../core/httpClient.js'; import { callSidecarApi, getWindowBridgeConfig, isWindowOverlayMode } from '../core/httpClient.js';
import { isEnglishLocale, normalizeI18nLanguage, t } from '../i18n/index.js'; import { isEnglishLocale, normalizeI18nLanguage, t } from '../i18n/index.js';
import { normalizeClientFontScale, normalizeClientThemeAccent } from '../core/appearance.js'; import { normalizeClientFontScale, normalizeClientThemeAccent } from '../core/appearance.js';
@@ -100,6 +100,8 @@ let feedbackTimer = null;
let activeBundleVersion = 0; let activeBundleVersion = 0;
let latestRequestSeq = 0; let latestRequestSeq = 0;
let activeForceCount = 0; let activeForceCount = 0;
let inFlightTelemetryPoll = null;
let lastReceivedSteps = null;
let loopActive = false; let loopActive = false;
let loopIntervalMs = 2000; let loopIntervalMs = 2000;
let loopTickFn = null; let loopTickFn = null;
@@ -526,10 +528,11 @@ function isEquivalentTelemetry(prev, next) {
) { ) {
return false; return false;
} }
const paSteps = pa?.recentSteps || []; // 主代理步骤由根会话统一比对,避免明细视图组装后的引用造成重复比对。
const naSteps = na?.recentSteps || []; const paSteps = pa?.isMain && pAct?.recentSteps ? [] : pa?.recentSteps || [];
const naSteps = na?.isMain && nAct?.recentSteps ? [] : na?.recentSteps || [];
if (paSteps.length !== naSteps.length) return false; if (paSteps.length !== naSteps.length) return false;
for (let j = 0; j < paSteps.length; j++) { for (let j = 0; paSteps !== naSteps && j < paSteps.length; j++) {
const bs = paSteps[j]; const bs = paSteps[j];
const as = naSteps[j]; const as = naSteps[j];
if ( if (
@@ -558,6 +561,8 @@ function isEquivalentTelemetry(prev, next) {
bs?.rootTurnIndex !== as?.rootTurnIndex || bs?.rootTurnIndex !== as?.rootTurnIndex ||
bs?.isTurnStart !== as?.isTurnStart || bs?.isTurnStart !== as?.isTurnStart ||
bs?.isRootTurnStart !== as?.isRootTurnStart || bs?.isRootTurnStart !== as?.isRootTurnStart ||
bs?.isLatestTurn !== as?.isLatestTurn ||
bs?.isRootLatestTurn !== as?.isRootLatestTurn ||
bs?.turnPrompt !== as?.turnPrompt || bs?.turnPrompt !== as?.turnPrompt ||
bs?.rootTurnPrompt !== as?.rootTurnPrompt bs?.rootTurnPrompt !== as?.rootTurnPrompt
) { ) {
@@ -584,9 +589,10 @@ function isEquivalentTelemetry(prev, next) {
if (pCtx?.systemPromptTokens !== nCtx?.systemPromptTokens) return false; if (pCtx?.systemPromptTokens !== nCtx?.systemPromptTokens) return false;
if (pCtx?.userRulesTokens !== nCtx?.userRulesTokens) return false; if (pCtx?.userRulesTokens !== nCtx?.userRulesTokens) return false;
if ((pAct?.recentSteps?.length || 0) !== (nAct?.recentSteps?.length || 0)) return false; if ((pAct?.recentSteps?.length || 0) !== (nAct?.recentSteps?.length || 0)) return false;
for (let i = 0; i < (pAct?.recentSteps?.length || 0); i++) { for (let i = 0; pAct?.recentSteps !== nAct?.recentSteps && i < (pAct?.recentSteps?.length || 0); i++) {
const before = pAct.recentSteps[i], after = nAct.recentSteps[i]; const before = pAct.recentSteps[i], after = nAct.recentSteps[i];
if ( if (
before.stepIndex !== after.stepIndex ||
before.createdAtMs !== after.createdAtMs || before.createdAtMs !== after.createdAtMs ||
before.totalDurationSec !== after.totalDurationSec || before.totalDurationSec !== after.totalDurationSec ||
before.streamDurationSec !== after.streamDurationSec || before.streamDurationSec !== after.streamDurationSec ||
@@ -611,6 +617,8 @@ function isEquivalentTelemetry(prev, next) {
before.rootTurnIndex !== after.rootTurnIndex || before.rootTurnIndex !== after.rootTurnIndex ||
before.isTurnStart !== after.isTurnStart || before.isTurnStart !== after.isTurnStart ||
before.isRootTurnStart !== after.isRootTurnStart || before.isRootTurnStart !== after.isRootTurnStart ||
before.isLatestTurn !== after.isLatestTurn ||
before.isRootLatestTurn !== after.isRootLatestTurn ||
before.turnPrompt !== after.turnPrompt || before.turnPrompt !== after.turnPrompt ||
before.rootTurnPrompt !== after.rootTurnPrompt before.rootTurnPrompt !== after.rootTurnPrompt
) { ) {
@@ -822,7 +830,61 @@ export async function fetchTelemetry({ force = false } = {}) {
return telemetryStore.getState().telemetry; return telemetryStore.getState().telemetry;
} }
const st = telemetryStore.getState(); const overlay = isWindowOverlayMode();
if (overlay) {
const st = telemetryStore.getState();
const liveRouteId = extractHostRouteCascadeId();
if (liveRouteId !== st.hostRouteConversationId) {
const patch = { hostRouteConversationId: liveRouteId };
if (liveRouteId && st.selectedConversationId && st.selectedConversationId !== liveRouteId) {
patch.selectedConversationId = '';
}
telemetryStore.setState(patch);
}
}
const current = telemetryStore.getState();
const effectiveConvId = current.selectedConversationId || current.hostRouteConversationId || '';
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));
}
if (force) params.set('force', '1');
params.set('stepDetails', 'display');
if (force) {
inFlightTelemetryPoll = null;
return requestTelemetry(params, true);
}
const query = params.toString();
const bridge = overlay ? getWindowBridgeConfig() : null;
const existing = inFlightTelemetryPoll;
if (existing?.query === query && existing.port === bridge?.port && existing.token === bridge?.token) {
return existing.promise;
}
const poll = { query, port: bridge?.port, token: bridge?.token, promise: null };
poll.promise = requestTelemetry(params, false).finally(() => {
if (inFlightTelemetryPoll === poll) inFlightTelemetryPoll = null;
});
inFlightTelemetryPoll = poll;
return poll.promise;
}
function readDisplaySteps(payload) {
const active = payload?.activeConversation;
if (!payload?.stepRevision || !Array.isArray(active?.recentSteps)) return null;
return {
revision: payload.stepRevision,
recentSteps: active.recentSteps,
agentSteps: active.agents.map((agent) => agent.recentSteps === active.recentSteps
? undefined
: agent.recentSteps),
};
}
async function requestTelemetry(params, force) {
const reqSeq = ++latestRequestSeq; const reqSeq = ++latestRequestSeq;
const startMs = Date.now(); const startMs = Date.now();
@@ -836,41 +898,28 @@ export async function fetchTelemetry({ force = false } = {}) {
} }
try { try {
if (isWindowOverlayMode()) { const previousSteps = lastReceivedSteps || readDisplaySteps(telemetryStore.getState().telemetry);
const liveRouteId = extractHostRouteCascadeId(); params.set('stepRevision', previousSteps?.revision || '');
if (liveRouteId !== st.hostRouteConversationId) { const payload = await callSidecarApi(`/api/telemetry?${params}`, {
const patch = { hostRouteConversationId: liveRouteId };
if (liveRouteId && st.selectedConversationId && st.selectedConversationId !== liveRouteId) {
patch.selectedConversationId = '';
}
telemetryStore.setState(patch);
}
}
const curSt = telemetryStore.getState();
const effectiveConvId = curSt.selectedConversationId || curSt.hostRouteConversationId || '';
const params = new URLSearchParams();
if (effectiveConvId) {
params.set('conversationId', effectiveConvId);
}
if (curSt.selectedTimeRange) {
params.set('range', curSt.selectedTimeRange);
}
if (curSt.selectedTimeRange === 'custom') {
if (curSt.customStartMs > 0) params.set('startMs', String(curSt.customStartMs));
if (curSt.customEndMs > 0) params.set('endMs', String(curSt.customEndMs));
}
if (force) {
params.set('force', '1');
}
const qs = params.toString();
const payload = await callSidecarApi(`/api/telemetry${qs ? `?${qs}` : ''}`, {
method: 'GET', method: 'GET',
abortKey: force ? 'telemetry-force' : 'telemetry-poll', abortKey: force ? 'telemetry-force' : 'telemetry-poll',
}); });
const active = payload?.activeConversation;
if (payload?.stepsUnchanged) {
if (!active || !previousSteps || payload.stepRevision !== previousSteps.revision) {
throw new Error('Telemetry step revision mismatch');
}
active.recentSteps = previousSteps.recentSteps;
active.agents.forEach((agent, index) => {
const steps = previousSteps.agentSteps[index];
if (steps) agent.recentSteps = steps;
});
}
if (reqSeq !== latestRequestSeq) { if (reqSeq !== latestRequestSeq) {
return payload; return payload;
} }
lastReceivedSteps = readDisplaySteps(payload);
if (payload?.uiBundleVersion) { if (payload?.uiBundleVersion) {
if (activeBundleVersion && activeBundleVersion !== payload.uiBundleVersion) { if (activeBundleVersion && activeBundleVersion !== payload.uiBundleVersion) {
@@ -1170,26 +1219,28 @@ export function formatAgentLabel(agent) {
* @param {object|null} telemetry * @param {object|null} telemetry
* @param {string} [selectedAgentScope='all'] * @param {string} [selectedAgentScope='all']
* @param {string} [ctxInspectorAgentId='auto'] * @param {string} [ctxInspectorAgentId='auto']
* @param {boolean} [includeSteps=false] 是否组装调用明细所需的步骤列表
*/ */
export function resolveScopedConversation( export function resolveScopedConversation(
telemetry, telemetry,
selectedAgentScope = 'all', selectedAgentScope = 'all',
ctxInspectorAgentId = 'auto' ctxInspectorAgentId = 'auto',
includeSteps = false
) { ) {
const active = telemetry?.activeConversation || {}; const active = telemetry?.activeConversation || {};
const agents = Array.isArray(active.agents) && active.agents.length > 0 ? active.agents : []; const agents = Array.isArray(active.agents) && active.agents.length > 0 ? active.agents : [];
const hasSubagents = Boolean(active.hasSubagents && agents.length > 1); const hasSubagents = Boolean(active.hasSubagents && agents.length > 1);
const subagents = agents.filter((a) => !a.isMain); const subagents = agents.filter((a) => !a.isMain);
const mainAgent = agents.find((a) => a.isMain) || active; const mainAgent = agents.find((a) => a.isMain) || active;
if (mainAgent && !Array.isArray(mainAgent.recentSteps) && Array.isArray(active.recentSteps)) { if (includeSteps && !Array.isArray(mainAgent.recentSteps) && Array.isArray(active.recentSteps)) {
mainAgent.recentSteps = active.recentSteps; mainAgent.recentSteps = active.recentSteps;
} }
const aggregated = active.aggregated || active; const aggregated = active.aggregated || active;
if (hasSubagents && aggregated && !Array.isArray(aggregated.recentSteps)) { if (includeSteps && hasSubagents && !Array.isArray(aggregated.recentSteps)) {
const combined = []; const combined = [];
for (const ag of agents) { for (const ag of agents) {
const steps = ag.isMain ? ag.recentSteps || active.recentSteps || [] : ag.recentSteps || []; const steps = ag.isMain ? ag.recentSteps || active.recentSteps || [] : ag.recentSteps || [];
combined.push(...steps); for (const step of steps) combined.push(step);
} }
combined.sort( combined.sort(
(a, b) => (a, b) =>
+5
View File
@@ -23,9 +23,14 @@ export function getViewTabs() {
export const uiStore = createReactiveStore({ export const uiStore = createReactiveStore({
activeView: 'overview', activeView: 'overview',
monitorVisible: true,
stepsSubTab: 'steps', // 'steps' | 'models' stepsSubTab: 'steps', // 'steps' | 'models'
settingsSubTab: 'general', // 'general' | 'structure' | 'account' | 'other' settingsSubTab: 'general', // 'general' | 'structure' | 'account' | 'other'
settingsStructureTab: 'mount', // 'mount' | 'hover' | 'overview' | 'steps' settingsStructureTab: 'mount', // 'mount' | 'hover' | 'overview' | 'steps'
selectedAgentScope: 'all', // 'all' | 'main' | <subagent cascadeId> selectedAgentScope: 'all', // 'all' | 'main' | <subagent cascadeId>
ctxInspectorAgentId: 'auto', // 'auto' | 'main' | <subagent cascadeId> ctxInspectorAgentId: 'auto', // 'auto' | 'main' | <subagent cascadeId>
}); });
export function getVisibleMonitorView(state = uiStore.getState()) {
return state.monitorVisible ? state.activeView : null;
}
+16 -10
View File
@@ -147,29 +147,37 @@
--rail-dot: var(--accent-primary); --rail-dot: var(--accent-primary);
} }
.turn-rail-line { .turn-rail::before {
content: '';
position: absolute; position: absolute;
left: 3.25px; left: 3.25px;
width: 1.5px; width: 1.5px;
background: var(--rail-line); background: var(--rail-line);
} }
.turn-rail.has-up.has-down .turn-rail-line { .turn-rail:not(.has-up):not(.has-down)::before {
display: none;
}
.turn-rail.has-up.has-down::before {
top: 0; top: 0;
bottom: 0; bottom: 0;
} }
.turn-rail.has-up:not(.has-down) .turn-rail-line { .turn-rail.has-up:not(.has-down)::before {
top: 0; top: 0;
bottom: 50%; bottom: 50%;
} }
.turn-rail.has-down:not(.has-up) .turn-rail-line { .turn-rail.has-down:not(.has-up)::before {
top: 50%; top: 50%;
bottom: 0; bottom: 0;
} }
.turn-rail-dot { .turn-rail.is-cap::after,
.turn-rail.is-origin::after {
content: '';
box-sizing: border-box;
position: absolute; position: absolute;
top: 50%; top: 50%;
left: 4px; left: 4px;
@@ -177,13 +185,13 @@
border-radius: var(--radius-pill); border-radius: var(--radius-pill);
} }
.turn-rail-dot.is-cap { .turn-rail.is-cap::after {
width: 3.5px; width: 3.5px;
height: 3.5px; height: 3.5px;
background: var(--rail-line); background: var(--rail-line);
} }
.turn-rail-dot.is-origin { .turn-rail.is-origin::after {
width: 6px; width: 6px;
height: 6px; height: 6px;
background: var(--surface-panel); background: var(--surface-panel);
@@ -191,13 +199,11 @@
box-shadow: 0 0 0 1px var(--surface-panel); box-shadow: 0 0 0 1px var(--surface-panel);
} }
.turn-rail.is-latest .turn-rail-dot.is-origin { .turn-rail.is-latest.is-origin::after {
background: var(--rail-dot); background: var(--rail-dot);
} }
.turn-rail[hidden], .turn-rail[hidden],
.turn-rail-line[hidden],
.turn-rail-dot[hidden],
.turn-prompt-tip[hidden] { .turn-prompt-tip[hidden] {
display: none !important; display: none !important;
} }
+32 -15
View File
@@ -29,7 +29,7 @@ import {
import { i18nStore, isEnglishLocale, t } from '../i18n/index.js'; import { i18nStore, isEnglishLocale, t } from '../i18n/index.js';
import { createSvgIcon } from '../icons/SvgIcon.js'; import { createSvgIcon } from '../icons/SvgIcon.js';
import { fetchTelemetry, telemetryStore } from '../store/telemetryStore.js'; import { fetchTelemetry, telemetryStore } from '../store/telemetryStore.js';
import { uiStore } from '../store/uiStore.js'; import { getVisibleMonitorView, uiStore } from '../store/uiStore.js';
import { import {
createTrendAreaChart, createTrendAreaChart,
HEATMAP_DAYS_THRESHOLD, HEATMAP_DAYS_THRESHOLD,
@@ -506,11 +506,38 @@ export const ConsumptionView = defineComponent({
let latestSlice = null; let latestSlice = null;
let isDirty = false; let isDirty = false;
let lastRenderedUsage = '';
/** /**
* 将遥测状态切片同步渲染至消费统计视图的 5 个子面板。 * 将遥测状态切片同步渲染至消费统计视图的 5 个子面板。
*/ */
function renderConsumptionData(slice) { function renderConsumptionData(slice) {
if (!slice) return; if (!slice) return;
const cons = slice.consumption || {};
const preset =
slice.range !== 'custom' && cons.presets?.[slice.range]
? cons.presets[slice.range]
: null;
const acct = preset?.account || cons.account || {};
const rangeInfo = cons.selectedRange || {};
const dateSpan = formatDateSpanBadge(rangeInfo.startMs, rangeInfo.endMs);
const now = new Date();
const currentMonthIdx = now.getMonth();
const monthlyYear = cons.monthlyYear || now.getFullYear();
const locale = i18nStore.getState().locale;
// 额度与会话状态也会发布遥测更新,只对用量页实际展示的数据重绘。
const signature = JSON.stringify([
locale, slice.range, slice.customStartMs, slice.customEndMs, slice.showUpstreamModel,
slice.orchestratorIdMode, dateSpan, preset?.label || rangeInfo.label, acct,
cons.trendSeries, slice.modelBreakdown, cons.sourcesBreakdown,
monthlyYear, currentMonthIdx, cons.monthlySeries,
]);
if (signature === lastRenderedUsage) return;
drawConsumptionData(slice, { cons, preset, acct, rangeInfo, dateSpan, currentMonthIdx, monthlyYear });
lastRenderedUsage = signature;
}
function drawConsumptionData(slice, { cons, preset, acct, rangeInfo, dateSpan, currentMonthIdx, monthlyYear }) {
timeFilterSwitch.setValue(slice.range); timeFilterSwitch.setValue(slice.range);
patchAttr(customRangeBar, 'hidden', slice.range !== 'custom'); patchAttr(customRangeBar, 'hidden', slice.range !== 'custom');
if (!hasUncommittedCustomDraft) { if (!hasUncommittedCustomDraft) {
@@ -520,16 +547,8 @@ export const ConsumptionView = defineComponent({
endPicker.setValue(draftEndMs); endPicker.setValue(draftEndMs);
} }
const cons = slice.consumption || {};
const preset =
slice.range !== 'custom' && cons.presets?.[slice.range]
? cons.presets[slice.range]
: null;
const acct = preset?.account || cons.account || {};
const rangeInfo = cons.selectedRange || {};
// 1. 同步用量概览矩阵与顶部 4 段比例条 // 1. 同步用量概览矩阵与顶部 4 段比例条
patchText(dateSpanBadge, formatDateSpanBadge(rangeInfo.startMs, rangeInfo.endMs)); patchText(dateSpanBadge, dateSpan);
const totalTokens = Number(acct.totalTokens || 0); const totalTokens = Number(acct.totalTokens || 0);
const inputTokens = Number(acct.inputTokens || 0); const inputTokens = Number(acct.inputTokens || 0);
const cacheTokens = Number(acct.cacheReadTokens || 0); const cacheTokens = Number(acct.cacheReadTokens || 0);
@@ -656,8 +675,6 @@ export const ConsumptionView = defineComponent({
}); });
// 5. 同步 12 个月垂直堆叠柱状图(相对于年度峰值月缩放柱高,最低保留 8% 可视高度) // 5. 同步 12 个月垂直堆叠柱状图(相对于年度峰值月缩放柱高,最低保留 8% 可视高度)
const monthlyYear = cons.monthlyYear || new Date().getFullYear();
const currentMonthIdx = new Date().getMonth();
patchText(monthlyYearBadge, String(monthlyYear)); patchText(monthlyYearBadge, String(monthlyYear));
const monthlySeries = cons.monthlySeries || []; const monthlySeries = cons.monthlySeries || [];
const maxMonthTokens = Math.max( const maxMonthTokens = Math.max(
@@ -718,7 +735,7 @@ export const ConsumptionView = defineComponent({
}), }),
(slice) => { (slice) => {
latestSlice = slice; latestSlice = slice;
if (uiStore.getState().activeView !== 'consumption') { if (getVisibleMonitorView() !== 'consumption') {
isDirty = true; isDirty = true;
return; return;
} }
@@ -728,7 +745,7 @@ export const ConsumptionView = defineComponent({
); );
const unsubView = uiStore.subscribe( const unsubView = uiStore.subscribe(
(st) => st.activeView, getVisibleMonitorView,
(activeView) => { (activeView) => {
if (activeView === 'consumption' && isDirty) { if (activeView === 'consumption' && isDirty) {
isDirty = false; isDirty = false;
@@ -770,7 +787,7 @@ export const ConsumptionView = defineComponent({
(st) => st.locale, (st) => st.locale,
() => { () => {
syncStaticLocaleLabels(); syncStaticLocaleLabels();
if (uiStore.getState().activeView === 'consumption' && latestSlice) { if (getVisibleMonitorView() === 'consumption' && latestSlice) {
isDirty = false; isDirty = false;
renderConsumptionData(latestSlice); renderConsumptionData(latestSlice);
} else { } else {
+7 -7
View File
@@ -14,7 +14,7 @@ import {
normalizeClientOverviewModules, normalizeClientOverviewModules,
telemetryStore, telemetryStore,
} from '../store/telemetryStore.js'; } from '../store/telemetryStore.js';
import { uiStore } from '../store/uiStore.js'; import { getVisibleMonitorView, uiStore } from '../store/uiStore.js';
import { CustomScrollbar } from '../components/ui/CustomScrollbar.js'; import { CustomScrollbar } from '../components/ui/CustomScrollbar.js';
export { CTX_CHANNEL_DEFS } from '../components/widgets/ContextWindowWidget.js'; export { CTX_CHANNEL_DEFS } from '../components/widgets/ContextWindowWidget.js';
@@ -37,7 +37,7 @@ export const LiveOverviewView = defineComponent({
const widgetHost = createDynamicWidgetHost({ const widgetHost = createDynamicWidgetHost({
containerEl: overviewInner, containerEl: overviewInner,
mode: 'overview', mode: 'overview',
isVisibleFn: () => uiStore.getState().activeView === 'overview', isVisibleFn: () => getVisibleMonitorView() === 'overview',
initialModuleKeys: DEFAULT_CLIENT_OVERVIEW_MODULES, initialModuleKeys: DEFAULT_CLIENT_OVERVIEW_MODULES,
}); });
@@ -58,13 +58,13 @@ export const LiveOverviewView = defineComponent({
} }
function ensureCountdownTicker() { function ensureCountdownTicker() {
if (uiStore.getState().activeView !== 'overview') { if (getVisibleMonitorView() !== 'overview') {
stopCountdownTicker(); stopCountdownTicker();
return; return;
} }
if (!countdownTickTimer) { if (!countdownTickTimer) {
countdownTickTimer = setInterval(() => { countdownTickTimer = setInterval(() => {
if (uiStore.getState().activeView === 'overview' && latestData) { if (getVisibleMonitorView() === 'overview' && latestData) {
renderData(latestData); renderData(latestData);
} }
}, 30_000); }, 30_000);
@@ -88,7 +88,7 @@ export const LiveOverviewView = defineComponent({
(st) => ({ telemetry: st.telemetry, minuteTick: st.minuteTick }), (st) => ({ telemetry: st.telemetry, minuteTick: st.minuteTick }),
({ telemetry: data }) => { ({ telemetry: data }) => {
latestData = data; latestData = data;
if (uiStore.getState().activeView !== 'overview') { if (getVisibleMonitorView() !== 'overview') {
const stillRunning = const stillRunning =
(Array.isArray(data?.runningConversations) && data.runningConversations.length > 0) || (Array.isArray(data?.runningConversations) && data.runningConversations.length > 0) ||
Boolean( Boolean(
@@ -110,7 +110,7 @@ export const LiveOverviewView = defineComponent({
const unsubView = uiStore.subscribe( const unsubView = uiStore.subscribe(
(st) => ({ (st) => ({
activeView: st.activeView, activeView: getVisibleMonitorView(st),
ctxInspectorAgentId: st.ctxInspectorAgentId, ctxInspectorAgentId: st.ctxInspectorAgentId,
}), }),
(slice) => { (slice) => {
@@ -136,7 +136,7 @@ export const LiveOverviewView = defineComponent({
const unsubI18n = i18nStore.subscribe( const unsubI18n = i18nStore.subscribe(
(st) => st.locale, (st) => st.locale,
() => { () => {
if (uiStore.getState().activeView !== 'overview') { if (getVisibleMonitorView() !== 'overview') {
isDirty = true; isDirty = true;
// Refresh initial skeleton labels even before telemetry arrives // Refresh initial skeleton labels even before telemetry arrives
if (!latestData) { if (!latestData) {
+20 -35
View File
@@ -8,7 +8,7 @@ import { defineComponent } from '../core/component.js';
import { h, patchAttr } from '../core/domPatch.js'; import { h, patchAttr } from '../core/domPatch.js';
import { i18nStore, t } from '../i18n/index.js'; import { i18nStore, t } from '../i18n/index.js';
import { telemetryStore } from '../store/telemetryStore.js'; import { telemetryStore } from '../store/telemetryStore.js';
import { uiStore } from '../store/uiStore.js'; import { getVisibleMonitorView, uiStore } from '../store/uiStore.js';
import { CustomScrollbar } from '../components/ui/CustomScrollbar.js'; import { CustomScrollbar } from '../components/ui/CustomScrollbar.js';
import { SegmentedControl } from '../components/ui/SegmentedControl.js'; import { SegmentedControl } from '../components/ui/SegmentedControl.js';
import { SettingsAccountTab } from './settings/SettingsAccountTab.js'; import { SettingsAccountTab } from './settings/SettingsAccountTab.js';
@@ -37,7 +37,7 @@ export const SettingsView = defineComponent({
modelValue: initialSubTab, modelValue: initialSubTab,
options: getSettingsSubTabOptions(), options: getSettingsSubTabOptions(),
onUpdateModelValue: (nextSubTab) => { onUpdateModelValue: (nextSubTab) => {
uiStore.setState({ settingsSubTab: nextSubTab }); uiStore.setState({ settingsSubTab: nextSubTab }, { sync: true });
}, },
}); });
@@ -95,20 +95,21 @@ export const SettingsView = defineComponent({
viewScrollbar.el, viewScrollbar.el,
]); ]);
let latestSettings = null; function syncActiveTab() {
let latestCloudStatus = null; const ui = uiStore.getState();
let latestContextWindowModels = []; const { settingsSubTab } = ui;
const initialTelemetry = telemetryStore.getState().telemetry; if (getVisibleMonitorView(ui) !== 'settings') return;
accountTab.refs.renderAccount(initialTelemetry?.account, initialTelemetry?.quotas); const telemetry = telemetryStore.getState().telemetry;
const settings = telemetry?.settings;
function syncAllTabs(settings, cloudStatus) { if (settingsSubTab === 'structure') {
if (settings) { if (settings) structureTab.refs.renderSettings(settings);
generalTab.refs.renderSettings(settings); } else if (settingsSubTab === 'other') {
structureTab.refs.renderSettings(settings); if (settings) otherTab.refs.renderSettings(settings, telemetry.contextWindowModels || []);
otherTab.refs.renderSettings(settings, latestContextWindowModels); } else if (SHOW_ACCOUNT_TAB && settingsSubTab === 'account') {
} accountTab.refs.renderAccount(telemetry?.account, telemetry?.quotas);
if (cloudStatus) { } else {
generalTab.refs.renderCloudStatus(cloudStatus); if (settings) generalTab.refs.renderSettings(settings);
if (telemetry?.cloudStatus) generalTab.refs.renderCloudStatus(telemetry.cloudStatus);
} }
refreshScroll(); refreshScroll();
} }
@@ -121,33 +122,17 @@ export const SettingsView = defineComponent({
account: st.telemetry?.account, account: st.telemetry?.account,
quotas: st.telemetry?.quotas, quotas: st.telemetry?.quotas,
}), }),
(slice) => { syncActiveTab
latestSettings = slice.settings;
latestCloudStatus = slice.cloudStatus;
latestContextWindowModels = slice.contextWindowModels || [];
accountTab.refs.renderAccount(slice.account, slice.quotas);
if (slice.settings) {
generalTab.refs.renderSettings(slice.settings);
structureTab.refs.renderSettings(slice.settings);
otherTab.refs.renderSettings(slice.settings, latestContextWindowModels);
}
if (uiStore.getState().activeView === 'settings' && slice.cloudStatus) {
generalTab.refs.renderCloudStatus(slice.cloudStatus);
}
refreshScroll();
}
); );
const unsubUi = uiStore.subscribe( const unsubUi = uiStore.subscribe(
(st) => ({ (st) => ({
activeView: st.activeView, activeView: getVisibleMonitorView(st),
settingsSubTab: st.settingsSubTab, settingsSubTab: st.settingsSubTab,
}), }),
(slice) => { (slice) => {
applyActiveSubTab(slice.settingsSubTab, slice.activeView); applyActiveSubTab(slice.settingsSubTab, slice.activeView);
if (slice.activeView === 'settings') { syncActiveTab();
syncAllTabs(latestSettings, latestCloudStatus);
}
} }
); );
+9 -8
View File
@@ -29,7 +29,7 @@ import {
resolveScopedConversation, resolveScopedConversation,
telemetryStore, telemetryStore,
} from '../store/telemetryStore.js'; } from '../store/telemetryStore.js';
import { uiStore } from '../store/uiStore.js'; import { getVisibleMonitorView, uiStore } from '../store/uiStore.js';
import { import {
MODEL_COLOR_VARS, MODEL_COLOR_VARS,
createModelFitChart, createModelFitChart,
@@ -50,7 +50,7 @@ function mergeSelectedAgentUnits(units) {
for (const ag of units) { for (const ag of units) {
if (!ag || typeof ag !== 'object') continue; if (!ag || typeof ag !== 'object') continue;
if (Array.isArray(ag.recentSteps)) { if (Array.isArray(ag.recentSteps)) {
combinedSteps.push(...ag.recentSteps); for (const step of ag.recentSteps) combinedSteps.push(step);
} }
const breakdown = Array.isArray(ag.modelBreakdown) ? ag.modelBreakdown : []; const breakdown = Array.isArray(ag.modelBreakdown) ? ag.modelBreakdown : [];
for (const m of breakdown) { for (const m of breakdown) {
@@ -520,7 +520,8 @@ export const StepsDetailView = defineComponent({
const baseScope = resolveScopedConversation( const baseScope = resolveScopedConversation(
{ activeConversation: slice.activeConversation }, { activeConversation: slice.activeConversation },
'all', 'all',
uiSt.ctxInspectorAgentId uiSt.ctxInspectorAgentId,
true
); );
const { hasSubagents, agents, subagents, mainAgent, aggregated } = baseScope; const { hasSubagents, agents, subagents, mainAgent, aggregated } = baseScope;
@@ -1027,7 +1028,7 @@ export const StepsDetailView = defineComponent({
subTabSwitch.setValue(tab); subTabSwitch.setValue(tab);
patchAttr(stepsScroll.el, 'hidden', tab !== 'steps'); patchAttr(stepsScroll.el, 'hidden', tab !== 'steps');
patchAttr(modelsScroll.el, 'hidden', tab !== 'models'); patchAttr(modelsScroll.el, 'hidden', tab !== 'models');
if (uiStore.getState().activeView === 'steps' && latestSlice) { if (getVisibleMonitorView() === 'steps' && latestSlice) {
renderStepsData(latestSlice); renderStepsData(latestSlice);
} else if (tab === 'steps') { } else if (tab === 'steps') {
stepsScroll.refresh(); stepsScroll.refresh();
@@ -1053,7 +1054,7 @@ export const StepsDetailView = defineComponent({
}), }),
(slice) => { (slice) => {
latestSlice = slice; latestSlice = slice;
if (uiStore.getState().activeView !== 'steps') { if (getVisibleMonitorView() !== 'steps') {
if (!fitUserPicked) { if (!fitUserPicked) {
fitPinnedWhileVisible = false; fitPinnedWhileVisible = false;
} }
@@ -1066,11 +1067,11 @@ export const StepsDetailView = defineComponent({
); );
let prevScope = uiStore.getState().selectedAgentScope; let prevScope = uiStore.getState().selectedAgentScope;
let prevActiveView = uiStore.getState().activeView; let prevActiveView = getVisibleMonitorView();
const unsubView = uiStore.subscribe( const unsubView = uiStore.subscribe(
(st) => ({ (st) => ({
activeView: st.activeView, activeView: getVisibleMonitorView(st),
selectedAgentScope: st.selectedAgentScope, selectedAgentScope: st.selectedAgentScope,
}), }),
(uiSlice) => { (uiSlice) => {
@@ -1099,7 +1100,7 @@ export const StepsDetailView = defineComponent({
(st) => st.locale, (st) => st.locale,
() => { () => {
refreshStaticLocaleLabels(); refreshStaticLocaleLabels();
if (uiStore.getState().activeView === 'steps' && latestSlice) { if (getVisibleMonitorView() === 'steps' && latestSlice) {
renderStepsData(latestSlice); renderStepsData(latestSlice);
} else { } else {
isDirty = true; isDirty = true;
@@ -33,7 +33,7 @@ import {
normalizeClientWindowMountMode, normalizeClientWindowMountMode,
saveSettingsPatch, saveSettingsPatch,
} from '../../store/telemetryStore.js'; } from '../../store/telemetryStore.js';
import { uiStore } from '../../store/uiStore.js'; import { getVisibleMonitorView, uiStore } from '../../store/uiStore.js';
import { CollapsibleSection } from '../../components/settings/CollapsibleSection.js'; import { CollapsibleSection } from '../../components/settings/CollapsibleSection.js';
import { EditableSlotList } from '../../components/settings/EditableSlotList.js'; import { EditableSlotList } from '../../components/settings/EditableSlotList.js';
import { buildStructurePreviewTelemetry } from '../../components/settings/structurePreviewMock.js'; import { buildStructurePreviewTelemetry } from '../../components/settings/structurePreviewMock.js';
@@ -94,7 +94,7 @@ export const SettingsStructureTab = defineComponent({
function isStructureVisible() { function isStructureVisible() {
const st = uiStore.getState(); const st = uiStore.getState();
return st.activeView === 'settings' && st.settingsSubTab === 'structure'; return getVisibleMonitorView(st) === 'settings' && st.settingsSubTab === 'structure';
} }
function buildDraftTelemetry() { function buildDraftTelemetry() {
@@ -789,7 +789,7 @@ export const SettingsStructureTab = defineComponent({
let wasStructureVisible = isStructureVisible(); let wasStructureVisible = isStructureVisible();
const unsubUi = uiStore.subscribe( const unsubUi = uiStore.subscribe(
(st) => ({ (st) => ({
activeView: st.activeView, activeView: getVisibleMonitorView(st),
settingsSubTab: st.settingsSubTab, settingsSubTab: st.settingsSubTab,
settingsStructureTab: st.settingsStructureTab, settingsStructureTab: st.settingsStructureTab,
}), }),
+16 -10
View File
@@ -2669,29 +2669,37 @@ input {
--rail-dot: var(--accent-primary); --rail-dot: var(--accent-primary);
} }
.turn-rail-line { .turn-rail::before {
content: '';
position: absolute; position: absolute;
left: 3.25px; left: 3.25px;
width: 1.5px; width: 1.5px;
background: var(--rail-line); background: var(--rail-line);
} }
.turn-rail.has-up.has-down .turn-rail-line { .turn-rail:not(.has-up):not(.has-down)::before {
display: none;
}
.turn-rail.has-up.has-down::before {
top: 0; top: 0;
bottom: 0; bottom: 0;
} }
.turn-rail.has-up:not(.has-down) .turn-rail-line { .turn-rail.has-up:not(.has-down)::before {
top: 0; top: 0;
bottom: 50%; bottom: 50%;
} }
.turn-rail.has-down:not(.has-up) .turn-rail-line { .turn-rail.has-down:not(.has-up)::before {
top: 50%; top: 50%;
bottom: 0; bottom: 0;
} }
.turn-rail-dot { .turn-rail.is-cap::after,
.turn-rail.is-origin::after {
content: '';
box-sizing: border-box;
position: absolute; position: absolute;
top: 50%; top: 50%;
left: 4px; left: 4px;
@@ -2699,13 +2707,13 @@ input {
border-radius: var(--radius-pill); border-radius: var(--radius-pill);
} }
.turn-rail-dot.is-cap { .turn-rail.is-cap::after {
width: 3.5px; width: 3.5px;
height: 3.5px; height: 3.5px;
background: var(--rail-line); background: var(--rail-line);
} }
.turn-rail-dot.is-origin { .turn-rail.is-origin::after {
width: 6px; width: 6px;
height: 6px; height: 6px;
background: var(--surface-panel); background: var(--surface-panel);
@@ -2713,13 +2721,11 @@ input {
box-shadow: 0 0 0 1px var(--surface-panel); box-shadow: 0 0 0 1px var(--surface-panel);
} }
.turn-rail.is-latest .turn-rail-dot.is-origin { .turn-rail.is-latest.is-origin::after {
background: var(--rail-dot); background: var(--rail-dot);
} }
.turn-rail[hidden], .turn-rail[hidden],
.turn-rail-line[hidden],
.turn-rail-dot[hidden],
.turn-prompt-tip[hidden] { .turn-prompt-tip[hidden] {
display: none !important; display: none !important;
} }
+12 -2
View File
@@ -1,6 +1,8 @@
import fs from 'node:fs'; import fs from 'node:fs';
import path from 'node:path'; import path from 'node:path';
import vm from 'node:vm'; import vm from 'node:vm';
import { randomUUID } from 'node:crypto';
import { isDeepStrictEqual } from 'node:util';
import * as metrics from '../speed-metrics.mjs'; import * as metrics from '../speed-metrics.mjs';
import { stripModuleSyntax } from '../scripts/build-bundle.mjs'; import { stripModuleSyntax } from '../scripts/build-bundle.mjs';
@@ -61,6 +63,7 @@ export function backendHarness({
remoteFetch=null, remoteFetch=null,
execFileImpl=null, execFileImpl=null,
sourceText=null, sourceText=null,
clock=null,
metricsImplementation=metrics, metricsImplementation=metrics,
}={}) { }={}) {
const mainUrl = pluginRootPath ? `file://${pluginRootPath}/sidecars/panel/main.mjs` : 'file:///test/sidecars/panel/main.mjs'; const mainUrl = pluginRootPath ? `file://${pluginRootPath}/sidecars/panel/main.mjs` : 'file:///test/sidecars/panel/main.mjs';
@@ -68,7 +71,11 @@ export function backendHarness({
const source = stripEsmSyntax(sourceText ?? loadCombinedBackendSource(), mainUrl); const source = stripEsmSyntax(sourceText ?? loadCombinedBackendSource(), mainUrl);
const state={calls:[],errors:[],saves:[],settings,trajectories,transcripts,transcriptMtimeMs:1,userStatus,quotaSummary,localCatalog,remoteCatalog,pluginManifest,hasGitDir,deepStats,deepStatsMtimeMs:1}; const state={calls:[],errors:[],saves:[],settings,trajectories,transcripts,transcriptMtimeMs:1,userStatus,quotaSummary,localCatalog,remoteCatalog,pluginManifest,hasGitDir,deepStats,deepStatsMtimeMs:1};
const ctx={ const ctx={
...metricsImplementation, URL, AbortSignal, Buffer, ...metricsImplementation, URL, AbortSignal, Buffer, isDeepStrictEqual, randomUUID,
...(clock ? { Date: class extends Date {
constructor(...args) { super(...(args.length ? args : [clock()])); }
static now() { return clock(); }
} } : {}),
process:{platform:'win32',env:{ANTIGRAVITY_EXECUTABLE_DATA_DIR:'/test-data',ANTIGRAVITY_LS_ADDRESS:'test.invalid',ANTIGRAVITY_CSRF_TOKEN:'test'}}, process:{platform:'win32',env:{ANTIGRAVITY_EXECUTABLE_DATA_DIR:'/test-data',ANTIGRAVITY_LS_ADDRESS:'test.invalid',ANTIGRAVITY_CSRF_TOKEN:'test'}},
console:{error:m=>state.errors.push(m)}, console:{error:m=>state.errors.push(m)},
cpSync:()=>{}, cpSync:()=>{},
@@ -132,6 +139,9 @@ export function backendHarness({
state.remoteCatalog = parsed; state.remoteCatalog = parsed;
} }
}, },
writeTrajectoryCacheFile:(p,data)=>{
state.saves.push({path:p,data:JSON.parse(JSON.stringify(data))});
},
homedir:()=>'/test-home',dirname:path.dirname,join:path.join,basename:path.basename,fileURLToPath:()=>mainPath, homedir:()=>'/test-home',dirname:path.dirname,join:path.join,basename:path.basename,fileURLToPath:()=>mainPath,
Response:class {constructor(body,options){this.body=body;this.options=options;}}, Response:class {constructor(body,options){this.body=body;this.options=options;}},
SidecarApp:class {page(){} api(){} run(){}}, SidecarApp:class {page(){} api(){} run(){}},
@@ -154,6 +164,6 @@ export function backendHarness({
return {ok:true,json:async()=>data}; return {ok:true,json:async()=>data};
}, },
}; };
vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,computeStepCost,resolveModelInfo,inferFamilyFromProviderOrKey,isArgonModelIdentifier,isCarbonModelIdentifier,getBaseModelLabel,formatUpstreamModelId,PLACEHOLDER_MAP,normalizeQuotaFraction,classifyOfficialBucketWindow,classifyQuotaPoolIdentity,buildOfficialQuotaPools,resolveTimeWindow,sanitizeCatalogPayload,rebuildActiveCatalog,syncCloudCatalog,getCloudStatus,isValidSemver,compareSemver,performPluginUpdate,resolveMigratedGitRemoteUrl,loadSettings,executeSettingsAction,executeModelContextWindowAction,executeResetSettingsAction,executeRebuildCacheAction,clearRuntimeCaches,normalizeTopbarCapsuleSlots,normalizeHoverModules,normalizeOverviewModules,normalizeOverviewMetrics,normalizeStepTableColumns};',ctx); vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,executeTelemetryAction,computeStepCost,resolveModelInfo,inferFamilyFromProviderOrKey,isArgonModelIdentifier,isCarbonModelIdentifier,getBaseModelLabel,formatUpstreamModelId,PLACEHOLDER_MAP,normalizeQuotaFraction,classifyOfficialBucketWindow,classifyQuotaPoolIdentity,buildOfficialQuotaPools,resolveTimeWindow,sanitizeCatalogPayload,rebuildActiveCatalog,syncCloudCatalog,getCloudStatus,isValidSemver,compareSemver,performPluginUpdate,resolveMigratedGitRemoteUrl,loadSettings,executeSettingsAction,executeModelContextWindowAction,executeResetSettingsAction,executeRebuildCacheAction,clearRuntimeCaches,normalizeTopbarCapsuleSlots,normalizeHoverModules,normalizeOverviewModules,normalizeOverviewMetrics,normalizeStepTableColumns};',ctx);
return {...ctx.api,state}; return {...ctx.api,state};
} }
+178
View File
@@ -1,6 +1,10 @@
import test from 'node:test'; import test from 'node:test';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { existsSync, mkdtempSync, readFileSync, readdirSync, rmdirSync, unlinkSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import {backendHarness} from './backend-harness.mjs'; import {backendHarness} from './backend-harness.mjs';
import { writeTrajectoryCacheFile } from '../backend/trajectory-cache-file.mjs';
const raw={trajectory:{steps:[{status:'CORTEX_STEP_STATUS_DONE',metadata:{ const raw={trajectory:{steps:[{status:'CORTEX_STEP_STATUS_DONE',metadata:{
createdAt:'2026-01-01T00:00:00Z',finishedGeneratingAt:'2026-01-01T00:00:10Z', createdAt:'2026-01-01T00:00:00Z',finishedGeneratingAt:'2026-01-01T00:00:10Z',
@@ -8,6 +12,37 @@ const raw={trajectory:{steps:[{status:'CORTEX_STEP_STATUS_DONE',metadata:{
},plannerResponse:{response:'answer',thinkingDuration:'5s'}}],generatorMetadata:[{stepIndices:[0],chatModel:{timeToFirstToken:'3s',streamingDuration:'7s'}}]}}; },plannerResponse:{response:'answer',thinkingDuration:'5s'}}],generatorMetadata:[{stepIndices:[0],chatModel:{timeToFirstToken:'3s',streamingDuration:'7s'}}]}};
const old={signature:'v5:old',title:'test',steps:[{stepIndex:0,modelKey:'MODEL_PLACEHOLDER_M418',inputTokens:100,cacheReadTokens:200,outputTokens:600,thinkingTokens:100,responseTokens:500,createdAtMs:1767225600000,ttftSec:0.4,streamTokPerSec:200,streamTokens:500,streamDurationSec:2.5,totalDurationSec:10,totalTokPerSec:60}]}; const old={signature:'v5:old',title:'test',steps:[{stepIndex:0,modelKey:'MODEL_PLACEHOLDER_M418',inputTokens:100,cacheReadTokens:200,outputTokens:600,thinkingTokens:100,responseTokens:500,createdAtMs:1767225600000,ttftSec:0.4,streamTokPerSec:200,streamTokens:500,streamDurationSec:2.5,totalDurationSec:10,totalTokPerSec:60}]};
test('trajectory checkpoints preserve updated metadata and ignore bytes replaced by another writer', () => {
const directory = mkdtempSync(fileURLToPath(new URL('./.checkpoint-', import.meta.url)));
const file = join(directory, 'trajectory_usage_cache.json');
const state = {
'会话📝': { title: 'first', steps: [{ stepIndex: 1, model: '模型', inputTokens: 10 }] },
second: { title: 'second', steps: [{ stepIndex: 2, outputTokens: 4 }] },
};
const read = () => JSON.parse(readFileSync(file, 'utf8'));
try {
writeTrajectoryCacheFile(file, state);
assert.deepEqual(read(), state);
state['会话📝'].title = 'new metadata';
state.second.steps = [{ stepIndex: 2, outputTokens: 8 }];
writeTrajectoryCacheFile(file, state);
assert.deepEqual(read(), state);
const external = read();
external['会话📝'].steps[0].inputTokens = 90;
writeFileSync(file, JSON.stringify(external));
writeTrajectoryCacheFile(file, state);
assert.deepEqual(read(), state);
writeTrajectoryCacheFile(file, {});
assert.deepEqual(read(), {});
assert.deepEqual(readdirSync(directory), ['trajectory_usage_cache.json']);
} finally {
if (existsSync(file)) unlinkSync(file);
rmdirSync(directory);
}
});
test('failed migration retains all accounting, makes legacy speed and TTFT unavailable',async()=>{ test('failed migration retains all accounting, makes legacy speed and TTFT unavailable',async()=>{
const h=backendHarness({cache:{test:old},trajectories:{test:new Error('offline')}}); const h=backendHarness({cache:{test:old},trajectories:{test:new Error('offline')}});
const p=await h.buildTelemetryPayloadInternal('test'); const p=await h.buildTelemetryPayloadInternal('test');
@@ -648,6 +683,118 @@ test('cached incomplete timing is refreshed once without invalidating completed
); );
}); });
test('unchanged running steps skip cache writes, but corrected timing with the same summary is persisted', async () => {
const time = '2026-01-01T00:00:10Z';
const live = structuredClone(raw);
live.trajectory.steps[0].status = 'CORTEX_STEP_STATUS_GENERATING';
const h = backendHarness({
trajectories: { live },
summaries: { live: { stepCount: 1, lastModifiedTime: time, status: 'CASCADE_RUN_STATUS_RUNNING' } },
});
const pending = await h.buildTelemetryPayloadInternal('live');
assert.equal(pending.activeConversation.latestTokPerSec, null);
const writes = h.state.saves.length;
assert.ok(writes > 0);
await h.buildTelemetryPayloadInternal('live');
assert.equal(h.state.saves.length, writes);
h.state.trajectories.live = raw;
const completed = await h.buildTelemetryPayloadInternal('live');
assert.equal(completed.activeConversation.latestTokPerSec, 60);
assert.equal(h.state.saves.length, writes + 1);
assert.equal(h.state.saves.at(-1).data.live.steps[0].totalTokPerSec, 60);
});
test('display step revisions omit only matching rows and invalidate on timing changes', async () => {
const time = '2026-01-01T00:00:10Z';
const live = structuredClone(raw);
live.trajectory.steps[0].status = 'CORTEX_STEP_STATUS_GENERATING';
const h = backendHarness({
trajectories: { live },
summaries: { live: { stepCount: 1, lastModifiedTime: time, status: 'CASCADE_RUN_STATUS_RUNNING' } },
});
const request = { conversationId: 'live', stepDetails: 'display' };
const get = async (stepRevision) => JSON.parse((await h.executeTelemetryAction({
...request, stepRevision
})).body);
const initial = await get('');
assert.equal(initial.stepsUnchanged, false);
assert.equal(initial.activeConversation.recentSteps[0].tokPerSec, null);
const same = await get(initial.stepRevision);
assert.equal(same.stepsUnchanged, true);
assert.equal(same.stepRevision, initial.stepRevision);
assert.equal(same.activeConversation.recentSteps, undefined);
h.state.trajectories.live = raw;
const changed = await get(initial.stepRevision);
assert.equal(changed.stepsUnchanged, false);
assert.notEqual(changed.stepRevision, initial.stepRevision);
assert.equal(changed.activeConversation.recentSteps[0].tokPerSec, 60);
assert.equal((await get()).activeConversation.recentSteps[0].tokPerSec, 60);
});
test('simultaneous ranges share the trajectory scan while keeping their own totals', async () => {
const h = backendHarness({
trajectories: { live: raw },
summaries: { live: { stepCount: 1, lastModifiedTime: '2026-01-01T00:00:10Z' } },
});
const [all, custom] = await Promise.all([
h.buildTelemetryPayloadInternal('live', false, { range: 'all' }),
h.buildTelemetryPayloadInternal('live', false, { range: 'custom', startMs: 1, endMs: 2 }),
]);
assert.equal(all.consumption.account.totalTokens, 900);
assert.equal(custom.consumption.account.totalTokens, 0);
assert.equal(h.state.calls.filter((call) => call.method === 'GetAllCascadeTrajectories').length, 1);
assert.equal(h.state.calls.filter((call) => call.method === 'GetCascadeTrajectory').length, 1);
});
test('cached usage follows rolling boundaries and reprices unchanged steps', async () => {
const { extractModelSteps } = await import('../speed-metrics.mjs');
const [step] = extractModelSteps(raw.trajectory.steps, raw.trajectory.generatorMetadata);
const modelKey = 'test-metered-model';
let now = Date.parse('2026-03-08T07:00:00Z');
const priceCatalog = (price) => ({
schemaVersion: 1,
pricing: {
[modelKey]: { input: price, cache: price, output: price, family: 'Gemini', short: modelKey },
},
});
const h = backendHarness({
clock: () => now,
localCatalog: priceCatalog(100),
cache: {
live: {
signature: 'v10-model-identity:disk:0',
contextLimitTelemetry: true, turnRailTelemetry: true, contextGroupsTelemetry: true,
speedClearedTelemetry: true, subagentRefs: [],
steps: [
{ ...step, modelKey, createdAtMs: now - 86400000, turnIndex: null },
{ ...step, modelKey, stepIndex: 2, createdAtMs: now + 1, inputTokens: 120, turnIndex: null },
],
},
},
});
const build = () => h.buildTelemetryPayloadInternal('live', false, { range: '24h' });
const first = await build();
assert.equal(first.consumption.account.totalTokens, 900);
assert.equal(first.consumption.account.costUsd, 0.09);
now += 1;
const crossing = await build();
assert.equal(crossing.consumption.account.totalTokens, 920);
assert.equal(crossing.consumption.account.calls, 1);
now += 1;
h.state.localCatalog = priceCatalog(1000);
h.rebuildActiveCatalog();
const repriced = await build();
assert.equal(repriced.consumption.account.totalTokens, 920);
assert.equal(repriced.consumption.account.costUsd, 0.92);
assert.equal(repriced.activeConversation.recentSteps[0].costUsd, 0.92);
});
test('modelBreakdown exposes avgTtftSec, cacheHitPct, and subagent scoped breakdowns + fit math helpers', async () => { test('modelBreakdown exposes avgTtftSec, cacheHitPct, and subagent scoped breakdowns + fit math helpers', async () => {
const { const {
computeLinearFit, computeLinearFit,
@@ -958,6 +1105,37 @@ test('assigns unified rootTurnIndex across interleaved main and subagent steps s
assert.equal(subSteps[1].isRootTurnStart, false); assert.equal(subSteps[1].isRootTurnStart, false);
assert.equal(subSteps[1].isTurnStart, true); assert.equal(subSteps[1].isTurnStart, true);
assert.equal(subSteps[1].turnPrompt, 'Subagent internal brief'); assert.equal(subSteps[1].turnPrompt, 'Subagent internal brief');
const panel = JSON.parse((await h.executeTelemetryAction({
conversationId: 'root-turn', stepDetails: 'display'
})).body).activeConversation;
const full = JSON.parse((await h.executeTelemetryAction({
conversationId: 'root-turn'
})).body).activeConversation;
assert.equal(panel.recentSteps.length, full.recentSteps.length);
assert.equal(panel.agents.length, full.agents.length);
for (const [displaySteps, fullSteps] of [
[panel.recentSteps, full.recentSteps],
[panel.agents[1].recentSteps, full.agents[1].recentSteps],
]) {
assert.equal(displaySteps.length, fullSteps.length);
for (let i = 0; i < fullSteps.length; i++) {
assert.equal(displaySteps[i].rootTurnPrompt, fullSteps[i].rootTurnPrompt);
assert.equal(displaySteps[i].tokPerSec, fullSteps[i].tokPerSec);
assert.equal(displaySteps[i].contextTokens, fullSteps[i].contextTokens);
assert.ok(!Object.hasOwn(displaySteps[i], 'contextBreakdown'));
assert.ok(Object.hasOwn(fullSteps[i], 'contextBreakdown'));
}
}
const requested = { conversationId: 'root-turn', stepDetails: 'display' };
const initial = JSON.parse((await h.executeTelemetryAction({ ...requested, stepRevision: '' })).body);
const delta = JSON.parse((await h.executeTelemetryAction({
...requested, stepRevision: initial.stepRevision,
})).body);
assert.equal(delta.stepsUnchanged, true);
assert.equal(delta.activeConversation.recentSteps, undefined);
assert.equal(delta.activeConversation.agents[1].recentSteps, undefined);
assert.equal(delta.activeConversation.agents[1].stepCount, 2);
}); });
test('reconciles 8-group context breakdown with real API prompt+output tokens and auto-refreshes cached dropped groups', async () => { test('reconciles 8-group context breakdown with real API prompt+output tokens and auto-refreshes cached dropped groups', async () => {
@@ -83,8 +83,14 @@ test('cleared steps with a recorded generation end retain their original request
for(const status of ['CORTEX_STEP_STATUS_CANCELED','CORTEX_STEP_STATUS_ERROR','CORTEX_STEP_STATUS_GENERATING']){ for(const status of ['CORTEX_STEP_STATUS_CANCELED','CORTEX_STEP_STATUS_ERROR','CORTEX_STEP_STATUS_GENERATING']){
assert.equal(extractModelSteps([{...s,status}],[gm])[0].totalTokPerSec,null); assert.equal(extractModelSteps([{...s,status}],[gm])[0].totalTokPerSec,null);
} }
const [canceled]=extractModelSteps([{...s,status:'CORTEX_STEP_STATUS_CANCELED'}],[gm]);
assert.equal(speedMetric(canceled).reason,'canceled');
delete s.metadata.finishedGeneratingAt; delete s.metadata.finishedGeneratingAt;
assert.equal(extractModelSteps([s],[gm])[0].totalTokPerSec,null); assert.equal(extractModelSteps([s],[gm])[0].totalTokPerSec,null);
const [checkpoint]=extractModelSteps([{...s,type:'CORTEX_STEP_TYPE_CHECKPOINT'}],[gm]);
assert.equal(speedMetric(checkpoint).value,null);
assert.equal(speedMetric(checkpoint).reason,'compaction_timing_unavailable');
assert.equal(summarizeSpeed([checkpoint,canceled]).sampleCount,0);
}); });
test('zero output is a real zero; malformed or missing output counts cannot produce rates',()=>{ test('zero output is a real zero; malformed or missing output counts cannot produce rates',()=>{
const zero=parse({output:0,response:0,thinking:0}); const zero=parse({output:0,response:0,thinking:0});
+10 -8
View File
@@ -1958,9 +1958,10 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
'has-turn-rail class removed when showStepTurnRail is false' 'has-turn-rail class removed when showStepTurnRail is false'
); );
assert.equal( assert.equal(
stepTableWhileRailOff.querySelector('.turn-rail').hasAttribute('hidden'), Array.from(stepTableWhileRailOff.querySelectorAll('.turn-rail'))
.every((rail) => rail.hasAttribute('hidden')),
true, true,
'Turn rail DOM hidden when showStepTurnRail is false' 'No visible turn rail when showStepTurnRail is false'
); );
const stepHeaderThs = stepTableWhileRailOff.children[0].children[0].children; const stepHeaderThs = stepTableWhileRailOff.children[0].children[0].children;
assert.equal(stepHeaderThs.length, 9, 'StepsDetailView thead dynamically renders 9 columns'); assert.equal(stepHeaderThs.length, 9, 'StepsDetailView thead dynamically renders 9 columns');
@@ -2144,8 +2145,8 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
const row1Rail = stepRows[1].children[0].querySelector('.turn-rail'); const row1Rail = stepRows[1].children[0].querySelector('.turn-rail');
assert.equal(row0Rail.hasAttribute('hidden'), false); assert.equal(row0Rail.hasAttribute('hidden'), false);
assert.equal(row0Rail.classList.contains('is-latest'), true); assert.equal(row0Rail.classList.contains('is-latest'), true);
assert.equal(row0Rail.querySelector('.turn-rail-dot').classList.contains('is-cap'), true, 'Newest step in turn renders cap dot'); assert.equal(row0Rail.classList.contains('is-cap'), true, 'Newest step in turn renders cap dot');
assert.equal(row1Rail.querySelector('.turn-rail-dot').classList.contains('is-origin'), true, 'First step of user turn renders hollow origin dot'); assert.equal(row1Rail.classList.contains('is-origin'), true, 'First step of user turn renders hollow origin dot');
const turnPromptTipEl = stepsPane.querySelector('.turn-prompt-tip'); const turnPromptTipEl = stepsPane.querySelector('.turn-prompt-tip');
assert.equal(turnPromptTipEl.hasAttribute('hidden'), true, 'Prompt preview tooltip hidden initially'); assert.equal(turnPromptTipEl.hasAttribute('hidden'), true, 'Prompt preview tooltip hidden initially');
@@ -2438,17 +2439,18 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
assert.equal(multiStepRows[0].children[0].querySelector('.agent-badge').textContent, '子1'); assert.equal(multiStepRows[0].children[0].querySelector('.agent-badge').textContent, '子1');
assert.equal(multiStepRows[1].children[0].querySelector('.agent-badge').textContent, '主'); assert.equal(multiStepRows[1].children[0].querySelector('.agent-badge').textContent, '主');
assert.equal( assert.equal(
multiStepRows[0].children[0].querySelector('.turn-rail-dot').classList.contains('is-cap'), multiStepRows[0].children[0].querySelector('.turn-rail').classList.contains('is-cap'),
true, true,
'Interleaved subagent step at top joins unified rootTurnIndex rail as cap' 'Interleaved subagent step at top joins unified rootTurnIndex rail as cap'
); );
assert.equal( assert.equal(
multiStepRows[1].children[0].querySelector('.turn-rail-dot').hasAttribute('hidden'), multiStepRows[1].children[0].querySelector('.turn-rail').classList.contains('is-cap') ||
true, multiStepRows[1].children[0].querySelector('.turn-rail').classList.contains('is-origin'),
false,
'Middle main step connects continuously along unified rootTurnIndex rail' 'Middle main step connects continuously along unified rootTurnIndex rail'
); );
assert.equal( assert.equal(
multiStepRows[2].children[0].querySelector('.turn-rail-dot').classList.contains('is-origin'), multiStepRows[2].children[0].querySelector('.turn-rail').classList.contains('is-origin'),
true, true,
'Earliest main step anchors unified rootTurnIndex rail origin' 'Earliest main step anchors unified rootTurnIndex rail origin'
); );