mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-26 17:09:28 +08:00
feat(panel): add step anomaly diagnostics, >=100 tok/s integer speed formatting, and capsule alignment fix
This commit is contained in:
+764
-57
File diff suppressed because it is too large
Load Diff
@@ -79,7 +79,7 @@ function projectDisplayStep(st) {
|
||||
const {
|
||||
stepIndex, createdAtMs, isCompactionStep, modelKey, modelShort, modelLabel,
|
||||
modelUpstream, responseModel, modelSource, tokPerSec, ttftSec, totalDurationSec,
|
||||
streamDurationSec, selectedSpeedReason, contextTokens, inputTokens, cacheReadTokens,
|
||||
streamDurationSec, selectedSpeedReason, anomaly, anomalySig, contextTokens, inputTokens, cacheReadTokens,
|
||||
outputTokens, thinkingTokens, responseTokens, cacheHitPct, costUsd, inCostUsd,
|
||||
cacheCostUsd, outCostUsd, agentId, agentCascadeId, agentKind, agentOrdinal,
|
||||
agentCustomRole, agentLabel, agentBadge, agentRole, agentIndex, isSubagent,
|
||||
@@ -91,7 +91,9 @@ function projectDisplayStep(st) {
|
||||
return {
|
||||
stepIndex, createdAtMs, isCompactionStep, modelKey, modelShort, modelLabel,
|
||||
modelUpstream, responseModel, modelSource, tokPerSec, ttftSec, totalDurationSec,
|
||||
streamDurationSec, selectedSpeedReason, contextTokens, inputTokens, cacheReadTokens,
|
||||
streamDurationSec, selectedSpeedReason,
|
||||
...(anomaly ? { anomaly, anomalySig } : {}),
|
||||
contextTokens, inputTokens, cacheReadTokens,
|
||||
outputTokens, thinkingTokens, responseTokens, cacheHitPct, costUsd, inCostUsd,
|
||||
cacheCostUsd, outCostUsd, agentId, agentCascadeId, agentKind, agentOrdinal,
|
||||
agentCustomRole, agentLabel, agentBadge, agentRole, agentIndex, isSubagent,
|
||||
@@ -104,7 +106,9 @@ function projectDisplayStep(st) {
|
||||
|
||||
const MAX_DISPLAY_STEP_CACHE_ENTRIES = 8;
|
||||
const displayStepsCache = new Map();
|
||||
const displayStepFields = Object.keys(projectDisplayStep({}));
|
||||
const displayStepFields = Object.keys(projectDisplayStep({ anomaly: true, anomalySig: '' })).filter(
|
||||
(k) => k !== 'anomaly'
|
||||
);
|
||||
|
||||
function haveSameDisplaySteps(previous, current) {
|
||||
if (!previous || !current) return previous === current;
|
||||
|
||||
@@ -914,6 +914,84 @@ function decodeProtoContextWindowMetaSlice(buf, state, end, includeBreakdown) {
|
||||
};
|
||||
}
|
||||
|
||||
function decodeProtoRetryInfoSlice(buf, state, end) {
|
||||
const ri = {};
|
||||
while (state.off < end) {
|
||||
const rTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end)));
|
||||
const rFn = rTag >>> 3;
|
||||
const rWt = rTag & 7;
|
||||
if (rFn === 2 && rWt === 2) {
|
||||
ri.usage = decodeProtoModelUsageSlice(buf, state, readSubEnd(buf, state, end));
|
||||
} else if (rFn === 3 && rWt === 2) {
|
||||
const errStr = readProtoString(buf, state, end).trim();
|
||||
if (errStr) {
|
||||
ri.error = errStr.length > 320 ? `${errStr.slice(0, 319)}…` : errStr;
|
||||
}
|
||||
} else if (rFn === 5 && rWt === 0) {
|
||||
const code = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end)));
|
||||
if (code > 0) ri.reasonCode = code;
|
||||
} else if (rFn === 7 && rWt === 2) {
|
||||
const dur = decodeProtoDurationSlice(buf, state, readSubEnd(buf, state, end));
|
||||
if (dur) ri.retryDelay = dur;
|
||||
} else {
|
||||
skipProtoField(buf, state, rWt, end);
|
||||
}
|
||||
}
|
||||
state.off = end;
|
||||
return ri;
|
||||
}
|
||||
|
||||
function decodeProtoErrorMessageSlice(buf, state, end) {
|
||||
let userErrorMessage = '';
|
||||
let shortError = '';
|
||||
let errorCode = 0;
|
||||
let shouldShowModel = false;
|
||||
let shouldShowUser = false;
|
||||
|
||||
while (state.off < end) {
|
||||
const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end)));
|
||||
const fn = tag >>> 3;
|
||||
const wt = tag & 7;
|
||||
if (fn === 3 && wt === 2) {
|
||||
const eEnd = readSubEnd(buf, state, end);
|
||||
while (state.off < eEnd) {
|
||||
const eTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, eEnd)));
|
||||
const eFn = eTag >>> 3;
|
||||
const eWt = eTag & 7;
|
||||
if (eFn === 1 && eWt === 2) {
|
||||
const s = readProtoString(buf, state, eEnd).trim();
|
||||
if (s) userErrorMessage = s.length > 240 ? `${s.slice(0, 239)}…` : s;
|
||||
} else if (eFn === 2 && eWt === 2) {
|
||||
const s = readProtoString(buf, state, eEnd).trim();
|
||||
if (s) shortError = s.length > 320 ? `${s.slice(0, 319)}…` : s;
|
||||
} else if (eFn === 7 && eWt === 0) {
|
||||
errorCode = Number(BigInt.asUintN(32, readProtoVarint(buf, state, eEnd)));
|
||||
} else {
|
||||
skipProtoField(buf, state, eWt, eEnd);
|
||||
}
|
||||
}
|
||||
state.off = eEnd;
|
||||
} else if (fn === 4 && wt === 0) {
|
||||
shouldShowModel = readProtoVarint(buf, state, end) !== 0n;
|
||||
} else if (fn === 5 && wt === 0) {
|
||||
shouldShowUser = readProtoVarint(buf, state, end) !== 0n;
|
||||
} else {
|
||||
skipProtoField(buf, state, wt, end);
|
||||
}
|
||||
}
|
||||
state.off = end;
|
||||
if (!userErrorMessage && !shortError && !errorCode) return null;
|
||||
return {
|
||||
error: {
|
||||
...(userErrorMessage ? { userErrorMessage } : {}),
|
||||
...(shortError ? { shortError } : {}),
|
||||
...(errorCode > 0 ? { errorCode } : {}),
|
||||
},
|
||||
...(shouldShowModel ? { shouldShowModel: true } : {}),
|
||||
...(shouldShowUser ? { shouldShowUser: true } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function decodeProtoChatModelMetaSlice(buf, state, end, includeBreakdown) {
|
||||
let model = '';
|
||||
let usage = null;
|
||||
@@ -922,6 +1000,8 @@ function decodeProtoChatModelMetaSlice(buf, state, end, includeBreakdown) {
|
||||
let streamingDuration = '';
|
||||
let responseModel = '';
|
||||
let modelDisplayName = '';
|
||||
let retryCount = 0;
|
||||
let retryInfos = null;
|
||||
const extraMeta = {};
|
||||
let messagePrompts = null;
|
||||
let tools = null;
|
||||
@@ -1004,6 +1084,8 @@ function decodeProtoChatModelMetaSlice(buf, state, end, includeBreakdown) {
|
||||
timeToFirstToken = decodeProtoDurationSlice(buf, state, readSubEnd(buf, state, end));
|
||||
} else if (fn === 12 && wt === 2) {
|
||||
streamingDuration = decodeProtoDurationSlice(buf, state, readSubEnd(buf, state, end));
|
||||
} else if (fn === 14 && wt === 0) {
|
||||
retryCount = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end)));
|
||||
} else if (fn === 16 && wt === 2) {
|
||||
if (includeBreakdown) {
|
||||
const psEnd = readSubEnd(buf, state, end);
|
||||
@@ -1030,6 +1112,10 @@ function decodeProtoChatModelMetaSlice(buf, state, end, includeBreakdown) {
|
||||
} else {
|
||||
skipProtoField(buf, state, wt, end);
|
||||
}
|
||||
} else if (fn === 17 && wt === 2) {
|
||||
const ri = decodeProtoRetryInfoSlice(buf, state, readSubEnd(buf, state, end));
|
||||
if (!retryInfos) retryInfos = [];
|
||||
retryInfos.push(ri);
|
||||
} else if (fn === 19 && wt === 2) {
|
||||
responseModel = readProtoString(buf, state, end).trim();
|
||||
} else if (fn === 20 && wt === 2) {
|
||||
@@ -1056,6 +1142,8 @@ function decodeProtoChatModelMetaSlice(buf, state, end, includeBreakdown) {
|
||||
usage.apiProvider = 'API_PROVIDER_ANTHROPIC';
|
||||
}
|
||||
|
||||
const hasRetryEvidence =
|
||||
retryCount > 0 || Boolean(retryInfos && retryInfos.some((r) => r?.error || r?.reasonCode));
|
||||
return {
|
||||
chatModel: {
|
||||
...(model ? { model } : {}),
|
||||
@@ -1065,6 +1153,8 @@ function decodeProtoChatModelMetaSlice(buf, state, end, includeBreakdown) {
|
||||
: {}),
|
||||
...(timeToFirstToken ? { timeToFirstToken } : {}),
|
||||
...(streamingDuration ? { streamingDuration } : {}),
|
||||
...(retryCount > 0 ? { retryCount } : {}),
|
||||
...(hasRetryEvidence && retryInfos ? { retryInfos } : {}),
|
||||
...(responseModel ? { responseModel } : {}),
|
||||
...(modelDisplayName ? { modelDisplayName } : {}),
|
||||
...(messagePrompts ? { messagePrompts } : {}),
|
||||
@@ -1233,19 +1323,7 @@ function decodeProtoStepMeta(rawBlob, fallbackIdx) {
|
||||
}
|
||||
state.off = siEnd;
|
||||
} else if (fn === 28 && wt === 2) {
|
||||
const riEnd = readSubEnd(buf, state, end);
|
||||
const ri = {};
|
||||
while (state.off < riEnd) {
|
||||
const rTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, riEnd)));
|
||||
const rFn = rTag >>> 3;
|
||||
const rWt = rTag & 7;
|
||||
if (rFn === 2 && rWt === 2) {
|
||||
ri.usage = decodeProtoModelUsageSlice(buf, state, readSubEnd(buf, state, riEnd));
|
||||
} else {
|
||||
skipProtoField(buf, state, rWt, riEnd);
|
||||
}
|
||||
}
|
||||
state.off = riEnd;
|
||||
const ri = decodeProtoRetryInfoSlice(buf, state, readSubEnd(buf, state, end));
|
||||
if (!retryInfos) retryInfos = [];
|
||||
retryInfos.push(ri);
|
||||
} else if (fn === 30 && wt === 2) {
|
||||
@@ -1501,6 +1579,9 @@ function decodeProtoSelectiveStepPayload(
|
||||
readSubEnd(buf, state, end),
|
||||
keepFullText
|
||||
);
|
||||
} else if (fn === 24 && wt === 2 && stepTypeNum === 17) {
|
||||
const em = decodeProtoErrorMessageSlice(buf, state, readSubEnd(buf, state, end));
|
||||
if (em) out.errorMessage = em;
|
||||
} else if (fn === 114 && wt === 2 && stepTypeNum === 101 && includeSystemMessage) {
|
||||
const sysMsg = decodeProtoSystemMessageSlice(buf, state, readSubEnd(buf, state, end));
|
||||
if (sysMsg) out.systemMessage = { message: sysMsg };
|
||||
@@ -1786,6 +1867,7 @@ export function readLocalSqliteTrajectory(dbFilePath, options = {}) {
|
||||
if (
|
||||
rec.stepTypeNum === 14 ||
|
||||
rec.stepTypeNum === 15 ||
|
||||
rec.stepTypeNum === 17 ||
|
||||
(isChildTrajectory && rec.stepTypeNum === 101) ||
|
||||
isInvSub ||
|
||||
(inRunningTail && (rec.stepTypeNum !== 132 || !rec.metadata?.toolCall?.argumentsJson))
|
||||
@@ -1868,6 +1950,9 @@ export function readLocalSqliteTrajectory(dbFilePath, options = {}) {
|
||||
if (decodedPayload.plannerResponse) {
|
||||
stepObj.plannerResponse = decodedPayload.plannerResponse;
|
||||
}
|
||||
if (decodedPayload.errorMessage) {
|
||||
stepObj.errorMessage = decodedPayload.errorMessage;
|
||||
}
|
||||
if (decodedPayload.invokeSubagent) {
|
||||
stepObj.invokeSubagent = decodedPayload.invokeSubagent;
|
||||
}
|
||||
|
||||
@@ -783,11 +783,23 @@ function loadOfflineTranscriptConversation(conv, diskFiles, externalByLower, loc
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (sq.type === 'CORTEX_STEP_TYPE_ERROR_MESSAGE') {
|
||||
sqliteRawSteps.push({
|
||||
type: sq.type,
|
||||
status: sq.status,
|
||||
...(sq.errorMessage ? { errorMessage: sq.errorMessage } : {}),
|
||||
...(typeof tLine?.error === 'string' && tLine.error ? { error: tLine.error } : {}),
|
||||
...(typeof tLine?.content === 'string' && tLine.content ? { content: tLine.content } : {}),
|
||||
metadata: sq.metadata,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
if (sq.metadata?.modelUsage) {
|
||||
const rawUsage = sq.metadata?.modelUsage || sq.metadata?.retryInfos?.[0]?.usage;
|
||||
if (rawUsage) {
|
||||
const deepStep = extMatch?.steps?.[modelOrdinal] || null;
|
||||
modelOrdinal += 1;
|
||||
const mu = { ...sq.metadata.modelUsage };
|
||||
const mu = { ...rawUsage };
|
||||
if (!mu.model) {
|
||||
const fallbackModel = String(
|
||||
tLine?.model || tLine?.generator_model || deepStep?.modelKey || ''
|
||||
@@ -822,7 +834,9 @@ function loadOfflineTranscriptConversation(conv, diskFiles, externalByLower, loc
|
||||
upperType === 'CORTEX_STEP_TYPE_USER_INPUT' ||
|
||||
(line.userInput && typeof line.userInput === 'object') ||
|
||||
upperType === 'SYSTEM_MESSAGE' ||
|
||||
upperType === 'CORTEX_STEP_TYPE_SYSTEM_MESSAGE'
|
||||
upperType === 'CORTEX_STEP_TYPE_SYSTEM_MESSAGE' ||
|
||||
upperType === 'ERROR_MESSAGE' ||
|
||||
upperType === 'CORTEX_STEP_TYPE_ERROR_MESSAGE'
|
||||
) {
|
||||
sqliteRawSteps.push(line);
|
||||
} else if (
|
||||
@@ -830,14 +844,19 @@ function loadOfflineTranscriptConversation(conv, diskFiles, externalByLower, loc
|
||||
line.cache_read_tokens !== undefined ||
|
||||
line.output_tokens !== undefined
|
||||
) {
|
||||
const tailStatus = String(line.status || '').trim().toUpperCase();
|
||||
sqliteRawSteps.push({
|
||||
type:
|
||||
upperType === 'CHECKPOINT' || upperType === 'CORTEX_STEP_TYPE_CHECKPOINT'
|
||||
? 'CORTEX_STEP_TYPE_CHECKPOINT'
|
||||
: String(line.type || 'PLANNER_RESPONSE'),
|
||||
status: /CANCEL/i.test(String(line.status || ''))
|
||||
status: /CANCEL/.test(tailStatus)
|
||||
? 'CORTEX_STEP_STATUS_CANCELED'
|
||||
: 'CORTEX_STEP_STATUS_DONE',
|
||||
: /ERROR/.test(tailStatus)
|
||||
? 'CORTEX_STEP_STATUS_ERROR'
|
||||
: /INTERRUPT/.test(tailStatus)
|
||||
? 'CORTEX_STEP_STATUS_INTERRUPTED'
|
||||
: 'CORTEX_STEP_STATUS_DONE',
|
||||
plannerResponse: {
|
||||
response: typeof line.content === 'string' ? line.content : '',
|
||||
thinking: typeof line.thinking === 'string' ? line.thinking : '',
|
||||
@@ -873,7 +892,9 @@ function loadOfflineTranscriptConversation(conv, diskFiles, externalByLower, loc
|
||||
upperType === 'CORTEX_STEP_TYPE_USER_INPUT' ||
|
||||
(line.userInput && typeof line.userInput === 'object') ||
|
||||
upperType === 'SYSTEM_MESSAGE' ||
|
||||
upperType === 'CORTEX_STEP_TYPE_SYSTEM_MESSAGE'
|
||||
upperType === 'CORTEX_STEP_TYPE_SYSTEM_MESSAGE' ||
|
||||
upperType === 'ERROR_MESSAGE' ||
|
||||
upperType === 'CORTEX_STEP_TYPE_ERROR_MESSAGE'
|
||||
) {
|
||||
syntheticSteps.push(line);
|
||||
continue;
|
||||
@@ -898,7 +919,11 @@ function loadOfflineTranscriptConversation(conv, diskFiles, externalByLower, loc
|
||||
const rawStatus = String(line.status || '').trim().toUpperCase();
|
||||
const mappedStatus = /CANCEL/.test(rawStatus)
|
||||
? 'CORTEX_STEP_STATUS_CANCELED'
|
||||
: 'CORTEX_STEP_STATUS_DONE';
|
||||
: /ERROR/.test(rawStatus)
|
||||
? 'CORTEX_STEP_STATUS_ERROR'
|
||||
: /INTERRUPT/.test(rawStatus)
|
||||
? 'CORTEX_STEP_STATUS_INTERRUPTED'
|
||||
: 'CORTEX_STEP_STATUS_DONE';
|
||||
const finishedAt = String(
|
||||
line.finished_generating_at ||
|
||||
line.finishedGeneratingAt ||
|
||||
@@ -1931,6 +1956,7 @@ export async function enumerateAndSyncConversations({
|
||||
turnRailTelemetry: true,
|
||||
wakeupTurnTelemetry: true,
|
||||
contextGroupsTelemetry: 2,
|
||||
anomalyTelemetry: 1,
|
||||
steps: stepsWithOwners,
|
||||
subagentRefs,
|
||||
};
|
||||
@@ -1964,6 +1990,7 @@ export async function enumerateAndSyncConversations({
|
||||
!prev.speedClearedTelemetry ||
|
||||
!prev.turnRailTelemetry ||
|
||||
!prev.contextGroupsTelemetry ||
|
||||
!prev.anomalyTelemetry ||
|
||||
metaChanged ||
|
||||
!isDeepStrictEqual(prev.steps, stepsWithOwners);
|
||||
|
||||
@@ -2033,6 +2060,7 @@ export async function enumerateAndSyncConversations({
|
||||
speedClearedTelemetry: true,
|
||||
turnRailTelemetry: true,
|
||||
contextGroupsTelemetry: 2,
|
||||
anomalyTelemetry: 1,
|
||||
steps: offlineStepsWithOwners,
|
||||
subagentRefs: offlineFallback.subagentRefs,
|
||||
};
|
||||
@@ -2163,6 +2191,7 @@ export async function enumerateAndSyncConversations({
|
||||
if (!cached.contextLimitTelemetry && lowerCid === contextTelemetryCascadeId) return true;
|
||||
if (
|
||||
(!cached.turnRailTelemetry ||
|
||||
!cached.anomalyTelemetry ||
|
||||
hasMissingTurnRailFields(cached) ||
|
||||
needsWakeupTurnRefresh(conv, cached) ||
|
||||
hasDroppedContextGroups(cached)) &&
|
||||
@@ -2345,6 +2374,7 @@ export async function enumerateAndSyncConversations({
|
||||
!hasMissingStepFields(existingSubCache) &&
|
||||
(!isSelectedSubFamily ||
|
||||
(Boolean(existingSubCache.turnRailTelemetry) &&
|
||||
Boolean(existingSubCache.anomalyTelemetry) &&
|
||||
!hasMissingTurnRailFields(existingSubCache) &&
|
||||
!needsWakeupTurnRefresh(subConv, existingSubCache) &&
|
||||
!hasDroppedContextGroups(existingSubCache)));
|
||||
|
||||
@@ -291,6 +291,11 @@ function accumulateStepIntoModelMap(perModelStats, st, mInfo, stepCost) {
|
||||
ttftSumSec: 0,
|
||||
ttftSampleCount: 0,
|
||||
speedAccumulator: createSpeedAccumulator(),
|
||||
anomalySteps: 0,
|
||||
anomalyCount: 0,
|
||||
anomalyDangerCount: 0,
|
||||
anomalyTotalDelaySec: 0,
|
||||
anomalyByKind: {},
|
||||
});
|
||||
}
|
||||
const agg = perModelStats.get(modelGroupKey);
|
||||
@@ -315,6 +320,28 @@ function accumulateStepIntoModelMap(perModelStats, st, mInfo, stepCost) {
|
||||
agg.ttftSampleCount += 1;
|
||||
}
|
||||
|
||||
if (st?.anomaly && Number(st.anomaly.count) > 0) {
|
||||
agg.anomalySteps += 1;
|
||||
agg.anomalyCount += Number(st.anomaly.count);
|
||||
if (st.anomaly.severity === 'danger') {
|
||||
agg.anomalyDangerCount += 1;
|
||||
}
|
||||
if (Number(st.anomaly.totalDelaySec) > 0) {
|
||||
agg.anomalyTotalDelaySec += Number(st.anomaly.totalDelaySec);
|
||||
}
|
||||
if (st.anomaly.kinds && typeof st.anomaly.kinds === 'object') {
|
||||
for (const [k, v] of Object.entries(st.anomaly.kinds)) {
|
||||
const cnt = Number(v || 0);
|
||||
if (cnt > 0) {
|
||||
agg.anomalyByKind[k] = (agg.anomalyByKind[k] || 0) + cnt;
|
||||
}
|
||||
}
|
||||
} else if (st.anomaly.primaryKind) {
|
||||
agg.anomalyByKind[st.anomaly.primaryKind] =
|
||||
(agg.anomalyByKind[st.anomaly.primaryKind] || 0) + Number(st.anomaly.count);
|
||||
}
|
||||
}
|
||||
|
||||
agg.calls += 1;
|
||||
agg.inputTokens += inTok;
|
||||
agg.cacheReadTokens += cacheTok;
|
||||
@@ -342,6 +369,11 @@ function finalizeModelBreakdownMap(perModelStats) {
|
||||
fallbackModelId,
|
||||
ttftSumSec,
|
||||
ttftSampleCount,
|
||||
anomalySteps,
|
||||
anomalyCount,
|
||||
anomalyDangerCount,
|
||||
anomalyTotalDelaySec,
|
||||
anomalyByKind,
|
||||
...m
|
||||
}) => {
|
||||
const sortedUpstream = Array.from((upstreamModelCounts || new Map()).entries())
|
||||
@@ -355,6 +387,7 @@ function finalizeModelBreakdownMap(perModelStats) {
|
||||
promptTokens > 0 ? +((m.cacheReadTokens / promptTokens) * 100).toFixed(1) : 0;
|
||||
const avgTtftSec =
|
||||
ttftSampleCount > 0 ? roundMetric(ttftSumSec / ttftSampleCount) : null;
|
||||
const hasAnomalies = Number(anomalyCount || 0) > 0;
|
||||
return {
|
||||
...m,
|
||||
upstreamName: primaryUpstream,
|
||||
@@ -365,6 +398,15 @@ function finalizeModelBreakdownMap(perModelStats) {
|
||||
ttftSampleCount,
|
||||
avgTokPerSec: roundMetric(finishedSpeed.avgTokPerSec),
|
||||
speedSummary: finishedSpeed,
|
||||
...(hasAnomalies
|
||||
? {
|
||||
anomalySteps: Number(anomalySteps || 0),
|
||||
anomalyCount: Number(anomalyCount || 0),
|
||||
anomalyDangerCount: Number(anomalyDangerCount || 0),
|
||||
anomalyTotalDelaySec: +(Number(anomalyTotalDelaySec || 0)).toFixed(1),
|
||||
anomalyByKind: anomalyByKind || {},
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
@@ -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=1795088041305">
|
||||
<link rel="stylesheet" href="/styles.css?v=1795093491990">
|
||||
<script src="/preload.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app-root"></div>
|
||||
<script src="/app.js?v=1795088041305"></script>
|
||||
<script src="/app.js?v=1795093491990"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -11,6 +11,8 @@
|
||||
import { h, patchAttr, patchClasses, patchStyleVar, patchText } from '../../core/domPatch.js';
|
||||
import {
|
||||
formatAgentBadgeText,
|
||||
formatSpeedMetric,
|
||||
formatStepAnomalyInlineSummary,
|
||||
formatTokens,
|
||||
formatTokensPrecise,
|
||||
formatUsd,
|
||||
@@ -641,7 +643,7 @@ function formatChartMetricValue(metric, val) {
|
||||
case 'context':
|
||||
return `${formatTokensPrecise(val)} tok`;
|
||||
case 'tps':
|
||||
return `${val.toFixed(1)} tok/s`;
|
||||
return formatSpeedMetric(val, ' tok/s');
|
||||
case 'ttft':
|
||||
return `${val.toFixed(1)}s`;
|
||||
case 'cache':
|
||||
@@ -660,7 +662,7 @@ function formatChartMetricCompact(metric, val) {
|
||||
case 'context':
|
||||
return formatTokens(val);
|
||||
case 'tps':
|
||||
return `${val.toFixed(1)} tok/s`;
|
||||
return formatSpeedMetric(val, ' tok/s');
|
||||
case 'ttft':
|
||||
return `${val.toFixed(1)}s`;
|
||||
case 'cache':
|
||||
@@ -750,6 +752,10 @@ export function createSessionLineChart() {
|
||||
const dotsGroup = document.createElementNS(SVG_NS, 'g');
|
||||
svg.appendChild(dotsGroup);
|
||||
|
||||
const anomalyDotsGroup = document.createElementNS(SVG_NS, 'g');
|
||||
anomalyDotsGroup.setAttribute('class', 'sstep-anomaly-dots');
|
||||
svg.appendChild(anomalyDotsGroup);
|
||||
|
||||
const hoverLine = document.createElementNS(SVG_NS, 'line');
|
||||
hoverLine.setAttribute('class', 'trend-hover-line');
|
||||
hoverLine.setAttribute('y1', '10');
|
||||
@@ -776,10 +782,12 @@ export function createSessionLineChart() {
|
||||
const tipMainLeft = h('strong', { className: 'trend-tip-tokens text-mono' });
|
||||
const tipMainRight = h('span', { className: 'trend-tip-cost text-mono' });
|
||||
const tipSub = h('div', { className: 'trend-tip-sub text-mono', hidden: true });
|
||||
const tipAnomaly = h('div', { className: 'trend-tip-anomaly text-mono', hidden: true });
|
||||
const tooltipEl = h('div', { className: 'trend-tooltip', hidden: true }, [
|
||||
h('div', { className: 'trend-tip-head' }, [tipHeadLeft, tipHeadRight]),
|
||||
h('div', { className: 'trend-tip-main' }, [tipMainLeft, tipMainRight]),
|
||||
tipSub,
|
||||
tipAnomaly,
|
||||
]);
|
||||
|
||||
const xAxisEl = h('div', { className: 'trend-x-axis' });
|
||||
@@ -837,7 +845,12 @@ export function createSessionLineChart() {
|
||||
patchAttr(hoverDot, 'hidden', false);
|
||||
patchAttr(hoverDot, 'cx', pt.x.toFixed(1));
|
||||
patchAttr(hoverDot, 'cy', pt.y.toFixed(1));
|
||||
patchStyleVar(hoverDot, '--hover-dot-color', pt.hoverColor || 'var(--ctx-cached)');
|
||||
const hoverAccent = pt.anomalySummary
|
||||
? pt.anomalySeverity === 'danger'
|
||||
? 'var(--metric-danger)'
|
||||
: 'var(--metric-warn)'
|
||||
: pt.hoverColor || 'var(--ctx-cached)';
|
||||
patchStyleVar(hoverDot, '--hover-dot-color', hoverAccent);
|
||||
|
||||
patchAttr(peakPill, 'hidden', true);
|
||||
patchAttr(tooltipEl, 'hidden', false);
|
||||
@@ -853,6 +866,11 @@ export function createSessionLineChart() {
|
||||
if (pt.subDetail) {
|
||||
patchText(tipSub, pt.subDetail);
|
||||
}
|
||||
patchAttr(tipAnomaly, 'hidden', !pt.anomalySummary);
|
||||
if (pt.anomalySummary) {
|
||||
patchText(tipAnomaly, pt.anomalySummary);
|
||||
patchClasses(tipAnomaly, { 'is-danger': pt.anomalySeverity === 'danger' });
|
||||
}
|
||||
|
||||
const rawPct = (pt.x / viewW) * 100;
|
||||
const clampedPct = Math.max(1, Math.min(99, rawPct));
|
||||
@@ -998,6 +1016,7 @@ export function createSessionLineChart() {
|
||||
while (multiAreaGroup.firstChild) multiAreaGroup.removeChild(multiAreaGroup.firstChild);
|
||||
while (multiLineGroup.firstChild) multiLineGroup.removeChild(multiLineGroup.firstChild);
|
||||
while (dotsGroup.firstChild) dotsGroup.removeChild(dotsGroup.firstChild);
|
||||
while (anomalyDotsGroup.firstChild) anomalyDotsGroup.removeChild(anomalyDotsGroup.firstChild);
|
||||
while (xAxisEl.firstChild) xAxisEl.removeChild(xAxisEl.firstChild);
|
||||
patchAttr(modelLegendEl, 'hidden', true);
|
||||
patchAttr(peakPill, 'hidden', true);
|
||||
@@ -1126,7 +1145,7 @@ export function createSessionLineChart() {
|
||||
} else if (metric === 'ttft') {
|
||||
valid = !st.isCompactionStep && Number.isFinite(st.ttftSec) && st.ttftSec >= 0;
|
||||
value = valid ? Number(st.ttftSec) : 0;
|
||||
secondaryRight = Number.isFinite(st.tokPerSec) ? `${st.tokPerSec.toFixed(1)} tok/s` : '';
|
||||
secondaryRight = Number.isFinite(st.tokPerSec) ? formatSpeedMetric(st.tokPerSec, ' tok/s') : '';
|
||||
subDetail = valid
|
||||
? t('chart.step.ctxAndCache', {
|
||||
ctxTok: formatTokens(ctxTok),
|
||||
@@ -1165,6 +1184,7 @@ export function createSessionLineChart() {
|
||||
}
|
||||
|
||||
const dotColor = modelColorMap.get(gk) || accentColor;
|
||||
const anomalySummary = formatStepAnomalyInlineSummary(st.anomaly);
|
||||
return {
|
||||
idx,
|
||||
st,
|
||||
@@ -1177,6 +1197,8 @@ export function createSessionLineChart() {
|
||||
value,
|
||||
secondaryRight,
|
||||
subDetail,
|
||||
anomalySummary,
|
||||
anomalySeverity: st.anomaly?.severity || '',
|
||||
};
|
||||
});
|
||||
|
||||
@@ -1212,7 +1234,10 @@ export function createSessionLineChart() {
|
||||
const sig =
|
||||
`${locale}|${viewW}|${metric}|${showAgentPrefix}|${isMultiCompare ? 'multi' : 'single'}:${targetKeys.join(',')}|${colorSig}|` +
|
||||
points
|
||||
.map((p) => `${p.stepTag}:${p.modelText}:${p.valid ? p.value.toFixed(4) : 'x'}`)
|
||||
.map(
|
||||
(p) =>
|
||||
`${p.stepTag}:${p.modelText}:${p.valid ? p.value.toFixed(4) : 'x'}:${p.st?.anomalySig || ''}`
|
||||
)
|
||||
.join('|');
|
||||
|
||||
if (sig !== lastSig) {
|
||||
@@ -1220,6 +1245,7 @@ export function createSessionLineChart() {
|
||||
while (multiAreaGroup.firstChild) multiAreaGroup.removeChild(multiAreaGroup.firstChild);
|
||||
while (multiLineGroup.firstChild) multiLineGroup.removeChild(multiLineGroup.firstChild);
|
||||
while (dotsGroup.firstChild) dotsGroup.removeChild(dotsGroup.firstChild);
|
||||
while (anomalyDotsGroup.firstChild) anomalyDotsGroup.removeChild(anomalyDotsGroup.firstChild);
|
||||
|
||||
if (isMultiCompare) {
|
||||
patchAttr(linePath, 'd', '');
|
||||
@@ -1315,6 +1341,19 @@ export function createSessionLineChart() {
|
||||
}
|
||||
}
|
||||
|
||||
for (const pt of points) {
|
||||
if (!pt.valid || !pt.anomalySummary) continue;
|
||||
const aDot = document.createElementNS(SVG_NS, 'circle');
|
||||
aDot.setAttribute('cx', pt.x.toFixed(1));
|
||||
aDot.setAttribute('cy', pt.y.toFixed(1));
|
||||
aDot.setAttribute('r', '2.9');
|
||||
aDot.setAttribute(
|
||||
'class',
|
||||
`sstep-anomaly-dot${pt.anomalySeverity === 'danger' ? ' is-danger' : ''}`
|
||||
);
|
||||
anomalyDotsGroup.appendChild(aDot);
|
||||
}
|
||||
|
||||
const tickIndices = computeStepTickIndices(points.length);
|
||||
while (xAxisEl.firstChild) xAxisEl.removeChild(xAxisEl.firstChild);
|
||||
tickElsByIdx = new Map();
|
||||
@@ -1542,10 +1581,12 @@ export function createModelFitChart() {
|
||||
const tipMainLeft = h('strong', { className: 'trend-tip-tokens text-mono' });
|
||||
const tipMainRight = h('span', { className: 'trend-tip-cost text-mono' });
|
||||
const tipSub = h('div', { className: 'trend-tip-sub text-mono', hidden: true });
|
||||
const tipAnomaly = h('div', { className: 'trend-tip-anomaly text-mono', hidden: true });
|
||||
const tooltipEl = h('div', { className: 'trend-tooltip', hidden: true }, [
|
||||
h('div', { className: 'trend-tip-head' }, [tipHeadLeft, tipHeadRight]),
|
||||
h('div', { className: 'trend-tip-main' }, [tipMainLeft, tipMainRight]),
|
||||
tipSub,
|
||||
tipAnomaly,
|
||||
]);
|
||||
|
||||
const fitMethodLabelEl = h('span', { text: t('chart.fit.loess') });
|
||||
@@ -1636,6 +1677,10 @@ export function createModelFitChart() {
|
||||
patchAttr(hoverRawDot, 'hidden', false);
|
||||
patchAttr(hoverRawDot, 'cx', sp.x.toFixed(1));
|
||||
patchAttr(hoverRawDot, 'cy', sp.rawY.toFixed(1));
|
||||
patchClasses(hoverRawDot, {
|
||||
'is-anomaly': Boolean(sp.anomalySummary),
|
||||
'is-danger': Boolean(sp.anomalySummary && sp.anomalySeverity === 'danger'),
|
||||
});
|
||||
|
||||
const wasHidden = tooltipEl.hasAttribute('hidden');
|
||||
patchAttr(tooltipEl, 'hidden', false);
|
||||
@@ -1668,6 +1713,11 @@ export function createModelFitChart() {
|
||||
})
|
||||
);
|
||||
}
|
||||
patchAttr(tipAnomaly, 'hidden', !sp.anomalySummary);
|
||||
if (sp.anomalySummary) {
|
||||
patchText(tipAnomaly, sp.anomalySummary);
|
||||
patchClasses(tipAnomaly, { 'is-danger': sp.anomalySeverity === 'danger' });
|
||||
}
|
||||
|
||||
const rawPct = (sp.x / viewW) * 100;
|
||||
const clampedPct = Math.max(1, Math.min(99, rawPct));
|
||||
@@ -1952,6 +2002,8 @@ export function createModelFitChart() {
|
||||
rawVal,
|
||||
stepTag: formatStepAxisTag(st, showAgentPrefix),
|
||||
modelText: disp.baseText || disp.text,
|
||||
anomalySummary: formatStepAnomalyInlineSummary(st.anomaly),
|
||||
anomalySeverity: st.anomaly?.severity || '',
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -2105,7 +2157,12 @@ export function createModelFitChart() {
|
||||
.map(
|
||||
(s) =>
|
||||
`${s.key}:${s.colorVar}:` +
|
||||
s.samples.map((p) => `${p.xVal}:${p.rawVal.toFixed(3)}:${p.fitVal.toFixed(3)}`).join(',')
|
||||
s.samples
|
||||
.map(
|
||||
(p) =>
|
||||
`${p.xVal}:${p.rawVal.toFixed(3)}:${p.fitVal.toFixed(3)}:${p.st?.anomalySig || ''}`
|
||||
)
|
||||
.join(',')
|
||||
)
|
||||
.join('||');
|
||||
|
||||
@@ -2134,10 +2191,15 @@ export function createModelFitChart() {
|
||||
typeof document.createDocumentFragment === 'function'
|
||||
? document.createDocumentFragment()
|
||||
: scatterGroup;
|
||||
const anomalyOverlayDots = [];
|
||||
|
||||
for (const s of seriesList) {
|
||||
const binCounts = dedupOverdraw ? new Map() : null;
|
||||
for (const sp of s.samples) {
|
||||
if (sp.anomalySummary) {
|
||||
anomalyOverlayDots.push(sp);
|
||||
continue;
|
||||
}
|
||||
if (binCounts) {
|
||||
const binKey = (Math.round(sp.x * 2) << 11) ^ Math.round(sp.rawY * 2);
|
||||
const prevCnt = binCounts.get(binKey) || 0;
|
||||
@@ -2200,6 +2262,17 @@ export function createModelFitChart() {
|
||||
multiCurveGroup.appendChild(curveEl);
|
||||
}
|
||||
}
|
||||
for (const sp of anomalyOverlayDots) {
|
||||
const aDot = document.createElementNS(SVG_NS, 'circle');
|
||||
aDot.setAttribute('cx', sp.x.toFixed(1));
|
||||
aDot.setAttribute('cy', sp.rawY.toFixed(1));
|
||||
aDot.setAttribute('r', '2.9');
|
||||
aDot.setAttribute(
|
||||
'class',
|
||||
`sstep-scatter-dot is-anomaly${sp.anomalySeverity === 'danger' ? ' is-danger' : ''}`
|
||||
);
|
||||
scatterTarget.appendChild(aDot);
|
||||
}
|
||||
if (scatterTarget !== scatterGroup) {
|
||||
scatterGroup.appendChild(scatterTarget);
|
||||
}
|
||||
@@ -2316,7 +2389,11 @@ export function createModelFitChart() {
|
||||
|
||||
const sig =
|
||||
`single|${locale}|${viewW}|${targetKeys[0]}|${metric}|${showAgentPrefix}|${yScale.min.toFixed(4)}|${yScale.max.toFixed(4)}|` +
|
||||
samples.map((s) => `${s.xVal}:${s.rawVal.toFixed(4)}:${s.fitVal.toFixed(4)}`).join('|');
|
||||
samples
|
||||
.map(
|
||||
(s) => `${s.xVal}:${s.rawVal.toFixed(4)}:${s.fitVal.toFixed(4)}:${s.st?.anomalySig || ''}`
|
||||
)
|
||||
.join('|');
|
||||
|
||||
if (sig !== lastSig) {
|
||||
lastSig = sig;
|
||||
@@ -2340,7 +2417,12 @@ export function createModelFitChart() {
|
||||
typeof document.createDocumentFragment === 'function'
|
||||
? document.createDocumentFragment()
|
||||
: scatterGroup;
|
||||
const singleAnomalyDots = [];
|
||||
for (const s of samples) {
|
||||
if (s.anomalySummary) {
|
||||
singleAnomalyDots.push(s);
|
||||
continue;
|
||||
}
|
||||
if (binCounts) {
|
||||
const binKey = (Math.round(s.x * 2) << 11) ^ Math.round(s.rawY * 2);
|
||||
const prevCnt = binCounts.get(binKey) || 0;
|
||||
@@ -2354,6 +2436,17 @@ export function createModelFitChart() {
|
||||
dot.setAttribute('class', 'sstep-scatter-dot');
|
||||
scatterTarget.appendChild(dot);
|
||||
}
|
||||
for (const s of singleAnomalyDots) {
|
||||
const aDot = document.createElementNS(SVG_NS, 'circle');
|
||||
aDot.setAttribute('cx', s.x.toFixed(1));
|
||||
aDot.setAttribute('cy', s.rawY.toFixed(1));
|
||||
aDot.setAttribute('r', '2.9');
|
||||
aDot.setAttribute(
|
||||
'class',
|
||||
`sstep-scatter-dot is-anomaly${s.anomalySeverity === 'danger' ? ' is-danger' : ''}`
|
||||
);
|
||||
scatterTarget.appendChild(aDot);
|
||||
}
|
||||
if (scatterTarget !== scatterGroup) {
|
||||
scatterGroup.appendChild(scatterTarget);
|
||||
}
|
||||
|
||||
@@ -13,7 +13,11 @@ import {
|
||||
patchKeyedList,
|
||||
patchText,
|
||||
} from '../../core/domPatch.js';
|
||||
import { resolveModelDisplayInfo, speedReasonText } from '../../core/formatters.js';
|
||||
import {
|
||||
buildStepAnomalyDiagnostic,
|
||||
resolveModelDisplayInfo,
|
||||
speedReasonText,
|
||||
} from '../../core/formatters.js';
|
||||
import { getEffectiveLocale, t } from '../../i18n/index.js';
|
||||
import {
|
||||
DEFAULT_STEP_COLUMN_KEYS,
|
||||
@@ -198,9 +202,14 @@ function buildColumnSizerSpec(tableSteps, colKeys, wantedSet, cellCtx) {
|
||||
|
||||
if (needTps) {
|
||||
const tpsVal = Number(st.tokPerSec);
|
||||
if (Number.isFinite(tpsVal) && tpsVal > maxTpsVal) {
|
||||
maxTpsVal = tpsVal;
|
||||
maxTpsObj = st;
|
||||
if (Number.isFinite(tpsVal) && tpsVal >= 0) {
|
||||
const tpsScore =
|
||||
(tpsVal >= 100 ? String(Math.round(tpsVal)).length : tpsVal.toFixed(1).length) * 1e6 +
|
||||
tpsVal;
|
||||
if (tpsScore > maxTpsVal) {
|
||||
maxTpsVal = tpsScore;
|
||||
maxTpsObj = st;
|
||||
}
|
||||
}
|
||||
if (st.selectedSpeedReason) {
|
||||
reasonCandidates.add(st.selectedSpeedReason);
|
||||
@@ -415,8 +424,31 @@ export const StepTableWidget = defineComponent({
|
||||
});
|
||||
const hideTurnTip = () => patchAttr(turnTipEl, 'hidden', true);
|
||||
|
||||
const anomalyTipTitleEl = h('div', { className: 'step-anomaly-tip-title' });
|
||||
const anomalyTipSubEl = h('div', { className: 'step-anomaly-tip-sub text-mono', hidden: true });
|
||||
const anomalyTipHeadEl = h('div', { className: 'step-anomaly-tip-head' }, [
|
||||
anomalyTipTitleEl,
|
||||
anomalyTipSubEl,
|
||||
]);
|
||||
const anomalyTipListEl = h('div', { className: 'step-anomaly-tip-list' });
|
||||
const anomalyTipHintEl = h('div', { className: 'step-anomaly-tip-hint', hidden: true });
|
||||
const anomalyTipEl = h(
|
||||
'div',
|
||||
{
|
||||
className: 'step-anomaly-tip',
|
||||
role: 'tooltip',
|
||||
hidden: true,
|
||||
},
|
||||
[anomalyTipHeadEl, anomalyTipListEl, anomalyTipHintEl]
|
||||
);
|
||||
const hideAnomalyTip = () => patchAttr(anomalyTipEl, 'hidden', true);
|
||||
|
||||
const standaloneHostEl = standalone
|
||||
? h('div', { className: 'step-table-preview-host' }, [stepsTablePane, turnTipEl])
|
||||
? h('div', { className: 'step-table-preview-host' }, [
|
||||
stepsTablePane,
|
||||
turnTipEl,
|
||||
anomalyTipEl,
|
||||
])
|
||||
: null;
|
||||
|
||||
let boundsContainerGetter =
|
||||
@@ -430,40 +462,85 @@ export const StepTableWidget = defineComponent({
|
||||
}
|
||||
}
|
||||
|
||||
function positionFloatingTip(tipEl, anchorEl) {
|
||||
const boundsEl = boundsContainerGetter?.();
|
||||
if (
|
||||
!boundsEl ||
|
||||
typeof boundsEl.getBoundingClientRect !== 'function' ||
|
||||
typeof anchorEl?.getBoundingClientRect !== 'function'
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const panelRect = boundsEl.getBoundingClientRect();
|
||||
const anchorRect = anchorEl.getBoundingClientRect();
|
||||
if (!(panelRect.width > 0 && panelRect.height > 0)) return;
|
||||
const tipH = tipEl.offsetHeight || 56;
|
||||
const tipW = tipEl.offsetWidth || 220;
|
||||
const placeAbove =
|
||||
panelRect.bottom - anchorRect.bottom < tipH + 10 &&
|
||||
anchorRect.top - panelRect.top > tipH + 6;
|
||||
const topPx = placeAbove
|
||||
? Math.max(4, Math.round(anchorRect.top - panelRect.top - tipH - 5))
|
||||
: Math.round(anchorRect.bottom - panelRect.top + 5);
|
||||
const maxLeft = Math.max(6, Math.round(panelRect.width - tipW - 8));
|
||||
const leftPx = Math.min(
|
||||
maxLeft,
|
||||
Math.max(6, Math.round(anchorRect.left - panelRect.left))
|
||||
);
|
||||
tipEl.style.top = `${topPx}px`;
|
||||
tipEl.style.left = `${leftPx}px`;
|
||||
}
|
||||
|
||||
function showTurnTip(anchorCell, promptText) {
|
||||
const text = String(promptText || '').trim();
|
||||
const boundsEl = boundsContainerGetter?.();
|
||||
if (!anchorCell || !text) {
|
||||
hideTurnTip();
|
||||
return;
|
||||
}
|
||||
hideAnomalyTip();
|
||||
patchText(turnTipEl, text);
|
||||
patchAttr(turnTipEl, 'hidden', false);
|
||||
if (
|
||||
boundsEl &&
|
||||
typeof boundsEl.getBoundingClientRect === 'function' &&
|
||||
typeof anchorCell.getBoundingClientRect === 'function'
|
||||
) {
|
||||
const panelRect = boundsEl.getBoundingClientRect();
|
||||
const cellRect = anchorCell.getBoundingClientRect();
|
||||
if (panelRect.width > 0 && panelRect.height > 0) {
|
||||
const tipH = turnTipEl.offsetHeight || 36;
|
||||
const tipW = turnTipEl.offsetWidth || 180;
|
||||
const placeAbove =
|
||||
panelRect.bottom - cellRect.bottom < tipH + 10 &&
|
||||
cellRect.top - panelRect.top > tipH + 6;
|
||||
const topPx = placeAbove
|
||||
? Math.max(4, Math.round(cellRect.top - panelRect.top - tipH - 4))
|
||||
: Math.round(cellRect.bottom - panelRect.top + 4);
|
||||
const maxLeft = Math.max(6, Math.round(panelRect.width - tipW - 8));
|
||||
const leftPx = Math.min(
|
||||
maxLeft,
|
||||
Math.max(6, Math.round(cellRect.left - panelRect.left + 4))
|
||||
);
|
||||
turnTipEl.style.top = `${topPx}px`;
|
||||
turnTipEl.style.left = `${leftPx}px`;
|
||||
}
|
||||
positionFloatingTip(turnTipEl, anchorCell);
|
||||
}
|
||||
|
||||
function showAnomalyTip(anchorEl, diag) {
|
||||
if (!anchorEl || !diag || !diag.title) {
|
||||
hideAnomalyTip();
|
||||
return;
|
||||
}
|
||||
hideTurnTip();
|
||||
patchClasses(anomalyTipEl, { 'is-danger': diag.severity === 'danger' });
|
||||
patchText(anomalyTipTitleEl, diag.title);
|
||||
patchAttr(anomalyTipSubEl, 'hidden', !diag.sub);
|
||||
if (diag.sub) patchText(anomalyTipSubEl, diag.sub);
|
||||
|
||||
while (anomalyTipListEl.firstChild) {
|
||||
anomalyTipListEl.removeChild(anomalyTipListEl.firstChild);
|
||||
}
|
||||
const rows = Array.isArray(diag.rows) ? diag.rows : [];
|
||||
for (const row of rows) {
|
||||
const lineEl = h('div', {
|
||||
className: `step-anomaly-tip-row${row.danger ? ' is-danger' : ''}`,
|
||||
text: row.text,
|
||||
});
|
||||
const itemChildren = [lineEl];
|
||||
if (row.detail) {
|
||||
itemChildren.push(
|
||||
h('div', {
|
||||
className: 'step-anomaly-tip-detail text-mono',
|
||||
text: row.detail,
|
||||
})
|
||||
);
|
||||
}
|
||||
anomalyTipListEl.appendChild(h('div', { className: 'step-anomaly-tip-item' }, itemChildren));
|
||||
}
|
||||
patchAttr(anomalyTipListEl, 'hidden', rows.length === 0);
|
||||
|
||||
patchAttr(anomalyTipHintEl, 'hidden', !diag.hint);
|
||||
if (diag.hint) patchText(anomalyTipHintEl, diag.hint);
|
||||
|
||||
patchAttr(anomalyTipEl, 'hidden', false);
|
||||
positionFloatingTip(anomalyTipEl, anchorEl);
|
||||
}
|
||||
|
||||
const hoverRows = new WeakMap();
|
||||
@@ -598,15 +675,30 @@ export const StepTableWidget = defineComponent({
|
||||
}
|
||||
|
||||
function moveInStepCell(event) {
|
||||
if (event?.target === hoverRows.get(this).badge) hideTurnTip();
|
||||
const { badge } = hoverRows.get(this);
|
||||
if (event?.target === badge) hideTurnTip();
|
||||
}
|
||||
|
||||
function moveAlongTurnRail(event) {
|
||||
const { badge, prompt } = hoverRows.get(this);
|
||||
const { badge, prompt, anomalyStep } = 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();
|
||||
if (event?.target !== badge && relX <= 18) {
|
||||
showTurnTip(this, prompt);
|
||||
} else {
|
||||
hideTurnTip();
|
||||
if (anomalyStep) {
|
||||
showAnomalyTip(this, buildStepAnomalyDiagnostic(anomalyStep));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function leaveStepCell(event) {
|
||||
const entry = hoverRows.get(this);
|
||||
hideTurnTip();
|
||||
if (entry?.anomalyStep && entry.tr && event?.relatedTarget && entry.tr.contains?.(event.relatedTarget)) {
|
||||
showAnomalyTip(this, buildStepAnomalyDiagnostic(entry.anomalyStep));
|
||||
}
|
||||
}
|
||||
|
||||
function clearCellHover(cell) {
|
||||
@@ -898,7 +990,8 @@ export const StepTableWidget = defineComponent({
|
||||
? `${cellCtx.scopeSigKey}:${st.agentId || 'main'}:${st.agentBadge || ''}:${st.agentLabel || ''}`
|
||||
: '';
|
||||
const stripeSig = isVirtualized ? (item.isStripeEven ? 'E' : 'O') : 'N';
|
||||
return `${locale}:${colOrderSig}:${stripeSig}:${badgeSig}:${railActive}:${item.hasTurn}:${item.hasUp}:${item.hasDown}:${item.isStart}:${item.isLatest}:${item.prompt}:${parts}`;
|
||||
const anomalySig = st.anomalySig || '';
|
||||
return `${locale}:${colOrderSig}:${stripeSig}:${badgeSig}:${anomalySig}:${railActive}:${item.hasTurn}:${item.hasUp}:${item.hasDown}:${item.isStart}:${item.isLatest}:${item.prompt}:${parts}`;
|
||||
},
|
||||
createRow: (item) => {
|
||||
if (item.isSizer) {
|
||||
@@ -1140,6 +1233,24 @@ export const StepTableWidget = defineComponent({
|
||||
refs.agentBadgeEl.onclick = null;
|
||||
}
|
||||
|
||||
const hasStepAnomaly = Boolean(st?.anomaly && Number(st.anomaly.count) > 0);
|
||||
const isAnomalyDanger = Boolean(hasStepAnomaly && st.anomaly.severity === 'danger');
|
||||
const isAnomalyWarn = Boolean(hasStepAnomaly && !isAnomalyDanger);
|
||||
patchClasses(tr, {
|
||||
'is-anomaly-warn': isAnomalyWarn,
|
||||
'is-anomaly-danger': isAnomalyDanger,
|
||||
});
|
||||
if (hasStepAnomaly) {
|
||||
const anchorEl = firstTd || tr;
|
||||
tr.onmouseenter = () => {
|
||||
showAnomalyTip(anchorEl, buildStepAnomalyDiagnostic(st));
|
||||
};
|
||||
tr.onmouseleave = hideAnomalyTip;
|
||||
} else {
|
||||
tr.onmouseenter = null;
|
||||
tr.onmouseleave = null;
|
||||
}
|
||||
|
||||
patchAttr(refs.railEl, 'hidden', !showRowRail);
|
||||
if (showRowRail) {
|
||||
const marker = isStart ? ' is-origin' : !hasUp && hasDown ? ' is-cap' : '';
|
||||
@@ -1154,10 +1265,16 @@ export const StepTableWidget = defineComponent({
|
||||
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;
|
||||
hoverRows.set(hoverTd, {
|
||||
badge: refs.agentBadgeEl,
|
||||
prompt,
|
||||
anomalyStep: hasStepAnomaly ? st : null,
|
||||
tr,
|
||||
});
|
||||
const useWholeCellTurnTip = firstColKey === 'step' && !hasStepAnomaly;
|
||||
hoverTd.onmouseenter = useWholeCellTurnTip ? enterStepCell : null;
|
||||
hoverTd.onmousemove = useWholeCellTurnTip ? moveInStepCell : moveAlongTurnRail;
|
||||
hoverTd.onmouseleave = leaveStepCell;
|
||||
}
|
||||
|
||||
if (enteringRowKeys?.has(item.rowKey)) {
|
||||
@@ -1179,7 +1296,14 @@ export const StepTableWidget = defineComponent({
|
||||
}
|
||||
clearRowEnterState(tr);
|
||||
if (!refs?.isSpacer && !refs?.isSizer && tr) {
|
||||
patchClasses(tr, { 'is-stripe-even': false, 'is-step-entering': false });
|
||||
patchClasses(tr, {
|
||||
'is-stripe-even': false,
|
||||
'is-step-entering': false,
|
||||
'is-anomaly-warn': false,
|
||||
'is-anomaly-danger': false,
|
||||
});
|
||||
tr.onmouseenter = null;
|
||||
tr.onmouseleave = null;
|
||||
if (refs.agentBadgeEl) {
|
||||
refs.agentBadgeEl.onclick = null;
|
||||
}
|
||||
@@ -1209,6 +1333,7 @@ export const StepTableWidget = defineComponent({
|
||||
|
||||
function onPaneScroll() {
|
||||
hideTurnTip();
|
||||
hideAnomalyTip();
|
||||
if (!activeDataset?.isVirtualized) return;
|
||||
if (typeof requestAnimationFrame === 'function') {
|
||||
if (scrollRafId) return;
|
||||
@@ -1221,8 +1346,13 @@ export const StepTableWidget = defineComponent({
|
||||
}
|
||||
}
|
||||
|
||||
function onTbodyLeave() {
|
||||
hideTurnTip();
|
||||
hideAnomalyTip();
|
||||
}
|
||||
|
||||
stepsTablePane.addEventListener('scroll', onPaneScroll, { passive: true });
|
||||
stepsTbody.addEventListener('mouseleave', hideTurnTip);
|
||||
stepsTbody.addEventListener('mouseleave', onTbodyLeave);
|
||||
|
||||
let paneResizeObs = null;
|
||||
if (typeof ResizeObserver === 'function') {
|
||||
@@ -1424,7 +1554,7 @@ export const StepTableWidget = defineComponent({
|
||||
|
||||
onCleanup(() => {
|
||||
stepsTablePane.removeEventListener('scroll', onPaneScroll);
|
||||
stepsTbody.removeEventListener('mouseleave', hideTurnTip);
|
||||
stepsTbody.removeEventListener('mouseleave', onTbodyLeave);
|
||||
if (scrollRafId && typeof cancelAnimationFrame === 'function') {
|
||||
cancelAnimationFrame(scrollRafId);
|
||||
scrollRafId = 0;
|
||||
@@ -1449,10 +1579,13 @@ export const StepTableWidget = defineComponent({
|
||||
stepsTheadRow,
|
||||
stepsTbody,
|
||||
turnTipEl,
|
||||
anomalyTipEl,
|
||||
syncTableHeaderColumns,
|
||||
renderStepTable,
|
||||
refreshViewport,
|
||||
hideTurnTip,
|
||||
showAnomalyTip,
|
||||
hideAnomalyTip,
|
||||
setBoundsElGetter,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -25,6 +25,12 @@ export function formatMetric(value, unit = '') {
|
||||
return Number.isFinite(value) ? `${value.toFixed(1)}${unit}` : '—';
|
||||
}
|
||||
|
||||
export function formatSpeedMetric(value, unit = ' tok/s') {
|
||||
if (!Number.isFinite(value)) return '—';
|
||||
const numStr = value >= 100 ? String(Math.round(value)) : value.toFixed(1);
|
||||
return `${numStr}${unit}`;
|
||||
}
|
||||
|
||||
export function formatCachePct(value) {
|
||||
if (value == null || !Number.isFinite(Number(value))) return '—';
|
||||
const num = Math.max(0, Math.min(100, +Number(value).toFixed(1)));
|
||||
@@ -98,6 +104,8 @@ const SPEED_REASON_LABELS = {
|
||||
__proto__: null,
|
||||
incomplete_or_invalid_timing: 'fmt.speedIncomplete',
|
||||
canceled: 'fmt.speedCanceled',
|
||||
error: 'fmt.speedError',
|
||||
interrupted: 'fmt.speedInterrupted',
|
||||
compaction_timing_unavailable: 'fmt.speedCompactionTimingUnavailable',
|
||||
invalid_output_tokens: 'fmt.speedInvalidOutput',
|
||||
inconsistent_timing: 'fmt.speedInconsistent',
|
||||
@@ -110,6 +118,135 @@ export function speedReasonText(reason) {
|
||||
return label ? t(label) : '';
|
||||
}
|
||||
|
||||
const ANOMALY_KIND_ORDER = Object.freeze([
|
||||
'rate_limit',
|
||||
'timeout',
|
||||
'capacity',
|
||||
'disconnect',
|
||||
'upstream',
|
||||
'model_output',
|
||||
'safety',
|
||||
'auth_or_model',
|
||||
'error',
|
||||
]);
|
||||
|
||||
export function formatAnomalyKindLabel(kind) {
|
||||
const k = String(kind || 'error');
|
||||
const key = `steps.anomalyKind.${k}`;
|
||||
const text = t(key);
|
||||
return text === key ? t('steps.anomalyKind.error') : text;
|
||||
}
|
||||
|
||||
export function formatAnomalyTagText(primaryKind, count = 1) {
|
||||
const n = Math.max(1, Math.floor(Number(count) || 1));
|
||||
const k = String(primaryKind || 'error');
|
||||
if (k === 'capacity' && n === 1) return t('steps.anomalyTag.capacitySingle');
|
||||
if (k === 'upstream' && n === 1) return t('steps.anomalyTag.upstreamSingle');
|
||||
const key = `steps.anomalyTag.${k}`;
|
||||
const formatted = t(key, { n });
|
||||
return formatted === key ? t('steps.anomalyTag.error', { n }) : formatted;
|
||||
}
|
||||
|
||||
export function resolveModelAnomalySummary(m) {
|
||||
const count = Math.max(0, Number(m?.anomalyCount || 0));
|
||||
const steps = Math.max(0, Number(m?.anomalySteps || 0));
|
||||
if (count <= 0 && steps <= 0) return null;
|
||||
const byKind = m?.anomalyByKind && typeof m.anomalyByKind === 'object' ? m.anomalyByKind : {};
|
||||
const entries = Object.entries(byKind)
|
||||
.map(([k, v]) => [k, Math.max(0, Number(v || 0))])
|
||||
.filter(([, v]) => v > 0)
|
||||
.sort((a, b) => {
|
||||
if (b[1] !== a[1]) return b[1] - a[1];
|
||||
const pa = ANOMALY_KIND_ORDER.indexOf(a[0]);
|
||||
const pb = ANOMALY_KIND_ORDER.indexOf(b[0]);
|
||||
return (pa < 0 ? 99 : pa) - (pb < 0 ? 99 : pb);
|
||||
});
|
||||
const totalCount = count || entries.reduce((sum, [, v]) => sum + v, 0) || steps;
|
||||
const primaryKind = entries.length === 1 ? entries[0][0] : entries.length > 1 ? 'mixed' : 'error';
|
||||
const severity =
|
||||
Number(m?.anomalyDangerCount || 0) > 0 ||
|
||||
entries.some(([k]) => k === 'rate_limit' || k === 'auth_or_model')
|
||||
? 'danger'
|
||||
: 'warn';
|
||||
return {
|
||||
count: totalCount,
|
||||
steps: steps || totalCount,
|
||||
totalDelaySec: Math.max(0, Number(m?.anomalyTotalDelaySec || 0)),
|
||||
primaryKind,
|
||||
severity,
|
||||
entries,
|
||||
tagText: formatAnomalyTagText(primaryKind, totalCount),
|
||||
};
|
||||
}
|
||||
|
||||
export function formatStepAnomalyInlineSummary(anomaly) {
|
||||
if (!anomaly || !(Number(anomaly.count) > 0)) return '';
|
||||
const tag = formatAnomalyTagText(anomaly.primaryKind, anomaly.count);
|
||||
const label = formatAnomalyKindLabel(anomaly.primaryKind);
|
||||
const delaySec = Number(anomaly.totalDelaySec || 0);
|
||||
const delayPart = delaySec > 0 ? ` · ${t('steps.anomalyDelayPart', { sec: delaySec })}` : '';
|
||||
return `${tag} · ${label}${delayPart}`;
|
||||
}
|
||||
|
||||
export function buildStepAnomalyDiagnostic(st) {
|
||||
const a = st?.anomaly;
|
||||
if (!a || !(Number(a.count) > 0)) return null;
|
||||
const title = t('steps.anomalyStepTitle', {
|
||||
step: Number(st.stepIndex ?? 0),
|
||||
count: Number(a.count),
|
||||
});
|
||||
const delaySec = Number(a.totalDelaySec || 0);
|
||||
const sub = delaySec > 0 ? t('steps.anomalyDelayPart', { sec: delaySec }) : '';
|
||||
const events = Array.isArray(a.events) ? a.events : [];
|
||||
const rows = events.map((ev, idx) => {
|
||||
const label = formatAnomalyKindLabel(ev.kind);
|
||||
const parts = [`#${ev.attempt || idx + 1} ${label}`];
|
||||
if (Number(ev.delaySec) > 0) {
|
||||
parts.push(t('steps.anomalyDelayPart', { sec: ev.delaySec }));
|
||||
}
|
||||
if (ev.terminal) {
|
||||
parts.push(t('steps.anomalyTerminalTag'));
|
||||
}
|
||||
return {
|
||||
text: parts.join(' · '),
|
||||
detail: ev.message || '',
|
||||
danger: Boolean(ev.terminal || ev.kind === 'rate_limit' || ev.kind === 'auth_or_model'),
|
||||
};
|
||||
});
|
||||
return {
|
||||
title,
|
||||
sub,
|
||||
rows,
|
||||
hint: '',
|
||||
severity: a.severity === 'danger' ? 'danger' : 'warn',
|
||||
};
|
||||
}
|
||||
|
||||
export function buildModelAnomalyDiagnostic(m) {
|
||||
const sum = resolveModelAnomalySummary(m);
|
||||
if (!sum) return null;
|
||||
const title = t('steps.anomalyModelTitle', {
|
||||
model: m?.displayText || m?.shortName || m?.label || '—',
|
||||
count: sum.count,
|
||||
});
|
||||
const subParts = [t('steps.anomalyModelSub', { steps: sum.steps })];
|
||||
if (sum.totalDelaySec > 0) {
|
||||
subParts.push(t('steps.anomalyDelayPart', { sec: sum.totalDelaySec }));
|
||||
}
|
||||
const rows = sum.entries.map(([k, v]) => ({
|
||||
text: t('steps.anomalyModelKindRow', { kind: formatAnomalyKindLabel(k), count: v }),
|
||||
detail: '',
|
||||
danger: k === 'rate_limit' || k === 'auth_or_model',
|
||||
}));
|
||||
return {
|
||||
title,
|
||||
sub: subParts.join(' · '),
|
||||
rows,
|
||||
hint: t('steps.anomalyModelClickHint'),
|
||||
severity: sum.severity,
|
||||
};
|
||||
}
|
||||
|
||||
export function sampleSummary(summary) {
|
||||
const valid = summary?.sampleCount || 0;
|
||||
const excluded = summary?.excludedCount || 0;
|
||||
@@ -389,6 +526,12 @@ export function mergeModelsByDisplayName(models = [], settings = {}, options = {
|
||||
ttftWeightedSum: hasTtft ? Number(m.avgTtftSec) * ttftWeight : 0,
|
||||
ttftWeight: hasTtft ? ttftWeight : 0,
|
||||
ttftSampleCount,
|
||||
anomalySteps: Math.max(0, Number(m.anomalySteps || 0)),
|
||||
anomalyCount: Math.max(0, Number(m.anomalyCount || 0)),
|
||||
anomalyDangerCount: Math.max(0, Number(m.anomalyDangerCount || 0)),
|
||||
anomalyTotalDelaySec: Math.max(0, Number(m.anomalyTotalDelaySec || 0)),
|
||||
anomalyByKind:
|
||||
m.anomalyByKind && typeof m.anomalyByKind === 'object' ? { ...m.anomalyByKind } : {},
|
||||
};
|
||||
if (m.upstreamName) acc.upstreamSet.add(m.upstreamName);
|
||||
byDisplay.set(key, acc);
|
||||
@@ -417,6 +560,17 @@ export function mergeModelsByDisplayName(models = [], settings = {}, options = {
|
||||
acc.costUsd += costUsd;
|
||||
acc.unpricedCalls += unpricedCalls;
|
||||
|
||||
acc.anomalySteps += Math.max(0, Number(m.anomalySteps || 0));
|
||||
acc.anomalyCount += Math.max(0, Number(m.anomalyCount || 0));
|
||||
acc.anomalyDangerCount += Math.max(0, Number(m.anomalyDangerCount || 0));
|
||||
acc.anomalyTotalDelaySec += Math.max(0, Number(m.anomalyTotalDelaySec || 0));
|
||||
if (m.anomalyByKind && typeof m.anomalyByKind === 'object') {
|
||||
for (const [ak, av] of Object.entries(m.anomalyByKind)) {
|
||||
const cnt = Math.max(0, Number(av || 0));
|
||||
if (cnt > 0) acc.anomalyByKind[ak] = (acc.anomalyByKind[ak] || 0) + cnt;
|
||||
}
|
||||
}
|
||||
|
||||
if (hasSpeed) {
|
||||
acc.speedWeightedSum += Number(m.avgTokPerSec) * speedWeight;
|
||||
acc.speedWeight += speedWeight;
|
||||
@@ -467,6 +621,15 @@ export function mergeModelsByDisplayName(models = [], settings = {}, options = {
|
||||
avgTokPerSec,
|
||||
avgTtftSec,
|
||||
ttftSampleCount: acc.ttftSampleCount,
|
||||
...(acc.anomalyCount > 0
|
||||
? {
|
||||
anomalySteps: acc.anomalySteps,
|
||||
anomalyCount: acc.anomalyCount,
|
||||
anomalyDangerCount: acc.anomalyDangerCount,
|
||||
anomalyTotalDelaySec: +acc.anomalyTotalDelaySec.toFixed(1),
|
||||
anomalyByKind: acc.anomalyByKind,
|
||||
}
|
||||
: {}),
|
||||
speedSummary: acc.baseItem.speedSummary
|
||||
? {
|
||||
...acc.baseItem.speedSummary,
|
||||
|
||||
@@ -37,6 +37,8 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
'fmt.pending': 'N/A',
|
||||
'fmt.speedIncomplete': 'Incomplete timing',
|
||||
'fmt.speedCanceled': 'Canceled',
|
||||
'fmt.speedError': 'Call error',
|
||||
'fmt.speedInterrupted': 'Interrupted',
|
||||
'fmt.speedCompactionTimingUnavailable': 'Untimed compaction',
|
||||
'fmt.speedInvalidOutput': 'No valid output',
|
||||
'fmt.speedInconsistent': 'Invalid timing',
|
||||
@@ -299,6 +301,38 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
'steps.fitInactiveCardTitle': 'Click to inspect {text} in Trend Fit (Ctrl/Shift-click to compare)',
|
||||
'steps.turnMediaOnly': '[Media Attachment]',
|
||||
'steps.turnMediaSuffix': '[Media]',
|
||||
'steps.anomalyTag.timeout': 'TO{n}',
|
||||
'steps.anomalyTag.rate_limit': '429×{n}',
|
||||
'steps.anomalyTag.capacity': '503×{n}',
|
||||
'steps.anomalyTag.capacitySingle': '503',
|
||||
'steps.anomalyTag.disconnect': 'Drop{n}',
|
||||
'steps.anomalyTag.upstream': '500×{n}',
|
||||
'steps.anomalyTag.upstreamSingle': '500',
|
||||
'steps.anomalyTag.model_output': 'Fix{n}',
|
||||
'steps.anomalyTag.safety': 'Safe{n}',
|
||||
'steps.anomalyTag.auth_or_model': 'Err{n}',
|
||||
'steps.anomalyTag.error': 'Err{n}',
|
||||
'steps.anomalyTag.mixed': 'Warn{n}',
|
||||
'steps.anomalyKind.timeout': 'Stream Idle / Connect Timeout',
|
||||
'steps.anomalyKind.rate_limit': '429 Rate Limit / Quota Reached',
|
||||
'steps.anomalyKind.capacity': '503 No Capacity Available',
|
||||
'steps.anomalyKind.disconnect': 'Connection Reset / Stream Interrupted',
|
||||
'steps.anomalyKind.upstream': 'Upstream 5xx Internal Error',
|
||||
'steps.anomalyKind.model_output': 'Invalid Model Output / Tool Call',
|
||||
'steps.anomalyKind.safety': 'Content Safety Filter',
|
||||
'steps.anomalyKind.auth_or_model': 'Request / Model Rejected',
|
||||
'steps.anomalyKind.error': 'Call Error',
|
||||
'steps.anomalyKind.canceled': 'Canceled by User',
|
||||
'steps.anomalyStepTitle': '#{step} · {count} Retries / Errors',
|
||||
'steps.anomalyDelayPart': 'Backoff {sec}s',
|
||||
'steps.anomalyTerminalTag': 'Stopped',
|
||||
'steps.anomalyModelTitle': '{model} · {count} Retries / Errors',
|
||||
'steps.anomalyModelSub': '{steps} steps affected',
|
||||
'steps.anomalyModelKindRow': '{kind}: {count}',
|
||||
'steps.anomalyModelClickHint': 'Click to filter anomalous steps',
|
||||
'steps.anomalySummaryMeta': '{count} retries/errors ({steps} steps)',
|
||||
'steps.anomalyFilterLabel': 'Anomalies Only ({count})',
|
||||
'steps.anomalyFilterAll': 'Show All Steps',
|
||||
|
||||
// Step Table Columns (Headers & Option Labels)
|
||||
'stepCol.step.th': 'Step',
|
||||
|
||||
@@ -37,6 +37,8 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
'fmt.pending': '待定',
|
||||
'fmt.speedIncomplete': '计时不完整',
|
||||
'fmt.speedCanceled': '已取消',
|
||||
'fmt.speedError': '调用报错',
|
||||
'fmt.speedInterrupted': '连接中断',
|
||||
'fmt.speedCompactionTimingUnavailable': '压缩无计时',
|
||||
'fmt.speedInvalidOutput': '无有效输出',
|
||||
'fmt.speedInconsistent': '耗时数据异常',
|
||||
@@ -299,6 +301,38 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
'steps.fitInactiveCardTitle': '点击在上方拟合图查看 {text}(按住 Ctrl/Shift 点击可多选同图对比)',
|
||||
'steps.turnMediaOnly': '[图片/附件提问]',
|
||||
'steps.turnMediaSuffix': '[附图]',
|
||||
'steps.anomalyTag.timeout': '超时{n}',
|
||||
'steps.anomalyTag.rate_limit': '限流{n}',
|
||||
'steps.anomalyTag.capacity': '503×{n}',
|
||||
'steps.anomalyTag.capacitySingle': '503',
|
||||
'steps.anomalyTag.disconnect': '断连{n}',
|
||||
'steps.anomalyTag.upstream': '500×{n}',
|
||||
'steps.anomalyTag.upstreamSingle': '500',
|
||||
'steps.anomalyTag.model_output': '纠偏{n}',
|
||||
'steps.anomalyTag.safety': '过滤{n}',
|
||||
'steps.anomalyTag.auth_or_model': '受限{n}',
|
||||
'steps.anomalyTag.error': '报错{n}',
|
||||
'steps.anomalyTag.mixed': '异常{n}',
|
||||
'steps.anomalyKind.timeout': '流空闲 / 连接超时',
|
||||
'steps.anomalyKind.rate_limit': '429 限流 / 配额耗尽',
|
||||
'steps.anomalyKind.capacity': '503 上游算力不足',
|
||||
'steps.anomalyKind.disconnect': '连接中断 / 断流',
|
||||
'steps.anomalyKind.upstream': '上游 5xx 内部错误',
|
||||
'steps.anomalyKind.model_output': '模型输出 / 工具参数无效',
|
||||
'steps.anomalyKind.safety': '内容安全过滤',
|
||||
'steps.anomalyKind.auth_or_model': '请求受限 / 模型不可用',
|
||||
'steps.anomalyKind.error': '调用异常',
|
||||
'steps.anomalyKind.canceled': '用户取消',
|
||||
'steps.anomalyStepTitle': '#{step} · 异常 {count} 次',
|
||||
'steps.anomalyDelayPart': '退避 {sec}s',
|
||||
'steps.anomalyTerminalTag': '中止',
|
||||
'steps.anomalyModelTitle': '{model} · 异常 {count} 次',
|
||||
'steps.anomalyModelSub': '涉及 {steps} 步',
|
||||
'steps.anomalyModelKindRow': '{kind}:{count} 次',
|
||||
'steps.anomalyModelClickHint': '点击前往「按步查看」筛选异常步',
|
||||
'steps.anomalySummaryMeta': '异常 {count} 次({steps} 步)',
|
||||
'steps.anomalyFilterLabel': '仅看异常 ({count})',
|
||||
'steps.anomalyFilterAll': '返回全部步骤',
|
||||
|
||||
// Step Table Columns (Headers & Option Labels)
|
||||
'stepCol.step.th': '步序',
|
||||
|
||||
@@ -9,6 +9,7 @@ import { h, patchAttr, patchText } from '../core/domPatch.js';
|
||||
import {
|
||||
formatCachePct,
|
||||
formatMetric,
|
||||
formatSpeedMetric,
|
||||
formatTokens,
|
||||
formatUsd,
|
||||
getCacheToneClass,
|
||||
@@ -191,7 +192,7 @@ export const STEP_COLUMN_REGISTRY = Object.freeze({
|
||||
return { td, refs: { wrapEl, speedMain, speedReason: null } };
|
||||
},
|
||||
updateCell: (refs, st, ctx) => {
|
||||
patchText(refs.speedMain, formatMetric(st.tokPerSec, ' tok/s'));
|
||||
patchText(refs.speedMain, formatSpeedMetric(st.tokPerSec, ' tok/s'));
|
||||
const hasValidSpeed =
|
||||
st.tokPerSec != null && Number.isFinite(Number(st.tokPerSec)) && Number(st.tokPerSec) > 0;
|
||||
const toneCls =
|
||||
|
||||
@@ -603,6 +603,7 @@ export function isEquivalentTelemetry(prev, next) {
|
||||
bs?.contextTokens !== as?.contextTokens ||
|
||||
bs?.cacheHitPct !== as?.cacheHitPct ||
|
||||
bs?.selectedSpeedReason !== as?.selectedSpeedReason ||
|
||||
bs?.anomalySig !== as?.anomalySig ||
|
||||
bs?.turnIndex !== as?.turnIndex ||
|
||||
bs?.rootTurnIndex !== as?.rootTurnIndex ||
|
||||
bs?.isTurnStart !== as?.isTurnStart ||
|
||||
@@ -659,6 +660,7 @@ export function isEquivalentTelemetry(prev, next) {
|
||||
before.contextTokens !== after.contextTokens ||
|
||||
before.cacheHitPct !== after.cacheHitPct ||
|
||||
before.selectedSpeedReason !== after.selectedSpeedReason ||
|
||||
before.anomalySig !== after.anomalySig ||
|
||||
before.turnIndex !== after.turnIndex ||
|
||||
before.rootTurnIndex !== after.rootTurnIndex ||
|
||||
before.isTurnStart !== after.isTurnStart ||
|
||||
@@ -711,7 +713,9 @@ export function isEquivalentTelemetry(prev, next) {
|
||||
a[k]?.costUsd !== b[k]?.costUsd ||
|
||||
a[k]?.unpricedCalls !== b[k]?.unpricedCalls ||
|
||||
a[k]?.totalTokens !== b[k]?.totalTokens ||
|
||||
a[k]?.calls !== b[k]?.calls
|
||||
a[k]?.calls !== b[k]?.calls ||
|
||||
Number(a[k]?.anomalyCount || 0) !== Number(b[k]?.anomalyCount || 0) ||
|
||||
Number(a[k]?.anomalySteps || 0) !== Number(b[k]?.anomalySteps || 0)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
@@ -750,6 +754,9 @@ export function isEquivalentTelemetry(prev, next) {
|
||||
}
|
||||
|
||||
// 7. 比对按模型汇总明细与数据来源汇总明细
|
||||
if (!areModelSlicesEqual(pAct?.modelBreakdown, nAct?.modelBreakdown)) {
|
||||
return false;
|
||||
}
|
||||
if (!areModelSlicesEqual(prev.modelBreakdown, next.modelBreakdown)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -343,7 +343,8 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .agent-badge,
|
||||
[data-modern-ui="true"] .agent-badge.is-clickable:hover {
|
||||
[data-modern-ui="true"] .agent-badge.is-clickable:hover,
|
||||
[data-modern-ui="true"] .step-anomaly-tag {
|
||||
border: none;
|
||||
}
|
||||
|
||||
@@ -456,6 +457,7 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .trend-tip-sub,
|
||||
[data-modern-ui="true"] .trend-tip-anomaly,
|
||||
[data-modern-ui="true"] .cons-pop-models {
|
||||
border-top: none;
|
||||
padding-top: 3px;
|
||||
@@ -516,6 +518,28 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
|
||||
background: var(--modern-surface-hover);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .data-table tbody tr.is-anomaly-warn,
|
||||
[data-modern-ui="true"] .data-table:not(.is-virtualized) tbody tr.is-anomaly-warn:nth-child(even),
|
||||
[data-modern-ui="true"] .data-table.is-virtualized tbody tr.is-stripe-even.is-anomaly-warn {
|
||||
background: color-mix(in srgb, var(--metric-warn) 12%, transparent);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .data-table tbody tr.is-anomaly-warn:hover,
|
||||
[data-modern-ui="true"] .data-table.is-virtualized tbody tr.is-stripe-even.is-anomaly-warn:hover {
|
||||
background: color-mix(in srgb, var(--metric-warn) 19%, transparent);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .data-table tbody tr.is-anomaly-danger,
|
||||
[data-modern-ui="true"] .data-table:not(.is-virtualized) tbody tr.is-anomaly-danger:nth-child(even),
|
||||
[data-modern-ui="true"] .data-table.is-virtualized tbody tr.is-stripe-even.is-anomaly-danger {
|
||||
background: color-mix(in srgb, var(--metric-danger) 14%, transparent);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .data-table tbody tr.is-anomaly-danger:hover,
|
||||
[data-modern-ui="true"] .data-table.is-virtualized tbody tr.is-stripe-even.is-anomaly-danger:hover {
|
||||
background: color-mix(in srgb, var(--metric-danger) 21%, transparent);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .steps-inline-scope-select .select-trigger,
|
||||
[data-modern-ui="true"] .steps-inline-model-select .select-trigger,
|
||||
[data-modern-ui="true"] .sstep-fit-model-select .select-trigger {
|
||||
@@ -550,6 +574,22 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
|
||||
background: var(--accent-primary-soft);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .steps-anomaly-filterbar,
|
||||
[data-modern-ui="true"] .steps-anomaly-strip {
|
||||
border: none;
|
||||
border-radius: var(--radius-xs);
|
||||
background: var(--metric-warn-soft);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .steps-anomaly-filterbar {
|
||||
margin: 4px 2px 2px;
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .sstep-anomaly-dot,
|
||||
[data-modern-ui="true"] .sstep-scatter-dot.is-anomaly {
|
||||
fill: var(--modern-surface-card);
|
||||
}
|
||||
|
||||
/* --- 6. 设置表单、折叠面板、槽位排序与输入控件去边框 --- */
|
||||
[data-modern-ui="true"] .collapsible-body,
|
||||
[data-modern-ui="true"] .settings-action-block + .settings-action-block,
|
||||
@@ -630,13 +670,19 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
|
||||
|
||||
[data-modern-ui="true"] .trend-tooltip,
|
||||
[data-modern-ui="true"] .cons-breakdown-popover,
|
||||
[data-modern-ui="true"] .turn-prompt-tip {
|
||||
[data-modern-ui="true"] .turn-prompt-tip,
|
||||
[data-modern-ui="true"] .step-anomaly-tip {
|
||||
border: none;
|
||||
background: var(--modern-surface-card);
|
||||
box-shadow: var(--shadow-popover);
|
||||
animation: anim-modern-tip-fade 150ms var(--ease-modern);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .step-anomaly-tip-list,
|
||||
[data-modern-ui="true"] .step-anomaly-tip-hint {
|
||||
border-top-color: var(--modern-surface-hover);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .trend-tooltip:not(.is-hm-top):not(.is-hm-bottom) {
|
||||
top: 2px;
|
||||
bottom: auto;
|
||||
@@ -740,10 +786,18 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
|
||||
[data-modern-ui="true"] .wm-multi-label[data-od-active="1"] {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 18px;
|
||||
line-height: 18px;
|
||||
}
|
||||
|
||||
:host([data-modern-ui="true"]) .wm-slot-text.wm-ctx-pct[data-od-active="1"],
|
||||
:host([data-modern-ui="true"]) .wm-multi-label[data-od-active="1"],
|
||||
[data-modern-ui="true"] .wm-slot-text.wm-ctx-pct[data-od-active="1"],
|
||||
[data-modern-ui="true"] .wm-multi-label[data-od-active="1"] {
|
||||
justify-content: flex-start;
|
||||
}
|
||||
|
||||
:host([data-modern-ui="true"]) .wm-od-digit,
|
||||
[data-modern-ui="true"] .wm-od-digit {
|
||||
display: inline-block;
|
||||
|
||||
@@ -295,6 +295,248 @@
|
||||
animation: anim-popover-in var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
/* --- 2.6 单步异常整行语义着色、模型汇总微标、筛选条与悬停诊断卡 --- */
|
||||
.data-table tbody tr.is-anomaly-warn {
|
||||
background: color-mix(in srgb, var(--metric-warn) 11%, transparent);
|
||||
}
|
||||
|
||||
.data-table tbody tr.is-anomaly-warn:hover {
|
||||
background: color-mix(in srgb, var(--metric-warn) 18%, transparent);
|
||||
}
|
||||
|
||||
.data-table tbody tr.is-anomaly-warn td:first-child {
|
||||
box-shadow: inset 2px 0 0 var(--metric-warn);
|
||||
}
|
||||
|
||||
.data-table tbody tr.is-anomaly-warn td:first-child > span:not(.agent-badge):not(.turn-rail) {
|
||||
color: var(--metric-warn);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.data-table tbody tr.is-anomaly-danger {
|
||||
background: color-mix(in srgb, var(--metric-danger) 13%, transparent);
|
||||
}
|
||||
|
||||
.data-table tbody tr.is-anomaly-danger:hover {
|
||||
background: color-mix(in srgb, var(--metric-danger) 20%, transparent);
|
||||
}
|
||||
|
||||
.data-table tbody tr.is-anomaly-danger td:first-child {
|
||||
box-shadow: inset 2px 0 0 var(--metric-danger);
|
||||
}
|
||||
|
||||
.data-table tbody tr.is-anomaly-danger td:first-child > span:not(.agent-badge):not(.turn-rail) {
|
||||
color: var(--metric-danger);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.step-anomaly-tag {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
vertical-align: middle;
|
||||
margin-left: 4px;
|
||||
padding: 0 3.5px;
|
||||
font-size: var(--fs-2xs);
|
||||
font-weight: 600;
|
||||
line-height: 1.35;
|
||||
border-radius: 3px;
|
||||
color: var(--metric-warn);
|
||||
background: var(--metric-warn-soft);
|
||||
border: 1px solid color-mix(in srgb, var(--metric-warn) 34%, transparent);
|
||||
cursor: help;
|
||||
white-space: nowrap;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.step-anomaly-tag.is-danger {
|
||||
color: var(--metric-danger);
|
||||
background: var(--metric-danger-soft);
|
||||
border-color: color-mix(in srgb, var(--metric-danger) 36%, transparent);
|
||||
}
|
||||
|
||||
.step-anomaly-tag[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.smodel-anomaly-tag {
|
||||
margin-left: 0;
|
||||
cursor: pointer;
|
||||
font-family: inherit;
|
||||
transition:
|
||||
background-color var(--dur-instant) var(--ease-fast),
|
||||
border-color var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.smodel-anomaly-tag:hover {
|
||||
background: color-mix(in srgb, var(--metric-warn) 22%, transparent);
|
||||
}
|
||||
|
||||
.smodel-anomaly-tag.is-danger:hover {
|
||||
background: color-mix(in srgb, var(--metric-danger) 22%, transparent);
|
||||
}
|
||||
|
||||
.step-anomaly-tip {
|
||||
position: absolute;
|
||||
z-index: 46;
|
||||
max-width: min(300px, calc(100% - 16px));
|
||||
min-width: 176px;
|
||||
padding: 7px 9px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 5px;
|
||||
font-size: var(--fs-sm);
|
||||
line-height: 1.38;
|
||||
color: var(--text-primary);
|
||||
background: var(--surface-panel);
|
||||
border: 1px solid color-mix(in srgb, var(--metric-warn) 42%, var(--border-strong));
|
||||
border-radius: var(--radius-xs);
|
||||
box-shadow: var(--shadow-popover);
|
||||
pointer-events: none;
|
||||
animation: anim-popover-in var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.step-anomaly-tip.is-danger {
|
||||
border-color: color-mix(in srgb, var(--metric-danger) 46%, var(--border-strong));
|
||||
}
|
||||
|
||||
.step-anomaly-tip[hidden],
|
||||
.step-anomaly-tip-sub[hidden],
|
||||
.step-anomaly-tip-list[hidden],
|
||||
.step-anomaly-tip-hint[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.step-anomaly-tip-head {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.step-anomaly-tip-title {
|
||||
font-weight: 600;
|
||||
color: var(--metric-warn);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.step-anomaly-tip.is-danger .step-anomaly-tip-title {
|
||||
color: var(--metric-danger);
|
||||
}
|
||||
|
||||
.step-anomaly-tip-sub {
|
||||
font-size: var(--fs-xs);
|
||||
color: var(--text-secondary);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.step-anomaly-tip-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
padding-top: 4px;
|
||||
border-top: 1px solid var(--border-hairline);
|
||||
}
|
||||
|
||||
.step-anomaly-tip-item {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1px;
|
||||
}
|
||||
|
||||
.step-anomaly-tip-row {
|
||||
font-size: var(--fs-xs);
|
||||
font-weight: 500;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.step-anomaly-tip-row.is-danger {
|
||||
color: var(--metric-danger);
|
||||
}
|
||||
|
||||
.step-anomaly-tip-detail {
|
||||
font-size: var(--fs-2xs);
|
||||
line-height: 1.35;
|
||||
color: var(--text-muted);
|
||||
word-break: break-word;
|
||||
display: -webkit-box;
|
||||
-webkit-box-orient: vertical;
|
||||
-webkit-line-clamp: 2;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.step-anomaly-tip-hint {
|
||||
font-size: var(--fs-2xs);
|
||||
color: var(--text-muted);
|
||||
padding-top: 3px;
|
||||
border-top: 1px solid var(--border-hairline);
|
||||
}
|
||||
|
||||
.steps-anomaly-filterbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
padding: 4px 8px;
|
||||
border-top: 1px solid var(--border-hairline);
|
||||
background: color-mix(in srgb, var(--metric-warn) 8%, var(--surface-panel));
|
||||
font-size: var(--fs-xs);
|
||||
}
|
||||
|
||||
.steps-anomaly-filterbar[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.steps-anomaly-filter-label {
|
||||
font-weight: 600;
|
||||
color: var(--metric-warn);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.steps-anomaly-filter-clear {
|
||||
flex-shrink: 0;
|
||||
padding: 1px 7px;
|
||||
font-size: var(--fs-xs);
|
||||
}
|
||||
|
||||
.steps-anomaly-strip {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px 6px;
|
||||
padding: 4px 8px;
|
||||
border: 1px solid color-mix(in srgb, var(--metric-warn) 26%, var(--border-hairline));
|
||||
border-radius: var(--radius-xs);
|
||||
background: color-mix(in srgb, var(--metric-warn) 7%, var(--surface-panel));
|
||||
}
|
||||
|
||||
.steps-anomaly-strip[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.steps-anomaly-strip-meta {
|
||||
border: none;
|
||||
background: transparent;
|
||||
padding: 0;
|
||||
font-size: var(--fs-xs);
|
||||
font-weight: 600;
|
||||
color: var(--metric-warn);
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.steps-anomaly-strip-meta:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.steps-anomaly-strip-tags {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
/* --- 3. 按模型汇总分析视图:双趋势图与极简模型总览 (Models Analytics Pane) --- */
|
||||
.models-analytics-pane {
|
||||
display: flex;
|
||||
@@ -517,6 +759,47 @@
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.sstep-hover-raw-dot.is-anomaly {
|
||||
stroke: var(--metric-warn);
|
||||
stroke-width: 1.85;
|
||||
}
|
||||
|
||||
.sstep-hover-raw-dot.is-danger {
|
||||
stroke: var(--metric-danger);
|
||||
}
|
||||
|
||||
.sstep-anomaly-dot,
|
||||
.sstep-scatter-dot.is-anomaly {
|
||||
fill: var(--surface-panel);
|
||||
fill-opacity: 1;
|
||||
stroke: var(--metric-warn);
|
||||
stroke-width: 1.6;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.sstep-anomaly-dot.is-danger,
|
||||
.sstep-scatter-dot.is-anomaly.is-danger {
|
||||
stroke: var(--metric-danger);
|
||||
}
|
||||
|
||||
.trend-tip-anomaly {
|
||||
margin-top: 3px;
|
||||
padding-top: 3px;
|
||||
border-top: 1px solid var(--border-hairline);
|
||||
font-size: var(--fs-xs);
|
||||
font-weight: 600;
|
||||
color: var(--metric-warn);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.trend-tip-anomaly.is-danger {
|
||||
color: var(--metric-danger);
|
||||
}
|
||||
|
||||
.trend-tip-anomaly[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.sstep-empty-hint {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
|
||||
@@ -14,12 +14,17 @@ import {
|
||||
patchText,
|
||||
} from '../core/domPatch.js';
|
||||
import {
|
||||
buildModelAnomalyDiagnostic,
|
||||
formatAnomalyKindLabel,
|
||||
formatAnomalyTagText,
|
||||
formatMetric,
|
||||
formatSpeedMetric,
|
||||
formatTokens,
|
||||
formatUsd,
|
||||
mergeModelsByDisplayName,
|
||||
normalizeModelDisplayMode,
|
||||
normalizeOrchestratorIdDisplayMode,
|
||||
resolveModelAnomalySummary,
|
||||
resolveModelDisplayInfo,
|
||||
} from '../core/formatters.js';
|
||||
import { createSvgIcon } from '../icons/SvgIcon.js';
|
||||
@@ -77,6 +82,11 @@ function mergeSelectedAgentUnits(units) {
|
||||
totalTokens: 0,
|
||||
costUsd: 0,
|
||||
unpricedCalls: 0,
|
||||
anomalySteps: 0,
|
||||
anomalyCount: 0,
|
||||
anomalyDangerCount: 0,
|
||||
anomalyTotalDelaySec: 0,
|
||||
anomalyByKind: {},
|
||||
_speedWeightedSum: 0,
|
||||
_speedWeight: 0,
|
||||
_ttftWeightedSum: 0,
|
||||
@@ -116,6 +126,16 @@ function mergeSelectedAgentUnits(units) {
|
||||
acc.totalTokens += totTok;
|
||||
acc.costUsd += costUsd;
|
||||
acc.unpricedCalls += unpricedCalls;
|
||||
acc.anomalySteps += Math.max(0, Number(m.anomalySteps || 0));
|
||||
acc.anomalyCount += Math.max(0, Number(m.anomalyCount || 0));
|
||||
acc.anomalyDangerCount += Math.max(0, Number(m.anomalyDangerCount || 0));
|
||||
acc.anomalyTotalDelaySec += Math.max(0, Number(m.anomalyTotalDelaySec || 0));
|
||||
if (m.anomalyByKind && typeof m.anomalyByKind === 'object') {
|
||||
for (const [kind, cnt] of Object.entries(m.anomalyByKind)) {
|
||||
const n = Math.max(0, Number(cnt || 0));
|
||||
if (n > 0) acc.anomalyByKind[kind] = (acc.anomalyByKind[kind] || 0) + n;
|
||||
}
|
||||
}
|
||||
|
||||
if (Number.isFinite(Number(m.avgTokPerSec)) && Number(m.avgTokPerSec) > 0) {
|
||||
const w = Math.max(1, outTok || calls || 1);
|
||||
@@ -164,6 +184,15 @@ function mergeSelectedAgentUnits(units) {
|
||||
avgTtftSec:
|
||||
acc._ttftWeight > 0 ? +(acc._ttftWeightedSum / acc._ttftWeight).toFixed(1) : null,
|
||||
cacheHitPct: promptTok > 0 ? +((acc.cacheReadTokens / promptTok) * 100).toFixed(1) : 0,
|
||||
...(acc.anomalyCount > 0
|
||||
? {
|
||||
anomalySteps: acc.anomalySteps,
|
||||
anomalyCount: acc.anomalyCount,
|
||||
anomalyDangerCount: acc.anomalyDangerCount,
|
||||
anomalyTotalDelaySec: +acc.anomalyTotalDelaySec.toFixed(1),
|
||||
anomalyByKind: acc.anomalyByKind,
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
})
|
||||
.sort((a, b) => b.totalTokens - a.totalTokens || b.calls - a.calls);
|
||||
@@ -197,6 +226,8 @@ export const StepsDetailView = defineComponent({
|
||||
let lastSyncedUiScope = uiStore.getState().selectedAgentScope || 'all';
|
||||
let selectedTableModels = ['__all__'];
|
||||
let selectedLineModels = ['__all__'];
|
||||
let onlyAnomalies = false;
|
||||
let anomalyKindFilter = '';
|
||||
|
||||
function applyAgentScopesSelection(nextScopes) {
|
||||
selectedAgentScopes = nextScopes;
|
||||
@@ -271,7 +302,10 @@ export const StepsDetailView = defineComponent({
|
||||
stepsTheadRow,
|
||||
stepsTbody,
|
||||
turnTipEl,
|
||||
anomalyTipEl,
|
||||
hideTurnTip,
|
||||
showAnomalyTip,
|
||||
hideAnomalyTip,
|
||||
syncTableHeaderColumns,
|
||||
renderStepTable,
|
||||
refreshViewport: refreshStepTableViewport,
|
||||
@@ -281,6 +315,23 @@ export const StepsDetailView = defineComponent({
|
||||
className: 'table-scroll-host',
|
||||
});
|
||||
|
||||
const anomalyFilterLabelEl = h('span', { className: 'steps-anomaly-filter-label text-mono' });
|
||||
const anomalyFilterClearBtn = h('button', {
|
||||
type: 'button',
|
||||
className: 'btn-ghost-sm steps-anomaly-filter-clear',
|
||||
text: t('steps.anomalyFilterAll'),
|
||||
onclick: () => {
|
||||
onlyAnomalies = false;
|
||||
anomalyKindFilter = '';
|
||||
if (latestSlice) renderStepsData(latestSlice);
|
||||
},
|
||||
});
|
||||
const anomalyFilterBarEl = h(
|
||||
'div',
|
||||
{ className: 'steps-anomaly-filterbar', hidden: true },
|
||||
[anomalyFilterLabelEl, anomalyFilterClearBtn]
|
||||
);
|
||||
|
||||
// --- 子视图 2:总汇总分析面板 ---
|
||||
let selectedLineMetric = 'totalTokens';
|
||||
let selectedFitMetric = 'tps';
|
||||
@@ -383,6 +434,24 @@ export const StepsDetailView = defineComponent({
|
||||
className: 'cons-badge text-mono',
|
||||
text: t('cons.callsCount', { calls: 0 }),
|
||||
});
|
||||
const modelsAnomalyMetaEl = h('button', {
|
||||
type: 'button',
|
||||
className: 'steps-anomaly-strip-meta text-mono',
|
||||
onclick: () => {
|
||||
hideAnomalyTip();
|
||||
selectedTableModels = ['__all__'];
|
||||
onlyAnomalies = true;
|
||||
anomalyKindFilter = '';
|
||||
uiStore.setState({ stepsSubTab: 'steps' });
|
||||
},
|
||||
});
|
||||
const modelsAnomalyTagsEl = h('div', { className: 'steps-anomaly-strip-tags' });
|
||||
const modelsAnomalyStripEl = h(
|
||||
'div',
|
||||
{ className: 'steps-anomaly-strip', hidden: true },
|
||||
[modelsAnomalyMetaEl, modelsAnomalyTagsEl]
|
||||
);
|
||||
let lastAnomalyStripSig = '';
|
||||
const modelsEmptyEl = h('div', {
|
||||
className: 'smodel-empty text-muted',
|
||||
text: t('steps.modelsEmpty'),
|
||||
@@ -390,6 +459,7 @@ export const StepsDetailView = defineComponent({
|
||||
const modelsListEl = h('div', { className: 'smodel-list' });
|
||||
const modelsSummarySection = h('div', { className: 'smodel-section' }, [
|
||||
h('div', { className: 'smodel-section-head' }, [modelsSectionTitleEl, modelsSummaryMeta]),
|
||||
modelsAnomalyStripEl,
|
||||
modelsEmptyEl,
|
||||
modelsListEl,
|
||||
]);
|
||||
@@ -399,6 +469,8 @@ export const StepsDetailView = defineComponent({
|
||||
modelFitCard,
|
||||
modelsSummarySection,
|
||||
]);
|
||||
const onModelsPaneScroll = () => hideAnomalyTip();
|
||||
modelsAnalyticsPane.addEventListener('scroll', onModelsPaneScroll, { passive: true });
|
||||
const modelsScroll = CustomScrollbar({
|
||||
contentEl: modelsAnalyticsPane,
|
||||
className: 'table-scroll-host',
|
||||
@@ -424,9 +496,11 @@ export const StepsDetailView = defineComponent({
|
||||
subTabSwitch.el,
|
||||
]),
|
||||
]),
|
||||
anomalyFilterBarEl,
|
||||
stepsScroll.el,
|
||||
modelsScroll.el,
|
||||
turnTipEl,
|
||||
anomalyTipEl,
|
||||
]
|
||||
);
|
||||
stepTableWidget.refs.setBoundsElGetter(() => panelEl);
|
||||
@@ -497,6 +571,8 @@ export const StepsDetailView = defineComponent({
|
||||
patchText(fitTitleEl, t('steps.fitTitle'));
|
||||
patchText(modelsSectionTitleEl, t('steps.modelsTitle'));
|
||||
patchText(modelsEmptyEl, t('steps.modelsEmpty'));
|
||||
patchText(anomalyFilterClearBtn, t('steps.anomalyFilterAll'));
|
||||
lastAnomalyStripSig = '';
|
||||
lineMetricSwitch.setProps({
|
||||
modelValue: selectedLineMetric,
|
||||
options: getLineMetricSwitchOptions(),
|
||||
@@ -530,6 +606,8 @@ export const StepsDetailView = defineComponent({
|
||||
lastSyncedUiScope = uiSt.selectedAgentScope || 'all';
|
||||
selectedTableModels = ['__all__'];
|
||||
selectedLineModels = ['__all__'];
|
||||
onlyAnomalies = false;
|
||||
anomalyKindFilter = '';
|
||||
}
|
||||
fitLockedCascadeId = currentCid;
|
||||
fitUserPicked = false;
|
||||
@@ -723,9 +801,29 @@ export const StepsDetailView = defineComponent({
|
||||
const tableModelFilterSet = selectedTableModels.includes('__all__')
|
||||
? null
|
||||
: new Set(selectedTableModels);
|
||||
const tableSteps = tableModelFilterSet
|
||||
const modelFilteredSteps = tableModelFilterSet
|
||||
? steps.filter((st) => tableModelFilterSet.has(getStepModelGroupKey(st)))
|
||||
: steps;
|
||||
const tableSteps = onlyAnomalies
|
||||
? modelFilteredSteps.filter((st) => {
|
||||
const a = st?.anomaly;
|
||||
if (!a || !(Number(a.count) > 0)) return false;
|
||||
if (anomalyKindFilter) {
|
||||
return Number(a.kinds?.[anomalyKindFilter] || 0) > 0;
|
||||
}
|
||||
return true;
|
||||
})
|
||||
: modelFilteredSteps;
|
||||
|
||||
const showAnomalyFilterBar = !showModels && onlyAnomalies;
|
||||
patchAttr(anomalyFilterBarEl, 'hidden', !showAnomalyFilterBar);
|
||||
if (showAnomalyFilterBar) {
|
||||
const baseLabel = t('steps.anomalyFilterLabel', { count: tableSteps.length });
|
||||
const kindSuffix = anomalyKindFilter
|
||||
? ` · ${formatAnomalyKindLabel(anomalyKindFilter)}`
|
||||
: '';
|
||||
patchText(anomalyFilterLabelEl, `${baseLabel}${kindSuffix}`);
|
||||
}
|
||||
|
||||
const stepsTabLabel =
|
||||
tableSteps.length !== steps.length
|
||||
@@ -863,10 +961,79 @@ export const StepsDetailView = defineComponent({
|
||||
|
||||
// 4. 极简模型总览列表增量对账
|
||||
const displayModels = mergeModelsByDisplayName(models, displaySettings, { fallback: '—' });
|
||||
const needStepAnomalyFallback = displayModels.every((m) => !(Number(m?.anomalyCount) > 0));
|
||||
let stepAnomalyByGroup = null;
|
||||
if (needStepAnomalyFallback) {
|
||||
for (const st of chronoSteps) {
|
||||
const a = st?.anomaly;
|
||||
if (!a || !(Number(a.count) > 0)) continue;
|
||||
if (!stepAnomalyByGroup) stepAnomalyByGroup = new Map();
|
||||
const gk = getStepModelGroupKey(st);
|
||||
let acc = stepAnomalyByGroup.get(gk);
|
||||
if (!acc) {
|
||||
acc = {
|
||||
anomalySteps: 0,
|
||||
anomalyCount: 0,
|
||||
anomalyDangerCount: 0,
|
||||
anomalyTotalDelaySec: 0,
|
||||
anomalyByKind: {},
|
||||
};
|
||||
stepAnomalyByGroup.set(gk, acc);
|
||||
}
|
||||
acc.anomalySteps += 1;
|
||||
acc.anomalyCount += Number(a.count) || 0;
|
||||
if (a.severity === 'danger') acc.anomalyDangerCount += 1;
|
||||
acc.anomalyTotalDelaySec += Number(a.totalDelaySec) || 0;
|
||||
if (a.kinds && typeof a.kinds === 'object') {
|
||||
for (const [k, cnt] of Object.entries(a.kinds)) {
|
||||
const n = Math.max(0, Number(cnt || 0));
|
||||
if (n > 0) acc.anomalyByKind[k] = (acc.anomalyByKind[k] || 0) + n;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const resolveEffectiveAnomalyModel = (m) => {
|
||||
if (Number(m?.anomalyCount) > 0 || !stepAnomalyByGroup) return m;
|
||||
const gk = getStepModelGroupKey(m);
|
||||
const groupKeys =
|
||||
Array.isArray(m.sourceLabels) && m.sourceLabels.length > 0
|
||||
? Array.from(new Set(m.sourceLabels.map((lbl) => getStepModelGroupKey({ label: lbl }))))
|
||||
: [gk];
|
||||
let anomalySteps = 0;
|
||||
let anomalyCount = 0;
|
||||
let anomalyDangerCount = 0;
|
||||
let anomalyTotalDelaySec = 0;
|
||||
const anomalyByKind = {};
|
||||
for (const key of groupKeys) {
|
||||
const hit = stepAnomalyByGroup.get(key);
|
||||
if (!hit) continue;
|
||||
anomalySteps += hit.anomalySteps;
|
||||
anomalyCount += hit.anomalyCount;
|
||||
anomalyDangerCount += hit.anomalyDangerCount;
|
||||
anomalyTotalDelaySec += hit.anomalyTotalDelaySec;
|
||||
for (const [k, cnt] of Object.entries(hit.anomalyByKind)) {
|
||||
anomalyByKind[k] = (anomalyByKind[k] || 0) + cnt;
|
||||
}
|
||||
}
|
||||
if (anomalyCount <= 0) return m;
|
||||
return {
|
||||
...m,
|
||||
anomalySteps,
|
||||
anomalyCount,
|
||||
anomalyDangerCount,
|
||||
anomalyTotalDelaySec: +anomalyTotalDelaySec.toFixed(1),
|
||||
anomalyByKind,
|
||||
};
|
||||
};
|
||||
|
||||
let sumCalls = 0;
|
||||
let sumTokens = 0;
|
||||
let sumCost = 0;
|
||||
let sumUnpriced = 0;
|
||||
let sumAnomalyCount = 0;
|
||||
let sumAnomalySteps = 0;
|
||||
const sumAnomalyByKind = {};
|
||||
const effectiveAnomalyModels = new Map();
|
||||
for (const m of displayModels) {
|
||||
sumCalls += Math.max(0, Number(m.calls || 0));
|
||||
sumTokens += Math.max(0, Number(m.totalTokens || 0));
|
||||
@@ -874,6 +1041,54 @@ export const StepsDetailView = defineComponent({
|
||||
if (Number.isFinite(Number(m.costUsd))) {
|
||||
sumCost += Math.max(0, Number(m.costUsd));
|
||||
}
|
||||
const effM = resolveEffectiveAnomalyModel(m);
|
||||
effectiveAnomalyModels.set(m, effM);
|
||||
const anomSum = resolveModelAnomalySummary(effM);
|
||||
if (anomSum) {
|
||||
sumAnomalyCount += anomSum.count;
|
||||
sumAnomalySteps += anomSum.steps;
|
||||
for (const [k, v] of anomSum.entries) {
|
||||
sumAnomalyByKind[k] = (sumAnomalyByKind[k] || 0) + v;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (sumAnomalyCount > 0) {
|
||||
patchAttr(modelsAnomalyStripEl, 'hidden', false);
|
||||
const sortedKinds = Object.entries(sumAnomalyByKind)
|
||||
.filter(([, v]) => v > 0)
|
||||
.sort((a, b) => b[1] - a[1]);
|
||||
const stripSig = `${locale}:${sumAnomalyCount}:${sumAnomalySteps}:${sortedKinds.map(([k, v]) => `${k}=${v}`).join(',')}`;
|
||||
if (stripSig !== lastAnomalyStripSig) {
|
||||
lastAnomalyStripSig = stripSig;
|
||||
patchText(
|
||||
modelsAnomalyMetaEl,
|
||||
t('steps.anomalySummaryMeta', { count: sumAnomalyCount, steps: sumAnomalySteps })
|
||||
);
|
||||
while (modelsAnomalyTagsEl.firstChild) {
|
||||
modelsAnomalyTagsEl.removeChild(modelsAnomalyTagsEl.firstChild);
|
||||
}
|
||||
for (const [kind, cnt] of sortedKinds) {
|
||||
const isDanger = kind === 'rate_limit' || kind === 'auth_or_model';
|
||||
const btn = h('button', {
|
||||
type: 'button',
|
||||
className: `step-anomaly-tag smodel-anomaly-tag text-mono${isDanger ? ' is-danger' : ''}`,
|
||||
text: formatAnomalyTagText(kind, cnt),
|
||||
title: `${formatAnomalyKindLabel(kind)} · ${t('steps.anomalyModelClickHint')}`,
|
||||
onclick: () => {
|
||||
hideAnomalyTip();
|
||||
selectedTableModels = ['__all__'];
|
||||
onlyAnomalies = true;
|
||||
anomalyKindFilter = kind;
|
||||
uiStore.setState({ stepsSubTab: 'steps' });
|
||||
},
|
||||
});
|
||||
modelsAnomalyTagsEl.appendChild(btn);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
lastAnomalyStripSig = '';
|
||||
patchAttr(modelsAnomalyStripEl, 'hidden', true);
|
||||
}
|
||||
|
||||
if (displayModels.length === 0) {
|
||||
@@ -917,11 +1132,20 @@ export const StepsDetailView = defineComponent({
|
||||
: [gk];
|
||||
const isActiveFit =
|
||||
hasMultipleModels && cardGroupKeys.some((k) => fitActiveKeySet.has(k));
|
||||
return `${locale}:${m.displayText}:${m.displayTitle}:${m.calls}:${sumCalls}:${displayModels.length}:${m.avgTokPerSec}:${avgTtft}:${m.cacheHitPct}:${m.inputTokens}:${m.cacheReadTokens}:${m.thinkingTokens}:${m.responseTokens}:${m.totalTokens}:${m.costUsd}:${m.unpricedCalls}:${isActiveFit}:${hasMultipleModels}`;
|
||||
const effM = effectiveAnomalyModels.get(m) || m;
|
||||
const anomSum = resolveModelAnomalySummary(effM);
|
||||
const anomSig = anomSum
|
||||
? `${anomSum.count}:${anomSum.steps}:${anomSum.primaryKind}:${anomSum.severity}:${anomSum.totalDelaySec}`
|
||||
: '';
|
||||
return `${locale}:${m.displayText}:${m.displayTitle}:${m.calls}:${sumCalls}:${displayModels.length}:${m.avgTokPerSec}:${avgTtft}:${m.cacheHitPct}:${m.inputTokens}:${m.cacheReadTokens}:${m.thinkingTokens}:${m.responseTokens}:${m.totalTokens}:${m.costUsd}:${m.unpricedCalls}:${isActiveFit}:${hasMultipleModels}:${anomSig}`;
|
||||
},
|
||||
createRow: () => {
|
||||
const nameEl = h('strong', { className: 'smodel-name' });
|
||||
const callsPillEl = h('span', { className: 'smodel-calls-pill text-mono' });
|
||||
const anomalyTagEl = h('span', {
|
||||
className: 'step-anomaly-tag smodel-anomaly-tag text-mono',
|
||||
hidden: true,
|
||||
});
|
||||
const tokEl = h('span', { className: 'smodel-tok text-mono' });
|
||||
const costEl = h('strong', { className: 'smodel-cost text-mono' });
|
||||
const segBar = createFourSegmentBar();
|
||||
@@ -932,7 +1156,7 @@ export const StepsDetailView = defineComponent({
|
||||
|
||||
const cardEl = h('div', { className: 'smodel-card' }, [
|
||||
h('div', { className: 'smodel-head' }, [
|
||||
h('div', { className: 'smodel-ident' }, [nameEl, callsPillEl]),
|
||||
h('div', { className: 'smodel-ident' }, [nameEl, callsPillEl, anomalyTagEl]),
|
||||
h('div', { className: 'smodel-totals' }, [tokEl, costEl]),
|
||||
]),
|
||||
segBar.el,
|
||||
@@ -941,7 +1165,7 @@ export const StepsDetailView = defineComponent({
|
||||
|
||||
return {
|
||||
el: cardEl,
|
||||
refs: { nameEl, callsPillEl, tokEl, costEl, segBar, perfEl, splitEl },
|
||||
refs: { nameEl, callsPillEl, anomalyTagEl, tokEl, costEl, segBar, perfEl, splitEl },
|
||||
};
|
||||
},
|
||||
updateRow: (refs, m, _idx, cardEl) => {
|
||||
@@ -966,6 +1190,29 @@ export const StepsDetailView = defineComponent({
|
||||
: t('steps.modelCallsOnly', { calls })
|
||||
);
|
||||
|
||||
const effM = effectiveAnomalyModels.get(m) || m;
|
||||
const anomSum = resolveModelAnomalySummary(effM);
|
||||
patchAttr(refs.anomalyTagEl, 'hidden', !anomSum);
|
||||
if (anomSum) {
|
||||
patchText(refs.anomalyTagEl, anomSum.tagText);
|
||||
patchClasses(refs.anomalyTagEl, { 'is-danger': anomSum.severity === 'danger' });
|
||||
refs.anomalyTagEl.onmouseenter = () =>
|
||||
showAnomalyTip(refs.anomalyTagEl, buildModelAnomalyDiagnostic(effM));
|
||||
refs.anomalyTagEl.onmouseleave = hideAnomalyTip;
|
||||
refs.anomalyTagEl.onclick = (e) => {
|
||||
e?.stopPropagation?.();
|
||||
hideAnomalyTip();
|
||||
selectedTableModels = hasMultipleModels ? [...cardGroupKeys] : ['__all__'];
|
||||
onlyAnomalies = true;
|
||||
anomalyKindFilter = '';
|
||||
uiStore.setState({ stepsSubTab: 'steps' });
|
||||
};
|
||||
} else {
|
||||
refs.anomalyTagEl.onmouseenter = null;
|
||||
refs.anomalyTagEl.onmouseleave = null;
|
||||
refs.anomalyTagEl.onclick = null;
|
||||
}
|
||||
|
||||
const inTok = Math.max(0, Number(m.inputTokens || 0));
|
||||
const cacheTok = Math.max(0, Number(m.cacheReadTokens || 0));
|
||||
const outTok = Math.max(0, Number(m.outputTokens || 0));
|
||||
@@ -1009,7 +1256,7 @@ export const StepsDetailView = defineComponent({
|
||||
patchText(
|
||||
refs.perfEl,
|
||||
t('steps.modelPerfFoot', {
|
||||
tps: formatMetric(m.avgTokPerSec, ' tok/s'),
|
||||
tps: formatSpeedMetric(m.avgTokPerSec, ' tok/s'),
|
||||
ttft: formatMetric(resolvedAvgTtft, 's'),
|
||||
cache: resolvedCachePct,
|
||||
})
|
||||
@@ -1070,7 +1317,9 @@ export const StepsDetailView = defineComponent({
|
||||
(st) => st.stepsSubTab,
|
||||
(tab) => {
|
||||
hideTurnTip();
|
||||
hideAnomalyTip();
|
||||
subTabSwitch.setValue(tab);
|
||||
patchAttr(anomalyFilterBarEl, 'hidden', tab !== 'steps' || !onlyAnomalies);
|
||||
patchAttr(stepsScroll.el, 'hidden', tab !== 'steps');
|
||||
patchAttr(modelsScroll.el, 'hidden', tab !== 'models');
|
||||
if (getVisibleMonitorView() === 'steps' && latestSlice) {
|
||||
@@ -1142,6 +1391,7 @@ export const StepsDetailView = defineComponent({
|
||||
prevActiveView = uiSlice.activeView;
|
||||
if (uiSlice.activeView !== 'steps') {
|
||||
hideTurnTip();
|
||||
hideAnomalyTip();
|
||||
fitPinnedWhileVisible = false;
|
||||
if (scopeChanged) isDirty = true;
|
||||
return;
|
||||
@@ -1166,6 +1416,7 @@ export const StepsDetailView = defineComponent({
|
||||
);
|
||||
|
||||
onCleanup(() => {
|
||||
modelsAnalyticsPane.removeEventListener('scroll', onModelsPaneScroll);
|
||||
unsubUi();
|
||||
unsubTelemetry();
|
||||
unsubView();
|
||||
@@ -1191,6 +1442,9 @@ export const StepsDetailView = defineComponent({
|
||||
stepsTheadRow,
|
||||
stepsTbody,
|
||||
turnTipEl,
|
||||
anomalyTipEl,
|
||||
anomalyFilterBarEl,
|
||||
modelsAnomalyStripEl,
|
||||
modelsListEl,
|
||||
inlineScopeSelect,
|
||||
stepsModelSelect,
|
||||
|
||||
+339
-2
@@ -3197,6 +3197,248 @@ html[data-standalone="true"] .app-shell {
|
||||
animation: anim-popover-in var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
/* --- 2.6 单步异常整行语义着色、模型汇总微标、筛选条与悬停诊断卡 --- */
|
||||
.data-table tbody tr.is-anomaly-warn {
|
||||
background: color-mix(in srgb, var(--metric-warn) 11%, transparent);
|
||||
}
|
||||
|
||||
.data-table tbody tr.is-anomaly-warn:hover {
|
||||
background: color-mix(in srgb, var(--metric-warn) 18%, transparent);
|
||||
}
|
||||
|
||||
.data-table tbody tr.is-anomaly-warn td:first-child {
|
||||
box-shadow: inset 2px 0 0 var(--metric-warn);
|
||||
}
|
||||
|
||||
.data-table tbody tr.is-anomaly-warn td:first-child > span:not(.agent-badge):not(.turn-rail) {
|
||||
color: var(--metric-warn);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.data-table tbody tr.is-anomaly-danger {
|
||||
background: color-mix(in srgb, var(--metric-danger) 13%, transparent);
|
||||
}
|
||||
|
||||
.data-table tbody tr.is-anomaly-danger:hover {
|
||||
background: color-mix(in srgb, var(--metric-danger) 20%, transparent);
|
||||
}
|
||||
|
||||
.data-table tbody tr.is-anomaly-danger td:first-child {
|
||||
box-shadow: inset 2px 0 0 var(--metric-danger);
|
||||
}
|
||||
|
||||
.data-table tbody tr.is-anomaly-danger td:first-child > span:not(.agent-badge):not(.turn-rail) {
|
||||
color: var(--metric-danger);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.step-anomaly-tag {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
vertical-align: middle;
|
||||
margin-left: 4px;
|
||||
padding: 0 3.5px;
|
||||
font-size: var(--fs-2xs);
|
||||
font-weight: 600;
|
||||
line-height: 1.35;
|
||||
border-radius: 3px;
|
||||
color: var(--metric-warn);
|
||||
background: var(--metric-warn-soft);
|
||||
border: 1px solid color-mix(in srgb, var(--metric-warn) 34%, transparent);
|
||||
cursor: help;
|
||||
white-space: nowrap;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.step-anomaly-tag.is-danger {
|
||||
color: var(--metric-danger);
|
||||
background: var(--metric-danger-soft);
|
||||
border-color: color-mix(in srgb, var(--metric-danger) 36%, transparent);
|
||||
}
|
||||
|
||||
.step-anomaly-tag[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.smodel-anomaly-tag {
|
||||
margin-left: 0;
|
||||
cursor: pointer;
|
||||
font-family: inherit;
|
||||
transition:
|
||||
background-color var(--dur-instant) var(--ease-fast),
|
||||
border-color var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.smodel-anomaly-tag:hover {
|
||||
background: color-mix(in srgb, var(--metric-warn) 22%, transparent);
|
||||
}
|
||||
|
||||
.smodel-anomaly-tag.is-danger:hover {
|
||||
background: color-mix(in srgb, var(--metric-danger) 22%, transparent);
|
||||
}
|
||||
|
||||
.step-anomaly-tip {
|
||||
position: absolute;
|
||||
z-index: 46;
|
||||
max-width: min(300px, calc(100% - 16px));
|
||||
min-width: 176px;
|
||||
padding: 7px 9px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 5px;
|
||||
font-size: var(--fs-sm);
|
||||
line-height: 1.38;
|
||||
color: var(--text-primary);
|
||||
background: var(--surface-panel);
|
||||
border: 1px solid color-mix(in srgb, var(--metric-warn) 42%, var(--border-strong));
|
||||
border-radius: var(--radius-xs);
|
||||
box-shadow: var(--shadow-popover);
|
||||
pointer-events: none;
|
||||
animation: anim-popover-in var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.step-anomaly-tip.is-danger {
|
||||
border-color: color-mix(in srgb, var(--metric-danger) 46%, var(--border-strong));
|
||||
}
|
||||
|
||||
.step-anomaly-tip[hidden],
|
||||
.step-anomaly-tip-sub[hidden],
|
||||
.step-anomaly-tip-list[hidden],
|
||||
.step-anomaly-tip-hint[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.step-anomaly-tip-head {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.step-anomaly-tip-title {
|
||||
font-weight: 600;
|
||||
color: var(--metric-warn);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.step-anomaly-tip.is-danger .step-anomaly-tip-title {
|
||||
color: var(--metric-danger);
|
||||
}
|
||||
|
||||
.step-anomaly-tip-sub {
|
||||
font-size: var(--fs-xs);
|
||||
color: var(--text-secondary);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.step-anomaly-tip-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
padding-top: 4px;
|
||||
border-top: 1px solid var(--border-hairline);
|
||||
}
|
||||
|
||||
.step-anomaly-tip-item {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1px;
|
||||
}
|
||||
|
||||
.step-anomaly-tip-row {
|
||||
font-size: var(--fs-xs);
|
||||
font-weight: 500;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.step-anomaly-tip-row.is-danger {
|
||||
color: var(--metric-danger);
|
||||
}
|
||||
|
||||
.step-anomaly-tip-detail {
|
||||
font-size: var(--fs-2xs);
|
||||
line-height: 1.35;
|
||||
color: var(--text-muted);
|
||||
word-break: break-word;
|
||||
display: -webkit-box;
|
||||
-webkit-box-orient: vertical;
|
||||
-webkit-line-clamp: 2;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.step-anomaly-tip-hint {
|
||||
font-size: var(--fs-2xs);
|
||||
color: var(--text-muted);
|
||||
padding-top: 3px;
|
||||
border-top: 1px solid var(--border-hairline);
|
||||
}
|
||||
|
||||
.steps-anomaly-filterbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
padding: 4px 8px;
|
||||
border-top: 1px solid var(--border-hairline);
|
||||
background: color-mix(in srgb, var(--metric-warn) 8%, var(--surface-panel));
|
||||
font-size: var(--fs-xs);
|
||||
}
|
||||
|
||||
.steps-anomaly-filterbar[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.steps-anomaly-filter-label {
|
||||
font-weight: 600;
|
||||
color: var(--metric-warn);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.steps-anomaly-filter-clear {
|
||||
flex-shrink: 0;
|
||||
padding: 1px 7px;
|
||||
font-size: var(--fs-xs);
|
||||
}
|
||||
|
||||
.steps-anomaly-strip {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px 6px;
|
||||
padding: 4px 8px;
|
||||
border: 1px solid color-mix(in srgb, var(--metric-warn) 26%, var(--border-hairline));
|
||||
border-radius: var(--radius-xs);
|
||||
background: color-mix(in srgb, var(--metric-warn) 7%, var(--surface-panel));
|
||||
}
|
||||
|
||||
.steps-anomaly-strip[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.steps-anomaly-strip-meta {
|
||||
border: none;
|
||||
background: transparent;
|
||||
padding: 0;
|
||||
font-size: var(--fs-xs);
|
||||
font-weight: 600;
|
||||
color: var(--metric-warn);
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.steps-anomaly-strip-meta:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.steps-anomaly-strip-tags {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
/* --- 3. 按模型汇总分析视图:双趋势图与极简模型总览 (Models Analytics Pane) --- */
|
||||
.models-analytics-pane {
|
||||
display: flex;
|
||||
@@ -3419,6 +3661,47 @@ html[data-standalone="true"] .app-shell {
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.sstep-hover-raw-dot.is-anomaly {
|
||||
stroke: var(--metric-warn);
|
||||
stroke-width: 1.85;
|
||||
}
|
||||
|
||||
.sstep-hover-raw-dot.is-danger {
|
||||
stroke: var(--metric-danger);
|
||||
}
|
||||
|
||||
.sstep-anomaly-dot,
|
||||
.sstep-scatter-dot.is-anomaly {
|
||||
fill: var(--surface-panel);
|
||||
fill-opacity: 1;
|
||||
stroke: var(--metric-warn);
|
||||
stroke-width: 1.6;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.sstep-anomaly-dot.is-danger,
|
||||
.sstep-scatter-dot.is-anomaly.is-danger {
|
||||
stroke: var(--metric-danger);
|
||||
}
|
||||
|
||||
.trend-tip-anomaly {
|
||||
margin-top: 3px;
|
||||
padding-top: 3px;
|
||||
border-top: 1px solid var(--border-hairline);
|
||||
font-size: var(--fs-xs);
|
||||
font-weight: 600;
|
||||
color: var(--metric-warn);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.trend-tip-anomaly.is-danger {
|
||||
color: var(--metric-danger);
|
||||
}
|
||||
|
||||
.trend-tip-anomaly[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.sstep-empty-hint {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
@@ -5819,7 +6102,8 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .agent-badge,
|
||||
[data-modern-ui="true"] .agent-badge.is-clickable:hover {
|
||||
[data-modern-ui="true"] .agent-badge.is-clickable:hover,
|
||||
[data-modern-ui="true"] .step-anomaly-tag {
|
||||
border: none;
|
||||
}
|
||||
|
||||
@@ -5932,6 +6216,7 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .trend-tip-sub,
|
||||
[data-modern-ui="true"] .trend-tip-anomaly,
|
||||
[data-modern-ui="true"] .cons-pop-models {
|
||||
border-top: none;
|
||||
padding-top: 3px;
|
||||
@@ -5992,6 +6277,28 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
|
||||
background: var(--modern-surface-hover);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .data-table tbody tr.is-anomaly-warn,
|
||||
[data-modern-ui="true"] .data-table:not(.is-virtualized) tbody tr.is-anomaly-warn:nth-child(even),
|
||||
[data-modern-ui="true"] .data-table.is-virtualized tbody tr.is-stripe-even.is-anomaly-warn {
|
||||
background: color-mix(in srgb, var(--metric-warn) 12%, transparent);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .data-table tbody tr.is-anomaly-warn:hover,
|
||||
[data-modern-ui="true"] .data-table.is-virtualized tbody tr.is-stripe-even.is-anomaly-warn:hover {
|
||||
background: color-mix(in srgb, var(--metric-warn) 19%, transparent);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .data-table tbody tr.is-anomaly-danger,
|
||||
[data-modern-ui="true"] .data-table:not(.is-virtualized) tbody tr.is-anomaly-danger:nth-child(even),
|
||||
[data-modern-ui="true"] .data-table.is-virtualized tbody tr.is-stripe-even.is-anomaly-danger {
|
||||
background: color-mix(in srgb, var(--metric-danger) 14%, transparent);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .data-table tbody tr.is-anomaly-danger:hover,
|
||||
[data-modern-ui="true"] .data-table.is-virtualized tbody tr.is-stripe-even.is-anomaly-danger:hover {
|
||||
background: color-mix(in srgb, var(--metric-danger) 21%, transparent);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .steps-inline-scope-select .select-trigger,
|
||||
[data-modern-ui="true"] .steps-inline-model-select .select-trigger,
|
||||
[data-modern-ui="true"] .sstep-fit-model-select .select-trigger {
|
||||
@@ -6026,6 +6333,22 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
|
||||
background: var(--accent-primary-soft);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .steps-anomaly-filterbar,
|
||||
[data-modern-ui="true"] .steps-anomaly-strip {
|
||||
border: none;
|
||||
border-radius: var(--radius-xs);
|
||||
background: var(--metric-warn-soft);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .steps-anomaly-filterbar {
|
||||
margin: 4px 2px 2px;
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .sstep-anomaly-dot,
|
||||
[data-modern-ui="true"] .sstep-scatter-dot.is-anomaly {
|
||||
fill: var(--modern-surface-card);
|
||||
}
|
||||
|
||||
/* --- 6. 设置表单、折叠面板、槽位排序与输入控件去边框 --- */
|
||||
[data-modern-ui="true"] .collapsible-body,
|
||||
[data-modern-ui="true"] .settings-action-block + .settings-action-block,
|
||||
@@ -6106,13 +6429,19 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
|
||||
|
||||
[data-modern-ui="true"] .trend-tooltip,
|
||||
[data-modern-ui="true"] .cons-breakdown-popover,
|
||||
[data-modern-ui="true"] .turn-prompt-tip {
|
||||
[data-modern-ui="true"] .turn-prompt-tip,
|
||||
[data-modern-ui="true"] .step-anomaly-tip {
|
||||
border: none;
|
||||
background: var(--modern-surface-card);
|
||||
box-shadow: var(--shadow-popover);
|
||||
animation: anim-modern-tip-fade 150ms var(--ease-modern);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .step-anomaly-tip-list,
|
||||
[data-modern-ui="true"] .step-anomaly-tip-hint {
|
||||
border-top-color: var(--modern-surface-hover);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .trend-tooltip:not(.is-hm-top):not(.is-hm-bottom) {
|
||||
top: 2px;
|
||||
bottom: auto;
|
||||
@@ -6216,10 +6545,18 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
|
||||
[data-modern-ui="true"] .wm-multi-label[data-od-active="1"] {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 18px;
|
||||
line-height: 18px;
|
||||
}
|
||||
|
||||
:host([data-modern-ui="true"]) .wm-slot-text.wm-ctx-pct[data-od-active="1"],
|
||||
:host([data-modern-ui="true"]) .wm-multi-label[data-od-active="1"],
|
||||
[data-modern-ui="true"] .wm-slot-text.wm-ctx-pct[data-od-active="1"],
|
||||
[data-modern-ui="true"] .wm-multi-label[data-od-active="1"] {
|
||||
justify-content: flex-start;
|
||||
}
|
||||
|
||||
:host([data-modern-ui="true"]) .wm-od-digit,
|
||||
[data-modern-ui="true"] .wm-od-digit {
|
||||
display: inline-block;
|
||||
|
||||
@@ -0,0 +1,782 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { readLocalSqliteTrajectory } from '../backend/cli-sqlite-reader.mjs';
|
||||
import { classifyStepAnomalyError, extractModelSteps } from '../trajectory-metrics.mjs';
|
||||
import { buildScopedModelBreakdown } from '../backend/usage-aggregator.mjs';
|
||||
import { createMockDom } from './mock-dom.mjs';
|
||||
import { i18nStore } from '../src/i18n/index.js';
|
||||
import {
|
||||
buildModelAnomalyDiagnostic,
|
||||
buildStepAnomalyDiagnostic,
|
||||
formatAnomalyTagText,
|
||||
formatSpeedMetric,
|
||||
} from '../src/core/formatters.js';
|
||||
import { STEP_COLUMN_REGISTRY } from '../src/registries/stepColumnRegistry.js';
|
||||
import { StepTableWidget } from '../src/components/widgets/StepTableWidget.js';
|
||||
import {
|
||||
createModelFitChart,
|
||||
createSessionLineChart,
|
||||
} from '../src/components/charts/SessionStepCharts.js';
|
||||
import { StepsDetailView } from '../src/views/StepsDetailView.js';
|
||||
import { telemetryStore } from '../src/store/telemetryStore.js';
|
||||
import { uiStore } from '../src/store/uiStore.js';
|
||||
|
||||
function encodeVarint(val) {
|
||||
let v = BigInt(val);
|
||||
if (v < 0n) v = BigInt.asUintN(64, v);
|
||||
const out = [];
|
||||
while (v >= 0x80n) {
|
||||
out.push(Number((v & 0x7fn) | 0x80n));
|
||||
v >>= 7n;
|
||||
}
|
||||
out.push(Number(v));
|
||||
return Buffer.from(out);
|
||||
}
|
||||
|
||||
function encodeFieldVarint(fieldNo, val) {
|
||||
return Buffer.concat([encodeVarint((fieldNo << 3) | 0), encodeVarint(val)]);
|
||||
}
|
||||
|
||||
function encodeFieldBytes(fieldNo, bufOrStr) {
|
||||
const b = Buffer.isBuffer(bufOrStr) ? bufOrStr : Buffer.from(String(bufOrStr), 'utf8');
|
||||
return Buffer.concat([encodeVarint((fieldNo << 3) | 2), encodeVarint(b.length), b]);
|
||||
}
|
||||
|
||||
function encodeTimestamp(sec, nanos = 0) {
|
||||
return Buffer.concat([encodeFieldVarint(1, sec), ...(nanos ? [encodeFieldVarint(2, nanos)] : [])]);
|
||||
}
|
||||
|
||||
function encodeRetryInfo({ error = '', reasonCode = 1, delaySec = 0, delayNanos = 0 } = {}) {
|
||||
const parts = [];
|
||||
if (error) parts.push(encodeFieldBytes(3, error));
|
||||
if (reasonCode) parts.push(encodeFieldVarint(5, reasonCode));
|
||||
if (delaySec || delayNanos) {
|
||||
parts.push(encodeFieldBytes(7, encodeTimestamp(delaySec, delayNanos)));
|
||||
}
|
||||
return Buffer.concat(parts);
|
||||
}
|
||||
|
||||
function encodeStepMeta({
|
||||
createdSec,
|
||||
finishedSec,
|
||||
stepIndex,
|
||||
modelEnumInt = 0,
|
||||
inputTokens = 0,
|
||||
cacheReadTokens = 0,
|
||||
outputTokens = 0,
|
||||
retryInfos = [],
|
||||
}) {
|
||||
const parts = [encodeFieldBytes(1, encodeTimestamp(createdSec))];
|
||||
if (finishedSec) parts.push(encodeFieldBytes(7, encodeTimestamp(finishedSec)));
|
||||
if (modelEnumInt || inputTokens || cacheReadTokens || outputTokens) {
|
||||
const muParts = [];
|
||||
if (modelEnumInt) muParts.push(encodeFieldVarint(1, modelEnumInt));
|
||||
if (inputTokens) muParts.push(encodeFieldVarint(2, inputTokens));
|
||||
if (outputTokens) muParts.push(encodeFieldVarint(3, outputTokens));
|
||||
if (cacheReadTokens) muParts.push(encodeFieldVarint(5, cacheReadTokens));
|
||||
muParts.push(encodeFieldVarint(6, 24));
|
||||
parts.push(encodeFieldBytes(9, Buffer.concat(muParts)));
|
||||
}
|
||||
parts.push(encodeFieldBytes(20, encodeFieldVarint(2, stepIndex)));
|
||||
for (const ri of retryInfos) {
|
||||
parts.push(encodeFieldBytes(28, encodeRetryInfo(ri)));
|
||||
}
|
||||
return Buffer.concat(parts);
|
||||
}
|
||||
|
||||
function encodeErrorMessagePayload({
|
||||
userErrorMessage = '',
|
||||
shortError = '',
|
||||
errorCode = '',
|
||||
shouldShowModel = false,
|
||||
shouldShowUser = false,
|
||||
}) {
|
||||
const errParts = [];
|
||||
if (userErrorMessage) errParts.push(encodeFieldBytes(1, userErrorMessage));
|
||||
if (shortError) errParts.push(encodeFieldBytes(2, shortError));
|
||||
if (errorCode) errParts.push(encodeFieldBytes(7, errorCode));
|
||||
const inner = [encodeFieldBytes(3, Buffer.concat(errParts))];
|
||||
if (shouldShowModel) inner.push(encodeFieldVarint(4, 1));
|
||||
if (shouldShowUser) inner.push(encodeFieldVarint(5, 1));
|
||||
return encodeFieldBytes(24, Buffer.concat(inner));
|
||||
}
|
||||
|
||||
function encodeGenMeta({
|
||||
stepIndex,
|
||||
cascadeId,
|
||||
responseModel,
|
||||
modelDisplayName,
|
||||
retryCount = 0,
|
||||
retryInfos = [],
|
||||
}) {
|
||||
const mapCascade = Buffer.concat([
|
||||
encodeFieldBytes(1, 'cascade_id'),
|
||||
encodeFieldBytes(2, cascadeId),
|
||||
]);
|
||||
const chatParts = [
|
||||
encodeFieldBytes(11, encodeTimestamp(1, 0)),
|
||||
encodeFieldBytes(19, responseModel),
|
||||
encodeFieldBytes(20, mapCascade),
|
||||
encodeFieldBytes(21, modelDisplayName),
|
||||
];
|
||||
if (retryCount > 0) chatParts.push(encodeFieldVarint(14, retryCount));
|
||||
for (const ri of retryInfos) {
|
||||
chatParts.push(encodeFieldBytes(17, encodeRetryInfo(ri)));
|
||||
}
|
||||
return Buffer.concat([
|
||||
encodeFieldVarint(2, stepIndex),
|
||||
encodeFieldBytes(1, Buffer.concat(chatParts)),
|
||||
]);
|
||||
}
|
||||
|
||||
function installMockBrowser() {
|
||||
const prevDoc = globalThis.document;
|
||||
const prevWin = globalThis.window;
|
||||
const prevRaf = globalThis.requestAnimationFrame;
|
||||
const prevCaf = globalThis.cancelAnimationFrame;
|
||||
const prevResizeObs = globalThis.ResizeObserver;
|
||||
const { document } = createMockDom();
|
||||
globalThis.document = document;
|
||||
globalThis.window = {
|
||||
innerWidth: 960,
|
||||
innerHeight: 720,
|
||||
getComputedStyle: () => ({ getPropertyValue: () => '' }),
|
||||
addEventListener: () => {},
|
||||
removeEventListener: () => {},
|
||||
};
|
||||
globalThis.requestAnimationFrame = (fn) => {
|
||||
fn();
|
||||
return 1;
|
||||
};
|
||||
globalThis.cancelAnimationFrame = () => {};
|
||||
globalThis.ResizeObserver = class {
|
||||
observe() {}
|
||||
disconnect() {}
|
||||
};
|
||||
return {
|
||||
document,
|
||||
restore() {
|
||||
globalThis.document = prevDoc;
|
||||
globalThis.window = prevWin;
|
||||
globalThis.requestAnimationFrame = prevRaf;
|
||||
globalThis.cancelAnimationFrame = prevCaf;
|
||||
globalThis.ResizeObserver = prevResizeObs;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test('SQLite protobuf decoder + trajectory-metrics + usage-aggregator decode chatModel retries, checkpoint retries, deduplicated ERROR_MESSAGE, and trailing terminal errors', (t) => {
|
||||
const sqliteMod =
|
||||
typeof process.getBuiltinModule === 'function' ? process.getBuiltinModule('node:sqlite') : null;
|
||||
if (!sqliteMod?.DatabaseSync) {
|
||||
t.skip('node:sqlite DatabaseSync unavailable');
|
||||
return;
|
||||
}
|
||||
const { DatabaseSync } = sqliteMod;
|
||||
const tempRoot = mkdtempSync(join(tmpdir(), 'agy-anomaly-sqlite-'));
|
||||
t.after(() => rmSync(tempRoot, { recursive: true, force: true }));
|
||||
|
||||
const cid = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee';
|
||||
const dbPath = join(tempRoot, `${cid}.db`);
|
||||
const db = new DatabaseSync(dbPath);
|
||||
db.exec(`
|
||||
CREATE TABLE trajectory_meta (trajectory_id TEXT, cascade_id TEXT, trajectory_type INTEGER, source INTEGER);
|
||||
CREATE TABLE steps (idx INTEGER PRIMARY KEY, step_type INTEGER, status INTEGER, metadata BLOB, step_payload BLOB);
|
||||
CREATE TABLE gen_metadata (idx INTEGER PRIMARY KEY, data BLOB);
|
||||
`);
|
||||
db.prepare('INSERT INTO trajectory_meta VALUES (?, ?, 1, 1)').run(cid, cid);
|
||||
|
||||
const baseSec = 1794960000;
|
||||
// Step 0: USER_INPUT (step_type=14)
|
||||
db.prepare('INSERT INTO steps VALUES (0, 14, 3, ?, ?)').run(
|
||||
encodeStepMeta({ createdSec: baseSec, finishedSec: baseSec, stepIndex: 0 }),
|
||||
encodeFieldBytes(19, encodeFieldBytes(2, '帮我排查超时'))
|
||||
);
|
||||
// Step 1: Normal model response (zero anomalies)
|
||||
db.prepare('INSERT INTO steps VALUES (1, 15, 3, ?, ?)').run(
|
||||
encodeStepMeta({
|
||||
createdSec: baseSec + 1,
|
||||
finishedSec: baseSec + 3,
|
||||
stepIndex: 1,
|
||||
modelEnumInt: 1035,
|
||||
inputTokens: 500,
|
||||
cacheReadTokens: 2000,
|
||||
outputTokens: 260,
|
||||
}),
|
||||
encodeFieldBytes(20, encodeFieldBytes(1, 'ok'))
|
||||
);
|
||||
db.prepare('INSERT INTO gen_metadata VALUES (0, ?)').run(
|
||||
encodeGenMeta({
|
||||
stepIndex: 1,
|
||||
cascadeId: cid,
|
||||
responseModel: 'gemini-3-flash',
|
||||
modelDisplayName: 'Gemini 3 Flash',
|
||||
})
|
||||
);
|
||||
|
||||
// Step 2: Preceding ERROR_MESSAGE (duplicate of retryInfo capacity 503) — should be deduplicated against step 3 retryInfos
|
||||
db.prepare('INSERT INTO steps VALUES (2, 17, 3, ?, ?)').run(
|
||||
encodeStepMeta({ createdSec: baseSec + 4, finishedSec: baseSec + 4, stepIndex: 2 }),
|
||||
encodeErrorMessagePayload({
|
||||
shortError: 'HTTP 503 No capacity available for model',
|
||||
errorCode: 'UNAVAILABLE',
|
||||
shouldShowUser: false,
|
||||
})
|
||||
);
|
||||
// Step 3: Retried model response with 2 retryInfos (timeout 2.5s + capacity 5s)
|
||||
db.prepare('INSERT INTO steps VALUES (3, 15, 3, ?, ?)').run(
|
||||
encodeStepMeta({
|
||||
createdSec: baseSec + 5,
|
||||
finishedSec: baseSec + 15,
|
||||
stepIndex: 3,
|
||||
modelEnumInt: 1035,
|
||||
inputTokens: 600,
|
||||
cacheReadTokens: 3000,
|
||||
outputTokens: 300,
|
||||
}),
|
||||
encodeFieldBytes(20, encodeFieldBytes(1, 'retried ok'))
|
||||
);
|
||||
db.prepare('INSERT INTO gen_metadata VALUES (1, ?)').run(
|
||||
encodeGenMeta({
|
||||
stepIndex: 3,
|
||||
cascadeId: cid,
|
||||
responseModel: 'gemini-3-flash',
|
||||
modelDisplayName: 'Gemini 3 Flash',
|
||||
retryCount: 2,
|
||||
retryInfos: [
|
||||
{
|
||||
error: 'stream idle timeout: no data received for 60s',
|
||||
reasonCode: 1,
|
||||
delaySec: 2,
|
||||
delayNanos: 500_000_000,
|
||||
},
|
||||
{
|
||||
error: 'HTTP 503 No capacity available for model',
|
||||
reasonCode: 1,
|
||||
delaySec: 5,
|
||||
},
|
||||
],
|
||||
})
|
||||
);
|
||||
|
||||
// Step 4: CHECKPOINT (step_type=18) with metadata.fn=28 retryInfo (model_output)
|
||||
db.prepare('INSERT INTO steps VALUES (4, 18, 3, ?, NULL)').run(
|
||||
encodeStepMeta({
|
||||
createdSec: baseSec + 16,
|
||||
finishedSec: baseSec + 19,
|
||||
stepIndex: 4,
|
||||
modelEnumInt: 1035,
|
||||
inputTokens: 400,
|
||||
outputTokens: 120,
|
||||
retryInfos: [
|
||||
{
|
||||
error: 'invalid tool call arguments JSON',
|
||||
reasonCode: 2,
|
||||
delaySec: 1,
|
||||
},
|
||||
],
|
||||
})
|
||||
);
|
||||
|
||||
// Step 5: Model step followed by turn-ending terminal ERROR_MESSAGE (status=7 CORTEX_STEP_STATUS_ERROR)
|
||||
db.prepare('INSERT INTO steps VALUES (5, 15, 7, ?, ?)').run(
|
||||
encodeStepMeta({
|
||||
createdSec: baseSec + 20,
|
||||
finishedSec: baseSec + 25,
|
||||
stepIndex: 5,
|
||||
modelEnumInt: 1035,
|
||||
inputTokens: 200,
|
||||
outputTokens: 0,
|
||||
}),
|
||||
encodeFieldBytes(20, encodeFieldBytes(1, ''))
|
||||
);
|
||||
db.prepare('INSERT INTO gen_metadata VALUES (2, ?)').run(
|
||||
encodeGenMeta({
|
||||
stepIndex: 5,
|
||||
cascadeId: cid,
|
||||
responseModel: 'gemini-3-pro',
|
||||
modelDisplayName: 'Gemini 3 Pro',
|
||||
})
|
||||
);
|
||||
// Step 6: Trailing terminal ERROR_MESSAGE (should attach to step 5)
|
||||
db.prepare('INSERT INTO steps VALUES (6, 17, 3, ?, ?)').run(
|
||||
encodeStepMeta({ createdSec: baseSec + 25, finishedSec: baseSec + 25, stepIndex: 6 }),
|
||||
encodeErrorMessagePayload({
|
||||
userErrorMessage: 'TLS handshake timeout while reaching upstream',
|
||||
shortError: 'dial tcp: TLS handshake timeout',
|
||||
errorCode: 'DEADLINE_EXCEEDED',
|
||||
shouldShowUser: true,
|
||||
})
|
||||
);
|
||||
db.close();
|
||||
|
||||
const traj = readLocalSqliteTrajectory(dbPath);
|
||||
assert.ok(traj, 'SQLite trajectory decoded');
|
||||
const gen1 = traj.generatorMetadata.find((g) => g.stepIndices?.includes(3));
|
||||
assert.equal(gen1?.chatModel?.retryCount, 2);
|
||||
assert.equal(gen1?.chatModel?.retryInfos?.length, 2);
|
||||
assert.equal(gen1?.chatModel?.retryInfos?.[0]?.retryDelay, '2.5s');
|
||||
assert.equal(traj.steps[4]?.metadata?.retryInfos?.length, 1);
|
||||
assert.equal(traj.steps[6]?.errorMessage?.shouldShowUser, true);
|
||||
assert.match(traj.steps[6]?.errorMessage?.error?.userErrorMessage || '', /TLS handshake timeout/);
|
||||
|
||||
const extracted = extractModelSteps(traj.steps, traj.generatorMetadata);
|
||||
const s1 = extracted.find((s) => s.stepIndex === 1);
|
||||
const s3 = extracted.find((s) => s.stepIndex === 3);
|
||||
const s4 = extracted.find((s) => s.stepIndex === 4);
|
||||
const s5 = extracted.find((s) => s.stepIndex === 5);
|
||||
|
||||
assert.equal(s1.anomaly, undefined, 'Normal step carries zero anomaly payload');
|
||||
assert.equal(s1.anomalySig, undefined, 'Normal step omits anomalySig');
|
||||
|
||||
assert.ok(s3.anomaly, 'Step 3 has anomaly record');
|
||||
assert.equal(s3.anomaly.count, 2, 'Duplicate preceding 503 ERROR_MESSAGE is deduplicated against retryInfos');
|
||||
assert.equal(s3.anomaly.totalDelaySec, 7.5);
|
||||
assert.equal(s3.anomaly.kinds.timeout, 1);
|
||||
assert.equal(s3.anomaly.kinds.capacity, 1);
|
||||
assert.equal(s3.anomaly.severity, 'warn');
|
||||
|
||||
assert.ok(s4.anomaly, 'Checkpoint step 4 decodes metadata.fn=28 retryInfo');
|
||||
assert.equal(s4.anomaly.primaryKind, 'model_output');
|
||||
assert.equal(s4.anomaly.count, 1);
|
||||
|
||||
assert.ok(s5.anomaly, 'Trailing turn-ending ERROR_MESSAGE attaches to step 5');
|
||||
assert.equal(s5.anomaly.primaryKind, 'timeout');
|
||||
assert.equal(s5.anomaly.severity, 'danger', 'Terminal error escalates severity to danger');
|
||||
assert.equal(s5.anomaly.events[0]?.terminal, true);
|
||||
assert.equal(s5.speedReason, 'error');
|
||||
assert.equal(s5.totalTokPerSec, null);
|
||||
|
||||
// Also check classifyStepAnomalyError directly for rate_limit & safety
|
||||
assert.equal(classifyStepAnomalyError('HTTP 429 RESOURCE_EXHAUSTED quota exceeded'), 'rate_limit');
|
||||
assert.equal(classifyStepAnomalyError('blocked by safety filter policy'), 'safety');
|
||||
|
||||
const breakdown = buildScopedModelBreakdown(extracted, (st) => ({
|
||||
label: st.responseModel || 'Unknown',
|
||||
shortName: st.responseModel || 'Unknown',
|
||||
rawModel: st.model || '',
|
||||
upstreamName: st.responseModel || '',
|
||||
costUsd: 0.01,
|
||||
}));
|
||||
const flash = breakdown.find((m) => m.label === 'gemini-3-flash');
|
||||
const pro = breakdown.find((m) => m.label === 'gemini-3-pro');
|
||||
assert.ok(flash && pro);
|
||||
assert.equal(flash.anomalySteps, 1);
|
||||
assert.equal(flash.anomalyCount, 2);
|
||||
assert.equal(flash.anomalyTotalDelaySec, 7.5);
|
||||
assert.equal(pro.anomalySteps, 1);
|
||||
assert.equal(pro.anomalyCount, 1);
|
||||
assert.equal(pro.anomalyDangerCount, 1);
|
||||
assert.equal(pro.anomalyByKind.timeout, 1);
|
||||
});
|
||||
|
||||
test('formatSpeedMetric drops decimals at >= 100 tok/s and STEP_COLUMN_REGISTRY.tps renders integer speeds and error reasons', () => {
|
||||
const env = installMockBrowser();
|
||||
try {
|
||||
i18nStore.setState({ locale: 'zh-CN' });
|
||||
|
||||
assert.equal(formatSpeedMetric(100), '100 tok/s');
|
||||
assert.equal(formatSpeedMetric(128.4), '128 tok/s');
|
||||
assert.equal(formatSpeedMetric(145.6), '146 tok/s');
|
||||
assert.equal(formatSpeedMetric(99.9), '99.9 tok/s');
|
||||
assert.equal(formatSpeedMetric(65.7), '65.7 tok/s');
|
||||
assert.equal(formatSpeedMetric(0), '0.0 tok/s');
|
||||
assert.equal(formatSpeedMetric(null), '—');
|
||||
|
||||
const fastCell = STEP_COLUMN_REGISTRY.tps.createCell();
|
||||
STEP_COLUMN_REGISTRY.tps.updateCell(fastCell.refs, { tokPerSec: 128.4 }, { showStepSpeedColor: false });
|
||||
assert.equal(fastCell.refs.speedMain.textContent, '128 tok/s');
|
||||
|
||||
STEP_COLUMN_REGISTRY.tps.updateCell(fastCell.refs, { tokPerSec: 65.7 }, { showStepSpeedColor: false });
|
||||
assert.equal(fastCell.refs.speedMain.textContent, '65.7 tok/s');
|
||||
|
||||
STEP_COLUMN_REGISTRY.tps.updateCell(
|
||||
fastCell.refs,
|
||||
{ tokPerSec: null, selectedSpeedReason: 'error' },
|
||||
{ showStepSpeedColor: false }
|
||||
);
|
||||
assert.equal(fastCell.refs.speedMain.textContent, '—');
|
||||
assert.equal(fastCell.refs.speedReason.textContent, '调用报错');
|
||||
} finally {
|
||||
env.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('StepTableWidget tints entire anomaly rows with zero extra column width and reveals full diagnostic popover on row hover', () => {
|
||||
const env = installMockBrowser();
|
||||
const widget = StepTableWidget({ standalone: true });
|
||||
try {
|
||||
i18nStore.setState({ locale: 'zh-CN' });
|
||||
|
||||
const colKeys = ['step', 'model', 'tps', 'ttft'];
|
||||
const steps = [
|
||||
{
|
||||
stepIndex: 4924,
|
||||
modelShort: '4-neon',
|
||||
modelLabel: '4-neon',
|
||||
tokPerSec: 132.6,
|
||||
ttftSec: 2.1,
|
||||
anomalySig: 'timeout:1:w:2.5',
|
||||
anomaly: {
|
||||
count: 1,
|
||||
primaryKind: 'timeout',
|
||||
severity: 'warn',
|
||||
totalDelaySec: 2.5,
|
||||
kinds: { timeout: 1 },
|
||||
events: [
|
||||
{
|
||||
attempt: 1,
|
||||
kind: 'timeout',
|
||||
delaySec: 2.5,
|
||||
terminal: false,
|
||||
message: 'stream idle timeout: no data received',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
stepIndex: 4922,
|
||||
modelShort: '4-neon',
|
||||
modelLabel: '4-neon',
|
||||
tokPerSec: null,
|
||||
selectedSpeedReason: 'error',
|
||||
ttftSec: null,
|
||||
anomalySig: 'rate_limit:1:d:0',
|
||||
anomaly: {
|
||||
count: 1,
|
||||
primaryKind: 'rate_limit',
|
||||
severity: 'danger',
|
||||
totalDelaySec: 0,
|
||||
kinds: { rate_limit: 1 },
|
||||
events: [
|
||||
{
|
||||
attempt: 1,
|
||||
kind: 'rate_limit',
|
||||
delaySec: 0,
|
||||
terminal: true,
|
||||
message: 'HTTP 429 RESOURCE_EXHAUSTED',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
stepIndex: 4920,
|
||||
modelShort: '4-neon',
|
||||
modelLabel: '4-neon',
|
||||
tokPerSec: 65.7,
|
||||
ttftSec: 1.4,
|
||||
anomalySig: '',
|
||||
},
|
||||
];
|
||||
|
||||
widget.refs.renderStepTable(steps, 'cid-1', colKeys, 'zh-CN', {
|
||||
hasSubagents: false,
|
||||
showStepAgentBadge: true,
|
||||
showStepTurnRail: false,
|
||||
});
|
||||
|
||||
// Zero extra columns and zero inline text badges added to table cells
|
||||
assert.equal(widget.refs.stepsTheadRow.children.length, colKeys.length);
|
||||
const rows = widget.refs.stepsTbody.children;
|
||||
assert.equal(rows.length, 3);
|
||||
assert.equal(rows[0].children.length, colKeys.length);
|
||||
assert.equal(rows[0].querySelector('.step-anomaly-tag'), null, 'No inline tag widening the #step column');
|
||||
|
||||
// Row 0: warn tint (orange) + integer speed 133 tok/s
|
||||
assert.equal(rows[0].classList.contains('is-anomaly-warn'), true);
|
||||
assert.equal(rows[0].classList.contains('is-anomaly-danger'), false);
|
||||
assert.equal(rows[0].children[2].textContent, '133 tok/s');
|
||||
|
||||
// Row 1: danger tint (red)
|
||||
assert.equal(rows[1].classList.contains('is-anomaly-danger'), true);
|
||||
assert.equal(rows[1].classList.contains('is-anomaly-warn'), false);
|
||||
|
||||
// Row 2: normal step has NO anomaly row classes and keeps 1 decimal < 100 tok/s
|
||||
assert.equal(rows[2].classList.contains('is-anomaly-warn'), false);
|
||||
assert.equal(rows[2].classList.contains('is-anomaly-danger'), false);
|
||||
assert.equal(rows[2].children[2].textContent, '65.7 tok/s');
|
||||
|
||||
// Hovering the tinted row expands the structured diagnostic popover
|
||||
const tipEl = widget.refs.anomalyTipEl;
|
||||
assert.equal(tipEl.hasAttribute('hidden'), true);
|
||||
rows[0].onmouseenter();
|
||||
assert.equal(tipEl.hasAttribute('hidden'), false);
|
||||
assert.match(tipEl.querySelector('.step-anomaly-tip-title').textContent, /#4924.*异常 1 次/);
|
||||
assert.equal(tipEl.querySelector('.step-anomaly-tip-sub').textContent, '退避 2.5s');
|
||||
assert.match(tipEl.querySelector('.step-anomaly-tip-detail').textContent, /stream idle timeout/);
|
||||
|
||||
rows[0].onmouseleave();
|
||||
assert.equal(tipEl.hasAttribute('hidden'), true);
|
||||
|
||||
// Hovering danger row sets danger style on tooltip
|
||||
rows[1].onmouseenter();
|
||||
assert.equal(tipEl.hasAttribute('hidden'), false);
|
||||
assert.equal(tipEl.classList.contains('is-danger'), true);
|
||||
assert.match(tipEl.querySelector('.step-anomaly-tip-detail').textContent, /429 RESOURCE_EXHAUSTED/);
|
||||
rows[1].onmouseleave();
|
||||
assert.equal(tipEl.hasAttribute('hidden'), true);
|
||||
|
||||
// Verify helper outputs cleanly
|
||||
assert.equal(formatAnomalyTagText('capacity', 1), '503');
|
||||
assert.equal(formatAnomalyTagText('capacity', 3), '503×3');
|
||||
assert.ok(buildStepAnomalyDiagnostic(steps[0]));
|
||||
assert.equal(buildStepAnomalyDiagnostic(steps[2]), null);
|
||||
} finally {
|
||||
widget.destroy();
|
||||
env.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('StepsDetailView total summary cards, session anomaly strip, click-to-filter jump, and line/fit chart anomaly markers & hover tooltips work across UI modes', async () => {
|
||||
const env = installMockBrowser();
|
||||
const prevUi = uiStore.getState();
|
||||
const prevTel = telemetryStore.getState();
|
||||
let view = null;
|
||||
let lineChart = null;
|
||||
let fitChart = null;
|
||||
try {
|
||||
i18nStore.setState({ locale: 'zh-CN' });
|
||||
view = StepsDetailView();
|
||||
|
||||
const anomalyObj = {
|
||||
count: 2,
|
||||
primaryKind: 'timeout',
|
||||
severity: 'danger',
|
||||
totalDelaySec: 4.5,
|
||||
kinds: { timeout: 2 },
|
||||
events: [
|
||||
{ attempt: 1, kind: 'timeout', delaySec: 2, terminal: false, message: 'idle timeout #1' },
|
||||
{ attempt: 2, kind: 'timeout', delaySec: 2.5, terminal: true, message: 'TLS handshake timeout' },
|
||||
],
|
||||
};
|
||||
|
||||
const recentSteps = [
|
||||
{
|
||||
stepIndex: 10,
|
||||
createdAtMs: 1794960100000,
|
||||
modelLabel: 'Gemini 3 Pro',
|
||||
modelShort: '3-pro',
|
||||
tokPerSec: 120.4,
|
||||
ttftSec: 1.5,
|
||||
inputTokens: 1000,
|
||||
cacheReadTokens: 4000,
|
||||
outputTokens: 300,
|
||||
thinkingTokens: 100,
|
||||
responseTokens: 200,
|
||||
contextTokens: 5300,
|
||||
cacheHitPct: 80,
|
||||
costUsd: 0.02,
|
||||
anomalySig: 'timeout:2:d:4.5',
|
||||
anomaly: anomalyObj,
|
||||
},
|
||||
{
|
||||
stepIndex: 9,
|
||||
createdAtMs: 1794960050000,
|
||||
modelLabel: 'Gemini 3 Flash',
|
||||
modelShort: '3-flash',
|
||||
tokPerSec: 88.2,
|
||||
ttftSec: 0.9,
|
||||
inputTokens: 500,
|
||||
cacheReadTokens: 2000,
|
||||
outputTokens: 150,
|
||||
thinkingTokens: 50,
|
||||
responseTokens: 100,
|
||||
contextTokens: 2650,
|
||||
cacheHitPct: 80,
|
||||
costUsd: 0.005,
|
||||
anomalySig: '',
|
||||
},
|
||||
];
|
||||
|
||||
const modelBreakdown = [
|
||||
{
|
||||
label: 'Gemini 3 Pro',
|
||||
shortName: '3-pro',
|
||||
calls: 1,
|
||||
inputTokens: 1000,
|
||||
cacheReadTokens: 4000,
|
||||
outputTokens: 300,
|
||||
thinkingTokens: 100,
|
||||
responseTokens: 200,
|
||||
totalTokens: 5300,
|
||||
costUsd: 0.02,
|
||||
avgTokPerSec: 120.4,
|
||||
avgTtftSec: 1.5,
|
||||
cacheHitPct: 80,
|
||||
anomalySteps: 1,
|
||||
anomalyCount: 2,
|
||||
anomalyDangerCount: 1,
|
||||
anomalyTotalDelaySec: 4.5,
|
||||
anomalyByKind: { timeout: 2 },
|
||||
},
|
||||
{
|
||||
label: 'Gemini 3 Flash',
|
||||
shortName: '3-flash',
|
||||
calls: 1,
|
||||
inputTokens: 500,
|
||||
cacheReadTokens: 2000,
|
||||
outputTokens: 150,
|
||||
thinkingTokens: 50,
|
||||
responseTokens: 100,
|
||||
totalTokens: 2650,
|
||||
costUsd: 0.005,
|
||||
avgTokPerSec: 88.2,
|
||||
avgTtftSec: 0.9,
|
||||
cacheHitPct: 80,
|
||||
},
|
||||
];
|
||||
|
||||
uiStore.setState({
|
||||
monitorVisible: true,
|
||||
activeView: 'steps',
|
||||
stepsSubTab: 'models',
|
||||
selectedAgentScope: 'all',
|
||||
});
|
||||
telemetryStore.setState({
|
||||
telemetry: {
|
||||
settings: {
|
||||
stepTableColumns: ['step', 'model', 'tps', 'ttft'],
|
||||
experimentalModernUi: false,
|
||||
},
|
||||
activeConversation: {
|
||||
cascadeId: 'cid-summary-test',
|
||||
recentSteps,
|
||||
modelBreakdown,
|
||||
},
|
||||
},
|
||||
});
|
||||
await Promise.resolve();
|
||||
|
||||
// Session-level anomaly strip is visible with timeout tag
|
||||
const stripEl = view.refs.modelsAnomalyStripEl;
|
||||
assert.equal(stripEl.hasAttribute('hidden'), false);
|
||||
assert.match(stripEl.textContent, /异常 2 次.*1 步/);
|
||||
|
||||
// Model summary cards: Pro shows danger anomaly badge + integer 120 tok/s; Flash hides badge + keeps 88.2 tok/s
|
||||
const cards = view.refs.modelsListEl.querySelectorAll('.smodel-card');
|
||||
assert.equal(cards.length, 2);
|
||||
const proBadge = cards[0].querySelector('.smodel-anomaly-tag');
|
||||
const flashBadge = cards[1].querySelector('.smodel-anomaly-tag');
|
||||
assert.equal(proBadge.hasAttribute('hidden'), false);
|
||||
assert.equal(proBadge.textContent, '超时2');
|
||||
assert.equal(proBadge.classList.contains('is-danger'), true);
|
||||
assert.match(cards[0].querySelector('.smodel-perf').textContent, /120 tok\/s/);
|
||||
assert.equal(flashBadge.hasAttribute('hidden'), true);
|
||||
assert.match(cards[1].querySelector('.smodel-perf').textContent, /88\.2 tok\/s/);
|
||||
|
||||
// Hovering model card anomaly badge opens diagnostic popover with click hint
|
||||
const modelDiag = buildModelAnomalyDiagnostic(modelBreakdown[0]);
|
||||
assert.ok(modelDiag && modelDiag.hint);
|
||||
proBadge.onmouseenter();
|
||||
assert.equal(view.refs.anomalyTipEl.hasAttribute('hidden'), false);
|
||||
assert.match(view.refs.anomalyTipEl.querySelector('.step-anomaly-tip-hint').textContent, /按步查看/);
|
||||
proBadge.onmouseleave();
|
||||
assert.equal(view.refs.anomalyTipEl.hasAttribute('hidden'), true);
|
||||
|
||||
// Clicking model card anomaly badge jumps to 'steps', activates anomaly filterbar, and filters to only anomaly step #10
|
||||
proBadge.onclick({ stopPropagation() {} });
|
||||
await Promise.resolve();
|
||||
assert.equal(uiStore.getState().stepsSubTab, 'steps');
|
||||
assert.equal(view.refs.anomalyFilterBarEl.hasAttribute('hidden'), false);
|
||||
assert.equal(view.refs.stepsTbody.children.length, 1);
|
||||
assert.match(view.refs.stepsTbody.children[0].children[0].textContent, /#10/);
|
||||
|
||||
// Clicking "返回全部步骤" restores all rows and hides the filterbar
|
||||
view.refs.anomalyFilterBarEl
|
||||
.querySelector('.steps-anomaly-filter-clear')
|
||||
.dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
assert.equal(view.refs.anomalyFilterBarEl.hasAttribute('hidden'), true);
|
||||
assert.equal(view.refs.stepsTbody.children.length, 1);
|
||||
|
||||
// Switch back to 'models' and click a session-level anomaly strip category pill -> jumps to 'steps' filtered by kind
|
||||
uiStore.setState({ stepsSubTab: 'models' });
|
||||
await Promise.resolve();
|
||||
const stripTagBtn = stripEl.querySelector('.smodel-anomaly-tag');
|
||||
assert.ok(stripTagBtn, 'Session anomaly strip renders clickable category micro-tag');
|
||||
assert.equal(stripTagBtn.textContent, '超时2');
|
||||
stripTagBtn.dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await Promise.resolve();
|
||||
assert.equal(uiStore.getState().stepsSubTab, 'steps');
|
||||
assert.equal(view.refs.anomalyFilterBarEl.hasAttribute('hidden'), false);
|
||||
assert.match(view.refs.anomalyFilterBarEl.textContent, /流空闲 \/ 连接超时/);
|
||||
assert.equal(view.refs.stepsTbody.children.length, 1);
|
||||
|
||||
// Line chart (>64 points still renders anomaly ring overlay!) and Fit chart scatter anomaly overlay + hover tooltip linkage
|
||||
const manySteps = Array.from({ length: 70 }, (_, idx) => ({
|
||||
stepIndex: idx + 1,
|
||||
createdAtMs: 1794960000000 + idx * 1000,
|
||||
modelLabel: 'Gemini 3 Pro',
|
||||
modelShort: '3-pro',
|
||||
tokPerSec: 90 + (idx % 25),
|
||||
ttftSec: 1.2,
|
||||
inputTokens: 1000,
|
||||
cacheReadTokens: 3000,
|
||||
outputTokens: 200,
|
||||
contextTokens: 4200,
|
||||
cacheHitPct: 75,
|
||||
costUsd: 0.01,
|
||||
...(idx === 35 ? { anomalySig: 'timeout:2:d:4.5', anomaly: anomalyObj } : { anomalySig: '' }),
|
||||
}));
|
||||
|
||||
lineChart = createSessionLineChart();
|
||||
lineChart.update({
|
||||
steps: manySteps,
|
||||
modelGroupKey: '__all__',
|
||||
modelGroupKeys: ['__all__'],
|
||||
metric: 'tps',
|
||||
});
|
||||
const lineAnomalyDots = lineChart.el.querySelectorAll('.sstep-anomaly-dot');
|
||||
assert.equal(lineAnomalyDots.length, 1, 'Line chart renders anomaly ring marker even when steps > 64');
|
||||
assert.equal(lineAnomalyDots[0].classList.contains('is-danger'), true);
|
||||
|
||||
fitChart = createModelFitChart();
|
||||
fitChart.update({
|
||||
steps: manySteps,
|
||||
modelGroupKey: 'Gemini 3 Pro',
|
||||
modelGroupKeys: ['Gemini 3 Pro'],
|
||||
metric: 'tps',
|
||||
});
|
||||
const fitAnomalyDots = fitChart.el.querySelectorAll('.sstep-scatter-dot.is-anomaly');
|
||||
assert.equal(fitAnomalyDots.length, 1, 'Fit scatter chart renders anomaly ring overlay without overdraw drop');
|
||||
assert.equal(fitAnomalyDots[0].classList.contains('is-danger'), true);
|
||||
assert.ok(fitChart.el.querySelector('.trend-tip-anomaly'), 'Fit chart tooltip mounts linked anomaly diagnostic row');
|
||||
} finally {
|
||||
lineChart?.destroy?.();
|
||||
fitChart?.destroy?.();
|
||||
view?.destroy?.();
|
||||
uiStore.setState(prevUi);
|
||||
telemetryStore.setState(prevTel);
|
||||
env.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('Compiled styles.css centers odometer capsule slot text and ships both classic & modern-ui anomaly styles', () => {
|
||||
const builtCss = readFileSync(new URL('../styles.css', import.meta.url), 'utf8');
|
||||
|
||||
// Capsule bar alignment fix: centered by default for fixed-width slots, flex-start for ctx-pct and multi-label
|
||||
assert.match(
|
||||
builtCss,
|
||||
/\.wm-slot-text\[data-od-active="1"\][\s\S]*?justify-content:\s*center;/,
|
||||
'Odometer active slot text centers horizontally inside fixed-width capsule slots'
|
||||
);
|
||||
assert.match(
|
||||
builtCss,
|
||||
/\.wm-slot-text\.wm-ctx-pct\[data-od-active="1"\][\s\S]*?justify-content:\s*flex-start;/,
|
||||
'Context percentage slot stays left-aligned next to its progress ring'
|
||||
);
|
||||
|
||||
// Universal Classic + Modern UI anomaly styling
|
||||
assert.match(builtCss, /tr\.is-anomaly-warn\s*\{/);
|
||||
assert.match(builtCss, /tr\.is-anomaly-danger\s*\{/);
|
||||
assert.match(builtCss, /\[data-modern-ui="true"\][\s\S]*?tr\.is-anomaly-warn/);
|
||||
assert.match(builtCss, /\.step-anomaly-tag\s*\{/);
|
||||
assert.match(builtCss, /\.step-anomaly-tip\s*\{/);
|
||||
assert.match(builtCss, /\.steps-anomaly-strip\s*\{/);
|
||||
assert.match(builtCss, /\.steps-anomaly-filterbar\s*\{/);
|
||||
assert.match(builtCss, /\.sstep-anomaly-dot/);
|
||||
assert.match(builtCss, /\.trend-tip-anomaly/);
|
||||
assert.match(builtCss, /\[data-modern-ui="true"\]\s*\.step-anomaly-tip/);
|
||||
});
|
||||
@@ -2474,7 +2474,7 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
|
||||
smodelCards = modelsAnalyticsPane.querySelectorAll('.smodel-card');
|
||||
assert.equal(smodelCards.length, 1, 'Scoped to subagent #1 model only');
|
||||
assert.equal(smodelCards[0].querySelector('.smodel-name').textContent, 'gemini-3-flash');
|
||||
assert.match(fitCard.querySelector('.cons-badge').textContent, /^1步 · 均 145\.0 tok\/s$/);
|
||||
assert.match(fitCard.querySelector('.cons-badge').textContent, /^1步 · 均 145 tok\/s$/);
|
||||
assert.equal(
|
||||
lineModelSelectEl.hasAttribute('hidden'),
|
||||
true,
|
||||
|
||||
@@ -597,6 +597,260 @@ export function extractContextBreakdown(chat) {
|
||||
};
|
||||
}
|
||||
|
||||
const ANOMALY_SEVERITY_PRIORITY = Object.freeze({
|
||||
rate_limit: 9,
|
||||
auth_or_model: 8,
|
||||
timeout: 7,
|
||||
capacity: 6,
|
||||
disconnect: 5,
|
||||
upstream: 4,
|
||||
model_output: 3,
|
||||
safety: 2,
|
||||
error: 1,
|
||||
canceled: 0,
|
||||
});
|
||||
|
||||
/**
|
||||
* 将模型调用重试、超时或错误文本归类为标准化异常类型。
|
||||
*
|
||||
* @param {string} [rawError='']
|
||||
* @param {{ reasonCode?: number, errorCode?: number, isCanceled?: boolean }} [opts]
|
||||
* @returns {'timeout'|'rate_limit'|'capacity'|'disconnect'|'upstream'|'model_output'|'safety'|'auth_or_model'|'canceled'|'error'}
|
||||
*/
|
||||
export function classifyStepAnomalyError(
|
||||
rawError = '',
|
||||
{ reasonCode = 0, errorCode = 0, isCanceled = false } = {}
|
||||
) {
|
||||
const s = String(rawError || '').trim();
|
||||
if (isCanceled || /context canceled by user|stream reading error:\s*context canceled/i.test(s)) {
|
||||
return 'canceled';
|
||||
}
|
||||
if (reasonCode === 2 || /model output error|model produced invalid output|invalid tool call/i.test(s)) {
|
||||
return 'model_output';
|
||||
}
|
||||
if (
|
||||
errorCode === 429 ||
|
||||
/\b429\b|RESOURCE_EXHAUSTED|quota reached|rate.?limit/i.test(s)
|
||||
) {
|
||||
return 'rate_limit';
|
||||
}
|
||||
if (
|
||||
/stream idle timeout|TLS handshake timeout|i\/o timeout|context deadline exceeded|\btimeout\b/i.test(
|
||||
s
|
||||
)
|
||||
) {
|
||||
return 'timeout';
|
||||
}
|
||||
if (
|
||||
errorCode === 503 ||
|
||||
/\b503\b|UNAVAILABLE|No capacity available|overloaded|high demand/i.test(s)
|
||||
) {
|
||||
return 'capacity';
|
||||
}
|
||||
if (
|
||||
/wsarecv|wsasend|forcibly closed|connection reset|broken pipe|ECONNRESET|unexpected EOF|:\s*EOF\b|The stream was interrupted|no such host|dial tcp|tls:|bad record MAC/i.test(
|
||||
s
|
||||
)
|
||||
) {
|
||||
return 'disconnect';
|
||||
}
|
||||
if (/safety filter|content safety|sensitive words/i.test(s)) {
|
||||
return 'safety';
|
||||
}
|
||||
if (
|
||||
errorCode === 500 ||
|
||||
errorCode === 502 ||
|
||||
errorCode === 504 ||
|
||||
/\b(?:500|502|504)\b|\bINTERNAL\b|BAD_GATEWAY/i.test(s)
|
||||
) {
|
||||
return 'upstream';
|
||||
}
|
||||
if (
|
||||
errorCode === 400 ||
|
||||
errorCode === 401 ||
|
||||
errorCode === 403 ||
|
||||
errorCode === 404 ||
|
||||
/\b(?:400|401|403|404)\b|PERMISSION_DENIED|UNAUTHENTICATED|FAILED_PRECONDITION|NOT_FOUND|unknown model|unsupported mime/i.test(
|
||||
s
|
||||
)
|
||||
) {
|
||||
return 'auth_or_model';
|
||||
}
|
||||
return 'error';
|
||||
}
|
||||
|
||||
function cleanAnomalyErrorExcerpt(rawText) {
|
||||
let s = String(rawText || '')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
if (!s) return '';
|
||||
s = s.replace(/^API error \(attempt \d+\):\s*/i, '');
|
||||
s = s.replace(/^agent executor error:\s*generating and executing:\s*/i, '');
|
||||
s = s.replace(/^request failed:\s*/i, '');
|
||||
return s.length > 180 ? `${s.slice(0, 179)}…` : s;
|
||||
}
|
||||
|
||||
function extractErrorStepPayload(step) {
|
||||
if (!step || typeof step !== 'object') return null;
|
||||
const em = step.errorMessage;
|
||||
const errObj = em?.error && typeof em.error === 'object' ? em.error : em;
|
||||
const shortErr = String(
|
||||
errObj?.shortError ||
|
||||
errObj?.message ||
|
||||
step.error ||
|
||||
''
|
||||
).trim();
|
||||
const userMsg = String(errObj?.userErrorMessage || '').trim();
|
||||
const fallbackContent =
|
||||
!shortErr && !userMsg && typeof step.content === 'string'
|
||||
? step.content.replace(/^Error:\s*/i, '').trim()
|
||||
: '';
|
||||
const message = shortErr || userMsg || fallbackContent;
|
||||
if (!message) return null;
|
||||
const errorCode = Number(errObj?.errorCode || 0) || 0;
|
||||
const terminal = Boolean(em?.shouldShowUser);
|
||||
return { message, userMsg, errorCode, terminal };
|
||||
}
|
||||
|
||||
function buildStepAnomalyRecord(step, meta, chat, pendingErrorSteps = []) {
|
||||
const retryInfosRaw = [
|
||||
...(Array.isArray(chat?.retryInfos) ? chat.retryInfos : []),
|
||||
...(Array.isArray(meta?.retryInfos) ? meta.retryInfos : []),
|
||||
];
|
||||
const retryErrorEntries = [];
|
||||
for (let i = 0; i < retryInfosRaw.length; i += 1) {
|
||||
const ri = retryInfosRaw[i];
|
||||
if (!ri || typeof ri !== 'object') continue;
|
||||
const errText = String(ri.error || ri.errorMessage || '').trim();
|
||||
const reasonCode = Number(ri.reasonCode || 0) || 0;
|
||||
const delaySec = duration(ri.retryDelay);
|
||||
if (!errText && !(reasonCode > 0 && reasonCode !== 3)) continue;
|
||||
const kind = classifyStepAnomalyError(errText, { reasonCode });
|
||||
// 纯用户取消且无其他重试时不重复打告警微标(速度列已有「已取消」)
|
||||
if (kind === 'canceled') continue;
|
||||
retryErrorEntries.push({
|
||||
attempt: retryErrorEntries.length + 1,
|
||||
kind,
|
||||
delaySec: delaySec != null && delaySec > 0 ? +delaySec.toFixed(1) : 0,
|
||||
message: cleanAnomalyErrorExcerpt(errText),
|
||||
terminal: reasonCode === 3,
|
||||
source: 'retry',
|
||||
});
|
||||
}
|
||||
|
||||
const events = [...retryErrorEntries];
|
||||
const declaredRetryCount = Math.max(0, Math.floor(Number(chat?.retryCount || 0)));
|
||||
|
||||
// 合并同一轮前置 ERROR_MESSAGE 步骤(对已被 retryInfos 记录的同源重试做去重,保留断流续跑/安全过滤/离线日志补充)
|
||||
const usedRetryKinds = new Map();
|
||||
for (const ev of retryErrorEntries) {
|
||||
usedRetryKinds.set(ev.kind, (usedRetryKinds.get(ev.kind) || 0) + 1);
|
||||
}
|
||||
const matchedKindBudget = new Map(usedRetryKinds);
|
||||
|
||||
for (const errStep of pendingErrorSteps || []) {
|
||||
const info = extractErrorStepPayload(errStep);
|
||||
if (!info) continue;
|
||||
const kind = classifyStepAnomalyError(info.message, { errorCode: info.errorCode });
|
||||
if (kind === 'canceled') continue;
|
||||
const isInterruptOrSafety =
|
||||
kind === 'safety' ||
|
||||
/The stream was interrupted/i.test(info.message) ||
|
||||
info.terminal;
|
||||
if (!isInterruptOrSafety) {
|
||||
const rem = matchedKindBudget.get(kind) || 0;
|
||||
if (rem > 0) {
|
||||
matchedKindBudget.set(kind, rem - 1);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
events.push({
|
||||
attempt: events.length + 1,
|
||||
kind,
|
||||
delaySec: 0,
|
||||
message: cleanAnomalyErrorExcerpt(info.message),
|
||||
terminal: Boolean(info.terminal),
|
||||
source: 'error_step',
|
||||
});
|
||||
}
|
||||
|
||||
const isStatusError = step?.status === 'CORTEX_STEP_STATUS_ERROR';
|
||||
const isStatusInterrupted = step?.status === 'CORTEX_STEP_STATUS_INTERRUPTED';
|
||||
if (events.length === 0 && (isStatusError || isStatusInterrupted)) {
|
||||
events.push({
|
||||
attempt: 1,
|
||||
kind: isStatusInterrupted ? 'disconnect' : 'error',
|
||||
delaySec: 0,
|
||||
message: '',
|
||||
terminal: isStatusError,
|
||||
source: 'status',
|
||||
});
|
||||
}
|
||||
|
||||
const count = Math.max(events.length, declaredRetryCount);
|
||||
if (count <= 0) return null;
|
||||
|
||||
if (events.length === 0 && declaredRetryCount > 0) {
|
||||
events.push({
|
||||
attempt: 1,
|
||||
kind: 'error',
|
||||
delaySec: 0,
|
||||
message: '',
|
||||
terminal: false,
|
||||
source: 'retry_count',
|
||||
});
|
||||
}
|
||||
|
||||
const kinds = {};
|
||||
let totalDelaySec = 0;
|
||||
let hasDanger = isStatusError;
|
||||
for (const ev of events) {
|
||||
kinds[ev.kind] = (kinds[ev.kind] || 0) + 1;
|
||||
if (ev.delaySec > 0) totalDelaySec += ev.delaySec;
|
||||
if (ev.terminal || ev.kind === 'rate_limit' || ev.kind === 'auth_or_model') {
|
||||
hasDanger = true;
|
||||
}
|
||||
}
|
||||
// 归并主分类:按出现次数降序,同次数按严重度优先级决胜
|
||||
let primaryKind = events[0].kind;
|
||||
let bestCount = -1;
|
||||
let bestPrio = -1;
|
||||
for (const [k, c] of Object.entries(kinds)) {
|
||||
const prio = ANOMALY_SEVERITY_PRIORITY[k] ?? 1;
|
||||
if (c > bestCount || (c === bestCount && prio > bestPrio)) {
|
||||
primaryKind = k;
|
||||
bestCount = c;
|
||||
bestPrio = prio;
|
||||
}
|
||||
}
|
||||
|
||||
const roundedDelay = totalDelaySec > 0 ? +totalDelaySec.toFixed(1) : 0;
|
||||
const severity = hasDanger ? 'danger' : 'warn';
|
||||
const compactEvents = events.slice(0, 6).map((ev, idx) => ({
|
||||
attempt: idx + 1,
|
||||
kind: ev.kind,
|
||||
...(ev.delaySec > 0 ? { delaySec: ev.delaySec } : {}),
|
||||
...(ev.message ? { message: ev.message } : {}),
|
||||
...(ev.terminal ? { terminal: true } : {}),
|
||||
}));
|
||||
const kindSig = Object.entries(kinds)
|
||||
.sort((a, b) => a[0].localeCompare(b[0]))
|
||||
.map(([k, v]) => `${k}=${v}`)
|
||||
.join(',');
|
||||
const sig = `${primaryKind}:${count}:${severity}:${roundedDelay}:${kindSig}`;
|
||||
return {
|
||||
anomaly: {
|
||||
count,
|
||||
primaryKind,
|
||||
severity,
|
||||
totalDelaySec: roundedDelay,
|
||||
kinds,
|
||||
events: compactEvents,
|
||||
},
|
||||
anomalySig: sig,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 从原始轨迹步骤数组与生成器元数据中提取标准化模型步骤指标。
|
||||
*
|
||||
@@ -790,10 +1044,95 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
||||
|
||||
let pendingTurnCleanPrompts = [];
|
||||
let pendingTurnDoorbellOnly = false;
|
||||
let pendingErrorSteps = [];
|
||||
|
||||
const isErrorMessageStep = (step) => {
|
||||
if (!step || typeof step !== 'object') return false;
|
||||
const t = String(step.type || '').trim().toUpperCase();
|
||||
return (
|
||||
t === 'CORTEX_STEP_TYPE_ERROR_MESSAGE' ||
|
||||
t === 'ERROR_MESSAGE' ||
|
||||
Boolean(step.errorMessage && typeof step.errorMessage === 'object')
|
||||
);
|
||||
};
|
||||
|
||||
const mergeTrailingErrorsIntoStep = (targetStep, errSteps) => {
|
||||
if (!targetStep || !Array.isArray(errSteps) || errSteps.length === 0) return;
|
||||
const prevEvents = Array.isArray(targetStep.anomaly?.events) ? targetStep.anomaly.events : [];
|
||||
const trailingRec = buildStepAnomalyRecord(null, null, null, errSteps);
|
||||
if (!trailingRec) return;
|
||||
const isStatusOnlyPlaceholder =
|
||||
prevEvents.length === 1 &&
|
||||
Number(targetStep.anomaly?.count || 0) === 1 &&
|
||||
!prevEvents[0].message &&
|
||||
!(Number(prevEvents[0].delaySec) > 0) &&
|
||||
(prevEvents[0].kind === 'error' || prevEvents[0].kind === 'disconnect');
|
||||
if (prevEvents.length === 0 || isStatusOnlyPlaceholder) {
|
||||
const nextAnomaly =
|
||||
isStatusOnlyPlaceholder &&
|
||||
targetStep.anomaly?.severity === 'danger' &&
|
||||
trailingRec.anomaly.severity !== 'danger'
|
||||
? { ...trailingRec.anomaly, severity: 'danger' }
|
||||
: trailingRec.anomaly;
|
||||
targetStep.anomaly = nextAnomaly;
|
||||
targetStep.anomalySig =
|
||||
nextAnomaly === trailingRec.anomaly
|
||||
? trailingRec.anomalySig
|
||||
: trailingRec.anomalySig.replace(':warn:', ':danger:');
|
||||
return;
|
||||
}
|
||||
const mergedKinds = { ...(targetStep.anomaly.kinds || {}) };
|
||||
for (const [k, c] of Object.entries(trailingRec.anomaly.kinds || {})) {
|
||||
mergedKinds[k] = (mergedKinds[k] || 0) + c;
|
||||
}
|
||||
const mergedCount = Number(targetStep.anomaly.count || 0) + Number(trailingRec.anomaly.count || 0);
|
||||
const mergedDelay = +(
|
||||
Number(targetStep.anomaly.totalDelaySec || 0) + Number(trailingRec.anomaly.totalDelaySec || 0)
|
||||
).toFixed(1);
|
||||
const mergedSeverity =
|
||||
targetStep.anomaly.severity === 'danger' || trailingRec.anomaly.severity === 'danger'
|
||||
? 'danger'
|
||||
: 'warn';
|
||||
let primaryKind = targetStep.anomaly.primaryKind || trailingRec.anomaly.primaryKind;
|
||||
let bestCount = -1;
|
||||
let bestPrio = -1;
|
||||
for (const [k, c] of Object.entries(mergedKinds)) {
|
||||
const prio = ANOMALY_SEVERITY_PRIORITY[k] ?? 1;
|
||||
if (c > bestCount || (c === bestCount && prio > bestPrio)) {
|
||||
primaryKind = k;
|
||||
bestCount = c;
|
||||
bestPrio = prio;
|
||||
}
|
||||
}
|
||||
const combinedEvents = [...prevEvents, ...(trailingRec.anomaly.events || [])]
|
||||
.slice(0, 6)
|
||||
.map((ev, i) => ({ ...ev, attempt: i + 1 }));
|
||||
const kindSig = Object.entries(mergedKinds)
|
||||
.sort((a, b) => a[0].localeCompare(b[0]))
|
||||
.map(([k, v]) => `${k}=${v}`)
|
||||
.join(',');
|
||||
targetStep.anomaly = {
|
||||
count: mergedCount,
|
||||
primaryKind,
|
||||
severity: mergedSeverity,
|
||||
totalDelaySec: mergedDelay,
|
||||
kinds: mergedKinds,
|
||||
events: combinedEvents,
|
||||
};
|
||||
targetStep.anomalySig = `${primaryKind}:${mergedCount}:${mergedSeverity}:${mergedDelay}:${kindSig}`;
|
||||
};
|
||||
|
||||
rawSteps.forEach((s, index) => {
|
||||
const isHumanBoundary = isUserTurnBoundary(s);
|
||||
const isWakeupBoundary = !isHumanBoundary && isSystemWakeupBoundary(s);
|
||||
if (isHumanBoundary || isWakeupBoundary) {
|
||||
if (pendingErrorSteps.length > 0 && result.length > 0) {
|
||||
const lastPrev = result[result.length - 1];
|
||||
if (lastPrev.turnIndex === activeTurnIndex) {
|
||||
mergeTrailingErrorsIntoStep(lastPrev, pendingErrorSteps);
|
||||
}
|
||||
}
|
||||
pendingErrorSteps = [];
|
||||
const { cleanText, legacyPrompt, hasMedia, isDoorbellOnly = false } = isHumanBoundary
|
||||
? extractUserTurnInfo(s)
|
||||
: extractSystemWakeupInfo(s);
|
||||
@@ -825,11 +1164,18 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
||||
}
|
||||
}
|
||||
|
||||
if (isErrorMessageStep(s)) {
|
||||
pendingErrorSteps.push(s);
|
||||
return;
|
||||
}
|
||||
|
||||
const m = s?.metadata;
|
||||
const u = m?.modelUsage || m?.retryInfos?.[0]?.usage;
|
||||
if (!u) {
|
||||
return;
|
||||
}
|
||||
const stepPendingErrors = pendingErrorSteps;
|
||||
pendingErrorSteps = [];
|
||||
|
||||
let stepIsTurnStart = false;
|
||||
let stepTurnPrompt = '';
|
||||
@@ -917,6 +1263,10 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
||||
let timingReason = null;
|
||||
if (s.status === 'CORTEX_STEP_STATUS_CANCELED') {
|
||||
timingReason = 'canceled';
|
||||
} else if (s.status === 'CORTEX_STEP_STATUS_ERROR') {
|
||||
timingReason = 'error';
|
||||
} else if (s.status === 'CORTEX_STEP_STATUS_INTERRUPTED') {
|
||||
timingReason = 'interrupted';
|
||||
} else if (!complete || !(totalDurationSec > 0)) {
|
||||
timingReason = 'incomplete_or_invalid_timing';
|
||||
} else if (!validCount(u.outputTokens)) {
|
||||
@@ -981,6 +1331,8 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
||||
? 'Orchestrator Worker (Hydrogen)'
|
||||
: rawDisplayName;
|
||||
|
||||
const anomalyRec = buildStepAnomalyRecord(s, m, chat, stepPendingErrors);
|
||||
|
||||
result.push({
|
||||
stepIndex,
|
||||
isCompactionStep,
|
||||
@@ -1020,6 +1372,7 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
||||
speedSampleEligible:
|
||||
totalTokPerSec !== null && !shortOutputSample && !isCompactionStep,
|
||||
speedReason,
|
||||
...(anomalyRec ? { anomaly: anomalyRec.anomaly, anomalySig: anomalyRec.anomalySig } : {}),
|
||||
turnIndex: activeTurnIndex,
|
||||
isTurnStart: stepIsTurnStart,
|
||||
...(stepIsTurnStart && stepTurnPrompt ? { turnPrompt: stepTurnPrompt } : {}),
|
||||
@@ -1028,6 +1381,13 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
||||
});
|
||||
});
|
||||
|
||||
if (pendingErrorSteps.length > 0 && result.length > 0) {
|
||||
const lastStep = result[result.length - 1];
|
||||
if (lastStep.turnIndex === activeTurnIndex) {
|
||||
mergeTrailingErrorsIntoStep(lastStep, pendingErrorSteps);
|
||||
}
|
||||
}
|
||||
|
||||
// 末尾步骤上下文回填:若最后一个非压缩步骤缺少 contextBreakdown,且最近一次有效的 generatorMetadata 未跨过压缩边界,则补齐
|
||||
if (
|
||||
result.length > 0 &&
|
||||
|
||||
Reference in New Issue
Block a user