From 71fc7d5279239e7222291adce7d7d21c88296920 Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Sat, 21 Nov 2026 16:02:43 +0900 Subject: [PATCH] feat(panel): add timing breakdown hover tooltip on TTFT and duration cells --- sidecars/panel/app.js | 261 +++++++++++++++++- sidecars/panel/index.html | 4 +- .../src/components/widgets/StepTableWidget.js | 108 +++++++- sidecars/panel/src/core/formatters.js | 117 ++++++++ sidecars/panel/src/i18n/en-US.js | 11 + sidecars/panel/src/i18n/zh-CN.js | 11 + .../src/registries/stepColumnRegistry.js | 6 +- sidecars/panel/src/store/telemetryStore.js | 6 + sidecars/panel/src/styles/views-tables.css | 28 ++ sidecars/panel/styles.css | 28 ++ sidecars/panel/test/step-anomalies.test.mjs | 199 ++++++++++++- 11 files changed, 754 insertions(+), 25 deletions(-) diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index eb74809..9d1e6b6 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -1425,6 +1425,17 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'steps.compactionSummaryRow': '输入 {input} → 摘要输出 {output}', 'steps.compactionDetailHint': '系统自动触发的上下文压缩步骤,用于折叠历史对话以释放窗口空间', 'steps.compactionAnomalyHint': '该步骤同时为系统自动压缩步骤', + 'steps.timingStepTitle': '#{step} · 耗时拆解', + 'steps.timingTotalSub': '总计 {sec}', + 'steps.timingTtftLabel': '首字等待 (TTFT)', + 'steps.timingStreamLabel': '流式返回', + 'steps.timingAfterTtftLabel': '首字后耗时', + 'steps.timingThinkLabel': '原生思考计时', + 'steps.timingTotalLabel': '端到端总耗时', + 'steps.timingOverlapHint': '原生思考计时可能重叠首字或流式阶段,不可直接相加', + 'steps.timingToolBufferedHint': '含工具调用,缓冲返回时流式耗时较短', + 'steps.timingAnomalyHint': '含 {count} 次异常', + 'steps.timingAnomalyDelayHint': '含 {count} 次异常 · 退避 {sec}s', 'steps.anomalyTerminalTag': '中止', 'steps.anomalyModelTitle': '{model} · 异常 {count} 次', 'steps.anomalyModelSub': '涉及 {steps} 步', @@ -2166,6 +2177,17 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'steps.compactionSummaryRow': 'Input {input} → Summary {output}', 'steps.compactionDetailHint': 'Automatic context compaction step triggered to summarize history and free window space', 'steps.compactionAnomalyHint': 'This step is also an auto-compaction step', + 'steps.timingStepTitle': '#{step} · Timing Breakdown', + 'steps.timingTotalSub': 'Total {sec}', + 'steps.timingTtftLabel': 'First Token (TTFT)', + 'steps.timingStreamLabel': 'Streaming', + 'steps.timingAfterTtftLabel': 'After First Token', + 'steps.timingThinkLabel': 'Native Thinking', + 'steps.timingTotalLabel': 'Total Duration', + 'steps.timingOverlapHint': 'Native thinking timing may overlap TTFT/streaming; not additive', + 'steps.timingToolBufferedHint': 'Tool call step (buffered return yields short stream)', + 'steps.timingAnomalyHint': '{count} retries/errors', + 'steps.timingAnomalyDelayHint': '{count} retries/errors · backoff {sec}s', 'steps.anomalyTerminalTag': 'Stopped', 'steps.anomalyModelTitle': '{model} · {count} Retries / Errors', 'steps.anomalyModelSub': '{steps} steps affected', @@ -3555,7 +3577,7 @@ return { defineComponent }; })(); // --- src/core/formatters.js --- -const { formatMetric, formatSpeedMetric, formatCachePct, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, formatUsd, speedReasonText, formatAnomalyKindLabel, formatAnomalyTagText, resolveModelAnomalySummary, formatStepAnomalyInlineSummary, buildStepAnomalyDiagnostic, buildStepCompactionDiagnostic, buildModelAnomalyDiagnostic, sampleSummary, formatCountdown, formatCompactDateTime, formatElapsedSec, stripVendorModelPrefix, normalizeOrchestratorIdDisplayMode, resolveModelDisplayInfo, mergeModelsByDisplayName, getAgentBadgeClass, formatAgentBadgeText, formatAgentLabel, formatConversationMeta, formatLiveActivityLabel, formatLiveActivityDetail, getCanonicalModelColorSeed, resolveDeterministicModelColor, buildDeterministicModelColorMap } = (() => { +const { formatMetric, formatSpeedMetric, formatCachePct, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, formatUsd, speedReasonText, formatAnomalyKindLabel, formatAnomalyTagText, resolveModelAnomalySummary, formatStepAnomalyInlineSummary, buildStepAnomalyDiagnostic, buildStepCompactionDiagnostic, formatTimingDetailSec, hasStepTimingData, buildStepTimingDiagnostic, buildModelAnomalyDiagnostic, sampleSummary, formatCountdown, formatCompactDateTime, formatElapsedSec, stripVendorModelPrefix, normalizeOrchestratorIdDisplayMode, resolveModelDisplayInfo, mergeModelsByDisplayName, getAgentBadgeClass, formatAgentBadgeText, formatAgentLabel, formatConversationMeta, formatLiveActivityLabel, formatLiveActivityDetail, getCanonicalModelColorSeed, resolveDeterministicModelColor, buildDeterministicModelColorMap } = (() => { /** * @fileoverview Pure formatting utilities for speed metrics, token counts, * USD estimates, countdown timers, and custom datetime displays. @@ -3804,6 +3826,123 @@ function buildStepCompactionDiagnostic(st, displaySettings = {}) { }; } +function finiteNonNegativeSec(val) { + if (val === null || val === undefined || val === '') return null; + const num = Number(val); + return Number.isFinite(num) && num >= 0 ? num : null; +} + +function formatTimingDetailSec(sec) { + const num = finiteNonNegativeSec(sec); + if (num === null) return '—'; + if (num > 0 && num < 0.01) return '<0.01s'; + if (num >= 10) return `${num.toFixed(1)}s`; + return `${num.toFixed(2)}s`; +} + +function hasStepTimingData(st) { + if (!st || typeof st !== 'object') return false; + return ( + finiteNonNegativeSec(st.nativeTtftSec ?? st.ttftSec) !== null || + finiteNonNegativeSec(st.totalDurationSec ?? st.streamDurationSec) !== null || + finiteNonNegativeSec(st.nativeStreamSec) !== null || + finiteNonNegativeSec(st.thinkingDurationSec) !== null + ); +} + +function buildStepTimingDiagnostic(st) { + if (!st || typeof st !== 'object') return null; + const ttft = finiteNonNegativeSec(st.nativeTtftSec ?? st.ttftSec); + const total = finiteNonNegativeSec(st.totalDurationSec ?? st.streamDurationSec); + const nativeStream = finiteNonNegativeSec(st.nativeStreamSec); + const think = finiteNonNegativeSec(st.thinkingDurationSec); + if (ttft === null && total === null && nativeStream === null && think === null) { + return null; + } + + const afterTtft = + nativeStream === null && total !== null && ttft !== null && total >= ttft + ? +(total - ttft).toFixed(6) + : null; + + const rows = []; + if (ttft !== null) { + let valText = formatTimingDetailSec(ttft); + if (total !== null && total > 0 && ttft <= total + 0.01) { + const pct = Math.min(100, Math.max(0, Math.round((ttft / total) * 100))); + valText = `${valText} (${pct}%)`; + } + rows.push({ + text: t('steps.timingTtftLabel'), + value: valText, + toneClass: getTtftToneClass(ttft), + }); + } + if (nativeStream !== null) { + rows.push({ + text: t('steps.timingStreamLabel'), + value: formatTimingDetailSec(nativeStream), + }); + } else if (afterTtft !== null) { + rows.push({ + text: t('steps.timingAfterTtftLabel'), + value: formatTimingDetailSec(afterTtft), + }); + } + if (think !== null) { + rows.push({ + text: t('steps.timingThinkLabel'), + value: formatTimingDetailSec(think), + }); + } + + const showTotalInSub = total !== null && rows.length > 0; + if (total !== null && !showTotalInSub) { + rows.push({ + text: t('steps.timingTotalLabel'), + value: formatTimingDetailSec(total), + }); + } + + const hints = []; + const hasOverlap = + think !== null && + total !== null && + ((ttft !== null && ttft + think > total + 0.05) || + (nativeStream !== null && ttft !== null && ttft + nativeStream + think > total + 0.05) || + think > total + 0.05); + if (hasOverlap) { + hints.push(t('steps.timingOverlapHint')); + } + const streamForToolCheck = nativeStream ?? afterTtft; + if ( + st.hasToolCalls && + streamForToolCheck !== null && + streamForToolCheck < 0.5 && + ttft !== null && + ttft >= 2 + ) { + hints.push(t('steps.timingToolBufferedHint')); + } + const anomalyCount = Math.max(0, Number(st.anomaly?.count || 0)); + if (anomalyCount > 0) { + const delaySec = Number(st.anomaly?.totalDelaySec || 0); + hints.push( + delaySec > 0 + ? t('steps.timingAnomalyDelayHint', { count: anomalyCount, sec: delaySec }) + : t('steps.timingAnomalyHint', { count: anomalyCount }) + ); + } + + return { + title: t('steps.timingStepTitle', { step: Number(st.stepIndex ?? 0) }), + sub: showTotalInSub ? t('steps.timingTotalSub', { sec: formatTimingDetailSec(total) }) : '', + rows, + hint: hints.join(' · '), + severity: 'timing', + }; +} + function buildModelAnomalyDiagnostic(m) { const sum = resolveModelAnomalySummary(m); if (!sum) return null; @@ -4742,7 +4881,7 @@ function buildDeterministicModelColorMap(models = []) { return colorMap; } -return { formatMetric, formatSpeedMetric, formatCachePct, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, formatUsd, speedReasonText, formatAnomalyKindLabel, formatAnomalyTagText, resolveModelAnomalySummary, formatStepAnomalyInlineSummary, buildStepAnomalyDiagnostic, buildStepCompactionDiagnostic, buildModelAnomalyDiagnostic, sampleSummary, formatCountdown, formatCompactDateTime, formatElapsedSec, stripVendorModelPrefix, normalizeOrchestratorIdDisplayMode, resolveModelDisplayInfo, mergeModelsByDisplayName, getAgentBadgeClass, formatAgentBadgeText, formatAgentLabel, formatConversationMeta, formatLiveActivityLabel, formatLiveActivityDetail, getCanonicalModelColorSeed, resolveDeterministicModelColor, buildDeterministicModelColorMap }; +return { formatMetric, formatSpeedMetric, formatCachePct, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, formatUsd, speedReasonText, formatAnomalyKindLabel, formatAnomalyTagText, resolveModelAnomalySummary, formatStepAnomalyInlineSummary, buildStepAnomalyDiagnostic, buildStepCompactionDiagnostic, formatTimingDetailSec, hasStepTimingData, buildStepTimingDiagnostic, buildModelAnomalyDiagnostic, sampleSummary, formatCountdown, formatCompactDateTime, formatElapsedSec, stripVendorModelPrefix, normalizeOrchestratorIdDisplayMode, resolveModelDisplayInfo, mergeModelsByDisplayName, getAgentBadgeClass, formatAgentBadgeText, formatAgentLabel, formatConversationMeta, formatLiveActivityLabel, formatLiveActivityDetail, getCanonicalModelColorSeed, resolveDeterministicModelColor, buildDeterministicModelColorMap }; })(); // --- src/core/settingsBackup.js --- @@ -5956,6 +6095,9 @@ function isEquivalentTelemetry(prev, next) { bs?.createdAtMs !== as?.createdAtMs || bs?.totalDurationSec !== as?.totalDurationSec || bs?.streamDurationSec !== as?.streamDurationSec || + bs?.nativeStreamSec !== as?.nativeStreamSec || + bs?.thinkingDurationSec !== as?.thinkingDurationSec || + Boolean(bs?.hasToolCalls) !== Boolean(as?.hasToolCalls) || bs?.modelKey !== as?.modelKey || bs?.modelShort !== as?.modelShort || bs?.modelLabel !== as?.modelLabel || @@ -6013,6 +6155,9 @@ function isEquivalentTelemetry(prev, next) { before.createdAtMs !== after.createdAtMs || before.totalDurationSec !== after.totalDurationSec || before.streamDurationSec !== after.streamDurationSec || + before.nativeStreamSec !== after.nativeStreamSec || + before.thinkingDurationSec !== after.thinkingDurationSec || + Boolean(before.hasToolCalls) !== Boolean(after.hasToolCalls) || before.modelKey !== after.modelKey || before.modelShort !== after.modelShort || before.modelLabel !== after.modelLabel || @@ -15950,7 +16095,8 @@ const STEP_COLUMN_REGISTRY = Object.freeze({ key: 'ttft', thLabel: () => t('stepCol.ttft.th'), optLabel: () => t('stepCol.ttft.opt'), - sigPart: (st) => `${st.ttftSec}`, + sigPart: (st) => + `${st.ttftSec ?? ''}:${st.totalDurationSec ?? ''}:${st.nativeStreamSec ?? ''}:${st.thinkingDurationSec ?? ''}:${st.hasToolCalls ? 1 : 0}`, sortValue: (st) => finiteSortNum(st?.ttftSec), createCell: () => { const valEl = h('span'); @@ -15968,7 +16114,8 @@ const STEP_COLUMN_REGISTRY = Object.freeze({ key: 'duration', thLabel: () => t('stepCol.duration.th'), optLabel: () => t('stepCol.duration.opt'), - sigPart: (st) => `${st.totalDurationSec ?? st.streamDurationSec ?? ''}`, + sigPart: (st) => + `${st.totalDurationSec ?? st.streamDurationSec ?? ''}:${st.ttftSec ?? ''}:${st.nativeStreamSec ?? ''}:${st.thinkingDurationSec ?? ''}:${st.hasToolCalls ? 1 : 0}`, sortValue: (st) => finiteSortNum(st?.totalDurationSec ?? st?.streamDurationSec), createCell: () => { const valEl = h('span'); @@ -17344,6 +17491,7 @@ const StepTableWidget = defineComponent({ patchClasses(anomalyTipEl, { 'is-danger': diag.severity === 'danger', 'is-compaction': diag.severity === 'compaction', + 'is-timing': diag.severity === 'timing', }); patchText(anomalyTipTitleEl, diag.title); patchAttr(anomalyTipSubEl, 'hidden', !diag.sub); @@ -17354,10 +17502,23 @@ const StepTableWidget = defineComponent({ } 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 hasKvValue = row.value !== undefined && row.value !== null && row.value !== ''; + const lineEl = hasKvValue + ? h( + 'div', + { className: `step-anomaly-tip-row is-kv${row.danger ? ' is-danger' : ''}` }, + [ + h('span', { className: 'step-anomaly-tip-k', text: row.text }), + h('span', { + className: `step-anomaly-tip-v text-mono${row.toneClass ? ` ${row.toneClass}` : ''}`, + text: row.value, + }), + ] + ) + : h('div', { + className: `step-anomaly-tip-row${row.danger ? ' is-danger' : ''}`, + text: row.text, + }); const itemChildren = [lineEl]; if (row.detail) { itemChildren.push( @@ -17382,6 +17543,7 @@ const StepTableWidget = defineComponent({ } const hoverRows = new WeakMap(); + const timingHoverRows = new WeakMap(); let lastRenderedRows = null; let lastRenderOptions = ''; let trackedCascadeId = null; @@ -17537,15 +17699,18 @@ const StepTableWidget = defineComponent({ } function moveAlongTurnRail(event) { - const { badge, prompt, rowDiagGetter } = hoverRows.get(this); + const { badge, prompt, rowDiagGetter, timingDiagGetter } = 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 (rowDiagGetter) { - showAnomalyTip(this, rowDiagGetter()); + const diag = timingDiagGetter?.() || rowDiagGetter?.(); + if (diag) { + showAnomalyTip(this, diag); + } else { + hideAnomalyTip(); } } } @@ -17554,7 +17719,9 @@ const StepTableWidget = defineComponent({ const entry = hoverRows.get(this); hideTurnTip(); if (entry?.rowDiagGetter && entry.tr && event?.relatedTarget && entry.tr.contains?.(event.relatedTarget)) { - showAnomalyTip(this, entry.rowDiagGetter()); + showAnomalyTip(entry.rowAnchorEl || this, entry.rowDiagGetter()); + } else if (entry?.timingDiagGetter) { + hideAnomalyTip(); } } @@ -17565,6 +17732,43 @@ const StepTableWidget = defineComponent({ cell.onmouseleave = null; } + function enterTimingCell() { + const entry = timingHoverRows.get(this); + if (!entry) return; + const diag = entry.timingDiagGetter?.(); + if (diag) { + showAnomalyTip(this, diag); + } + } + + function leaveTimingCell(event) { + const entry = timingHoverRows.get(this); + if ( + entry?.rowDiagGetter && + entry.tr && + event?.relatedTarget && + entry.tr.contains?.(event.relatedTarget) + ) { + showAnomalyTip(entry.rowAnchorEl || entry.tr, entry.rowDiagGetter()); + return; + } + hideAnomalyTip(); + } + + function clearTimingCellHover(cell) { + if (!cell || !timingHoverRows.delete(cell)) return; + cell.onmouseenter = null; + cell.onmouseleave = null; + } + + function clearRowTimingHovers(refs) { + if (!refs?.timingHoverTds) return; + for (const td of refs.timingHoverTds) { + clearTimingCellHover(td); + } + refs.timingHoverTds.clear(); + } + function calibrateRowHeights() { calibrateRafId = 0; if (!activeDataset?.isVirtualized) return; @@ -17887,6 +18091,7 @@ const StepTableWidget = defineComponent({ railEl: null, agentBadgeEl: null, hoverTd: null, + timingHoverTds: new Set(), }, }; }, @@ -17969,6 +18174,7 @@ const StepTableWidget = defineComponent({ clearCellHover(refs.hoverTd); refs.hoverTd = null; } + clearRowTimingHovers(refs); for (const [oldColKey, entry] of refs.cellMap) { if (!wantedSet.has(oldColKey)) { if (refs.railEl?.parentNode === entry.td) { @@ -18125,6 +18331,10 @@ const StepTableWidget = defineComponent({ ); } + const hasTimingTip = hasStepTimingData(st); + const timingDiagGetter = hasTimingTip ? () => buildStepTimingDiagnostic(st) : null; + const isFirstTimingCol = firstColKey === 'ttft' || firstColKey === 'duration'; + const hoverTd = showRowRail && prompt ? firstTd : null; if (refs.hoverTd !== hoverTd) clearCellHover(refs.hoverTd); refs.hoverTd = hoverTd; @@ -18132,7 +18342,9 @@ const StepTableWidget = defineComponent({ hoverRows.set(hoverTd, { badge: refs.agentBadgeEl, prompt, + rowAnchorEl: firstTd || tr, rowDiagGetter, + timingDiagGetter: isFirstTimingCol ? timingDiagGetter : null, tr, }); const useWholeCellTurnTip = firstColKey === 'step' && !hasRowTip; @@ -18141,6 +18353,30 @@ const StepTableWidget = defineComponent({ hoverTd.onmouseleave = leaveStepCell; } + if (!refs.timingHoverTds) refs.timingHoverTds = new Set(); + const nextTimingTds = new Set(); + if (timingDiagGetter) { + for (const timingColKey of ['ttft', 'duration']) { + const timingTd = refs.cellMap.get(timingColKey)?.td || null; + if (!timingTd || timingTd === hoverTd) continue; + nextTimingTds.add(timingTd); + timingHoverRows.set(timingTd, { + tr, + rowAnchorEl: firstTd || tr, + rowDiagGetter, + timingDiagGetter, + }); + timingTd.onmouseenter = enterTimingCell; + timingTd.onmouseleave = leaveTimingCell; + } + } + for (const prevTd of refs.timingHoverTds) { + if (!nextTimingTds.has(prevTd)) { + clearTimingCellHover(prevTd); + } + } + refs.timingHoverTds = nextTimingTds; + if (enteringRowKeys?.has(item.rowKey)) { clearRowEnterState(tr); patchClasses(tr, { 'is-step-entering': true }); @@ -18158,6 +18394,7 @@ const StepTableWidget = defineComponent({ clearCellHover(refs.hoverTd); refs.hoverTd = null; } + clearRowTimingHovers(refs); clearRowEnterState(tr); if (!refs?.isSpacer && !refs?.isSizer && tr) { patchClasses(tr, { diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index 56e566d..37c16d4 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/src/components/widgets/StepTableWidget.js b/sidecars/panel/src/components/widgets/StepTableWidget.js index e973b81..10816d8 100644 --- a/sidecars/panel/src/components/widgets/StepTableWidget.js +++ b/sidecars/panel/src/components/widgets/StepTableWidget.js @@ -16,6 +16,8 @@ import { import { buildStepAnomalyDiagnostic, buildStepCompactionDiagnostic, + buildStepTimingDiagnostic, + hasStepTimingData, resolveModelDisplayInfo, speedReasonText, } from '../../core/formatters.js'; @@ -573,6 +575,7 @@ export const StepTableWidget = defineComponent({ patchClasses(anomalyTipEl, { 'is-danger': diag.severity === 'danger', 'is-compaction': diag.severity === 'compaction', + 'is-timing': diag.severity === 'timing', }); patchText(anomalyTipTitleEl, diag.title); patchAttr(anomalyTipSubEl, 'hidden', !diag.sub); @@ -583,10 +586,23 @@ export const StepTableWidget = defineComponent({ } 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 hasKvValue = row.value !== undefined && row.value !== null && row.value !== ''; + const lineEl = hasKvValue + ? h( + 'div', + { className: `step-anomaly-tip-row is-kv${row.danger ? ' is-danger' : ''}` }, + [ + h('span', { className: 'step-anomaly-tip-k', text: row.text }), + h('span', { + className: `step-anomaly-tip-v text-mono${row.toneClass ? ` ${row.toneClass}` : ''}`, + text: row.value, + }), + ] + ) + : h('div', { + className: `step-anomaly-tip-row${row.danger ? ' is-danger' : ''}`, + text: row.text, + }); const itemChildren = [lineEl]; if (row.detail) { itemChildren.push( @@ -611,6 +627,7 @@ export const StepTableWidget = defineComponent({ } const hoverRows = new WeakMap(); + const timingHoverRows = new WeakMap(); let lastRenderedRows = null; let lastRenderOptions = ''; let trackedCascadeId = null; @@ -766,15 +783,18 @@ export const StepTableWidget = defineComponent({ } function moveAlongTurnRail(event) { - const { badge, prompt, rowDiagGetter } = hoverRows.get(this); + const { badge, prompt, rowDiagGetter, timingDiagGetter } = 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 (rowDiagGetter) { - showAnomalyTip(this, rowDiagGetter()); + const diag = timingDiagGetter?.() || rowDiagGetter?.(); + if (diag) { + showAnomalyTip(this, diag); + } else { + hideAnomalyTip(); } } } @@ -783,7 +803,9 @@ export const StepTableWidget = defineComponent({ const entry = hoverRows.get(this); hideTurnTip(); if (entry?.rowDiagGetter && entry.tr && event?.relatedTarget && entry.tr.contains?.(event.relatedTarget)) { - showAnomalyTip(this, entry.rowDiagGetter()); + showAnomalyTip(entry.rowAnchorEl || this, entry.rowDiagGetter()); + } else if (entry?.timingDiagGetter) { + hideAnomalyTip(); } } @@ -794,6 +816,43 @@ export const StepTableWidget = defineComponent({ cell.onmouseleave = null; } + function enterTimingCell() { + const entry = timingHoverRows.get(this); + if (!entry) return; + const diag = entry.timingDiagGetter?.(); + if (diag) { + showAnomalyTip(this, diag); + } + } + + function leaveTimingCell(event) { + const entry = timingHoverRows.get(this); + if ( + entry?.rowDiagGetter && + entry.tr && + event?.relatedTarget && + entry.tr.contains?.(event.relatedTarget) + ) { + showAnomalyTip(entry.rowAnchorEl || entry.tr, entry.rowDiagGetter()); + return; + } + hideAnomalyTip(); + } + + function clearTimingCellHover(cell) { + if (!cell || !timingHoverRows.delete(cell)) return; + cell.onmouseenter = null; + cell.onmouseleave = null; + } + + function clearRowTimingHovers(refs) { + if (!refs?.timingHoverTds) return; + for (const td of refs.timingHoverTds) { + clearTimingCellHover(td); + } + refs.timingHoverTds.clear(); + } + function calibrateRowHeights() { calibrateRafId = 0; if (!activeDataset?.isVirtualized) return; @@ -1116,6 +1175,7 @@ export const StepTableWidget = defineComponent({ railEl: null, agentBadgeEl: null, hoverTd: null, + timingHoverTds: new Set(), }, }; }, @@ -1198,6 +1258,7 @@ export const StepTableWidget = defineComponent({ clearCellHover(refs.hoverTd); refs.hoverTd = null; } + clearRowTimingHovers(refs); for (const [oldColKey, entry] of refs.cellMap) { if (!wantedSet.has(oldColKey)) { if (refs.railEl?.parentNode === entry.td) { @@ -1354,6 +1415,10 @@ export const StepTableWidget = defineComponent({ ); } + const hasTimingTip = hasStepTimingData(st); + const timingDiagGetter = hasTimingTip ? () => buildStepTimingDiagnostic(st) : null; + const isFirstTimingCol = firstColKey === 'ttft' || firstColKey === 'duration'; + const hoverTd = showRowRail && prompt ? firstTd : null; if (refs.hoverTd !== hoverTd) clearCellHover(refs.hoverTd); refs.hoverTd = hoverTd; @@ -1361,7 +1426,9 @@ export const StepTableWidget = defineComponent({ hoverRows.set(hoverTd, { badge: refs.agentBadgeEl, prompt, + rowAnchorEl: firstTd || tr, rowDiagGetter, + timingDiagGetter: isFirstTimingCol ? timingDiagGetter : null, tr, }); const useWholeCellTurnTip = firstColKey === 'step' && !hasRowTip; @@ -1370,6 +1437,30 @@ export const StepTableWidget = defineComponent({ hoverTd.onmouseleave = leaveStepCell; } + if (!refs.timingHoverTds) refs.timingHoverTds = new Set(); + const nextTimingTds = new Set(); + if (timingDiagGetter) { + for (const timingColKey of ['ttft', 'duration']) { + const timingTd = refs.cellMap.get(timingColKey)?.td || null; + if (!timingTd || timingTd === hoverTd) continue; + nextTimingTds.add(timingTd); + timingHoverRows.set(timingTd, { + tr, + rowAnchorEl: firstTd || tr, + rowDiagGetter, + timingDiagGetter, + }); + timingTd.onmouseenter = enterTimingCell; + timingTd.onmouseleave = leaveTimingCell; + } + } + for (const prevTd of refs.timingHoverTds) { + if (!nextTimingTds.has(prevTd)) { + clearTimingCellHover(prevTd); + } + } + refs.timingHoverTds = nextTimingTds; + if (enteringRowKeys?.has(item.rowKey)) { clearRowEnterState(tr); patchClasses(tr, { 'is-step-entering': true }); @@ -1387,6 +1478,7 @@ export const StepTableWidget = defineComponent({ clearCellHover(refs.hoverTd); refs.hoverTd = null; } + clearRowTimingHovers(refs); clearRowEnterState(tr); if (!refs?.isSpacer && !refs?.isSizer && tr) { patchClasses(tr, { diff --git a/sidecars/panel/src/core/formatters.js b/sidecars/panel/src/core/formatters.js index 4d9de39..fff94cc 100644 --- a/sidecars/panel/src/core/formatters.js +++ b/sidecars/panel/src/core/formatters.js @@ -258,6 +258,123 @@ export function buildStepCompactionDiagnostic(st, displaySettings = {}) { }; } +function finiteNonNegativeSec(val) { + if (val === null || val === undefined || val === '') return null; + const num = Number(val); + return Number.isFinite(num) && num >= 0 ? num : null; +} + +export function formatTimingDetailSec(sec) { + const num = finiteNonNegativeSec(sec); + if (num === null) return '—'; + if (num > 0 && num < 0.01) return '<0.01s'; + if (num >= 10) return `${num.toFixed(1)}s`; + return `${num.toFixed(2)}s`; +} + +export function hasStepTimingData(st) { + if (!st || typeof st !== 'object') return false; + return ( + finiteNonNegativeSec(st.nativeTtftSec ?? st.ttftSec) !== null || + finiteNonNegativeSec(st.totalDurationSec ?? st.streamDurationSec) !== null || + finiteNonNegativeSec(st.nativeStreamSec) !== null || + finiteNonNegativeSec(st.thinkingDurationSec) !== null + ); +} + +export function buildStepTimingDiagnostic(st) { + if (!st || typeof st !== 'object') return null; + const ttft = finiteNonNegativeSec(st.nativeTtftSec ?? st.ttftSec); + const total = finiteNonNegativeSec(st.totalDurationSec ?? st.streamDurationSec); + const nativeStream = finiteNonNegativeSec(st.nativeStreamSec); + const think = finiteNonNegativeSec(st.thinkingDurationSec); + if (ttft === null && total === null && nativeStream === null && think === null) { + return null; + } + + const afterTtft = + nativeStream === null && total !== null && ttft !== null && total >= ttft + ? +(total - ttft).toFixed(6) + : null; + + const rows = []; + if (ttft !== null) { + let valText = formatTimingDetailSec(ttft); + if (total !== null && total > 0 && ttft <= total + 0.01) { + const pct = Math.min(100, Math.max(0, Math.round((ttft / total) * 100))); + valText = `${valText} (${pct}%)`; + } + rows.push({ + text: t('steps.timingTtftLabel'), + value: valText, + toneClass: getTtftToneClass(ttft), + }); + } + if (nativeStream !== null) { + rows.push({ + text: t('steps.timingStreamLabel'), + value: formatTimingDetailSec(nativeStream), + }); + } else if (afterTtft !== null) { + rows.push({ + text: t('steps.timingAfterTtftLabel'), + value: formatTimingDetailSec(afterTtft), + }); + } + if (think !== null) { + rows.push({ + text: t('steps.timingThinkLabel'), + value: formatTimingDetailSec(think), + }); + } + + const showTotalInSub = total !== null && rows.length > 0; + if (total !== null && !showTotalInSub) { + rows.push({ + text: t('steps.timingTotalLabel'), + value: formatTimingDetailSec(total), + }); + } + + const hints = []; + const hasOverlap = + think !== null && + total !== null && + ((ttft !== null && ttft + think > total + 0.05) || + (nativeStream !== null && ttft !== null && ttft + nativeStream + think > total + 0.05) || + think > total + 0.05); + if (hasOverlap) { + hints.push(t('steps.timingOverlapHint')); + } + const streamForToolCheck = nativeStream ?? afterTtft; + if ( + st.hasToolCalls && + streamForToolCheck !== null && + streamForToolCheck < 0.5 && + ttft !== null && + ttft >= 2 + ) { + hints.push(t('steps.timingToolBufferedHint')); + } + const anomalyCount = Math.max(0, Number(st.anomaly?.count || 0)); + if (anomalyCount > 0) { + const delaySec = Number(st.anomaly?.totalDelaySec || 0); + hints.push( + delaySec > 0 + ? t('steps.timingAnomalyDelayHint', { count: anomalyCount, sec: delaySec }) + : t('steps.timingAnomalyHint', { count: anomalyCount }) + ); + } + + return { + title: t('steps.timingStepTitle', { step: Number(st.stepIndex ?? 0) }), + sub: showTotalInSub ? t('steps.timingTotalSub', { sec: formatTimingDetailSec(total) }) : '', + rows, + hint: hints.join(' · '), + severity: 'timing', + }; +} + export function buildModelAnomalyDiagnostic(m) { const sum = resolveModelAnomalySummary(m); if (!sum) return null; diff --git a/sidecars/panel/src/i18n/en-US.js b/sidecars/panel/src/i18n/en-US.js index 0bbd0c5..8f915a1 100644 --- a/sidecars/panel/src/i18n/en-US.js +++ b/sidecars/panel/src/i18n/en-US.js @@ -353,6 +353,17 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'steps.compactionSummaryRow': 'Input {input} → Summary {output}', 'steps.compactionDetailHint': 'Automatic context compaction step triggered to summarize history and free window space', 'steps.compactionAnomalyHint': 'This step is also an auto-compaction step', + 'steps.timingStepTitle': '#{step} · Timing Breakdown', + 'steps.timingTotalSub': 'Total {sec}', + 'steps.timingTtftLabel': 'First Token (TTFT)', + 'steps.timingStreamLabel': 'Streaming', + 'steps.timingAfterTtftLabel': 'After First Token', + 'steps.timingThinkLabel': 'Native Thinking', + 'steps.timingTotalLabel': 'Total Duration', + 'steps.timingOverlapHint': 'Native thinking timing may overlap TTFT/streaming; not additive', + 'steps.timingToolBufferedHint': 'Tool call step (buffered return yields short stream)', + 'steps.timingAnomalyHint': '{count} retries/errors', + 'steps.timingAnomalyDelayHint': '{count} retries/errors · backoff {sec}s', 'steps.anomalyTerminalTag': 'Stopped', 'steps.anomalyModelTitle': '{model} · {count} Retries / Errors', 'steps.anomalyModelSub': '{steps} steps affected', diff --git a/sidecars/panel/src/i18n/zh-CN.js b/sidecars/panel/src/i18n/zh-CN.js index 8e8accc..c773bee 100644 --- a/sidecars/panel/src/i18n/zh-CN.js +++ b/sidecars/panel/src/i18n/zh-CN.js @@ -353,6 +353,17 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'steps.compactionSummaryRow': '输入 {input} → 摘要输出 {output}', 'steps.compactionDetailHint': '系统自动触发的上下文压缩步骤,用于折叠历史对话以释放窗口空间', 'steps.compactionAnomalyHint': '该步骤同时为系统自动压缩步骤', + 'steps.timingStepTitle': '#{step} · 耗时拆解', + 'steps.timingTotalSub': '总计 {sec}', + 'steps.timingTtftLabel': '首字等待 (TTFT)', + 'steps.timingStreamLabel': '流式返回', + 'steps.timingAfterTtftLabel': '首字后耗时', + 'steps.timingThinkLabel': '原生思考计时', + 'steps.timingTotalLabel': '端到端总耗时', + 'steps.timingOverlapHint': '原生思考计时可能重叠首字或流式阶段,不可直接相加', + 'steps.timingToolBufferedHint': '含工具调用,缓冲返回时流式耗时较短', + 'steps.timingAnomalyHint': '含 {count} 次异常', + 'steps.timingAnomalyDelayHint': '含 {count} 次异常 · 退避 {sec}s', 'steps.anomalyTerminalTag': '中止', 'steps.anomalyModelTitle': '{model} · 异常 {count} 次', 'steps.anomalyModelSub': '涉及 {steps} 步', diff --git a/sidecars/panel/src/registries/stepColumnRegistry.js b/sidecars/panel/src/registries/stepColumnRegistry.js index 898afd2..d9daf9d 100644 --- a/sidecars/panel/src/registries/stepColumnRegistry.js +++ b/sidecars/panel/src/registries/stepColumnRegistry.js @@ -240,7 +240,8 @@ export const STEP_COLUMN_REGISTRY = Object.freeze({ key: 'ttft', thLabel: () => t('stepCol.ttft.th'), optLabel: () => t('stepCol.ttft.opt'), - sigPart: (st) => `${st.ttftSec}`, + sigPart: (st) => + `${st.ttftSec ?? ''}:${st.totalDurationSec ?? ''}:${st.nativeStreamSec ?? ''}:${st.thinkingDurationSec ?? ''}:${st.hasToolCalls ? 1 : 0}`, sortValue: (st) => finiteSortNum(st?.ttftSec), createCell: () => { const valEl = h('span'); @@ -258,7 +259,8 @@ export const STEP_COLUMN_REGISTRY = Object.freeze({ key: 'duration', thLabel: () => t('stepCol.duration.th'), optLabel: () => t('stepCol.duration.opt'), - sigPart: (st) => `${st.totalDurationSec ?? st.streamDurationSec ?? ''}`, + sigPart: (st) => + `${st.totalDurationSec ?? st.streamDurationSec ?? ''}:${st.ttftSec ?? ''}:${st.nativeStreamSec ?? ''}:${st.thinkingDurationSec ?? ''}:${st.hasToolCalls ? 1 : 0}`, sortValue: (st) => finiteSortNum(st?.totalDurationSec ?? st?.streamDurationSec), createCell: () => { const valEl = h('span'); diff --git a/sidecars/panel/src/store/telemetryStore.js b/sidecars/panel/src/store/telemetryStore.js index e60e825..00907b6 100644 --- a/sidecars/panel/src/store/telemetryStore.js +++ b/sidecars/panel/src/store/telemetryStore.js @@ -724,6 +724,9 @@ export function isEquivalentTelemetry(prev, next) { bs?.createdAtMs !== as?.createdAtMs || bs?.totalDurationSec !== as?.totalDurationSec || bs?.streamDurationSec !== as?.streamDurationSec || + bs?.nativeStreamSec !== as?.nativeStreamSec || + bs?.thinkingDurationSec !== as?.thinkingDurationSec || + Boolean(bs?.hasToolCalls) !== Boolean(as?.hasToolCalls) || bs?.modelKey !== as?.modelKey || bs?.modelShort !== as?.modelShort || bs?.modelLabel !== as?.modelLabel || @@ -781,6 +784,9 @@ export function isEquivalentTelemetry(prev, next) { before.createdAtMs !== after.createdAtMs || before.totalDurationSec !== after.totalDurationSec || before.streamDurationSec !== after.streamDurationSec || + before.nativeStreamSec !== after.nativeStreamSec || + before.thinkingDurationSec !== after.thinkingDurationSec || + Boolean(before.hasToolCalls) !== Boolean(after.hasToolCalls) || before.modelKey !== after.modelKey || before.modelShort !== after.modelShort || before.modelLabel !== after.modelLabel || diff --git a/sidecars/panel/src/styles/views-tables.css b/sidecars/panel/src/styles/views-tables.css index 6a9f403..3f4fb7a 100644 --- a/sidecars/panel/src/styles/views-tables.css +++ b/sidecars/panel/src/styles/views-tables.css @@ -474,6 +474,10 @@ border-color: color-mix(in srgb, var(--accent-primary) 46%, var(--border-strong)); } +.step-anomaly-tip.is-timing { + border-color: var(--border-strong); +} + .step-anomaly-tip[hidden], .step-anomaly-tip-sub[hidden], .step-anomaly-tip-list[hidden], @@ -502,6 +506,10 @@ color: var(--accent-primary); } +.step-anomaly-tip.is-timing .step-anomaly-tip-title { + color: var(--text-primary); +} + .step-anomaly-tip-sub { font-size: var(--fs-xs); color: var(--text-secondary); @@ -528,6 +536,26 @@ color: var(--text-primary); } +.step-anomaly-tip-row.is-kv { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 14px; + font-weight: 400; +} + +.step-anomaly-tip-k { + color: var(--text-secondary); + white-space: nowrap; +} + +.step-anomaly-tip-v { + font-weight: 600; + color: var(--text-primary); + white-space: nowrap; + text-align: right; +} + .step-anomaly-tip-row.is-danger { color: var(--metric-danger); } diff --git a/sidecars/panel/styles.css b/sidecars/panel/styles.css index 9634547..c1ffac8 100644 --- a/sidecars/panel/styles.css +++ b/sidecars/panel/styles.css @@ -3976,6 +3976,10 @@ html[data-standalone="true"] .app-shell { border-color: color-mix(in srgb, var(--accent-primary) 46%, var(--border-strong)); } +.step-anomaly-tip.is-timing { + border-color: var(--border-strong); +} + .step-anomaly-tip[hidden], .step-anomaly-tip-sub[hidden], .step-anomaly-tip-list[hidden], @@ -4004,6 +4008,10 @@ html[data-standalone="true"] .app-shell { color: var(--accent-primary); } +.step-anomaly-tip.is-timing .step-anomaly-tip-title { + color: var(--text-primary); +} + .step-anomaly-tip-sub { font-size: var(--fs-xs); color: var(--text-secondary); @@ -4030,6 +4038,26 @@ html[data-standalone="true"] .app-shell { color: var(--text-primary); } +.step-anomaly-tip-row.is-kv { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 14px; + font-weight: 400; +} + +.step-anomaly-tip-k { + color: var(--text-secondary); + white-space: nowrap; +} + +.step-anomaly-tip-v { + font-weight: 600; + color: var(--text-primary); + white-space: nowrap; + text-align: right; +} + .step-anomaly-tip-row.is-danger { color: var(--metric-danger); } diff --git a/sidecars/panel/test/step-anomalies.test.mjs b/sidecars/panel/test/step-anomalies.test.mjs index aa48588..8c94862 100644 --- a/sidecars/panel/test/step-anomalies.test.mjs +++ b/sidecars/panel/test/step-anomalies.test.mjs @@ -7,14 +7,16 @@ 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 { i18nStore, setI18nLanguage } from '../src/i18n/index.js'; import { buildModelAnomalyDiagnostic, buildStepAnomalyDiagnostic, buildStepCompactionDiagnostic, + buildStepTimingDiagnostic, formatAnomalyTagText, formatMetric, formatSpeedMetric, + hasStepTimingData, } from '../src/core/formatters.js'; import { ContextSegmentMeter } from '../src/components/ui/ContextSegmentMeter.js'; import { STEP_COLUMN_REGISTRY } from '../src/registries/stepColumnRegistry.js'; @@ -924,4 +926,199 @@ test('Compiled styles.css centers odometer capsule slot text and ships both clas assert.match(builtCss, /\.progress-track\.ctx-segment-meter\s*\{[\s\S]*?height:\s*6px;/); assert.match(builtCss, /\.progress-track\.ctx-segment-meter\s+\.progress-seg\s*\{[\s\S]*?border-radius:\s*2px;/); assert.match(builtCss, /\.progress-track\.ctx-segment-meter\s+\.progress-seg\.is-active\.has-sep\s*\{[\s\S]*?margin-left:\s*2px;/); + assert.match(builtCss, /\.step-anomaly-tip\.is-timing\s*\{/); + assert.match(builtCss, /\.step-anomaly-tip-row\.is-kv\s*\{[\s\S]*?justify-content:\s*space-between;/); +}); + +test('buildStepTimingDiagnostic and StepTableWidget TTFT/duration hover tooltips render stage breakdown and coexist cleanly with anomaly rows', () => { + const env = installMockBrowser(); + const prevLang = i18nStore.getState().language; + let widget = null; + try { + setI18nLanguage('zh-CN'); + + // 1. Slow buffered tool-call step with overlapping native thinking timing + const slowToolStep = { + stepIndex: 101, + modelLabel: 'Gemini 4 Neon', + modelShort: '4-neon', + tokPerSec: 2.3, + ttftSec: 119.167, + nativeTtftSec: 119.167, + nativeStreamSec: 0.203, + thinkingDurationSec: 119.266, + totalDurationSec: 119.37, + hasToolCalls: true, + contextTokens: 45300, + inputTokens: 45030, + cacheReadTokens: 0, + outputTokens: 270, + thinkingTokens: 180, + responseTokens: 90, + cacheHitPct: 0, + costUsd: 0.14, + }; + assert.equal(hasStepTimingData(slowToolStep), true); + const slowDiag = buildStepTimingDiagnostic(slowToolStep); + assert.equal(slowDiag.severity, 'timing'); + assert.equal(slowDiag.title, '#101 · 耗时拆解'); + assert.equal(slowDiag.sub, '总计 119.4s'); + assert.equal(slowDiag.rows.length, 3); + assert.equal(slowDiag.rows[0].value, '119.2s (100%)'); + assert.equal(slowDiag.rows[0].toneClass, 'tone-danger'); + assert.equal(slowDiag.rows[1].value, '0.20s'); + assert.equal(slowDiag.rows[2].value, '119.3s'); + assert.match(slowDiag.hint, /重叠/); + assert.match(slowDiag.hint, /工具调用/); + + // 2. Legacy step without nativeStreamSec derives after-TTFT cleanly; inconsistent timing avoids bogus share + const legacyDiag = buildStepTimingDiagnostic({ + stepIndex: 102, + ttftSec: 1.25, + totalDurationSec: 5.0, + }); + assert.equal(legacyDiag.rows.length, 2); + assert.equal(legacyDiag.rows[0].value, '1.25s (25%)'); + assert.equal(legacyDiag.rows[1].text, '首字后耗时'); + assert.equal(legacyDiag.rows[1].value, '3.75s'); + assert.equal(legacyDiag.hint, ''); + + const inconsistentDiag = buildStepTimingDiagnostic({ + stepIndex: 103, + ttftSec: 20, + totalDurationSec: 10, + }); + assert.equal(inconsistentDiag.rows.length, 1); + assert.equal(inconsistentDiag.rows[0].value, '20.0s'); + + // 3. Step with zero timing metadata produces null + assert.equal(hasStepTimingData({ stepIndex: 104, ttftSec: null, totalDurationSec: null }), false); + assert.equal(buildStepTimingDiagnostic({ stepIndex: 104, ttftSec: null, totalDurationSec: null }), null); + + // 4. Anomaly row + normal row + compaction row in StepTableWidget + const anomalyStep = { + stepIndex: 105, + modelLabel: 'Claude Opus 4.6 (Thinking)', + modelShort: 'opus-4.6', + tokPerSec: 42.0, + ttftSec: 14.01, + nativeTtftSec: 14.01, + nativeStreamSec: 1.08, + thinkingDurationSec: 14.36, + totalDurationSec: 15.09, + hasToolCalls: false, + anomaly: { + count: 1, + primaryKind: 'timeout', + severity: 'warn', + totalDelaySec: 2.5, + kinds: { timeout: 1 }, + events: [{ attempt: 1, kind: 'timeout', delaySec: 2.5, message: 'stream idle timeout' }], + }, + anomalySig: 'timeout:1:warn:2.5:timeout=1', + }; + const compactionStep = { + stepIndex: 106, + isCompactionStep: true, + modelLabel: 'Gemini 4 Neon [自动压缩]', + modelShort: '4-neon·压缩', + tokPerSec: null, + ttftSec: null, + totalDurationSec: null, + inputTokens: 120000, + outputTokens: 3200, + }; + + widget = StepTableWidget({ standalone: true }); + widget.refs.renderStepTable( + [slowToolStep, anomalyStep, compactionStep], + 'conv-timing-tip', + ['step', 'model', 'ttft', 'duration', 'cost'], + 'zh-CN', + { hasSubagents: false, showStepAgentBadge: false, showStepTurnRail: false } + ); + + const rows = Array.from(widget.refs.stepsTbody.children); + assert.equal(rows.length, 3); + const tipEl = widget.refs.anomalyTipEl; + assert.equal(tipEl.hasAttribute('hidden'), true); + + // Hovering TTFT cell on normal row opens neutral timing popover + const slowTtftTd = rows[0].children[2]; + const slowDurTd = rows[0].children[3]; + assert.equal(typeof slowTtftTd.onmouseenter, 'function'); + assert.equal(typeof slowDurTd.onmouseenter, 'function'); + slowTtftTd.onmouseenter(); + assert.equal(tipEl.hasAttribute('hidden'), false); + assert.equal(tipEl.classList.contains('is-timing'), true); + assert.equal(tipEl.classList.contains('is-danger'), false); + assert.equal(tipEl.classList.contains('is-compaction'), false); + assert.equal(tipEl.querySelector('.step-anomaly-tip-title').textContent, '#101 · 耗时拆解'); + assert.equal(tipEl.querySelector('.step-anomaly-tip-sub').textContent, '总计 119.4s'); + const kvKeys = Array.from(tipEl.querySelectorAll('.step-anomaly-tip-k')).map((el) => el.textContent); + const kvVals = Array.from(tipEl.querySelectorAll('.step-anomaly-tip-v')).map((el) => el.textContent); + assert.deepEqual(kvKeys, ['首字等待 (TTFT)', '流式返回', '原生思考计时']); + assert.deepEqual(kvVals, ['119.2s (100%)', '0.20s', '119.3s']); + + slowTtftTd.onmouseleave({}); + assert.equal(tipEl.hasAttribute('hidden'), true); + + // Hovering duration cell also opens the timing popover + slowDurTd.onmouseenter(); + assert.equal(tipEl.hasAttribute('hidden'), false); + assert.equal(tipEl.classList.contains('is-timing'), true); + slowDurTd.onmouseleave({}); + assert.equal(tipEl.hasAttribute('hidden'), true); + + // Anomaly row: hovering TTFT switches to timing tip with anomaly hint, leaving to another cell in same row restores anomaly tip + const anomModelTd = rows[1].children[1]; + const anomTtftTd = rows[1].children[2]; + rows[1].onmouseenter(); + assert.equal(tipEl.classList.contains('is-timing'), false); + assert.match(tipEl.querySelector('.step-anomaly-tip-title').textContent, /#105.*异常 1 次/); + + anomTtftTd.onmouseenter(); + assert.equal(tipEl.classList.contains('is-timing'), true); + assert.equal(tipEl.querySelector('.step-anomaly-tip-title').textContent, '#105 · 耗时拆解'); + assert.match(tipEl.querySelector('.step-anomaly-tip-hint').textContent, /含 1 次异常 · 退避 2\.5s/); + + anomTtftTd.onmouseleave({ relatedTarget: anomModelTd }); + assert.equal(tipEl.hasAttribute('hidden'), false); + assert.equal(tipEl.classList.contains('is-timing'), false); + assert.match(tipEl.querySelector('.step-anomaly-tip-title').textContent, /#105.*异常 1 次/); + + rows[1].onmouseleave(); + assert.equal(tipEl.hasAttribute('hidden'), true); + + // Compaction row without timing data does not bind timing hover on TTFT/duration cells + assert.equal(rows[2].children[2].onmouseenter ?? null, null); + assert.equal(rows[2].children[3].onmouseenter ?? null, null); + + // Updating row data updates timing popover content dynamically (including en-US locale) + setI18nLanguage('en-US'); + const updatedStep = { ...slowToolStep, ttftSec: 2.4, nativeTtftSec: 2.4, nativeStreamSec: 1.6, thinkingDurationSec: null, totalDurationSec: 4.0, hasToolCalls: false }; + widget.refs.renderStepTable( + [updatedStep], + 'conv-timing-tip', + ['step', 'model', 'ttft', 'duration', 'cost'], + 'en-US', + { hasSubagents: false, showStepAgentBadge: false, showStepTurnRail: false } + ); + const refreshedTtftTd = widget.refs.stepsTbody.children[0].children[2]; + refreshedTtftTd.onmouseenter(); + assert.equal(tipEl.querySelector('.step-anomaly-tip-title').textContent, '#101 · Timing Breakdown'); + assert.equal(tipEl.querySelector('.step-anomaly-tip-sub').textContent, 'Total 4.00s'); + assert.deepEqual( + Array.from(tipEl.querySelectorAll('.step-anomaly-tip-k')).map((el) => el.textContent), + ['First Token (TTFT)', 'Streaming'] + ); + assert.deepEqual( + Array.from(tipEl.querySelectorAll('.step-anomaly-tip-v')).map((el) => el.textContent), + ['2.40s (60%)', '1.60s'] + ); + } finally { + widget?.destroy(); + setI18nLanguage(prevLang); + env.restore(); + } });