dsh-token-dash 2.1.0 → 2.3.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
@@ -32,7 +32,7 @@ window.__ModuleLoader__.load({
32
32
  '[data-td-pill]:hover{background:color-mix(in srgb,currentColor 8%,transparent)}',
33
33
  '[data-td-btn]:hover{background:color-mix(in srgb,var(--td-accent) 24%,transparent);border-color:color-mix(in srgb,var(--td-accent) 48%,transparent)}',
34
34
  '[data-td-btn]:active{background:color-mix(in srgb,var(--td-accent) 28%,transparent)}',
35
- '@media (max-width:560px){[data-td-cards]{grid-template-columns:minmax(0,1fr)}}',
35
+ '@media (max-width:560px){[data-td-cards]{grid-template-columns:repeat(2,minmax(0,1fr))}[data-td-cards]>*:nth-child(n+3){border-top:1px solid color-mix(in srgb,currentColor 18%,transparent)}[data-td-cards]>*:nth-child(3){border-left:0}}',
36
36
  '[data-td-scroll]{overflow-x:auto}',
37
37
  '[data-td-scroll] > *{min-width:560px}',
38
38
  '[data-testid=token-dash-board-scroll]::-webkit-scrollbar{width:8px}',
@@ -89,7 +89,11 @@ window.__ModuleLoader__.load({
89
89
  '导入中…': 'Importing…', '数据已导出': 'Data exported', '数据导出失败': 'Data export failed',
90
90
  '已导入 {month} 数据': 'Imported {month} data', '导入失败:{reason}': 'Import failed: {reason}',
91
91
  '检查失败': 'Check failed', '未发布': 'Not published', '已是最新': 'Up to date',
92
- '发现 {version}': 'Found {version}', '更新': 'Update', '取消': 'Cancel',
92
+ '发现 {version}': 'Found {version}', '更新': 'Update',
93
+ '重试': 'Retry', '更新中': 'Updating',
94
+ '更新检查失败': 'Update check failed',
95
+ '版本号不合法': 'Invalid version', '该版本未发布': 'Version not published',
96
+ '版本未变化': 'Version unchanged', '未找到 dsh 命令': 'dsh command not found',
93
97
  '复制命令': 'Copy command', '命令已复制': 'Command copied', '复制失败': 'Copy failed',
94
98
  '设置加载中…': 'Loading settings…', '检查更新': 'Check for updates',
95
99
  '更新失败({reason})': 'Update failed ({reason})',
@@ -117,6 +121,16 @@ window.__ModuleLoader__.load({
117
121
  '周期至 {time}': 'Cycle ends {time}', '限流中': 'Rate limited',
118
122
  '渠道用量 {value}': 'Channel usage {value}',
119
123
  '价目表为 CNY,该 provider 按 USD 结算;可用 priceOverrides 补 USD 单价': 'Price table is CNY while this provider bills in USD; add a USD priceOverrides entry',
124
+ '总请求数': 'Total requests', '缓存命中率': 'Cache hit rate',
125
+ '{n} 个币种': '{n} currencies', '范围内全部模型': 'All models in range',
126
+ '创建 {a} · 命中 {b}': 'Created {a} · hit {b}',
127
+ '趋势指标': 'Trend metric', '使用趋势 · {metric}': 'Trend · {metric}',
128
+ '按天': 'Daily', '按月': 'Monthly',
129
+ '与上方卡片同口径': 'Same scope as cards above',
130
+ '命中率': 'Hit rate', '无数据': 'No data',
131
+ '多币种下成本柱不可用,请切换其他指标': 'Cost bars unavailable with multiple currencies; switch metric',
132
+ // 刻度单位:中文用「万 / 亿」,英文用 K / M / B;'万' 同时是语言探针(见 isChinese)
133
+ '万': 'K',
120
134
  }
121
135
  const ZH = Object.fromEntries(Object.keys(EN).map((key) => [key, key]))
122
136
  /** 未定价原因 → 可读文案;未知 reason 回退「未定价」。 */
@@ -261,18 +275,45 @@ window.__ModuleLoader__.load({
261
275
  let updateRequest = null
262
276
  let updateResetTimer = null
263
277
  let autoUpdateChecked = false
278
+ /** 更新检测节奏:UI 稳定 30s 后启动检测(无条件),运行中每 4h 一次。 */
279
+ const UPDATE_STARTUP_DELAY = 30_000
280
+ const UPDATE_INTERVAL_MS = 4 * 60 * 60 * 1000
281
+ /**
282
+ * 启动延迟可被 localStorage 覆盖,仅供 e2e 缩短等待。它只改变「何时开始检测」,
283
+ * 不改变检测内容与判定结果——检测本身仍走真实 registry,因此不构成测试造假。
284
+ */
285
+ const updateStartupDelay = () => {
286
+ try {
287
+ const override = Number(globalThis.localStorage?.getItem(UPDATE_DELAY_KEY))
288
+ if (Number.isFinite(override) && override >= 0) return override
289
+ } catch { /* 隐私模式忽略 */ }
290
+ return UPDATE_STARTUP_DELAY
291
+ }
292
+ /**
293
+ * 更新检测的时间戳存在 localStorage:apply 时看板组件可能还没挂载,
294
+ * 拿不到 /prefs 的结果,用 localStorage 才能保证启动补检不依赖组件渲染顺序。
295
+ */
296
+ const UPDATE_TS_KEY = 'td:updateCheckedAt'
297
+ const UPDATE_DELAY_KEY = 'td:updateStartupDelay'
298
+ const readStoredTs = () => {
299
+ try { return Number(globalThis.localStorage?.getItem(UPDATE_TS_KEY)) || 0 } catch { return 0 }
300
+ }
301
+ const writeStoredTs = (at) => {
302
+ try { globalThis.localStorage?.setItem(UPDATE_TS_KEY, String(at)) } catch { /* 隐私模式忽略 */ }
303
+ }
264
304
 
265
305
  function emitUpdate(patch) {
266
306
  updateSnapshot = { ...updateSnapshot, ...patch }
267
307
  for (const listener of updateListeners) listener()
268
308
  }
269
309
 
270
- function resetUpdateLater() {
310
+ function resetUpdateLater(delayMs = 1600) {
271
311
  if (updateResetTimer !== null) clearTimeout(updateResetTimer)
272
312
  updateResetTimer = setTimeout(() => {
273
313
  updateResetTimer = null
274
- if (updateSnapshot.phase === 'done') emitUpdate({ phase: 'idle', text: null, latest: null, command: null })
275
- }, 1600)
314
+ if (updateSnapshot.phase === 'done') emitUpdate({ phase: 'idle', text: null, latest: null, command: null, errorKind: null })
315
+ else if (updateSnapshot.phase === 'autoError') emitUpdate({ phase: 'idle', text: null, errorKind: null })
316
+ }, delayMs)
276
317
  }
277
318
 
278
319
  function useUpdateSnapshot() {
@@ -292,43 +333,92 @@ window.__ModuleLoader__.load({
292
333
  emitUpdate({ phase: 'checking', text: null, command: null })
293
334
  updateRequest = (async () => {
294
335
  try {
295
- const data = await getJson('/update')
336
+ // 启动检测与手动点击都强刷:命中宿主 5min 缓存就等于没检查
337
+ const data = await getJson('/update?refresh=1')
296
338
  if (data.published === false) {
297
339
  if (manual) { emitUpdate({ phase: 'done', text: tr('未发布') }); resetUpdateLater() }
298
340
  else emitUpdate({ phase: 'idle', text: null })
299
341
  } else if (data.hasUpdate) {
300
- emitUpdate({ phase: manual ? 'confirm' : 'available', latest: data.latest, text: null })
342
+ emitUpdate({ phase: 'available', latest: data.latest, text: null })
343
+ // 手动检测命中更新:直接开始安装,不再弹二次确认
344
+ if (manual) void installUpdateRequest()
301
345
  } else if (manual) {
302
346
  emitUpdate({ phase: 'done', text: tr('已是最新') })
303
347
  resetUpdateLater()
304
348
  } else {
305
349
  emitUpdate({ phase: 'idle', text: null })
306
350
  }
307
- } catch {
308
- if (manual) emitUpdate({ phase: 'error', text: tr('检查失败') })
309
- else emitUpdate({ phase: 'idle', text: null })
351
+ } catch (error) {
352
+ // 失败分级:手动要强提示(按钮转「重试」),自动只给低强度文字且 5s 自动消失。
353
+ // 自动路径不能让按钮变红——用户没做任何操作,页面不该忽然报警。
354
+ const reason = String(error?.message ?? error)
355
+ const auto = !manual
356
+ emitUpdate({
357
+ phase: auto ? 'autoError' : 'error',
358
+ text: auto ? tr('更新检查失败') : tr('检查失败'),
359
+ command: null,
360
+ errorKind: reason,
361
+ })
362
+ // 自动检测失败提示留 5s:够看清,又不长期占位
363
+ if (auto) resetUpdateLater(5000)
310
364
  } finally {
311
365
  updateRequest = null
366
+ markUpdateCheckedAt()
312
367
  }
313
368
  })()
314
369
  return updateRequest
315
370
  }
316
371
 
372
+ /** 检测完成(无论成功失败)都记时间戳:失败也计一次,避免失败后立刻又发请求。 */
373
+ function markUpdateCheckedAt() {
374
+ writeStoredTs(Date.now())
375
+ }
376
+
377
+ /** 调度日志:区分「按周期跳过」与「根本没跑」,否则线上无法判断更新为何不提示。 */
378
+ function logUpdateSchedule(event, meta) {
379
+ try {
380
+ void fetch(`${API}/log`, {
381
+ method: 'POST',
382
+ headers: { 'content-type': 'application/json' },
383
+ body: JSON.stringify({ module: 'update', event, meta }),
384
+ })
385
+ } catch { /* 日志失败不影响调度 */ }
386
+ }
387
+
388
+ /** 安装失败原因 → 用户可读文案;未知原因保留原文而不是吞成 unknown。 */
389
+ const INSTALL_REASON_TEXT = {
390
+ 'invalid-version': '版本号不合法',
391
+ unpublished: '该版本未发布',
392
+ 'version-unchanged': '版本未变化',
393
+ 'cli-not-found': '未找到 dsh 命令',
394
+ }
395
+ const installReasonText = (reason) => INSTALL_REASON_TEXT[reason] ?? (String(reason ?? '').trim() || 'unknown')
396
+
317
397
  async function installUpdateRequest() {
318
398
  if (updateSnapshot.phase === 'installing') return
399
+ const target = updateSnapshot.latest
319
400
  emitUpdate({ phase: 'installing', text: null })
320
401
  try {
321
- const res = await fetch(`${API}/update/install`, { method: 'POST', headers: { accept: 'application/json' } })
402
+ // 把用户看到的版本原样交给宿主,避免宿主重新查 registry 导致装到别的版本
403
+ const res = await fetch(`${API}/update/install`, {
404
+ method: 'POST',
405
+ headers: { accept: 'application/json', 'content-type': 'application/json' },
406
+ body: JSON.stringify(target === null ? {} : { version: target }),
407
+ })
322
408
  const body = await res.json().catch(() => ({}))
323
409
  const data = body?.data
324
- if (body?.ok === true) {
410
+ if (res.ok && body?.ok === true) {
325
411
  emitUpdate({ phase: 'done', text: data?.to ? tr('已更新到 {version},重启 DSH 后生效', { version: data.to }) : tr('已更新,重启 DSH 后生效'), latest: null })
326
412
  resetUpdateLater()
327
- } else {
328
- emitUpdate({ phase: 'error', text: tr('更新失败({reason})', { reason: data?.reason ?? 'unknown' }), command: data?.command ?? null })
413
+ return
329
414
  }
415
+ emitUpdate({
416
+ phase: 'error',
417
+ text: tr('更新失败({reason})', { reason: installReasonText(body?.reason ?? data?.reason) }),
418
+ command: data?.command ?? null,
419
+ })
330
420
  } catch (error) {
331
- emitUpdate({ phase: 'error', text: tr('更新失败({reason})', { reason: error.message }), command: null })
421
+ emitUpdate({ phase: 'error', text: tr('更新失败({reason})', { reason: installReasonText(error?.message) }), command: null })
332
422
  }
333
423
  }
334
424
 
@@ -499,12 +589,17 @@ window.__ModuleLoader__.load({
499
589
  kvLabel: { color: T.muted, whiteSpace: 'nowrap' },
500
590
  kvValue: { color: T.text, fontWeight: 600, fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' },
501
591
  summaryBand: {
502
- display: 'grid', gridTemplateColumns: '1fr 1fr', border: `1px solid ${T.border}`,
592
+ display: 'grid', gridTemplateColumns: 'repeat(4, minmax(0, 1fr))', border: `1px solid ${T.border}`,
503
593
  borderRadius: 8, overflow: 'hidden',
504
594
  },
505
- summaryHalf: { padding: 16, display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', gap: 8, minWidth: 0 },
595
+ summaryHalf: {
596
+ padding: '12px 8px', display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center',
597
+ gap: 4, minWidth: 0, border: 0, background: 'transparent', color: 'inherit', font: 'inherit', cursor: 'pointer',
598
+ transition: 'background .15s',
599
+ },
600
+ summaryHalfOn: { background: `color-mix(in srgb, ${T.accent} 10%, transparent)` },
506
601
  summaryK: { color: T.muted, fontSize: 12 },
507
- summaryV: { display: 'flex', alignItems: 'baseline', justifyContent: 'center', flexWrap: 'wrap', gap: 8, fontSize: 26, fontWeight: 600, lineHeight: '30px', fontVariantNumeric: 'tabular-nums' },
602
+ summaryV: { display: 'flex', alignItems: 'baseline', justifyContent: 'center', flexWrap: 'wrap', gap: 8, fontSize: 22, fontWeight: 600, lineHeight: '26px', fontVariantNumeric: 'tabular-nums' },
508
603
  summarySub: { color: T.weak, fontSize: 11, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: '100%' },
509
604
  rangeBox: {
510
605
  border: `1px solid ${T.border}`, borderRadius: 10, background: T.section,
@@ -513,6 +608,61 @@ window.__ModuleLoader__.load({
513
608
  rangeHead: { display: 'flex', alignItems: 'center', justifyContent: 'flex-start', flexWrap: 'wrap', gap: 16 },
514
609
  rangeMeta: { color: T.weak, fontSize: 11 },
515
610
  detailWrap: { overflowX: 'auto', borderTop: `1px solid ${T.border}`, paddingTop: 12 },
611
+ trendBox: { display: 'flex', flexDirection: 'column', gap: 8, borderTop: `1px solid ${T.border}`, paddingTop: 12, minWidth: 0 },
612
+ trendHead: { display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', minWidth: 0 },
613
+ trendTitle: { fontSize: 13, fontWeight: 600 },
614
+ trendHint: { color: T.weak, fontSize: 11 },
615
+ trendSpacer: { flex: '1 1 auto' },
616
+ trendPlot: { position: 'relative', height: 132, minWidth: 0 },
617
+ 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 },
620
+ // 每根柱独占一个等分槽并在槽内居中:只对柱体设 maxWidth 会让所有柱挤到一侧
621
+ trendSlot: { flex: '1 1 0', minWidth: 1, height: '100%', display: 'flex', alignItems: 'flex-end', justifyContent: 'center' },
622
+ 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 },
624
+ // 虚线要压在柱体之上:柱容器 zIndex 1,指示线 zIndex 4,浮层 5
625
+ trendHoverLine: {
626
+ position: 'absolute', top: 0, bottom: 18, width: 1, marginLeft: -0.5, pointerEvents: 'none',
627
+ borderLeft: `1px dashed ${T.accent}`, opacity: 0.9, zIndex: 4,
628
+ },
629
+ trendHoverDot: {
630
+ position: 'absolute', width: 5, height: 5, marginLeft: -2.5, marginBottom: -2.5, borderRadius: 999,
631
+ background: T.accent, pointerEvents: 'none', zIndex: 5,
632
+ },
633
+ trendTip: {
634
+ position: 'absolute', bottom: 'calc(100% - 12px)', transform: 'translateX(-50%)',
635
+ padding: '3px 8px', borderRadius: 6, whiteSpace: 'nowrap', pointerEvents: 'none', zIndex: 6,
636
+ fontSize: 11, lineHeight: '16px',
637
+ background: T.tooltip, color: T.tooltipText, border: `1px solid ${T.border}`,
638
+ boxShadow: 'var(--dsw-shadow-lv2, 0 4px 12px rgba(0,0,0,.24))',
639
+ },
640
+ trendTick: { flex: '1 1 0', minWidth: 0, textAlign: 'center', whiteSpace: 'nowrap' },
641
+ // UpdateButton:8 态矩阵见 docs/ui-design.md §5.7.1;尺寸与既有 ghost 按钮一致,不改变「版本」行排版
642
+ updateBox: { display: 'inline-flex', alignItems: 'center', gap: 6, minWidth: 0 },
643
+ updateButton: {
644
+ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 4,
645
+ height: 22, minWidth: 22, padding: '0 6px', boxSizing: 'border-box',
646
+ borderRadius: 6, border: `1px solid ${T.border}`, background: 'transparent',
647
+ color: T.text, fontSize: 11, font: 'inherit', cursor: 'pointer',
648
+ transition: 'background .15s, border-color .15s, color .15s',
649
+ },
650
+ updateButtonOn: {
651
+ borderColor: `color-mix(in srgb, ${T.accent} 42%, transparent)`,
652
+ background: `color-mix(in srgb, ${T.accent} 16%, transparent)`,
653
+ color: T.accent, fontWeight: 500,
654
+ },
655
+ updateButtonError: {
656
+ borderColor: `color-mix(in srgb, ${T.over} 42%, transparent)`,
657
+ background: 'transparent', color: T.over,
658
+ },
659
+ updateHint: { fontSize: 11, color: T.accent, fontWeight: 500, whiteSpace: 'nowrap' },
660
+ updateHintError: { fontSize: 11, color: T.over, whiteSpace: 'nowrap' },
661
+ updateDismiss: {
662
+ height: 22, padding: '0 8px', boxSizing: 'border-box', borderRadius: 6, font: 'inherit', fontSize: 11,
663
+ cursor: 'pointer', border: '1px solid transparent', background: 'transparent', color: T.muted,
664
+ },
665
+ trendMsg: { position: 'absolute', inset: '0 0 18px 34px', display: 'flex', alignItems: 'center', justifyContent: 'center', color: T.muted, fontSize: 11 },
516
666
  quotaCards: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 12 },
517
667
  quotaCard: {
518
668
  border: `1px solid ${T.border}`, borderRadius: 8, background: T.section, padding: 16,
@@ -874,28 +1024,269 @@ window.__ModuleLoader__.load({
874
1024
  : `${row.approximate === true ? '≈' : ''}${fmtMoney(row.cost, row.currency)}`)))))
875
1025
  }
876
1026
 
877
- /** P3 两格卡:总费用(多币种同行)与真实 Tokens。 */
878
- function RangeCards({ usage }) {
1027
+ /** P3 趋势指标:唯一顺序源——四格摘要带与右侧胶囊都从这里派生,禁止各自维护顺序。 */
1028
+ const TREND_METRICS = [['tokens', 'Tokens'], ['cost', '费用'], ['hitRate', '命中率'], ['requests', '请求']]
1029
+ const METRIC_LABELS = { tokens: 'Tokens', requests: '请求', cost: '费用', hitRate: '命中率' }
1030
+ /** 词典里 '万' 的英文值是 K:据此判断当前是否中文,不依赖 localeService 暴露语言码。 */
1031
+ const isChinese = () => tr('万') === '万'
1032
+
1033
+ /** 趋势轴刻度:中文「万 / 亿」,英文沿用 fmtTokens 的 K / M / B。 */
1034
+ function fmtTrendTokens(value) {
1035
+ const n = Math.max(0, Number(value) || 0)
1036
+ if (!isChinese()) return fmtTokens(n)
1037
+ if (n >= 1e8) return `${trimZeros((n / 1e8).toFixed(1))}亿`
1038
+ if (n >= 1e4) return `${trimZeros((n / 1e4).toFixed(1))}万`
1039
+ return fmtTokens(n)
1040
+ }
1041
+
1042
+ /** 命中率轴的中间档:留一位小数,避免 96.5% 被压成 96%。 */
1043
+ const fmtHitTick = (value) => `${trimZeros(((Number(value) || 0) * 100).toFixed(1))}%`
1044
+
1045
+ /** 单点取值:命中率缺数据返回 null(不画柱),其余字段缺失按 0。 */
1046
+ function trendValue(point, metric) {
1047
+ if (point === null || point === undefined) return null
1048
+ if (metric === 'hitRate') return point.hitRate === undefined ? null : point.hitRate
1049
+ if (metric === 'cost') return costTotalOf(point)
1050
+ return Number(point[metric]) || 0
1051
+ }
1052
+
1053
+ /** 成本点的标量:多币种时调用方已禁用成本指标,这里只处理单币种;空对象按 0。 */
1054
+ function costTotalOf(point) {
1055
+ const entries = Object.entries(point.cost ?? {})
1056
+ if (entries.length === 0) return 0
1057
+ return Number(entries[0][1]?.cost) || 0
1058
+ }
1059
+
1060
+ function fmtMetric(value, metric, currency = 'CNY') {
1061
+ if (value === null || value === undefined) return tr('无数据')
1062
+ if (metric === 'hitRate') return fmtRatio(value)
1063
+ if (metric === 'cost') return fmtMoney(value, currency)
1064
+ if (metric === 'requests') return String(Math.round(value))
1065
+ return fmtTokens(value)
1066
+ }
1067
+
1068
+ function fmtAxisMetric(value, metric, currency = 'CNY') {
1069
+ if (metric === 'hitRate') return fmtHitTick(value)
1070
+ if (metric === 'cost') return fmtMoney(value, currency)
1071
+ return fmtTrendTokens(value)
1072
+ }
1073
+
1074
+ /** 命中率轴下限:命中率普遍在 90% 以上,从 0 起画柱子几乎等高;最低值往下留余量并取整到 5%。 */
1075
+ function hitRateFloor(values) {
1076
+ const known = values.filter((value) => value !== null)
1077
+ if (known.length === 0) return 0
1078
+ const min = Math.min(...known)
1079
+ const padded = min - Math.max((1 - min) / 2, 0.02)
1080
+ const floor = Math.floor(padded * 20 + 1e-9) / 20
1081
+ return floor < 0.5 ? 0 : floor
1082
+ }
1083
+
1084
+ /** 英文月份短名:用 Intl 而不是手写表,大小写与语言差异交给平台。 */
1085
+ function monthNameOf(dayKey) {
1086
+ const [year, month] = String(dayKey).split('-').map(Number)
1087
+ if (!Number.isFinite(year) || !Number.isFinite(month)) return dayKey
1088
+ try {
1089
+ return new Intl.DateTimeFormat('en', { month: 'short' }).format(new Date(year, month - 1, 1))
1090
+ } catch {
1091
+ return dayKey
1092
+ }
1093
+ }
1094
+
1095
+ /** P3 四格卡:兼作趋势指标选择器;每格 button[role=radio],选中态由 metric 决定。
1096
+ * 渲染顺序固定取自 TREND_METRICS(与右侧指标胶囊同源),禁止在此手写格子顺序。 */
1097
+ function RangeCards({ usage, metric = 'tokens', onMetricChange }) {
879
1098
  const pending = usage === null
880
1099
  const costEntries = Object.entries(usage?.totals ?? {})
881
1100
  const total = usage?.total ?? null
1101
+ const dash = '—'
882
1102
  const costNodes = costEntries.map(([currency, value]) => h('span', { key: currency }, fmtMoney(value.cost, currency)))
883
- return h('div', { 'data-testid': 'token-dash-range-cards', 'data-td-cards': true, style: styles.summaryBand },
884
- h('div', { 'data-testid': 'token-dash-card-cost', style: styles.summaryHalf },
885
- h('div', { style: styles.summaryK }, tr('总费用')),
886
- h('div', { 'data-testid': 'token-dash-cost-values', style: styles.summaryV },
887
- pending ? '—' : (costNodes.length === 0 ? '—' : costNodes))),
888
- h('div', { 'data-testid': 'token-dash-card-tokens', style: styles.summaryHalf },
889
- h('div', { style: styles.summaryK },
890
- `${tr('真实 Tokens')} `,
891
- h(InfoTip, {
892
- label: tr('Tokens 括号说明'),
893
- text: tr('Tokens 括号顺序:输入 / 缓存(读+写)/ 输出'),
894
- variant: 'inline',
895
- }, h(Icon, { name: 'info', size: 11 }))),
896
- h('div', { style: styles.summaryV }, pending ? '—' : fmtTokens(total?.tokens ?? 0)),
897
- h('div', { style: styles.summarySub },
898
- pending ? '—' : `${fmtTokens(total?.input ?? 0)} · ${fmtTokens(total?.cache ?? 0)} · ${fmtTokens(total?.output ?? 0)}`)))
1103
+ const tokensLabel = h('span', null,
1104
+ tr('真实 Tokens'),
1105
+ h(InfoTip, {
1106
+ label: tr('Tokens 括号说明'),
1107
+ text: tr('Tokens 括号顺序:输入 / 缓存(读+写)/ 输出'),
1108
+ variant: 'inline',
1109
+ }, h(Icon, { name: 'info', size: 11 })))
1110
+ /** 一格一渲染器:长标签 / 主值节点 / 副值文案;主值节点沿用历史 testid。 */
1111
+ const CARDS = {
1112
+ tokens: {
1113
+ label: tokensLabel,
1114
+ main: () => h('div', { 'data-testid': 'token-dash-cost-values', style: styles.summaryV },
1115
+ pending ? dash : fmtTokens(total?.tokens ?? 0)),
1116
+ sub: () => (pending ? dash : `${fmtTokens(total?.input ?? 0)} · ${fmtTokens(total?.cache ?? 0)} · ${fmtTokens(total?.output ?? 0)}`),
1117
+ },
1118
+ cost: {
1119
+ label: tr('总费用'),
1120
+ main: () => h('div', { style: styles.summaryV },
1121
+ pending ? dash : (costNodes.length === 0 ? dash : costNodes)),
1122
+ sub: () => (pending ? dash : tr('{n} 个币种', { n: costEntries.length })),
1123
+ },
1124
+ hitRate: {
1125
+ label: tr('缓存命中率'),
1126
+ main: () => h('div', { style: styles.summaryV },
1127
+ pending ? dash : (total?.hitRate === null || total?.hitRate === undefined ? dash : fmtRatio(total.hitRate))),
1128
+ sub: () => (pending ? dash : tr('创建 {a} · 命中 {b}', { a: fmtTokens(total?.cacheWrite ?? 0), b: fmtTokens(total?.cacheRead ?? 0) })),
1129
+ },
1130
+ requests: {
1131
+ label: tr('总请求数'),
1132
+ main: () => h('div', { style: styles.summaryV }, pending ? dash : String(total?.requests ?? 0)),
1133
+ sub: () => tr('范围内全部模型'),
1134
+ },
1135
+ }
1136
+ return h('div', {
1137
+ 'data-testid': 'token-dash-range-cards', 'data-td-cards': true, role: 'radiogroup',
1138
+ 'aria-label': tr('趋势指标'), style: styles.summaryBand,
1139
+ },
1140
+ ...TREND_METRICS.map(([key]) => {
1141
+ const card = CARDS[key]
1142
+ return h('button', {
1143
+ key, type: 'button', role: 'radio', 'aria-pressed': metric === key,
1144
+ 'data-testid': `token-dash-card-${key}`,
1145
+ onClick: () => onMetricChange?.(key),
1146
+ style: { ...styles.summaryHalf, ...(metric === key ? styles.summaryHalfOn : null) },
1147
+ },
1148
+ h('span', { style: { ...styles.summaryK, ...(metric === key ? { color: T.accent } : null) } }, card.label),
1149
+ card.main(),
1150
+ h('div', { style: styles.summarySub }, card.sub()))
1151
+ }))
1152
+ }
1153
+
1154
+ /**
1155
+ * UpdateButton:设置区「版本」行右端的更新控件,8 态矩阵见 docs/ui-design.md §5.7.1。
1156
+ * 有更新时按钮整体转 accent 并常显版本号——不用小圆点,避免「看到点但不知道是什么」。
1157
+ * 失败分级:手动失败按钮转 over 色可重试;自动失败只给低强度文字,不动按钮外观。
1158
+ */
1159
+ function UpdateButton({ update, onCheck, onInstall, onCopyCommand }) {
1160
+ const phase = update?.phase ?? 'idle'
1161
+ const latest = update?.latest ?? null
1162
+ const busy = phase === 'checking' || phase === 'installing'
1163
+ const available = phase === 'available'
1164
+ const manualError = phase === 'error'
1165
+ const autoError = phase === 'autoError'
1166
+ const done = phase === 'done'
1167
+ const iconName = busy ? 'loader' : (manualError ? 'refresh' : (done ? 'check' : 'download'))
1168
+ const label = available
1169
+ ? tr('发现 {version},点击更新', { version: latest })
1170
+ : (manualError ? tr('重试') : tr('检查更新'))
1171
+ const buttonStyle = {
1172
+ ...styles.updateButton,
1173
+ ...(available ? styles.updateButtonOn : null),
1174
+ ...(manualError ? styles.updateButtonError : null),
1175
+ ...(busy ? { opacity: 0.55, cursor: 'default' } : null),
1176
+ }
1177
+ const hintText = done ? (update?.text ?? tr('已是最新')) : (autoError ? tr('更新检查失败') : null)
1178
+ const buttonText = phase === 'installing' ? tr('更新中') : (available ? tr('更新') : null)
1179
+ return h('span', { style: styles.updateBox, 'data-testid': 'token-dash-update-box' },
1180
+ manualError && update?.command ? h('button', { type: 'button', style: styles.updateDismiss, onClick: () => onCopyCommand?.() }, tr('复制命令')) : null,
1181
+ h('button', {
1182
+ type: 'button',
1183
+ 'data-testid': 'token-dash-update',
1184
+ 'data-state': available ? 'available' : (manualError ? 'error' : 'idle'),
1185
+ 'aria-label': label,
1186
+ title: label,
1187
+ disabled: busy,
1188
+ style: buttonStyle,
1189
+ onClick: () => { if (available || manualError) onInstall?.(); else onCheck?.() },
1190
+ },
1191
+ h(Icon, { name: iconName, size: 13 }),
1192
+ buttonText !== null ? h('span', null, buttonText) : null),
1193
+ available && latest !== null
1194
+ ? h('span', { style: styles.updateHint, 'data-testid': 'token-dash-update-latest' }, latest)
1195
+ : null,
1196
+ hintText !== null
1197
+ // 成功/中性提示用 status 播报;失败用 alert,语义不同不复用同一节点
1198
+ ? h('span', {
1199
+ role: autoError ? 'alert' : 'status',
1200
+ 'aria-live': autoError ? 'assertive' : 'polite',
1201
+ style: autoError ? styles.updateHintError : { fontSize: 11, color: T.muted },
1202
+ 'data-testid': 'token-dash-update-hint',
1203
+ }, hintText)
1204
+ : null)
1205
+ }
1206
+
1207
+
1208
+
1209
+ /** P3 趋势柱:连续日/月序列 → flex 柱 + 绝对定位网格线;悬停走原生 title,无交互状态。 */
1210
+ function TrendChart({ series, metric, grain = 'day', onMetricChange }) {
1211
+ // 悬停态:{ center: 柱位百分比, ratio: 柱高百分比, text: 浮层文案 };null 表示未悬停
1212
+ const [hover, setHover] = useState(null)
1213
+ const points = Array.isArray(series) ? series : []
1214
+ const values = points.map((point) => trendValue(point, metric))
1215
+ const known = values.filter((value) => value !== null && value > 0)
1216
+ const max = known.length > 0 ? Math.max(...known) : 0
1217
+ const floor = metric === 'hitRate' ? hitRateFloor(values) : 0
1218
+ 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
+ // 换指标 / 换范围后旧的柱位与文案都已失效,直接清空悬停态
1225
+ useEffect(() => { setHover(null) }, [metric, series])
1226
+ const tickOf = (dayKey) => {
1227
+ if (grain !== 'month') return String(dayKey).slice(5)
1228
+ return isChinese() ? `${String(dayKey).slice(5)}月` : monthNameOf(dayKey)
1229
+ }
1230
+ // 日期刻度按可用宽度抽稀,末点必显
1231
+ const step = Math.max(1, Math.ceil(points.length / 6))
1232
+ const emptyMessage = costBlocked
1233
+ ? tr('多币种下成本柱不可用,请切换其他指标')
1234
+ : (points.length === 0 || known.length === 0 ? tr('该范围内暂无消耗') : null)
1235
+ return h('div', { 'data-testid': 'token-dash-trend', 'data-td-trend': metric, style: styles.trendBox },
1236
+ h('div', { style: styles.trendHead },
1237
+ h('b', { 'data-testid': 'token-dash-trend-title', style: styles.trendTitle },
1238
+ tr('使用趋势 · {metric}', { metric: tr(METRIC_LABELS[metric]) })),
1239
+ h('span', { style: styles.trendHint }, tr(grain === 'month' ? '按月' : '按天')),
1240
+ h('span', { style: styles.trendSpacer }),
1241
+ h(Segmented, {
1242
+ value: metric, onChange: onMetricChange, label: tr('趋势指标'), kind: 'radiogroup', fit: true,
1243
+ options: TREND_METRICS.map(([value, label]) => ({ value, label: tr(label) })),
1244
+ })),
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})`,
1281
+ },
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))
899
1290
  }
900
1291
 
901
1292
  function MiniBar({ ratio = 0, neutral = false, stretch = false }) {
@@ -1477,33 +1868,13 @@ window.__ModuleLoader__.load({
1477
1868
  const version = summary?.version ?? ''
1478
1869
  const catalog = summary?.catalog
1479
1870
 
1480
- let updateControl
1481
- const updateBusy = update.phase === 'checking' || update.phase === 'installing'
1482
- const updateAvailable = update.phase === 'available'
1483
- const updateError = update.phase === 'error'
1484
- if (update.phase === 'confirm') {
1485
- updateControl = h('span', { style: styles.rowStart },
1486
- h('span', { style: styles.muted }, tr('发现 {version}', { version: update.latest })),
1487
- h('button', { type: 'button', style: styles.button, onClick: installUpdate }, tr('更新')),
1488
- h('button', { type: 'button', style: styles.button, onClick: () => emitUpdate({ phase: 'idle', latest: null }) }, tr('取消')))
1489
- } else {
1490
- updateControl = h('span', { style: styles.rowStart },
1491
- updateError && update.command
1492
- ? h('button', { type: 'button', style: styles.button, onClick: copyCommand }, tr('复制命令'))
1493
- : null,
1494
- h(IconButton, {
1495
- label: updateAvailable ? tr('发现 {version},点击更新', { version: update.latest }) : tr('检查更新'),
1496
- testid: 'token-dash-update', disabled: updateBusy,
1497
- dot: updateAvailable || updateError,
1498
- dotColor: updateError ? T.over : T.accent,
1499
- onClick: () => {
1500
- if (updateAvailable) emitUpdate({ phase: 'confirm', latest: update.latest })
1501
- else checkUpdate()
1502
- },
1503
- }, h(Icon, {
1504
- name: updateBusy ? 'loader' : update.phase === 'done' ? 'check' : 'download', size: 13,
1505
- })))
1506
- }
1871
+ const updateControl = h(UpdateButton, {
1872
+ update,
1873
+ onCheck: checkUpdate,
1874
+ onInstall: installUpdate,
1875
+ onCopyCommand: copyCommand,
1876
+ })
1877
+
1507
1878
 
1508
1879
  const statusText = update.text ?? status?.text ?? ''
1509
1880
  return h('div', { 'data-testid': 'token-dash-settings', style: { display: 'grid', minWidth: 0 } },
@@ -1769,6 +2140,7 @@ window.__ModuleLoader__.load({
1769
2140
  const [usage, setUsage] = useState(null)
1770
2141
  const [prefs, setPrefs] = useState(null)
1771
2142
  const [range, setRange] = useState('all')
2143
+ const [metric, setMetric] = useState('tokens')
1772
2144
  const [refreshing, setRefreshing] = useState(false)
1773
2145
  const [error, setError] = useState(false)
1774
2146
  const [usageError, setUsageError] = useState(false)
@@ -1786,7 +2158,7 @@ window.__ModuleLoader__.load({
1786
2158
  }, [active])
1787
2159
 
1788
2160
  const loadPrefs = useCallback(async () => {
1789
- try { setPrefs(await getJson('/prefs')) } catch { /* keep previous */ }
2161
+ try { const loaded = await getJson('/prefs'); updatePrefsCache = loaded; setPrefs(loaded) } catch { /* keep previous */ }
1790
2162
  }, [])
1791
2163
 
1792
2164
  const loadUsage = useCallback(async () => {
@@ -1817,6 +2189,7 @@ window.__ModuleLoader__.load({
1817
2189
  try {
1818
2190
  const saved = await putPrefs({ ...prefsRef.current, ...patch })
1819
2191
  prefsRef.current = saved
2192
+ updatePrefsCache = saved
1820
2193
  setPrefs(saved)
1821
2194
  setSummary((current) => (current === null ? current : mergeBudgets(current, saved)))
1822
2195
  return { ok: true, prefs: saved }
@@ -1887,7 +2260,8 @@ window.__ModuleLoader__.load({
1887
2260
  usageError ? h('div', { style: styles.errorStrip, role: 'alert' },
1888
2261
  h('span', null, tr('范围数据加载失败')),
1889
2262
  h('button', { type: 'button', style: styles.button, onClick: () => { void loadUsage() } }, tr('重试'))) : null,
1890
- h(RangeCards, { usage }),
2263
+ h(RangeCards, { usage, metric, onMetricChange: setMetric }),
2264
+ h(TrendChart, { series: usage?.series, metric, grain: usage?.grain, onMetricChange: setMetric }),
1891
2265
  h('div', { style: styles.detailWrap }, h(DetailTable, {
1892
2266
  rows: models,
1893
2267
  providerNames: Object.fromEntries(providers.map((provider) => [provider.id, provider.name])),
@@ -1921,8 +2295,46 @@ window.__ModuleLoader__.load({
1921
2295
  if (!autoUpdateChecked) {
1922
2296
  autoUpdateChecked = true
1923
2297
  ctx.effect?.(() => {
1924
- const timer = setTimeout(() => { void checkForUpdate({ manual: false }) }, 4000)
1925
- return () => clearTimeout(timer)
2298
+ // 启动补检:UI 稳定 30s 后检测;距上次检测不足 1h 则跳过,
2299
+ // 避免一天重启多次就反复请求 registry。
2300
+ let timer = null
2301
+ let interval = null
2302
+ let cancelled = false
2303
+ const lastAt = readStoredTs
2304
+ // 周期检测与「恢复可见补检」共用同一个到期判定,避免两处各判一次导致连发
2305
+ const isDue = () => Date.now() - lastAt() >= UPDATE_INTERVAL_MS
2306
+ const runAuto = (source) => {
2307
+ if (cancelled) return
2308
+ logUpdateSchedule(source, { elapsed: Date.now() - lastAt() })
2309
+ void checkForUpdate({ manual: false })
2310
+ }
2311
+ logUpdateSchedule('armed', {
2312
+ delay: updateStartupDelay(), lastAt: lastAt(), interval: UPDATE_INTERVAL_MS,
2313
+ hasLocalStorage: typeof globalThis.localStorage !== 'undefined',
2314
+ })
2315
+ timer = setTimeout(() => {
2316
+ timer = null
2317
+ // 启动检测无条件执行:用户要求「每次启动都检查」,不看缓存也不看上次检测时间
2318
+ runAuto('startup.run')
2319
+ interval = setInterval(() => {
2320
+ if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return
2321
+ if (!isDue()) return
2322
+ runAuto('interval.run')
2323
+ }, UPDATE_INTERVAL_MS)
2324
+ }, updateStartupDelay())
2325
+
2326
+ const onVisible = () => {
2327
+ if (typeof document === 'undefined' || document.visibilityState !== 'visible') return
2328
+ if (!isDue()) return
2329
+ runAuto('visible.run')
2330
+ }
2331
+ if (typeof document !== 'undefined') document.addEventListener?.('visibilitychange', onVisible)
2332
+ return () => {
2333
+ cancelled = true
2334
+ if (timer !== null) clearTimeout(timer)
2335
+ if (interval !== null) clearInterval(interval)
2336
+ if (typeof document !== 'undefined') document.removeEventListener?.('visibilitychange', onVisible)
2337
+ }
1926
2338
  }, 'update:startup')
1927
2339
  }
1928
2340
  ctxRef = typeof ctx === 'object' ? ctx : null
@@ -1956,4 +2368,4 @@ window.__ModuleLoader__.load({
1956
2368
  },
1957
2369
  }
1958
2370
  },
1959
- })
2371
+ })