mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-26 17:09:28 +08:00
perf(panel): add incremental step transport, memoized aggregation, atomic cache writes, and hidden-view gating
- Project display-only step fields in /api/telemetry, skip unchanged step payloads via stepRevision, coalesce identical client refreshes, and share in-flight backend trajectory scans across same-account requests - Reuse normalized step values and memoize up to two range aggregations in usage-aggregator gated by step timestamps, pricing revision, model overrides, timezone, and source identity; cache per-trajectory model facts and single-agent step preparation via WeakMap/WeakRef - Persist trajectory checkpoints atomically in trajectory-cache-file.mjs via chunked writevSync + renameSync while reusing serialized step byte slices for unchanged conversations - Render step turn-rail lines/dots via CSS pseudo-elements, allocate speed-reason nodes on demand, short-circuit unchanged table reconciliations, and cache per-series LOESS publication fits in SessionStepCharts - Gate DOM updates and timers across closed overlay panels, hover popups, inactive settings tabs, and unchanged ConsumptionView payloads - Distinguish canceled steps (CORTEX_STEP_STATUS_CANCELED) and untimed compaction steps from generic incomplete timing in speed-metrics and bilingual i18n labels
This commit is contained in:
+472
-353
File diff suppressed because it is too large
Load Diff
@@ -8,6 +8,8 @@
|
||||
|
||||
import { readFileSync, promises as fsPromises } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { isDeepStrictEqual } from 'node:util';
|
||||
import { handleAccountCredentialAction } from './account-switch.mjs';
|
||||
import {
|
||||
HERE,
|
||||
@@ -110,6 +112,84 @@ function sanitizePositiveFiniteMs(val) {
|
||||
return Number.isFinite(num) && num > 0 && num <= MAX_SAFE_DATE_MS ? Math.floor(num) : 0;
|
||||
}
|
||||
|
||||
function projectDisplayStep(st) {
|
||||
const {
|
||||
stepIndex, createdAtMs, isCompactionStep, modelKey, modelShort, modelLabel,
|
||||
modelUpstream, responseModel, modelSource, tokPerSec, ttftSec, totalDurationSec,
|
||||
streamDurationSec, selectedSpeedReason, contextTokens, inputTokens, cacheReadTokens,
|
||||
outputTokens, thinkingTokens, responseTokens, cacheHitPct, costUsd, agentId,
|
||||
agentCascadeId, agentLabel, agentBadge, agentRole, agentIndex, isSubagent,
|
||||
turnIndex, isTurnStart, isLatestTurn, turnPrompt, rootTurnIndex, isRootTurnStart,
|
||||
isRootLatestTurn, rootTurnPrompt,
|
||||
} = st;
|
||||
return {
|
||||
stepIndex, createdAtMs, isCompactionStep, modelKey, modelShort, modelLabel,
|
||||
modelUpstream, responseModel, modelSource, tokPerSec, ttftSec, totalDurationSec,
|
||||
streamDurationSec, selectedSpeedReason, contextTokens, inputTokens, cacheReadTokens,
|
||||
outputTokens, thinkingTokens, responseTokens, cacheHitPct, costUsd, agentId,
|
||||
agentCascadeId, agentLabel, agentBadge, agentRole, agentIndex, isSubagent,
|
||||
turnIndex, isTurnStart, isLatestTurn, turnPrompt, rootTurnIndex, isRootTurnStart,
|
||||
isRootLatestTurn, rootTurnPrompt,
|
||||
};
|
||||
}
|
||||
|
||||
let lastDisplaySteps = null;
|
||||
const displayStepFields = Object.keys(projectDisplayStep({}));
|
||||
|
||||
function haveSameDisplaySteps(previous, current) {
|
||||
if (!previous || !current) return previous === current;
|
||||
if (previous.length !== current.length) return false;
|
||||
for (let i = 0; i < current.length; i++) {
|
||||
const before = previous[i];
|
||||
const after = current[i];
|
||||
for (const key of displayStepFields) {
|
||||
if (before[key] !== after[key]) return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function projectDisplayTelemetry(payload, requestedRevision) {
|
||||
const active = payload.activeConversation;
|
||||
const agents = active.agents;
|
||||
const sourceSteps = [active.recentSteps, ...agents.map((agent) => agent.recentSteps)];
|
||||
let projected;
|
||||
let revision;
|
||||
if (typeof requestedRevision === 'string') {
|
||||
const scope = [
|
||||
payload.account?.status,
|
||||
payload.account?.email || payload.account?.name || '',
|
||||
active.cascadeId,
|
||||
...agents.map((agent) => agent.agentId),
|
||||
];
|
||||
const previous = lastDisplaySteps;
|
||||
if (previous && isDeepStrictEqual(scope, previous.scope) &&
|
||||
sourceSteps.every((steps, index) => (steps && previous.sources[index]?.deref() === steps) ||
|
||||
haveSameDisplaySteps(previous.steps[index], steps))) {
|
||||
({ revision, steps: projected } = previous);
|
||||
previous.sources = sourceSteps.map((steps) => steps ? new WeakRef(steps) : undefined);
|
||||
} else {
|
||||
revision = randomUUID();
|
||||
projected = sourceSteps.map((steps) => steps?.map(projectDisplayStep));
|
||||
lastDisplaySteps = { scope, steps: projected, revision,
|
||||
sources: sourceSteps.map((steps) => steps ? new WeakRef(steps) : undefined) };
|
||||
}
|
||||
}
|
||||
projected ||= sourceSteps.map((steps) => steps?.map(projectDisplayStep));
|
||||
const stepsUnchanged = revision !== undefined && requestedRevision === revision;
|
||||
return {
|
||||
...payload,
|
||||
...(revision ? { stepRevision: revision, stepsUnchanged } : {}),
|
||||
activeConversation: {
|
||||
...active,
|
||||
recentSteps: stepsUnchanged ? undefined : projected[0],
|
||||
agents: agents.map((agent, index) => projected[index + 1]
|
||||
? { ...agent, recentSteps: stepsUnchanged ? undefined : projected[index + 1] }
|
||||
: agent),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function executeTelemetryAction(data, { onRestart = null } = {}) {
|
||||
const rawConvId = String(
|
||||
data?.conversationId || process.env.ANTIGRAVITY_CONVERSATION_ID || ''
|
||||
@@ -148,11 +228,14 @@ export async function executeTelemetryAction(data, { onRestart = null } = {}) {
|
||||
scheduleSidecarRestart(150);
|
||||
}
|
||||
}
|
||||
const responsePayload = data?.stepDetails === 'display'
|
||||
? projectDisplayTelemetry(payload, data.stepRevision)
|
||||
: payload;
|
||||
return {
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
headers: { 'Cache-Control': 'no-store' },
|
||||
body: JSON.stringify(payload),
|
||||
body: JSON.stringify(responsePayload),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ import { homedir } from 'node:os';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { inferCompactionStepModels, normalizeCachedStep } from '../speed-metrics.mjs';
|
||||
import { writeTrajectoryCacheFile } from './trajectory-cache-file.mjs';
|
||||
import {
|
||||
DEFAULT_HOVER_MODULES,
|
||||
DEFAULT_OVERVIEW_METRICS,
|
||||
@@ -227,9 +228,11 @@ export function loadJson(filePath, fallback) {
|
||||
export function saveJson(filePath, data) {
|
||||
try {
|
||||
mkdirSync(DATA_DIR, { recursive: true });
|
||||
const serialized =
|
||||
filePath === CACHE_FILE ? JSON.stringify(data) : JSON.stringify(data, null, 2);
|
||||
writeFileSync(filePath, serialized, 'utf8');
|
||||
if (filePath === CACHE_FILE) {
|
||||
writeTrajectoryCacheFile(filePath, data);
|
||||
} else {
|
||||
writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf8');
|
||||
}
|
||||
return true;
|
||||
} catch (err) {
|
||||
console.error(`Failed writing ${filePath}: ${err.message}`);
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
|
||||
import { closeSync, existsSync, openSync, readFileSync, readSync, readdirSync, statSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { isDeepStrictEqual } from 'node:util';
|
||||
import {
|
||||
extractLiveActivity,
|
||||
extractModelSteps,
|
||||
@@ -905,8 +906,9 @@ export async function enumerateAndSyncConversations({
|
||||
!prev.turnRailTelemetry ||
|
||||
!prev.contextGroupsTelemetry ||
|
||||
metaChanged ||
|
||||
JSON.stringify(prev.steps) !== JSON.stringify(steps);
|
||||
!isDeepStrictEqual(prev.steps, steps);
|
||||
|
||||
if (!stepsChanged) cacheEntry.steps = prev.steps;
|
||||
trajectoryCache[conv.cascadeId] = cacheEntry;
|
||||
if (stepsChanged) {
|
||||
cacheDirty = true;
|
||||
|
||||
@@ -288,11 +288,16 @@ export function createStepModelResolver(dynamicModelMap) {
|
||||
) {
|
||||
return resolveModelInfo(modelKey, dynamicModelMap, apiProvider, modelDisplayName, responseModel);
|
||||
}
|
||||
const key = JSON.stringify([modelKey, apiProvider, modelDisplayName, responseModel]);
|
||||
let info = models.get(key);
|
||||
let providers = models.get(modelKey);
|
||||
if (!providers) models.set(modelKey, (providers = new Map()));
|
||||
let names = providers.get(apiProvider);
|
||||
if (!names) providers.set(apiProvider, (names = new Map()));
|
||||
let responses = names.get(modelDisplayName);
|
||||
if (!responses) names.set(modelDisplayName, (responses = new Map()));
|
||||
let info = responses.get(responseModel);
|
||||
if (!info) {
|
||||
info = resolveModelInfo(modelKey, dynamicModelMap, apiProvider, modelDisplayName, responseModel);
|
||||
models.set(key, info);
|
||||
responses.set(responseModel, info);
|
||||
}
|
||||
return info;
|
||||
};
|
||||
|
||||
@@ -32,6 +32,7 @@ import {
|
||||
*/
|
||||
export const MODEL_PRICING = {};
|
||||
export const PLACEHOLDER_MAP = {};
|
||||
export let pricingCatalogRevision = 0;
|
||||
|
||||
/**
|
||||
* 校验字符串是否为合法的 SemVer 2.0 语义化版本号格式(支持 `-prerelease` 与 `+build` 元数据)。
|
||||
@@ -361,6 +362,7 @@ export function rebuildActiveCatalog() {
|
||||
|
||||
for (const k of Object.keys(PLACEHOLDER_MAP)) delete PLACEHOLDER_MAP[k];
|
||||
Object.assign(PLACEHOLDER_MAP, nextPlaceholders);
|
||||
pricingCatalogRevision += 1;
|
||||
|
||||
cloudSyncState.source = activeSource;
|
||||
cloudSyncState.catalogVersion = catalogVersion;
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
* 5. 调用 `aggregateMultiWindowUsage` 完成全量多窗口聚合,并组装精简的前端遥测 JSON。
|
||||
*/
|
||||
|
||||
import { isDeepStrictEqual } from 'node:util';
|
||||
import {
|
||||
extractLiveActivity,
|
||||
parseIsoMs,
|
||||
@@ -33,7 +34,7 @@ import {
|
||||
isArgonModelIdentifier,
|
||||
isCarbonModelIdentifier,
|
||||
} from './model-pricing.mjs';
|
||||
import { getCloudStatus } from './pricing-catalog.mjs';
|
||||
import { getCloudStatus, pricingCatalogRevision } from './pricing-catalog.mjs';
|
||||
import { buildOfficialQuotaPools } from './quota-pools.mjs';
|
||||
import {
|
||||
aggregateMultiWindowUsage,
|
||||
@@ -43,6 +44,9 @@ import {
|
||||
|
||||
const MAX_RECENT_CONVERSATIONS = 30;
|
||||
const POOL_PRIORITY_ORDER = ['Gemini', 'Argon', 'Carbon', 'Claude & GPT'];
|
||||
const inFlightTelemetrySources = new Map();
|
||||
const trajectoryModelFacts = new WeakMap();
|
||||
let lastMainPreparation = null;
|
||||
|
||||
function roundSessionCost(val) {
|
||||
if (!Number.isFinite(val) || val <= 0) return 0;
|
||||
@@ -59,24 +63,50 @@ function findTrajectoryCacheEntry(cascadeId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建全局 `modelKey -> responseModel` 已知映射表(单次轮询仅扫描一次 `trajectoryCache`)。
|
||||
*
|
||||
* @returns {Map<string, string>}
|
||||
*/
|
||||
function rememberModelContextLimit(limits, step) {
|
||||
const previous = limits.get(step.modelKey);
|
||||
if (!previous || step.createdAtMs > previous.at) {
|
||||
limits.set(step.modelKey, { tokens: step.reportedContextLimitTokens, at: step.createdAtMs });
|
||||
}
|
||||
}
|
||||
|
||||
function readTrajectoryModelFacts(steps) {
|
||||
const cached = trajectoryModelFacts.get(steps);
|
||||
if (cached) return cached;
|
||||
const upstream = new Map();
|
||||
const limits = new Map();
|
||||
let sortableLimits = true;
|
||||
for (const step of steps) {
|
||||
if (step?.modelKey && step.modelKey !== 'unknown' && step.responseModel) {
|
||||
upstream.set(step.modelKey, step.responseModel);
|
||||
}
|
||||
if (!step?.isCompactionStep && step?.reportedContextLimitTokens > 0) {
|
||||
sortableLimits &&= Number.isFinite(step.createdAtMs);
|
||||
rememberModelContextLimit(limits, step);
|
||||
}
|
||||
}
|
||||
const result = { upstream, limits: sortableLimits ? limits : null };
|
||||
trajectoryModelFacts.set(steps, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
/** 合并各会话的上游模型与上下文上限,步骤数组更新后重新提取对应会话的数据。 */
|
||||
function buildKnownUpstreamModelMap(contextLimits, currentAccountName) {
|
||||
const knownUpstreamByModelKey = new Map();
|
||||
for (const entry of Object.values(trajectoryCache)) {
|
||||
const trackContext = contextLimits && !entry.subagentSpec &&
|
||||
(!entry.accountName || entry.accountName === currentAccountName);
|
||||
for (const s of entry?.steps || []) {
|
||||
if (s?.modelKey && s.modelKey !== 'unknown' && s.responseModel) {
|
||||
knownUpstreamByModelKey.set(s.modelKey, s.responseModel);
|
||||
if (!entry?.steps?.length) continue;
|
||||
const facts = readTrajectoryModelFacts(entry.steps);
|
||||
for (const [key, model] of facts.upstream) knownUpstreamByModelKey.set(key, model);
|
||||
if (entry.subagentSpec || (entry.accountName && entry.accountName !== currentAccountName)) continue;
|
||||
if (facts.limits) {
|
||||
for (const [key, limit] of facts.limits) {
|
||||
const previous = contextLimits.get(key);
|
||||
if (!previous || limit.at > previous.at) contextLimits.set(key, limit);
|
||||
}
|
||||
if (trackContext && !s.isCompactionStep && s.reportedContextLimitTokens > 0) {
|
||||
const prev = contextLimits.get(s.modelKey);
|
||||
if (!prev || s.createdAtMs > prev.at) {
|
||||
contextLimits.set(s.modelKey, { tokens: s.reportedContextLimitTokens, at: s.createdAtMs });
|
||||
} else {
|
||||
for (const step of entry.steps) {
|
||||
if (!step?.isCompactionStep && step?.reportedContextLimitTokens > 0) {
|
||||
rememberModelContextLimit(contextLimits, step);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -90,12 +120,14 @@ function buildKnownUpstreamModelMap(contextLimits, currentAccountName) {
|
||||
*
|
||||
* @param {object[]} activeSteps 当前会话的原始缓存步骤
|
||||
* @param {ReturnType<typeof createStepModelResolver>} resolveStepModel 模型身份与价格解析器
|
||||
* @param {Map<string, string>} [sharedUpstreamMap=null] 预先构建的已知上游模型映射表
|
||||
* @param {Map<string, string>} sharedUpstreamMap 预先构建的已知上游模型映射表
|
||||
* @param {object} agentFields 步骤所属代理的标签和标识
|
||||
*/
|
||||
function enrichActiveConversationSteps(
|
||||
activeSteps,
|
||||
resolveStepModel,
|
||||
sharedUpstreamMap = null
|
||||
sharedUpstreamMap,
|
||||
agentFields
|
||||
) {
|
||||
const sessionSpeed = summarizeSpeed(activeSteps);
|
||||
const sessionTtft = summarizeTtft(activeSteps);
|
||||
@@ -105,13 +137,7 @@ function enrichActiveConversationSteps(
|
||||
let sessionCacheReadTokens = 0;
|
||||
let sessionOutputTokens = 0;
|
||||
|
||||
const knownUpstreamByModelKey = sharedUpstreamMap || buildKnownUpstreamModelMap();
|
||||
for (const s of activeSteps) {
|
||||
if (s?.modelKey && s.modelKey !== 'unknown' && s.responseModel) {
|
||||
knownUpstreamByModelKey.set(s.modelKey, s.responseModel);
|
||||
}
|
||||
}
|
||||
|
||||
const knownUpstreamByModelKey = sharedUpstreamMap;
|
||||
const enrichedActiveSteps = activeSteps.map((st) => {
|
||||
const mInfo = resolveStepModel(st);
|
||||
const costUsd = computeStepCost(st, mInfo.pricing);
|
||||
@@ -121,7 +147,8 @@ function enrichActiveConversationSteps(
|
||||
if (costUsd === null) sessionUnpricedCalls++;
|
||||
sessionInputTokens += st.inputTokens;
|
||||
sessionCacheReadTokens += st.cacheReadTokens;
|
||||
sessionOutputTokens += resolveStepOutputTokens(st);
|
||||
const outputTokens = resolveStepOutputTokens(st);
|
||||
sessionOutputTokens += outputTokens;
|
||||
|
||||
const tokPerSec = metric.value;
|
||||
const totalPrompt = st.inputTokens + st.cacheReadTokens;
|
||||
@@ -167,7 +194,8 @@ function enrichActiveConversationSteps(
|
||||
inCostUsd: inCostUsd === null ? null : +inCostUsd.toFixed(4),
|
||||
cacheCostUsd: cacheCostUsd === null ? null : +cacheCostUsd.toFixed(4),
|
||||
outCostUsd: outCostUsd === null ? null : +outCostUsd.toFixed(4),
|
||||
contextTokens: st.inputTokens + st.cacheReadTokens + resolveStepOutputTokens(st),
|
||||
contextTokens: totalPrompt + outputTokens,
|
||||
...agentFields,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -450,6 +478,30 @@ function extractActiveContextTelemetry(
|
||||
};
|
||||
}
|
||||
|
||||
function prepareAgentSteps(rawSteps, resolveStepModel, upstream, agentFields, reuseInputs) {
|
||||
for (const [key, model] of readTrajectoryModelFacts(rawSteps).upstream) upstream.set(key, model);
|
||||
const previous = lastMainPreparation;
|
||||
if (reuseInputs && previous?.rawSteps === rawSteps &&
|
||||
isDeepStrictEqual(previous.inputs, reuseInputs) && isDeepStrictEqual(previous.upstream, upstream)) {
|
||||
const prepared = previous.prepared.deref();
|
||||
if (prepared) return prepared;
|
||||
}
|
||||
const enrichedRes = enrichActiveConversationSteps(rawSteps, resolveStepModel, upstream, agentFields);
|
||||
const taggedSteps = enrichedRes.enrichedActiveSteps;
|
||||
const prepared = {
|
||||
enrichedRes,
|
||||
recentSteps: taggedSteps.slice().reverse(),
|
||||
ctxRes: extractActiveContextTelemetry(taggedSteps, enrichedRes.latestEnriched,
|
||||
enrichedRes.sessionInputTokens, enrichedRes.sessionCacheReadTokens),
|
||||
modelBreakdown: buildScopedModelBreakdown(taggedSteps, resolveStepModel),
|
||||
};
|
||||
// 单代理行可跨轮询复用。内存紧张时允许回收,运行状态仍单独实时组装。
|
||||
if (reuseInputs) {
|
||||
lastMainPreparation = { rawSteps, inputs: reuseInputs, upstream, prepared: new WeakRef(prepared) };
|
||||
}
|
||||
return prepared;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建单个代理(主代理或子代理)的标准遥测单元对象。
|
||||
*/
|
||||
@@ -470,29 +522,24 @@ function buildAgentUnitTelemetry({
|
||||
resolveStepModel,
|
||||
knownUpstreamByModelKey,
|
||||
includeRecentSteps = true,
|
||||
reuseInputs = null,
|
||||
}) {
|
||||
const enrichedRes = enrichActiveConversationSteps(
|
||||
const { enrichedRes, ctxRes, modelBreakdown, recentSteps } = prepareAgentSteps(
|
||||
rawSteps,
|
||||
resolveStepModel,
|
||||
knownUpstreamByModelKey
|
||||
knownUpstreamByModelKey,
|
||||
{
|
||||
agentId,
|
||||
agentCascadeId: cascadeId,
|
||||
agentLabel,
|
||||
agentBadge: badgeText,
|
||||
agentRole: role,
|
||||
agentIndex: index,
|
||||
isSubagent: !isMain,
|
||||
},
|
||||
reuseInputs
|
||||
);
|
||||
const taggedSteps = enrichedRes.enrichedActiveSteps.map((st) => ({
|
||||
...st,
|
||||
agentId,
|
||||
agentCascadeId: cascadeId,
|
||||
agentLabel,
|
||||
agentBadge: badgeText,
|
||||
agentRole: role,
|
||||
agentIndex: index,
|
||||
isSubagent: !isMain,
|
||||
}));
|
||||
const ctxRes = extractActiveContextTelemetry(
|
||||
taggedSteps,
|
||||
enrichedRes.latestEnriched,
|
||||
enrichedRes.sessionInputTokens,
|
||||
enrichedRes.sessionCacheReadTokens
|
||||
);
|
||||
const modelBreakdown = buildScopedModelBreakdown(taggedSteps, resolveStepModel);
|
||||
const taggedSteps = enrichedRes.enrichedActiveSteps;
|
||||
const lastModifiedMs =
|
||||
enrichedRes.latestEnriched?.createdAtMs || fallbackLastModMs || 0;
|
||||
const isRunning = status === 'CASCADE_RUN_STATUS_RUNNING';
|
||||
@@ -504,6 +551,7 @@ function buildAgentUnitTelemetry({
|
||||
return {
|
||||
enrichedRes,
|
||||
taggedSteps,
|
||||
recentSteps,
|
||||
ctxRes,
|
||||
telemetryUnit: {
|
||||
agentId,
|
||||
@@ -547,13 +595,44 @@ function buildAgentUnitTelemetry({
|
||||
enrichedRes.latestEnriched?.modelShort ||
|
||||
'模型未知',
|
||||
context: ctxRes.context,
|
||||
...(includeRecentSteps ? { recentSteps: taggedSteps.slice().reverse() } : {}),
|
||||
...(includeRecentSteps ? { recentSteps } : {}),
|
||||
modelBreakdown,
|
||||
lastModifiedMs,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function readTelemetrySources(requestedConvId, forceQuotaRefresh, currentAccountName, accountScope, userStatus) {
|
||||
const [allTrajRes, officialQuotaInfo, contextModelCatalog] = await Promise.all([
|
||||
callLsRpc('GetAllCascadeTrajectories', {}).catch(() => ({})),
|
||||
userStatus ? getOfficialQuotaSummary(forceQuotaRefresh, currentAccountName) : null,
|
||||
getContextModelCatalog(),
|
||||
]);
|
||||
|
||||
const sessions = await enumerateAndSyncConversations({
|
||||
summariesObj: allTrajRes?.trajectorySummaries || {},
|
||||
currentAccountName: accountScope,
|
||||
requestedConvId,
|
||||
forceRefresh: forceQuotaRefresh,
|
||||
});
|
||||
return { officialQuotaInfo, contextModelCatalog, sessions };
|
||||
}
|
||||
|
||||
function getTelemetrySources(requestedConvId, forceQuotaRefresh, currentAccountName, accountScope, userStatus) {
|
||||
const read = () => readTelemetrySources(
|
||||
requestedConvId, forceQuotaRefresh, currentAccountName, accountScope, userStatus
|
||||
);
|
||||
if (forceQuotaRefresh) return read();
|
||||
const key = JSON.stringify([requestedConvId || '', accountScope, Boolean(userStatus)]);
|
||||
const existing = inFlightTelemetrySources.get(key);
|
||||
if (existing) return existing;
|
||||
const pending = read().finally(() => {
|
||||
inFlightTelemetrySources.delete(key);
|
||||
});
|
||||
inFlightTelemetrySources.set(key, pending);
|
||||
return pending;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建完整的前端遥测载荷(核心内部实现,直接供单元测试沙箱调用)。
|
||||
*
|
||||
@@ -573,11 +652,10 @@ export async function buildTelemetryPayloadInternal(
|
||||
const accountStatus = currentAccountName ? 'signedIn' :
|
||||
userStatus && !userStatus.userTier && !userStatus.planStatus ? 'signedOut' : 'unknown';
|
||||
const accountScope = accountStatus === 'signedOut' ? null : currentAccountName;
|
||||
const [allTrajRes, officialQuotaInfo, contextModelCatalog] = await Promise.all([
|
||||
callLsRpc('GetAllCascadeTrajectories', {}).catch(() => ({})),
|
||||
userStatus ? getOfficialQuotaSummary(forceQuotaRefresh, currentAccountName) : null,
|
||||
getContextModelCatalog(),
|
||||
]);
|
||||
const { officialQuotaInfo, contextModelCatalog, sessions } = await getTelemetrySources(
|
||||
requestedConvId, forceQuotaRefresh, currentAccountName, accountScope, userStatus
|
||||
);
|
||||
const { conversations, activeConvSummary, activeCascadeId } = sessions;
|
||||
|
||||
const officialQuota = officialQuotaInfo?.data || null;
|
||||
const clientConfigs = userStatus?.cascadeModelConfigData?.clientModelConfigs || [];
|
||||
@@ -588,14 +666,6 @@ export async function buildTelemetryPayloadInternal(
|
||||
clientConfigs
|
||||
);
|
||||
|
||||
// 2. 枚举本地与 LS 会话,并增量同步历史轨迹步骤
|
||||
const { conversations, activeConvSummary, activeCascadeId } =
|
||||
await enumerateAndSyncConversations({
|
||||
summariesObj: allTrajRes?.trajectorySummaries || {},
|
||||
currentAccountName: accountScope,
|
||||
requestedConvId,
|
||||
forceRefresh: forceQuotaRefresh,
|
||||
});
|
||||
const resolveStepModel = createStepModelResolver(dynamicModelMap);
|
||||
|
||||
// 3. 计算当前活跃根会话及其子代理的步骤指标、10 通道上下文拆解与按模型汇总
|
||||
@@ -603,6 +673,9 @@ export async function buildTelemetryPayloadInternal(
|
||||
const knownUpstreamByModelKey = buildKnownUpstreamModelMap(reportedContextLimits, currentAccountName);
|
||||
const activeEntry = findTrajectoryCacheEntry(activeCascadeId);
|
||||
const activeSteps = activeEntry?.steps || [];
|
||||
const subagentSummaries = activeConvSummary?.subagents || [];
|
||||
if (subagentSummaries.length) lastMainPreparation = null;
|
||||
const modelInputs = { catalogRevision: pricingCatalogRevision, dynamicModelMap };
|
||||
const mainUnit = buildAgentUnitTelemetry({
|
||||
agentId: 'main',
|
||||
cascadeId: activeCascadeId,
|
||||
@@ -620,6 +693,7 @@ export async function buildTelemetryPayloadInternal(
|
||||
resolveStepModel,
|
||||
knownUpstreamByModelKey,
|
||||
includeRecentSteps: false,
|
||||
reuseInputs: subagentSummaries.length ? null : { ...modelInputs, activeCascadeId, accountScope },
|
||||
});
|
||||
|
||||
const enrichedActiveSteps = mainUnit.taggedSteps;
|
||||
@@ -638,11 +712,10 @@ export async function buildTelemetryPayloadInternal(
|
||||
const mainAgentTelemetry = mainUnit.telemetryUnit;
|
||||
const mainModelBreakdown = mainAgentTelemetry.modelBreakdown;
|
||||
|
||||
const subagentSummaries = activeConvSummary?.subagents || [];
|
||||
const activeFamilyCascadeIds = new Set(activeCascadeId ? [activeCascadeId.toLowerCase()] : []);
|
||||
const subAgentTelemetries = [];
|
||||
const allCombinedRawSteps = [...activeSteps];
|
||||
const allCombinedEnrichedSteps = [...enrichedActiveSteps];
|
||||
const allCombinedRawSteps = subagentSummaries.length ? activeSteps.slice() : [];
|
||||
const allCombinedEnrichedSteps = subagentSummaries.length ? enrichedActiveSteps.slice() : [];
|
||||
let totalRawSessionCostUsd = sessionCostUsd;
|
||||
let totalFamilyInputTokens = sessionInputTokens;
|
||||
let totalFamilyCacheReadTokens = sessionCacheReadTokens;
|
||||
@@ -654,7 +727,7 @@ export async function buildTelemetryPayloadInternal(
|
||||
activeFamilyCascadeIds.add(String(subCid || '').toLowerCase());
|
||||
const subEntry = findTrajectoryCacheEntry(subCid);
|
||||
const subRawSteps = subEntry?.steps || [];
|
||||
allCombinedRawSteps.push(...subRawSteps);
|
||||
for (const step of subRawSteps) allCombinedRawSteps.push(step);
|
||||
|
||||
const subSpec = subSum.subagentSpec || subEntry?.subagentSpec || null;
|
||||
const rawRole =
|
||||
@@ -684,7 +757,7 @@ export async function buildTelemetryPayloadInternal(
|
||||
includeRecentSteps: true,
|
||||
});
|
||||
|
||||
allCombinedEnrichedSteps.push(...subUnit.taggedSteps);
|
||||
for (const step of subUnit.taggedSteps) allCombinedEnrichedSteps.push(step);
|
||||
totalRawSessionCostUsd += subUnit.enrichedRes.sessionCostUsd;
|
||||
totalFamilyInputTokens += subUnit.enrichedRes.sessionInputTokens;
|
||||
totalFamilyCacheReadTokens += subUnit.enrichedRes.sessionCacheReadTokens;
|
||||
@@ -948,6 +1021,7 @@ export async function buildTelemetryPayloadInternal(
|
||||
activeFamilyCascadeIds,
|
||||
resolveStepModel,
|
||||
quotaPoolsMap,
|
||||
modelInputs,
|
||||
});
|
||||
|
||||
const emptyCycleSummary = () => ({
|
||||
@@ -1339,7 +1413,9 @@ export async function buildTelemetryPayloadInternal(
|
||||
stepCount: enrichedActiveSteps.length,
|
||||
hasSubagents: subAgentTelemetries.length > 0,
|
||||
subagentCount: subAgentTelemetries.length,
|
||||
totalStepsAllAgents: allCombinedEnrichedSteps.length,
|
||||
totalStepsAllAgents: subAgentTelemetries.length
|
||||
? allCombinedEnrichedSteps.length
|
||||
: enrichedActiveSteps.length,
|
||||
latestTokPerSec: latestEnriched?.tokPerSec ?? null,
|
||||
latestTtftSec: latestEnriched?.ttftSec ?? null,
|
||||
latestSpeedReason: latestEnriched?.selectedSpeedReason ?? null,
|
||||
@@ -1363,7 +1439,7 @@ export async function buildTelemetryPayloadInternal(
|
||||
activeModelUpstream:
|
||||
latestEnriched?.modelUpstream || latestEnriched?.modelShort || '模型未知',
|
||||
context,
|
||||
recentSteps: enrichedActiveSteps.slice().reverse(),
|
||||
recentSteps: mainUnit.recentSteps,
|
||||
modelBreakdown: mainModelBreakdown,
|
||||
agents: allAgents,
|
||||
aggregated: aggregatedTelemetry,
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import {
|
||||
closeSync, fstatSync, openSync, readFileSync, renameSync, statSync, unlinkSync, writevSync,
|
||||
} from 'node:fs';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
|
||||
let lastWrite = null;
|
||||
|
||||
function isSameFile(a, b) {
|
||||
return b.ino !== 0n && a.dev === b.dev && a.ino === b.ino &&
|
||||
a.size === b.size && a.mtimeNs === b.mtimeNs;
|
||||
}
|
||||
|
||||
function readReusableBytes(filePath, expected) {
|
||||
let fd;
|
||||
try {
|
||||
fd = openSync(filePath, 'r');
|
||||
const before = fstatSync(fd, { bigint: true });
|
||||
if (!isSameFile(before, expected) || before.ctimeNs !== expected.ctimeNs) return null;
|
||||
const bytes = readFileSync(fd);
|
||||
const after = fstatSync(fd, { bigint: true });
|
||||
return isSameFile(before, after) && before.ctimeNs === after.ctimeNs &&
|
||||
BigInt(bytes.length) === after.size ? bytes : null;
|
||||
} catch {
|
||||
return null;
|
||||
} finally {
|
||||
if (fd !== undefined) closeSync(fd);
|
||||
}
|
||||
}
|
||||
|
||||
// 只复用上次确认写入的步骤字节。扫描器用新数组替换变更步骤,每次仍重新序列化会话元数据。
|
||||
export function writeTrajectoryCacheFile(filePath, data) {
|
||||
const previous = lastWrite?.filePath === filePath ? lastWrite : null;
|
||||
const bytes = previous ? readReusableBytes(filePath, previous.file) : null;
|
||||
const ranges = new WeakMap();
|
||||
const parts = [];
|
||||
let position = 0;
|
||||
function append(part) {
|
||||
const buffer = typeof part === 'string' ? Buffer.from(part) : part;
|
||||
parts.push(buffer);
|
||||
position += buffer.length;
|
||||
}
|
||||
|
||||
append('{');
|
||||
let separator = '';
|
||||
for (const [id, entry] of Object.entries(data)) {
|
||||
const { steps, ...metadata } = entry;
|
||||
const header = JSON.stringify(metadata);
|
||||
append(`${separator}${JSON.stringify(id)}:${header.slice(0, -1)}${header === '{}' ? '' : ','}"steps":`);
|
||||
const range = bytes && previous.ranges.get(steps);
|
||||
const start = position;
|
||||
append(range ? bytes.subarray(range.start, range.end) : JSON.stringify(steps));
|
||||
ranges.set(steps, { start, end: position });
|
||||
append('}');
|
||||
separator = ',';
|
||||
}
|
||||
append('}');
|
||||
|
||||
const temporaryPath = `${filePath}.${randomUUID()}.tmp`;
|
||||
try {
|
||||
const fd = openSync(temporaryPath, 'wx');
|
||||
try {
|
||||
// 按块写入,避免再复制一份完整缓存到连续缓冲区。
|
||||
const batchSize = 256;
|
||||
for (let i = 0; i < parts.length; i += batchSize) {
|
||||
const batch = parts.slice(i, i + batchSize);
|
||||
const length = batch.reduce((sum, part) => sum + part.length, 0);
|
||||
if (writevSync(fd, batch) !== length) throw new Error('Incomplete cache write');
|
||||
}
|
||||
} finally {
|
||||
closeSync(fd);
|
||||
}
|
||||
const written = statSync(temporaryPath, { bigint: true });
|
||||
renameSync(temporaryPath, filePath);
|
||||
const file = statSync(filePath, { bigint: true });
|
||||
lastWrite = isSameFile(written, file) ? { filePath, file, ranges } : null;
|
||||
} finally {
|
||||
try { unlinkSync(temporaryPath); } catch {}
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@
|
||||
* 进行去重遍历聚合,输出前端消费分析与模型明细所需的完整统计结构。
|
||||
*/
|
||||
|
||||
import { isDeepStrictEqual } from 'node:util';
|
||||
import {
|
||||
MEASUREMENT_VERSION,
|
||||
accumulateSpeed,
|
||||
@@ -186,27 +187,13 @@ function createUsageBucket() {
|
||||
* 将单个模型步骤的 Token 与成本累加至目标统计桶。
|
||||
*
|
||||
* @param {ReturnType<typeof createUsageBucket>} bucket
|
||||
* @param {object} st 步骤对象
|
||||
* @param {ReturnType<StepModelResolver>} mInfo 模型信息
|
||||
* @param {number|null} stepCost 单步美元成本(未知时为 `null`)
|
||||
* @param {object} usage 已归一化的单步用量
|
||||
* @param {string} cascadeId 会话标识
|
||||
*/
|
||||
function accumulateStepIntoBucket(bucket, st, mInfo, stepCost, cascadeId) {
|
||||
const inTok = safeTok(st?.inputTokens);
|
||||
const cacheTok = safeTok(st?.cacheReadTokens);
|
||||
const outTok = safeTok(st?.outputTokens);
|
||||
const thinkTok = safeTok(st?.thinkingTokens);
|
||||
const respTok =
|
||||
st?.responseTokens !== undefined && st?.responseTokens !== null
|
||||
? safeTok(st.responseTokens)
|
||||
: Math.max(0, outTok - thinkTok);
|
||||
|
||||
const stepTotalTokens = inTok + cacheTok + outTok;
|
||||
const savedCost = mInfo?.pricing
|
||||
? (cacheTok / 1_000_000) * Math.max(0, mInfo.pricing.input - mInfo.pricing.cache)
|
||||
: 0;
|
||||
if (stepCost === null) bucket.unpricedCalls = (bucket.unpricedCalls || 0) + 1;
|
||||
const resolvedCost = Number.isFinite(stepCost) ? stepCost : 0;
|
||||
function accumulateStepIntoBucket(bucket, usage, cascadeId) {
|
||||
const { inTok, cacheTok, outTok, thinkTok, respTok, stepTotalTokens,
|
||||
resolvedCost, savedCost, unpriced } = usage;
|
||||
if (unpriced) bucket.unpricedCalls = (bucket.unpricedCalls || 0) + 1;
|
||||
bucket.calls += 1;
|
||||
if (cascadeId) bucket.conversationsSet.add(cascadeId);
|
||||
bucket.inputTokens += inTok;
|
||||
@@ -383,6 +370,75 @@ export function buildScopedModelBreakdown(steps, resolveStepModel) {
|
||||
return finalizeModelBreakdownMap(perModelStats);
|
||||
}
|
||||
|
||||
let lastUsageSnapshot = null;
|
||||
const MAX_TREND_TIMESTAMP_MS = 8_640_000_000_000_000;
|
||||
|
||||
function planUsageTrend(window, nowMs, earliest, latest) {
|
||||
const safeMs = (value, fallback) =>
|
||||
Number.isFinite(value) && value > 0 && value <= MAX_TREND_TIMESTAMP_MS ? value : fallback;
|
||||
const end = Math.max(safeMs(window.endMs, Math.max(nowMs, latest || nowMs)), latest);
|
||||
const defaultStart = end - 24 * 3600 * 1000;
|
||||
const start = window.key === 'all'
|
||||
? Math.min(safeMs(earliest, defaultStart), end - 3600 * 1000)
|
||||
: Math.min(safeMs(window.startMs, defaultStart), end);
|
||||
const hourly = window.key === 'today' || window.key === '24h' || window.key === '5h' ||
|
||||
end - start <= 72 * 3600 * 1000;
|
||||
const first = new Date(start);
|
||||
const last = new Date(end);
|
||||
if (hourly) {
|
||||
first.setMinutes(0, 0, 0);
|
||||
last.setMinutes(0, 0, 0);
|
||||
} else {
|
||||
first.setHours(0, 0, 0, 0);
|
||||
last.setHours(0, 0, 0, 0);
|
||||
}
|
||||
return { start, end, hourly, first: first.getTime(), last: last.getTime() };
|
||||
}
|
||||
|
||||
function sameUsageEntries(previous, current) {
|
||||
return previous.length === current.length && current.every((entry, index) => {
|
||||
const before = previous[index];
|
||||
return entry.steps === before.steps && entry.cascadeId === before.cascadeId &&
|
||||
entry.appSource === before.appSource && entry.isCurrentConv === before.isCurrentConv;
|
||||
});
|
||||
}
|
||||
|
||||
function sortedUsageTimestamps(entries) {
|
||||
const dates = new Float64Array(entries.reduce((sum, entry) => sum + entry.steps.length, 0));
|
||||
let count = 0;
|
||||
for (const { steps } of entries) {
|
||||
for (const step of steps) {
|
||||
const date = Number(step?.createdAtMs);
|
||||
if (date > 0) dates[count++] = date;
|
||||
}
|
||||
}
|
||||
return dates.subarray(0, count).sort();
|
||||
}
|
||||
|
||||
function usageTimestampBoundary(dates, value, inclusive) {
|
||||
let start = 0;
|
||||
let end = dates.length;
|
||||
while (start < end) {
|
||||
const i = (start + end) >>> 1;
|
||||
if (dates[i] < value || (inclusive && dates[i] === value)) start = i + 1;
|
||||
else end = i;
|
||||
}
|
||||
return start;
|
||||
}
|
||||
|
||||
function sameUsageWindows(previous, current, dates) {
|
||||
return previous.length === current.length && current.every((window, index) => {
|
||||
const before = previous[index];
|
||||
return before.key === window.key && before.label === window.label &&
|
||||
(before.startMs === window.startMs ||
|
||||
usageTimestampBoundary(dates, before.startMs, false) ===
|
||||
usageTimestampBoundary(dates, window.startMs, false)) &&
|
||||
(before.endMs === window.endMs ||
|
||||
usageTimestampBoundary(dates, before.endMs, true) ===
|
||||
usageTimestampBoundary(dates, window.endMs, true));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 聚合所有预设时间窗口、当前选定窗口、趋势图、年度月序列、来源占比与分模型统计。
|
||||
*
|
||||
@@ -393,6 +449,7 @@ export function buildScopedModelBreakdown(steps, resolveStepModel) {
|
||||
* activeCascadeId?: string|null,
|
||||
* activeFamilyCascadeIds?: Set<string>|null,
|
||||
* resolveStepModel: StepModelResolver
|
||||
* modelInputs?: { catalogRevision: number, dynamicModelMap: Map }
|
||||
* }} params
|
||||
*/
|
||||
export function aggregateMultiWindowUsage({
|
||||
@@ -403,6 +460,7 @@ export function aggregateMultiWindowUsage({
|
||||
activeFamilyCascadeIds = null,
|
||||
resolveStepModel,
|
||||
quotaPoolsMap = null,
|
||||
modelInputs = null,
|
||||
}) {
|
||||
const rawFamilyIds =
|
||||
activeFamilyCascadeIds instanceof Set
|
||||
@@ -456,11 +514,13 @@ export function aggregateMultiWindowUsage({
|
||||
}
|
||||
const hasDedicatedCarbonPool = poolCycleBuckets.has('Carbon');
|
||||
const hasDedicatedArgonPool = poolCycleBuckets.has('Argon');
|
||||
const selectedAccountBucket = createUsageBucket();
|
||||
const selectedSessionBucket = createUsageBucket();
|
||||
const poolByModel = new Map();
|
||||
const selectedAccountBucket = accountBuckets[selectedWindow.key] || createUsageBucket();
|
||||
const selectedSessionBucket = sessionBuckets[selectedWindow.key] || createUsageBucket();
|
||||
const perModelStats = new Map();
|
||||
const selectedWindowSteps = [];
|
||||
let earliestSelectedStepMs = Infinity;
|
||||
let latestSelectedStepMs = 0;
|
||||
|
||||
const currentYear = new Date(nowMs).getFullYear();
|
||||
const monthlySeries = Array.from({ length: 12 }, (_, idx) => ({
|
||||
@@ -551,6 +611,33 @@ export function aggregateMultiWindowUsage({
|
||||
});
|
||||
}
|
||||
|
||||
const timeZone = modelInputs ? new Intl.DateTimeFormat().resolvedOptions().timeZone : '';
|
||||
const quotaWindows = Array.from(poolCycleBuckets, ([key, { start5hMs, startWkMs }]) => [
|
||||
{ key: `${key}:5h`, startMs: start5hMs, endMs: nowMs },
|
||||
{ key: `${key}:week`, startMs: startWkMs, endMs: nowMs },
|
||||
]).flat();
|
||||
const windows = [selectedWindow, ...Object.values(presetWindows), ...quotaWindows];
|
||||
const snapshot = lastUsageSnapshot;
|
||||
const sameSnapshot = modelInputs && snapshot && timeZone === snapshot.timeZone &&
|
||||
currentYear === snapshot.currentYear && modelInputs.catalogRevision === snapshot.modelInputs.catalogRevision &&
|
||||
isDeepStrictEqual(modelInputs.dynamicModelMap, snapshot.modelInputs.dynamicModelMap) &&
|
||||
sameUsageEntries(snapshot.entries, allEntriesToAggregate);
|
||||
const previous = sameSnapshot ? snapshot.ranges.get(selectedWindow.key) : null;
|
||||
if (previous) {
|
||||
// 时钟继续前进,只有实际有步骤跨过窗口边界时才重新聚合。
|
||||
const trend = planUsageTrend(selectedWindow, nowMs, previous.earliest, previous.latest);
|
||||
if (
|
||||
trend.hourly === previous.trend.hourly && trend.first === previous.trend.first &&
|
||||
trend.last === previous.trend.last &&
|
||||
sameUsageWindows(previous.windows, windows,
|
||||
snapshot.dates ??= sortedUsageTimestamps(allEntriesToAggregate))
|
||||
) {
|
||||
snapshot.ranges.delete(selectedWindow.key);
|
||||
snapshot.ranges.set(selectedWindow.key, previous);
|
||||
return { ...previous.result, selectedWindow, trendStartMs: trend.start, trendEndMs: trend.end };
|
||||
}
|
||||
}
|
||||
|
||||
for (const entry of allEntriesToAggregate) {
|
||||
const { cascadeId, isCurrentConv } = entry;
|
||||
const srcKey = entry.appSource || 'standalone';
|
||||
@@ -572,6 +659,11 @@ export function aggregateMultiWindowUsage({
|
||||
const resolvedCost = Number.isFinite(stepCost) ? stepCost : 0;
|
||||
const unpriced = stepCost === null ? 1 : 0;
|
||||
const tMs = Number(st.createdAtMs) > 0 ? Number(st.createdAtMs) : 0;
|
||||
const savedCost = mInfo.pricing
|
||||
? (cacheTok / 1_000_000) * Math.max(0, mInfo.pricing.input - mInfo.pricing.cache)
|
||||
: 0;
|
||||
const stepUsage = { inTok, cacheTok, outTok, thinkTok, respTok, stepTotalTokens,
|
||||
resolvedCost, savedCost, unpriced };
|
||||
|
||||
if (tMs > 0) {
|
||||
const stepDate = new Date(tMs);
|
||||
@@ -593,46 +685,36 @@ export function aggregateMultiWindowUsage({
|
||||
for (const k of presetKeys) {
|
||||
const w = presetWindows[k];
|
||||
if (k === 'all' || (tMs > 0 && tMs >= w.startMs && tMs <= w.endMs)) {
|
||||
accumulateStepIntoBucket(accountBuckets[k], st, mInfo, stepCost, cascadeId);
|
||||
accumulateStepIntoBucket(accountBuckets[k], stepUsage, cascadeId);
|
||||
if (isCurrentConv) {
|
||||
accumulateStepIntoBucket(sessionBuckets[k], st, mInfo, stepCost, cascadeId);
|
||||
accumulateStepIntoBucket(sessionBuckets[k], stepUsage, cascadeId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (poolCycleBuckets.size > 0 && tMs > 0 && tMs <= nowMs) {
|
||||
const stepPoolKey =
|
||||
hasDedicatedCarbonPool &&
|
||||
isCarbonModelIdentifier(
|
||||
st.modelKey,
|
||||
st.responseModel,
|
||||
mInfo.modelId,
|
||||
mInfo.label,
|
||||
st.modelDisplayName
|
||||
)
|
||||
? 'Carbon'
|
||||
: hasDedicatedArgonPool &&
|
||||
isArgonModelIdentifier(
|
||||
st.modelKey,
|
||||
st.responseModel,
|
||||
mInfo.modelId,
|
||||
mInfo.label,
|
||||
st.modelDisplayName
|
||||
)
|
||||
? 'Argon'
|
||||
: mInfo.family === 'Gemini' && poolCycleBuckets.has('Gemini')
|
||||
? 'Gemini'
|
||||
: ['Claude', 'GPT', 'Other'].includes(mInfo.family) &&
|
||||
poolCycleBuckets.has('Claude & GPT')
|
||||
? 'Claude & GPT'
|
||||
: null;
|
||||
const poolBucketEntry = stepPoolKey ? poolCycleBuckets.get(stepPoolKey) : null;
|
||||
let cachedPool = poolByModel.get(mInfo);
|
||||
if (!cachedPool || cachedPool.key !== st.modelKey ||
|
||||
cachedPool.response !== st.responseModel || cachedPool.displayName !== st.modelDisplayName) {
|
||||
const ids = [st.modelKey, st.responseModel, mInfo.modelId, mInfo.label, st.modelDisplayName];
|
||||
let poolKey = null;
|
||||
if (hasDedicatedCarbonPool && isCarbonModelIdentifier(...ids)) poolKey = 'Carbon';
|
||||
else if (hasDedicatedArgonPool && isArgonModelIdentifier(...ids)) poolKey = 'Argon';
|
||||
else if (mInfo.family === 'Gemini') poolKey = 'Gemini';
|
||||
else if (['Claude', 'GPT', 'Other'].includes(mInfo.family)) poolKey = 'Claude & GPT';
|
||||
cachedPool = {
|
||||
key: st.modelKey, response: st.responseModel, displayName: st.modelDisplayName,
|
||||
bucket: poolCycleBuckets.get(poolKey),
|
||||
};
|
||||
poolByModel.set(mInfo, cachedPool);
|
||||
}
|
||||
const poolBucketEntry = cachedPool.bucket;
|
||||
if (poolBucketEntry) {
|
||||
if (tMs >= poolBucketEntry.start5hMs) {
|
||||
accumulateStepIntoBucket(poolBucketEntry.b5h, st, mInfo, stepCost, cascadeId);
|
||||
accumulateStepIntoBucket(poolBucketEntry.b5h, stepUsage, cascadeId);
|
||||
}
|
||||
if (tMs >= poolBucketEntry.startWkMs) {
|
||||
accumulateStepIntoBucket(poolBucketEntry.bWk, st, mInfo, stepCost, cascadeId);
|
||||
accumulateStepIntoBucket(poolBucketEntry.bWk, stepUsage, cascadeId);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -642,12 +724,15 @@ export function aggregateMultiWindowUsage({
|
||||
(tMs > 0 && tMs >= selectedWindow.startMs && tMs <= selectedWindow.endMs);
|
||||
|
||||
if (inSelectedWindow) {
|
||||
accumulateStepIntoBucket(selectedAccountBucket, st, mInfo, stepCost, cascadeId);
|
||||
if (isCurrentConv) {
|
||||
accumulateStepIntoBucket(selectedSessionBucket, st, mInfo, stepCost, cascadeId);
|
||||
if (selectedWindow.key === 'custom') {
|
||||
accumulateStepIntoBucket(selectedAccountBucket, stepUsage, cascadeId);
|
||||
if (isCurrentConv) {
|
||||
accumulateStepIntoBucket(selectedSessionBucket, stepUsage, cascadeId);
|
||||
}
|
||||
}
|
||||
if (tMs > 0) {
|
||||
if (tMs < earliestSelectedStepMs) earliestSelectedStepMs = tMs;
|
||||
if (tMs > latestSelectedStepMs && tMs <= MAX_TREND_TIMESTAMP_MS) latestSelectedStepMs = tMs;
|
||||
selectedWindowSteps.push({
|
||||
tMs,
|
||||
tokens: stepTotalTokens,
|
||||
@@ -691,52 +776,15 @@ export function aggregateMultiWindowUsage({
|
||||
}
|
||||
|
||||
// 构建当前选定时间窗口的自适应自然整点/整日趋势序列 (trendSeries)
|
||||
const MAX_SAFE_MS = 8_640_000_000_000_000;
|
||||
const safeMs = (val, fallback) =>
|
||||
Number.isFinite(val) && val > 0 && val <= MAX_SAFE_MS ? val : fallback;
|
||||
let latestSelectedStepMs = 0;
|
||||
for (const item of selectedWindowSteps) {
|
||||
if (item.tMs > latestSelectedStepMs && item.tMs <= MAX_SAFE_MS) {
|
||||
latestSelectedStepMs = item.tMs;
|
||||
}
|
||||
}
|
||||
const baseEndMs = safeMs(selectedWindow.endMs, Math.max(nowMs, latestSelectedStepMs || nowMs));
|
||||
const trendEndMs = Math.max(baseEndMs, latestSelectedStepMs || 0);
|
||||
const rawTrendStartMs =
|
||||
selectedWindow.key === 'all'
|
||||
? safeMs(earliestSelectedStepMs, trendEndMs - 24 * 3600 * 1000)
|
||||
: safeMs(selectedWindow.startMs, trendEndMs - 24 * 3600 * 1000);
|
||||
const effectiveStartMs =
|
||||
selectedWindow.key === 'all'
|
||||
? Math.min(
|
||||
rawTrendStartMs,
|
||||
earliestSelectedStepMs < Infinity
|
||||
? safeMs(earliestSelectedStepMs, rawTrendStartMs)
|
||||
: rawTrendStartMs,
|
||||
trendEndMs - 3600 * 1000
|
||||
)
|
||||
: Math.min(rawTrendStartMs, trendEndMs);
|
||||
const trendStartMs = effectiveStartMs;
|
||||
const rawSpanMs = Math.max(3600 * 1000, trendEndMs - effectiveStartMs);
|
||||
const trend = planUsageTrend(selectedWindow, nowMs, earliestSelectedStepMs, latestSelectedStepMs);
|
||||
const { start: trendStartMs, end: trendEndMs, hourly: useHourly } = trend;
|
||||
const pad2 = (n) => String(n).padStart(2, '0');
|
||||
const WEEKDAY_NAMES = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
|
||||
|
||||
// 72 小时(3 天)以内按自然整点小时分桶;超过 72 小时按本地自然日分桶
|
||||
const useHourly =
|
||||
selectedWindow.key === 'today' ||
|
||||
selectedWindow.key === '24h' ||
|
||||
selectedWindow.key === '5h' ||
|
||||
rawSpanMs <= 72 * 3600 * 1000;
|
||||
|
||||
const trendSeries = [];
|
||||
if (useHourly) {
|
||||
const startHourD = new Date(effectiveStartMs);
|
||||
startHourD.setMinutes(0, 0, 0);
|
||||
const endHourD = new Date(trendEndMs);
|
||||
endHourD.setMinutes(0, 0, 0);
|
||||
|
||||
let firstHourMs = startHourD.getTime();
|
||||
let lastHourMs = endHourD.getTime();
|
||||
let firstHourMs = trend.first;
|
||||
let lastHourMs = trend.last;
|
||||
if (selectedWindow.key === 'today') {
|
||||
const minTodayEndMs = firstHourMs + 5 * 3600 * 1000;
|
||||
if (lastHourMs < minTodayEndMs) {
|
||||
@@ -786,8 +834,8 @@ export function aggregateMultiWindowUsage({
|
||||
});
|
||||
}
|
||||
} else {
|
||||
const firstDayMs = getStartOfLocalDayMs(effectiveStartMs);
|
||||
const lastDayMs = getStartOfLocalDayMs(trendEndMs);
|
||||
const firstDayMs = trend.first;
|
||||
const lastDayMs = trend.last;
|
||||
const dayStarts = [];
|
||||
const cursor = new Date(firstDayMs);
|
||||
cursor.setHours(0, 0, 0, 0);
|
||||
@@ -842,10 +890,14 @@ export function aggregateMultiWindowUsage({
|
||||
if (trendSeries.length > 0) {
|
||||
const firstBucketStart = trendSeries[0].startMs;
|
||||
const lastIdx = trendSeries.length - 1;
|
||||
let previousBucketIndex = 0;
|
||||
for (const item of selectedWindowSteps) {
|
||||
let targetIdx = lastIdx;
|
||||
const previousBucket = trendSeries[previousBucketIndex];
|
||||
if (item.tMs <= firstBucketStart) {
|
||||
targetIdx = 0;
|
||||
} else if (item.tMs >= previousBucket.startMs && item.tMs < previousBucket.endMs) {
|
||||
targetIdx = previousBucketIndex;
|
||||
} else {
|
||||
// 二分查找匹配的时间桶 [startMs, endMs)
|
||||
let lo = 0;
|
||||
@@ -863,6 +915,7 @@ export function aggregateMultiWindowUsage({
|
||||
}
|
||||
}
|
||||
}
|
||||
previousBucketIndex = targetIdx;
|
||||
const bucket = trendSeries[targetIdx];
|
||||
bucket.tokens += item.tokens;
|
||||
bucket.inputTokens += item.inputTokens || 0;
|
||||
@@ -939,7 +992,7 @@ export function aggregateMultiWindowUsage({
|
||||
}
|
||||
: null;
|
||||
|
||||
return {
|
||||
const result = {
|
||||
selectedWindow,
|
||||
trendStartMs,
|
||||
trendEndMs,
|
||||
@@ -956,4 +1009,19 @@ export function aggregateMultiWindowUsage({
|
||||
poolCycleStats,
|
||||
poolsWeeklySummary,
|
||||
};
|
||||
if (modelInputs) {
|
||||
if (!sameSnapshot) {
|
||||
lastUsageSnapshot = {
|
||||
timeZone, modelInputs, currentYear, entries: allEntriesToAggregate, dates: null, ranges: new Map(),
|
||||
};
|
||||
}
|
||||
const { ranges } = lastUsageSnapshot;
|
||||
ranges.delete(selectedWindow.key);
|
||||
ranges.set(selectedWindow.key, {
|
||||
windows, trend, result, earliest: earliestSelectedStepMs, latest: latestSelectedStepMs,
|
||||
});
|
||||
// 侧栏和悬浮窗可同时查看不同范围,共用时间索引并最多保留两份聚合结果。
|
||||
if (ranges.size > 2) ranges.delete(ranges.keys().next().value);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -1335,6 +1335,8 @@ export function createWindowBridgeController(options) {
|
||||
const initOut = await handleApiRequest('/api/telemetry', 'GET', {
|
||||
conversationId: targetConvId,
|
||||
range: 'today',
|
||||
stepDetails: 'display',
|
||||
stepRevision: '',
|
||||
});
|
||||
if (Number(initOut?.status || 200) === 200 && initOut?.body) {
|
||||
initialTelemetry = JSON.parse(initOut.body);
|
||||
|
||||
@@ -4,11 +4,11 @@
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>用量监控</title>
|
||||
<link rel="stylesheet" href="/styles.css?v=1794740175626">
|
||||
<link rel="stylesheet" href="/styles.css?v=1794752913974">
|
||||
<script src="/preload.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app-root"></div>
|
||||
<script src="/app.js?v=1794740175626"></script>
|
||||
<script src="/app.js?v=1794752913974"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -608,7 +608,8 @@ export function extractContextBreakdown(chat) {
|
||||
* - 优先级 3:`chat.model`(`chatModel` 请求级模型标识)
|
||||
* - 优先级 4:`metadata.generatorModel`(步骤 `metadata` 顶层记录的生成模型)
|
||||
* - 优先级 5:`chat.responseModel`(上游返回的具体响应模型名)
|
||||
* 2. **5 种测速过滤与排除原因(`timingReason` / `speedReason`)**:
|
||||
* 2. **测速过滤与排除原因(`timingReason` / `speedReason`)**:
|
||||
* - `'canceled'`:生成已取消,保留用量但不参与测速;
|
||||
* - `'incomplete_or_invalid_timing'`:没有完成生成的证据,或总耗时 `totalDurationSec` 缺失/非正数;
|
||||
* - `'invalid_output_tokens'`:`outputTokens` 不是合法的非负安全整数;
|
||||
* - `'short_timing'`:请求总耗时低于 `MIN_SPEED_DURATION_SECONDS`(0.5s),易受计时器粒度噪声干扰;
|
||||
@@ -806,9 +807,11 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
||||
const nativeStreamSec = duration(chat?.streamingDuration);
|
||||
const thinkingDurationSec = duration(p.thinkingDuration);
|
||||
|
||||
// 5 种测速过滤原因判定:先校验耗时与 Token 合法性(timingReason),再判定压缩步与短样本(speedReason)
|
||||
// 先校验状态、耗时与 Token 合法性,再判定压缩步与短样本。
|
||||
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';
|
||||
} else if (!validCount(u.outputTokens)) {
|
||||
timingReason = 'invalid_output_tokens';
|
||||
@@ -1187,7 +1190,10 @@ export function speedMetric(step) {
|
||||
!Number.isFinite(step.totalTokPerSec) ||
|
||||
!(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 {
|
||||
|
||||
@@ -317,7 +317,8 @@ export function computePublicationFit(
|
||||
let swx = 0;
|
||||
for (let j = start; j < end; j++) {
|
||||
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;
|
||||
sw += w;
|
||||
swx += w * xs[j];
|
||||
@@ -339,6 +340,8 @@ export function computePublicationFit(
|
||||
|
||||
const dx0 = x0 - mx;
|
||||
const useSlope = sxxW > 1e-12;
|
||||
const inverseWeightSum = 1 / sw;
|
||||
const slopeScale = useSlope ? dx0 / sxxW : 0;
|
||||
let rawFit = 0;
|
||||
let leverageNormSq = 0;
|
||||
let diagHat = 0;
|
||||
@@ -346,7 +349,7 @@ export function computePublicationFit(
|
||||
for (let j = start; j < end; j++) {
|
||||
const w = wBuf[j];
|
||||
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];
|
||||
leverageNormSq += lj * lj;
|
||||
if (j === diagIdx) diagHat = lj;
|
||||
@@ -1477,6 +1480,26 @@ export function createModelFitChart() {
|
||||
let hoveredIdx = -1;
|
||||
let lastSig = '';
|
||||
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() {
|
||||
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) {
|
||||
fitCache.clear();
|
||||
currentSamples = [];
|
||||
lastSig = 'empty';
|
||||
patchAttr(ciBandPath, 'd', '');
|
||||
@@ -1834,12 +1866,7 @@ export function createModelFitChart() {
|
||||
if (items.length === 0) continue;
|
||||
const xs = items.map((d) => d.xVal);
|
||||
const rawYs = items.map((d) => d.rawVal);
|
||||
const pubFit = computePublicationFit(xs, rawYs, {
|
||||
minVal: minBound,
|
||||
maxVal: maxBound,
|
||||
gridSize: 56,
|
||||
span: 0.5,
|
||||
});
|
||||
const pubFit = reusePublicationFit(key, xs, rawYs, maxBound, true);
|
||||
const colorVar =
|
||||
modelColorByGroup?.get(key) || MODEL_COLOR_VARS[kIdx % MODEL_COLOR_VARS.length];
|
||||
seriesList.push({
|
||||
@@ -2067,12 +2094,7 @@ export function createModelFitChart() {
|
||||
const filtered = matchedItems;
|
||||
const xs = filtered.map((d) => d.xVal);
|
||||
const rawYs = filtered.map((d) => d.rawVal);
|
||||
const pubFit = computePublicationFit(xs, rawYs, {
|
||||
minVal: minBound,
|
||||
maxVal: maxBound,
|
||||
gridSize: 64,
|
||||
span: 0.5,
|
||||
});
|
||||
const pubFit = reusePublicationFit(null, xs, rawYs, maxBound, false);
|
||||
|
||||
patchText(fitMethodLabelEl, pubFit.method === 'LOESS' ? 'LOESS 拟合' : 'OLS 回归');
|
||||
patchAttr(olsLegendWrapEl, 'hidden', filtered.length < 6);
|
||||
|
||||
@@ -120,6 +120,7 @@ export const TopSessionHeader = defineComponent({
|
||||
} else if (currentCascadeId) {
|
||||
lastActiveCascadeId = currentCascadeId;
|
||||
}
|
||||
if (!uiSt.monitorVisible) return;
|
||||
|
||||
patchAttr(updateBtn, 'aria-label', t('header.ariaUpdate'));
|
||||
patchAttr(refreshBtn, 'aria-label', t('header.ariaRefresh'));
|
||||
@@ -283,10 +284,18 @@ export const TopSessionHeader = defineComponent({
|
||||
(st) => st.locale,
|
||||
() => renderHeaderState()
|
||||
);
|
||||
const unsubVisibility = uiStore.subscribe(
|
||||
(st) => st.monitorVisible,
|
||||
(visible) => {
|
||||
if (visible) renderHeaderState();
|
||||
},
|
||||
{ immediate: false }
|
||||
);
|
||||
|
||||
onCleanup(() => {
|
||||
unsubTelemetry();
|
||||
unsubI18n();
|
||||
unsubVisibility();
|
||||
convSelect.destroy();
|
||||
});
|
||||
|
||||
|
||||
@@ -1091,11 +1091,15 @@ export function mountWindowOverlay() {
|
||||
}
|
||||
}
|
||||
|
||||
function stopMultiLiveTicker() {
|
||||
function pauseMultiLiveTicker() {
|
||||
if (multiLiveTickTimer) {
|
||||
clearInterval(multiLiveTickTimer);
|
||||
multiLiveTickTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
function stopMultiLiveTicker() {
|
||||
pauseMultiLiveTicker();
|
||||
multiTimersMap.clear();
|
||||
}
|
||||
|
||||
@@ -1563,6 +1567,7 @@ export function mountWindowOverlay() {
|
||||
);
|
||||
|
||||
// 完整四标签悬浮容器
|
||||
uiStore.setState({ monitorVisible: false });
|
||||
const appInstance = App();
|
||||
const popoverEl = h(
|
||||
'div',
|
||||
@@ -2238,10 +2243,13 @@ export function mountWindowOverlay() {
|
||||
patchClasses(multiPanelEl, { 'is-instant': Boolean(instant && multiOpen) });
|
||||
patchAttr(multiPanelEl, 'hidden', !multiOpen);
|
||||
if (multiOpen) {
|
||||
renderCapsuleTelemetry();
|
||||
positionFloatingElements();
|
||||
if (typeof requestAnimationFrame === 'function') {
|
||||
requestAnimationFrame(() => positionFloatingElements());
|
||||
}
|
||||
} else {
|
||||
pauseMultiLiveTicker();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2272,6 +2280,7 @@ export function mountWindowOverlay() {
|
||||
patchClasses(hoverTipEl, { 'is-instant': Boolean(instant && targetOpen) });
|
||||
patchAttr(hoverTipEl, 'hidden', !tooltipOpen);
|
||||
if (tooltipOpen) {
|
||||
renderHoverWidgets();
|
||||
hoverWidgetHost.resumeTickers();
|
||||
positionFloatingElements();
|
||||
if (typeof requestAnimationFrame === 'function') {
|
||||
@@ -2296,6 +2305,7 @@ export function mountWindowOverlay() {
|
||||
patchClasses(popoverEl, { 'is-instant': Boolean(instant && popoverOpen) });
|
||||
patchAttr(capsuleBtn, 'aria-expanded', popoverOpen ? 'true' : 'false');
|
||||
patchAttr(popoverEl, 'hidden', !popoverOpen);
|
||||
uiStore.setState({ monitorVisible: popoverOpen && !document.hidden }, { sync: true });
|
||||
if (popoverOpen) {
|
||||
positionFloatingElements();
|
||||
if (typeof requestAnimationFrame === 'function') {
|
||||
@@ -2313,125 +2323,17 @@ export function mountWindowOverlay() {
|
||||
syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, slotCtx);
|
||||
}
|
||||
|
||||
// --- 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);
|
||||
function renderMultiRunningPanel(rawRunningList, runningCount, runningSubCount, hostRouteConversationId) {
|
||||
if (manualSubExpandMap.size > 0) {
|
||||
const runningIds = new Set(rawRunningList.map((item) => item.cascadeId));
|
||||
for (const id of manualSubExpandMap.keys()) {
|
||||
if (!runningIds.has(id)) manualSubExpandMap.delete(id);
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
if (!multiOpen || document.hidden) return;
|
||||
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(
|
||||
telSt.hostRouteConversationId || extractHostRouteCascadeId() || ''
|
||||
hostRouteConversationId || extractHostRouteCascadeId() || ''
|
||||
).toLowerCase();
|
||||
|
||||
patchText(
|
||||
@@ -2445,20 +2347,10 @@ export function mountWindowOverlay() {
|
||||
patchAttr(multiEmptyEl, 'hidden', runningCount > 0);
|
||||
patchAttr(multiRunningListEl, 'hidden', runningCount === 0);
|
||||
|
||||
const runningIdsLower = new Set(
|
||||
rawRunningList.map((item) => String(item.cascadeId || '').toLowerCase())
|
||||
);
|
||||
|
||||
if (runningCount === 0) {
|
||||
stopMultiLiveTicker();
|
||||
manualSubExpandMap.clear();
|
||||
patchKeyedList(multiRunningListEl, [], {});
|
||||
} else {
|
||||
for (const cid of [...manualSubExpandMap.keys()]) {
|
||||
if (!runningIdsLower.has(String(cid || '').toLowerCase())) {
|
||||
manualSubExpandMap.delete(cid);
|
||||
}
|
||||
}
|
||||
|
||||
const activeTimerKeys = new Set();
|
||||
for (const item of rawRunningList) {
|
||||
activeTimerKeys.add(`main:${item.cascadeId}`);
|
||||
@@ -2646,7 +2538,135 @@ export function mountWindowOverlay() {
|
||||
}
|
||||
}
|
||||
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 动态槽位胶囊与组件化悬停浮层 ---
|
||||
const isRunning = Boolean(aggregated?.isRunning || activeConv.isRunning);
|
||||
@@ -2752,13 +2772,8 @@ export function mountWindowOverlay() {
|
||||
if (hoverModuleKeys.length === 0 && !showUpdatePrompt && tooltipOpen) {
|
||||
setTooltipOpen(false);
|
||||
}
|
||||
const minuteTick = Number(telSt.minuteTick || Math.floor(Date.now() / 30000));
|
||||
hoverWidgetHost.update({
|
||||
moduleKeys: hoverModuleKeys,
|
||||
data: telemetry,
|
||||
minuteTick,
|
||||
});
|
||||
if (tooltipOpen) {
|
||||
renderHoverWidgets();
|
||||
positionFloatingElements();
|
||||
}
|
||||
}
|
||||
@@ -2867,6 +2882,8 @@ export function mountWindowOverlay() {
|
||||
const onDocFocusIn = () => syncHostRouteIfChanged();
|
||||
const onVisibilityChange = () => {
|
||||
if (document.hidden) {
|
||||
uiStore.setState({ monitorVisible: false });
|
||||
pauseMultiLiveTicker();
|
||||
hasPointerCoords = false;
|
||||
if (tooltipOpen) {
|
||||
setTooltipOpen(false);
|
||||
@@ -2877,6 +2894,8 @@ export function mountWindowOverlay() {
|
||||
return;
|
||||
}
|
||||
if (!document.hidden && !disposed) {
|
||||
uiStore.setState({ monitorVisible: popoverOpen });
|
||||
if (multiOpen) renderCapsuleTelemetry();
|
||||
syncHostRouteIfChanged();
|
||||
void fetchTelemetry({ force: false });
|
||||
}
|
||||
|
||||
@@ -128,6 +128,34 @@ export const StepTableWidget = defineComponent({
|
||||
|
||||
stepsTablePane.addEventListener('scroll', 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(
|
||||
tableSteps,
|
||||
@@ -144,6 +172,16 @@ export const StepTableWidget = defineComponent({
|
||||
} = {}
|
||||
) {
|
||||
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);
|
||||
syncTableHeaderColumns(colKeys);
|
||||
|
||||
@@ -166,20 +204,23 @@ export const StepTableWidget = defineComponent({
|
||||
Boolean(useRootTurn ? (st?.isRootLatestTurn ?? st?.isLatestTurn) : st?.isLatestTurn);
|
||||
const getStepPrompt = (st) =>
|
||||
(useRootTurn ? (st?.rootTurnPrompt ?? st?.turnPrompt) : st?.turnPrompt) || '';
|
||||
const turnKeyOf = (st) => {
|
||||
if (!showStepTurnRail) return '';
|
||||
const turnKeys = showStepTurnRail ? tableSteps.map((st) => {
|
||||
const tIdx = getStepTurnIdx(st);
|
||||
if (!Number.isInteger(tIdx) || tIdx <= 0) return '';
|
||||
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 tKey = turnKeyOf(st);
|
||||
const tKey = turnKeys[idx];
|
||||
const hasTurn = Boolean(tKey);
|
||||
const hasUp = Boolean(hasTurn && idx > 0 && turnKeyOf(tableSteps[idx - 1]) === tKey);
|
||||
const hasDown = Boolean(
|
||||
hasTurn && idx + 1 < tableSteps.length && turnKeyOf(tableSteps[idx + 1]) === tKey
|
||||
);
|
||||
const hasUp = hasTurn && turnKeys[idx - 1] === tKey;
|
||||
const hasDown = hasTurn && turnKeys[idx + 1] === tKey;
|
||||
return {
|
||||
st,
|
||||
rowKey: `${st.agentCascadeId || cascadeId || 'conv'}-${st.stepIndex}`,
|
||||
@@ -188,7 +229,7 @@ export const StepTableWidget = defineComponent({
|
||||
hasDown,
|
||||
isStart: Boolean(hasTurn && (getStepIsStart(st) || !hasDown)),
|
||||
isLatest: hasTurn && getStepIsLatest(st),
|
||||
prompt: hasTurn ? formatTurnPromptText(getStepPrompt(st)) : '',
|
||||
prompt: hasTurn ? formattedTurnPrompt(st) : '',
|
||||
};
|
||||
});
|
||||
|
||||
@@ -205,32 +246,20 @@ export const StepTableWidget = defineComponent({
|
||||
const parts = colKeys
|
||||
.map((colKey) => STEP_COLUMN_REGISTRY[colKey].sigPart(st, cellCtx))
|
||||
.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}`;
|
||||
},
|
||||
createRow: () => {
|
||||
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 {
|
||||
el: tr,
|
||||
refs: {
|
||||
cellMap: new Map(),
|
||||
colOrderSig: '',
|
||||
railEl,
|
||||
railLineEl,
|
||||
railDotEl,
|
||||
agentBadgeEl,
|
||||
railEl: null,
|
||||
agentBadgeEl: null,
|
||||
hoverTd: null,
|
||||
},
|
||||
};
|
||||
@@ -240,17 +269,15 @@ export const StepTableWidget = defineComponent({
|
||||
|
||||
if (refs.colOrderSig !== colOrderSig) {
|
||||
if (refs.hoverTd) {
|
||||
refs.hoverTd.onmouseenter = null;
|
||||
refs.hoverTd.onmousemove = null;
|
||||
refs.hoverTd.onmouseleave = null;
|
||||
clearCellHover(refs.hoverTd);
|
||||
refs.hoverTd = null;
|
||||
}
|
||||
for (const [oldColKey, entry] of refs.cellMap) {
|
||||
if (!wantedSet.has(oldColKey)) {
|
||||
if (refs.railEl.parentNode === entry.td) {
|
||||
if (refs.railEl?.parentNode === entry.td) {
|
||||
entry.td.removeChild(refs.railEl);
|
||||
}
|
||||
if (refs.agentBadgeEl.parentNode === entry.td) {
|
||||
if (refs.agentBadgeEl?.parentNode === entry.td) {
|
||||
entry.td.removeChild(refs.agentBadgeEl);
|
||||
}
|
||||
tr.removeChild(entry.td);
|
||||
@@ -258,14 +285,19 @@ export const StepTableWidget = defineComponent({
|
||||
}
|
||||
}
|
||||
|
||||
for (const [i, colKey] of colKeys.entries()) {
|
||||
if (!refs.cellMap.has(colKey)) {
|
||||
refs.cellMap.set(colKey, STEP_COLUMN_REGISTRY[colKey].createCell());
|
||||
const isNewRow = refs.colOrderSig === '';
|
||||
for (let i = 0; i < colKeys.length; i++) {
|
||||
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;
|
||||
const currentTd = tr.children[i] || null;
|
||||
if (currentTd !== targetTd) {
|
||||
tr.insertBefore(targetTd, currentTd);
|
||||
if (isNewRow) {
|
||||
tr.appendChild(cell.td);
|
||||
} else {
|
||||
const currentTd = tr.children[i] || null;
|
||||
if (currentTd !== cell.td) tr.insertBefore(cell.td, currentTd);
|
||||
}
|
||||
}
|
||||
refs.colOrderSig = colOrderSig;
|
||||
@@ -278,12 +310,22 @@ export const StepTableWidget = defineComponent({
|
||||
|
||||
const firstColKey = colKeys[0];
|
||||
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 (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);
|
||||
}
|
||||
const afterRail = refs.railEl.nextSibling ?? firstTd.children[1] ?? null;
|
||||
if (refs.agentBadgeEl.parentNode !== firstTd || afterRail !== refs.agentBadgeEl) {
|
||||
const afterRail = refs.railEl
|
||||
? refs.railEl.nextSibling ?? firstTd.children[1] ?? null
|
||||
: firstTd.firstChild;
|
||||
if (refs.agentBadgeEl &&
|
||||
(refs.agentBadgeEl.parentNode !== firstTd || afterRail !== refs.agentBadgeEl)) {
|
||||
firstTd.insertBefore(refs.agentBadgeEl, afterRail);
|
||||
}
|
||||
}
|
||||
@@ -334,72 +376,29 @@ export const StepTableWidget = defineComponent({
|
||||
patchAttr(refs.agentBadgeEl, 'title', null);
|
||||
refs.agentBadgeEl.onclick = null;
|
||||
}
|
||||
} else {
|
||||
} else if (refs.agentBadgeEl) {
|
||||
refs.agentBadgeEl.onclick = null;
|
||||
}
|
||||
|
||||
const showRowRail = Boolean(railActive && hasTurn && firstTd);
|
||||
patchAttr(refs.railEl, 'hidden', !showRowRail);
|
||||
if (showRowRail) {
|
||||
patchClasses(refs.railEl, {
|
||||
'is-latest': isLatest,
|
||||
'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 marker = isStart ? ' is-origin' : !hasUp && hasDown ? ' is-cap' : '';
|
||||
patchAttr(refs.railEl, 'class', `turn-rail${isLatest ? ' is-latest' : ''}${hasUp ? ' has-up' : ''}${hasDown ? ' has-down' : ''}${marker}`);
|
||||
}
|
||||
|
||||
const targetHoverTd = firstTd;
|
||||
if (refs.hoverTd && refs.hoverTd !== targetHoverTd) {
|
||||
refs.hoverTd.onmouseenter = null;
|
||||
refs.hoverTd.onmousemove = null;
|
||||
refs.hoverTd.onmouseleave = null;
|
||||
}
|
||||
refs.hoverTd = targetHoverTd;
|
||||
|
||||
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;
|
||||
}
|
||||
const hoverTd = showRowRail && prompt ? firstTd : null;
|
||||
if (refs.hoverTd !== hoverTd) clearCellHover(refs.hoverTd);
|
||||
refs.hoverTd = hoverTd;
|
||||
if (hoverTd) {
|
||||
hoverRows.set(hoverTd, { badge: refs.agentBadgeEl, prompt });
|
||||
hoverTd.onmouseenter = firstColKey === 'step' ? enterStepCell : null;
|
||||
hoverTd.onmousemove = firstColKey === 'step' ? moveInStepCell : moveAlongTurnRail;
|
||||
hoverTd.onmouseleave = hideTurnTip;
|
||||
}
|
||||
},
|
||||
});
|
||||
lastRenderOptions = renderOptions;
|
||||
lastRenderedRows = tableSteps;
|
||||
}
|
||||
|
||||
onCleanup(() => {
|
||||
|
||||
@@ -115,6 +115,8 @@ export function formatUsd(amount, { precise = false } = {}) {
|
||||
const SPEED_REASON_LABELS = {
|
||||
__proto__: null,
|
||||
incomplete_or_invalid_timing: 'fmt.speedIncomplete',
|
||||
canceled: 'fmt.speedCanceled',
|
||||
compaction_timing_unavailable: 'fmt.speedCompactionTimingUnavailable',
|
||||
invalid_output_tokens: 'fmt.speedInvalidOutput',
|
||||
inconsistent_timing: 'fmt.speedInconsistent',
|
||||
short_timing: 'fmt.speedShort',
|
||||
|
||||
@@ -34,6 +34,8 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
// Formatters & Common Labels
|
||||
'fmt.pending': 'N/A',
|
||||
'fmt.speedIncomplete': 'Incomplete timing',
|
||||
'fmt.speedCanceled': 'Canceled',
|
||||
'fmt.speedCompactionTimingUnavailable': 'Untimed compaction',
|
||||
'fmt.speedInvalidOutput': 'No valid output',
|
||||
'fmt.speedInconsistent': 'Invalid timing',
|
||||
'fmt.speedShort': 'Too brief (<0.5s)',
|
||||
|
||||
@@ -34,6 +34,8 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
// Formatters & Common Labels
|
||||
'fmt.pending': '待定',
|
||||
'fmt.speedIncomplete': '计时不完整',
|
||||
'fmt.speedCanceled': '已取消',
|
||||
'fmt.speedCompactionTimingUnavailable': '压缩无计时',
|
||||
'fmt.speedInvalidOutput': '无有效输出',
|
||||
'fmt.speedInconsistent': '耗时数据异常',
|
||||
'fmt.speedShort': '耗时过短 (<0.5s)',
|
||||
|
||||
@@ -123,24 +123,29 @@ export const STEP_COLUMN_REGISTRY = Object.freeze({
|
||||
className: 'cell-value tone-muted',
|
||||
style: 'font-size: var(--fs-base-sm);',
|
||||
});
|
||||
const speedReason = h('div', {
|
||||
className: 'text-muted',
|
||||
style: 'font-size: var(--fs-2xs);',
|
||||
});
|
||||
const wrapEl = h(
|
||||
'span',
|
||||
{ style: 'display: inline-block; vertical-align: middle;' },
|
||||
[speedMain, speedReason]
|
||||
[speedMain]
|
||||
);
|
||||
const td = h('td', {}, [wrapEl]);
|
||||
return { td, refs: { td, speedMain, speedReason } };
|
||||
return { td, refs: { wrapEl, speedMain, speedReason: null } };
|
||||
},
|
||||
updateCell: (refs, st) => {
|
||||
patchText(refs.speedMain, formatMetric(st.tokPerSec, ' tok/s'));
|
||||
patchAttr(refs.speedMain, 'class', `cell-value ${getSpeedToneClass(st.tokPerSec)}`);
|
||||
const reason = speedReasonText(st.selectedSpeedReason);
|
||||
patchText(refs.speedReason, reason);
|
||||
patchAttr(refs.speedReason, 'hidden', !reason);
|
||||
if (reason && !refs.speedReason) {
|
||||
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);
|
||||
}
|
||||
},
|
||||
},
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
*/
|
||||
|
||||
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 { normalizeClientFontScale, normalizeClientThemeAccent } from '../core/appearance.js';
|
||||
|
||||
@@ -100,6 +100,8 @@ let feedbackTimer = null;
|
||||
let activeBundleVersion = 0;
|
||||
let latestRequestSeq = 0;
|
||||
let activeForceCount = 0;
|
||||
let inFlightTelemetryPoll = null;
|
||||
let lastReceivedSteps = null;
|
||||
let loopActive = false;
|
||||
let loopIntervalMs = 2000;
|
||||
let loopTickFn = null;
|
||||
@@ -526,10 +528,11 @@ function isEquivalentTelemetry(prev, next) {
|
||||
) {
|
||||
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;
|
||||
for (let j = 0; j < paSteps.length; j++) {
|
||||
for (let j = 0; paSteps !== naSteps && j < paSteps.length; j++) {
|
||||
const bs = paSteps[j];
|
||||
const as = naSteps[j];
|
||||
if (
|
||||
@@ -558,6 +561,8 @@ function isEquivalentTelemetry(prev, next) {
|
||||
bs?.rootTurnIndex !== as?.rootTurnIndex ||
|
||||
bs?.isTurnStart !== as?.isTurnStart ||
|
||||
bs?.isRootTurnStart !== as?.isRootTurnStart ||
|
||||
bs?.isLatestTurn !== as?.isLatestTurn ||
|
||||
bs?.isRootLatestTurn !== as?.isRootLatestTurn ||
|
||||
bs?.turnPrompt !== as?.turnPrompt ||
|
||||
bs?.rootTurnPrompt !== as?.rootTurnPrompt
|
||||
) {
|
||||
@@ -584,9 +589,10 @@ function isEquivalentTelemetry(prev, next) {
|
||||
if (pCtx?.systemPromptTokens !== nCtx?.systemPromptTokens) return false;
|
||||
if (pCtx?.userRulesTokens !== nCtx?.userRulesTokens) 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];
|
||||
if (
|
||||
before.stepIndex !== after.stepIndex ||
|
||||
before.createdAtMs !== after.createdAtMs ||
|
||||
before.totalDurationSec !== after.totalDurationSec ||
|
||||
before.streamDurationSec !== after.streamDurationSec ||
|
||||
@@ -611,6 +617,8 @@ function isEquivalentTelemetry(prev, next) {
|
||||
before.rootTurnIndex !== after.rootTurnIndex ||
|
||||
before.isTurnStart !== after.isTurnStart ||
|
||||
before.isRootTurnStart !== after.isRootTurnStart ||
|
||||
before.isLatestTurn !== after.isLatestTurn ||
|
||||
before.isRootLatestTurn !== after.isRootLatestTurn ||
|
||||
before.turnPrompt !== after.turnPrompt ||
|
||||
before.rootTurnPrompt !== after.rootTurnPrompt
|
||||
) {
|
||||
@@ -822,7 +830,61 @@ export async function fetchTelemetry({ force = false } = {}) {
|
||||
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 startMs = Date.now();
|
||||
|
||||
@@ -836,41 +898,28 @@ export async function fetchTelemetry({ force = false } = {}) {
|
||||
}
|
||||
|
||||
try {
|
||||
if (isWindowOverlayMode()) {
|
||||
const liveRouteId = extractHostRouteCascadeId();
|
||||
if (liveRouteId !== st.hostRouteConversationId) {
|
||||
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}` : ''}`, {
|
||||
const previousSteps = lastReceivedSteps || readDisplaySteps(telemetryStore.getState().telemetry);
|
||||
params.set('stepRevision', previousSteps?.revision || '');
|
||||
const payload = await callSidecarApi(`/api/telemetry?${params}`, {
|
||||
method: 'GET',
|
||||
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) {
|
||||
return payload;
|
||||
}
|
||||
lastReceivedSteps = readDisplaySteps(payload);
|
||||
|
||||
if (payload?.uiBundleVersion) {
|
||||
if (activeBundleVersion && activeBundleVersion !== payload.uiBundleVersion) {
|
||||
@@ -1170,26 +1219,28 @@ export function formatAgentLabel(agent) {
|
||||
* @param {object|null} telemetry
|
||||
* @param {string} [selectedAgentScope='all']
|
||||
* @param {string} [ctxInspectorAgentId='auto']
|
||||
* @param {boolean} [includeSteps=false] 是否组装调用明细所需的步骤列表
|
||||
*/
|
||||
export function resolveScopedConversation(
|
||||
telemetry,
|
||||
selectedAgentScope = 'all',
|
||||
ctxInspectorAgentId = 'auto'
|
||||
ctxInspectorAgentId = 'auto',
|
||||
includeSteps = false
|
||||
) {
|
||||
const active = telemetry?.activeConversation || {};
|
||||
const agents = Array.isArray(active.agents) && active.agents.length > 0 ? active.agents : [];
|
||||
const hasSubagents = Boolean(active.hasSubagents && agents.length > 1);
|
||||
const subagents = agents.filter((a) => !a.isMain);
|
||||
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;
|
||||
}
|
||||
const aggregated = active.aggregated || active;
|
||||
if (hasSubagents && aggregated && !Array.isArray(aggregated.recentSteps)) {
|
||||
if (includeSteps && hasSubagents && !Array.isArray(aggregated.recentSteps)) {
|
||||
const combined = [];
|
||||
for (const ag of agents) {
|
||||
const steps = ag.isMain ? ag.recentSteps || active.recentSteps || [] : ag.recentSteps || [];
|
||||
combined.push(...steps);
|
||||
for (const step of steps) combined.push(step);
|
||||
}
|
||||
combined.sort(
|
||||
(a, b) =>
|
||||
|
||||
@@ -23,9 +23,14 @@ export function getViewTabs() {
|
||||
|
||||
export const uiStore = createReactiveStore({
|
||||
activeView: 'overview',
|
||||
monitorVisible: true,
|
||||
stepsSubTab: 'steps', // 'steps' | 'models'
|
||||
settingsSubTab: 'general', // 'general' | 'structure' | 'account' | 'other'
|
||||
settingsStructureTab: 'mount', // 'mount' | 'hover' | 'overview' | 'steps'
|
||||
selectedAgentScope: 'all', // 'all' | 'main' | <subagent cascadeId>
|
||||
ctxInspectorAgentId: 'auto', // 'auto' | 'main' | <subagent cascadeId>
|
||||
});
|
||||
|
||||
export function getVisibleMonitorView(state = uiStore.getState()) {
|
||||
return state.monitorVisible ? state.activeView : null;
|
||||
}
|
||||
|
||||
@@ -147,29 +147,37 @@
|
||||
--rail-dot: var(--accent-primary);
|
||||
}
|
||||
|
||||
.turn-rail-line {
|
||||
.turn-rail::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
left: 3.25px;
|
||||
width: 1.5px;
|
||||
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;
|
||||
bottom: 0;
|
||||
}
|
||||
|
||||
.turn-rail.has-up:not(.has-down) .turn-rail-line {
|
||||
.turn-rail.has-up:not(.has-down)::before {
|
||||
top: 0;
|
||||
bottom: 50%;
|
||||
}
|
||||
|
||||
.turn-rail.has-down:not(.has-up) .turn-rail-line {
|
||||
.turn-rail.has-down:not(.has-up)::before {
|
||||
top: 50%;
|
||||
bottom: 0;
|
||||
}
|
||||
|
||||
.turn-rail-dot {
|
||||
.turn-rail.is-cap::after,
|
||||
.turn-rail.is-origin::after {
|
||||
content: '';
|
||||
box-sizing: border-box;
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 4px;
|
||||
@@ -177,13 +185,13 @@
|
||||
border-radius: var(--radius-pill);
|
||||
}
|
||||
|
||||
.turn-rail-dot.is-cap {
|
||||
.turn-rail.is-cap::after {
|
||||
width: 3.5px;
|
||||
height: 3.5px;
|
||||
background: var(--rail-line);
|
||||
}
|
||||
|
||||
.turn-rail-dot.is-origin {
|
||||
.turn-rail.is-origin::after {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
background: var(--surface-panel);
|
||||
@@ -191,13 +199,11 @@
|
||||
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);
|
||||
}
|
||||
|
||||
.turn-rail[hidden],
|
||||
.turn-rail-line[hidden],
|
||||
.turn-rail-dot[hidden],
|
||||
.turn-prompt-tip[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
@@ -29,7 +29,7 @@ import {
|
||||
import { i18nStore, isEnglishLocale, t } from '../i18n/index.js';
|
||||
import { createSvgIcon } from '../icons/SvgIcon.js';
|
||||
import { fetchTelemetry, telemetryStore } from '../store/telemetryStore.js';
|
||||
import { uiStore } from '../store/uiStore.js';
|
||||
import { getVisibleMonitorView, uiStore } from '../store/uiStore.js';
|
||||
import {
|
||||
createTrendAreaChart,
|
||||
HEATMAP_DAYS_THRESHOLD,
|
||||
@@ -506,11 +506,38 @@ export const ConsumptionView = defineComponent({
|
||||
let latestSlice = null;
|
||||
let isDirty = false;
|
||||
|
||||
let lastRenderedUsage = '';
|
||||
|
||||
/**
|
||||
* 将遥测状态切片同步渲染至消费统计视图的 5 个子面板。
|
||||
*/
|
||||
function renderConsumptionData(slice) {
|
||||
if (!slice) return;
|
||||
const cons = slice.consumption || {};
|
||||
const preset =
|
||||
slice.range !== 'custom' && cons.presets?.[slice.range]
|
||||
? cons.presets[slice.range]
|
||||
: null;
|
||||
const acct = preset?.account || cons.account || {};
|
||||
const rangeInfo = cons.selectedRange || {};
|
||||
const dateSpan = formatDateSpanBadge(rangeInfo.startMs, rangeInfo.endMs);
|
||||
const now = new Date();
|
||||
const currentMonthIdx = now.getMonth();
|
||||
const monthlyYear = cons.monthlyYear || now.getFullYear();
|
||||
const locale = i18nStore.getState().locale;
|
||||
// 额度与会话状态也会发布遥测更新,只对用量页实际展示的数据重绘。
|
||||
const signature = JSON.stringify([
|
||||
locale, slice.range, slice.customStartMs, slice.customEndMs, slice.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);
|
||||
patchAttr(customRangeBar, 'hidden', slice.range !== 'custom');
|
||||
if (!hasUncommittedCustomDraft) {
|
||||
@@ -520,16 +547,8 @@ export const ConsumptionView = defineComponent({
|
||||
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 段比例条
|
||||
patchText(dateSpanBadge, formatDateSpanBadge(rangeInfo.startMs, rangeInfo.endMs));
|
||||
patchText(dateSpanBadge, dateSpan);
|
||||
const totalTokens = Number(acct.totalTokens || 0);
|
||||
const inputTokens = Number(acct.inputTokens || 0);
|
||||
const cacheTokens = Number(acct.cacheReadTokens || 0);
|
||||
@@ -656,8 +675,6 @@ export const ConsumptionView = defineComponent({
|
||||
});
|
||||
|
||||
// 5. 同步 12 个月垂直堆叠柱状图(相对于年度峰值月缩放柱高,最低保留 8% 可视高度)
|
||||
const monthlyYear = cons.monthlyYear || new Date().getFullYear();
|
||||
const currentMonthIdx = new Date().getMonth();
|
||||
patchText(monthlyYearBadge, String(monthlyYear));
|
||||
const monthlySeries = cons.monthlySeries || [];
|
||||
const maxMonthTokens = Math.max(
|
||||
@@ -718,7 +735,7 @@ export const ConsumptionView = defineComponent({
|
||||
}),
|
||||
(slice) => {
|
||||
latestSlice = slice;
|
||||
if (uiStore.getState().activeView !== 'consumption') {
|
||||
if (getVisibleMonitorView() !== 'consumption') {
|
||||
isDirty = true;
|
||||
return;
|
||||
}
|
||||
@@ -728,7 +745,7 @@ export const ConsumptionView = defineComponent({
|
||||
);
|
||||
|
||||
const unsubView = uiStore.subscribe(
|
||||
(st) => st.activeView,
|
||||
getVisibleMonitorView,
|
||||
(activeView) => {
|
||||
if (activeView === 'consumption' && isDirty) {
|
||||
isDirty = false;
|
||||
@@ -770,7 +787,7 @@ export const ConsumptionView = defineComponent({
|
||||
(st) => st.locale,
|
||||
() => {
|
||||
syncStaticLocaleLabels();
|
||||
if (uiStore.getState().activeView === 'consumption' && latestSlice) {
|
||||
if (getVisibleMonitorView() === 'consumption' && latestSlice) {
|
||||
isDirty = false;
|
||||
renderConsumptionData(latestSlice);
|
||||
} else {
|
||||
|
||||
@@ -14,7 +14,7 @@ import {
|
||||
normalizeClientOverviewModules,
|
||||
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';
|
||||
|
||||
export { CTX_CHANNEL_DEFS } from '../components/widgets/ContextWindowWidget.js';
|
||||
@@ -37,7 +37,7 @@ export const LiveOverviewView = defineComponent({
|
||||
const widgetHost = createDynamicWidgetHost({
|
||||
containerEl: overviewInner,
|
||||
mode: 'overview',
|
||||
isVisibleFn: () => uiStore.getState().activeView === 'overview',
|
||||
isVisibleFn: () => getVisibleMonitorView() === 'overview',
|
||||
initialModuleKeys: DEFAULT_CLIENT_OVERVIEW_MODULES,
|
||||
});
|
||||
|
||||
@@ -58,13 +58,13 @@ export const LiveOverviewView = defineComponent({
|
||||
}
|
||||
|
||||
function ensureCountdownTicker() {
|
||||
if (uiStore.getState().activeView !== 'overview') {
|
||||
if (getVisibleMonitorView() !== 'overview') {
|
||||
stopCountdownTicker();
|
||||
return;
|
||||
}
|
||||
if (!countdownTickTimer) {
|
||||
countdownTickTimer = setInterval(() => {
|
||||
if (uiStore.getState().activeView === 'overview' && latestData) {
|
||||
if (getVisibleMonitorView() === 'overview' && latestData) {
|
||||
renderData(latestData);
|
||||
}
|
||||
}, 30_000);
|
||||
@@ -88,7 +88,7 @@ export const LiveOverviewView = defineComponent({
|
||||
(st) => ({ telemetry: st.telemetry, minuteTick: st.minuteTick }),
|
||||
({ telemetry: data }) => {
|
||||
latestData = data;
|
||||
if (uiStore.getState().activeView !== 'overview') {
|
||||
if (getVisibleMonitorView() !== 'overview') {
|
||||
const stillRunning =
|
||||
(Array.isArray(data?.runningConversations) && data.runningConversations.length > 0) ||
|
||||
Boolean(
|
||||
@@ -110,7 +110,7 @@ export const LiveOverviewView = defineComponent({
|
||||
|
||||
const unsubView = uiStore.subscribe(
|
||||
(st) => ({
|
||||
activeView: st.activeView,
|
||||
activeView: getVisibleMonitorView(st),
|
||||
ctxInspectorAgentId: st.ctxInspectorAgentId,
|
||||
}),
|
||||
(slice) => {
|
||||
@@ -136,7 +136,7 @@ export const LiveOverviewView = defineComponent({
|
||||
const unsubI18n = i18nStore.subscribe(
|
||||
(st) => st.locale,
|
||||
() => {
|
||||
if (uiStore.getState().activeView !== 'overview') {
|
||||
if (getVisibleMonitorView() !== 'overview') {
|
||||
isDirty = true;
|
||||
// Refresh initial skeleton labels even before telemetry arrives
|
||||
if (!latestData) {
|
||||
|
||||
@@ -8,7 +8,7 @@ import { defineComponent } from '../core/component.js';
|
||||
import { h, patchAttr } from '../core/domPatch.js';
|
||||
import { i18nStore, t } from '../i18n/index.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 { SegmentedControl } from '../components/ui/SegmentedControl.js';
|
||||
import { SettingsAccountTab } from './settings/SettingsAccountTab.js';
|
||||
@@ -37,7 +37,7 @@ export const SettingsView = defineComponent({
|
||||
modelValue: initialSubTab,
|
||||
options: getSettingsSubTabOptions(),
|
||||
onUpdateModelValue: (nextSubTab) => {
|
||||
uiStore.setState({ settingsSubTab: nextSubTab });
|
||||
uiStore.setState({ settingsSubTab: nextSubTab }, { sync: true });
|
||||
},
|
||||
});
|
||||
|
||||
@@ -95,20 +95,21 @@ export const SettingsView = defineComponent({
|
||||
viewScrollbar.el,
|
||||
]);
|
||||
|
||||
let latestSettings = null;
|
||||
let latestCloudStatus = null;
|
||||
let latestContextWindowModels = [];
|
||||
const initialTelemetry = telemetryStore.getState().telemetry;
|
||||
accountTab.refs.renderAccount(initialTelemetry?.account, initialTelemetry?.quotas);
|
||||
|
||||
function syncAllTabs(settings, cloudStatus) {
|
||||
if (settings) {
|
||||
generalTab.refs.renderSettings(settings);
|
||||
structureTab.refs.renderSettings(settings);
|
||||
otherTab.refs.renderSettings(settings, latestContextWindowModels);
|
||||
}
|
||||
if (cloudStatus) {
|
||||
generalTab.refs.renderCloudStatus(cloudStatus);
|
||||
function syncActiveTab() {
|
||||
const ui = uiStore.getState();
|
||||
const { settingsSubTab } = ui;
|
||||
if (getVisibleMonitorView(ui) !== 'settings') return;
|
||||
const telemetry = telemetryStore.getState().telemetry;
|
||||
const settings = telemetry?.settings;
|
||||
if (settingsSubTab === 'structure') {
|
||||
if (settings) structureTab.refs.renderSettings(settings);
|
||||
} else if (settingsSubTab === 'other') {
|
||||
if (settings) otherTab.refs.renderSettings(settings, telemetry.contextWindowModels || []);
|
||||
} else if (SHOW_ACCOUNT_TAB && settingsSubTab === 'account') {
|
||||
accountTab.refs.renderAccount(telemetry?.account, telemetry?.quotas);
|
||||
} else {
|
||||
if (settings) generalTab.refs.renderSettings(settings);
|
||||
if (telemetry?.cloudStatus) generalTab.refs.renderCloudStatus(telemetry.cloudStatus);
|
||||
}
|
||||
refreshScroll();
|
||||
}
|
||||
@@ -121,33 +122,17 @@ export const SettingsView = defineComponent({
|
||||
account: st.telemetry?.account,
|
||||
quotas: st.telemetry?.quotas,
|
||||
}),
|
||||
(slice) => {
|
||||
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();
|
||||
}
|
||||
syncActiveTab
|
||||
);
|
||||
|
||||
const unsubUi = uiStore.subscribe(
|
||||
(st) => ({
|
||||
activeView: st.activeView,
|
||||
activeView: getVisibleMonitorView(st),
|
||||
settingsSubTab: st.settingsSubTab,
|
||||
}),
|
||||
(slice) => {
|
||||
applyActiveSubTab(slice.settingsSubTab, slice.activeView);
|
||||
if (slice.activeView === 'settings') {
|
||||
syncAllTabs(latestSettings, latestCloudStatus);
|
||||
}
|
||||
syncActiveTab();
|
||||
}
|
||||
);
|
||||
|
||||
|
||||
@@ -29,7 +29,7 @@ import {
|
||||
resolveScopedConversation,
|
||||
telemetryStore,
|
||||
} from '../store/telemetryStore.js';
|
||||
import { uiStore } from '../store/uiStore.js';
|
||||
import { getVisibleMonitorView, uiStore } from '../store/uiStore.js';
|
||||
import {
|
||||
MODEL_COLOR_VARS,
|
||||
createModelFitChart,
|
||||
@@ -50,7 +50,7 @@ function mergeSelectedAgentUnits(units) {
|
||||
for (const ag of units) {
|
||||
if (!ag || typeof ag !== 'object') continue;
|
||||
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 : [];
|
||||
for (const m of breakdown) {
|
||||
@@ -520,7 +520,8 @@ export const StepsDetailView = defineComponent({
|
||||
const baseScope = resolveScopedConversation(
|
||||
{ activeConversation: slice.activeConversation },
|
||||
'all',
|
||||
uiSt.ctxInspectorAgentId
|
||||
uiSt.ctxInspectorAgentId,
|
||||
true
|
||||
);
|
||||
const { hasSubagents, agents, subagents, mainAgent, aggregated } = baseScope;
|
||||
|
||||
@@ -1027,7 +1028,7 @@ export const StepsDetailView = defineComponent({
|
||||
subTabSwitch.setValue(tab);
|
||||
patchAttr(stepsScroll.el, 'hidden', tab !== 'steps');
|
||||
patchAttr(modelsScroll.el, 'hidden', tab !== 'models');
|
||||
if (uiStore.getState().activeView === 'steps' && latestSlice) {
|
||||
if (getVisibleMonitorView() === 'steps' && latestSlice) {
|
||||
renderStepsData(latestSlice);
|
||||
} else if (tab === 'steps') {
|
||||
stepsScroll.refresh();
|
||||
@@ -1053,7 +1054,7 @@ export const StepsDetailView = defineComponent({
|
||||
}),
|
||||
(slice) => {
|
||||
latestSlice = slice;
|
||||
if (uiStore.getState().activeView !== 'steps') {
|
||||
if (getVisibleMonitorView() !== 'steps') {
|
||||
if (!fitUserPicked) {
|
||||
fitPinnedWhileVisible = false;
|
||||
}
|
||||
@@ -1066,11 +1067,11 @@ export const StepsDetailView = defineComponent({
|
||||
);
|
||||
|
||||
let prevScope = uiStore.getState().selectedAgentScope;
|
||||
let prevActiveView = uiStore.getState().activeView;
|
||||
let prevActiveView = getVisibleMonitorView();
|
||||
|
||||
const unsubView = uiStore.subscribe(
|
||||
(st) => ({
|
||||
activeView: st.activeView,
|
||||
activeView: getVisibleMonitorView(st),
|
||||
selectedAgentScope: st.selectedAgentScope,
|
||||
}),
|
||||
(uiSlice) => {
|
||||
@@ -1099,7 +1100,7 @@ export const StepsDetailView = defineComponent({
|
||||
(st) => st.locale,
|
||||
() => {
|
||||
refreshStaticLocaleLabels();
|
||||
if (uiStore.getState().activeView === 'steps' && latestSlice) {
|
||||
if (getVisibleMonitorView() === 'steps' && latestSlice) {
|
||||
renderStepsData(latestSlice);
|
||||
} else {
|
||||
isDirty = true;
|
||||
|
||||
@@ -33,7 +33,7 @@ import {
|
||||
normalizeClientWindowMountMode,
|
||||
saveSettingsPatch,
|
||||
} 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 { EditableSlotList } from '../../components/settings/EditableSlotList.js';
|
||||
import { buildStructurePreviewTelemetry } from '../../components/settings/structurePreviewMock.js';
|
||||
@@ -94,7 +94,7 @@ export const SettingsStructureTab = defineComponent({
|
||||
|
||||
function isStructureVisible() {
|
||||
const st = uiStore.getState();
|
||||
return st.activeView === 'settings' && st.settingsSubTab === 'structure';
|
||||
return getVisibleMonitorView(st) === 'settings' && st.settingsSubTab === 'structure';
|
||||
}
|
||||
|
||||
function buildDraftTelemetry() {
|
||||
@@ -789,7 +789,7 @@ export const SettingsStructureTab = defineComponent({
|
||||
let wasStructureVisible = isStructureVisible();
|
||||
const unsubUi = uiStore.subscribe(
|
||||
(st) => ({
|
||||
activeView: st.activeView,
|
||||
activeView: getVisibleMonitorView(st),
|
||||
settingsSubTab: st.settingsSubTab,
|
||||
settingsStructureTab: st.settingsStructureTab,
|
||||
}),
|
||||
|
||||
+16
-10
@@ -2669,29 +2669,37 @@ input {
|
||||
--rail-dot: var(--accent-primary);
|
||||
}
|
||||
|
||||
.turn-rail-line {
|
||||
.turn-rail::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
left: 3.25px;
|
||||
width: 1.5px;
|
||||
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;
|
||||
bottom: 0;
|
||||
}
|
||||
|
||||
.turn-rail.has-up:not(.has-down) .turn-rail-line {
|
||||
.turn-rail.has-up:not(.has-down)::before {
|
||||
top: 0;
|
||||
bottom: 50%;
|
||||
}
|
||||
|
||||
.turn-rail.has-down:not(.has-up) .turn-rail-line {
|
||||
.turn-rail.has-down:not(.has-up)::before {
|
||||
top: 50%;
|
||||
bottom: 0;
|
||||
}
|
||||
|
||||
.turn-rail-dot {
|
||||
.turn-rail.is-cap::after,
|
||||
.turn-rail.is-origin::after {
|
||||
content: '';
|
||||
box-sizing: border-box;
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 4px;
|
||||
@@ -2699,13 +2707,13 @@ input {
|
||||
border-radius: var(--radius-pill);
|
||||
}
|
||||
|
||||
.turn-rail-dot.is-cap {
|
||||
.turn-rail.is-cap::after {
|
||||
width: 3.5px;
|
||||
height: 3.5px;
|
||||
background: var(--rail-line);
|
||||
}
|
||||
|
||||
.turn-rail-dot.is-origin {
|
||||
.turn-rail.is-origin::after {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
background: var(--surface-panel);
|
||||
@@ -2713,13 +2721,11 @@ input {
|
||||
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);
|
||||
}
|
||||
|
||||
.turn-rail[hidden],
|
||||
.turn-rail-line[hidden],
|
||||
.turn-rail-dot[hidden],
|
||||
.turn-prompt-tip[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import vm from 'node:vm';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { isDeepStrictEqual } from 'node:util';
|
||||
import * as metrics from '../speed-metrics.mjs';
|
||||
import { stripModuleSyntax } from '../scripts/build-bundle.mjs';
|
||||
|
||||
@@ -61,6 +63,7 @@ export function backendHarness({
|
||||
remoteFetch=null,
|
||||
execFileImpl=null,
|
||||
sourceText=null,
|
||||
clock=null,
|
||||
metricsImplementation=metrics,
|
||||
}={}) {
|
||||
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 state={calls:[],errors:[],saves:[],settings,trajectories,transcripts,transcriptMtimeMs:1,userStatus,quotaSummary,localCatalog,remoteCatalog,pluginManifest,hasGitDir,deepStats,deepStatsMtimeMs:1};
|
||||
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'}},
|
||||
console:{error:m=>state.errors.push(m)},
|
||||
cpSync:()=>{},
|
||||
@@ -132,6 +139,9 @@ export function backendHarness({
|
||||
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,
|
||||
Response:class {constructor(body,options){this.body=body;this.options=options;}},
|
||||
SidecarApp:class {page(){} api(){} run(){}},
|
||||
@@ -154,6 +164,6 @@ export function backendHarness({
|
||||
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};
|
||||
}
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import test from 'node:test';
|
||||
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 { writeTrajectoryCacheFile } from '../backend/trajectory-cache-file.mjs';
|
||||
|
||||
const raw={trajectory:{steps:[{status:'CORTEX_STEP_STATUS_DONE',metadata:{
|
||||
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'}}]}};
|
||||
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()=>{
|
||||
const h=backendHarness({cache:{test:old},trajectories:{test:new Error('offline')}});
|
||||
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 () => {
|
||||
const {
|
||||
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].isTurnStart, true);
|
||||
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 () => {
|
||||
|
||||
@@ -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']){
|
||||
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;
|
||||
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',()=>{
|
||||
const zero=parse({output:0,response:0,thinking:0});
|
||||
|
||||
@@ -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'
|
||||
);
|
||||
assert.equal(
|
||||
stepTableWhileRailOff.querySelector('.turn-rail').hasAttribute('hidden'),
|
||||
Array.from(stepTableWhileRailOff.querySelectorAll('.turn-rail'))
|
||||
.every((rail) => rail.hasAttribute('hidden')),
|
||||
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;
|
||||
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');
|
||||
assert.equal(row0Rail.hasAttribute('hidden'), false);
|
||||
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(row1Rail.querySelector('.turn-rail-dot').classList.contains('is-origin'), true, 'First step of user turn renders hollow origin dot');
|
||||
assert.equal(row0Rail.classList.contains('is-cap'), true, 'Newest step in turn renders cap 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');
|
||||
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[1].children[0].querySelector('.agent-badge').textContent, '主');
|
||||
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,
|
||||
'Interleaved subagent step at top joins unified rootTurnIndex rail as cap'
|
||||
);
|
||||
assert.equal(
|
||||
multiStepRows[1].children[0].querySelector('.turn-rail-dot').hasAttribute('hidden'),
|
||||
true,
|
||||
multiStepRows[1].children[0].querySelector('.turn-rail').classList.contains('is-cap') ||
|
||||
multiStepRows[1].children[0].querySelector('.turn-rail').classList.contains('is-origin'),
|
||||
false,
|
||||
'Middle main step connects continuously along unified rootTurnIndex rail'
|
||||
);
|
||||
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,
|
||||
'Earliest main step anchors unified rootTurnIndex rail origin'
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user