dsh-token-dash 2.3.0 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js CHANGED
@@ -11,6 +11,36 @@ window.__ModuleLoader__.load({
11
11
 
12
12
  const API = '/token-dash/api'
13
13
  const PKG = 'dsh-token-dash'
14
+
15
+ // 客户端事件上报:走宿主 /log 落到本机日志。三层限流防止「增强本身变成故障源」。
16
+ const CLIENT_LOG_PER_EVENT = 20
17
+ const CLIENT_LOG_PER_HOUR = 100
18
+ const clientLogState = { seen: new Set(), perEvent: new Map(), windowStart: 0, total: 0 }
19
+
20
+ function reportClientLog(module, event, meta) {
21
+ try {
22
+ const now = Date.now()
23
+ const state = clientLogState
24
+ if (now - state.windowStart > 3600_000) {
25
+ state.windowStart = now
26
+ state.perEvent.clear()
27
+ state.seen.clear()
28
+ state.total = 0
29
+ }
30
+ const key = `${event}|${meta?.message ?? ''}|${meta?.path ?? ''}`
31
+ if (state.seen.has(key)) return
32
+ if ((state.perEvent.get(event) ?? 0) >= CLIENT_LOG_PER_EVENT) return
33
+ if (state.total >= CLIENT_LOG_PER_HOUR) return
34
+ state.seen.add(key)
35
+ state.perEvent.set(event, (state.perEvent.get(event) ?? 0) + 1)
36
+ state.total += 1
37
+ void fetch(`${API}/log`, {
38
+ method: 'POST',
39
+ headers: { 'content-type': 'application/json' },
40
+ body: JSON.stringify({ module, event, meta }),
41
+ }).catch(() => {})
42
+ } catch { /* 日志失败绝不影响渲染 */ }
43
+ }
14
44
  const PAGE_ID = 'token-dash'
15
45
  const REPO_URL = 'https://github.com/spartawhy117/dsh-token-dash'
16
46
  const SUB_CRITICAL = 90
@@ -44,6 +74,11 @@ window.__ModuleLoader__.load({
44
74
  '30秒': '30s', '1分钟': '1m', '5分钟': '5m',
45
75
  '社区': 'Community', '内置兜底': 'Built-in fallback',
46
76
  '查询失败': 'Query failed', '套餐查询失败': 'Quota query failed',
77
+ '数据加载中': 'Loading data',
78
+ '含估算': 'incl. estimates',
79
+ 'API 与订阅金额均为本地按目录价估算,非供应商账单;缓存读按缓存价计,命中率高的行每 token 成本显著更低,不同行不可直接按 token 数比较;不同币种需自行换算': 'Both API and subscription amounts are estimated locally from catalog prices, not provider invoices; cached reads use the cache price, so rows with a higher hit rate cost much less per token and rows are not directly comparable by token count; currencies are not converted.',
80
+ '本月估算': 'Est. this month',
81
+ '订阅不计价,估算值仅作参考': 'Subscription is not billed; the estimate is for reference only',
47
82
  '周': 'Week', '月': 'Month', '重置': 'Reset',
48
83
  'API 用量': 'API usage', '订阅': 'Subscription', '账户套餐': 'Account plan',
49
84
  '预算': 'Budget', '未设置': 'Not set', '今日 {value}': 'Today {value}',
@@ -125,6 +160,7 @@ window.__ModuleLoader__.load({
125
160
  '{n} 个币种': '{n} currencies', '范围内全部模型': 'All models in range',
126
161
  '创建 {a} · 命中 {b}': 'Created {a} · hit {b}',
127
162
  '趋势指标': 'Trend metric', '使用趋势 · {metric}': 'Trend · {metric}',
163
+ '模型明细': 'Model breakdown', '范围按当前时间范围统计': 'Scoped to the selected range',
128
164
  '按天': 'Daily', '按月': 'Monthly',
129
165
  '与上方卡片同口径': 'Same scope as cards above',
130
166
  '命中率': 'Hit rate', '无数据': 'No data',
@@ -157,6 +193,8 @@ window.__ModuleLoader__.load({
157
193
  muted: 'var(--dsw-alias-label-secondary, rgba(235,235,235,.65))',
158
194
  weak: 'var(--dsw-alias-label-tertiary, rgba(235,235,235,.45))',
159
195
  accent: 'var(--dsw-alias-state-business-primary, #6ea8ff)',
196
+ // 第二条数据序列(双轴图的次币种柱):独立色相,不借用绿/黄/红等状态语义色
197
+ series2: 'var(--td-series-2, #c9a5ff)',
160
198
  warn: 'var(--dsw-alias-state-warn-primary, #f0a020)',
161
199
  over: 'var(--dsw-alias-state-error-primary, #e05a5a)',
162
200
  ok: 'var(--td-state-ok, var(--dsw-alias-state-success-primary, #4ed17e))',
@@ -242,7 +280,8 @@ window.__ModuleLoader__.load({
242
280
  }
243
281
 
244
282
  async function getJson(path) {
245
- const res = await fetch(`${API}${path}`, { headers: { accept: 'application/json' } })
283
+ // 10 秒超时:把「一直等」转成可重试的失败态,避免长时间无反馈(REQ-07)
284
+ const res = await fetch(`${API}${path}`, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(10_000) })
246
285
  const body = await res.json().catch(() => ({}))
247
286
  if (!res.ok || body?.ok !== true) throw new Error(body?.reason ?? `http-${res.status}`)
248
287
  return body.data
@@ -570,7 +609,7 @@ window.__ModuleLoader__.load({
570
609
  apiCard: {
571
610
  flex: '1 1 220px', maxWidth: 260, minWidth: 220, boxSizing: 'border-box',
572
611
  border: `1px solid ${T.border}`, borderRadius: 8, background: T.section, padding: 16,
573
- display: 'grid', gap: 8, alignContent: 'start',
612
+ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr)', gap: 8, alignContent: 'start',
574
613
  },
575
614
  apiCardHead: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, minWidth: 0 },
576
615
  apiCardName: { fontSize: 13, fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
@@ -607,20 +646,35 @@ window.__ModuleLoader__.load({
607
646
  },
608
647
  rangeHead: { display: 'flex', alignItems: 'center', justifyContent: 'flex-start', flexWrap: 'wrap', gap: 16 },
609
648
  rangeMeta: { color: T.weak, fontSize: 11 },
610
- detailWrap: { overflowX: 'auto', borderTop: `1px solid ${T.border}`, paddingTop: 12 },
649
+ detailHead: { display: 'flex', alignItems: 'baseline', gap: 8, marginTop: 16, paddingTop: 14, borderTop: `1px solid ${T.border}`, minWidth: 0 },
650
+ detailHint: { color: T.weak, fontSize: 11 },
651
+ detailWrap: { overflowX: 'auto', paddingTop: 8 },
611
652
  trendBox: { display: 'flex', flexDirection: 'column', gap: 8, borderTop: `1px solid ${T.border}`, paddingTop: 12, minWidth: 0 },
612
653
  trendHead: { display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', minWidth: 0 },
613
654
  trendTitle: { fontSize: 13, fontWeight: 600 },
614
655
  trendHint: { color: T.weak, fontSize: 11 },
615
656
  trendSpacer: { flex: '1 1 auto' },
616
- trendPlot: { position: 'relative', height: 132, minWidth: 0 },
657
+ // 轴与绘图区两列:轴在绘图区之外(与 CC Switch 的 <YAxis> 同构),绘图区自己承担网格与柱
658
+ trendPlot: { display: 'grid', gridTemplateColumns: 'auto minmax(0, 1fr)', height: 132, minWidth: 0 },
659
+ trendPlotDual: { gridTemplateColumns: 'auto minmax(0, 1fr) auto' },
660
+ trendAxisColRight: { paddingRight: 0, paddingLeft: 6 },
661
+ trendAxisRight: {
662
+ position: 'absolute', left: 0, fontSize: 11, color: T.weak, fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap',
663
+ },
664
+ trendLegend: { display: 'flex', alignItems: 'center', gap: 6, marginRight: 8, fontSize: 11, color: T.muted, whiteSpace: 'nowrap' },
665
+ trendLegendDot: { width: 8, height: 8, borderRadius: 999, display: 'inline-block', marginRight: 3 },
666
+ trendAxisCol: { position: 'relative', minWidth: 0, paddingRight: 6 },
667
+ trendAxis: {
668
+ position: 'absolute', right: 6, color: T.weak, fontSize: 11, lineHeight: '14px',
669
+ fontVariantNumeric: 'tabular-nums', textAlign: 'right', whiteSpace: 'nowrap', pointerEvents: 'none',
670
+ },
671
+ trendPlotArea: { position: 'relative', minWidth: 0 },
617
672
  trendGrid: { position: 'absolute', left: 0, right: 0, height: 1, background: T.border, pointerEvents: 'none' },
618
- trendAxis: { position: 'absolute', left: 0, color: T.weak, fontSize: 11, fontVariantNumeric: 'tabular-nums' },
619
- trendBars: { position: 'absolute', inset: '0 0 18px 0', display: 'flex', alignItems: 'flex-end', gap: 2, paddingLeft: 34, zIndex: 1 },
673
+ trendBars: { position: 'absolute', inset: '0 0 18px 0', display: 'flex', alignItems: 'flex-end', gap: 2, zIndex: 1 },
620
674
  // 每根柱独占一个等分槽并在槽内居中:只对柱体设 maxWidth 会让所有柱挤到一侧
621
675
  trendSlot: { flex: '1 1 0', minWidth: 1, height: '100%', display: 'flex', alignItems: 'flex-end', justifyContent: 'center' },
622
676
  trendBar: { width: '100%', maxWidth: 36, borderRadius: '3px 3px 0 0', background: T.accent },
623
- trendTicks: { position: 'absolute', left: 34, right: 0, bottom: 0, height: 18, display: 'flex', alignItems: 'center', gap: 2, color: T.weak, fontSize: 11 },
677
+ trendTicks: { position: 'absolute', left: 0, right: 0, bottom: 0, height: 18, display: 'flex', alignItems: 'center', gap: 2, color: T.weak, fontSize: 11 },
624
678
  // 虚线要压在柱体之上:柱容器 zIndex 1,指示线 zIndex 4,浮层 5
625
679
  trendHoverLine: {
626
680
  position: 'absolute', top: 0, bottom: 18, width: 1, marginLeft: -0.5, pointerEvents: 'none',
@@ -662,14 +716,18 @@ window.__ModuleLoader__.load({
662
716
  height: 22, padding: '0 8px', boxSizing: 'border-box', borderRadius: 6, font: 'inherit', fontSize: 11,
663
717
  cursor: 'pointer', border: '1px solid transparent', background: 'transparent', color: T.muted,
664
718
  },
665
- trendMsg: { position: 'absolute', inset: '0 0 18px 34px', display: 'flex', alignItems: 'center', justifyContent: 'center', color: T.muted, fontSize: 11 },
666
- quotaCards: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 12 },
719
+ // 空态文案:绘图区内居中(轴已在左列,无需再让出留白)
720
+ trendMsg: { position: 'absolute', inset: '0 0 18px 0', display: 'flex', alignItems: 'center', justifyContent: 'center', color: T.muted, fontSize: 11 },
721
+ // 订阅卡与按量卡同一套宽度规则:flex 等分 + 上限 260,单家时不再铺满
722
+ quotaCards: { display: 'flex', flexWrap: 'wrap', justifyContent: 'center', alignItems: 'start', gap: 12 },
667
723
  quotaCard: {
668
724
  border: `1px solid ${T.border}`, borderRadius: 8, background: T.section, padding: 16,
669
- display: 'grid', gap: 12, alignContent: 'start', minWidth: 0,
725
+ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr)', gap: 12, alignContent: 'start', minWidth: 0,
726
+ flex: '1 1 220px', maxWidth: 260, boxSizing: 'border-box',
670
727
  },
671
728
  quotaWindows: { display: 'grid', gap: 12, minWidth: 0 },
672
- cardCaption: { color: T.weak, fontSize: 11, textAlign: 'center', marginTop: 4, whiteSpace: 'nowrap' },
729
+ // 说明行可能很长(周期 / 限流 / 渠道用量叠加),必须允许换行,否则会把卡片撑宽(Issue #4)
730
+ cardCaption: { color: T.weak, fontSize: 11, textAlign: 'center', marginTop: 4, whiteSpace: 'normal', overflowWrap: 'anywhere' },
673
731
  rangeCapsule: { width: '100%', minWidth: 0 },
674
732
  }
675
733
  styles.button['--td-accent'] = T.accent
@@ -682,6 +740,35 @@ window.__ModuleLoader__.load({
682
740
  styles.ghost = { ...styles.button, color: T.accent, borderColor: 'transparent', background: 'transparent' }
683
741
  styles.outline = { ...styles.button, color: T.text, borderColor: T.border, background: 'transparent' }
684
742
 
743
+ /** 看板渲染兜底:异常时给可读文案 + 重试,而不是整块空白;并把 componentStack 上报落盘。 */
744
+ class BoardBoundary extends React.Component {
745
+ constructor(props) {
746
+ super(props)
747
+ this.state = { failed: false }
748
+ }
749
+
750
+ static getDerivedStateFromError() { return { failed: true } }
751
+
752
+ componentDidCatch(error, info) {
753
+ reportClientLog('board', 'render.error', {
754
+ message: String(error?.message ?? error).slice(0, 200),
755
+ stack: String(info?.componentStack ?? '').slice(0, 400),
756
+ })
757
+ }
758
+
759
+ render() {
760
+ if (this.state.failed) {
761
+ return h('div', { 'data-testid': 'token-dash-board-error', style: styles.cardBox },
762
+ h('div', { style: styles.empty }, tr('数据渲染失败')),
763
+ h('button', {
764
+ type: 'button', style: styles.button,
765
+ onClick: () => this.setState({ failed: false }),
766
+ }, tr('重试')))
767
+ }
768
+ return this.props.children
769
+ }
770
+ }
771
+
685
772
  function Icon({ name, size = 14, style }) {
686
773
  const props = { width: size, height: size, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 2, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true, style }
687
774
  if (name === 'info') return h('svg', props, h('circle', { cx: 12, cy: 12, r: 9 }), h('path', { d: 'M12 11v5' }), h('path', { d: 'M12 8h.01' }))
@@ -978,8 +1065,9 @@ window.__ModuleLoader__.load({
978
1065
  /** P3 明细表:八列,费用只对 API 计价行展示。 */
979
1066
  function DetailTable({ rows, providerNames = {} }) {
980
1067
  if (rows.length === 0) return h('div', { style: styles.empty }, tr('范围内暂无消耗'))
981
- const headCell = (text, align = 'right') => h('span', {
1068
+ const headCell = (text, align = 'right', title) => h('span', {
982
1069
  role: 'columnheader',
1070
+ ...(title === undefined ? {} : { title }),
983
1071
  style: { color: T.weak, fontSize: 11, textAlign: align, paddingBottom: 8, borderBottom: `1px solid ${T.border}` },
984
1072
  }, text)
985
1073
  const cell = { padding: '4px 0', borderBottom: TABLE_BORDER, fontSize: 13, minWidth: 0 }
@@ -988,7 +1076,9 @@ window.__ModuleLoader__.load({
988
1076
  h('div', { style: { display: 'contents' } },
989
1077
  headCell(tr('模型'), 'left'),
990
1078
  headCell('Tokens'), headCell(tr('输入')), headCell(tr('缓存')), headCell(tr('输出')),
991
- headCell(tr('请求')), headCell(tr('命中')), headCell(tr('费用'))),
1079
+ headCell(tr('请求')), headCell(tr('命中')),
1080
+ headCell(h('span', { style: { display: 'inline-flex', alignItems: 'center', gap: 4 } },
1081
+ tr('费用'), h(Icon, { name: 'info', size: 11 })), 'right', tr('API 与订阅金额均为本地按目录价估算,非供应商账单;缓存读按缓存价计,命中率高的行每 token 成本显著更低,不同行不可直接按 token 数比较;不同币种需自行换算'))),
992
1082
  ...rows.map((row) => h('div', {
993
1083
  key: `${row.providerId}:${row.modelId}`,
994
1084
  role: 'row',
@@ -1017,11 +1107,17 @@ window.__ModuleLoader__.load({
1017
1107
  : undefined,
1018
1108
  style: { ...styles.cellNum, ...cell, textAlign: 'right' },
1019
1109
  },
1020
- row.kind !== 'api' || row.priced === 'empty'
1021
- ? '—'
1022
- : row.priced === false
1023
- ? tr('未定价')
1024
- : `${row.approximate === true ? '≈' : ''}${fmtMoney(row.cost, row.currency)}`)))))
1110
+ row.kind !== 'api'
1111
+ ? (row.estimatedPriced === undefined
1112
+ ? '—'
1113
+ : row.estimatedPriced === true
1114
+ ? `≈${fmtMoney(row.estimatedCost, row.currency)}`
1115
+ : tr('未定价'))
1116
+ : row.priced === 'empty'
1117
+ ? '—'
1118
+ : row.priced === false
1119
+ ? tr('未定价')
1120
+ : `≈${fmtMoney(row.cost, row.currency)}`)))))
1025
1121
  }
1026
1122
 
1027
1123
  /** P3 趋势指标:唯一顺序源——四格摘要带与右侧胶囊都从这里派生,禁止各自维护顺序。 */
@@ -1071,13 +1167,41 @@ window.__ModuleLoader__.load({
1071
1167
  return fmtTrendTokens(value)
1072
1168
  }
1073
1169
 
1170
+ /**
1171
+ * 趋势图 Y 轴刻度:上 / 中 / 下三档。
1172
+ * 底部档只在坐标下限不为 0(命中率轴)时出现——否则底部档与「0」重复,白白多一行字。
1173
+ * 中部档取下限与上限的中点,与中间那条网格线一一对应。
1174
+ */
1175
+ function trendAxisTicks({ floor, max, metric, currency = 'CNY' }) {
1176
+ const low = Number(floor) || 0
1177
+ // 命中率轴上限恒为 100%:数据最高点往往差一点点(99.6%),按数据取值会让顶档变成
1178
+ // 「99.6%」这种既不好看也不对称的刻度;其余指标上限仍取数据最大值。
1179
+ const high = metric === 'hitRate' ? Math.max(1, low) : Math.max(Number(max) || 0, low)
1180
+ const mid = low + (high - low) / 2
1181
+ const ticks = [
1182
+ { key: 'top', top: 0, text: fmtAxisMetric(high, metric, currency) },
1183
+ { key: 'mid', top: '50%', text: fmtAxisMetric(mid, metric, currency) },
1184
+ ]
1185
+ // 下限为 0 时底部档恒为「0」,与中部档区分度低且挤占高度,省略
1186
+ if (low > 0) ticks.push({ key: 'bottom', top: null, text: fmtAxisMetric(low, metric, currency) })
1187
+ return ticks
1188
+ }
1189
+
1074
1190
  /** 命中率轴下限:命中率普遍在 90% 以上,从 0 起画柱子几乎等高;最低值往下留余量并取整到 5%。 */
1075
1191
  function hitRateFloor(values) {
1076
1192
  const known = values.filter((value) => value !== null)
1077
1193
  if (known.length === 0) return 0
1078
- const min = Math.min(...known)
1194
+ // 单个 0% 日(当次请求全未命中)会把整条轴拽回 0,导致中档落在 49.8% 这种无意义刻度。
1195
+ // 命中率轴的目的是看「差别有多大」,因此按去掉离群低点后的最低值定下限;
1196
+ // 离群点低于下限时柱高归零,与「下限非 0 时柱高按 (v-floor)/span 归一」的既有算法一致。
1197
+ const sorted = [...known].sort((a, b) => a - b)
1198
+ const outliers = sorted.filter((value) => value <= 0)
1199
+ const usable = sorted.filter((value) => value > 0)
1200
+ const min = usable.length > 0 ? usable[0] : (outliers.length > 0 ? 0 : 0)
1079
1201
  const padded = min - Math.max((1 - min) / 2, 0.02)
1080
1202
  const floor = Math.floor(padded * 20 + 1e-9) / 20
1203
+ // 有真实数据时下限不低于 50%:低于此值时柱高差异已无意义,直接回落为 0
1204
+ if (usable.length === 0) return 0
1081
1205
  return floor < 0.5 ? 0 : floor
1082
1206
  }
1083
1207
 
@@ -1099,6 +1223,7 @@ window.__ModuleLoader__.load({
1099
1223
  const costEntries = Object.entries(usage?.totals ?? {})
1100
1224
  const total = usage?.total ?? null
1101
1225
  const dash = '—'
1226
+ // 总费用含订阅估算:金额不加前缀,口径说明只由副行「含估算」承担(REQ-10,修正 D-04 的一半)
1102
1227
  const costNodes = costEntries.map(([currency, value]) => h('span', { key: currency }, fmtMoney(value.cost, currency)))
1103
1228
  const tokensLabel = h('span', null,
1104
1229
  tr('真实 Tokens'),
@@ -1119,7 +1244,7 @@ window.__ModuleLoader__.load({
1119
1244
  label: tr('总费用'),
1120
1245
  main: () => h('div', { style: styles.summaryV },
1121
1246
  pending ? dash : (costNodes.length === 0 ? dash : costNodes)),
1122
- sub: () => (pending ? dash : tr('{n} 个币种', { n: costEntries.length })),
1247
+ sub: () => (pending ? dash : `${tr('{n} 个币种', { n: costEntries.length })} · ${tr('含估算')}`),
1123
1248
  },
1124
1249
  hitRate: {
1125
1250
  label: tr('缓存命中率'),
@@ -1211,16 +1336,25 @@ window.__ModuleLoader__.load({
1211
1336
  // 悬停态:{ center: 柱位百分比, ratio: 柱高百分比, text: 浮层文案 };null 表示未悬停
1212
1337
  const [hover, setHover] = useState(null)
1213
1338
  const points = Array.isArray(series) ? series : []
1214
- const values = points.map((point) => trendValue(point, metric))
1339
+ // 成本指标:两个币种走双轴双柱;>2 仍给出口文案(三轴不可读,明确不做)
1340
+ const currencies = new Set()
1341
+ for (const point of points) for (const currency of Object.keys(point.cost ?? {})) currencies.add(currency)
1342
+ const currencyList = [...currencies]
1343
+ const dual = metric === 'cost' && currencyList.length === 2
1344
+ const primary = currencyList.includes('CNY') ? 'CNY' : (currencyList[0] ?? 'CNY')
1345
+ const secondary = dual ? currencyList.find((code) => code !== primary) : null
1346
+ const costBlocked = metric === 'cost' && currencyList.length > 2
1347
+ const costCurrency = currencyList.length === 1 ? currencyList[0] : primary
1348
+ const costAt = (point, code) => Number(point?.cost?.[code]?.cost) || 0
1349
+ const primaryValues = dual ? points.map((point) => costAt(point, primary)) : null
1350
+ const secondaryValues = dual ? points.map((point) => costAt(point, secondary)) : null
1351
+ const values = dual ? primaryValues : points.map((point) => trendValue(point, metric))
1215
1352
  const known = values.filter((value) => value !== null && value > 0)
1216
1353
  const max = known.length > 0 ? Math.max(...known) : 0
1354
+ const secondaryKnown = dual ? secondaryValues.filter((value) => value > 0) : []
1355
+ const secondaryMax = secondaryKnown.length > 0 ? Math.max(...secondaryKnown) : 0
1217
1356
  const floor = metric === 'hitRate' ? hitRateFloor(values) : 0
1218
1357
  const span = Math.max(max - floor, 1e-9)
1219
- // 多币种时一根柱无法表达,按既定决策禁用成本指标并给出口文案
1220
- const currencies = new Set()
1221
- for (const point of points) for (const currency of Object.keys(point.cost ?? {})) currencies.add(currency)
1222
- const costBlocked = metric === 'cost' && currencies.size > 1
1223
- const costCurrency = currencies.size === 1 ? [...currencies][0] : 'CNY'
1224
1358
  // 换指标 / 换范围后旧的柱位与文案都已失效,直接清空悬停态
1225
1359
  useEffect(() => { setHover(null) }, [metric, series])
1226
1360
  const tickOf = (dayKey) => {
@@ -1229,64 +1363,133 @@ window.__ModuleLoader__.load({
1229
1363
  }
1230
1364
  // 日期刻度按可用宽度抽稀,末点必显
1231
1365
  const step = Math.max(1, Math.ceil(points.length / 6))
1366
+ const hasData = dual ? (known.length > 0 || secondaryKnown.length > 0) : known.length > 0
1232
1367
  const emptyMessage = costBlocked
1233
1368
  ? tr('多币种下成本柱不可用,请切换其他指标')
1234
- : (points.length === 0 || known.length === 0 ? tr('该范围内暂无消耗') : null)
1369
+ : (points.length === 0 || !hasData ? tr('范围内暂无消耗') : null)
1370
+ const axisTicks = emptyMessage === null ? trendAxisTicks({ floor, max, metric, currency: costCurrency }) : []
1371
+ const rightTicks = emptyMessage === null && dual
1372
+ ? trendAxisTicks({ floor: 0, max: secondaryMax, metric, currency: secondary })
1373
+ : []
1374
+ // 轴宽随最长刻度自适应:字号 11px 下中文≈11px、其余≈6.2px,再留 6px 与柱体的间距
1375
+ // 轴列宽度由内容自适应(grid auto 列),这里只保证空态时左侧不塌陷
1376
+ const axisWidth = axisTicks.reduce((widest, tick) => {
1377
+ let px = 0
1378
+ for (const char of tick.text) px += /[\u4e00-\u9fff]/.test(char) ? 11 : 6.2
1379
+ return Math.max(widest, px)
1380
+ }, 0)
1381
+ const axisPad = axisTicks.length === 0 ? 34 : Math.max(28, Math.ceil(axisWidth) + 6)
1382
+ const rightWidth = rightTicks.reduce((widest, tick) => {
1383
+ let px = 0
1384
+ for (const char of tick.text) px += /[\u4e00-\u9fff]/.test(char) ? 11 : 6.2
1385
+ return Math.max(widest, px)
1386
+ }, 0)
1387
+ const rightPad = rightTicks.length === 0 ? 0 : Math.max(28, Math.ceil(rightWidth) + 6)
1235
1388
  return h('div', { 'data-testid': 'token-dash-trend', 'data-td-trend': metric, style: styles.trendBox },
1236
1389
  h('div', { style: styles.trendHead },
1237
1390
  h('b', { 'data-testid': 'token-dash-trend-title', style: styles.trendTitle },
1238
1391
  tr('使用趋势 · {metric}', { metric: tr(METRIC_LABELS[metric]) })),
1239
1392
  h('span', { style: styles.trendHint }, tr(grain === 'month' ? '按月' : '按天')),
1240
1393
  h('span', { style: styles.trendSpacer }),
1394
+ dual
1395
+ ? h('span', { 'data-testid': 'token-dash-trend-legend', style: styles.trendLegend },
1396
+ h('i', { style: { ...styles.trendLegendDot, background: T.accent } }), fmtMoney(0, primary).slice(0, 1) + primary,
1397
+ h('i', { style: { ...styles.trendLegendDot, background: T.series2, marginLeft: 8 } }), fmtMoney(0, secondary).slice(0, 1) + secondary)
1398
+ : null,
1241
1399
  h(Segmented, {
1242
1400
  value: metric, onChange: onMetricChange, label: tr('趋势指标'), kind: 'radiogroup', fit: true,
1243
1401
  options: TREND_METRICS.map(([value, label]) => ({ value, label: tr(label) })),
1244
1402
  })),
1245
- h('div', { style: styles.trendPlot },
1246
- emptyMessage === null ? h('div', {
1247
- style: styles.trendBars,
1248
- onMouseLeave: () => setHover(null),
1249
- },
1250
- ...points.map((point, index) => {
1251
- const value = values[index]
1252
- const ratio = value === null || value <= floor ? 0 : Math.max(0, Math.min(100, ((value - floor) / span) * 100))
1253
- // 悬停即渲染虚线与浮层:不挂原生 title,避免系统 tooltip 的 ~1s 延迟
1254
- return h('span', {
1255
- key: point.dayKey,
1256
- 'data-testid': `token-dash-trend-slot-${point.dayKey}`,
1257
- style: styles.trendSlot,
1258
- onMouseEnter: () => setHover({
1259
- center: ((index + 0.5) / points.length) * 100,
1260
- ratio,
1261
- text: `${point.dayKey} · ${fmtMetric(value, metric, costCurrency)}`,
1262
- }),
1263
- },
1264
- h('span', {
1265
- 'data-testid': `token-dash-trend-bar-${point.dayKey}`,
1266
- style: { ...styles.trendBar, height: `${ratio}%`, background: ratio === 0 ? 'transparent' : T.accent },
1267
- }))
1268
- })) : h('div', { 'data-testid': 'token-dash-trend-empty', style: styles.trendMsg }, emptyMessage),
1269
- emptyMessage === null && hover !== null ? h('span', {
1270
- 'data-testid': 'token-dash-trend-hover-line',
1271
- 'aria-hidden': true,
1272
- style: { ...styles.trendHoverLine, left: `calc(34px + (100% - 34px) * ${hover.center / 100})` },
1273
- }) : null,
1274
- emptyMessage === null && hover !== null ? h('span', {
1275
- 'data-testid': 'token-dash-trend-hover-dot',
1276
- 'aria-hidden': true,
1277
- style: {
1278
- ...styles.trendHoverDot,
1279
- left: `calc(34px + (100% - 34px) * ${hover.center / 100})`,
1280
- bottom: `calc(18px + (132px - 18px) * ${hover.ratio / 100})`,
1403
+ h('div', { style: dual ? { ...styles.trendPlot, ...styles.trendPlotDual } : styles.trendPlot },
1404
+ // 左列:Y 轴(在绘图区之外,与 CC Switch 的 <YAxis> 同构)
1405
+ h('div', { 'data-testid': 'token-dash-trend-axis-col', style: { ...styles.trendAxisCol, minWidth: axisPad } },
1406
+ ...axisTicks.map((tick) => h('span', {
1407
+ key: tick.key,
1408
+ 'data-testid': `token-dash-trend-axis-${tick.key}`,
1409
+ 'aria-hidden': true,
1410
+ style: tick.top === null
1411
+ ? { ...styles.trendAxis, bottom: 18 }
1412
+ : { ...styles.trendAxis, top: tick.top, transform: tick.top === '50%' ? 'translateY(-50%)' : undefined },
1413
+ }, tick.text))),
1414
+ // 右列:绘图区(网格 / 柱 / 悬停层都只在这里活动)
1415
+ h('div', { 'data-testid': 'token-dash-trend-plot-area', style: styles.trendPlotArea },
1416
+ emptyMessage === null ? h('span', { 'aria-hidden': true, style: { ...styles.trendGrid, top: 0 } }) : null,
1417
+ emptyMessage === null ? h('span', { 'aria-hidden': true, style: { ...styles.trendGrid, top: '50%' } }) : null,
1418
+ emptyMessage === null ? h('span', { 'aria-hidden': true, style: { ...styles.trendGrid, bottom: 18 } }) : null,
1419
+ emptyMessage === null ? h('div', {
1420
+ style: styles.trendBars,
1421
+ onMouseLeave: () => setHover(null),
1281
1422
  },
1282
- }) : null,
1283
- emptyMessage === null ? h('div', { style: styles.trendTicks },
1284
- ...points.map((point, index) => h('span', { key: point.dayKey, style: styles.trendTick },
1285
- index % step === 0 || index === points.length - 1 ? tickOf(point.dayKey) : ''))) : null,
1286
- emptyMessage === null && hover !== null ? h('div', {
1287
- 'data-testid': 'token-dash-trend-hover-tip',
1288
- style: { ...styles.trendTip, left: `calc(34px + (100% - 34px) * ${hover.center / 100})` },
1289
- }, hover.text) : null))
1423
+ ...points.map((point, index) => {
1424
+ const value = values[index]
1425
+ const ratio = value === null || value <= floor ? 0 : Math.max(0, Math.min(100, ((value - floor) / span) * 100))
1426
+ const secondaryRatio = dual && secondaryMax > 0
1427
+ ? Math.max(0, Math.min(100, (secondaryValues[index] / secondaryMax) * 100))
1428
+ : 0
1429
+ const hoverText = dual
1430
+ ? `${point.dayKey} · ${fmtMoney(value, primary)} · ${fmtMoney(secondaryValues[index], secondary)}`
1431
+ : `${point.dayKey} · ${fmtMetric(value, metric, costCurrency)}`
1432
+ // 悬停即渲染虚线与浮层:不挂原生 title,避免系统 tooltip 的 ~1s 延迟
1433
+ return h('span', {
1434
+ key: point.dayKey,
1435
+ 'data-testid': `token-dash-trend-slot-${point.dayKey}`,
1436
+ style: dual ? { ...styles.trendSlot, display: 'flex', alignItems: 'flex-end', gap: 1 } : styles.trendSlot,
1437
+ onMouseEnter: () => setHover({
1438
+ center: ((index + 0.5) / points.length) * 100,
1439
+ ratio,
1440
+ text: hoverText,
1441
+ }),
1442
+ },
1443
+ dual
1444
+ ? [
1445
+ h('span', {
1446
+ key: primary,
1447
+ 'data-testid': `token-dash-trend-bar-${point.dayKey}-${primary}`,
1448
+ style: { ...styles.trendBar, flex: '1 1 0', height: `${ratio}%`, background: ratio === 0 ? 'transparent' : T.accent },
1449
+ }),
1450
+ h('span', {
1451
+ key: secondary,
1452
+ 'data-testid': `token-dash-trend-bar-${point.dayKey}-${secondary}`,
1453
+ style: { ...styles.trendBar, flex: '1 1 0', height: `${secondaryRatio}%`, background: secondaryRatio === 0 ? 'transparent' : T.series2 },
1454
+ }),
1455
+ ]
1456
+ : h('span', {
1457
+ 'data-testid': `token-dash-trend-bar-${point.dayKey}`,
1458
+ style: { ...styles.trendBar, height: `${ratio}%`, background: ratio === 0 ? 'transparent' : T.accent },
1459
+ }))
1460
+ })) : h('div', { 'data-testid': 'token-dash-trend-empty', style: styles.trendMsg }, emptyMessage),
1461
+ emptyMessage === null && hover !== null ? h('span', {
1462
+ 'data-testid': 'token-dash-trend-hover-line',
1463
+ 'aria-hidden': true,
1464
+ style: { ...styles.trendHoverLine, left: `${hover.center}%` },
1465
+ }) : null,
1466
+ emptyMessage === null && hover !== null ? h('span', {
1467
+ 'data-testid': 'token-dash-trend-hover-dot',
1468
+ 'aria-hidden': true,
1469
+ style: {
1470
+ ...styles.trendHoverDot,
1471
+ left: `${hover.center}%`,
1472
+ bottom: `calc(18px + (132px - 18px) * ${hover.ratio / 100})`,
1473
+ },
1474
+ }) : null,
1475
+ emptyMessage === null ? h('div', { style: styles.trendTicks },
1476
+ ...points.map((point, index) => h('span', { key: point.dayKey, style: styles.trendTick },
1477
+ index % step === 0 || index === points.length - 1 ? tickOf(point.dayKey) : ''))) : null,
1478
+ emptyMessage === null && hover !== null ? h('div', {
1479
+ 'data-testid': 'token-dash-trend-hover-tip',
1480
+ style: { ...styles.trendTip, left: `${hover.center}%` },
1481
+ }, hover.text) : null),
1482
+ dual
1483
+ ? h('div', { 'data-testid': 'token-dash-trend-axis-col-right', style: { ...styles.trendAxisCol, ...styles.trendAxisColRight, minWidth: rightPad } },
1484
+ ...rightTicks.map((tick) => h('span', {
1485
+ key: tick.key,
1486
+ 'data-testid': `token-dash-trend-axis-right-${tick.key}`,
1487
+ 'aria-hidden': true,
1488
+ style: tick.top === null
1489
+ ? { ...styles.trendAxisRight, bottom: 18 }
1490
+ : { ...styles.trendAxisRight, top: tick.top, transform: tick.top === '50%' ? 'translateY(-50%)' : undefined },
1491
+ }, tick.text)))
1492
+ : null))
1290
1493
  }
1291
1494
 
1292
1495
  function MiniBar({ ratio = 0, neutral = false, stretch = false }) {
@@ -1309,7 +1512,8 @@ window.__ModuleLoader__.load({
1309
1512
 
1310
1513
  /** P3 API 卡底部说明:状态 · 比例,再补余额周期 / 限流 / 渠道用量(渠道值只读)。 */
1311
1514
  function apiCardCaption(provider, { hasBudget, percent, budget }) {
1312
- const parts = [`${hasBudget ? stateOf(percent, API_CRITICAL) : 'unset'} · ${hasBudget ? fmtRatio(budget.percent) : '—'}`]
1515
+ // 状态与比例已由环和百分比表达,说明行只留环上放不下的信息(D-07)
1516
+ const parts = []
1313
1517
  const periodEnd = Number(provider.balance?.periodEnd)
1314
1518
  const period = Number.isFinite(periodEnd) && periodEnd > 0 ? resetParts(periodEnd).absolute : null
1315
1519
  if (period !== null) parts.push(tr('周期至 {time}', { time: period }))
@@ -2050,7 +2254,9 @@ window.__ModuleLoader__.load({
2050
2254
  style: { fontSize: 10, color: T.weak },
2051
2255
  }, tr('按社区表 CNY'))
2052
2256
  : null)),
2053
- h('div', { style: styles.cardCaption }, apiCardCaption(provider, { hasBudget, percent, budget })))
2257
+ apiCardCaption(provider, { hasBudget, percent, budget }) === ''
2258
+ ? null
2259
+ : h('div', { style: styles.cardCaption }, apiCardCaption(provider, { hasBudget, percent, budget })))
2054
2260
  }))
2055
2261
  }
2056
2262
 
@@ -2092,7 +2298,10 @@ window.__ModuleLoader__.load({
2092
2298
  }, windows.map((plan) => h(QuotaCell, {
2093
2299
  key: plan.key, providerId: provider.id, plan, windowKey: plan.key,
2094
2300
  }))),
2095
- h('div', { style: styles.cardCaption }, `${windows.length} ${tr('窗')}`))
2301
+ Number(provider.usage?.monthEstimate) > 0
2302
+ ? h('div', { style: styles.cardCaption },
2303
+ `${tr('本月估算')} ${fmtMoney(provider.usage.monthEstimate, provider.currency)}`)
2304
+ : null)
2096
2305
  }))
2097
2306
  }
2098
2307
 
@@ -2154,6 +2363,7 @@ window.__ModuleLoader__.load({
2154
2363
  setError(false)
2155
2364
  } catch {
2156
2365
  setError(true)
2366
+ reportClientLog('board', 'fetch.error', { path: 'summary' })
2157
2367
  }
2158
2368
  }, [active])
2159
2369
 
@@ -2168,6 +2378,7 @@ window.__ModuleLoader__.load({
2168
2378
  setUsageError(false)
2169
2379
  } catch {
2170
2380
  setUsageError(true)
2381
+ reportClientLog('board', 'fetch.error', { path: 'usage' })
2171
2382
  }
2172
2383
  }, [range])
2173
2384
 
@@ -2209,9 +2420,20 @@ window.__ModuleLoader__.load({
2209
2420
  const models = Array.isArray(usage?.models) ? usage.models : []
2210
2421
  const updated = fmtClock(summary?.updatedAt)
2211
2422
  const degraded = summary?.providersDegraded === true
2423
+ // 无数据时只给一行加载提示,避免重挂载后长时间空白(REQ-07)
2424
+ if (summary === null) {
2425
+ return h('div', { 'data-testid': 'token-dash-board-loading', style: styles.empty }, tr('数据加载中'))
2426
+ }
2212
2427
  const emptyAll = summary !== null && api.length === 0 && subscriptions.length === 0
2428
+ // 空态快照:确认「空白」到底是走了空态分支还是渲染异常
2429
+ if (api.length + subscriptions.length === 0) {
2430
+ reportClientLog('board', 'render.empty', {
2431
+ api: api.length, subscriptions: subscriptions.length,
2432
+ degraded, emptyAll, hasSummary: summary !== null,
2433
+ })
2434
+ }
2213
2435
 
2214
- return h('div', { 'data-testid': 'token-dash-board-scroll', style: styles.boardScroll },
2436
+ return h(BoardBoundary, null, h('div', { 'data-testid': 'token-dash-board-scroll', style: styles.boardScroll },
2215
2437
  h('div', { 'data-testid': 'token-dash-board', style: styles.board },
2216
2438
  h('style', null, TD_CSS),
2217
2439
  h('div', { style: styles.boardHead },
@@ -2262,6 +2484,10 @@ window.__ModuleLoader__.load({
2262
2484
  h('button', { type: 'button', style: styles.button, onClick: () => { void loadUsage() } }, tr('重试'))) : null,
2263
2485
  h(RangeCards, { usage, metric, onMetricChange: setMetric }),
2264
2486
  h(TrendChart, { series: usage?.series, metric, grain: usage?.grain, onMetricChange: setMetric }),
2487
+ // 明细表独立分区标题:柱状图与表格之间需要视觉断点,否则只有一条 1px 线难以区分
2488
+ h('div', { style: styles.detailHead },
2489
+ h('b', { 'data-testid': 'token-dash-detail-title', style: styles.sectionTitle }, tr('模型明细')),
2490
+ h('span', { style: styles.detailHint }, tr('范围按当前时间范围统计'))),
2265
2491
  h('div', { style: styles.detailWrap }, h(DetailTable, {
2266
2492
  rows: models,
2267
2493
  providerNames: Object.fromEntries(providers.map((provider) => [provider.id, provider.name])),
@@ -2278,7 +2504,7 @@ window.__ModuleLoader__.load({
2278
2504
  style: styles.settingsHint,
2279
2505
  }, tr('语言跟随DSH设置;当前仅中文/English,其他语言回退英文')))),
2280
2506
  h('div', { 'data-testid': 'token-dash-settings-capsule', style: styles.capsule },
2281
- h(SettingsRows, { summary, prefs, onSave: savePrefs, onRefresh: refresh, onRefreshSubs: refreshSubs })))))
2507
+ h(SettingsRows, { summary, prefs, onSave: savePrefs, onRefresh: refresh, onRefreshSubs: refreshSubs }))))))
2282
2508
  }
2283
2509
 
2284
2510
  return {