dsh-token-dash 2.5.1 → 2.6.1

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
@@ -46,7 +46,7 @@ window.__ModuleLoader__.load({
46
46
  const SUB_CRITICAL = 90
47
47
  const API_CRITICAL = 100
48
48
  const STALE_MS = 5000
49
-
49
+
50
50
  const RANGES = [
51
51
  ['today', '当天'],
52
52
  ['7d', '近7天'],
@@ -72,8 +72,11 @@ window.__ModuleLoader__.load({
72
72
  const EN = {
73
73
  '当天': 'Today', '近7天': 'Last 7 days', '近30天': 'Last 30 days', '全部': 'All',
74
74
  '30秒': '30s', '1分钟': '1m', '5分钟': '5m',
75
- '社区': 'Community', '内置兜底': 'Built-in fallback',
75
+ '社区': 'Community', '内置兜底': 'Built-in fallback', '离线缓存': 'Offline cache', '内置目录': 'Built-in catalog',
76
76
  '查询失败': 'Query failed', '套餐查询失败': 'Quota query failed',
77
+ '不限量': 'Unlimited', '自动': 'Auto', '手动': 'Manual', '国内': 'China', '国际': 'Global',
78
+ '中国': 'China', '海外': 'Global', '切换区域:中国 / 海外': 'Switch region: China / global',
79
+ '切换区域:自动 / 国内 / 国际': 'Switch region: auto / China / global',
77
80
  '数据加载中': 'Loading data',
78
81
  '含估算': 'incl. estimates',
79
82
  '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.',
@@ -487,6 +490,8 @@ window.__ModuleLoader__.load({
487
490
  overflow: 'auto', zIndex: 9999, padding: 16, borderRadius: 12,
488
491
  background: 'var(--dsw-alias-bg-layer-2, var(--dsh-bg-elevated, #1f1f1f))', color: T.text,
489
492
  border: `1px solid ${T.border}`, boxShadow: '0 12px 40px rgba(0,0,0,.35)', fontSize: 13, outline: 'none',
493
+ // P2 纵向节奏(v3.22,Issue #3):组间 12 / 组内 8,全部走 gap,不再用零散 margin
494
+ display: 'flex', flexDirection: 'column', gap: 12,
490
495
  },
491
496
  header: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, minHeight: 28 },
492
497
  headerTabs: { flex: 1, minWidth: 0 },
@@ -563,6 +568,10 @@ window.__ModuleLoader__.load({
563
568
  summaryValue: { fontSize: 12, fontWeight: 600, fontVariantNumeric: 'tabular-nums' },
564
569
  providerLine: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, minWidth: 0, minHeight: 24 },
565
570
  providerChip: { color: T.muted, fontSize: 12, whiteSpace: 'nowrap' },
571
+ // P2 订阅块 / 范围组(v3.22,Issue #3):组内 8;窗口三列间距 12
572
+ p2SubBlock: { display: 'grid', gap: 8, minWidth: 0 },
573
+ p2RangeGroup: { display: 'grid', gap: 8, minWidth: 0 },
574
+ p2Windows: { display: 'grid', gridTemplateColumns: 'repeat(3, minmax(0, 1fr))', gap: 12, minWidth: 0 },
566
575
  staleBadge: { color: T.weak, fontSize: 11, whiteSpace: 'nowrap', border: `1px solid ${T.border}`, borderRadius: 4, padding: '0 4px' },
567
576
  windowRow: { display: 'grid', gridTemplateColumns: 'auto 1fr 1fr 1fr', columnGap: 8, alignItems: 'center', minHeight: 24, fontSize: 13 },
568
577
  windowKey: { display: 'inline-flex', alignItems: 'center', gap: 6, whiteSpace: 'nowrap' },
@@ -571,7 +580,7 @@ window.__ModuleLoader__.load({
571
580
  tableRow: { display: 'grid', columnGap: 8, alignItems: 'baseline', minHeight: 28, padding: '4px 0', fontSize: 13, borderBottom: '1px solid color-mix(in srgb, currentColor 6%, transparent)' },
572
581
  cellNum: { fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' },
573
582
  cellName: { minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
574
- footer: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, marginTop: 12, minHeight: 22 },
583
+ footer: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, minHeight: 22 },
575
584
  boardScroll: {
576
585
  width: '100%', height: '100%', overflowY: 'auto', overflowX: 'hidden',
577
586
  boxSizing: 'border-box', overscrollBehavior: 'contain',
@@ -633,7 +642,28 @@ window.__ModuleLoader__.load({
633
642
  },
634
643
  apiCardHead: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, minWidth: 0 },
635
644
  apiCardName: { fontSize: 13, fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
636
- apiChip: { color: T.muted, fontSize: 11, whiteSpace: 'nowrap' },
645
+ // 区域胶囊(v3.25 / Issue #1):两段单选,选中段实心 accent;单区另一段置灰
646
+ regionCapsule: {
647
+ display: 'inline-flex', alignItems: 'center', gap: 4, height: 22, padding: 2,
648
+ boxSizing: 'border-box', borderRadius: 999, flex: '0 0 auto',
649
+ border: `1px solid color-mix(in srgb, ${T.accent} 32%, transparent)`,
650
+ background: `color-mix(in srgb, ${T.accent} 10%, transparent)`,
651
+ },
652
+ regionSegment: {
653
+ height: 18, padding: '0 10px', boxSizing: 'border-box', borderRadius: 999, border: 0,
654
+ background: 'transparent', color: T.muted, font: 'inherit', fontSize: 11, fontWeight: 600,
655
+ lineHeight: '18px', cursor: 'pointer', whiteSpace: 'nowrap',
656
+ },
657
+ regionSegmentActive: {
658
+ height: 18, padding: '0 10px', boxSizing: 'border-box', borderRadius: 999, border: 0,
659
+ background: T.accent, color: '#0f1115', font: 'inherit', fontSize: 11, fontWeight: 600,
660
+ lineHeight: '18px', cursor: 'default', whiteSpace: 'nowrap',
661
+ },
662
+ regionSegmentDisabled: {
663
+ height: 18, padding: '0 10px', boxSizing: 'border-box', borderRadius: 999, border: 0,
664
+ background: 'transparent', color: T.weak, font: 'inherit', fontSize: 11, fontWeight: 600,
665
+ lineHeight: '18px', cursor: 'default', whiteSpace: 'nowrap',
666
+ },
637
667
  apiGaugeWrap: { display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8 },
638
668
  budgetLabel: { color: T.muted, fontSize: 11 },
639
669
  budgetInputWrap: {
@@ -1396,9 +1426,10 @@ window.__ModuleLoader__.load({
1396
1426
 
1397
1427
 
1398
1428
 
1399
- /** P3 趋势柱:连续日/月序列 → flex 柱 + 绝对定位网格线;悬停走原生 title,无交互状态。 */
1429
+ /** P3 趋势柱:连续日/月序列 → flex 柱 + 绝对定位网格线;悬停按槽 / 柱命中。 */
1400
1430
  function TrendChart({ series, metric, grain = 'day', onMetricChange }) {
1401
1431
  // 悬停态:{ center: 柱位百分比, ratio: 柱高百分比, text: 浮层文案 };null 表示未悬停
1432
+ // 双币时 center / ratio 来自鼠标所指的那根柱,而不是日期槽(Issue #2)
1402
1433
  const [hover, setHover] = useState(null)
1403
1434
  const points = Array.isArray(series) ? series : []
1404
1435
  // 成本指标:两个币种走双轴双柱;>2 仍给出口文案(三轴不可读,明确不做)
@@ -1432,6 +1463,34 @@ window.__ModuleLoader__.load({
1432
1463
  const emptyMessage = costBlocked
1433
1464
  ? tr('多币种下成本柱不可用,请切换其他指标')
1434
1465
  : (points.length === 0 || !hasData ? tr('范围内暂无消耗') : null)
1466
+ // 双币按「最近柱」命中(Issue #2):槽级 mousemove,指针 x 到哪根柱中心更近就选哪根。
1467
+ // 整列(gap / 短柱上方 / 零高柱 / 底部)都可命中,不再回落槽中心 + 主序列。
1468
+ const hoverAtDualSlot = (event, index, ratios, text) => {
1469
+ const slot = event.currentTarget
1470
+ const nodes = [...slot.querySelectorAll('[data-td-series]')]
1471
+ if (nodes.length === 0) return
1472
+ const plotRect = slot.closest('[data-testid="token-dash-trend-plot-area"]')?.getBoundingClientRect()
1473
+ let chosen = nodes[0]
1474
+ let best = Infinity
1475
+ for (const node of nodes) {
1476
+ const rect = node.getBoundingClientRect()
1477
+ const distance = Math.abs(event.clientX - (rect.left + rect.width / 2))
1478
+ if (distance < best) {
1479
+ best = distance
1480
+ chosen = node
1481
+ }
1482
+ }
1483
+ const series = chosen.dataset.tdSeries
1484
+ const rect = chosen.getBoundingClientRect()
1485
+ const center = plotRect === undefined || plotRect.width <= 0
1486
+ ? ((index + 0.5) / points.length) * 100
1487
+ : Math.max(0, Math.min(100, ((rect.left + rect.width / 2 - plotRect.left) / plotRect.width) * 100))
1488
+ const ratio = series === secondary ? ratios.secondary : ratios.primary
1489
+ // 同一根柱内移动不重复 setState;换柱才更新
1490
+ setHover((current) => current !== null && current.index === index && current.series === series
1491
+ ? current
1492
+ : { center, ratio, text, series, index })
1493
+ }
1435
1494
  const axisTicks = emptyMessage === null ? trendAxisTicks({ floor, max, metric, currency: costCurrency }) : []
1436
1495
  const rightTicks = emptyMessage === null && dual
1437
1496
  ? trendAxisTicks({ floor: 0, max: secondaryMax, metric, currency: secondary })
@@ -1499,22 +1558,29 @@ window.__ModuleLoader__.load({
1499
1558
  key: point.dayKey,
1500
1559
  'data-testid': `token-dash-trend-slot-${point.dayKey}`,
1501
1560
  style: dual ? { ...styles.trendSlot, display: 'flex', alignItems: 'flex-end', gap: 1 } : styles.trendSlot,
1502
- onMouseEnter: () => setHover({
1503
- center: ((index + 0.5) / points.length) * 100,
1504
- ratio,
1505
- text: hoverText,
1506
- }),
1561
+ onMouseEnter: dual
1562
+ ? (event) => hoverAtDualSlot(event, index, { primary: ratio, secondary: secondaryRatio }, hoverText)
1563
+ : () => setHover({
1564
+ center: ((index + 0.5) / points.length) * 100,
1565
+ ratio,
1566
+ text: hoverText,
1567
+ }),
1568
+ onMouseMove: dual
1569
+ ? (event) => hoverAtDualSlot(event, index, { primary: ratio, secondary: secondaryRatio }, hoverText)
1570
+ : undefined,
1507
1571
  },
1508
1572
  dual
1509
1573
  ? [
1510
1574
  h('span', {
1511
1575
  key: primary,
1512
1576
  'data-testid': `token-dash-trend-bar-${point.dayKey}-${primary}`,
1577
+ 'data-td-series': primary,
1513
1578
  style: { ...styles.trendBar, flex: '1 1 0', height: `${ratio}%`, background: ratio === 0 ? 'transparent' : T.accent },
1514
1579
  }),
1515
1580
  h('span', {
1516
1581
  key: secondary,
1517
1582
  'data-testid': `token-dash-trend-bar-${point.dayKey}-${secondary}`,
1583
+ 'data-td-series': secondary,
1518
1584
  style: { ...styles.trendBar, flex: '1 1 0', height: `${secondaryRatio}%`, background: secondaryRatio === 0 ? 'transparent' : T.series2 },
1519
1585
  }),
1520
1586
  ]
@@ -1590,16 +1656,20 @@ window.__ModuleLoader__.load({
1590
1656
 
1591
1657
  function windowLabel(key) { return { '5h': '5h', week: tr('周'), month: tr('月') }[key] ?? key }
1592
1658
 
1659
+ function subscriptionEmptyText(provider) {
1660
+ return provider.quotaError?.kind === 'unlimited' ? tr('不限量') : tr('套餐查询失败')
1661
+ }
1662
+
1593
1663
  function subscriptionText(provider) {
1594
1664
  const windows = Array.isArray(provider.windows) ? provider.windows : []
1595
- if (windows.length === 0) return tr('套餐查询失败')
1665
+ if (windows.length === 0) return subscriptionEmptyText(provider)
1596
1666
  return windows.slice(0, 3).map((plan) => `${windowLabel(plan.key)} ${fmtPercent(plan.usedPercent)}`).join(' · ')
1597
1667
  }
1598
1668
 
1599
1669
  /** P1 订阅窗口:复用 P0 的 SubWindow(横排、不显示时间),最多三窗。 */
1600
1670
  function subscriptionNodes(provider) {
1601
1671
  const windows = Array.isArray(provider.windows) ? provider.windows : []
1602
- if (windows.length === 0) return [h('span', { key: 'fail', style: styles.muted }, tr('套餐查询失败'))]
1672
+ if (windows.length === 0) return [h('span', { key: 'fail', style: styles.muted }, subscriptionEmptyText(provider))]
1603
1673
  const nodes = []
1604
1674
  for (const [index, plan] of windows.slice(0, 3).entries()) {
1605
1675
  // 分隔符用 U+30FB(片假名中点)且**不带两侧空格**(Issue #1):
@@ -1830,7 +1900,7 @@ window.__ModuleLoader__.load({
1830
1900
  * headerActions 不再需要 marginInlineEnd 负偏移——那是为抵消 ⓘ 的视觉留白。
1831
1901
  */
1832
1902
  function PanelHeader({ onRefresh, refreshing, onClose, stale = false, failed = false }) {
1833
- return h('div', { style: styles.header },
1903
+ return h('div', { 'data-testid': 'token-dash-panel-header', style: styles.header },
1834
1904
  h('b', { style: styles.title }, tr('当前模型')),
1835
1905
  h('div', { style: styles.headerActions },
1836
1906
  // 任一接口失败时,刷新位换成带文字的「重试」:全屏只保留这一个入口,
@@ -1928,14 +1998,16 @@ window.__ModuleLoader__.load({
1928
1998
  current.kind === 'subscription'
1929
1999
  ? h(P2Windows, { provider: current })
1930
2000
  : h(P2Summary, { provider: current, summary }),
1931
- h('div', { style: { marginTop: 12, ...styles.rangeCapsule } }, h(Segmented, {
1932
- value: range, onChange: setRange, label: tr('时间范围'),
1933
- options: RANGES.map(([value, label]) => ({ value, label: tr(label) })),
1934
- })),
1935
- usage === null && usageLoading
1936
- ? h('div', { style: styles.empty }, tr('范围数据加载中…'))
1937
- : h(TokenTable, { rows }),
1938
- h('div', { style: styles.footer },
2001
+ // 范围组(v3.22):胶囊 + 表格组内 8,外层由 panel 的 gap 12 分段
2002
+ h('div', { 'data-testid': 'token-dash-p2-range-group', style: styles.p2RangeGroup },
2003
+ h('div', { style: styles.rangeCapsule }, h(Segmented, {
2004
+ value: range, onChange: setRange, label: tr('时间范围'),
2005
+ options: RANGES.map(([value, label]) => ({ value, label: tr(label) })),
2006
+ })),
2007
+ usage === null && usageLoading
2008
+ ? h('div', { style: styles.empty }, tr('范围数据加载中…'))
2009
+ : h(TokenTable, { rows })),
2010
+ h('div', { 'data-testid': 'token-dash-p2-footer', style: styles.footer },
1939
2011
  h('span', { 'data-testid': 'token-dash-updated', style: { color: T.weak, fontSize: 12 } },
1940
2012
  updated === null ? '' : tr('更新于 {time}', { time: updated })),
1941
2013
  canOpen
@@ -1985,7 +2057,7 @@ window.__ModuleLoader__.load({
1985
2057
  const percent = hasBudget ? Number(budget.percent) * 100 : null
1986
2058
  const balance = balanceText(provider, summary?.showBalance)
1987
2059
  return h(React.Fragment, null,
1988
- h('div', { style: styles.providerLine },
2060
+ h('div', { 'data-testid': 'token-dash-p2-provider', style: styles.providerLine },
1989
2061
  h('span', { style: styles.title, title: provider.name }, provider.name),
1990
2062
  h('span', { style: { display: 'inline-flex', alignItems: 'center', gap: 6, minWidth: 0 } },
1991
2063
  h(StaleBadge, { provider }),
@@ -2090,18 +2162,17 @@ window.__ModuleLoader__.load({
2090
2162
  }
2091
2163
  function P2Windows({ provider }) {
2092
2164
  const windows = Array.isArray(provider.windows) ? provider.windows : []
2093
- return h(React.Fragment, null,
2094
- h('div', { style: styles.providerLine },
2165
+ // 订阅块(v3.22):供应商行 + 窗口行组内 8;窗口三列间距 12。
2166
+ // 倒计时已是正常流,不再需要旧的 paddingBottom 补偿(Issue #3)
2167
+ return h('div', { 'data-testid': 'token-dash-p2-sub-block', style: styles.p2SubBlock },
2168
+ h('div', { 'data-testid': 'token-dash-p2-provider', style: styles.providerLine },
2095
2169
  h('span', { style: styles.title, title: provider.name }, provider.name),
2096
2170
  h('span', { style: { display: 'inline-flex', alignItems: 'center', gap: 6, minWidth: 0 } },
2097
2171
  h(StaleBadge, { provider }),
2098
2172
  h('span', { style: styles.providerChip }, `[ ${tr('订阅')} ]`))),
2099
2173
  windows.length === 0
2100
- ? h('div', { style: styles.empty }, tr('套餐查询失败'))
2101
- // 倒计时是绝对定位(锚在圆环下方),故用 grid 分列 + 底部内边距容纳第二行
2102
- : h('div', {
2103
- style: { display: 'grid', gridTemplateColumns: 'repeat(3, minmax(0, 1fr))', gap: 12, paddingBottom: 15 },
2104
- }, windows.map((plan, index) => h(WindowRow, {
2174
+ ? h('div', { style: styles.empty }, subscriptionEmptyText(provider))
2175
+ : h('div', { 'data-testid': 'token-dash-p2-windows', style: styles.p2Windows }, windows.map((plan, index) => h(WindowRow, {
2105
2176
  key: plan.key,
2106
2177
  providerId: provider.id,
2107
2178
  plan,
@@ -2278,7 +2349,19 @@ window.__ModuleLoader__.load({
2278
2349
  `v${version} · ${tr('价格表')} ${formatCatalogTime(catalog?.updatedAt)}`,
2279
2350
  catalog?.url
2280
2351
  ? h('a', { href: catalog.url, target: '_blank', rel: 'noopener', style: { ...styles.link, color: T.muted, marginLeft: 4 } }, tr('社区'))
2281
- : h('span', { style: { marginLeft: 4 } }, sourceLabel(catalog?.source))),
2352
+ : h('span', { style: { marginLeft: 4 } }, sourceLabel(catalog?.source)),
2353
+ // 离线 / 内置时把来源说清楚:此刻的估算用哪份目录算的,用户一眼能分辨
2354
+ catalog?.degraded === true
2355
+ ? h('span', {
2356
+ 'data-testid': 'token-dash-catalog-degraded',
2357
+ title: catalog?.reason === 'offline-cache'
2358
+ ? tr('离线启动,使用上一次成功拉取的价目表')
2359
+ : tr('未能联网,使用内置目录,部分模型会显示未定价'),
2360
+ style: { marginLeft: 4, color: T.weak },
2361
+ }, catalog?.reason === 'offline-cache'
2362
+ ? `· ${tr('离线缓存')}${catalog?.fetchedAt ? ` ${formatCatalogTime(catalog.fetchedAt)}` : ''}`
2363
+ : `· ${tr('内置目录')}`)
2364
+ : null),
2282
2365
  h('span', { style: { flex: 1 } }),
2283
2366
  h('span', {
2284
2367
  'data-testid': 'token-dash-settings-status', role: 'status', 'aria-live': 'polite',
@@ -2338,7 +2421,7 @@ window.__ModuleLoader__.load({
2338
2421
  },
2339
2422
  h('div', { style: styles.apiCardHead },
2340
2423
  h('span', { style: styles.apiCardName, title: provider.name }, provider.name),
2341
- h('span', { style: styles.apiChip }, `[ ${tr('API 用量')} ]`)),
2424
+ h(RegionChip, { provider, prefs, onSave })),
2342
2425
  h('div', { style: styles.apiGaugeWrap },
2343
2426
  h(QuotaGauge, {
2344
2427
  label: tr('已用'), percent,
@@ -2437,8 +2520,38 @@ window.__ModuleLoader__.load({
2437
2520
  })
2438
2521
  }
2439
2522
 
2523
+ const REGION_TEXT = { cn: '中国', global: '海外' }
2524
+ const REGION_KEYS = ['cn', 'global']
2525
+ /** P3 卡头区域胶囊(v3.25 / Issue #1):两段单选;无区域能力不渲染,单区另一段置灰。 */
2526
+ function RegionChip({ provider, prefs, onSave }) {
2527
+ const regions = Array.isArray(provider.regions) ? provider.regions : []
2528
+ if (regions.length === 0) return null
2529
+ const current = prefs?.providerRegion?.[provider.id] ?? provider.region ?? regions[0]
2530
+ const pick = (key) => {
2531
+ if (key === current || !regions.includes(key)) return
2532
+ void onSave({ providerRegion: { ...(prefs?.providerRegion ?? {}), [provider.id]: key } })
2533
+ }
2534
+ return h('span', {
2535
+ 'data-testid': `token-dash-region-${provider.id}`,
2536
+ title: tr('切换区域:中国 / 海外'),
2537
+ style: styles.regionCapsule,
2538
+ }, ...REGION_KEYS.map((key) => {
2539
+ const active = key === current
2540
+ const disabled = !regions.includes(key)
2541
+ return h('button', {
2542
+ key,
2543
+ type: 'button',
2544
+ 'data-testid': `token-dash-region-${provider.id}-${key}`,
2545
+ 'aria-pressed': active ? 'true' : 'false',
2546
+ disabled,
2547
+ style: active ? styles.regionSegmentActive : disabled ? styles.regionSegmentDisabled : styles.regionSegment,
2548
+ onClick: () => pick(key),
2549
+ }, tr(REGION_TEXT[key]))
2550
+ }))
2551
+ }
2552
+
2440
2553
  /** P3 订阅卡:每 provider 一张,窗口按实际数量一排等分。 */
2441
- function QuotaTable({ providers }) {
2554
+ function QuotaTable({ providers, prefs, onSave }) {
2442
2555
  return h('div', { 'data-testid': 'token-dash-quota-table', style: styles.quotaCards },
2443
2556
  ...providers.map((provider) => {
2444
2557
  const windows = Array.isArray(provider.windows) ? provider.windows : []
@@ -2447,9 +2560,9 @@ window.__ModuleLoader__.load({
2447
2560
  },
2448
2561
  h('div', { style: styles.apiCardHead },
2449
2562
  h('span', { style: styles.apiCardName, title: provider.name }, provider.name),
2450
- h('span', { style: styles.apiChip }, `[ ${tr('订阅')} ]`)),
2563
+ h(RegionChip, { provider, prefs, onSave })),
2451
2564
  windows.length === 0
2452
- ? h('div', { style: styles.empty }, tr('套餐查询失败'))
2565
+ ? h('div', { style: styles.empty }, subscriptionEmptyText(provider))
2453
2566
  : h('div', {
2454
2567
  style: { ...styles.quotaWindows, gridTemplateColumns: `repeat(${windows.length}, minmax(0,1fr))` },
2455
2568
  }, windows.map((plan) => h(QuotaCell, {
@@ -2622,7 +2735,7 @@ window.__ModuleLoader__.load({
2622
2735
  label: tr('重新检测订阅配额'), testid: 'token-dash-board-rescan',
2623
2736
  disabled: refreshing, onClick: () => { void refreshSubs() },
2624
2737
  }, h(Icon, { name: refreshing ? 'loader' : 'refresh', size: 13 }))),
2625
- h(QuotaTable, { providers: subscriptions })) : null,
2738
+ h(QuotaTable, { providers: subscriptions, prefs, onSave: savePrefs })) : null,
2626
2739
  emptyAll ? h('div', { 'data-testid': 'token-dash-board-empty', style: styles.cardBox },
2627
2740
  h('div', { style: styles.empty }, degraded ? tr('供应商探测失败') : tr('未检测到已配置供应商')),
2628
2741
  degraded ? h('button', { type: 'button', style: styles.button, onClick: () => { void refresh() } }, tr('重试')) : null) : null,
package/index.js CHANGED
@@ -7,11 +7,11 @@ import { spawn } from 'node:child_process'
7
7
  import { dirname, join } from 'node:path'
8
8
  import { buildSummary, buildUsage, emptyState, localMonthKey, num, repriceState, repriceUnpriced, resolveProviderKind, stampProviderKinds } from './src/core.js'
9
9
  import { ingest, backfill } from './src/collect.js'
10
- import { REFRESH_OPTIONS, createFlusher, dataDir, loadPrefs, loadState, logsDir, normalizeCurrencyMap, normalizeOverrides, recoverState, resolveHome, saveJson, saveMonths } from './src/store.js'
10
+ import { CATALOG_CACHE_NAMES, REFRESH_OPTIONS, createFlusher, dataDir, loadCatalogCache, loadPrefs, loadState, logsDir, normalizeCurrencyMap, normalizeOverrides, normalizeRegionMap, recoverState, resolveHome, saveCatalogCache, saveJson, saveMonths } from './src/store.js'
11
11
  import { buildExport, mergeImportDays, validateBundle } from './src/backup.js'
12
- import { logAdapterEvents, logAdapterFailures, missSignature, readProviders, readSubscriptions } from './src/adapters.js'
12
+ import { logAdapterEvents, logAdapterFailures, missSignature, readProviders, readSubscriptions, resetRegionPins } from './src/adapters.js'
13
13
  import { PROVIDER_SOURCES } from './src/quota-sources.js'
14
- import { catalogInfo, configurePricing, loadCommunityPricing, loadRouterPricing } from './src/pricing.js'
14
+ import { catalogInfo, configurePricing, loadCommunityPricing, loadRouterPricing, restoreCatalogCache } from './src/pricing.js'
15
15
  import { providerCurrency } from './src/providers.js'
16
16
  import { clearLog, createLogger, exportLog, pruneLogs } from './src/diagnostics.js'
17
17
  import { isNewer, sameBase } from './src/version.js'
@@ -170,6 +170,7 @@ function normalizePrefs(input, base) {
170
170
  showBalance: base.showBalance,
171
171
  priceOverrides: normalizeOverrides(base.priceOverrides),
172
172
  providerCurrency: normalizeCurrencyMap(base.providerCurrency),
173
+ providerRegion: normalizeRegionMap(base.providerRegion),
173
174
  }
174
175
  if (input?.budgets !== undefined) {
175
176
  if (input.budgets === null || typeof input.budgets !== 'object') throw new Error('invalid-budgets')
@@ -201,6 +202,9 @@ function normalizePrefs(input, base) {
201
202
  prefs.providerCurrency = input?.providerCurrency !== undefined
202
203
  ? normalizeCurrencyMap(input.providerCurrency)
203
204
  : normalizeCurrencyMap(base.providerCurrency)
205
+ prefs.providerRegion = input?.providerRegion !== undefined
206
+ ? normalizeRegionMap(input.providerRegion)
207
+ : normalizeRegionMap(base.providerRegion)
204
208
  return prefs
205
209
  }
206
210
 
@@ -254,7 +258,14 @@ export function apply(ctx) {
254
258
  const currencyOf = (id) => prefs?.providerCurrency?.[id] ?? metaOf(id)?.currency ?? providerCurrency(id)
255
259
  let pricingConfigLogged = ''
256
260
  const applyPricingConfig = () => {
257
- configurePricing({ overrides: prefs?.priceOverrides ?? {}, currencyOf })
261
+ configurePricing({
262
+ overrides: prefs?.priceOverrides ?? {},
263
+ currencyOf,
264
+ // 只有联网成功路径会调用;离线启动不覆盖上一次成功的缓存
265
+ persistCatalog: (kind, payload) => {
266
+ void saveCatalogCache(dir, kind, payload, logger).catch(() => {})
267
+ },
268
+ })
258
269
  const overrides = Object.keys(prefs?.priceOverrides ?? {}).length
259
270
  const currencies = Object.keys(prefs?.providerCurrency ?? {}).length
260
271
  const signature = `${overrides}/${currencies}`
@@ -295,16 +306,42 @@ export function apply(ctx) {
295
306
  }
296
307
  }, 'dsh-token-dash: store')
297
308
 
298
- // 价格表必须先于重算就绪:社区表加载失败时回退已对齐官方价的内置目录。
309
+ // 价格表必须先于重算就绪。三级回退:本次联网 → 上次成功的盘上缓存 → 内置目录。
299
310
  const pricingReady = ready.then(async () => {
311
+ // 先读缓存,离线重启也能按上一次成功的目录估算,而不是直接跌回 14 个内置模型
312
+ try {
313
+ const [community, router] = await Promise.all([
314
+ loadCatalogCache(dir, 'community', logger),
315
+ loadCatalogCache(dir, 'router', logger),
316
+ ])
317
+ const restored = restoreCatalogCache({ community, router })
318
+ logger.info('pricing', 'catalog.cache.restore', {
319
+ community: community !== null,
320
+ router: router !== null,
321
+ restored,
322
+ fetchedAt: community?.fetchedAt ?? null,
323
+ })
324
+ } catch (error) {
325
+ logger.warn('pricing', 'catalog.cache.fail', { message: String(error?.message ?? error) })
326
+ }
327
+ applyPricingConfig()
300
328
  await Promise.allSettled([
301
329
  loadCommunityPricing()
302
330
  .then((info) => logger.info('pricing', 'catalog.loaded', info))
303
331
  .catch((error) => logger.warn('pricing', 'catalog.fail', { message: String(error?.message ?? error) })),
304
332
  loadRouterPricing()
305
- .then((ok) => logger.info('pricing', 'router.loaded', { ok }))
333
+ .then((ok) => {
334
+ logger.info('pricing', 'router.loaded', { ok })
335
+ // 联网失败不丢上一次成功的表:缓存已在 restore 阶段载入
336
+ if (!ok) logger.warn('pricing', 'router.degraded', { origin: catalogInfo().routerOrigin })
337
+ })
306
338
  .catch((error) => logger.warn('pricing', 'router.fail', { message: String(error?.message ?? error) })),
307
339
  ])
340
+ const info = catalogInfo()
341
+ logger.info('pricing', 'catalog.ready', {
342
+ source: info.source, origin: info.origin, models: info.models,
343
+ routerModels: info.routerModels, degraded: info.degraded, reason: info.reason,
344
+ })
308
345
  applyPricingConfig()
309
346
  })
310
347
 
@@ -722,15 +759,19 @@ export function apply(ctx) {
722
759
  }
723
760
  if (url.pathname === `${ROUTE_PREFIX}/prefs` && req.method === 'PUT') {
724
761
  const body = JSON.parse((await readBody(req)) || '{}')
762
+ const previousRegion = prefs.providerRegion
725
763
  prefs = normalizePrefs(body, prefs)
726
764
  await saveJson(dir, 'prefs.json', prefs)
727
765
  clearProviderCache()
766
+ // 只有区域设置真正变化才清 pin;改预算不应触发重探测
767
+ if (JSON.stringify(previousRegion) !== JSON.stringify(prefs.providerRegion)) resetRegionPins()
728
768
  applyPricingConfig()
729
769
  logger.info('boot', 'prefs.saved', {
730
770
  budgets: Object.keys(prefs.budgets).length,
731
771
  modes: Object.keys(prefs.billingModes).length,
732
772
  overrides: Object.keys(prefs.priceOverrides).length,
733
773
  currencies: Object.keys(prefs.providerCurrency).length,
774
+ regions: Object.keys(prefs.providerRegion).length,
734
775
  })
735
776
  json(res, 200, { ok: true, data: prefs })
736
777
  return
package/locale/en.json CHANGED
@@ -144,5 +144,16 @@
144
144
  "版本号不合法": "Invalid version",
145
145
  "该版本未发布": "Version not published",
146
146
  "版本未变化": "Version unchanged",
147
- "未找到 dsh 命令": "dsh command not found"
147
+ "未找到 dsh 命令": "dsh command not found",
148
+ "不限量": "Unlimited",
149
+ "自动": "Auto",
150
+ "手动": "Manual",
151
+ "国内": "China",
152
+ "国际": "Global",
153
+ "切换区域:自动 / 国内 / 国际": "Switch region: auto / China / global",
154
+ "中国": "China",
155
+ "海外": "Global",
156
+ "切换区域:中国 / 海外": "Switch region: China / global",
157
+ "离线缓存": "Offline cache",
158
+ "内置目录": "Built-in catalog"
148
159
  }
package/locale/zh.json CHANGED
@@ -144,5 +144,16 @@
144
144
  "版本号不合法": "版本号不合法",
145
145
  "该版本未发布": "该版本未发布",
146
146
  "版本未变化": "版本未变化",
147
- "未找到 dsh 命令": "未找到 dsh 命令"
147
+ "未找到 dsh 命令": "未找到 dsh 命令",
148
+ "不限量": "不限量",
149
+ "自动": "自动",
150
+ "手动": "手动",
151
+ "国内": "国内",
152
+ "国际": "国际",
153
+ "切换区域:自动 / 国内 / 国际": "切换区域:自动 / 国内 / 国际",
154
+ "中国": "中国",
155
+ "海外": "海外",
156
+ "切换区域:中国 / 海外": "切换区域:中国 / 海外",
157
+ "离线缓存": "离线缓存",
158
+ "内置目录": "内置目录"
148
159
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-token-dash",
3
- "version": "2.5.1",
4
- "description": "DeepSeek Harness Token 与费用看板:8 家供应商开箱即用,按供应商查看预算、订阅配额(GLM / Kimi / OpenCode Go / Command Code)与账户余额;Pill、浮层、整页三处呈现费用与真实 Tokens、缓存命中率与用量趋势,成本趋势双币种双轴;填第三方 API Key 的自建 / 中转 / 本地兼容服务同样能记账,未定价模型不按 0 元计,可导出 / 导入本地 JSON 备份。",
3
+ "version": "2.6.1",
4
+ "description": "DeepSeek Harness Token 与费用看板:9 家供应商开箱即用,按供应商查看预算、订阅配额(GLM / Kimi / OpenCode Go / Command Code / MiniMax)与账户余额,MiniMax 自动识别国内 / 国际站并支持按量 Key 余额,GLM / Kimi / Qwen 可在卡顶切换中国 / 海外区域;Pill、浮层、整页三处呈现费用与真实 Tokens、缓存命中率与用量趋势,成本趋势双币种双轴;价目表支持离线复用,断网重启用上一次成功的价格继续估算;填第三方 API Key 的自建 / 中转 / 本地兼容服务同样能记账,未定价模型不按 0 元计,可导出 / 导入本地 JSON 备份。",
5
5
  "type": "module",
6
6
  "main": "./index.js",
7
7
  "exports": {
@@ -33,6 +33,7 @@
33
33
  "cost",
34
34
  "budget",
35
35
  "quota",
36
+ "minimax",
36
37
  "dashboard"
37
38
  ],
38
39
  "license": "MIT",