feat(panel): unify chart motion and preserve pending TTFT reel roll

- Extract shared chartMotion and stepChartMath modules to bring GPU 2D pointer-following tooltips, cached tooltip geometry, cubic curve/band morphing, and quantized hover hit-testing to Summary step/fit charts and AccountQuotaTrendCard
- Hide chart peak pills whenever all plotted values are zero and keep them hidden across hover and mouseleave transitions
- Hold the active conversation's last valid TTFT and mounted odometer digit reels while a new step's TTFT is still pending, and add @starting-style reel entry transitions
This commit is contained in:
fish
2026-11-25 03:42:33 +09:00
parent e520efe84e
commit e8616ab0c3
16 changed files with 5105 additions and 2198 deletions
+1819 -594
View File
File diff suppressed because it is too large Load Diff
@@ -322,11 +322,13 @@ function enrichActiveConversationSteps(
const latestEnriched =
enrichedActiveSteps.length > 0 ? enrichedActiveSteps[enrichedActiveSteps.length - 1] : null;
const lastKnownTtftSec = findLastValidStepTtft(enrichedActiveSteps);
const sessionAvgTokPerSec = roundMetric(sessionSpeed.avgTokPerSec);
return {
enrichedActiveSteps,
latestEnriched,
lastKnownTtftSec,
sessionSpeed,
sessionTtft,
sessionAvgTokPerSec,
@@ -338,6 +340,21 @@ function enrichActiveConversationSteps(
};
}
function findLastValidStepTtft(steps) {
if (!Array.isArray(steps)) return null;
for (let i = steps.length - 1; i >= 0; i -= 1) {
const candidateTtft = steps[i]?.ttftSec;
if (
candidateTtft != null &&
Number.isFinite(Number(candidateTtft)) &&
Number(candidateTtft) >= 0
) {
return Number(candidateTtft);
}
}
return null;
}
const CONTEXT_CHANNEL_KEYS = [
'userInput',
'assistant',
@@ -863,6 +880,7 @@ export function buildAgentUnitTelemetry({
stepCount: taggedSteps.length,
latestTokPerSec: enrichedRes.latestEnriched?.tokPerSec ?? null,
latestTtftSec: enrichedRes.latestEnriched?.ttftSec ?? null,
lastKnownTtftSec: enrichedRes.lastKnownTtftSec ?? null,
latestSpeedReason: enrichedRes.latestEnriched?.selectedSpeedReason ?? null,
avgTokPerSec: enrichedRes.sessionAvgTokPerSec,
speedSummary: enrichedRes.sessionSpeed,
@@ -1415,6 +1433,11 @@ function buildActiveConversationAssembly({
}
: null;
const combinedLastKnownTtftSec =
findLastValidStepTtft(allCombinedEnrichedSteps) ??
latestMetricAgent.lastKnownTtftSec ??
null;
aggregatedTelemetry = {
agentId: 'all',
cascadeId: activeCascadeId,
@@ -1438,6 +1461,7 @@ function buildActiveConversationAssembly({
stepCount: allCombinedEnrichedSteps.length,
latestTokPerSec: latestMetricAgent.latestTokPerSec,
latestTtftSec: latestMetricAgent.latestTtftSec,
lastKnownTtftSec: combinedLastKnownTtftSec,
latestSpeedReason: latestMetricAgent.latestSpeedReason,
avgTokPerSec: combinedAvgTokPerSec,
speedSummary: combinedSpeed,
@@ -1487,6 +1511,8 @@ function buildActiveConversationAssembly({
: enrichedActiveSteps.length,
latestTokPerSec: latestEnriched?.tokPerSec ?? null,
latestTtftSec: latestEnriched?.ttftSec ?? null,
lastKnownTtftSec:
mainAgentTelemetry.lastKnownTtftSec ?? findLastValidStepTtft(enrichedActiveSteps),
latestSpeedReason: latestEnriched?.selectedSpeedReason ?? null,
avgTokPerSec: sessionAvgTokPerSec,
speedSummary: sessionSpeed,
@@ -2929,6 +2955,7 @@ export function buildCliStatusSnapshot(finalPayload, updatedAtMs = Date.now()) {
latestTokPerSec: capSource.latestTokPerSec ?? ac.latestTokPerSec ?? null,
avgTokPerSec: capSource.avgTokPerSec ?? ac.avgTokPerSec ?? null,
latestTtftSec: capSource.latestTtftSec ?? ac.latestTtftSec ?? null,
lastKnownTtftSec: capSource.lastKnownTtftSec ?? ac.lastKnownTtftSec ?? null,
latestStepCostUsd: capSource.latestStepCostUsd ?? ac.latestStepCostUsd ?? null,
sessionCostUsd: capSource.sessionCostUsd ?? ac.sessionCostUsd ?? null,
latestCacheHitPct: capSource.latestCacheHitPct ?? ac.latestCacheHitPct ?? null,
+2 -2
View File
@@ -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=1795532361594">
<link rel="stylesheet" href="/styles.css?v=1795537835379">
<script src="/preload.js"></script>
</head>
<body>
<div id="app-root"></div>
<script src="/app.js?v=1795532361594"></script>
<script src="/app.js?v=1795537835379"></script>
</body>
</html>
+2
View File
@@ -622,7 +622,9 @@ export function buildBundle(panelDir = PANEL_DIR) {
'src/components/ui/ContextSegmentMeter.js',
'src/components/ui/FourSegmentBar.js',
'src/components/ui/ConsumptionTooltipContent.js',
'src/components/charts/chartMotion.js',
'src/components/charts/TrendAreaChart.js',
'src/components/charts/stepChartMath.js',
'src/components/charts/SessionStepCharts.js',
'src/registries/metricRegistry.js',
'src/components/widgets/MetricMatrixWidget.js',
File diff suppressed because it is too large Load Diff
@@ -22,6 +22,12 @@ import {
import { SVG_NS } from '../../icons/SvgIcon.js';
import { getEffectiveLocale, isEnglishLocale, t } from '../../i18n/index.js';
import { createConsumptionBreakdownContent } from '../ui/ConsumptionTooltipContent.js';
import {
createCubicCurveMorphController,
createFloatingChartTooltipController,
createReadyClassArmer,
pointsToNormalizedCubicSegs,
} from './chartMotion.js';
/** 超过该自然日天数(> 90 天)时,趋势图切换为类 GitHub 每日小格子热力图 */
export const HEATMAP_DAYS_THRESHOLD = 90;
@@ -53,175 +59,6 @@ function buildSmoothSplinePath(points) {
return d;
}
/**
* 将采样点数组转为归一化横轴 `u` (`0..1`) 上的精确三次贝塞尔分段链,
* 控制点严格保持跟 `buildSmoothSplinePath` 一致的 `0.42` 水平张力。
*
* @param {Array<{ y: number }>} pts
* @param {number} bottomY
* @returns {Array<{ u0: number, y0: number, cu1: number, cy1: number, cu2: number, cy2: number, u3: number, y3: number }>}
*/
function pointsToNormalizedCubicSegs(pts, bottomY) {
const n = pts.length;
if (n === 0) {
return [
{ u0: 0, y0: bottomY, cu1: 0.42, cy1: bottomY, cu2: 0.58, cy2: bottomY, u3: 1, y3: bottomY },
];
}
if (n === 1) {
const py = pts[0].y;
if (Math.abs(py - bottomY) < 0.01) {
return [
{ u0: 0, y0: bottomY, cu1: 0.42, cy1: bottomY, cu2: 0.58, cy2: bottomY, u3: 1, y3: bottomY },
];
}
return [
{ u0: 0, y0: bottomY, cu1: 0.21, cy1: bottomY, cu2: 0.29, cy2: py, u3: 0.5, y3: py },
{ u0: 0.5, y0: py, cu1: 0.71, cy1: py, cu2: 0.79, cy2: bottomY, u3: 1, y3: bottomY },
];
}
const segs = new Array(n - 1);
for (let i = 0; i < n - 1; i++) {
const u0 = i / (n - 1);
const u3 = (i + 1) / (n - 1);
const du = u3 - u0;
const y0 = pts[i].y;
const y3 = pts[i + 1].y;
segs[i] = {
u0,
y0,
cu1: u0 + du * 0.42,
cy1: y0,
cu2: u3 - du * 0.42,
cy2: y3,
u3,
y3,
};
}
return segs;
}
function solveCubicParamForU(seg, targetU) {
if (targetU <= seg.u0) return 0;
if (targetU >= seg.u3) return 1;
let lo = 0;
let hi = 1;
for (let it = 0; it < 20; it++) {
const s = (lo + hi) * 0.5;
const inv = 1 - s;
const u =
inv * inv * inv * seg.u0 +
3 * inv * inv * s * seg.cu1 +
3 * inv * s * s * seg.cu2 +
s * s * s * seg.u3;
if (u < targetU) lo = s;
else hi = s;
}
return (lo + hi) * 0.5;
}
function splitCubicAt(seg, s) {
const u01 = seg.u0 + (seg.cu1 - seg.u0) * s;
const y01 = seg.y0 + (seg.cy1 - seg.y0) * s;
const u12 = seg.cu1 + (seg.cu2 - seg.cu1) * s;
const y12 = seg.cy1 + (seg.cy2 - seg.cy1) * s;
const u23 = seg.cu2 + (seg.u3 - seg.cu2) * s;
const y23 = seg.cy2 + (seg.y3 - seg.cy2) * s;
const u012 = u01 + (u12 - u01) * s;
const y012 = y01 + (y12 - y01) * s;
const u123 = u12 + (u23 - u12) * s;
const y123 = y12 + (y23 - y12) * s;
const u0123 = u012 + (u123 - u012) * s;
const y0123 = y012 + (y123 - y012) * s;
return [
{ u0: seg.u0, y0: seg.y0, cu1: u01, cy1: y01, cu2: u012, cy2: y012, u3: u0123, y3: y0123 },
{ u0: u0123, y0: y0123, cu1: u123, cy1: y123, cu2: u23, cy2: y23, u3: seg.u3, y3: seg.y3 },
];
}
function extractCubicSubsegment(seg, uStart, uEnd) {
const s0 = solveCubicParamForU(seg, uStart);
const s1 = solveCubicParamForU(seg, uEnd);
if (s0 <= 1e-7 && s1 >= 1 - 1e-7) return { ...seg };
const [, right] = s0 <= 1e-7 ? [null, seg] : splitCubicAt(seg, s0);
const remSpan = 1 - s0;
const localS1 = remSpan > 1e-9 ? Math.min(1, Math.max(0, (s1 - s0) / remSpan)) : 1;
const [sub] = localS1 >= 1 - 1e-7 ? [right] : splitCubicAt(right, localS1);
sub.u0 = uStart;
sub.u3 = uEnd;
return sub;
}
/**
* 合并两条贝塞尔链的断点(始终完整保留目标链 `toSegs` 全部断点,保证 `t=1` 零几何误差)。
*/
function mergeNormalizedKnots(fromSegs, toSegs) {
const raw = [0, 1];
for (let i = 0; i < toSegs.length; i++) raw.push(toSegs[i].u3);
if (fromSegs.length <= 64) {
for (let i = 0; i < fromSegs.length; i++) raw.push(fromSegs[i].u3);
} else {
const stride = Math.ceil(fromSegs.length / 48);
for (let i = 0; i < fromSegs.length; i += stride) raw.push(fromSegs[i].u3);
}
raw.sort((a, b) => a - b);
const uniq = [0];
for (let i = 1; i < raw.length; i++) {
if (raw[i] - uniq[uniq.length - 1] > 1e-6) {
uniq.push(raw[i]);
}
}
uniq[uniq.length - 1] = 1;
return uniq;
}
function subdivideChainToKnots(segs, knots) {
const out = new Array(knots.length - 1);
let j = 0;
for (let k = 0; k < knots.length - 1; k++) {
const a = knots[k];
const b = knots[k + 1];
const mid = (a + b) * 0.5;
while (j < segs.length - 1 && segs[j].u3 < mid) j++;
out[k] = extractCubicSubsegment(segs[j], a, b);
}
return out;
}
function buildPathFromNormalizedSegs(segs, leftX, spanX) {
const xAt = (u) => (leftX + u * spanX).toFixed(1);
let d = `M ${xAt(segs[0].u0)} ${segs[0].y0.toFixed(1)}`;
for (let i = 0; i < segs.length; i++) {
const s = segs[i];
d += ` C ${xAt(s.cu1)} ${s.cy1.toFixed(1)}, ${xAt(s.cu2)} ${s.cy2.toFixed(1)}, ${xAt(s.u3)} ${s.y3.toFixed(1)}`;
}
return d;
}
/**
* 求解标准 CSS `cubic-bezier(x1, y1, x2, y2)` 在进度 `t` (`0..1`) 处的精确输出值,
* 确保 JS 曲线形变、峰值胶囊滑动及进度条宽度缩放严格同频。
*/
function evalCubicBezier(x1, y1, x2, y2, t) {
if (t <= 0) return 0;
if (t >= 1) return 1;
let lo = 0;
let hi = 1;
for (let i = 0; i < 16; i++) {
const s = (lo + hi) * 0.5;
const inv = 1 - s;
const bx = 3 * inv * inv * s * x1 + 3 * inv * s * s * x2 + s * s * s;
if (bx < t) lo = s;
else hi = s;
}
const s = (lo + hi) * 0.5;
const inv = 1 - s;
return 3 * inv * inv * s * y1 + 3 * inv * s * s * y2 + s * s * s;
}
/**
* 根据分桶总数及标签平均长度,计算底部 X 轴应当展示的均匀刻度下标列表。
*
@@ -796,7 +633,7 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) {
hoverDot.setAttribute('hidden', 'true');
svg.appendChild(hoverDot);
const peakPill = h('span', { className: 'trend-peak-pill text-mono', text: '0' });
const peakPill = h('span', { className: 'trend-peak-pill text-mono', text: '0', hidden: true });
// 共享悬停详情浮层卡片(曲线图和热力格子图共用,含分模型四段进度条及底部四通道明细)
const tooltipContent = createConsumptionBreakdownContent({
@@ -870,6 +707,7 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) {
let currentSlots = [];
let currentPts = [];
let currentMaxTokens = 0;
let currentIsHeatmap = false;
let currentHmMode = 'day';
let lastBuildSegmentsFn = null;
@@ -888,161 +726,22 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) {
let hoveredCellEl = null;
let lastPointer = null;
let lastRenderSig = '';
let hasRenderedLineOnce = false;
let peakReadyArmed = false;
let peakReadyRaf = 0;
let tipTrackRaf = 0;
let morphRafId = 0;
let committedSegs = [];
let liveMorphSegs = null;
const vGridLinePool = [];
const xAxisTickPool = [];
const hmMonthPool = [];
const hmCellPool = [];
const CURVE_MORPH_DURATION_MS = 240;
function cancelCurveMorph() {
if (
morphRafId &&
typeof window !== 'undefined' &&
typeof window.cancelAnimationFrame === 'function'
) {
window.cancelAnimationFrame(morphRafId);
}
morphRafId = 0;
}
function cancelPeakReadyRaf() {
if (
peakReadyRaf &&
typeof window !== 'undefined' &&
typeof window.cancelAnimationFrame === 'function'
) {
window.cancelAnimationFrame(peakReadyRaf);
}
peakReadyRaf = 0;
}
function canAnimateInBrowser() {
if (
typeof window === 'undefined' ||
typeof window.requestAnimationFrame !== 'function' ||
typeof window.getComputedStyle !== 'function' ||
typeof performance === 'undefined' ||
typeof performance.now !== 'function'
) {
return false;
}
if (window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches) {
return false;
}
return true;
}
function startCurveMorph(
fromSegs,
toSegs,
{ leftX, rightX, spanX, finalLineD, finalAreaD }
) {
cancelCurveMorph();
if (!canAnimateInBrowser() || fromSegs.length === 0 || toSegs.length === 0) {
liveMorphSegs = null;
patchAttr(linePath, 'd', finalLineD);
patchAttr(areaPath, 'd', finalAreaD);
return;
}
const knots = mergeNormalizedKnots(fromSegs, toSegs);
const alignedFrom = subdivideChainToKnots(fromSegs, knots);
const alignedTo = subdivideChainToKnots(toSegs, knots);
const segCount = alignedTo.length;
let maxDeltaY = 0;
for (let i = 0; i < segCount; i++) {
const a = alignedFrom[i];
const b = alignedTo[i];
maxDeltaY = Math.max(
maxDeltaY,
Math.abs(b.y0 - a.y0),
Math.abs(b.cy1 - a.cy1),
Math.abs(b.cy2 - a.cy2),
Math.abs(b.y3 - a.y3)
);
}
if (maxDeltaY < 0.25) {
liveMorphSegs = null;
patchAttr(linePath, 'd', finalLineD);
patchAttr(areaPath, 'd', finalAreaD);
return;
}
const activeLive = alignedFrom.map((s) => ({ ...s }));
liveMorphSegs = activeLive;
const rightXFixed = rightX.toFixed(1);
const leftXFixed = leftX.toFixed(1);
const startTs = performance.now();
const step = (nowTs) => {
const elapsed = Math.max(0, nowTs - startTs);
const rawT = Math.min(1, elapsed / CURVE_MORPH_DURATION_MS);
if (rawT >= 1) {
morphRafId = 0;
liveMorphSegs = null;
patchAttr(linePath, 'd', finalLineD);
patchAttr(areaPath, 'd', finalAreaD);
return;
}
const ease = evalCubicBezier(0.22, 1, 0.36, 1, rawT);
for (let i = 0; i < segCount; i++) {
const a = alignedFrom[i];
const b = alignedTo[i];
const cur = activeLive[i];
cur.u0 = a.u0 + (b.u0 - a.u0) * ease;
cur.y0 = a.y0 + (b.y0 - a.y0) * ease;
cur.cu1 = a.cu1 + (b.cu1 - a.cu1) * ease;
cur.cy1 = a.cy1 + (b.cy1 - a.cy1) * ease;
cur.cu2 = a.cu2 + (b.cu2 - a.cu2) * ease;
cur.cy2 = a.cy2 + (b.cy2 - a.cy2) * ease;
cur.u3 = a.u3 + (b.u3 - a.u3) * ease;
cur.y3 = a.y3 + (b.y3 - a.y3) * ease;
}
const morphLineD = buildPathFromNormalizedSegs(activeLive, leftX, spanX);
const morphAreaD = `${morphLineD} L ${rightXFixed} ${BOTTOM_Y} L ${leftXFixed} ${BOTTOM_Y} Z`;
patchAttr(linePath, 'd', morphLineD);
patchAttr(areaPath, 'd', morphAreaD);
morphRafId = window.requestAnimationFrame(step);
};
morphRafId = window.requestAnimationFrame(step);
}
function cancelTipTrackRaf() {
if (tipTrackRaf && typeof window !== 'undefined' && typeof window.cancelAnimationFrame === 'function') {
window.cancelAnimationFrame(tipTrackRaf);
}
tipTrackRaf = 0;
}
function armTooltipTracking(wasHidden) {
if (!wasHidden) return;
patchClasses(tooltipEl, { 'is-tracking': false });
patchClasses(hoverDot, { 'is-tracking': false });
void tooltipEl.offsetWidth;
cancelTipTrackRaf();
if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') {
tipTrackRaf = window.requestAnimationFrame(() => {
tipTrackRaf = 0;
if (!tooltipEl.hasAttribute('hidden')) {
patchClasses(tooltipEl, { 'is-tracking': true });
patchClasses(hoverDot, { 'is-tracking': true });
}
const curveMorphCtrl = createCubicCurveMorphController();
const peakReadyArmer = createReadyClassArmer(peakPill, 'is-ready');
const tooltipCtrl = createFloatingChartTooltipController({
containerEl: chartWrap,
tooltipEl,
defaultTipWidth: 216,
defaultTipHeight: 104,
defaultViewWidth: DEFAULT_VIEW_W,
defaultViewHeight: VIEW_H,
useFloatingClass: false,
});
} else {
patchClasses(tooltipEl, { 'is-tracking': true });
patchClasses(hoverDot, { 'is-tracking': true });
}
}
function populateTooltipContent(slot) {
const slotTok = safeSlotTokens(slot.tokens);
@@ -1063,81 +762,13 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) {
});
}
let cachedWrapRect = null;
let cachedSvgRect = null;
let cachedHmGridRect = null;
let cachedClipRect = undefined;
function invalidateHoverRects() {
cachedWrapRect = null;
tooltipCtrl.invalidateRects();
cachedSvgRect = null;
cachedHmGridRect = null;
cachedClipRect = undefined;
}
function getCachedWrapRect() {
if (!cachedWrapRect) {
cachedWrapRect = chartWrap.getBoundingClientRect?.() || null;
}
return cachedWrapRect;
}
function positionTooltipNearAnchor(fallbackX, fallbackY, pointer = null) {
const wrapRect = getCachedWrapRect();
const wrapW =
wrapRect && wrapRect.width > 0
? wrapRect.width
: Number(chartWrap.clientWidth || viewW || DEFAULT_VIEW_W);
const wrapH =
wrapRect && wrapRect.height > 0
? wrapRect.height
: Number(chartWrap.offsetHeight || VIEW_H);
const tipW = Number(tooltipEl.offsetWidth || 0) || 216;
const tipH = Number(tooltipEl.offsetHeight || 0) || 104;
const hasPointer =
pointer &&
Number.isFinite(Number(pointer.clientX)) &&
Number.isFinite(Number(pointer.clientY)) &&
wrapRect &&
wrapRect.width > 0 &&
wrapRect.height > 0;
const anchorX = hasPointer ? Number(pointer.clientX) - wrapRect.left : fallbackX;
const anchorY = hasPointer ? Number(pointer.clientY) - wrapRect.top : fallbackY;
if (cachedClipRect === undefined) {
const clipEl = chartWrap.closest?.('.view-pane, .cons-view-stage') || null;
cachedClipRect = clipEl?.getBoundingClientRect?.() || null;
}
const clipRect = cachedClipRect;
const hasClip = Boolean(
clipRect && clipRect.height > 0 && wrapRect && wrapRect.height > 0
);
const minY = hasClip ? clipRect.top - wrapRect.top + 6 : -tipH - 16;
const maxY = hasClip ? clipRect.bottom - wrapRect.top - tipH - 6 : wrapH + 16;
const maxLeft = Math.max(4, wrapW - tipW - 4);
let leftPx = Math.max(4, Math.min(maxLeft, anchorX - tipW / 2));
const aboveY = anchorY - tipH - 14;
let topPx;
if (aboveY >= minY) {
topPx = Math.min(maxY, aboveY);
} else if (anchorX + 16 + tipW <= wrapW - 4) {
leftPx = anchorX + 16;
topPx = Math.max(minY, Math.min(maxY, anchorY - tipH / 2));
} else if (anchorX - 16 - tipW >= 4) {
leftPx = anchorX - 16 - tipW;
topPx = Math.max(minY, Math.min(maxY, anchorY - tipH / 2));
} else {
topPx = Math.max(minY, Math.min(maxY, anchorY + 18));
}
patchStyleVar(tooltipEl, '--tip-x', `${Math.round(leftPx)}px`);
patchStyleVar(tooltipEl, '--tip-shift', '0px');
patchStyleVar(tooltipEl, '--tip-y', `${Math.round(topPx)}px`);
}
function showLineHoverAtIndex(idx, pointer = null) {
@@ -1169,7 +800,6 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) {
'is-hm-top': false,
'is-line-low': false,
});
patchAttr(tooltipEl, 'hidden', false);
populateTooltipContent(slot);
for (const [tIdx, el] of tickElsByIdx.entries()) {
@@ -1177,15 +807,21 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) {
}
}
const wrapRect = getCachedWrapRect();
const wrapRect = tooltipCtrl.getWrapRect();
const wrapW =
wrapRect && wrapRect.width > 0
? wrapRect.width
: Number(chartWrap.clientWidth || viewW || DEFAULT_VIEW_W);
const fallbackX = (pt.x / Math.max(1, viewW)) * wrapW;
const fallbackY = pt.y + 6;
positionTooltipNearAnchor(fallbackX, fallbackY, pointer || lastPointer);
armTooltipTracking(wasHidden);
tooltipCtrl.show({
fallbackX,
fallbackY,
pointer: pointer || lastPointer,
trackedDots: [hoverDot],
viewWidth: viewW,
viewHeight: VIEW_H,
});
}
function showHeatmapHoverAtIndex(idx, cellEl, pointer = null) {
@@ -1239,11 +875,10 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) {
'is-hm-top': false,
'is-line-low': false,
});
patchAttr(tooltipEl, 'hidden', false);
populateTooltipContent(slot);
}
const wrapRect = getCachedWrapRect();
const wrapRect = tooltipCtrl.getWrapRect();
const cellRect = targetCell.getBoundingClientRect?.() || null;
const wrapW =
wrapRect && wrapRect.width > 0
@@ -1277,26 +912,25 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) {
}
: rawPtr;
positionTooltipNearAnchor(fallbackX, fallbackY, effectivePtr);
armTooltipTracking(wasHidden);
tooltipCtrl.show({
fallbackX,
fallbackY,
pointer: effectivePtr,
trackedDots: [],
viewWidth: viewW,
viewHeight: VIEW_H,
});
}
function clearHover() {
invalidateHoverRects();
cancelTipTrackRaf();
tooltipCtrl.hide();
hoveredIdx = -1;
lastPointer = null;
patchAttr(hoverLine, 'hidden', true);
patchAttr(hoverDot, 'hidden', true);
patchAttr(tooltipEl, 'hidden', true);
patchClasses(tooltipEl, {
'is-hm-bottom': false,
'is-hm-top': false,
'is-line-low': false,
'is-tracking': false,
});
patchClasses(hoverDot, { 'is-tracking': false });
if (!currentIsHeatmap) {
if (!currentIsHeatmap && currentMaxTokens > 0) {
patchAttr(peakPill, 'hidden', false);
}
if (hoveredHighlightEls.length > 0) {
@@ -1606,9 +1240,9 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) {
}
function destroy() {
cancelTipTrackRaf();
cancelCurveMorph();
cancelPeakReadyRaf();
tooltipCtrl.destroy();
curveMorphCtrl.cancel();
peakReadyArmer.cancel();
plotStage.removeEventListener('mousemove', handlePointerMove);
plotStage.removeEventListener('click', handleLineClick);
plotStage.removeEventListener('mouseleave', clearHover);
@@ -1661,8 +1295,7 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) {
if (modeChanged) {
clearHover();
cancelCurveMorph();
liveMorphSegs = null;
curveMorphCtrl.cancel();
}
patchClasses(chartWrap, { 'is-heatmap': useHeatmap });
patchAttr(plotStage, 'hidden', useHeatmap);
@@ -1689,6 +1322,7 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) {
peakIdx = i;
}
}
currentMaxTokens = maxTokens;
const locale = getEffectiveLocale();
patchText(wdayMonEl, t('chart.trend.wdayMon'));
@@ -2038,23 +1672,17 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) {
areaD = `${lineD} L ${pts[pts.length - 1].x.toFixed(1)} ${BOTTOM_Y} L ${pts[0].x.toFixed(1)} ${BOTTOM_Y} Z`;
}
const prevSegs = liveMorphSegs || committedSegs;
committedSegs = nextSegs;
if (hasRenderedLineOnce && !modeChanged && prevSegs.length > 0) {
startCurveMorph(prevSegs, nextSegs, {
curveMorphCtrl.morphTo({
nextSegs,
leftX,
rightX,
spanX,
bottomY: BOTTOM_Y,
linePath,
areaPath,
finalLineD: lineD,
finalAreaD: areaD,
skipMorph: modeChanged,
});
} else {
cancelCurveMorph();
liveMorphSegs = null;
patchAttr(linePath, 'd', lineD);
patchAttr(areaPath, 'd', areaD);
}
hasRenderedLineOnce = true;
// 就地增量补丁垂直参考网格线及底部 X 轴标签,保持文字常驻不重排不闪烁
const tickIndices = computeTickIndices(slots);
@@ -2123,11 +1751,10 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) {
}
}
if (maxTokens > 0) {
const peakPt = pts[peakIdx] || { x: viewW / 2, y: BOTTOM_Y };
const peakSlot = slots[peakIdx];
const peakText =
maxTokens > 0 && peakSlot?.label
const peakText = peakSlot?.label
? t('chart.trend.peakPill', {
label: peakSlot.label,
tokens: formatTokensPrecise(maxTokens),
@@ -2136,16 +1763,12 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) {
patchText(peakPill, peakText);
const pctLeft = Math.max(12, Math.min(88, (peakPt.x / viewW) * 100));
patchStyleVar(peakPill, '--peak-x', `${pctLeft.toFixed(1)}%`);
if (!peakReadyArmed) {
peakReadyArmed = true;
if (canAnimateInBrowser()) {
peakReadyRaf = window.requestAnimationFrame(() => {
peakReadyRaf = 0;
patchClasses(peakPill, { 'is-ready': true });
});
} else {
patchClasses(peakPill, { 'is-ready': true });
peakReadyArmer.arm();
if (hoveredIdx < 0) {
patchAttr(peakPill, 'hidden', false);
}
} else {
patchAttr(peakPill, 'hidden', true);
}
if (hoveredIdx >= slots.length) {
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,665 @@
/**
* @fileoverview Pure regression math (OLS + IRLS-LOESS), nice axis tick generators,
* SVG spline/polyline path builders, and step metric formatters extracted from SessionStepCharts.js.
*/
import {
formatAgentBadgeText,
formatMetric,
formatPctNumber,
formatSpeedMetric,
formatTokens,
formatTokensPrecise,
formatUsd,
} from '../../core/formatters.js';
import { t } from '../../i18n/index.js';
/** 多模型节点和多曲线对比语义调色板(全部取自 tokens.css 语义变量,兼顾设计一致性和交叉曲线区分度) */
export const MODEL_COLOR_VARS = Object.freeze([
'var(--ctx-cached)',
'var(--ctx-skills)',
'var(--ctx-user-input)',
'var(--ctx-checkpoint)',
'var(--ctx-tool-results)',
'var(--ctx-subagent-msg)',
]);
/**
* 提取步骤所属的基础模型分组键(和后端 `usage-aggregator.mjs` 中 `modelBreakdown[].label` 严格一致),
* 且不受“精简代号 / 原始模型 ID”或“自动压缩”后缀切换影响。
*
* @param {object|null|undefined} step
* @returns {string}
*/
export function getStepModelGroupKey(step) {
if (!step || typeof step !== 'object') return t('fmt.unknownModel');
const rawLabel = String(step.baseModelLabel || step.modelLabel || step.label || '')
.replace(/\s*\[自动压缩\]\s*$/u, '')
.replace(/\s*\((?:Max|XHigh|High|Medium|Low|Thinking|Extra Low|Tiered)\)\s*$/i, '')
.trim();
if (rawLabel) return rawLabel;
const rawShort = String(step.baseModelShort || step.modelShort || step.shortName || '')
.replace(/·(?:压缩|Compact)\s*$/iu, '')
.trim();
return rawShort || t('fmt.unknownModel');
}
/**
* 将逆序或混合代理的步骤列表归一化为严格时间升序序列(最旧 -> 最新)。
*
* @param {Array<object>} steps
* @param {boolean} isMergedAllAgents
* @returns {Array<object>}
*/
export function toChronologicalSteps(steps, isMergedAllAgents = false) {
if (!Array.isArray(steps) || steps.length === 0) return [];
const copy = steps.slice();
if (isMergedAllAgents) {
copy.sort(
(a, b) =>
(Number(a?.createdAtMs) || 0) - (Number(b?.createdAtMs) || 0) ||
(Number(a?.agentIndex) || 0) - (Number(b?.agentIndex) || 0) ||
(Number(a?.stepIndex) || 0) - (Number(b?.stepIndex) || 0)
);
return copy;
}
copy.sort(
(a, b) =>
(Number(a?.stepIndex) || 0) - (Number(b?.stepIndex) || 0) ||
(Number(a?.createdAtMs) || 0) - (Number(b?.createdAtMs) || 0)
);
return copy;
}
export function clampValue(v, minVal = 0, maxVal = Infinity) {
if (!Number.isFinite(v)) return minVal;
return Math.max(minVal, Math.min(maxVal, v));
}
/**
* 双侧 95% 置信区间对应的 Student-t 临界值近似表(t_{0.975, df})。
*
* @param {number} df 残差自由度
* @returns {number}
*/
function tCritical95(df) {
if (!Number.isFinite(df) || df <= 1.5) return 3.182;
if (df <= 2.5) return 3.182 + (2.5 - df) * 0.9;
if (df <= 3.5) return 2.776 + (3.5 - df) * 0.406;
if (df <= 4.5) return 2.571 + (4.5 - df) * 0.205;
if (df <= 6) return 2.447;
if (df <= 8) return 2.306;
if (df <= 10) return 2.228;
if (df <= 15) return 2.131;
if (df <= 20) return 2.086;
if (df <= 30) return 2.042;
if (df <= 60) return 2.0;
if (df <= 120) return 1.98;
return 1.96;
}
/**
* 计算普通最小二乘线性回归(OLS: y = intercept + slope * x)。
*
* @param {number[]} ys 样本纵坐标序列
* @param {{ minVal?: number, maxVal?: number, xs?: number[] }} [options]
* @returns {{ values: number[], slope: number, intercept: number, mean: number, r: number, r2: number }}
*/
export function computeLinearFit(ys, { minVal = 0, maxVal = Infinity, xs = null } = {}) {
const n = Array.isArray(ys) ? ys.length : 0;
if (n === 0) {
return { values: [], slope: 0, intercept: 0, mean: 0, r: 0, r2: 0 };
}
const xArr =
Array.isArray(xs) && xs.length === n ? xs : Array.from({ length: n }, (_, idx) => idx);
const meanY = ys.reduce((acc, v) => acc + v, 0) / n;
if (n === 1) {
const c = clampValue(ys[0], minVal, maxVal);
return { values: [c], slope: 0, intercept: c, mean: c, r: 0, r2: 0 };
}
const meanX = xArr.reduce((acc, v) => acc + v, 0) / n;
let sxx = 0;
let sxy = 0;
let syy = 0;
for (let i = 0; i < n; i++) {
const dx = xArr[i] - meanX;
const dy = ys[i] - meanY;
sxx += dx * dx;
sxy += dx * dy;
syy += dy * dy;
}
const slope = sxx > 1e-12 ? sxy / sxx : 0;
const intercept = meanY - slope * meanX;
const r =
sxx > 1e-12 && syy > 1e-12 ? clampValue(sxy / Math.sqrt(sxx * syy), -1, 1) : 0;
const values = xArr.map((x) => clampValue(intercept + slope * x, minVal, maxVal));
return { values, slope, intercept, mean: meanY, r, r2: r * r };
}
/**
* 学术论文级回归和 95% 置信带计算引擎(Cleveland & Devlin 高斯局部加权线性回归 LOESS + 精确帽子矩阵标准误,
* 小样本 n <= 5 时自动采用精确 OLS 线性回归和双曲 t 分布 95% 置信区间,等同于 R `ggplot2::geom_smooth(se = TRUE)`)。
*
* @param {number[]} xs 严格递增或单调的样本横坐标序列
* @param {number[]} ys 样本纵坐标序列
* @param {{ minVal?: number, maxVal?: number, gridSize?: number, span?: number }} [options]
*/
export function computePublicationFit(
xs,
ys,
{ minVal = 0, maxVal = Infinity, gridSize = 64, span = 0.5 } = {}
) {
const n = Math.min(Array.isArray(xs) ? xs.length : 0, Array.isArray(ys) ? ys.length : 0);
if (n === 0) {
return {
method: 'OLS',
mean: 0,
sd: 0,
slope: 0,
intercept: 0,
r: 0,
r2: 0,
sampleFits: [],
sampleCiLow: [],
sampleCiHigh: [],
sampleCiHalf: [],
grid: [],
};
}
const ols = computeLinearFit(ys, { minVal, maxVal, xs });
let syy = 0;
for (let i = 0; i < n; i++) {
const dy = ys[i] - ols.mean;
syy += dy * dy;
}
const sd = n > 1 ? Math.sqrt(syy / (n - 1)) : 0;
if (n === 1) {
const val = clampValue(ys[0], minVal, maxVal);
return {
method: 'OLS',
mean: val,
sd: 0,
slope: 0,
intercept: val,
r: 0,
r2: 0,
sampleFits: [val],
sampleCiLow: [val],
sampleCiHigh: [val],
sampleCiHalf: [0],
grid: [{ x: xs[0], fit: val, ciLow: val, ciHigh: val }],
};
}
const xMin = xs[0];
const xMax = xs[n - 1];
const xSpan = Math.max(1e-9, xMax - xMin);
const M = Math.max(2, gridSize);
const gridXs = Array.from({ length: M }, (_, k) => xMin + (k / (M - 1)) * xSpan);
// 小样本(n <= 5):采用精确 OLS 线性回归和 Student-t 双曲 95% CI 置信带
if (n <= 5) {
const meanX = xs.reduce((a, b) => a + b, 0) / n;
let sxx = 0;
let sse = 0;
for (let i = 0; i < n; i++) {
const dx = xs[i] - meanX;
sxx += dx * dx;
const resid = ys[i] - (ols.intercept + ols.slope * xs[i]);
sse += resid * resid;
}
const df = n - 2;
const seResid = df >= 1 ? Math.sqrt(sse / df) : 0;
const tCrit = df >= 1 ? tCritical95(df) : 0;
const evalOlsAt = (x0) => {
const rawFit = ols.intercept + ols.slope * x0;
const sePred =
seResid > 0
? seResid * Math.sqrt(1 / n + (sxx > 1e-12 ? ((x0 - meanX) * (x0 - meanX)) / sxx : 0))
: 0;
const half = tCrit * sePred;
return {
fit: clampValue(rawFit, minVal, maxVal),
ciLow: clampValue(rawFit - half, minVal, maxVal),
ciHigh: clampValue(rawFit + half, minVal, maxVal),
half,
};
};
const sampleEval = xs.map(evalOlsAt);
const grid = gridXs.map((gx) => {
const g = evalOlsAt(gx);
return { x: gx, fit: g.fit, ciLow: g.ciLow, ciHigh: g.ciHigh };
});
return {
method: 'OLS',
mean: ols.mean,
sd,
slope: ols.slope,
intercept: ols.intercept,
r: ols.r,
r2: ols.r2,
sampleFits: sampleEval.map((e) => e.fit),
sampleCiLow: sampleEval.map((e) => e.ciLow),
sampleCiHigh: sampleEval.map((e) => e.ciHigh),
sampleCiHalf: sampleEval.map((e) => e.half),
grid,
};
}
// n >= 6:Cleveland 高斯局部加权一阶线性回归(LOESS)+ 精确帽子矩阵杠杆度 95% CI 置信带
const q = Math.max(5, Math.min(n, Math.ceil(span * n)));
const wBuf = new Float64Array(n);
const sortedXs = q <= n && xs.slice(0, n).every(
(x, i) => Number.isFinite(x) && (i === 0 || xs[i - 1] <= x)
);
function loessBandwidth(x0) {
// 有序 x 上的 q 个最近样本可取连续区间;二分比较两端,避免每个拟合点都排序。
let left = 0;
let right = n - q;
while (left < right) {
const mid = (left + right) >>> 1;
if (x0 - xs[mid] > xs[mid + q] - x0) {
left = mid + 1;
} else {
right = mid;
}
}
return Math.max(Math.abs(xs[left] - x0), Math.abs(xs[left + q - 1] - x0));
}
function evalLoessPoint(x0, diagIdx = -1) {
let h;
if (sortedXs) {
h = loessBandwidth(x0);
if (h <= 1e-9) {
h = Math.max(Math.abs(xs[0] - x0), Math.abs(xs[n - 1] - x0), xSpan * 0.05, 1e-6);
}
} else {
const sortedDists = Array.from({ length: n }, (_, j) => Math.abs(xs[j] - x0)).sort((a, b) => a - b);
h = sortedDists[q - 1];
if (h <= 1e-9) {
h = Math.max(sortedDists[n - 1], xSpan * 0.05, 1e-6);
}
}
const maxDist = h * 1.0001;
let start = 0;
let end = n;
if (sortedXs) {
// 三次权重的支持区间之外权重为零,保留区间内样本原来的累加顺序。
let right = n;
while (start < right) {
const mid = (start + right) >>> 1;
if (x0 - xs[mid] >= maxDist) start = mid + 1;
else right = mid;
}
let left = start;
while (left < end) {
const mid = (left + end) >>> 1;
if (xs[mid] - x0 < maxDist) left = mid + 1;
else end = mid;
}
}
let sw = 0;
let swx = 0;
for (let j = start; j < end; j++) {
const u = Math.abs(xs[j] - x0) / maxDist;
const base = 1 - u * u * u;
const w = u >= 1 ? 0 : base * base * base;
wBuf[j] = w;
sw += w;
swx += w * xs[j];
}
if (sw <= 1e-12) {
const fallbackVal = ols.intercept + ols.slope * x0;
return { rawFit: fallbackVal, leverageNormSq: 1 / n, diagHat: 1 / n, localHatDiag: 1 / n };
}
const mx = swx / sw;
let sxxW = 0;
for (let j = start; j < end; j++) {
const w = wBuf[j];
if (w <= 0) continue;
const dx = xs[j] - mx;
sxxW += w * dx * dx;
}
const dx0 = x0 - mx;
const useSlope = sxxW > 1e-12;
const inverseWeightSum = 1 / sw;
const slopeScale = useSlope ? dx0 / sxxW : 0;
const localHatDiag = inverseWeightSum + (useSlope ? (dx0 * dx0) / sxxW : 0);
let rawFit = 0;
let leverageNormSq = 0;
let diagHat = 0;
for (let j = start; j < end; j++) {
const w = wBuf[j];
if (w <= 0) continue;
const lj = w * inverseWeightSum + (useSlope ? w * (xs[j] - mx) * slopeScale : 0);
rawFit += lj * ys[j];
leverageNormSq += lj * lj;
if (j === diagIdx) diagHat = lj;
}
return { rawFit, leverageNormSq, diagHat, localHatDiag };
}
const rawSampleFits = new Float64Array(n);
const sampleLevSq = new Float64Array(n);
let sse = 0;
let traceL = 0;
let precomputedGridEval = null;
// 大样本(n > 200 且 x 单调有序)采用和 R `stats::loess(surface = "interpolate")` 一致的网格插值加速:
// 仅在 M 个均匀网格顶点做精确 LOESS(O(M·N)),再线性插值样本拟合值和杠杆度,避免 O(N²) 阻塞主线程。
if (n > 200 && sortedXs && M >= 2) {
const gridRawFit = new Float64Array(M);
const gridLevSq = new Float64Array(M);
const gridHatDiag = new Float64Array(M);
for (let k = 0; k < M; k++) {
const res = evalLoessPoint(gridXs[k], -1);
gridRawFit[k] = res.rawFit;
gridLevSq[k] = res.leverageNormSq;
gridHatDiag[k] = res.localHatDiag;
}
precomputedGridEval = { gridRawFit, gridLevSq };
const invSpan = (M - 1) / xSpan;
const maxK0 = M - 2;
for (let i = 0; i < n; i++) {
const u = (xs[i] - xMin) * invSpan;
const k0 = u <= 0 ? 0 : u >= maxK0 ? maxK0 : Math.floor(u);
const frac = Math.max(0, Math.min(1, u - k0));
const rf = gridRawFit[k0] + frac * (gridRawFit[k0 + 1] - gridRawFit[k0]);
const ls = Math.max(0, gridLevSq[k0] + frac * (gridLevSq[k0 + 1] - gridLevSq[k0]));
const hd = gridHatDiag[k0] + frac * (gridHatDiag[k0 + 1] - gridHatDiag[k0]);
rawSampleFits[i] = rf;
sampleLevSq[i] = ls;
traceL += hd;
const diff = ys[i] - rf;
sse += diff * diff;
}
} else {
for (let i = 0; i < n; i++) {
const res = evalLoessPoint(xs[i], i);
rawSampleFits[i] = res.rawFit;
sampleLevSq[i] = res.leverageNormSq;
traceL += res.diagHat;
const diff = ys[i] - res.rawFit;
sse += diff * diff;
}
}
const dfRes = Math.max(1, n - traceL);
const sigmaHat = Math.sqrt(sse / dfRes);
const tCrit = tCritical95(dfRes);
const sampleFits = new Array(n);
const sampleCiLow = new Array(n);
const sampleCiHigh = new Array(n);
const sampleCiHalf = new Array(n);
let clampedSse = 0;
for (let i = 0; i < n; i++) {
const fitVal = clampValue(rawSampleFits[i], minVal, maxVal);
const half = tCrit * sigmaHat * Math.sqrt(sampleLevSq[i]);
sampleFits[i] = fitVal;
sampleCiLow[i] = clampValue(rawSampleFits[i] - half, minVal, maxVal);
sampleCiHigh[i] = clampValue(rawSampleFits[i] + half, minVal, maxVal);
sampleCiHalf[i] = half;
const d = ys[i] - fitVal;
clampedSse += d * d;
}
const grid = precomputedGridEval
? gridXs.map((gx, k) => {
const rf = precomputedGridEval.gridRawFit[k];
const half = tCrit * sigmaHat * Math.sqrt(Math.max(0, precomputedGridEval.gridLevSq[k]));
return {
x: gx,
fit: clampValue(rf, minVal, maxVal),
ciLow: clampValue(rf - half, minVal, maxVal),
ciHigh: clampValue(rf + half, minVal, maxVal),
};
})
: gridXs.map((gx) => {
const res = evalLoessPoint(gx, -1);
const half = tCrit * sigmaHat * Math.sqrt(res.leverageNormSq);
return {
x: gx,
fit: clampValue(res.rawFit, minVal, maxVal),
ciLow: clampValue(res.rawFit - half, minVal, maxVal),
ciHigh: clampValue(res.rawFit + half, minVal, maxVal),
};
});
const r2Loess = syy > 1e-12 ? clampValue(1 - clampedSse / syy, 0, 1) : 1;
return {
method: 'LOESS',
mean: ols.mean,
sd,
slope: ols.slope,
intercept: ols.intercept,
r: ols.r,
r2: r2Loess,
sampleFits,
sampleCiLow,
sampleCiHigh,
sampleCiHalf,
grid,
};
}
/**
* Heckbert 科学坐标轴刻度取整算法,生成科研图表风格的均匀整洁刻度。
*/
export function niceStepNumber(range, round) {
if (!Number.isFinite(range) || range <= 0) return 1;
const exponent = Math.floor(Math.log10(range));
const fraction = range / 10 ** exponent;
let niceFraction;
if (round) {
if (fraction < 1.5) niceFraction = 1;
else if (fraction < 3) niceFraction = 2;
else if (fraction < 7) niceFraction = 5;
else niceFraction = 10;
} else if (fraction <= 1) niceFraction = 1;
else if (fraction <= 2) niceFraction = 2;
else if (fraction <= 5) niceFraction = 5;
else niceFraction = 10;
return niceFraction * 10 ** exponent;
}
export function computeNiceYScale(dataMin, dataMax, { minBound = 0, maxBound = Infinity, tickCount = 4 } = {}) {
let lo = Number.isFinite(dataMin) ? dataMin : 0;
let hi = Number.isFinite(dataMax) ? dataMax : 1;
if (minBound === 0 && lo >= 0 && hi > 0 && lo <= hi * 0.32) {
lo = 0;
}
if (hi - lo <= 1e-9) {
const pad = lo > 0 ? lo * 0.15 : 1;
lo = Math.max(minBound, lo - pad);
hi = Math.min(maxBound, hi + pad);
if (hi - lo <= 1e-9) {
lo = Math.max(minBound, hi - 1);
}
} else {
const pad = (hi - lo) * 0.05;
lo = Math.max(minBound, lo - (lo === 0 ? 0 : pad));
hi = Math.min(maxBound, hi + pad);
}
const rawRange = niceStepNumber(hi - lo, false);
const step = niceStepNumber(rawRange / Math.max(2, tickCount - 1), true);
let graphMin = Math.max(minBound, Math.floor(lo / step) * step);
let graphMax = Math.min(maxBound, Math.ceil(hi / step) * step);
if (graphMax - graphMin <= 1e-9) {
graphMax = graphMin + step;
}
const ticks = [];
for (let v = graphMin; v <= graphMax + step * 0.25; v += step) {
const clamped = clampValue(+v.toPrecision(10), minBound, maxBound);
if (ticks.length === 0 || Math.abs(clamped - ticks[ticks.length - 1]) > step * 1e-4) {
ticks.push(clamped);
}
if (ticks.length >= 8) break;
}
return {
min: ticks[0] ?? graphMin,
max: ticks[ticks.length - 1] ?? graphMax,
step,
ticks,
};
}
export function computeNiceXStepTicks(xs) {
const n = xs.length;
if (n === 0) return [];
if (n <= 5) {
return Array.from(new Set(xs.map((x) => Math.round(x))));
}
const xMin = xs[0];
const xMax = xs[n - 1];
const span = xMax - xMin;
if (span <= 5) {
return Array.from(new Set(xs.map((x) => Math.round(x))));
}
const step = Math.max(1, Math.round(niceStepNumber(span / 4.5, true)));
const firstTick = Math.ceil(xMin / step) * step;
const ticks = [];
if (firstTick - xMin > step * 0.45) {
ticks.push(Math.round(xMin));
}
for (let v = firstTick; v <= xMax + 1e-6; v += step) {
ticks.push(Math.round(v));
if (ticks.length >= 7) break;
}
if (ticks.length === 0) {
return [Math.round(xMin), Math.round(xMax)];
}
return ticks;
}
export function formatYAxisTick(metric, val, step) {
if (!Number.isFinite(val)) return '';
if (Math.abs(val) < 1e-9) {
return metric === 'cost' ? '$0' : metric === 'cache' ? '0%' : metric === 'ttft' ? '0s' : '0';
}
if (metric === 'tps') {
return step >= 1 ? `${Math.round(val)}` : val.toFixed(1);
}
if (metric === 'ttft') {
return step >= 1 ? `${Math.round(val)}s` : `${val.toFixed(1)}s`;
}
if (metric === 'cache') {
return step >= 1 ? `${Math.round(val)}%` : formatPctNumber(val, { withSymbol: true });
}
if (metric === 'cost') {
if (step >= 1) return `$${Math.round(val)}`;
if (step >= 0.1) return `$${val.toFixed(1)}`;
if (step >= 0.01) return `$${val.toFixed(2)}`;
return `$${val.toFixed(3)}`;
}
return String(val);
}
export function buildPolylinePath(points) {
if (!points.length) return '';
let d = `M ${points[0].x.toFixed(1)} ${points[0].y.toFixed(1)}`;
for (let i = 1; i < points.length; i++) {
d += ` L ${points[i].x.toFixed(1)} ${points[i].y.toFixed(1)}`;
}
return d;
}
export function buildSplinePath(points) {
if (!points.length) return '';
if (points.length === 1) {
return `M ${points[0].x.toFixed(1)} ${points[0].y.toFixed(1)}`;
}
let d = `M ${points[0].x.toFixed(1)} ${points[0].y.toFixed(1)}`;
for (let i = 0; i < points.length - 1; i++) {
const p0 = points[i];
const p1 = points[i + 1];
const cpx1 = p0.x + (p1.x - p0.x) * 0.38;
const cpx2 = p1.x - (p1.x - p0.x) * 0.38;
d += ` C ${cpx1.toFixed(1)} ${p0.y.toFixed(1)}, ${cpx2.toFixed(1)} ${p1.y.toFixed(1)}, ${p1.x.toFixed(1)} ${p1.y.toFixed(1)}`;
}
return d;
}
export function computeStepTickIndices(count) {
if (count <= 0) return [];
if (count <= 6) return Array.from({ length: count }, (_, i) => i);
const maxTicks = 6;
const set = new Set();
for (let k = 0; k < maxTicks; k++) {
set.add(Math.round((k / (maxTicks - 1)) * (count - 1)));
}
return Array.from(set).sort((a, b) => a - b);
}
export function formatStepAxisTag(st, showAgentPrefix) {
const num = `#${Number(st?.stepIndex ?? 0)}`;
if (!showAgentPrefix) return num;
const badge = formatAgentBadgeText({
agentKind:
st?.agentKind || (!st?.isSubagent ? 'main' : st?.isSideQuestion ? 'side_question' : 'subagent'),
agentOrdinal:
st?.agentOrdinal || (st?.isSideQuestion ? st?.sideIndex || 0 : st?.agentIndex || 0),
isMain: !st?.isSubagent,
isSideQuestion: Boolean(st?.isSideQuestion),
sideIndex: st?.sideIndex || 0,
index: st?.agentIndex || 0,
badgeText: st?.agentBadge,
});
return `${badge}${num}`;
}
export function formatChartMetricValue(metric, val) {
if (!Number.isFinite(val)) return '—';
switch (metric) {
case 'totalTokens':
case 'context':
return `${formatTokensPrecise(val)} tok`;
case 'tps':
return formatSpeedMetric(val, ' tok/s');
case 'ttft':
return formatMetric(val, 's');
case 'cache':
return formatPctNumber(val, { withSymbol: true });
case 'cost':
return formatUsd(val, { precise: true });
default:
return String(val);
}
}
export function formatChartMetricCompact(metric, val) {
if (!Number.isFinite(val)) return '—';
switch (metric) {
case 'totalTokens':
case 'context':
return formatTokens(val);
case 'tps':
return formatSpeedMetric(val, ' tok/s');
case 'ttft':
return formatMetric(val, 's');
case 'cache':
return formatPctNumber(val, { withSymbol: true });
case 'cost':
return formatUsd(val, { precise: true });
default:
return String(val);
}
}
@@ -20,6 +20,11 @@ import { getEffectiveLocale, t } from '../../i18n/index.js';
import { CustomDateTimePicker } from '../ui/CustomDateTimePicker.js';
import { CustomSelect } from '../ui/CustomSelect.js';
import { SegmentedControl } from '../ui/SegmentedControl.js';
import {
createFloatingChartTooltipController,
createMultiSeriesCurveMorphController,
pointsToNormalizedCubicSegs,
} from '../charts/chartMotion.js';
const POOL_COLORS = Object.freeze({
Gemini: 'var(--accent-primary)',
@@ -83,6 +88,44 @@ function buildHorizontalTangentSpline(pts) {
return d;
}
const HOVER_SLOT_COUNT = 96;
const MAX_SVG_COLUMN_BUCKETS = 96;
/**
* Downsamples dense sub-pixel SVG points (e.g. 12s poll bursts) into `<= maxCols`
* min/max-preserving visual knots so curve rasterization and morphing stay crisp and fast,
* while `rawPoints` remain intact for exact timestamp interpolation.
*/
function simplifySvgPointsForRender(svgPts, leftX, plotW, maxCols = MAX_SVG_COLUMN_BUCKETS) {
if (svgPts.length <= maxCols) return svgPts;
const colW = Math.max(1, plotW) / maxCols;
const out = [svgPts[0]];
let idx = 1;
const endIdx = svgPts.length - 1;
while (idx < endIdx) {
const col = Math.floor((svgPts[idx].x - leftX) / colW);
let minPt = svgPts[idx];
let maxPt = svgPts[idx];
let j = idx + 1;
while (j < endIdx && Math.floor((svgPts[j].x - leftX) / colW) === col) {
const cand = svgPts[j];
if (cand.y < minPt.y) minPt = cand;
if (cand.y > maxPt.y) maxPt = cand;
j += 1;
}
if (minPt === maxPt) {
out.push(minPt);
} else if (minPt.x <= maxPt.x) {
out.push(minPt, maxPt);
} else {
out.push(maxPt, minPt);
}
idx = j;
}
out.push(svgPts[endIdx]);
return out;
}
/**
* Computes tight, integer-aligned `[yMin, yMid, yMax]` bounds (`0..100%`) around
* observed `[dataMin, dataMax]` so small-to-moderate quota changes use the full
@@ -452,6 +495,7 @@ export const AccountQuotaTrendCard = defineComponent({
options: [],
onUpdateModelValue: (val) => {
selectedAccountEmail = String(val || '').trim().toLowerCase();
hideHover();
renderChart();
},
});
@@ -463,6 +507,7 @@ export const AccountQuotaTrendCard = defineComponent({
options: [{ value: 'all', label: t('cons.cyclePoolAll') }],
onUpdateModelValue: (val) => {
selectedPool = val || 'all';
hideHover();
renderChart();
},
});
@@ -474,6 +519,7 @@ export const AccountQuotaTrendCard = defineComponent({
onUpdateModelValue: (val) => {
selectedWin = val === 'weekly' ? 'weekly' : '5h';
winSwitch.setProps({ modelValue: selectedWin, options: getQuotaWindowOptions() });
hideHover();
renderChart();
},
});
@@ -489,6 +535,7 @@ export const AccountQuotaTrendCard = defineComponent({
endPicker.setValue(draftEndMs);
}
rangeSwitch.setProps({ modelValue: selectedRange, options: getTimeRangeOptions() });
hideHover();
renderChart();
},
});
@@ -635,17 +682,42 @@ export const AccountQuotaTrendCard = defineComponent({
'div',
{
className: 'trend-plot-stage',
onPointermove: handlePointerMove,
onPointerleave: hideHover,
onMousemove: handlePointerMove,
onMouseleave: hideHover,
},
[svg, tooltipEl]
[svg]
);
const chartWrap = h('div', { className: 'trend-chart-wrap' }, [
plotStage,
xAxisEl,
legendRowEl,
tooltipEl,
]);
const tooltipCtrl = createFloatingChartTooltipController({
containerEl: chartWrap,
tooltipEl,
defaultTipWidth: 204,
defaultTipHeight: 78,
defaultViewWidth: 460,
defaultViewHeight: VIEW_H,
});
const seriesMorphCtrl = createMultiSeriesCurveMorphController();
const seriesNodePoolByKey = new Map();
const hoverDotPoolByKey = new Map();
let xTickElements = [];
let hoveredSlotIdx = -1;
let lastActiveDots = [];
let lastFallbackX = 0;
let lastFallbackY = 0;
let lastSizeKey = '';
let lastTipTimeStr = '';
let lastTipWinStr = '';
let lastHoveredTickIdx = -1;
let lastPointer = null;
let cachedSvgRect = null;
let lastPlotSig = '';
const rootEl = h('section', { className: 'panel account-quota-trend-panel' }, [
h('div', { className: 'panel-header account-trend-toprow' }, [
h('span', { className: 'panel-title cons-overview-title' }, [
@@ -670,10 +742,29 @@ export const AccountQuotaTrendCard = defineComponent({
return BOTTOM_Y - ((clamped - plottedYScale.yMin) / plottedYScale.span) * SPAN_Y;
}
function syncHoveredTickClass(activeTickIdx) {
if (activeTickIdx === lastHoveredTickIdx) return;
lastHoveredTickIdx = activeTickIdx;
for (let i = 0; i < xTickElements.length; i++) {
patchClasses(xTickElements[i], { 'is-hovered': i === activeTickIdx });
}
}
function hideHover() {
cachedSvgRect = null;
hoveredSlotIdx = -1;
lastActiveDots = [];
lastTipTimeStr = '';
lastTipWinStr = '';
lastPointer = null;
tooltipCtrl.hide();
hoverLine.setAttribute('hidden', '');
hoverDotsGroup.setAttribute('hidden', '');
patchAttr(tooltipEl, 'hidden', true);
for (const dot of hoverDotPoolByKey.values()) {
dot.setAttribute('hidden', '');
patchClasses(dot, { 'is-tracking': false });
}
syncHoveredTickClass(-1);
}
function sampleSeriesValueAt(points, targetMs) {
@@ -697,50 +788,90 @@ export const AccountQuotaTrendCard = defineComponent({
return a.val + (b.val - a.val) * ((targetMs - a.ts) / span);
}
function handlePointerMove(ev) {
if (!plottedSeries.length || !(plottedEndMs > plottedStartMs)) {
function showHoverAtSlot(slotIdx, pointer = null, { forceRefresh = false } = {}) {
if (!plottedSeries.length || !(plottedEndMs > plottedStartMs) || slotIdx < 0) {
hideHover();
return;
}
const rect = svg.getBoundingClientRect?.();
const widthPx = Number(rect?.width || viewW);
if (!(widthPx > 0)) return;
const offsetX = Number(ev.clientX || 0) - Number(rect?.left || 0);
const svgX = (offsetX / widthPx) * viewW;
const clampedSlot = Math.max(0, Math.min(HOVER_SLOT_COUNT, slotIdx));
const wasHidden = tooltipEl.hasAttribute('hidden');
const changedSlot = forceRefresh || wasHidden || clampedSlot !== hoveredSlotIdx;
hoveredSlotIdx = clampedSlot;
if (pointer) lastPointer = pointer;
if (changedSlot) {
const u = clampedSlot / HOVER_SLOT_COUNT;
const plotW = Math.max(20, viewW - LEFT_X - RIGHT_PAD);
const u = Math.max(0, Math.min(1, (svgX - LEFT_X) / plotW));
const clampedX = LEFT_X + u * plotW;
const targetMs = Math.round(plottedStartMs + u * (plottedEndMs - plottedStartMs));
hoverLine.setAttribute('x1', clampedX.toFixed(1));
hoverLine.setAttribute('x2', clampedX.toFixed(1));
while (hoverDotsGroup.firstChild) hoverDotsGroup.removeChild(hoverDotsGroup.firstChild);
const tipItems = [];
const activeDots = [];
let sumY = 0;
const usedKeys = new Set();
for (let i = 0; i < plottedSeries.length; i++) {
const s = plottedSeries[i];
const val = sampleSeriesValueAt(s.rawPoints, targetMs);
if (val === null) continue;
usedKeys.add(s.poolKey);
const y = valueToSvgY(val);
const dot = document.createElementNS(SVG_NS, 'circle');
sumY += y;
let dot = hoverDotPoolByKey.get(s.poolKey);
if (!dot) {
dot = document.createElementNS(SVG_NS, 'circle');
dot.setAttribute('class', 'trend-hover-dot');
dot.setAttribute('r', '3.2');
dot.style.fill = 'var(--surface-panel)';
hoverDotPoolByKey.set(s.poolKey, dot);
hoverDotsGroup.appendChild(dot);
}
if (dot._lastColor !== s.color) {
dot._lastColor = s.color;
dot.style.stroke = s.color;
}
dot.setAttribute('cx', clampedX.toFixed(1));
dot.setAttribute('cy', y.toFixed(1));
dot.setAttribute('r', '3.2');
dot.setAttribute('fill', 'var(--surface-panel)');
dot.setAttribute('stroke', s.color);
dot.setAttribute('stroke-width', '1.8');
hoverDotsGroup.appendChild(dot);
if (dot.hasAttribute('hidden')) dot.removeAttribute('hidden');
activeDots.push(dot);
tipItems.push({ key: s.poolKey, label: s.label, color: s.color, val });
}
for (const [k, dot] of hoverDotPoolByKey.entries()) {
if (!usedKeys.has(k) && !dot.hasAttribute('hidden')) {
dot.setAttribute('hidden', '');
patchClasses(dot, { 'is-tracking': false });
}
}
if (tipItems.length === 0) {
hideHover();
return;
}
hoverLine.removeAttribute('hidden');
hoverDotsGroup.removeAttribute('hidden');
if (hoverLine.hasAttribute('hidden')) hoverLine.removeAttribute('hidden');
if (hoverDotsGroup.hasAttribute('hidden')) hoverDotsGroup.removeAttribute('hidden');
if (xTickElements.length > 1) {
syncHoveredTickClass(Math.round(u * (xTickElements.length - 1)));
}
const nextTimeStr = formatHoverTimestamp(targetMs);
if (nextTimeStr !== lastTipTimeStr) {
lastTipTimeStr = nextTimeStr;
patchText(tipTimeEl, nextTimeStr);
}
const nextWinStr = t(
selectedWin === 'weekly' ? 'settings.account.winWeekly' : 'settings.account.win5h'
);
if (nextWinStr !== lastTipWinStr) {
lastTipWinStr = nextWinStr;
patchText(tipWinEl, nextWinStr);
}
patchText(tipTimeEl, formatHoverTimestamp(targetMs));
patchText(tipWinEl, t(selectedWin === 'weekly' ? 'settings.account.winWeekly' : 'settings.account.win5h'));
patchKeyedList(tipRowsHost, tipItems, {
keyFn: (it) => it.key,
sigFn: (it) => `${it.label}:${it.val.toFixed(1)}`,
@@ -755,17 +886,61 @@ export const AccountQuotaTrendCard = defineComponent({
return { el: row, refs: { sw, nm, vl } };
},
updateRow: (r, it) => {
if (r.sw._lastBg !== it.color) {
r.sw._lastBg = it.color;
r.sw.style.background = it.color;
}
patchText(r.nm, it.label);
patchText(r.vl, `${+it.val.toFixed(1)}%`);
},
});
const pctX = (clampedX / viewW) * 100;
const shift = pctX < 24 ? '0%' : pctX > 76 ? '-100%' : '-50%';
patchStyleVar(tooltipEl, '--tip-x', `${pctX.toFixed(1)}%`);
patchStyleVar(tooltipEl, '--tip-shift', shift);
patchAttr(tooltipEl, 'hidden', false);
const wrapRect = tooltipCtrl.getWrapRect();
const wrapW =
wrapRect && wrapRect.width > 0
? wrapRect.width
: Number(chartWrap.clientWidth || viewW || 460);
lastFallbackX = (clampedX / Math.max(1, viewW)) * wrapW;
lastFallbackY = sumY / activeDots.length + 6;
lastActiveDots = activeDots;
lastSizeKey = `rows:${tipItems.length}`;
}
tooltipCtrl.show({
fallbackX: lastFallbackX,
fallbackY: lastFallbackY,
pointer: pointer || lastPointer,
trackedDots: lastActiveDots,
viewWidth: viewW,
viewHeight: VIEW_H,
sizeKey: lastSizeKey,
});
}
function handlePointerMove(ev) {
if (!plottedSeries.length || !(plottedEndMs > plottedStartMs)) {
hideHover();
return;
}
if (!cachedSvgRect) {
cachedSvgRect = svg.getBoundingClientRect?.() || null;
}
const rect = cachedSvgRect;
const widthPx = Number(rect?.width || viewW);
if (!(widthPx > 0)) {
cachedSvgRect = null;
return;
}
const offsetX = Number(ev.clientX || 0) - Number(rect?.left || 0);
const svgX = (offsetX / widthPx) * viewW;
const plotW = Math.max(20, viewW - LEFT_X - RIGHT_PAD);
const u = Math.max(0, Math.min(1, (svgX - LEFT_X) / plotW));
const slotIdx = Math.round(u * HOVER_SLOT_COUNT);
const pointer =
Number.isFinite(Number(ev?.clientX)) && Number.isFinite(Number(ev?.clientY))
? { clientX: Number(ev.clientX), clientY: Number(ev.clientY) }
: null;
showHoverAtSlot(slotIdx, pointer);
}
function resolveTargetAccountEmail() {
@@ -849,10 +1024,9 @@ export const AccountQuotaTrendCard = defineComponent({
);
}
function renderChart() {
hideHover();
function renderChart({ skipMorph = false } = {}) {
const nowMs = Date.now();
void getEffectiveLocale();
const locale = getEffectiveLocale();
patchText(cardTitleText, t('settings.account.trendTitle'));
patchText(rangeToEl, t('cons.rangeTo'));
@@ -932,6 +1106,9 @@ export const AccountQuotaTrendCard = defineComponent({
patchAttr(emptyStateEl, 'hidden', hasPlot);
if (!hasPlot) {
plottedSeries = [];
lastPlotSig = '';
seriesMorphCtrl.reset();
hideHover();
patchText(emptyStateEl, t('settings.account.trendEmpty'));
return;
}
@@ -947,9 +1124,8 @@ export const AccountQuotaTrendCard = defineComponent({
gl.setAttribute('x2', String(viewW));
}
plottedSeries = rawBuilt.map((rb) => ({
...rb,
svgPts: rb.rawPoints.map((sp) => {
plottedSeries = rawBuilt.map((rb) => {
const fullSvgPts = rb.rawPoints.map((sp) => {
const u = Math.max(0, Math.min(1, (sp.ts - plottedStartMs) / spanMs));
return {
x: LEFT_X + u * plotW,
@@ -957,50 +1133,112 @@ export const AccountQuotaTrendCard = defineComponent({
val: sp.val,
ts: sp.ts,
};
}),
}));
});
return {
...rb,
svgPts: simplifySvgPointsForRender(fullSvgPts, LEFT_X, plotW),
};
});
const plotSig =
`${locale}|${viewW}|${targetEmail}|${selectedWin}|${selectedRange}|${selectedPool}|${plottedYScale.yMin}-${plottedYScale.yMax}|` +
plottedSeries
.map(
(s) =>
`${s.poolKey}:${s.svgPts.length}:${s.svgPts[0]?.x.toFixed(1)}:${s.svgPts[0]?.y.toFixed(1)}:${s.svgPts[s.svgPts.length - 1]?.x.toFixed(1)}:${s.svgPts[s.svgPts.length - 1]?.y.toFixed(1)}`
)
.join('|');
if (plotSig !== lastPlotSig) {
lastPlotSig = plotSig;
const activePoolKeys = new Set();
const morphItems = [];
while (seriesGroup.firstChild) seriesGroup.removeChild(seriesGroup.firstChild);
for (let i = 0; i < plottedSeries.length; i++) {
const s = plottedSeries[i];
activePoolKeys.add(s.poolKey);
let nodes = seriesNodePoolByKey.get(s.poolKey);
if (!nodes) {
const areaEl = document.createElementNS(SVG_NS, 'path');
const lineEl = document.createElementNS(SVG_NS, 'path');
lineEl.setAttribute('fill', 'none');
lineEl.setAttribute('stroke-width', '1.9');
lineEl.setAttribute('stroke-linecap', 'round');
const endDotEl = document.createElementNS(SVG_NS, 'circle');
endDotEl.setAttribute('r', '2.7');
nodes = { areaEl, lineEl, endDotEl };
seriesNodePoolByKey.set(s.poolKey, nodes);
}
const lineD = buildHorizontalTangentSpline(s.svgPts);
let areaD = '';
if (s.svgPts.length >= 2) {
const first = s.svgPts[0];
const last = s.svgPts[s.svgPts.length - 1];
const areaEl = document.createElementNS(SVG_NS, 'path');
areaEl.setAttribute(
'd',
`${lineD} L ${last.x.toFixed(1)} ${BOTTOM_Y} L ${first.x.toFixed(1)} ${BOTTOM_Y} Z`
);
areaD = `${lineD} L ${last.x.toFixed(1)} ${BOTTOM_Y} L ${first.x.toFixed(1)} ${BOTTOM_Y} Z`;
if (plottedSeries.length === 1) {
stopTop.setAttribute('stop-color', s.color);
stopBot.setAttribute('stop-color', s.color);
areaEl.setAttribute('fill', `url(#${gradId})`);
nodes.areaEl.removeAttribute('class');
nodes.areaEl.style.removeProperty('--sstep-series-color');
nodes.areaEl.setAttribute('fill', `url(#${gradId})`);
} else {
areaEl.setAttribute('class', 'sstep-multi-area');
areaEl.style.setProperty('--sstep-series-color', s.color);
nodes.areaEl.removeAttribute('fill');
nodes.areaEl.setAttribute('class', 'sstep-multi-area');
nodes.areaEl.style.setProperty('--sstep-series-color', s.color);
}
seriesGroup.appendChild(areaEl);
nodes.areaEl.removeAttribute('hidden');
} else {
nodes.areaEl.setAttribute('d', '');
nodes.areaEl.setAttribute('hidden', '');
}
const pathEl = document.createElementNS(SVG_NS, 'path');
pathEl.setAttribute('d', lineD);
pathEl.setAttribute('fill', 'none');
pathEl.setAttribute('stroke', s.color);
pathEl.setAttribute('stroke-width', '1.9');
pathEl.setAttribute('stroke-linecap', 'round');
seriesGroup.appendChild(pathEl);
nodes.lineEl.setAttribute('stroke', s.color);
nodes.endDotEl.setAttribute('fill', s.color);
seriesGroup.appendChild(nodes.areaEl);
seriesGroup.appendChild(nodes.lineEl);
seriesGroup.appendChild(nodes.endDotEl);
const endPt = s.svgPts[s.svgPts.length - 1];
const endDot = document.createElementNS(SVG_NS, 'circle');
endDot.setAttribute('cx', endPt.x.toFixed(1));
endDot.setAttribute('cy', endPt.y.toFixed(1));
endDot.setAttribute('r', '2.7');
endDot.setAttribute('fill', s.color);
seriesGroup.appendChild(endDot);
morphItems.push({
key: s.poolKey,
nextSegs: pointsToNormalizedCubicSegs(s.svgPts, BOTTOM_Y, {
leftX: LEFT_X,
spanX: plotW,
tension: 0.38,
}),
lineEl: nodes.lineEl,
areaEl: areaD ? nodes.areaEl : null,
endDotEl: nodes.endDotEl,
endX: endPt.x,
endY: endPt.y,
finalLineD: lineD,
finalAreaD: areaD,
});
}
// Edge-to-edge X-axis ticks (`0% .. 100%`)
for (const [k, nodes] of seriesNodePoolByKey.entries()) {
if (!activePoolKeys.has(k)) {
nodes.areaEl.remove();
nodes.lineEl.remove();
nodes.endDotEl.remove();
}
}
seriesMorphCtrl.morphSeries({
items: morphItems,
leftX: LEFT_X,
spanX: plotW,
bottomY: BOTTOM_Y,
skipMorph,
});
}
// Edge-to-edge X-axis ticks (`0% .. 100%`) with active hover highlight & click-to-inspect
const tickCount = 5;
const activeTickIdx =
hoveredSlotIdx >= 0 ? Math.round((hoveredSlotIdx / HOVER_SLOT_COUNT) * (tickCount - 1)) : -1;
const ticks = [];
for (let k = 0; k < tickCount; k++) {
const ratio = k / (tickCount - 1);
@@ -1008,25 +1246,37 @@ export const AccountQuotaTrendCard = defineComponent({
const leftPct = ratio * 100;
ticks.push({
idx: k,
slotIdx: Math.round(ratio * HOVER_SLOT_COUNT),
leftPct,
label: formatAxisTickTime(tickMs, spanMs),
fullTitle: formatHoverTimestamp(tickMs),
edge: k === 0 ? 'start' : k === tickCount - 1 ? 'end' : '',
isHovered: k === activeTickIdx,
});
}
xTickElements = [];
lastHoveredTickIdx = activeTickIdx;
patchKeyedList(xAxisEl, ticks, {
keyFn: (tk) => tk.idx,
sigFn: (tk) => `${tk.leftPct.toFixed(1)}:${tk.label}:${tk.edge}`,
sigFn: (tk) => `${tk.leftPct.toFixed(1)}:${tk.label}:${tk.edge}:${tk.isHovered}`,
createRow: () => {
const el = h('span', { className: 'trend-x-tick text-mono' });
return { el, refs: { el } };
},
updateRow: (r, tk) => {
patchText(r.el, tk.label);
patchAttr(r.el, 'title', tk.fullTitle);
patchStyleVar(r.el, '--tick-x', `${tk.leftPct.toFixed(2)}%`);
patchClasses(r.el, {
'is-start': tk.edge === 'start',
'is-end': tk.edge === 'end',
'is-hovered': tk.isHovered,
});
r.el.onclick = () => {
lastPointer = null;
showHoverAtSlot(tk.slotIdx, null, { forceRefresh: true });
};
xTickElements[tk.idx] = r.el;
},
});
@@ -1046,21 +1296,29 @@ export const AccountQuotaTrendCard = defineComponent({
patchText(r.vl, `${+s.latestVal.toFixed(1)}%`);
},
});
if (hoveredSlotIdx >= 0) {
showHoverAtSlot(hoveredSlotIdx, lastPointer, { forceRefresh: true });
}
}
let resizeObs = null;
if (typeof ResizeObserver === 'function') {
resizeObs = new ResizeObserver((entries) => {
cachedSvgRect = null;
tooltipCtrl.invalidateRects();
const w = Math.floor(Number(entries?.[0]?.contentRect?.width || 0));
if (w >= 180 && Math.abs(w - viewW) >= 2) {
viewW = w;
renderChart();
renderChart({ skipMorph: true });
}
});
resizeObs.observe(plotStage);
}
onCleanup(() => {
seriesMorphCtrl.cancel();
tooltipCtrl.destroy();
resizeObs?.disconnect();
accountSelect.destroy();
poolSelect.destroy();
@@ -1078,7 +1336,7 @@ export const AccountQuotaTrendCard = defineComponent({
renderChart();
return {
el: rootEl,
refs: { update, refreshLabels: renderChart },
refs: { update, refreshLabels: () => renderChart() },
};
},
});
@@ -182,6 +182,28 @@ export function patchCapsuleOdometerText(
return true;
}
function isValidTtftSec(val) {
return val != null && Number.isFinite(Number(val)) && Number(val) >= 0;
}
function findFallbackRecentStepTtft(steps) {
if (!Array.isArray(steps) || steps.length === 0) return null;
const firstIdx = Number(steps[0]?.stepIndex ?? 0);
const lastIdx = Number(steps[steps.length - 1]?.stepIndex ?? 0);
if (firstIdx >= lastIdx) {
for (let i = 0; i < steps.length; i += 1) {
const candidate = steps[i]?.ttftSec;
if (isValidTtftSec(candidate)) return Number(candidate);
}
return null;
}
for (let i = steps.length - 1; i >= 0; i -= 1) {
const candidate = steps[i]?.ttftSec;
if (isValidTtftSec(candidate)) return Number(candidate);
}
return null;
}
/**
* Compute shared context ring + 1..5 capsule slot metric payload from telemetry & scoped conversation.
*/
@@ -204,11 +226,29 @@ export function buildCapsuleSlotContext(
).toFixed(2);
const isRunning = Boolean(aggregated?.isRunning || activeConv.isRunning);
const convId = String(capActive.cascadeId || activeConv.cascadeId || '')
.trim()
.toLowerCase();
const scopeId = String(scopedConv?.agentId || aggregated?.agentId || 'main');
const conversationKey = convId ? `${convId}::${scopeId}` : '';
const stepCount = Math.max(0, Number(capActive.stepCount ?? activeConv.stepCount ?? 0));
const rawTtft =
scopedConv?.latestTtftSec ?? aggregated?.latestTtftSec ?? activeConv.latestTtftSec ?? null;
const fallbackTtft = isValidTtftSec(rawTtft)
? Number(rawTtft)
: scopedConv?.lastKnownTtftSec ??
findFallbackRecentStepTtft(scopedConv?.recentSteps) ??
aggregated?.lastKnownTtftSec ??
activeConv.lastKnownTtftSec ??
findFallbackRecentStepTtft(activeConv.recentSteps);
const resolvedTtft = isValidTtftSec(fallbackTtft) ? Number(fallbackTtft) : null;
const capInTok = Math.max(0, Number(capActive.inputTokens || 0));
const capCacheTok = Math.max(0, Number(capActive.cacheReadTokens || 0));
const capOutTok = Math.max(0, Number(capActive.outputTokens || 0));
const sessionTokens =
Number(capActive.stepCount || 0) > 0 ||
stepCount > 0 ||
capActive.totalTokens != null ||
capInTok + capCacheTok + capOutTok > 0
? Math.max(0, Number(capActive.totalTokens ?? capInTok + capCacheTok + capOutTok))
@@ -216,12 +256,14 @@ export function buildCapsuleSlotContext(
return {
hasTelemetry: true,
conversationKey,
stepCount,
usedPct,
dashOffset,
isRunning,
tps: scopedConv?.latestTokPerSec ?? aggregated?.latestTokPerSec ?? activeConv.latestTokPerSec ?? null,
avgTps: scopedConv?.avgTokPerSec ?? aggregated?.avgTokPerSec ?? activeConv.avgTokPerSec ?? null,
ttft: scopedConv?.latestTtftSec ?? aggregated?.latestTtftSec ?? activeConv.latestTtftSec ?? null,
ttft: resolvedTtft,
stepCost:
scopedConv?.latestStepCostUsd ??
aggregated?.latestStepCostUsd ??
@@ -351,6 +393,7 @@ export function createCapsuleSlotNode(slotIndex, initialMetric) {
textSpan,
ringMounted: isCtx,
prefixMounted: false,
heldTtft: null,
};
}
@@ -363,7 +406,25 @@ export function syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, slotCt
for (let i = 0; i < capsuleSlots.length; i += 1) {
const slot = capsuleSlots[i];
const metricKey = i < slotKeys.length ? slotKeys[i] : 'none';
const pres = resolveCapsuleMetricPresentation(metricKey, slotCtx, RING_CIRCUMFERENCE);
if (!slotCtx?.hasTelemetry || metricKey !== 'ttft') {
slot.heldTtft = null;
}
let pres = resolveCapsuleMetricPresentation(metricKey, slotCtx, RING_CIRCUMFERENCE);
if (metricKey === 'ttft' && slotCtx?.hasTelemetry) {
const convKey = String(slotCtx.conversationKey || '');
if (isValidTtftSec(slotCtx.ttft)) {
slot.heldTtft = convKey ? { conversationKey: convKey, pres } : null;
} else if (
convKey &&
slot.heldTtft &&
slot.heldTtft.conversationKey === convKey &&
(slotCtx.isRunning || Number(slotCtx.stepCount) > 0)
) {
pres = { ...slot.heldTtft.pres, running: Boolean(slotCtx.isRunning) };
} else {
slot.heldTtft = null;
}
}
if (pres.hidden) {
patchAttr(slot.el, 'hidden', true);
patchAttr(slot.el, 'data-metric', 'none');
@@ -756,6 +756,7 @@ export function isEquivalentTelemetry(prev, next) {
if (pAct?.aggregated?.activeAgentBadge !== nAct?.aggregated?.activeAgentBadge) return false;
if (pAct?.aggregated?.latestTokPerSec !== nAct?.aggregated?.latestTokPerSec) return false;
if (pAct?.aggregated?.latestTtftSec !== nAct?.aggregated?.latestTtftSec) return false;
if (pAct?.aggregated?.lastKnownTtftSec !== nAct?.aggregated?.lastKnownTtftSec) return false;
if (pAct?.aggregated?.avgTokPerSec !== nAct?.aggregated?.avgTokPerSec) return false;
if (pAct?.aggregated?.latestStepCostUsd !== nAct?.aggregated?.latestStepCostUsd) return false;
if (pAct?.aggregated?.sessionCostUsd !== nAct?.aggregated?.sessionCostUsd) return false;
@@ -767,6 +768,7 @@ export function isEquivalentTelemetry(prev, next) {
if (pAct?.aggregated?.latestSpeedReason !== nAct?.aggregated?.latestSpeedReason) return false;
if (pAct?.latestTokPerSec !== nAct?.latestTokPerSec) return false;
if (pAct?.latestTtftSec !== nAct?.latestTtftSec) return false;
if (pAct?.lastKnownTtftSec !== nAct?.lastKnownTtftSec) return false;
if (pAct?.avgTokPerSec !== nAct?.avgTokPerSec) return false;
if (pAct?.latestCacheHitPct !== nAct?.latestCacheHitPct) return false;
if (pAct?.sessionCacheHitPct !== nAct?.sessionCacheHitPct) return false;
@@ -805,6 +807,7 @@ export function isEquivalentTelemetry(prev, next) {
pa?.liveActivity?.signature !== na?.liveActivity?.signature ||
pa?.latestTokPerSec !== na?.latestTokPerSec ||
pa?.latestTtftSec !== na?.latestTtftSec ||
pa?.lastKnownTtftSec !== na?.lastKnownTtftSec ||
pa?.avgTokPerSec !== na?.avgTokPerSec ||
pa?.latestCacheHitPct !== na?.latestCacheHitPct ||
pa?.sessionCacheHitPct !== na?.sessionCacheHitPct ||
+22 -2
View File
@@ -854,7 +854,7 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
border: none;
}
[data-modern-ui="true"] .trend-tooltip:not(.is-hm-top):not(.is-hm-bottom):not(.is-rich-breakdown) {
[data-modern-ui="true"] .trend-tooltip:not(.is-hm-top):not(.is-hm-bottom):not(.is-rich-breakdown):not(.is-floating-tip) {
top: 2px;
bottom: auto;
transform: translate3d(var(--tip-shift, -50%), var(--tip-y, 0px), 0);
@@ -868,6 +868,14 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
translateX(var(--tip-shift, 0px));
}
[data-modern-ui="true"] .trend-tooltip.is-floating-tip {
top: 0;
bottom: auto;
left: 0;
transform: translate3d(var(--tip-x, 0px), var(--tip-y, 0px), 0)
translateX(var(--tip-shift, 0px));
}
[data-modern-ui="true"] .trend-tooltip.is-tracking {
transition:
left 150ms var(--ease-modern),
@@ -880,7 +888,12 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
transition: transform 150ms var(--ease-modern);
}
[data-modern-ui="true"] .trend-hover-dot.is-tracking {
[data-modern-ui="true"] .trend-tooltip.is-floating-tip.is-tracking {
transition: transform 150ms var(--ease-modern);
}
[data-modern-ui="true"] .trend-hover-dot.is-tracking,
[data-modern-ui="true"] .sstep-hover-raw-dot.is-tracking {
transition:
cx 150ms var(--ease-modern),
cy 150ms var(--ease-modern);
@@ -1008,6 +1021,13 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
will-change: transform;
}
@starting-style {
:host([data-modern-ui="true"]) .wm-od-track,
[data-modern-ui="true"] .wm-od-track {
transform: translate3d(0, 0, 0);
}
}
:host([data-modern-ui="true"]) .wm-od-cell,
[data-modern-ui="true"] .wm-od-cell {
display: block;
@@ -401,6 +401,7 @@
height: 184px;
display: block;
overflow: visible;
pointer-events: none;
}
.trend-grid line {
@@ -459,20 +460,24 @@
z-index: 2;
}
.cons-view-stage .progress-seg {
.cons-view-stage .progress-seg,
.models-analytics-pane .progress-seg {
flex: 0 0 auto;
transition:
background-color 80ms ease,
width 240ms cubic-bezier(0.22, 1, 0.36, 1);
}
.cons-view-stage .progress-fill {
.cons-view-stage .progress-fill,
.account-cards-stack .progress-fill {
transition: width 240ms cubic-bezier(0.22, 1, 0.36, 1);
}
@starting-style {
.cons-view-stage.is-ready .progress-seg,
.cons-view-stage.is-ready .progress-fill {
.cons-view-stage.is-ready .progress-fill,
.models-analytics-pane .progress-seg,
.account-cards-stack .progress-fill {
width: 0%;
}
}
@@ -498,8 +503,13 @@
@media (prefers-reduced-motion: reduce) {
.cons-view-stage .progress-seg,
.cons-view-stage .progress-fill,
.models-analytics-pane .progress-seg,
.account-cards-stack .progress-fill,
.trend-peak-pill.is-ready,
.trend-hm-cell {
.trend-hm-cell,
.trend-tooltip.is-tracking,
.trend-hover-dot.is-tracking,
.sstep-hover-raw-dot.is-tracking {
transition: none !important;
}
.cons-item-list.is-bars-revealing .progress-track {
@@ -1190,6 +1200,28 @@
contain: layout style;
}
.trend-tooltip.is-floating-tip {
top: 0;
bottom: auto;
left: 0;
transform: translate3d(var(--tip-x, 0px), var(--tip-y, 0px), 0)
translateX(var(--tip-shift, 0px));
will-change: transform;
contain: layout style;
}
.trend-tooltip.is-floating-tip.is-tracking,
.trend-tooltip.is-rich-breakdown.is-tracking {
transition: transform 150ms var(--ease-modern, cubic-bezier(0.16, 1, 0.3, 1));
}
.trend-hover-dot.is-tracking,
.sstep-hover-raw-dot.is-tracking {
transition:
cx 150ms var(--ease-modern, cubic-bezier(0.16, 1, 0.3, 1)),
cy 150ms var(--ease-modern, cubic-bezier(0.16, 1, 0.3, 1));
}
.trend-tooltip.is-rich-breakdown,
.cons-breakdown-popover.is-rich-breakdown {
min-width: 212px;
@@ -775,6 +775,7 @@
height: 106px;
display: block;
overflow: visible;
pointer-events: none;
}
.sstep-fit-svg {
+59 -6
View File
@@ -3200,6 +3200,7 @@ html[data-standalone="true"] .app-shell {
height: 184px;
display: block;
overflow: visible;
pointer-events: none;
}
.trend-grid line {
@@ -3258,20 +3259,24 @@ html[data-standalone="true"] .app-shell {
z-index: 2;
}
.cons-view-stage .progress-seg {
.cons-view-stage .progress-seg,
.models-analytics-pane .progress-seg {
flex: 0 0 auto;
transition:
background-color 80ms ease,
width 240ms cubic-bezier(0.22, 1, 0.36, 1);
}
.cons-view-stage .progress-fill {
.cons-view-stage .progress-fill,
.account-cards-stack .progress-fill {
transition: width 240ms cubic-bezier(0.22, 1, 0.36, 1);
}
@starting-style {
.cons-view-stage.is-ready .progress-seg,
.cons-view-stage.is-ready .progress-fill {
.cons-view-stage.is-ready .progress-fill,
.models-analytics-pane .progress-seg,
.account-cards-stack .progress-fill {
width: 0%;
}
}
@@ -3297,8 +3302,13 @@ html[data-standalone="true"] .app-shell {
@media (prefers-reduced-motion: reduce) {
.cons-view-stage .progress-seg,
.cons-view-stage .progress-fill,
.models-analytics-pane .progress-seg,
.account-cards-stack .progress-fill,
.trend-peak-pill.is-ready,
.trend-hm-cell {
.trend-hm-cell,
.trend-tooltip.is-tracking,
.trend-hover-dot.is-tracking,
.sstep-hover-raw-dot.is-tracking {
transition: none !important;
}
.cons-item-list.is-bars-revealing .progress-track {
@@ -3989,6 +3999,28 @@ html[data-standalone="true"] .app-shell {
contain: layout style;
}
.trend-tooltip.is-floating-tip {
top: 0;
bottom: auto;
left: 0;
transform: translate3d(var(--tip-x, 0px), var(--tip-y, 0px), 0)
translateX(var(--tip-shift, 0px));
will-change: transform;
contain: layout style;
}
.trend-tooltip.is-floating-tip.is-tracking,
.trend-tooltip.is-rich-breakdown.is-tracking {
transition: transform 150ms var(--ease-modern, cubic-bezier(0.16, 1, 0.3, 1));
}
.trend-hover-dot.is-tracking,
.sstep-hover-raw-dot.is-tracking {
transition:
cx 150ms var(--ease-modern, cubic-bezier(0.16, 1, 0.3, 1)),
cy 150ms var(--ease-modern, cubic-bezier(0.16, 1, 0.3, 1));
}
.trend-tooltip.is-rich-breakdown,
.cons-breakdown-popover.is-rich-breakdown {
min-width: 212px;
@@ -5058,6 +5090,7 @@ html[data-standalone="true"] .app-shell {
height: 106px;
display: block;
overflow: visible;
pointer-events: none;
}
.sstep-fit-svg {
@@ -9109,7 +9142,7 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
border: none;
}
[data-modern-ui="true"] .trend-tooltip:not(.is-hm-top):not(.is-hm-bottom):not(.is-rich-breakdown) {
[data-modern-ui="true"] .trend-tooltip:not(.is-hm-top):not(.is-hm-bottom):not(.is-rich-breakdown):not(.is-floating-tip) {
top: 2px;
bottom: auto;
transform: translate3d(var(--tip-shift, -50%), var(--tip-y, 0px), 0);
@@ -9123,6 +9156,14 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
translateX(var(--tip-shift, 0px));
}
[data-modern-ui="true"] .trend-tooltip.is-floating-tip {
top: 0;
bottom: auto;
left: 0;
transform: translate3d(var(--tip-x, 0px), var(--tip-y, 0px), 0)
translateX(var(--tip-shift, 0px));
}
[data-modern-ui="true"] .trend-tooltip.is-tracking {
transition:
left 150ms var(--ease-modern),
@@ -9135,7 +9176,12 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
transition: transform 150ms var(--ease-modern);
}
[data-modern-ui="true"] .trend-hover-dot.is-tracking {
[data-modern-ui="true"] .trend-tooltip.is-floating-tip.is-tracking {
transition: transform 150ms var(--ease-modern);
}
[data-modern-ui="true"] .trend-hover-dot.is-tracking,
[data-modern-ui="true"] .sstep-hover-raw-dot.is-tracking {
transition:
cx 150ms var(--ease-modern),
cy 150ms var(--ease-modern);
@@ -9263,6 +9309,13 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
will-change: transform;
}
@starting-style {
:host([data-modern-ui="true"]) .wm-od-track,
[data-modern-ui="true"] .wm-od-track {
transform: translate3d(0, 0, 0);
}
}
:host([data-modern-ui="true"]) .wm-od-cell,
[data-modern-ui="true"] .wm-od-cell {
display: block;
+279 -1
View File
@@ -15,11 +15,19 @@ import {
parseCssColorLuminance,
} from '../src/core/appearance.js';
import { createTrendAreaChart } from '../src/components/charts/TrendAreaChart.js';
import { computePublicationFit } from '../src/components/charts/SessionStepCharts.js';
import {
computePublicationFit,
createModelFitChart,
createSessionLineChart,
} from '../src/components/charts/SessionStepCharts.js';
import { CustomSelect } from '../src/components/ui/CustomSelect.js';
import { SegmentedControl } from '../src/components/ui/SegmentedControl.js';
import { AccountQuotaTrendCard } from '../src/components/widgets/AccountQuotaTrendCard.js';
import {
buildCapsuleSlotContext,
createCapsuleSlotNode,
patchCapsuleOdometerText,
syncCapsuleSlotNodes,
tokenizeCapsuleOdometerText,
} from '../src/components/widgets/CapsuleBarWidget.js';
import { ContextWindowWidget } from '../src/components/widgets/ContextWindowWidget.js';
@@ -558,12 +566,21 @@ test('SegmentedControl variable-width glider snaps cleanly on reveal and glides
const tipEl = trendChart.el.querySelector('.trend-tooltip');
Object.assign(tipEl, { offsetWidth: 216, offsetHeight: 82 });
const plotStage = trendChart.el.querySelector('.trend-plot-stage');
const trendPeakPill = trendChart.el.querySelector('.trend-peak-pill');
const svgEl = trendChart.el.querySelector('.trend-svg');
svgEl.getBoundingClientRect = () => ({ left: 0, top: 246, width: 460, height: 184, right: 460, bottom: 430 });
// Zero-data slots must keep peak pill hidden even after hover + mouseleave
trendChart.update([{ index: 0, label: '00:53', fullLabel: '11月25日 00:53 - 00:54', tokens: 0, calls: 0, costUsd: 0 }]);
assert.equal(trendPeakPill.hasAttribute('hidden'), true, 'Zero-data chart must hide peak pill');
plotStage.dispatchEvent({ type: 'mousemove', clientX: 200, clientY: 340 });
plotStage.dispatchEvent({ type: 'mouseleave' });
assert.equal(trendPeakPill.hasAttribute('hidden'), true, 'Peak pill stays hidden after mouseleave on zero-data chart');
trendChart.update([
{ index: 0, label: '00:00', fullLabel: '11月19日 00:00 - 01:00', tokens: 1000, calls: 2, costUsd: 0.1 },
{ index: 1, label: '10:00', fullLabel: '11月19日 10:00 - 11:00', tokens: 25_000_000, calls: 80, costUsd: 6.37 },
]);
assert.equal(trendPeakPill.hasAttribute('hidden'), false, 'Non-zero chart shows peak pill');
queuedRaf = null;
plotStage.dispatchEvent({ type: 'mousemove', clientX: 80, clientY: 360 });
const firstY = tipEl.style.getPropertyValue('--tip-y');
@@ -581,6 +598,135 @@ test('SegmentedControl variable-width glider snaps cleanly on reveal and glides
assert.equal(tipEl.style.getPropertyValue('--tip-y'), '54px');
trendChart.destroy();
// 10b. SessionStepCharts (Summary view) and AccountQuotaTrendCard share 2D pointer-following tooltip + .is-tracking focus dots
const stepLineChart = createSessionLineChart();
Object.assign(stepLineChart.el, {
clientWidth: 460,
offsetHeight: 130,
getBoundingClientRect: () => ({ left: 0, top: 200, width: 460, height: 130, right: 460, bottom: 330 }),
});
const stepTipEl = stepLineChart.el.querySelector('.trend-tooltip');
assert.equal(stepTipEl.classList.contains('is-floating-tip'), true);
Object.assign(stepTipEl, { offsetWidth: 208, offsetHeight: 76 });
const stepStage = stepLineChart.el.querySelector('.sstep-plot-stage');
const stepSvg = stepLineChart.el.querySelector('.sstep-svg');
stepSvg.getBoundingClientRect = () => ({ left: 0, top: 206, width: 460, height: 106, right: 460, bottom: 312 });
stepLineChart.update({
steps: [
{ stepIndex: 1, createdAtMs: 1000, modelShort: 'Gemini', totalTokens: 12000, inputTokens: 8000, cacheReadTokens: 2000, outputTokens: 2000, tokPerSec: 60, ttftSec: 0.4 },
{ stepIndex: 2, createdAtMs: 2000, modelShort: 'Gemini', totalTokens: 28000, inputTokens: 16000, cacheReadTokens: 8000, outputTokens: 4000, tokPerSec: 75, ttftSec: 0.3 },
],
metric: 'totalTokens',
});
queuedRaf?.();
assert.equal(stepLineChart.el.querySelector('.trend-peak-pill').classList.contains('is-ready'), true);
queuedRaf = null;
stepStage.dispatchEvent({ type: 'mousemove', clientX: 120, clientY: 300 });
assert.equal(stepTipEl.style.getPropertyValue('--tip-shift'), '0px');
assert.equal(stepTipEl.style.getPropertyValue('--tip-y'), '10px');
const stepHoverDot = stepLineChart.el.querySelector('.trend-hover-dot');
assert.equal(stepTipEl.classList.contains('is-tracking'), false);
assert.equal(stepHoverDot.classList.contains('is-tracking'), false);
queuedRaf?.();
assert.equal(stepTipEl.classList.contains('is-tracking'), true);
assert.equal(stepHoverDot.classList.contains('is-tracking'), true);
stepLineChart.destroy();
const fitChart = createModelFitChart();
Object.assign(fitChart.el, {
clientWidth: 460,
offsetHeight: 160,
getBoundingClientRect: () => ({ left: 0, top: 200, width: 460, height: 160, right: 460, bottom: 360 }),
});
const fitTipEl = fitChart.el.querySelector('.trend-tooltip');
assert.equal(fitTipEl.classList.contains('is-floating-tip'), true);
Object.assign(fitTipEl, { offsetWidth: 212, offsetHeight: 74 });
fitChart.el.querySelector('.sstep-fit-svg').getBoundingClientRect = () => ({
left: 0,
top: 204,
width: 460,
height: 138,
right: 460,
bottom: 342,
});
fitChart.update({
steps: [
{ stepIndex: 1, createdAtMs: 1000, modelShort: 'Gemini', tokPerSec: 55 },
{ stepIndex: 2, createdAtMs: 2000, modelShort: 'Gemini', tokPerSec: 68 },
{ stepIndex: 3, createdAtMs: 3000, modelShort: 'Gemini', tokPerSec: 72 },
],
metric: 'tps',
});
queuedRaf = null;
fitChart.el.querySelector('.sstep-plot-stage').dispatchEvent({ type: 'mousemove', clientX: 220, clientY: 310 });
queuedRaf?.();
assert.equal(fitTipEl.classList.contains('is-tracking'), true);
assert.equal(fitChart.el.querySelector('.trend-hover-dot').classList.contains('is-tracking'), true);
assert.equal(fitChart.el.querySelector('.sstep-hover-raw-dot').classList.contains('is-tracking'), true);
fitChart.destroy();
const nowQ = Date.now();
const quotaCard = AccountQuotaTrendCard({});
const quotaWrap = quotaCard.el.querySelector('.trend-chart-wrap');
Object.assign(quotaWrap, {
clientWidth: 460,
offsetHeight: 210,
getBoundingClientRect: () => ({ left: 0, top: 200, width: 460, height: 210, right: 460, bottom: 410 }),
});
const quotaTipEl = quotaCard.el.querySelector('.trend-tooltip');
assert.equal(quotaTipEl.classList.contains('is-floating-tip'), true);
Object.assign(quotaTipEl, { offsetWidth: 200, offsetHeight: 74 });
quotaCard.el.querySelector('.trend-svg').getBoundingClientRect = () => ({
left: 0,
top: 206,
width: 460,
height: 184,
right: 460,
bottom: 390,
});
quotaCard.refs.update({
activeEmail: 'user@example.com',
activePools: [
{
poolKey: 'Gemini',
poolLabel: 'Gemini',
remainingPct: 91,
weeklyRemainingPct: 88,
resetTime: new Date(nowQ + 2 * 3600_000).toISOString(),
},
],
quotaHistory: {
'user@example.com': {
pools: {
Gemini: {
label: 'Gemini',
reset5hMs: nowQ + 2 * 3600_000,
points: [
[nowQ - 3 * 3600_000 + 2000, 100, 90],
[nowQ - 3600_000, 95, 89],
],
},
},
},
},
});
queuedRaf = null;
quotaCard.el.querySelector('.trend-plot-stage').dispatchEvent({
type: 'mousemove',
clientX: 230,
clientY: 320,
});
assert.equal(quotaTipEl.style.getPropertyValue('--tip-y'), '32px');
queuedRaf?.();
assert.equal(quotaTipEl.classList.contains('is-tracking'), true);
assert.equal(quotaCard.el.querySelector('.trend-hover-dot').classList.contains('is-tracking'), true);
assert.equal(
quotaCard.el.querySelectorAll('.trend-x-tick').some((tk) => tk.classList.contains('is-hovered')),
true,
'Hovering quota chart highlights nearest X-axis tick'
);
quotaCard.destroy();
// 11. ContextWindowWidget + LiveActivityWidget use pure SVG chevrons and animate expand/collapse under [data-modern-ui="true"]
document.documentElement.setAttribute('data-modern-ui', 'true');
const ctxWidget = ContextWindowWidget({});
@@ -1236,4 +1382,136 @@ test('Capsule odometer digit rolling (0.15s) and color transition (0.1s) stay st
builtStyles,
/\[data-modern-ui="true"\]\s+\.trend-tooltip\.is-rich-breakdown\.is-tracking\s*\{\s*transition:\s*transform\s+150ms\s+var\(--ease-modern\);\s*\}/
);
assert.match(
builtStyles,
/@starting-style\s*\{[\s\S]*?\[data-modern-ui="true"\]\s+\.wm-od-track\s*\{\s*transform:\s*translate3d\(0,\s*0,\s*0\);/
);
assert.match(
builtStyles,
/\.trend-tooltip\.is-floating-tip\s*\{[^}]*left:\s*0;[^}]*transform:\s*translate3d\(var\(--tip-x,\s*0px\),\s*var\(--tip-y,\s*0px\),\s*0\)/
);
// 6. Pending TTFT during a new step must NOT flash --s or destroy odometer reels before TTFT is calculated
const capHost = document.createElement('div');
capHost.setAttribute('data-modern-ui', 'true');
const capSlots = [
createCapsuleSlotNode(0, 'tps'),
createCapsuleSlotNode(1, 'ttft'),
createCapsuleSlotNode(2, 'context'),
createCapsuleSlotNode(3, 'none'),
createCapsuleSlotNode(4, 'none'),
];
const capSeps = Array.from({ length: 4 }, () => document.createElement('span'));
for (const s of capSlots) capHost.appendChild(s.el);
document.body.appendChild(capHost);
const slotKeys = ['tps', 'ttft', 'context'];
// Poll 1: Step #10075 finished with ttft = 13.3s
syncCapsuleSlotNodes(
capSlots,
capSeps,
slotKeys,
buildCapsuleSlotContext({
activeConversation: {
cascadeId: 'df95cefc-791c-4ece-b433-d6ac4ad10316',
isRunning: false,
stepCount: 2131,
latestTokPerSec: 7.4,
latestTtftSec: 13.3,
lastKnownTtftSec: 13.3,
context: { totalTokens: 130000, compactionLimitTokens: 256000 },
},
})
);
assert.equal(capSlots[1].textSpan.getAttribute('data-od-value'), '13.3s');
const ttftReelsStep1 = capSlots[1].textSpan.querySelectorAll('.wm-od-digit');
assert.equal(ttftReelsStep1.length, 3);
const savedOnesReel = ttftReelsStep1[1];
const savedTenthsReel = ttftReelsStep1[2];
// Poll 2: Step #10077 streaming (10.5 t/s, latestTtftSec = null while TTFT is not calculated yet, even without lastKnownTtftSec)
syncCapsuleSlotNodes(
capSlots,
capSeps,
slotKeys,
buildCapsuleSlotContext({
activeConversation: {
cascadeId: 'df95cefc-791c-4ece-b433-d6ac4ad10316',
isRunning: true,
stepCount: 2132,
latestTokPerSec: 10.5,
latestTtftSec: null,
context: { totalTokens: 131000, compactionLimitTokens: 256000 },
},
})
);
assert.equal(
capSlots[1].textSpan.getAttribute('data-od-value'),
'13.3s',
'TTFT slot keeps previous valid TTFT while new step TTFT is still pending'
);
const ttftReelsPending = capSlots[1].textSpan.querySelectorAll('.wm-od-digit');
assert.equal(ttftReelsPending.length, 3);
assert.equal(ttftReelsPending[1], savedOnesReel);
assert.equal(ttftReelsPending[2], savedTenthsReel);
// Poll 2b: Cold-mounted slot mid-generation resolves lastKnownTtftSec / recentSteps fallback instead of --s
const coldSlotCtx = buildCapsuleSlotContext({
activeConversation: {
cascadeId: 'df95cefc-791c-4ece-b433-d6ac4ad10316',
isRunning: true,
stepCount: 2132,
latestTokPerSec: 10.5,
latestTtftSec: null,
lastKnownTtftSec: 13.3,
context: { totalTokens: 131000, compactionLimitTokens: 256000 },
},
});
assert.equal(coldSlotCtx.ttft, 13.3);
// Poll 3: Step #10077 TTFT calculated (8.4s) -> rolls directly 13.3s -> 8.4s on the preserved DOM reels
syncCapsuleSlotNodes(
capSlots,
capSeps,
slotKeys,
buildCapsuleSlotContext({
activeConversation: {
cascadeId: 'df95cefc-791c-4ece-b433-d6ac4ad10316',
isRunning: true,
stepCount: 2132,
latestTokPerSec: 10.5,
latestTtftSec: 8.4,
lastKnownTtftSec: 8.4,
context: { totalTokens: 131000, compactionLimitTokens: 256000 },
},
})
);
assert.equal(capSlots[1].textSpan.getAttribute('data-od-value'), '8.4s');
const ttftReelsResolved = capSlots[1].textSpan.querySelectorAll('.wm-od-digit');
assert.equal(ttftReelsResolved.length, 2);
assert.equal(ttftReelsResolved[0], savedOnesReel, 'Ones reel stays mounted for 150ms roll');
assert.equal(ttftReelsResolved[1], savedTenthsReel, 'Tenths reel stays mounted for 150ms roll');
assert.equal(savedOnesReel.querySelector('.wm-od-track').style.getPropertyValue('--od-val'), '8');
assert.equal(savedTenthsReel.querySelector('.wm-od-track').style.getPropertyValue('--od-val'), '4');
// Poll 4: Switching to a different conversation with no TTFT resets cleanly to --s without leaking
syncCapsuleSlotNodes(
capSlots,
capSeps,
slotKeys,
buildCapsuleSlotContext({
activeConversation: {
cascadeId: 'dddddddd-7777-8888-9999-eeeeeeeeeeee',
isRunning: false,
stepCount: 8,
latestTokPerSec: 120.5,
latestTtftSec: null,
recentSteps: [],
context: { totalTokens: 64000, compactionLimitTokens: 256000 },
},
})
);
assert.equal(capSlots[1].textSpan.textContent, '--s');
assert.equal(capSlots[1].textSpan.hasAttribute('data-od-active'), false);
});