/** * @fileoverview View 2: ConsumptionView (全景消耗统计视图). * 采用 5 段式分析布局展示指定时间窗口内的全量 Token 与费用消耗: * 1. 用量概览:支持预设时间段与自定义区间筛选,通过 3+2 组合矩阵展示总 Token/调用次数、 * USD/CNY 预估费用、缓存命中率与命中量、输入/输出细分占比,以及底部 4 段比例条 (`FourSegmentBar`)。 * 2. 历史趋势:基于 `TrendAreaChart` 渲染纯 SVG 三次贝塞尔平滑曲线面积图、峰值气泡与首/中/末三时间锚点。 * 3. 热门模型:按 Token 总量降序展示各模型的消耗占比徽章、4 段构成条及输入/缓存/输出/思考/调用明细。 * 4. 数据来源:按调用来源聚合展示 Token 构成、占比与费用明细。 * 5. 按月细分:12 个月垂直 4 段堆叠柱状图,直观对比全年各月费用、Token 总量与缓存/思考结构。 */ import { defineComponent } from '../core/component.js'; import { h, patchAttr, patchClasses, patchKeyedList, patchStyleVar, patchText, } from '../core/domPatch.js'; import { formatCnyApprox, formatDateSpanBadge, formatTokensPrecise, formatUsd, } from '../core/formatters.js'; import { createSvgIcon } from '../icons/SvgIcon.js'; import { fetchTelemetry, telemetryStore } from '../store/telemetryStore.js'; import { uiStore } from '../store/uiStore.js'; import { createTrendAreaChart } from '../components/charts/TrendAreaChart.js'; import { CustomDateTimePicker } from '../components/ui/CustomDateTimePicker.js'; import { CustomScrollbar } from '../components/ui/CustomScrollbar.js'; import { createFourSegmentBar } from '../components/ui/FourSegmentBar.js'; import { SegmentedControl } from '../components/ui/SegmentedControl.js'; /** 消耗统计顶栏支持的时间范围预设项 */ const TIME_RANGE_OPTIONS = [ { value: 'today', label: '今天' }, { value: '24h', label: '1天' }, { value: '7d', label: '7天' }, { value: '14d', label: '14天' }, { value: '30d', label: '30天' }, { value: 'all', label: '全部' }, { value: 'custom', label: '自定义' }, ]; export const ConsumptionView = defineComponent({ name: 'ConsumptionView', setup({ onCleanup }) { // --- 时间筛选栏:快速时间段分段控制器与自定义起止时间选择条 --- const timeFilterSwitch = SegmentedControl({ ariaLabel: '消耗统计时间范围', modelValue: telemetryStore.getState().selectedTimeRange, options: TIME_RANGE_OPTIONS, onUpdateModelValue: (nextRange) => { telemetryStore.setState({ selectedTimeRange: nextRange }); fetchTelemetry({ force: false }); }, }); const startPicker = CustomDateTimePicker({ modelValue: telemetryStore.getState().customStartMs, onUpdateModelValue: (ms) => { telemetryStore.setState({ customStartMs: ms }); }, }); const endPicker = CustomDateTimePicker({ modelValue: telemetryStore.getState().customEndMs, onUpdateModelValue: (ms) => { telemetryStore.setState({ customEndMs: ms }); }, }); const applyCustomBtn = h( 'button', { type: 'button', className: 'btn-primary', style: 'height: 26px; padding: 0 10px;', onClick: () => { telemetryStore.setState({ selectedTimeRange: 'custom' }); fetchTelemetry({ force: true }); }, }, [createSvgIcon('check', { size: 12 }), h('span', { text: '筛选' })] ); const customRangeBar = h( 'div', { style: 'display: flex; align-items: center; flex-wrap: wrap; gap: 6px; padding: 6px 8px; background: var(--surface-subtle); border: 1px solid var(--border-hairline); border-radius: var(--radius-xs);', hidden: true, }, [ startPicker.el, h('span', { className: 'text-muted', text: '至' }), endPicker.el, applyCustomBtn, ] ); // --- Section 1: 用量概览矩阵 (上层 3 列核心总量 + 下层 2 列输入/输出拆分 + 底部 4 段比例条) --- const dateSpanBadge = h('span', { className: 'cons-badge text-mono', text: '-- ~ --' }); const heroTotalTokens = h('strong', { className: 'cons-hero-num text-mono', text: '0' }); const heroTotalCalls = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '0 次' }); const heroCostUsd = h('strong', { className: 'cons-hero-cost text-mono', text: '$0.00' }); const heroCostCny = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '≈ ¥0' }); const cacheHitPctEl = h('strong', { className: 'cons-hero-cache text-mono', text: '0%' }); const cacheTokensEl = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '命中 0' }); const inputSharePct = h('span', { className: 'text-mono', style: 'color: var(--ctx-input); font-weight: 600; font-size: 11.5px;', text: '0%' }); const inputMainTokens = h('strong', { className: 'cons-mid-num text-mono', text: '0' }); const inputSubText = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '新输入 0 · 缓存 0' }); const outputSharePct = h('span', { className: 'text-mono', style: 'color: var(--ctx-output); font-weight: 600; font-size: 11.5px;', text: '0%' }); const outputMainTokens = h('strong', { className: 'cons-mid-num text-mono', text: '0' }); const outputSubText = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '回复 0 · 思考 0' }); const overviewSegBar = createFourSegmentBar(); const overviewPanel = h('section', { className: 'panel' }, [ h('div', { className: 'panel-header cons-overview-head' }, [ h('span', { className: 'panel-title' }, [ h('span', { text: '用量总览' }), dateSpanBadge, ]), timeFilterSwitch.el, ]), customRangeBar, h('div', { className: 'cons-box cons-unified-matrix' }, [ h('div', { className: 'cons-split-3' }, [ h('div', { className: 'cons-col' }, [ h('span', { className: 'text-muted', style: 'font-size: 11px;', text: '总 Token' }), h('div', { className: 'cons-baseline' }, [heroTotalTokens, heroTotalCalls]), ]), h('div', { className: 'cons-col is-bordered-col' }, [ h('span', { className: 'text-muted', style: 'font-size: 11px;', text: '预估费用' }), h('div', { className: 'cons-baseline' }, [heroCostUsd, heroCostCny]), ]), h('div', { className: 'cons-col is-bordered-col' }, [ h('span', { className: 'legend-left', style: 'font-size: 11px;' }, [ h('span', { className: 'dot-swatch seg-cached' }), h('span', { text: '缓存命中率' }), ]), h('div', { className: 'cons-baseline' }, [cacheHitPctEl, cacheTokensEl]), ]), ]), h('div', { className: 'cons-split-2 cons-matrix-bottom' }, [ h('div', { className: 'cons-col' }, [ h('div', { className: 'panel-header' }, [ h('span', { className: 'legend-left' }, [ h('span', { className: 'dot-swatch seg-input' }), h('span', { style: 'color: var(--text-primary); font-weight: 600; font-size: 11.5px;', text: '输入用量' }), inputMainTokens, ]), inputSharePct, ]), inputSubText, ]), h('div', { className: 'cons-col is-bordered-col' }, [ h('div', { className: 'panel-header' }, [ h('span', { className: 'legend-left' }, [ h('span', { className: 'dot-swatch seg-output' }), h('span', { style: 'color: var(--text-primary); font-weight: 600; font-size: 11.5px;', text: '输出用量' }), outputMainTokens, ]), outputSharePct, ]), outputSubText, ]), ]), ]), overviewSegBar.el, ]); // --- Section 2: 历史趋势 (SVG 三次贝塞尔平滑曲线图 + 首/中/末三时间锚点) --- const trendRangeBadge = h('span', { className: 'cons-badge', text: '全部时间' }); const trendChart = createTrendAreaChart(); const anchorStartTime = h('span', { className: 'text-muted text-mono', text: '00:00' }); const anchorStartVal = h('strong', { className: 'text-mono', text: '0' }); const anchorMidTime = h('span', { className: 'text-muted text-mono', text: '06:00' }); const anchorMidVal = h('strong', { className: 'text-mono', text: '0' }); const anchorEndTime = h('span', { className: 'text-muted text-mono', text: '12:00' }); const anchorEndVal = h('strong', { className: 'text-mono', text: '0' }); const trendPanel = h('section', { className: 'panel' }, [ h('div', { className: 'panel-header' }, [ h('span', { className: 'panel-title', text: '用量趋势' }), trendRangeBadge, ]), trendChart.el, h('div', { className: 'trend-anchors' }, [ h('div', { className: 'trend-anchor-col' }, [anchorStartTime, anchorStartVal]), h('div', { className: 'trend-anchor-col is-center' }, [anchorMidTime, anchorMidVal]), h('div', { className: 'trend-anchor-col is-end' }, [anchorEndTime, anchorEndVal]), ]), ]); // --- Section 3: 模型排行列表 --- const modelsListEl = h('div', { className: 'cons-item-list' }); const modelsPanel = h('section', { className: 'panel' }, [ h('div', { className: 'panel-header' }, [ h('span', { className: 'panel-title', text: '模型排行' }), ]), modelsListEl, ]); // --- Section 4: 客户端来源列表 --- const sourcesListEl = h('div', { className: 'cons-item-list' }); const sourcesPanel = h('section', { className: 'panel' }, [ h('div', { className: 'panel-header' }, [ h('span', { className: 'panel-title', text: '客户端来源' }), ]), sourcesListEl, ]); // --- Section 5: 按月细分 (12 个月垂直 4 段堆叠柱状图) --- const monthlyYearBadge = h('span', { className: 'cons-badge text-mono', text: '2026' }); const monthlyCols = Array.from({ length: 12 }, (_, idx) => { const costText = h('span', { className: 'month-cost text-mono', text: '' }); const barThink = h('div', { className: 'month-seg seg-thinking' }); const barOut = h('div', { className: 'month-seg seg-output' }); const barCache = h('div', { className: 'month-seg seg-cached' }); const barIn = h('div', { className: 'month-seg seg-input' }); const stackWrap = h('div', { className: 'month-stack' }, [ barThink, barOut, barCache, barIn, ]); const zeroDot = h('span', { className: 'month-zero-dot' }); const monthLabel = h('span', { className: 'month-label', text: `${idx + 1}月` }); const tokText = h('span', { className: 'month-tok text-mono', text: '' }); const colEl = h('div', { className: 'month-col' }, [ costText, h('div', { className: 'month-bar-well' }, [stackWrap, zeroDot]), monthLabel, tokText, ]); return { el: colEl, costText, stackWrap, zeroDot, barThink, barOut, barCache, barIn, monthLabel, tokText, }; }); const monthlyPanel = h('section', { className: 'panel' }, [ h('div', { className: 'panel-header' }, [ h('span', { className: 'panel-title', text: '月度统计' }), monthlyYearBadge, ]), h( 'div', { className: 'monthly-grid' }, monthlyCols.map((c) => c.el) ), h('div', { className: 'monthly-legend' }, [ h('span', { className: 'legend-left' }, [ h('span', { className: 'dot-swatch seg-input' }), h('span', { text: '输入' }), ]), h('span', { className: 'legend-left' }, [ h('span', { className: 'dot-swatch seg-cached' }), h('span', { text: '缓存' }), ]), h('span', { className: 'legend-left' }, [ h('span', { className: 'dot-swatch seg-output' }), h('span', { text: '输出' }), ]), h('span', { className: 'legend-left' }, [ h('span', { className: 'dot-swatch seg-thinking' }), h('span', { text: '思考' }), ]), ]), ]); const scrollInner = h( 'div', { style: 'display: flex; flex-direction: column; gap: var(--space-3); padding-bottom: var(--space-3);', }, [ overviewPanel, trendPanel, modelsPanel, sourcesPanel, monthlyPanel, ] ); const viewScrollbar = CustomScrollbar({ contentEl: scrollInner, className: 'view-pane', }); /** * 创建热门模型或数据来源的通用单行 DOM 结构(含标题、占比胶囊、总量、费用、4 段条与底部分项脚标)。 */ function createBreakdownItemRow() { const nameEl = h('strong', { className: 'cons-row-title' }); const pctBadge = h('span', { className: 'cons-share-pill text-mono', text: '0%' }); const totalTokEl = h('span', { className: 'cons-row-tok text-mono' }); const costEl = h('strong', { className: 'cons-row-cost text-mono' }); const segBar = createFourSegmentBar(); const inVal = h('strong', { className: 'text-mono' }); const cacheVal = h('strong', { className: 'text-mono' }); const outVal = h('strong', { className: 'text-mono' }); const thinkVal = h('strong', { className: 'text-mono' }); const callsVal = h('strong', { className: 'text-mono' }); const rowEl = h('div', { className: 'cons-item-row' }, [ h('div', { className: 'panel-header' }, [ nameEl, h('span', { className: 'cons-row-metrics' }, [ pctBadge, totalTokEl, costEl, ]), ]), segBar.el, h('div', { className: 'cons-item-foot' }, [ h('span', { className: 'legend-left' }, [ h('span', { className: 'dot-swatch seg-input' }), h('span', { text: '输入 ' }), inVal, ]), h('span', { className: 'legend-left' }, [ h('span', { className: 'dot-swatch seg-cached' }), h('span', { text: '缓存 ' }), cacheVal, ]), h('span', { className: 'legend-left' }, [ h('span', { className: 'dot-swatch seg-output' }), h('span', { text: '输出 ' }), outVal, ]), h('span', { className: 'legend-left' }, [ h('span', { className: 'dot-swatch seg-thinking' }), h('span', { text: '思考 ' }), thinkVal, ]), h('span', { className: 'legend-left' }, [ h('span', { text: '调用 ' }), callsVal, ]), ]), ]); return { el: rowEl, refs: { nameEl, pctBadge, totalTokEl, costEl, segBar, inVal, cacheVal, outVal, thinkVal, callsVal }, }; } /** * 增量更新热门模型或数据来源单行的指标文本与 4 段比例条宽度。 */ function updateBreakdownItemRow(refs, item, grandTotalTokens, showTokensInHeader = true) { patchText(refs.nameEl, item.label || item.name || item.shortName || '—'); const total = Number(item.totalTokens || 0); const share = grandTotalTokens > 0 ? +((total / grandTotalTokens) * 100).toFixed(1) : 0; patchText(refs.pctBadge, `${share.toFixed(1)}%`); patchText(refs.totalTokEl, showTokensInHeader ? formatTokensPrecise(total) : ''); patchAttr(refs.totalTokEl, 'hidden', !showTokensInHeader); patchText(refs.costEl, formatUsd(item.costUsd || 0, { unpricedCalls: item.unpricedCalls })); const responseTok = item.responseTokens != null ? Number(item.responseTokens) : Math.max(0, Number(item.outputTokens || 0) - Number(item.thinkingTokens || 0)); const thinkingTok = Number(item.thinkingTokens || 0); refs.segBar.update({ inputTokens: Number(item.inputTokens || 0), cacheReadTokens: Number(item.cacheReadTokens || 0), responseTokens: responseTok, thinkingTokens: thinkingTok, }); patchText(refs.inVal, formatTokensPrecise(item.inputTokens || 0)); patchText(refs.cacheVal, formatTokensPrecise(item.cacheReadTokens || 0)); patchText(refs.outVal, formatTokensPrecise(responseTok)); patchText(refs.thinkVal, formatTokensPrecise(thinkingTok)); patchText(refs.callsVal, String(Number(item.calls || 0))); } let latestSlice = null; let isDirty = false; /** * 将遥测状态切片同步渲染至消费统计视图的 5 个子面板。 */ function renderConsumptionData(slice) { if (!slice) return; timeFilterSwitch.setValue(slice.range); patchAttr(customRangeBar, 'hidden', slice.range !== 'custom'); startPicker.setValue(slice.customStartMs); endPicker.setValue(slice.customEndMs); const cons = slice.consumption || {}; const preset = slice.range !== 'custom' && cons.presets?.[slice.range] ? cons.presets[slice.range] : null; const acct = preset?.account || cons.account || {}; const rangeInfo = cons.selectedRange || {}; // 1. 同步用量概览矩阵与顶部 4 段比例条 patchText(dateSpanBadge, formatDateSpanBadge(rangeInfo.startMs, rangeInfo.endMs)); const totalTokens = Number(acct.totalTokens || 0); const inputTokens = Number(acct.inputTokens || 0); const cacheTokens = Number(acct.cacheReadTokens || 0); const outputTokens = Number(acct.outputTokens || 0); const responseTokens = Number(acct.responseTokens || 0); const thinkingTokens = Number(acct.thinkingTokens || 0); const costUsd = Number(acct.costUsd || 0); patchText(heroTotalTokens, formatTokensPrecise(totalTokens)); patchText(heroTotalCalls, `${acct.calls || 0} 次`); patchText(heroCostUsd, formatUsd(costUsd, { unpricedCalls: acct.unpricedCalls })); patchText(heroCostCny, acct.unpricedCalls > 0 ? `${acct.unpricedCalls} 步费用待定` : formatCnyApprox(costUsd)); patchText(cacheHitPctEl, `${Number(acct.cacheHitPct ?? 0).toFixed(1)}%`); patchText(cacheTokensEl, `命中 ${formatTokensPrecise(cacheTokens)}`); const inPct = totalTokens > 0 ? +((inputTokens / totalTokens) * 100).toFixed(1) : 0; const outPct = totalTokens > 0 ? +((outputTokens / totalTokens) * 100).toFixed(1) : 0; patchText(inputSharePct, `${inPct}%`); patchText(inputMainTokens, formatTokensPrecise(inputTokens)); patchText( inputSubText, `新输入 ${formatTokensPrecise(inputTokens)} · 缓存 ${formatTokensPrecise(cacheTokens)}` ); patchText(outputSharePct, `${outPct}%`); patchText(outputMainTokens, formatTokensPrecise(outputTokens)); patchText( outputSubText, `回复 ${formatTokensPrecise(responseTokens)} · 思考 ${formatTokensPrecise(thinkingTokens)}` ); overviewSegBar.update({ inputTokens, cacheReadTokens: cacheTokens, responseTokens, thinkingTokens, }); // 2. 同步历史趋势 SVG 面积图与首/中/末三时间锚点 patchText(trendRangeBadge, preset?.label || rangeInfo.label || '全部时间'); const trendSeries = cons.trendSeries || []; trendChart.update(trendSeries); if (trendSeries.length > 0) { const first = trendSeries[0]; const mid = trendSeries[Math.floor(trendSeries.length / 2)]; const last = trendSeries[trendSeries.length - 1]; patchText(anchorStartTime, first.label); patchText(anchorStartVal, formatTokensPrecise(first.tokens)); patchText(anchorMidTime, mid.label); patchText(anchorMidVal, formatTokensPrecise(mid.tokens)); patchText(anchorEndTime, last.label); patchText(anchorEndVal, formatTokensPrecise(last.tokens)); } // 3. 同步热门模型列表(按总 Token 数降序排列并执行键值增量对账) const models = (slice.modelBreakdown || []) .slice() .sort((a, b) => (b.totalTokens || 0) - (a.totalTokens || 0)); const modelsTotalTok = models.reduce((s, m) => s + Number(m.totalTokens || 0), 0); patchKeyedList(modelsListEl, models, { keyFn: (m) => m.label || m.shortName, sigFn: (m) => `${m.label}:${m.totalTokens}:${m.costUsd}:${m.unpricedCalls}:${m.calls}:${modelsTotalTok}`, createRow: createBreakdownItemRow, updateRow: (refs, m) => updateBreakdownItemRow(refs, m, modelsTotalTok, true), }); // 4. 同步数据来源列表 const sources = cons.sourcesBreakdown || []; const sourcesTotalTok = sources.reduce((s, x) => s + Number(x.totalTokens || 0), 0); patchKeyedList(sourcesListEl, sources, { keyFn: (s) => s.name, sigFn: (s) => `${s.name}:${s.totalTokens}:${s.costUsd}:${s.unpricedCalls}:${s.calls}:${sourcesTotalTok}`, createRow: createBreakdownItemRow, updateRow: (refs, s) => updateBreakdownItemRow(refs, s, sourcesTotalTok, true), }); // 5. 同步 12 个月垂直堆叠柱状图(相对于年度峰值月缩放柱高,最低保留 8% 可视高度) const monthlyYear = cons.monthlyYear || new Date().getFullYear(); const currentMonthIdx = new Date().getMonth(); patchText(monthlyYearBadge, String(monthlyYear)); const monthlySeries = cons.monthlySeries || []; const maxMonthTokens = Math.max( 1, ...monthlySeries.map((m) => Number(m.totalTokens || 0)) ); for (let i = 0; i < 12; i++) { const col = monthlyCols[i]; const m = monthlySeries[i] || { totalTokens: 0, costUsd: 0 }; const mTot = Number(m.totalTokens || 0); const hasData = mTot > 0; patchClasses(col.monthLabel, { 'is-current': i === currentMonthIdx }); patchAttr(col.stackWrap, 'hidden', !hasData); patchAttr(col.zeroDot, 'hidden', hasData); if (!hasData) { patchText(col.costText, ''); patchText(col.tokText, ''); } else { const cVal = Number(m.costUsd || 0); patchText(col.costText, m.unpricedCalls > 0 ? formatUsd(cVal, { unpricedCalls: m.unpricedCalls }) : cVal >= 10 ? `$${Math.round(cVal)}` : `$${cVal.toFixed(2)}`); patchText(col.tokText, formatTokensPrecise(mTot)); const totalHeightPct = Math.max(8, Math.min(100, (mTot / maxMonthTokens) * 100)); patchStyleVar(col.stackWrap, '--bar-h', `${totalHeightPct.toFixed(1)}%`); const inPctM = (Number(m.inputTokens || 0) / mTot) * 100; const cachePctM = (Number(m.cacheReadTokens || 0) / mTot) * 100; const outPctM = (Number(m.responseTokens || 0) / mTot) * 100; const thinkPctM = (Number(m.thinkingTokens || 0) / mTot) * 100; patchStyleVar(col.barIn, '--seg-h', `${inPctM.toFixed(1)}%`); patchStyleVar(col.barCache, '--seg-h', `${cachePctM.toFixed(1)}%`); patchStyleVar(col.barOut, '--seg-h', `${outPctM.toFixed(1)}%`); patchStyleVar(col.barThink, '--seg-h', `${thinkPctM.toFixed(1)}%`); } } viewScrollbar.refresh(); } const unsub = telemetryStore.subscribe( (st) => ({ range: st.selectedTimeRange, customStartMs: st.customStartMs, customEndMs: st.customEndMs, consumption: st.telemetry?.consumption, modelBreakdown: st.telemetry?.modelBreakdown, }), (slice) => { latestSlice = slice; if (uiStore.getState().activeView !== 'consumption') { isDirty = true; return; } isDirty = false; renderConsumptionData(slice); } ); const unsubView = uiStore.subscribe( (st) => st.activeView, (activeView) => { if (activeView === 'consumption' && isDirty) { isDirty = false; if (latestSlice) { renderConsumptionData(latestSlice); } } } ); onCleanup(() => { unsub(); unsubView(); timeFilterSwitch.destroy(); startPicker.destroy(); endPicker.destroy(); viewScrollbar.destroy(); }); return { el: viewScrollbar.el, refs: { timeFilterSwitch, startPicker, endPicker, viewScrollbar }, }; }, });