diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index 15ee1f7..ee2e004 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -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,13 +8044,18 @@ function buildConsumptionXlsx( tOut += outTok; tTot += totTok; tCost += cost; - const granLabel = isHourly + const stepMins = Math.max(1, Number(slot.stepMinutes) || 5); + const granLabel = isMinute ? en - ? 'Hourly' - : '按小时' - : en - ? 'Daily' - : '按天'; + ? `${stepMins}m` + : `按 ${stepMins} 分钟` + : isHourly + ? en + ? 'Hourly' + : '按小时' + : en + ? 'Daily' + : '按天'; return [ formatTrendWindowLabel(slot, isHourly), granLabel, @@ -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) { - const yStr = pts[0].y.toFixed(1); - lineD = `M ${leftX.toFixed(1)} ${yStr} L ${rightX.toFixed(1)} ${yStr}`; + 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`; } - patchAttr(linePath, 'd', lineD); - patchAttr(areaPath, 'd', areaD); - // 渲染与底部刻度对齐的垂直参考网格线及底部 X 轴标签(起止标签严格左右贴边) + 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 轴标签(起止标签严格左右贴边) 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,6 +30020,61 @@ const ConsumptionView = defineComponent({ const cacheReadLabel = h('span', { text: t('cons.cacheRead') }); const outputUsageLabel = h('span', { text: t('cons.outputUsage') }); + const unifiedMatrixEl = h('div', { className: 'cons-box cons-unified-matrix' }, [ + h('div', { className: 'cons-split-3' }, [ + h('div', { className: 'cons-col' }, [ + totalTokensLabel, + h('div', { className: 'cons-baseline' }, [heroTotalTokens, heroTotalCalls]), + ]), + h('div', { className: 'cons-col is-bordered-col' }, [ + estCostLabel, + h('div', { className: 'cons-baseline' }, [heroCostUsd, heroCostCny]), + ]), + h('div', { className: 'cons-col is-bordered-col' }, [ + h('span', { className: 'legend-left', style: 'font-size: var(--fs-md);' }, [ + h('span', { className: 'dot-swatch seg-cached' }), + cacheHitRateLabel, + ]), + h('div', { className: 'cons-baseline' }, [cacheHitPctEl, cacheTokensEl]), + ]), + ]), + h('div', { className: 'cons-split-3 cons-matrix-bottom' }, [ + h('div', { className: 'cons-col' }, [ + h('div', { className: 'cons-sub-head' }, [ + h('span', { className: 'legend-left cons-sub-label' }, [ + h('span', { className: 'dot-swatch seg-input' }), + newInputLabel, + ]), + inputSharePct, + ]), + inputMainTokens, + inputSubText, + ]), + h('div', { className: 'cons-col is-bordered-col' }, [ + h('div', { className: 'cons-sub-head' }, [ + h('span', { className: 'legend-left cons-sub-label' }, [ + h('span', { className: 'dot-swatch seg-cached' }), + cacheReadLabel, + ]), + cacheSharePct, + ]), + cacheMainTokens, + cacheSubText, + ]), + h('div', { className: 'cons-col is-bordered-col' }, [ + h('div', { className: 'cons-sub-head' }, [ + h('span', { className: 'legend-left cons-sub-label' }, [ + h('span', { className: 'dot-swatch seg-output' }), + outputUsageLabel, + ]), + outputSharePct, + ]), + outputMainTokens, + outputSubText, + ]), + ]), + ]); + const overviewPanel = h('section', { className: 'panel' }, [ h('div', { className: 'panel-header cons-overview-head' }, [ h('span', { className: 'panel-title' }, [ @@ -29624,60 +30086,7 @@ const ConsumptionView = defineComponent({ ]), ]), customRangeBar, - h('div', { className: 'cons-box cons-unified-matrix' }, [ - h('div', { className: 'cons-split-3' }, [ - h('div', { className: 'cons-col' }, [ - totalTokensLabel, - h('div', { className: 'cons-baseline' }, [heroTotalTokens, heroTotalCalls]), - ]), - h('div', { className: 'cons-col is-bordered-col' }, [ - estCostLabel, - h('div', { className: 'cons-baseline' }, [heroCostUsd, heroCostCny]), - ]), - h('div', { className: 'cons-col is-bordered-col' }, [ - h('span', { className: 'legend-left', style: 'font-size: var(--fs-md);' }, [ - h('span', { className: 'dot-swatch seg-cached' }), - cacheHitRateLabel, - ]), - h('div', { className: 'cons-baseline' }, [cacheHitPctEl, cacheTokensEl]), - ]), - ]), - h('div', { className: 'cons-split-3 cons-matrix-bottom' }, [ - h('div', { className: 'cons-col' }, [ - h('div', { className: 'cons-sub-head' }, [ - h('span', { className: 'legend-left cons-sub-label' }, [ - h('span', { className: 'dot-swatch seg-input' }), - newInputLabel, - ]), - inputSharePct, - ]), - inputMainTokens, - inputSubText, - ]), - h('div', { className: 'cons-col is-bordered-col' }, [ - h('div', { className: 'cons-sub-head' }, [ - h('span', { className: 'legend-left cons-sub-label' }, [ - h('span', { className: 'dot-swatch seg-cached' }), - cacheReadLabel, - ]), - cacheSharePct, - ]), - cacheMainTokens, - cacheSubText, - ]), - h('div', { className: 'cons-col is-bordered-col' }, [ - h('div', { className: 'cons-sub-head' }, [ - h('span', { className: 'legend-left cons-sub-label' }, [ - h('span', { className: 'dot-swatch seg-output' }), - outputUsageLabel, - ]), - outputSharePct, - ]), - outputMainTokens, - outputSubText, - ]), - ]), - ]), + 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,17 +31786,26 @@ 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 }) - : isHourlyTrend - ? t('cons.trendPointsHintHourly', { points: rawTrendSeries.length || 0 }) - : t('cons.trendPointsHintDaily', { points: rawTrendSeries.length || 0 }) + : 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 }) ); const enrichedTrendSeries = rawTrendSeries.map((slot, idx) => { const mergedSlotModels = trendMergedByIdx[idx]; @@ -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(); diff --git a/sidecars/panel/backend/usage-aggregator.mjs b/sidecars/panel/backend/usage-aggregator.mjs index c991a62..22d6655 100644 --- a/sidecars/panel/backend/usage-aggregator.mjs +++ b/sidecars/panel/backend/usage-aggregator.mjs @@ -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' - ? 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 start = + window.key === 'all' + ? Math.min(safeMs(earliest, defaultStart), end - 3600 * 1000) + : Math.min(safeMs(window.startMs, defaultStart), end); + 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() }; + first.setHours(0, 0, 0, 0); + last.setHours(0, 0, 0, 0); + 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( diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index b27c977..75d4058 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@