feat(panel): add sub-hour trend bucketing and smooth range switches

- Enforce strict window bounds on usage trends without 6-hour out-of-window padding, subdividing sub-2h intraday spans into 1m, 5m, and 15m slots with stepMs cache invalidation and minute export labels
- Morph SVG trend curves and areas continuously across varying slot counts via De Casteljau cubic Bezier knot subdivision, synchronized with peak pill glides, axis fades, and heatmap stage transitions
- Coordinate consumption range, tab, and sort switches with opacity crossfades and @starting-style progress bar width transitions while respecting prefers-reduced-motion
This commit is contained in:
fish
2026-11-24 04:41:26 +09:00
parent 49fe0b3457
commit 7e6d11d7aa
12 changed files with 1591 additions and 199 deletions
+537 -23
View File
@@ -1520,6 +1520,7 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({
'cons.trendTitle': '用量趋势',
'cons.allTime': '全部时间',
'cons.trendHeatmapHint': '按日 ({days}天) · 悬停查看',
'cons.trendPointsHintMinute': '按 {minutes} 分钟 ({points}点) · 悬停查看',
'cons.trendPointsHintHourly': '按小时 ({points}点) · 悬停查看',
'cons.trendPointsHintDaily': '按日 ({points}点) · 悬停查看',
'cons.topModels': '模型排行',
@@ -2413,6 +2414,7 @@ const I18N_MESSAGES_EN_US = Object.freeze({
'cons.trendTitle': 'Usage Trend',
'cons.allTime': 'All Time',
'cons.trendHeatmapHint': 'Daily ({days}d) · Hover for details',
'cons.trendPointsHintMinute': '{minutes}m ({points} pts) · Hover for details',
'cons.trendPointsHintHourly': 'Hourly ({points} pts) · Hover for details',
'cons.trendPointsHintDaily': 'Daily ({points} pts) · Hover for details',
'cons.topModels': 'Top Models',
@@ -8025,8 +8027,11 @@ function buildConsumptionXlsx(
let tTot = 0;
let tCost = 0;
const trendRows = trend.map((slot) => {
const isMinute = slot.granularity === 'minute';
const isHourly =
slot.granularity === 'hour' || String(slot.label || '').includes(':');
isMinute ||
slot.granularity === 'hour' ||
String(slot.label || '').includes(':');
const calls = Math.max(0, Number(slot.calls || 0));
const inTok = Math.max(0, Number(slot.inputTokens || 0));
const cacheTok = Math.max(0, Number(slot.cacheReadTokens || 0));
@@ -8039,7 +8044,12 @@ function buildConsumptionXlsx(
tOut += outTok;
tTot += totTok;
tCost += cost;
const granLabel = isHourly
const stepMins = Math.max(1, Number(slot.stepMinutes) || 5);
const granLabel = isMinute
? en
? `${stepMins}m`
: `按 ${stepMins} 分钟`
: isHourly
? en
? 'Hourly'
: '按小时'
@@ -9779,6 +9789,8 @@ function isEquivalentTelemetry(prev, next) {
pTrend[i]?.thinkingTokens !== nTrend[i]?.thinkingTokens ||
pTrend[i]?.responseTokens !== nTrend[i]?.responseTokens ||
pTrend[i]?.calls !== nTrend[i]?.calls ||
pTrend[i]?.granularity !== nTrend[i]?.granularity ||
pTrend[i]?.stepMinutes !== nTrend[i]?.stepMinutes ||
pTrend[i]?.label !== nTrend[i]?.label ||
pTrend[i]?.fullLabel !== nTrend[i]?.fullLabel ||
!areModelSlicesEqual(pTrend[i]?.models, nTrend[i]?.models)
@@ -13612,7 +13624,176 @@ function buildSmoothSplinePath(points) {
}
/**
* 根据分桶总数与标签平均长度,计算底部 X 轴应当展示的均匀刻度下标列表。
* 将采样点数组转为归一化横轴 `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 轴应当展示的均匀刻度下标列表。
*
* @param {Array<{ label?: string }>} slots
* @returns {number[]}
@@ -13620,10 +13801,11 @@ function buildSmoothSplinePath(points) {
function computeTickIndices(slots) {
const n = slots.length;
if (n <= 1) return [0];
if (n <= 8) {
const sampleLabel = String(slots[Math.floor(n / 2)]?.label || slots[0]?.label || '');
const maxDirectTicks = sampleLabel.length > 6 ? 5 : 8;
if (n <= maxDirectTicks) {
return Array.from({ length: n }, (_, i) => i);
}
const sampleLabel = String(slots[Math.floor(n / 2)]?.label || slots[0]?.label || '');
const maxTicks = sampleLabel.length > 6 ? 5 : 6;
const set = new Set();
for (let k = 0; k < maxTicks; k++) {
@@ -13942,7 +14124,163 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) {
let hoveredCellEl = null;
let lastPointer = null;
let lastRenderSig = '';
let lastTickLabelsSig = '';
let hasRenderedOnce = false;
let hasRenderedLineOnce = false;
let peakReadyArmed = false;
let peakReadyRaf = 0;
let tipTrackRaf = 0;
let morphRafId = 0;
let committedSegs = [];
let liveMorphSegs = null;
const transientClassTimers = new Map();
const CURVE_MORPH_DURATION_MS = 240;
function cleanupTransientClass(el) {
const rec = transientClassTimers.get(el);
if (!rec) return;
clearTimeout(rec.tid);
el?.removeEventListener?.('animationend', rec.onEnd);
el?.classList?.remove(rec.cls);
transientClassTimers.delete(el);
}
function triggerTransientClass(el, cls, fallbackMs = 650) {
if (!el || !el.classList) return;
cleanupTransientClass(el);
el.classList.remove(cls);
void el.offsetWidth;
const onEnd = (ev) => {
if (ev && ev.target && ev.target !== el) return;
cleanupTransientClass(el);
};
const tid = setTimeout(() => cleanupTransientClass(el), fallbackMs);
transientClassTimers.set(el, { cls, tid, onEnd });
el.addEventListener?.('animationend', onEnd);
el.classList.add(cls);
}
function clearAllTransientTimers() {
for (const el of Array.from(transientClassTimers.keys())) {
cleanupTransientClass(el);
}
}
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') {
@@ -14452,6 +14790,9 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) {
function destroy() {
cancelTipTrackRaf();
cancelCurveMorph();
cancelPeakReadyRaf();
clearAllTransientTimers();
plotStage.removeEventListener('mousemove', handlePointerMove);
plotStage.removeEventListener('click', handleLineClick);
plotStage.removeEventListener('mouseleave', clearHover);
@@ -14484,18 +14825,30 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) {
currentSlots = slots;
const isHourly =
slots[0]?.granularity === 'hour' || String(slots[0]?.label || '').includes(':');
slots[0]?.granularity === 'hour' ||
slots[0]?.granularity === 'minute' ||
String(slots[0]?.label || '').includes(':');
const useHeatmap = !isHourly && slots.length > HEATMAP_DAYS_THRESHOLD;
const modeChanged = useHeatmap !== currentIsHeatmap;
currentIsHeatmap = useHeatmap;
if (modeChanged) {
clearHover();
cancelCurveMorph();
liveMorphSegs = null;
}
patchClasses(chartWrap, { 'is-heatmap': useHeatmap });
patchAttr(plotStage, 'hidden', useHeatmap);
patchAttr(xAxisEl, 'hidden', useHeatmap);
patchAttr(heatmapStage, 'hidden', !useHeatmap);
if (hasRenderedOnce && modeChanged && canAnimateInBrowser()) {
if (useHeatmap) {
triggerTransientClass(heatmapStage, 'is-stage-entering');
} else {
triggerTransientClass(plotStage, 'is-stage-entering');
triggerTransientClass(xAxisEl, 'is-switching');
}
}
if (!useHeatmap) {
syncViewWidth();
@@ -14641,10 +14994,11 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) {
} else if (hoveredIdx >= 0) {
showHeatmapHoverAtIndex(hoveredIdx, currentCellEls[hoveredIdx], lastPointer);
}
hasRenderedOnce = true;
return;
}
// --- <= 90 天(或整点小时级):渲染平滑面积曲线图(1:1 贴边对齐) ---
// --- <= 90 天(或整点/分钟级):渲染平滑面积曲线图(1:1 贴边对齐 + 连续插值形变过渡) ---
currentCellEls = [];
const { leftX, rightX, spanX } = resolvePlotBounds(viewW);
const denom = Math.max(1, maxTokens);
@@ -14660,23 +15014,59 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) {
});
currentPts = pts;
const nextSegs = pointsToNormalizedCubicSegs(pts, BOTTOM_Y);
if (sig !== lastRenderSig) {
lastRenderSig = sig;
let lineD;
let areaD;
if (isSingle) {
if (maxTokens > 0) {
lineD = buildSmoothSplinePath([
{ x: leftX, y: BOTTOM_Y },
pts[0],
{ x: rightX, y: BOTTOM_Y },
]);
} else {
const yStr = pts[0].y.toFixed(1);
lineD = `M ${leftX.toFixed(1)} ${yStr} L ${rightX.toFixed(1)} ${yStr}`;
}
areaD = `${lineD} L ${rightX.toFixed(1)} ${BOTTOM_Y} L ${leftX.toFixed(1)} ${BOTTOM_Y} Z`;
} else {
lineD = buildSmoothSplinePath(pts);
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, {
leftX,
rightX,
spanX,
finalLineD: lineD,
finalAreaD: areaD,
});
} else {
cancelCurveMorph();
liveMorphSegs = null;
patchAttr(linePath, 'd', lineD);
patchAttr(areaPath, 'd', areaD);
}
hasRenderedLineOnce = true;
// 渲染与底部刻度对齐的垂直参考网格线及底部 X 轴标签(起止标签严格左右贴边)
// 渲染对齐底部刻度的垂直参考网格线及 X 轴标签(起止标签严格左右贴边)
const tickIndices = computeTickIndices(slots);
const nextTickLabelsSig = tickIndices
.map((tIdx) => `${tIdx}:${slots[tIdx]?.label || ''}`)
.join('|');
const ticksChanged =
hasRenderedOnce &&
!modeChanged &&
lastTickLabelsSig !== '' &&
nextTickLabelsSig !== lastTickLabelsSig;
lastTickLabelsSig = nextTickLabelsSig;
while (vGridGroup.firstChild) vGridGroup.removeChild(vGridGroup.firstChild);
while (xAxisEl.firstChild) xAxisEl.removeChild(xAxisEl.firstChild);
tickElsByIdx = new Map();
@@ -14712,6 +15102,11 @@ function createTrendAreaChart({ onSelectSlot = null } = {}) {
xAxisEl.appendChild(tickEl);
tickElsByIdx.set(tIdx, tickEl);
}
if (ticksChanged && canAnimateInBrowser()) {
triggerTransientClass(xAxisEl, 'is-switching');
triggerTransientClass(vGridGroup, 'is-switching');
}
}
const peakPt = pts[peakIdx] || { x: viewW / 2, y: BOTTOM_Y };
@@ -14727,12 +15122,24 @@ 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 });
}
}
if (hoveredIdx >= slots.length) {
clearHover();
} else if (hoveredIdx >= 0) {
showLineHoverAtIndex(hoveredIdx, lastPointer);
}
hasRenderedOnce = true;
}
return { el: chartWrap, update, destroy };
@@ -29613,18 +30020,7 @@ const ConsumptionView = defineComponent({
const cacheReadLabel = h('span', { text: t('cons.cacheRead') });
const outputUsageLabel = h('span', { text: t('cons.outputUsage') });
const overviewPanel = h('section', { className: 'panel' }, [
h('div', { className: 'panel-header cons-overview-head' }, [
h('span', { className: 'panel-title' }, [
dateSpanBadge,
]),
h('div', { className: 'cons-overview-controls' }, [
timeFilterSwitch.el,
consExportMenu.el,
]),
]),
customRangeBar,
h('div', { className: 'cons-box cons-unified-matrix' }, [
const unifiedMatrixEl = h('div', { className: 'cons-box cons-unified-matrix' }, [
h('div', { className: 'cons-split-3' }, [
h('div', { className: 'cons-col' }, [
totalTokensLabel,
@@ -29677,7 +30073,20 @@ const ConsumptionView = defineComponent({
outputSubText,
]),
]),
]);
const overviewPanel = h('section', { className: 'panel' }, [
h('div', { className: 'panel-header cons-overview-head' }, [
h('span', { className: 'panel-title' }, [
dateSpanBadge,
]),
h('div', { className: 'cons-overview-controls' }, [
timeFilterSwitch.el,
consExportMenu.el,
]),
]),
customRangeBar,
unifiedMatrixEl,
overviewSegBar.el,
]);
@@ -29732,6 +30141,54 @@ const ConsumptionView = defineComponent({
let lastModelsCount = 0;
let lastWorkspacesCount = 0;
let lastConvsCount = 0;
let hasCompletedInitialDraw = false;
let lastAnimatedRangeSig = '';
let lastAnimatedRankingKey = '';
let lastAnimatedSortSig = '';
const consAnimTimers = new Map();
const TRANSIENT_CONS_CLASSES = [
'is-range-switching',
'is-tab-entering',
'is-bars-revealing',
];
function cleanupConsAnim(el) {
const rec = consAnimTimers.get(el);
if (!rec) return;
clearTimeout(rec.tid);
el?.removeEventListener?.('animationend', rec.onEnd);
el?.classList?.remove(...TRANSIENT_CONS_CLASSES);
consAnimTimers.delete(el);
}
function triggerConsAnim(el, cls, fallbackMs = 650) {
if (
!el ||
!el.classList ||
typeof window === 'undefined' ||
typeof window.getComputedStyle !== 'function' ||
window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches
) {
return;
}
cleanupConsAnim(el);
el.classList.remove(...TRANSIENT_CONS_CLASSES);
void el.offsetWidth;
const onEnd = (ev) => {
if (ev && ev.target && ev.target !== el) return;
cleanupConsAnim(el);
};
const tid = setTimeout(() => cleanupConsAnim(el), fallbackMs);
consAnimTimers.set(el, { cls, tid, onEnd });
el.addEventListener?.('animationend', onEnd);
el.classList.add(cls);
}
function clearConsAnimTimers() {
for (const el of Array.from(consAnimTimers.keys())) {
cleanupConsAnim(el);
}
}
function getRankingTabOptions(
modelsCount = lastModelsCount,
@@ -31329,14 +31786,23 @@ const ConsumptionView = defineComponent({
t('cons.allTime')
: preset?.label || rangeInfo.label || t('cons.allTime');
patchText(trendRangeBadge, rangeBadgeText);
const firstTrendSlot = rawTrendSeries[0] || null;
const isMinuteTrend = firstTrendSlot?.granularity === 'minute';
const isHourlyTrend =
rawTrendSeries[0]?.granularity === 'hour' ||
(rawTrendSeries[0]?.label || '').includes(':');
const isHeatmapTrend = !isHourlyTrend && rawTrendSeries.length > HEATMAP_DAYS_THRESHOLD;
!isMinuteTrend &&
(firstTrendSlot?.granularity === 'hour' ||
(firstTrendSlot?.label || '').includes(':'));
const isHeatmapTrend =
!isMinuteTrend && !isHourlyTrend && rawTrendSeries.length > HEATMAP_DAYS_THRESHOLD;
patchText(
trendGranularityHint,
isHeatmapTrend
? t('cons.trendHeatmapHint', { days: rawTrendSeries.length })
: isMinuteTrend
? t('cons.trendPointsHintMinute', {
minutes: Math.max(1, Number(firstTrendSlot?.stepMinutes) || 5),
points: rawTrendSeries.length || 0,
})
: isHourlyTrend
? t('cons.trendPointsHintHourly', { points: rawTrendSeries.length || 0 })
: t('cons.trendPointsHintDaily', { points: rawTrendSeries.length || 0 })
@@ -31478,6 +31944,53 @@ const ConsumptionView = defineComponent({
updateRow: (refs, s) => updateSourceBreakdownRow(refs, s, sourcesTotalTok, modelColorMap),
});
const nextRangeSig = `${slice.range || ''}:${slice.customStartMs || 0}:${slice.customEndMs || 0}`;
const nextRankingKey = showWorkspacesTab
? 'workspaces'
: showSessionsTab
? 'sessions'
: 'models';
const nextSortSig = showModelsTab ? `m:${modelsSortBy}` : `c:${topConvsSortBy}`;
const activeRankingEl = showWorkspacesTab
? workspacesListEl
: showSessionsTab
? sortedTopConvs.length > 0
? topConvsListEl
: topConvsEmptyEl
: modelsListEl;
const rangeSwitched = hasCompletedInitialDraw && nextRangeSig !== lastAnimatedRangeSig;
const tabSwitched =
hasCompletedInitialDraw && !rangeSwitched && nextRankingKey !== lastAnimatedRankingKey;
const sortSwitched =
hasCompletedInitialDraw &&
!rangeSwitched &&
!tabSwitched &&
nextSortSig !== lastAnimatedSortSig;
if (rangeSwitched) {
triggerConsAnim(unifiedMatrixEl, 'is-range-switching');
triggerConsAnim(activeRankingEl, 'is-range-switching');
triggerConsAnim(sourcesListEl, 'is-range-switching');
} else if (tabSwitched) {
triggerConsAnim(activeRankingEl, 'is-tab-entering');
} else if (sortSwitched) {
triggerConsAnim(activeRankingEl, 'is-bars-revealing');
}
if (!hasCompletedInitialDraw) {
hasCompletedInitialDraw = true;
if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') {
window.requestAnimationFrame(() => {
rootEl.classList?.add('is-ready');
});
} else {
rootEl.classList?.add('is-ready');
}
}
lastAnimatedRangeSig = nextRangeSig;
lastAnimatedRankingKey = nextRankingKey;
lastAnimatedSortSig = nextSortSig;
// 5. 同步 12 个月垂直堆叠柱状图(按模型配色堆叠 + 长尾合并 + 悬停弹出明细浮层)
patchText(monthlyYearBadge, String(monthlyYear));
const maxMonthTokens = Math.max(
@@ -31679,6 +32192,7 @@ const ConsumptionView = defineComponent({
);
onCleanup(() => {
clearConsAnimTimers();
hideBreakdownPopover();
unsub();
unsubView();
+66 -37
View File
@@ -857,43 +857,34 @@ function buildUsageTrendSeries(
earliestSelectedStepMs,
latestSelectedStepMs
);
const { start: trendStartMs, end: trendEndMs, hourly: useHourly } = trend;
const { start: trendStartMs, end: trendEndMs, hourly: useHourly, stepMs: plannedStepMs } = trend;
const pad2 = (n) => String(n).padStart(2, '0');
const WEEKDAY_NAMES = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
const trendSeries = [];
if (useHourly) {
let firstHourMs = trend.first;
let lastHourMs = trend.last;
if (selectedWindow.key === 'today') {
const minTodayEndMs = firstHourMs + 5 * 3600 * 1000;
if (lastHourMs < minTodayEndMs) {
lastHourMs = minTodayEndMs;
}
} else if (lastHourMs - firstHourMs < 5 * 3600 * 1000) {
firstHourMs = lastHourMs - 5 * 3600 * 1000;
}
const firstSlotMs = trend.first;
const lastSlotMs = trend.last;
const slotMs = Math.max(60 * 1000, Number(plannedStepMs) || 3600 * 1000);
const stepMinutes = Math.max(1, Math.round(slotMs / (60 * 1000)));
const isSubHour = stepMinutes < 60;
const slotCount = Math.max(1, Math.floor((lastSlotMs - firstSlotMs) / slotMs) + 1);
const totalHours = Math.max(2, Math.round((lastHourMs - firstHourMs) / (3600 * 1000)) + 1);
const stepHours = totalHours > 72 ? Math.ceil(totalHours / 48) : 1;
const slotMs = stepHours * 3600 * 1000;
const slotCount = Math.max(2, Math.ceil((lastHourMs - firstHourMs + 3600 * 1000) / slotMs));
const firstD = new Date(firstHourMs);
const lastD = new Date(firstHourMs + (slotCount - 1) * slotMs);
const firstD = new Date(firstSlotMs);
const lastD = new Date(firstSlotMs + (slotCount - 1) * slotMs);
const isSameDay =
firstD.getFullYear() === lastD.getFullYear() &&
firstD.getMonth() === lastD.getMonth() &&
firstD.getDate() === lastD.getDate();
for (let idx = 0; idx < slotCount; idx++) {
const sMs = firstHourMs + idx * slotMs;
const sMs = firstSlotMs + idx * slotMs;
const eMs = sMs + slotMs;
const sd = new Date(sMs);
const ed = new Date(eMs);
if (Number.isNaN(sd.getTime())) continue;
const hh = `${pad2(sd.getHours())}:00`;
const endHh = `${pad2(ed.getHours())}:00`;
const hh = `${pad2(sd.getHours())}:${pad2(sd.getMinutes())}`;
const endHh = `${pad2(ed.getHours())}:${pad2(ed.getMinutes())}`;
const dateStr = `${sd.getMonth() + 1}/${pad2(sd.getDate())}`;
const axisLabel = isSameDay ? hh : `${dateStr} ${hh}`;
const fullLabel = `${sd.getMonth() + 1}月${sd.getDate()}日 ${hh} - ${endHh}`;
@@ -901,7 +892,8 @@ function buildUsageTrendSeries(
index: idx,
startMs: sMs,
endMs: eMs,
granularity: 'hour',
granularity: isSubHour ? 'minute' : 'hour',
...(isSubHour ? { stepMinutes } : {}),
label: axisLabel,
fullLabel,
tokens: 0,
@@ -928,11 +920,10 @@ function buildUsageTrendSeries(
cursor.setHours(0, 0, 0, 0);
safety++;
}
while (dayStarts.length < 2) {
const prev = new Date(dayStarts[0] || firstDayMs);
prev.setDate(prev.getDate() - 1);
prev.setHours(0, 0, 0, 0);
dayStarts.unshift(prev.getTime());
if (dayStarts.length === 0) {
const fallbackDay = new Date(firstDayMs);
fallbackDay.setHours(0, 0, 0, 0);
dayStarts.push(fallbackDay.getTime());
}
const firstYear = new Date(dayStarts[0]).getFullYear();
@@ -1082,26 +1073,61 @@ function buildUsageTrendSeries(
return { trend, trendStartMs, trendEndMs, trendSeries };
}
function resolveIntradayStepMinutes(spanMs, windowKey = '') {
if (windowKey !== 'all') {
if (spanMs < 15 * 60 * 1000) return 1;
if (spanMs < 60 * 60 * 1000) return 5;
if (spanMs < 2 * 3600 * 1000) return 15;
}
const totalHours = Math.max(2, Math.floor(spanMs / (3600 * 1000)) + 1);
return totalHours > 72 ? Math.ceil(totalHours / 48) * 60 : 60;
}
function floorToLocalTrendSlotMs(ms, stepMinutes) {
const d = new Date(ms);
if (stepMinutes < 60) {
const alignedMin = Math.floor(d.getMinutes() / stepMinutes) * stepMinutes;
d.setMinutes(alignedMin, 0, 0);
} else {
d.setMinutes(0, 0, 0);
}
return d.getTime();
}
function planUsageTrend(window, nowMs, earliest, latest) {
const safeMs = (value, fallback) =>
Number.isFinite(value) && value > 0 && value <= MAX_TREND_TIMESTAMP_MS ? value : fallback;
const end = Math.max(safeMs(window.endMs, Math.max(nowMs, latest || nowMs)), latest);
const defaultStart = end - 24 * 3600 * 1000;
const start = window.key === 'all'
const start =
window.key === 'all'
? Math.min(safeMs(earliest, defaultStart), end - 3600 * 1000)
: Math.min(safeMs(window.startMs, defaultStart), end);
const hourly = window.key === 'today' || window.key === '24h' || window.key === '5h' ||
end - start <= 72 * 3600 * 1000;
const spanMs = Math.max(0, end - start);
const hourly =
window.key === 'today' ||
window.key === '24h' ||
window.key === '5h' ||
spanMs <= 72 * 3600 * 1000;
if (hourly) {
const stepMinutes = resolveIntradayStepMinutes(spanMs, window.key);
const stepMs = stepMinutes * 60 * 1000;
const first = floorToLocalTrendSlotMs(start, stepMinutes);
const last = floorToLocalTrendSlotMs(end, stepMinutes);
return { start, end, hourly, stepMs, first, last };
}
const first = new Date(start);
const last = new Date(end);
if (hourly) {
first.setMinutes(0, 0, 0);
last.setMinutes(0, 0, 0);
} else {
first.setHours(0, 0, 0, 0);
last.setHours(0, 0, 0, 0);
}
return { start, end, hourly, first: first.getTime(), last: last.getTime() };
return {
start,
end,
hourly,
stepMs: 24 * 3600 * 1000,
first: first.getTime(),
last: last.getTime(),
};
}
function sameUsageEntries(previous, current) {
@@ -1441,7 +1467,9 @@ export function aggregateMultiWindowUsage({
: selectedWindow;
const trend = planUsageTrend(effectivePrevWin, nowMs, previous.earliest, previous.latest);
if (
trend.hourly === previous.trend.hourly && trend.first === previous.trend.first &&
trend.hourly === previous.trend.hourly &&
trend.stepMs === previous.trend.stepMs &&
trend.first === previous.trend.first &&
trend.last === previous.trend.last &&
sameUsageWindows(
previous.windows,
@@ -1994,6 +2022,7 @@ export function aggregateSelectedWindowUsage({
const trend = planUsageTrend(effectivePrevWin, nowMs, candidate.earliest, candidate.latest);
if (
trend.hourly === candidate.trend.hourly &&
trend.stepMs === candidate.trend.stepMs &&
trend.first === candidate.trend.first &&
trend.last === candidate.trend.last &&
sameUsageWindows(
+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=1795457102792">
<link rel="stylesheet" href="/styles.css?v=1795462720987">
<script src="/preload.js"></script>
</head>
<body>
<div id="app-root"></div>
<script src="/app.js?v=1795457102792"></script>
<script src="/app.js?v=1795462720987"></script>
</body>
</html>
@@ -49,7 +49,176 @@ function buildSmoothSplinePath(points) {
}
/**
* 根据分桶总数与标签平均长度,计算底部 X 轴应当展示的均匀刻度下标列表。
* 将采样点数组转为归一化横轴 `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 轴应当展示的均匀刻度下标列表。
*
* @param {Array<{ label?: string }>} slots
* @returns {number[]}
@@ -57,10 +226,11 @@ function buildSmoothSplinePath(points) {
function computeTickIndices(slots) {
const n = slots.length;
if (n <= 1) return [0];
if (n <= 8) {
const sampleLabel = String(slots[Math.floor(n / 2)]?.label || slots[0]?.label || '');
const maxDirectTicks = sampleLabel.length > 6 ? 5 : 8;
if (n <= maxDirectTicks) {
return Array.from({ length: n }, (_, i) => i);
}
const sampleLabel = String(slots[Math.floor(n / 2)]?.label || slots[0]?.label || '');
const maxTicks = sampleLabel.length > 6 ? 5 : 6;
const set = new Set();
for (let k = 0; k < maxTicks; k++) {
@@ -379,7 +549,163 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) {
let hoveredCellEl = null;
let lastPointer = null;
let lastRenderSig = '';
let lastTickLabelsSig = '';
let hasRenderedOnce = false;
let hasRenderedLineOnce = false;
let peakReadyArmed = false;
let peakReadyRaf = 0;
let tipTrackRaf = 0;
let morphRafId = 0;
let committedSegs = [];
let liveMorphSegs = null;
const transientClassTimers = new Map();
const CURVE_MORPH_DURATION_MS = 240;
function cleanupTransientClass(el) {
const rec = transientClassTimers.get(el);
if (!rec) return;
clearTimeout(rec.tid);
el?.removeEventListener?.('animationend', rec.onEnd);
el?.classList?.remove(rec.cls);
transientClassTimers.delete(el);
}
function triggerTransientClass(el, cls, fallbackMs = 650) {
if (!el || !el.classList) return;
cleanupTransientClass(el);
el.classList.remove(cls);
void el.offsetWidth;
const onEnd = (ev) => {
if (ev && ev.target && ev.target !== el) return;
cleanupTransientClass(el);
};
const tid = setTimeout(() => cleanupTransientClass(el), fallbackMs);
transientClassTimers.set(el, { cls, tid, onEnd });
el.addEventListener?.('animationend', onEnd);
el.classList.add(cls);
}
function clearAllTransientTimers() {
for (const el of Array.from(transientClassTimers.keys())) {
cleanupTransientClass(el);
}
}
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') {
@@ -889,6 +1215,9 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) {
function destroy() {
cancelTipTrackRaf();
cancelCurveMorph();
cancelPeakReadyRaf();
clearAllTransientTimers();
plotStage.removeEventListener('mousemove', handlePointerMove);
plotStage.removeEventListener('click', handleLineClick);
plotStage.removeEventListener('mouseleave', clearHover);
@@ -921,18 +1250,30 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) {
currentSlots = slots;
const isHourly =
slots[0]?.granularity === 'hour' || String(slots[0]?.label || '').includes(':');
slots[0]?.granularity === 'hour' ||
slots[0]?.granularity === 'minute' ||
String(slots[0]?.label || '').includes(':');
const useHeatmap = !isHourly && slots.length > HEATMAP_DAYS_THRESHOLD;
const modeChanged = useHeatmap !== currentIsHeatmap;
currentIsHeatmap = useHeatmap;
if (modeChanged) {
clearHover();
cancelCurveMorph();
liveMorphSegs = null;
}
patchClasses(chartWrap, { 'is-heatmap': useHeatmap });
patchAttr(plotStage, 'hidden', useHeatmap);
patchAttr(xAxisEl, 'hidden', useHeatmap);
patchAttr(heatmapStage, 'hidden', !useHeatmap);
if (hasRenderedOnce && modeChanged && canAnimateInBrowser()) {
if (useHeatmap) {
triggerTransientClass(heatmapStage, 'is-stage-entering');
} else {
triggerTransientClass(plotStage, 'is-stage-entering');
triggerTransientClass(xAxisEl, 'is-switching');
}
}
if (!useHeatmap) {
syncViewWidth();
@@ -1078,10 +1419,11 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) {
} else if (hoveredIdx >= 0) {
showHeatmapHoverAtIndex(hoveredIdx, currentCellEls[hoveredIdx], lastPointer);
}
hasRenderedOnce = true;
return;
}
// --- <= 90 天(或整点小时级):渲染平滑面积曲线图(1:1 贴边对齐) ---
// --- <= 90 天(或整点/分钟级):渲染平滑面积曲线图(1:1 贴边对齐 + 连续插值形变过渡) ---
currentCellEls = [];
const { leftX, rightX, spanX } = resolvePlotBounds(viewW);
const denom = Math.max(1, maxTokens);
@@ -1097,23 +1439,59 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) {
});
currentPts = pts;
const nextSegs = pointsToNormalizedCubicSegs(pts, BOTTOM_Y);
if (sig !== lastRenderSig) {
lastRenderSig = sig;
let lineD;
let areaD;
if (isSingle) {
if (maxTokens > 0) {
lineD = buildSmoothSplinePath([
{ x: leftX, y: BOTTOM_Y },
pts[0],
{ x: rightX, y: BOTTOM_Y },
]);
} else {
const yStr = pts[0].y.toFixed(1);
lineD = `M ${leftX.toFixed(1)} ${yStr} L ${rightX.toFixed(1)} ${yStr}`;
}
areaD = `${lineD} L ${rightX.toFixed(1)} ${BOTTOM_Y} L ${leftX.toFixed(1)} ${BOTTOM_Y} Z`;
} else {
lineD = buildSmoothSplinePath(pts);
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, {
leftX,
rightX,
spanX,
finalLineD: lineD,
finalAreaD: areaD,
});
} else {
cancelCurveMorph();
liveMorphSegs = null;
patchAttr(linePath, 'd', lineD);
patchAttr(areaPath, 'd', areaD);
}
hasRenderedLineOnce = true;
// 渲染与底部刻度对齐的垂直参考网格线及底部 X 轴标签(起止标签严格左右贴边)
// 渲染对齐底部刻度的垂直参考网格线及 X 轴标签(起止标签严格左右贴边)
const tickIndices = computeTickIndices(slots);
const nextTickLabelsSig = tickIndices
.map((tIdx) => `${tIdx}:${slots[tIdx]?.label || ''}`)
.join('|');
const ticksChanged =
hasRenderedOnce &&
!modeChanged &&
lastTickLabelsSig !== '' &&
nextTickLabelsSig !== lastTickLabelsSig;
lastTickLabelsSig = nextTickLabelsSig;
while (vGridGroup.firstChild) vGridGroup.removeChild(vGridGroup.firstChild);
while (xAxisEl.firstChild) xAxisEl.removeChild(xAxisEl.firstChild);
tickElsByIdx = new Map();
@@ -1149,6 +1527,11 @@ export function createTrendAreaChart({ onSelectSlot = null } = {}) {
xAxisEl.appendChild(tickEl);
tickElsByIdx.set(tIdx, tickEl);
}
if (ticksChanged && canAnimateInBrowser()) {
triggerTransientClass(xAxisEl, 'is-switching');
triggerTransientClass(vGridGroup, 'is-switching');
}
}
const peakPt = pts[peakIdx] || { x: viewW / 2, y: BOTTOM_Y };
@@ -1164,12 +1547,24 @@ 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 });
}
}
if (hoveredIdx >= slots.length) {
clearHover();
} else if (hoveredIdx >= 0) {
showLineHoverAtIndex(hoveredIdx, lastPointer);
}
hasRenderedOnce = true;
}
return { el: chartWrap, update, destroy };
+10 -2
View File
@@ -1307,8 +1307,11 @@ export function buildConsumptionXlsx(
let tTot = 0;
let tCost = 0;
const trendRows = trend.map((slot) => {
const isMinute = slot.granularity === 'minute';
const isHourly =
slot.granularity === 'hour' || String(slot.label || '').includes(':');
isMinute ||
slot.granularity === 'hour' ||
String(slot.label || '').includes(':');
const calls = Math.max(0, Number(slot.calls || 0));
const inTok = Math.max(0, Number(slot.inputTokens || 0));
const cacheTok = Math.max(0, Number(slot.cacheReadTokens || 0));
@@ -1321,7 +1324,12 @@ export function buildConsumptionXlsx(
tOut += outTok;
tTot += totTok;
tCost += cost;
const granLabel = isHourly
const stepMins = Math.max(1, Number(slot.stepMinutes) || 5);
const granLabel = isMinute
? en
? `${stepMins}m`
: `按 ${stepMins} 分钟`
: isHourly
? en
? 'Hourly'
: '按小时'
+1
View File
@@ -261,6 +261,7 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
'cons.trendTitle': 'Usage Trend',
'cons.allTime': 'All Time',
'cons.trendHeatmapHint': 'Daily ({days}d) · Hover for details',
'cons.trendPointsHintMinute': '{minutes}m ({points} pts) · Hover for details',
'cons.trendPointsHintHourly': 'Hourly ({points} pts) · Hover for details',
'cons.trendPointsHintDaily': 'Daily ({points} pts) · Hover for details',
'cons.topModels': 'Top Models',
+1
View File
@@ -261,6 +261,7 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
'cons.trendTitle': '用量趋势',
'cons.allTime': '全部时间',
'cons.trendHeatmapHint': '按日 ({days}天) · 悬停查看',
'cons.trendPointsHintMinute': '按 {minutes} 分钟 ({points}点) · 悬停查看',
'cons.trendPointsHintHourly': '按小时 ({points}点) · 悬停查看',
'cons.trendPointsHintDaily': '按日 ({points}点) · 悬停查看',
'cons.topModels': '模型排行',
@@ -967,6 +967,8 @@ export function isEquivalentTelemetry(prev, next) {
pTrend[i]?.thinkingTokens !== nTrend[i]?.thinkingTokens ||
pTrend[i]?.responseTokens !== nTrend[i]?.responseTokens ||
pTrend[i]?.calls !== nTrend[i]?.calls ||
pTrend[i]?.granularity !== nTrend[i]?.granularity ||
pTrend[i]?.stepMinutes !== nTrend[i]?.stepMinutes ||
pTrend[i]?.label !== nTrend[i]?.label ||
pTrend[i]?.fullLabel !== nTrend[i]?.fullLabel ||
!areModelSlicesEqual(pTrend[i]?.models, nTrend[i]?.models)
+108 -1
View File
@@ -387,6 +387,111 @@
z-index: 2;
}
.cons-view-stage .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 {
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 {
width: 0%;
}
}
.trend-peak-pill.is-ready {
transition:
left 240ms cubic-bezier(0.22, 1, 0.36, 1),
opacity 180ms cubic-bezier(0.22, 1, 0.36, 1);
}
@keyframes anim-cons-axis-fade {
from {
opacity: 0.3;
}
to {
opacity: 1;
}
}
@keyframes anim-cons-stage-in {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes anim-cons-content-switch {
from {
opacity: 0.52;
}
to {
opacity: 1;
}
}
@keyframes anim-cons-bar-grow {
from {
transform: scaleX(0);
}
to {
transform: scaleX(1);
}
}
.trend-x-axis.is-switching,
.trend-v-grid.is-switching {
animation: anim-cons-axis-fade 220ms cubic-bezier(0.22, 1, 0.36, 1) both;
}
.trend-plot-stage.is-stage-entering,
.trend-heatmap-stage.is-stage-entering,
.cons-item-list.is-tab-entering,
.cons-ranking-empty.is-tab-entering {
animation: anim-cons-stage-in 220ms cubic-bezier(0.22, 1, 0.36, 1) both;
}
.cons-unified-matrix.is-range-switching,
.cons-item-list.is-range-switching,
.cons-ranking-empty.is-range-switching {
animation: anim-cons-content-switch 220ms cubic-bezier(0.22, 1, 0.36, 1) both;
}
.cons-item-list.is-tab-entering .progress-track,
.cons-item-list.is-bars-revealing .progress-track {
transform-origin: left center;
animation: anim-cons-bar-grow 240ms cubic-bezier(0.22, 1, 0.36, 1) both;
}
@media (prefers-reduced-motion: reduce) {
.cons-view-stage .progress-seg,
.cons-view-stage .progress-fill,
.trend-peak-pill.is-ready,
.trend-hm-cell {
transition: none !important;
}
.trend-x-axis.is-switching,
.trend-v-grid.is-switching,
.trend-plot-stage.is-stage-entering,
.trend-heatmap-stage.is-stage-entering,
.cons-item-list.is-tab-entering,
.cons-ranking-empty.is-tab-entering,
.cons-unified-matrix.is-range-switching,
.cons-item-list.is-range-switching,
.cons-ranking-empty.is-range-switching,
.cons-item-list.is-bars-revealing .progress-track {
animation: none !important;
}
}
.trend-tooltip {
position: absolute;
top: 2px;
@@ -664,7 +769,9 @@
border-radius: 2px;
box-sizing: border-box;
cursor: pointer;
transition: transform var(--dur-instant) var(--ease-fast);
transition:
background-color 180ms ease-out,
transform var(--dur-instant) var(--ease-fast);
}
.trend-hm-cell.is-pad {
+122 -15
View File
@@ -280,18 +280,7 @@ export const ConsumptionView = defineComponent({
const cacheReadLabel = h('span', { text: t('cons.cacheRead') });
const outputUsageLabel = h('span', { text: t('cons.outputUsage') });
const overviewPanel = h('section', { className: 'panel' }, [
h('div', { className: 'panel-header cons-overview-head' }, [
h('span', { className: 'panel-title' }, [
dateSpanBadge,
]),
h('div', { className: 'cons-overview-controls' }, [
timeFilterSwitch.el,
consExportMenu.el,
]),
]),
customRangeBar,
h('div', { className: 'cons-box cons-unified-matrix' }, [
const unifiedMatrixEl = h('div', { className: 'cons-box cons-unified-matrix' }, [
h('div', { className: 'cons-split-3' }, [
h('div', { className: 'cons-col' }, [
totalTokensLabel,
@@ -344,7 +333,20 @@ export const ConsumptionView = defineComponent({
outputSubText,
]),
]),
]);
const overviewPanel = h('section', { className: 'panel' }, [
h('div', { className: 'panel-header cons-overview-head' }, [
h('span', { className: 'panel-title' }, [
dateSpanBadge,
]),
h('div', { className: 'cons-overview-controls' }, [
timeFilterSwitch.el,
consExportMenu.el,
]),
]),
customRangeBar,
unifiedMatrixEl,
overviewSegBar.el,
]);
@@ -399,6 +401,54 @@ export const ConsumptionView = defineComponent({
let lastModelsCount = 0;
let lastWorkspacesCount = 0;
let lastConvsCount = 0;
let hasCompletedInitialDraw = false;
let lastAnimatedRangeSig = '';
let lastAnimatedRankingKey = '';
let lastAnimatedSortSig = '';
const consAnimTimers = new Map();
const TRANSIENT_CONS_CLASSES = [
'is-range-switching',
'is-tab-entering',
'is-bars-revealing',
];
function cleanupConsAnim(el) {
const rec = consAnimTimers.get(el);
if (!rec) return;
clearTimeout(rec.tid);
el?.removeEventListener?.('animationend', rec.onEnd);
el?.classList?.remove(...TRANSIENT_CONS_CLASSES);
consAnimTimers.delete(el);
}
function triggerConsAnim(el, cls, fallbackMs = 650) {
if (
!el ||
!el.classList ||
typeof window === 'undefined' ||
typeof window.getComputedStyle !== 'function' ||
window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches
) {
return;
}
cleanupConsAnim(el);
el.classList.remove(...TRANSIENT_CONS_CLASSES);
void el.offsetWidth;
const onEnd = (ev) => {
if (ev && ev.target && ev.target !== el) return;
cleanupConsAnim(el);
};
const tid = setTimeout(() => cleanupConsAnim(el), fallbackMs);
consAnimTimers.set(el, { cls, tid, onEnd });
el.addEventListener?.('animationend', onEnd);
el.classList.add(cls);
}
function clearConsAnimTimers() {
for (const el of Array.from(consAnimTimers.keys())) {
cleanupConsAnim(el);
}
}
function getRankingTabOptions(
modelsCount = lastModelsCount,
@@ -1996,14 +2046,23 @@ export const ConsumptionView = defineComponent({
t('cons.allTime')
: preset?.label || rangeInfo.label || t('cons.allTime');
patchText(trendRangeBadge, rangeBadgeText);
const firstTrendSlot = rawTrendSeries[0] || null;
const isMinuteTrend = firstTrendSlot?.granularity === 'minute';
const isHourlyTrend =
rawTrendSeries[0]?.granularity === 'hour' ||
(rawTrendSeries[0]?.label || '').includes(':');
const isHeatmapTrend = !isHourlyTrend && rawTrendSeries.length > HEATMAP_DAYS_THRESHOLD;
!isMinuteTrend &&
(firstTrendSlot?.granularity === 'hour' ||
(firstTrendSlot?.label || '').includes(':'));
const isHeatmapTrend =
!isMinuteTrend && !isHourlyTrend && rawTrendSeries.length > HEATMAP_DAYS_THRESHOLD;
patchText(
trendGranularityHint,
isHeatmapTrend
? t('cons.trendHeatmapHint', { days: rawTrendSeries.length })
: isMinuteTrend
? t('cons.trendPointsHintMinute', {
minutes: Math.max(1, Number(firstTrendSlot?.stepMinutes) || 5),
points: rawTrendSeries.length || 0,
})
: isHourlyTrend
? t('cons.trendPointsHintHourly', { points: rawTrendSeries.length || 0 })
: t('cons.trendPointsHintDaily', { points: rawTrendSeries.length || 0 })
@@ -2145,6 +2204,53 @@ export const ConsumptionView = defineComponent({
updateRow: (refs, s) => updateSourceBreakdownRow(refs, s, sourcesTotalTok, modelColorMap),
});
const nextRangeSig = `${slice.range || ''}:${slice.customStartMs || 0}:${slice.customEndMs || 0}`;
const nextRankingKey = showWorkspacesTab
? 'workspaces'
: showSessionsTab
? 'sessions'
: 'models';
const nextSortSig = showModelsTab ? `m:${modelsSortBy}` : `c:${topConvsSortBy}`;
const activeRankingEl = showWorkspacesTab
? workspacesListEl
: showSessionsTab
? sortedTopConvs.length > 0
? topConvsListEl
: topConvsEmptyEl
: modelsListEl;
const rangeSwitched = hasCompletedInitialDraw && nextRangeSig !== lastAnimatedRangeSig;
const tabSwitched =
hasCompletedInitialDraw && !rangeSwitched && nextRankingKey !== lastAnimatedRankingKey;
const sortSwitched =
hasCompletedInitialDraw &&
!rangeSwitched &&
!tabSwitched &&
nextSortSig !== lastAnimatedSortSig;
if (rangeSwitched) {
triggerConsAnim(unifiedMatrixEl, 'is-range-switching');
triggerConsAnim(activeRankingEl, 'is-range-switching');
triggerConsAnim(sourcesListEl, 'is-range-switching');
} else if (tabSwitched) {
triggerConsAnim(activeRankingEl, 'is-tab-entering');
} else if (sortSwitched) {
triggerConsAnim(activeRankingEl, 'is-bars-revealing');
}
if (!hasCompletedInitialDraw) {
hasCompletedInitialDraw = true;
if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') {
window.requestAnimationFrame(() => {
rootEl.classList?.add('is-ready');
});
} else {
rootEl.classList?.add('is-ready');
}
}
lastAnimatedRangeSig = nextRangeSig;
lastAnimatedRankingKey = nextRankingKey;
lastAnimatedSortSig = nextSortSig;
// 5. 同步 12 个月垂直堆叠柱状图(按模型配色堆叠 + 长尾合并 + 悬停弹出明细浮层)
patchText(monthlyYearBadge, String(monthlyYear));
const maxMonthTokens = Math.max(
@@ -2346,6 +2452,7 @@ export const ConsumptionView = defineComponent({
);
onCleanup(() => {
clearConsAnimTimers();
hideBreakdownPopover();
unsub();
unsubView();
+108 -1
View File
@@ -3192,6 +3192,111 @@ html[data-standalone="true"] .app-shell {
z-index: 2;
}
.cons-view-stage .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 {
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 {
width: 0%;
}
}
.trend-peak-pill.is-ready {
transition:
left 240ms cubic-bezier(0.22, 1, 0.36, 1),
opacity 180ms cubic-bezier(0.22, 1, 0.36, 1);
}
@keyframes anim-cons-axis-fade {
from {
opacity: 0.3;
}
to {
opacity: 1;
}
}
@keyframes anim-cons-stage-in {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes anim-cons-content-switch {
from {
opacity: 0.52;
}
to {
opacity: 1;
}
}
@keyframes anim-cons-bar-grow {
from {
transform: scaleX(0);
}
to {
transform: scaleX(1);
}
}
.trend-x-axis.is-switching,
.trend-v-grid.is-switching {
animation: anim-cons-axis-fade 220ms cubic-bezier(0.22, 1, 0.36, 1) both;
}
.trend-plot-stage.is-stage-entering,
.trend-heatmap-stage.is-stage-entering,
.cons-item-list.is-tab-entering,
.cons-ranking-empty.is-tab-entering {
animation: anim-cons-stage-in 220ms cubic-bezier(0.22, 1, 0.36, 1) both;
}
.cons-unified-matrix.is-range-switching,
.cons-item-list.is-range-switching,
.cons-ranking-empty.is-range-switching {
animation: anim-cons-content-switch 220ms cubic-bezier(0.22, 1, 0.36, 1) both;
}
.cons-item-list.is-tab-entering .progress-track,
.cons-item-list.is-bars-revealing .progress-track {
transform-origin: left center;
animation: anim-cons-bar-grow 240ms cubic-bezier(0.22, 1, 0.36, 1) both;
}
@media (prefers-reduced-motion: reduce) {
.cons-view-stage .progress-seg,
.cons-view-stage .progress-fill,
.trend-peak-pill.is-ready,
.trend-hm-cell {
transition: none !important;
}
.trend-x-axis.is-switching,
.trend-v-grid.is-switching,
.trend-plot-stage.is-stage-entering,
.trend-heatmap-stage.is-stage-entering,
.cons-item-list.is-tab-entering,
.cons-ranking-empty.is-tab-entering,
.cons-unified-matrix.is-range-switching,
.cons-item-list.is-range-switching,
.cons-ranking-empty.is-range-switching,
.cons-item-list.is-bars-revealing .progress-track {
animation: none !important;
}
}
.trend-tooltip {
position: absolute;
top: 2px;
@@ -3469,7 +3574,9 @@ html[data-standalone="true"] .app-shell {
border-radius: 2px;
box-sizing: border-box;
cursor: pointer;
transition: transform var(--dur-instant) var(--ease-fast);
transition:
background-color 180ms ease-out,
transform var(--dur-instant) var(--ease-fast);
}
.trend-hm-cell.is-pad {
+121
View File
@@ -3780,3 +3780,124 @@ test('conversation undo preserves 10-channel context breakdown across unindexed
assert.equal(ctx4.userInputTokens, 20000);
assert.equal(ctx4.userInputTokens + ctx4.assistantTokens + ctx4.toolResultsTokens, 27500);
});
test('trendSeries respects strict window bounds without 6h out-of-window padding and subdivides <2h spans into 1m/5m/15m slots', async () => {
const mkStep = (atMs, tok) => ({
status: 'CORTEX_STEP_STATUS_DONE',
metadata: {
createdAt: new Date(atMs).toISOString(),
finishedGeneratingAt: new Date(atMs + 4000).toISOString(),
modelUsage: {
model: 'MODEL_PLACEHOLDER_M37',
inputTokens: String(tok),
cacheReadTokens: '0',
outputTokens: '0',
},
},
plannerResponse: { response: 'ok' },
});
// Anchor clock to local 2026-11-24 03:27:40 (3h 27m into 'today'; 27m into a cycle reset at 03:00:00)
const dayStart = new Date(2026, 10, 24, 0, 0, 0, 0).getTime();
let fakeNowMs = dayStart + 3 * 3600_000 + 27 * 60_000 + 40_000;
const cycleStartMs = dayStart + 3 * 3600_000;
const weeklyResetIso = new Date(cycleStartMs + 7 * 24 * 3600_000).toISOString();
const fiveHourResetIso = new Date(cycleStartMs + 5 * 3600_000).toISOString();
const h = backendHarness({
clock: () => fakeNowMs,
userStatus: {
email: 'trend@example.com',
cascadeModelConfigData: {
clientModelConfigs: [
{
label: 'Gemini 3.8 Flash (High)',
modelOrAlias: { model: 'MODEL_PLACEHOLDER_M37' },
quotaInfo: { remainingFraction: 0.9, resetTime: fiveHourResetIso },
},
],
},
},
quotaSummary: {
groups: [
{
displayName: 'Gemini',
buckets: [
{ remainingFraction: 0.9, resetTime: fiveHourResetIso },
{ remainingFraction: 0.95, resetTime: weeklyResetIso },
],
},
],
},
trajectories: {
cTrend: {
trajectory: {
steps: [
mkStep(dayStart + 2 * 3600_000 + 10 * 60_000, 30_000), // 02:10 (previous cycle)
mkStep(cycleStartMs + 18 * 60_000, 5_000), // 03:18 (current cycle)
],
generatorMetadata: [],
},
},
},
summaries: {
cTrend: { stepCount: 2, lastModifiedTime: new Date(fakeNowMs).toISOString(), status: 'IDLE' },
},
});
// 1. 'today' at 03:27 (>= 2h): strictly 4 hourly slots (00:00..03:00), never padded to future 04:00/05:00
const pToday = await h.buildTelemetryPayloadInternal('cTrend', false, { range: 'today' });
assert.deepEqual(
Array.from(pToday.consumption.trendSeries, (s) => s.label),
['00:00', '01:00', '02:00', '03:00']
);
assert.equal(pToday.consumption.trendSeries[0].granularity, 'hour');
assert.equal(pToday.consumption.trendSeries[2].tokens, 30_000);
assert.equal(pToday.consumption.trendSeries[3].tokens, 5_000);
// 2. 'cycle' 27m after reset (< 1h): 6 five-minute slots (03:00..03:25), never reaching back to 22:00..02:00
const pCycle = await h.buildTelemetryPayloadInternal('cTrend', false, { range: 'cycle' });
assert.deepEqual(
Array.from(pCycle.consumption.trendSeries, (s) => s.label),
['03:00', '03:05', '03:10', '03:15', '03:20', '03:25']
);
assert.equal(pCycle.consumption.trendSeries[0].granularity, 'minute');
assert.equal(pCycle.consumption.trendSeries[0].stepMinutes, 5);
assert.equal(pCycle.consumption.trendSeries[3].tokens, 5_000); // 03:18 falls in 03:15 - 03:20
// 3. Rewind to 01:20 (< 2h) on a fresh harness and verify 15m -> 1h cache invalidation across the 2h boundary
fakeNowMs = dayStart + 1 * 3600_000 + 20 * 60_000;
const hTransition = backendHarness({
clock: () => fakeNowMs,
trajectories: {
cEarly: {
trajectory: {
steps: [mkStep(dayStart + 35 * 60_000, 8_000)],
generatorMetadata: [],
},
},
},
summaries: {
cEarly: { stepCount: 1, lastModifiedTime: new Date(fakeNowMs).toISOString(), status: 'IDLE' },
},
});
const pEarly = await hTransition.buildTelemetryPayloadInternal('cEarly', false, { range: 'today' });
assert.deepEqual(
Array.from(pEarly.consumption.trendSeries, (s) => s.label),
['00:00', '00:15', '00:30', '00:45', '01:00', '01:15']
);
assert.equal(pEarly.consumption.trendSeries[0].granularity, 'minute');
assert.equal(pEarly.consumption.trendSeries[0].stepMinutes, 15);
assert.equal(pEarly.consumption.trendSeries[2].tokens, 8_000);
// Advance clock to 02:05 (>= 2h): snapshot cache must invalidate stepMs and switch to 3 hourly slots
fakeNowMs = dayStart + 2 * 3600_000 + 5 * 60_000;
const pAfter2h = await hTransition.buildTelemetryPayloadInternal('cEarly', false, { range: 'today' });
assert.deepEqual(
Array.from(pAfter2h.consumption.trendSeries, (s) => s.label),
['00:00', '01:00', '02:00']
);
assert.equal(pAfter2h.consumption.trendSeries[0].granularity, 'hour');
assert.equal(pAfter2h.consumption.trendSeries[0].tokens, 8_000);
});