dsh-token-dash 1.1.2 → 1.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
@@ -1,6 +1,6 @@
1
1
  /**
2
- * dsh-token-dash — client half. P1 constraint pill, P2 usage tab, P3 settings tab.
3
- * The visual contract lives in docs/ui-design.md v2.21.
2
+ * dsh-token-dash — client half. P1 pill, P2 current-model popover, P3 full-page board.
3
+ * The visual contract lives in docs/ui-design.md v3.1.
4
4
  */
5
5
  window.__ModuleLoader__.load({
6
6
  id: 'dsh-token-dash',
@@ -11,6 +11,12 @@ window.__ModuleLoader__.load({
11
11
 
12
12
  const API = '/token-dash/api'
13
13
  const PKG = 'dsh-token-dash'
14
+ const PAGE_ID = 'token-dash'
15
+ const REPO_URL = 'https://github.com/spartawhy117/dsh-token-dash'
16
+ const SUB_CRITICAL = 90
17
+ const API_CRITICAL = 100
18
+ const STALE_MS = 5000
19
+
14
20
  const RANGES = [
15
21
  ['today', '当天'],
16
22
  ['7d', '近7天'],
@@ -20,6 +26,19 @@ window.__ModuleLoader__.load({
20
26
  const REFRESH_OPTIONS = [[30000, '30秒'], [60000, '1分钟'], [300000, '5分钟']]
21
27
  const PRICE_LABELS = { zhipu: 'GLM', qwen: 'Qwen' }
22
28
  const SPIN_CSS = '@keyframes td-spin{to{transform:rotate(360deg)}}'
29
+ const TD_CSS = [
30
+ SPIN_CSS,
31
+ '@media (max-width:520px){[data-td-label]{display:none}}',
32
+ '[data-td-pill]:hover{background:color-mix(in srgb,currentColor 8%,transparent)}',
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
+ '[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)}}',
36
+ '[data-td-scroll]{overflow-x:auto}',
37
+ '[data-td-scroll] > *{min-width:560px}',
38
+ '[data-testid=token-dash-board-scroll]::-webkit-scrollbar{width:8px}',
39
+ '[data-testid=token-dash-board-scroll]::-webkit-scrollbar-thumb{background:color-mix(in srgb,currentColor 28%,transparent);border-radius:4px}',
40
+ '[data-testid=token-dash-board-scroll]::-webkit-scrollbar-track{background:transparent}',
41
+ ].join('')
23
42
  const EN = {
24
43
  '当天': 'Today', '近7天': 'Last 7 days', '近30天': 'Last 30 days', '全部': 'All',
25
44
  '30秒': '30s', '1分钟': '1m', '5分钟': '5m',
@@ -31,14 +50,19 @@ window.__ModuleLoader__.load({
31
50
  '余额 {value}': 'Balance {value}', '预算已用 {value}': 'Budget used {value}',
32
51
  '预算未设置': 'Budget not set', '收起': 'Collapse', '展开': 'Expand',
33
52
  'Token 看板': 'Token dashboard', '点击查看 Token 看板': 'Click to view Token dashboard',
34
- 'Token 看板:{text}': 'Token dashboard: {text}', '看板页面': 'Dashboard page',
35
- '用量': 'Usage', '设置': 'Settings',
53
+ 'Token 看板:{text}': 'Token dashboard: {text}',
54
+ '当前模型': 'Current model', '全量看板': 'Full dashboard', '查看仓库': 'View repository',
36
55
  '查看支持的 API Key 范围': 'View supported API Key scope',
37
56
  '目前支持 DeepSeek / Kimi / GLM / OpenRouter / Qwen API Key': 'Supports DeepSeek / Kimi / GLM / OpenRouter / Qwen API Keys',
38
57
  '刷新': 'Refresh', '关闭': 'Close',
39
58
  '未定价': 'Unpriced', '请求': 'Req', '命中': 'Hit',
40
- '本月预算': 'Monthly budget',
41
- '订阅套餐(账户级)': 'Subscription plan (account-wide)',
59
+ '按量计价(按供应商)': 'Pay-as-you-go (by provider)',
60
+ '订阅套餐(按供应商)': 'Subscription plans (by provider)',
61
+ '名称': 'Name', '已用': 'Used', '已用 / 预算': 'Used / budget', '计划余额': 'Planned left', '真实余额': 'Real balance',
62
+ '剩余 {value}': '{value} left', '本月已花': 'Spent this month',
63
+ '今日': 'Today', '总费用': 'Total cost', '重试': 'Retry',
64
+ '模型': 'Model', '共 {n} 个模型': 'Total {n} models', '窗': 'windows', '数据来源': 'Data source', '数据来自本机会话记录,费用与 Tokens 均在本地估算': 'Estimated locally from local session records', '范围与明细': 'Range & details', '输入': 'In', '缓存': 'Cache', '输出': 'Out', '费用': 'Cost',
65
+ '费用(API 计价估算)': 'Cost (API estimate)',
42
66
  '重新检测订阅配额': 'Recheck subscription quota',
43
67
  '未检测到已配置供应商': 'No configured provider detected',
44
68
  '供应商探测失败': 'Provider probe failed',
@@ -53,7 +77,7 @@ window.__ModuleLoader__.load({
53
77
  '设置加载失败': 'Failed to load settings', '已保存': 'Saved',
54
78
  '保存失败:{reason}': 'Save failed: {reason}', '请输入 0 或正数': 'Enter 0 or a positive number',
55
79
  '月度预算': 'Monthly budget', '账户余额': 'Account balance',
56
- '刷新间隔': 'Refresh interval', '显示': 'Display', '日志': 'Logs',
80
+ '刷新间隔': 'Refresh interval', '立即刷新': 'Refresh now', '日志': 'Logs',
57
81
  '查看日志': 'View logs', '打开日志文件夹': 'Open log folder', '导出日志': 'Export logs',
58
82
  '价格与版本': 'Prices and version', '价格表': 'Price table',
59
83
  '已重新检测': 'Rechecked', '已打开日志文件夹': 'Log folder opened',
@@ -70,17 +94,25 @@ window.__ModuleLoader__.load({
70
94
  '更新失败({reason})': 'Update failed ({reason})',
71
95
  '已更新到 {version},重启 DSH 后生效': 'Updated to {version}; restart DSH to apply',
72
96
  '已更新,重启 DSH 后生效': 'Updated; restart DSH to apply',
73
- 'API 计费': 'API billing',
74
97
  '发现 {version},点击更新': 'Found {version}; click to update',
75
98
  '版本 {version}': 'Version {version}',
76
99
  '{name} · {action} Token 看板': '{name} · {action} Token dashboard',
77
100
  '{name} 月度预算': '{name} monthly budget',
78
101
  '{name},按量 API,{budget},今日 {today}{balance}': '{name}, pay-as-you-go, {budget}, today {today}{balance}',
79
102
  '{name},订阅,账户套餐,{value}': '{name}, subscription, account plan, {value}',
103
+ '更新于 {time}': 'Updated {time}', '数据来自本机会话记录': 'From local session records',
104
+ '未配置凭据': 'No credentials', '刷新中': 'Refreshing',
105
+ '编辑预算': 'Edit budget', '退出编辑': 'Exit editing',
106
+ '设置与数据管理': 'Settings and data',
107
+ '账户真实余额,不受预算影响': 'Account balance; not affected by budget',
108
+ '本月累计消耗,等于已用/预算 的分子': 'Month-to-date spend; numerator of used/budget',
109
+ '提示': 'Note',
80
110
  }
81
111
  const ZH = Object.fromEntries(Object.keys(EN).map((key) => [key, key]))
82
112
  const MESSAGES = { zh: ZH, en: EN }
83
113
  let localeService = null
114
+ let ctxRef = null
115
+ let layoutRef = null
84
116
  let activeTranslate = (key, params) => {
85
117
  const template = ZH[key] ?? key
86
118
  if (!params) return template
@@ -95,7 +127,7 @@ window.__ModuleLoader__.load({
95
127
  accent: 'var(--dsw-alias-state-business-primary, #6ea8ff)',
96
128
  warn: 'var(--dsw-alias-state-warn-primary, #f0a020)',
97
129
  over: 'var(--dsw-alias-state-error-primary, #e05a5a)',
98
- ok: 'var(--dsw-alias-state-success-primary, #4ed17e)',
130
+ ok: 'var(--td-state-ok, var(--dsw-alias-state-success-primary, #4ed17e))',
99
131
  border: 'var(--dsw-alias-border-l2, rgba(128,128,128,.25))',
100
132
  section: 'color-mix(in srgb, var(--dsw-alias-label-primary, #eee) 3%, transparent)',
101
133
  tile: 'color-mix(in srgb, var(--dsw-alias-label-primary, #eee) 4%, transparent)',
@@ -127,22 +159,38 @@ window.__ModuleLoader__.load({
127
159
  const hm = `${pad(date.getHours())}:${pad(date.getMinutes())}`
128
160
  return date.toDateString() === now.toDateString() ? hm : `${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${hm}`
129
161
  }
130
- /** 重置时间带相对量:`3 小时后 · 11-03 20:15`;<1h 用分钟(最小 1),<24h 用小时,其余用天。 */
131
- const fmtReset = (ts) => {
132
- if (!Number.isFinite(ts) || ts <= 0) return null
162
+ /** 重置时间拆两段:相对量 <1h 分钟(最小 1)、<24h 小时、其余天;绝对时间 `MM-DD HH:mm`。 */
163
+ function resetParts(ts, now = Date.now()) {
164
+ if (!Number.isFinite(ts) || ts <= 0) return { relative: null, absolute: null }
133
165
  const date = new Date(ts)
134
166
  const pad = (value) => String(value).padStart(2, '0')
135
- const time = `${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`
136
- const minutes = Math.max(1, Math.round((Number(ts) - Date.now()) / 60000))
137
- const label = minutes < 60
167
+ const absolute = `${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`
168
+ const minutes = Math.max(1, Math.round((Number(ts) - now) / 60000))
169
+ const relative = minutes < 60
138
170
  ? tr('{n} 分钟后', { n: minutes })
139
171
  : minutes < 1440
140
172
  ? tr('{n} 小时后', { n: Math.round(minutes / 60) })
141
173
  : tr('{n} 天后', { n: Math.round(minutes / 1440) })
142
- return `${label} · ${time}`
174
+ return { relative, absolute }
175
+ }
176
+ const fmtReset = (ts) => {
177
+ const { relative, absolute } = resetParts(ts)
178
+ return relative === null ? null : `${relative} · ${absolute}`
179
+ }
180
+ const fmtClock = (ts) => {
181
+ if (!Number.isFinite(ts) || ts <= 0) return null
182
+ const date = new Date(ts)
183
+ const pad = (value) => String(value).padStart(2, '0')
184
+ return `${pad(date.getHours())}:${pad(date.getMinutes())}`
143
185
  }
144
186
  const budgetColor = (state) => (state === 'over' ? T.over : state === 'warn' ? T.warn : T.accent)
145
- const percentColor = (value) => (value >= 100 ? T.over : value >= 80 ? T.warn : T.accent)
187
+ /** 环状态:null 空环;≥critical 红;≥warn 黄;其余正常绿。 */
188
+ const stateOf = (percent, critical = 100) => (percent === null || percent === undefined ? 'empty' : percent >= critical ? 'critical' : percent >= 80 ? 'warn' : 'normal')
189
+ const ringState = stateOf
190
+ const stateColor = (state) => (state === 'critical' ? T.over : state === 'warn' ? T.warn : state === 'empty' ? T.weak : T.ok)
191
+ /** 数字色:与环同色,只表达告警。 */
192
+ const percentColor = (value, critical = 100) => stateColor(stateOf(value, critical))
193
+ const percentText = (value) => (value === null || value === undefined ? '—' : fmtPercent(value))
146
194
  const sourceLabel = (source) => String(source ?? '').includes('community') ? tr('社区') : tr('内置兜底')
147
195
  const linkLabel = (link) => PRICE_LABELS[link.id] ?? link.label
148
196
  const formatCatalogTime = (value) => {
@@ -279,16 +327,17 @@ window.__ModuleLoader__.load({
279
327
  background: T.tooltip, color: T.tooltipText, border: `1px solid ${T.border}`,
280
328
  fontSize: 11, whiteSpace: 'nowrap', boxShadow: '0 4px 16px rgba(0,0,0,.25)',
281
329
  },
282
- chevron: { marginLeft: 2, padding: '0 1px', color: T.accent, fontSize: 10 },
330
+ chevron: { marginLeft: 2, display: 'inline-flex', alignItems: 'center', color: T.muted },
283
331
  num: { fontWeight: 600, fontVariantNumeric: 'tabular-nums' },
284
332
  panel: {
285
333
  position: 'absolute', bottom: 'calc(100% + 8px)', left: 0,
286
- width: 'min(360px, calc(100vw - 16px))', boxSizing: 'border-box', maxHeight: '70vh',
287
- overflow: 'auto', zIndex: 9999, padding: 12, borderRadius: 12,
334
+ width: 'min(380px, calc(100vw - 16px))', maxWidth: 'calc(100vw - 16px)',
335
+ boxSizing: 'border-box', maxHeight: '70vh', transition: 'width 120ms ease-out',
336
+ overflow: 'auto', zIndex: 9999, padding: 16, borderRadius: 12,
288
337
  background: 'var(--dsw-alias-bg-layer-2, var(--dsh-bg-elevated, #1f1f1f))', color: T.text,
289
- border: `1px solid ${T.border}`, boxShadow: '0 12px 40px rgba(0,0,0,.35)', fontSize: 12, outline: 'none',
338
+ border: `1px solid ${T.border}`, boxShadow: '0 12px 40px rgba(0,0,0,.35)', fontSize: 13, outline: 'none',
290
339
  },
291
- header: { display: 'flex', alignItems: 'center', gap: 6, minHeight: 28 },
340
+ header: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, minHeight: 28 },
292
341
  headerTabs: { flex: 1, minWidth: 0 },
293
342
  headerActions: { display: 'flex', alignItems: 'center', gap: 4, flex: '0 0 auto' },
294
343
  row: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 },
@@ -344,16 +393,131 @@ window.__ModuleLoader__.load({
344
393
  card: { background: T.section, borderRadius: 10, padding: 10, marginTop: 10, display: 'grid', gap: 8 },
345
394
  link: { color: T.text, textDecoration: 'underline', cursor: 'pointer' },
346
395
  status: { minHeight: 15, fontSize: 10.5, color: T.muted, textAlign: 'right' },
347
- priceLinks: { display: 'flex', gap: 7, alignItems: 'center', overflowX: 'auto', whiteSpace: 'nowrap', paddingBottom: 1 },
396
+ summaryRow: { display: 'flex', flexWrap: 'nowrap', alignItems: 'center', justifyContent: 'space-between', gap: 12, minHeight: 24, fontSize: 12 },
397
+ summaryCell: { display: 'flex', flexDirection: 'column', gap: 4, minWidth: 0, whiteSpace: 'nowrap' },
398
+ summaryLabel: { color: T.muted, fontSize: 11 },
399
+ summaryValue: { fontSize: 12, fontWeight: 600, fontVariantNumeric: 'tabular-nums' },
400
+ providerLine: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, minWidth: 0, minHeight: 24 },
401
+ providerChip: { color: T.muted, fontSize: 12, whiteSpace: 'nowrap' },
402
+ windowRow: { display: 'grid', gridTemplateColumns: 'auto 1fr 1fr 1fr', columnGap: 8, alignItems: 'center', minHeight: 24, fontSize: 13 },
403
+ windowKey: { display: 'inline-flex', alignItems: 'center', gap: 6, whiteSpace: 'nowrap' },
404
+ table: { display: 'grid', minWidth: 0 },
405
+ tableHead: { display: 'grid', columnGap: 8, alignItems: 'center', color: T.weak, fontSize: 12, paddingBottom: 8, borderBottom: `1px solid ${T.border}` },
406
+ tableRow: { display: 'grid', columnGap: 8, alignItems: 'baseline', minHeight: 28, padding: '4px 0', fontSize: 13, borderBottom: '1px solid color-mix(in srgb, currentColor 6%, transparent)' },
407
+ cellNum: { fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' },
408
+ cellName: { minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
409
+ footer: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, marginTop: 12, minHeight: 22 },
410
+ boardScroll: {
411
+ width: '100%', height: '100%', overflowY: 'auto', overflowX: 'hidden',
412
+ boxSizing: 'border-box', overscrollBehavior: 'contain',
413
+ scrollbarWidth: 'thin',
414
+ scrollbarColor: 'color-mix(in srgb, currentColor 28%, transparent) transparent',
415
+ },
416
+ board: {
417
+ padding: 24, display: 'grid', gap: 24,
418
+ color: T.text, fontSize: 13, minWidth: 0, width: '100%', maxWidth: 1000, margin: '0 auto', boxSizing: 'border-box',
419
+ },
420
+ boardHead: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16, flexWrap: 'wrap' },
421
+ boardTitleRow: { display: 'flex', alignItems: 'baseline', gap: 16, flex: '1 1 auto', minWidth: 0 },
422
+ boardTitle: { fontSize: 18, fontWeight: 600, whiteSpace: 'nowrap' },
423
+ boardMeta: { color: T.muted, fontSize: 12, whiteSpace: 'nowrap' },
424
+ boardAction: {
425
+ boxSizing: 'border-box', width: 44, height: 26, padding: 0, borderRadius: 6,
426
+ display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
427
+ color: T.accent, fontSize: 13, textDecoration: 'none', cursor: 'pointer',
428
+ border: `1px solid color-mix(in srgb, ${T.accent} 32%, transparent)`,
429
+ background: `color-mix(in srgb, ${T.accent} 16%, transparent)`,
430
+ },
431
+ boardSection: { display: 'grid', gap: 12, minWidth: 0 },
432
+ boardSectionHead: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, minHeight: 24 },
433
+ sectionTitle: { fontSize: 13, fontWeight: 600 },
434
+ cardBox: {
435
+ border: `1px solid ${T.border}`, borderRadius: 8, padding: 12, background: T.section,
436
+ display: 'grid', gap: 4, minWidth: 0,
437
+ },
438
+ cards: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginTop: 16 },
439
+ capsule: {
440
+ padding: '4px 16px', marginBottom: 32, borderRadius: 10, display: 'grid', gap: 0,
441
+ background: 'var(--dsw-alias-bg-layer-2, var(--dsh-bg-elevated, #1f1f1f))',
442
+ border: `1px solid ${T.border}`,
443
+ },
444
+ settingsRow: {
445
+ display: 'grid', gridTemplateColumns: '40px minmax(0,1fr)', alignItems: 'center', gap: 12,
446
+ padding: '8px 0', minHeight: 24, borderTop: '1px solid color-mix(in srgb, currentColor 6%, transparent)',
447
+ },
448
+ settingsRowRefresh: { gridTemplateColumns: 'minmax(0,1fr) auto' },
449
+ settingsGroup: { display: 'flex', alignItems: 'center', gap: 12, minWidth: 0 },
450
+ settingsGroupLeft: { justifySelf: 'start' },
451
+ settingsGroupRight: { justifySelf: 'end' },
452
+ settingsLabel: { color: T.weak, fontSize: 11 },
453
+ repoChip: {
454
+ display: 'inline-flex', alignItems: 'center', gap: 4, height: 24, padding: '0 8px', borderRadius: 999,
455
+ border: `1px solid ${T.border}`, color: T.text, textDecoration: 'none', fontSize: 12, whiteSpace: 'nowrap',
456
+ },
457
+ inlineWrap: { display: 'inline-flex', alignItems: 'center', gap: 4 },
458
+ gaugeMeta: { color: T.muted, fontSize: 11, lineHeight: '15px', whiteSpace: 'nowrap' },
459
+ apiCards: { display: 'flex', flexWrap: 'wrap', justifyContent: 'center', gap: 12 },
460
+ apiCard: {
461
+ flex: '1 1 220px', maxWidth: 260, minWidth: 220, boxSizing: 'border-box',
462
+ border: `1px solid ${T.border}`, borderRadius: 8, background: T.section, padding: 16,
463
+ display: 'grid', gap: 8, alignContent: 'start',
464
+ },
465
+ apiCardHead: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, minWidth: 0 },
466
+ apiCardName: { fontSize: 13, fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
467
+ apiChip: { color: T.muted, fontSize: 11, whiteSpace: 'nowrap' },
468
+ apiGaugeWrap: { display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8 },
469
+ budgetLabel: { color: T.muted, fontSize: 11 },
470
+ budgetInputWrap: {
471
+ display: 'inline-flex', alignItems: 'center', gap: 4, border: `1px solid ${T.border}`,
472
+ borderRadius: 6, padding: '4px 8px', background: T.input,
473
+ },
474
+ budgetInput: {
475
+ width: 72, border: 0, background: 'transparent', color: T.text, font: 'inherit',
476
+ fontSize: 13, textAlign: 'right', outline: 'none', fontVariantNumeric: 'tabular-nums',
477
+ },
478
+ kvRow: { display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 8, fontSize: 12, minWidth: 0 },
479
+ kvLabel: { color: T.muted, whiteSpace: 'nowrap' },
480
+ kvValue: { color: T.text, fontWeight: 600, fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' },
481
+ summaryBand: {
482
+ display: 'grid', gridTemplateColumns: '1fr 1fr', border: `1px solid ${T.border}`,
483
+ borderRadius: 8, overflow: 'hidden',
484
+ },
485
+ summaryHalf: { padding: 16, display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', gap: 8, minWidth: 0 },
486
+ summaryK: { color: T.muted, fontSize: 12 },
487
+ summaryV: { display: 'flex', alignItems: 'baseline', justifyContent: 'center', flexWrap: 'wrap', gap: 8, fontSize: 26, fontWeight: 600, lineHeight: '30px', fontVariantNumeric: 'tabular-nums' },
488
+ summarySub: { color: T.weak, fontSize: 11, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: '100%' },
489
+ rangeBox: {
490
+ border: `1px solid ${T.border}`, borderRadius: 10, background: T.section,
491
+ padding: 16, display: 'flex', flexDirection: 'column', gap: 12, minWidth: 0,
492
+ },
493
+ rangeHead: { display: 'flex', alignItems: 'center', justifyContent: 'flex-start', flexWrap: 'wrap', gap: 16 },
494
+ rangeMeta: { color: T.weak, fontSize: 11 },
495
+ detailWrap: { overflowX: 'auto', borderTop: `1px solid ${T.border}`, paddingTop: 12 },
496
+ quotaCards: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 12 },
497
+ quotaCard: {
498
+ border: `1px solid ${T.border}`, borderRadius: 8, background: T.section, padding: 16,
499
+ display: 'grid', gap: 12, alignContent: 'start', minWidth: 0,
500
+ },
501
+ quotaWindows: { display: 'grid', gap: 12, minWidth: 0 },
502
+ cardCaption: { color: T.weak, fontSize: 11, textAlign: 'center', marginTop: 4, whiteSpace: 'nowrap' },
503
+ rangeCapsule: { width: '100%', minWidth: 0 },
348
504
  }
349
505
  styles.button['--td-accent'] = T.accent
350
506
  styles.iconButton = { ...styles.button, ...styles.iconButton, minHeight: 22, boxSizing: 'border-box' }
507
+ styles.primary = {
508
+ ...styles.button, color: T.accent,
509
+ borderColor: 'color-mix(in srgb, var(--td-accent) 32%, transparent)',
510
+ background: 'color-mix(in srgb, var(--td-accent) 16%, transparent)',
511
+ }
512
+ styles.ghost = { ...styles.button, color: T.accent, borderColor: 'transparent', background: 'transparent' }
513
+ styles.outline = { ...styles.button, color: T.text, borderColor: T.border, background: 'transparent' }
351
514
 
352
515
  function Icon({ name, size = 14, style }) {
353
516
  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 }
354
517
  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' }))
355
518
  if (name === 'close') return h('svg', props, h('path', { d: 'M6 6l12 12M18 6L6 18' }))
356
519
  if (name === 'check') return h('svg', props, h('path', { d: 'M20 6L9 17l-5-5' }))
520
+ if (name === 'chevron') return h('svg', props, h('path', { d: 'M6 9l6 6 6-6' }))
357
521
  if (name === 'download') return h('svg', props, h('path', { d: 'M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4' }), h('path', { d: 'M7 10l5 5 5-5' }), h('path', { d: 'M12 15V3' }))
358
522
  if (name === 'loader') return h('svg', { ...props, style: { ...style, animation: 'td-spin 1s linear infinite' } }, h('path', { d: 'M21 12a9 9 0 1 1-6.2-8.56' }))
359
523
  return h('svg', props, h('path', { d: 'M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8' }), h('path', { d: 'M3 3v5h5' }), h('path', { d: 'M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16' }), h('path', { d: 'M16 16h5v5' }))
@@ -503,6 +667,203 @@ window.__ModuleLoader__.load({
503
667
  }))
504
668
  }
505
669
 
670
+ /** 统一轮询:页面不可见暂停,恢复可见立即刷新并重排计时器。 */
671
+ function usePolling(task, { refreshMs, enabled = true }) {
672
+ const taskRef = useRef(task)
673
+ taskRef.current = task
674
+ useEffect(() => {
675
+ if (!enabled || !Number.isFinite(refreshMs) || refreshMs <= 0) return undefined
676
+ let timer = null
677
+ const stop = () => { if (timer !== null) { clearInterval(timer); timer = null } }
678
+ const start = () => {
679
+ stop()
680
+ timer = setInterval(() => { if (!document.hidden) taskRef.current?.() }, refreshMs)
681
+ }
682
+ const onVisibility = () => {
683
+ if (document.hidden) { stop(); return }
684
+ taskRef.current?.()
685
+ start()
686
+ }
687
+ start()
688
+ document.addEventListener('visibilitychange', onVisibility)
689
+ return () => { stop(); document.removeEventListener('visibilitychange', onVisibility) }
690
+ }, [refreshMs, enabled])
691
+ }
692
+
693
+ /** 进度环:空环 / 正常 / 临界三态,弧色只取宿主 token。 */
694
+ function ProgressRing({ percent, state = 'normal', size = 14, stroke = 2 }) {
695
+ const r = (size - stroke) / 2
696
+ const c = 2 * Math.PI * r
697
+ const ratio = Math.max(0, Math.min(100, Number(percent) || 0))
698
+ const arc = stateColor(state)
699
+ return h('svg', {
700
+ viewBox: `0 0 ${size} ${size}`, width: size, height: size, 'aria-hidden': true,
701
+ style: { flex: '0 0 auto', display: 'inline-block', verticalAlign: '-2px' },
702
+ },
703
+ h('circle', { cx: size / 2, cy: size / 2, r, fill: 'none', stroke: T.border, strokeWidth: stroke }),
704
+ state === 'empty' ? null : h('circle', {
705
+ cx: size / 2, cy: size / 2, r, fill: 'none', stroke: arc, strokeWidth: stroke, strokeLinecap: 'round',
706
+ transform: `rotate(-90 ${size / 2} ${size / 2})`,
707
+ strokeDasharray: `${(c * ratio) / 100} ${c}`,
708
+ }))
709
+ }
710
+
711
+ /** 百分比文本:只负责格式化与状态色,不管排版。 */
712
+ function PercentValue({ percent, state = stateOf(percent), size = 12, testid }) {
713
+ return h('b', {
714
+ 'data-testid': testid,
715
+ style: { fontSize: size, fontWeight: 600, color: stateColor(state), fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' },
716
+ }, percentText(percent))
717
+ }
718
+
719
+ /** 内联组合:环 + 右侧数字,P1 14/2、P2 20/2.5。 */
720
+ function InlineRing({ percent, state = stateOf(percent), size = 14, stroke = 2, text, testid, percentTestid }) {
721
+ return h('span', {
722
+ 'data-testid': testid,
723
+ style: { display: 'inline-flex', alignItems: 'center', gap: 4, minWidth: 0 },
724
+ },
725
+ h(ProgressRing, { percent, state, size, stroke }),
726
+ text !== undefined
727
+ ? h('b', { 'data-testid': percentTestid, style: { fontWeight: 600, color: stateColor(state) } }, text)
728
+ : h(PercentValue, { percent, state, size: 12, testid: percentTestid }))
729
+ }
730
+
731
+ /** P3 组合:环心标签 + 环下百分比 + 三行辅助。 */
732
+ function QuotaGauge({ label, percent, state = stateOf(percent), remaining, relative, absolute, size = 40, stroke = 4, testid, labelTestid, percentTestid, remainingTestid, relativeTestid, absoluteTestid }) {
733
+ const aria = [label, percentText(percent), remaining, relative].filter((part) => part !== undefined && part !== null && part !== '').join(',')
734
+ return h('div', {
735
+ 'data-testid': testid, role: 'group', 'aria-label': aria,
736
+ style: { display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4, minWidth: 0 },
737
+ },
738
+ h('div', { style: { position: 'relative', width: size, height: size, flex: '0 0 auto' } },
739
+ h(ProgressRing, { percent, state, size, stroke }),
740
+ label === undefined || label === null || label === ''
741
+ ? null
742
+ : h('span', {
743
+ 'data-testid': labelTestid,
744
+ style: {
745
+ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center',
746
+ fontSize: 12, fontWeight: 600, color: T.muted, letterSpacing: '.2px',
747
+ },
748
+ }, label)),
749
+ h('span', {
750
+ 'data-testid': percentTestid,
751
+ style: { fontSize: 16, fontWeight: 600, lineHeight: '20px', color: stateColor(state), fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' },
752
+ }, percentText(percent)),
753
+ remaining === undefined ? null : h('span', { 'data-testid': remainingTestid, style: styles.gaugeMeta }, remaining),
754
+ relative === undefined ? null : h('span', { 'data-testid': relativeTestid, style: styles.gaugeMeta }, relative),
755
+ absolute === undefined ? null : h('span', { 'data-testid': absoluteTestid, style: styles.gaugeMeta }, absolute))
756
+ }
757
+
758
+ const TOKEN_COLS = 'minmax(0,1fr) auto auto auto'
759
+
760
+ /** P2 用量表:四列全自适应,Tokens 按「单位 / `[` 交界」两段对齐。 */
761
+ const TABLE_BORDER = '1px solid color-mix(in srgb, currentColor 6%, transparent)'
762
+
763
+ function TokenTable({ rows, maxRows = 5, empty = tr('范围内暂无消耗') }) {
764
+ if (rows.length === 0) return h('div', { style: styles.empty }, empty)
765
+ const headCell = (text, align = 'right') => h('span', {
766
+ role: 'columnheader',
767
+ style: { color: T.weak, fontSize: 12, textAlign: align, paddingBottom: 6, borderBottom: `1px solid ${T.border}` },
768
+ }, text)
769
+ const cell = { padding: '5px 0', borderBottom: TABLE_BORDER, fontSize: 12, minWidth: 0 }
770
+ return h('div', {
771
+ 'data-testid': 'token-dash-usage-table',
772
+ role: 'table',
773
+ style: { ...styles.table, gridTemplateColumns: TOKEN_COLS, columnGap: 8, maxHeight: maxRows * 32, overflowY: 'auto' },
774
+ },
775
+ h('div', { style: { display: 'contents' } },
776
+ headCell(tr('模型'), 'left'), headCell('Tokens'), headCell(tr('请求')), headCell(tr('命中'))),
777
+ ...rows.map((row) => h('div', {
778
+ key: `${row.providerId}:${row.modelId}`,
779
+ role: 'row',
780
+ 'data-testid': `token-dash-usage-row-${row.providerId}-${row.modelId}`,
781
+ style: { display: 'contents' },
782
+ },
783
+ h('span', {
784
+ role: 'cell',
785
+ style: { ...styles.cellName, ...cell, maxWidth: 150 },
786
+ title: row.displayName ?? row.modelId,
787
+ }, row.displayName ?? row.modelId),
788
+ h('span', {
789
+ role: 'cell',
790
+ 'data-testid': 'token-dash-usage-line',
791
+ style: {
792
+ ...cell, display: 'inline-flex', alignItems: 'baseline', gap: 4,
793
+ fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap', justifySelf: 'end', textAlign: 'right',
794
+ },
795
+ },
796
+ h('span', { style: { minWidth: '5ch', textAlign: 'right', fontWeight: 600 } }, fmtTokens(row.tokens?.total ?? 0)),
797
+ h('span', { style: { color: T.muted, fontSize: 11 } }, `[${fmtTokens(row.tokens?.input ?? 0)}/${fmtTokens(row.tokens?.cache ?? 0)}/${fmtTokens(row.tokens?.output ?? 0)}]`)),
798
+ h('span', { role: 'cell', style: { ...styles.cellNum, ...cell, textAlign: 'right' } }, row.requests),
799
+ h('span', { role: 'cell', style: { ...styles.cellNum, ...cell, textAlign: 'right' } },
800
+ row.hitRate === null || row.hitRate === undefined ? '—' : fmtRatio(row.hitRate)))))
801
+ }
802
+
803
+ const DETAIL_COLS = 'minmax(0, 240px) repeat(7, minmax(56px, 1fr))'
804
+
805
+ /** P3 明细表:八列,费用只对 API 计价行展示。 */
806
+ function DetailTable({ rows, providerNames = {} }) {
807
+ if (rows.length === 0) return h('div', { style: styles.empty }, tr('范围内暂无消耗'))
808
+ const headCell = (text, align = 'right') => h('span', {
809
+ role: 'columnheader',
810
+ style: { color: T.weak, fontSize: 11, textAlign: align, paddingBottom: 8, borderBottom: `1px solid ${T.border}` },
811
+ }, text)
812
+ const cell = { padding: '4px 0', borderBottom: TABLE_BORDER, fontSize: 13, minWidth: 0 }
813
+ return h('div', { role: 'table', 'aria-label': tr('模型用量明细') },
814
+ h('div', { 'data-testid': 'token-dash-detail-table', style: { ...styles.table, gridTemplateColumns: DETAIL_COLS, columnGap: 8, minWidth: 720 } },
815
+ h('div', { style: { display: 'contents' } },
816
+ headCell(tr('模型'), 'left'),
817
+ headCell('Tokens'), headCell(tr('输入')), headCell(tr('缓存')), headCell(tr('输出')),
818
+ headCell(tr('请求')), headCell(tr('命中')), headCell(tr('费用'))),
819
+ ...rows.map((row) => h('div', {
820
+ key: `${row.providerId}:${row.modelId}`,
821
+ role: 'row',
822
+ 'data-testid': `token-dash-detail-row-${row.providerId}-${row.modelId}`,
823
+ style: { display: 'contents' },
824
+ },
825
+ h('span', {
826
+ role: 'cell',
827
+ style: { ...styles.cellName, ...cell },
828
+ title: [row.displayName ?? row.modelId, providerNames[row.providerId]].filter(Boolean).join(' · '),
829
+ }, [row.displayName ?? row.modelId, providerNames[row.providerId]].filter(Boolean).join(' · ')),
830
+ h('span', { role: 'cell', style: { ...styles.cellNum, ...cell, textAlign: 'right', fontWeight: 600 } }, fmtTokens(row.tokens?.total ?? 0)),
831
+ h('span', { role: 'cell', style: { ...styles.cellNum, ...cell, textAlign: 'right' } }, fmtTokens(row.tokens?.input ?? 0)),
832
+ h('span', { role: 'cell', style: { ...styles.cellNum, ...cell, textAlign: 'right' } }, fmtTokens(row.tokens?.cache ?? 0)),
833
+ h('span', { role: 'cell', style: { ...styles.cellNum, ...cell, textAlign: 'right' } }, fmtTokens(row.tokens?.output ?? 0)),
834
+ h('span', { role: 'cell', style: { ...styles.cellNum, ...cell, textAlign: 'right' } }, row.requests),
835
+ h('span', { role: 'cell', style: { ...styles.cellNum, ...cell, textAlign: 'right' } },
836
+ row.hitRate === null || row.hitRate === undefined ? '—' : fmtRatio(row.hitRate)),
837
+ h('span', { role: 'cell', style: { ...styles.cellNum, ...cell, textAlign: 'right' } },
838
+ row.kind !== 'api' ? '—' : row.priced === false
839
+ ? tr('未定价')
840
+ : `${row.approximate === true ? '≈' : ''}${fmtMoney(row.cost, row.currency)}`)))))
841
+ }
842
+
843
+ /** P3 两格卡:总费用(多币种同行)与真实 Tokens。 */
844
+ function RangeCards({ usage }) {
845
+ const pending = usage === null
846
+ const costEntries = Object.entries(usage?.totals ?? {})
847
+ const total = usage?.total ?? null
848
+ const costNodes = costEntries.map(([currency, value]) => h('span', { key: currency }, fmtMoney(value.cost, currency)))
849
+ return h('div', { 'data-testid': 'token-dash-range-cards', 'data-td-cards': true, style: styles.summaryBand },
850
+ h('div', { 'data-testid': 'token-dash-card-cost', style: styles.summaryHalf },
851
+ h('div', { style: styles.summaryK }, tr('总费用')),
852
+ h('div', { 'data-testid': 'token-dash-cost-values', style: styles.summaryV },
853
+ pending ? '—' : (costNodes.length === 0 ? '—' : costNodes))),
854
+ h('div', { 'data-testid': 'token-dash-card-tokens', style: styles.summaryHalf },
855
+ h('div', { style: styles.summaryK },
856
+ `${tr('真实 Tokens')} `,
857
+ h(InfoTip, {
858
+ label: tr('Tokens 括号说明'),
859
+ text: tr('Tokens 括号顺序:输入 / 缓存(读+写)/ 输出'),
860
+ variant: 'inline',
861
+ }, h(Icon, { name: 'info', size: 11 }))),
862
+ h('div', { style: styles.summaryV }, pending ? '—' : fmtTokens(total?.tokens ?? 0)),
863
+ h('div', { style: styles.summarySub },
864
+ pending ? '—' : `${fmtTokens(total?.input ?? 0)} · ${fmtTokens(total?.cache ?? 0)} · ${fmtTokens(total?.output ?? 0)}`)))
865
+ }
866
+
506
867
  function MiniBar({ ratio = 0, neutral = false, stretch = false }) {
507
868
  return h('span', {
508
869
  style: { display: 'block', width: stretch ? '100%' : 48, height: 4, borderRadius: 999, overflow: 'hidden', background: 'color-mix(in srgb, var(--dsw-alias-label-primary, #eee) 10%, transparent)' },
@@ -526,35 +887,61 @@ window.__ModuleLoader__.load({
526
887
  function subscriptionText(provider) {
527
888
  const windows = Array.isArray(provider.windows) ? provider.windows : []
528
889
  if (windows.length === 0) return tr('套餐查询失败')
529
- return windows.slice(0, 2).map((plan) => `${windowLabel(plan.key)} ${fmtPercent(plan.usedPercent)}`).join(' · ')
890
+ return windows.slice(0, 3).map((plan) => `${windowLabel(plan.key)} ${fmtPercent(plan.usedPercent)}`).join(' · ')
530
891
  }
531
892
 
532
- function subscriptionNodes(provider, withReset = false) {
893
+ /** P1 订阅窗口:短标签 + 环 + 百分比,最多三窗,不显示重置。 */
894
+ function subscriptionNodes(provider) {
533
895
  const windows = Array.isArray(provider.windows) ? provider.windows : []
534
- if (windows.length === 0) return [h('span', { key: 'fail' }, tr('套餐查询失败'))]
535
- const nodes = windows.slice(0, 2).map((plan, index) => h(React.Fragment, { key: plan.key },
536
- index > 0 ? ' · ' : null,
537
- `${windowLabel(plan.key)} `,
538
- h('b', { style: { ...styles.num, color: percentColor(plan.usedPercent ?? 0) } }, fmtPercent(plan.usedPercent))))
539
- if (withReset && windows.length === 1) {
540
- const reset = fmtTime(windows[0].resetAt)
541
- if (reset !== null) nodes.push(h('span', { key: 'reset' }, ` · ${tr('重置')} ${reset}`))
896
+ if (windows.length === 0) return [h('span', { key: 'fail', style: styles.muted }, tr('套餐查询失败'))]
897
+ const nodes = []
898
+ for (const [index, plan] of windows.slice(0, 3).entries()) {
899
+ if (index > 0) nodes.push(h('span', { key: `sep-${plan.key}`, style: { color: T.weak } }, ' · '))
900
+ const percent = Number(plan.usedPercent)
901
+ nodes.push(h('span', { key: plan.key, style: styles.inlineWrap },
902
+ h('span', { 'data-td-label': true, style: styles.summaryLabel }, windowLabel(plan.key)),
903
+ h(InlineRing, {
904
+ percent, state: stateOf(percent, SUB_CRITICAL), size: 14, stroke: 2,
905
+ testid: `token-dash-pill-ring-${plan.key}`,
906
+ })))
542
907
  }
543
908
  return nodes
544
909
  }
545
910
 
546
- function LocaleRoot() {
911
+ function LocaleRoot(props) {
547
912
  const [, setTick] = useState(0)
548
913
  useEffect(() => {
549
914
  if (localeService?.subscribe === undefined) return undefined
550
915
  return localeService.subscribe(() => setTick((value) => value + 1))
551
916
  }, [])
552
- return h(Pill)
917
+ return h(Pill, props)
553
918
  }
554
919
 
555
- function Pill() {
920
+ const summaryPath = (active) => (typeof active === 'string' && active !== ''
921
+ ? `/summary?active=${encodeURIComponent(active)}`
922
+ : '/summary')
923
+
924
+ /** 三级取值:投影 next / lastUsed → 宿主默认模型 → 账本(null 交给 currentProviderId)。 */
925
+ function rawActiveProvider(props) {
926
+ try {
927
+ const projection = typeof props?.useProjection === 'function' ? props.useProjection('modelSelection') : null
928
+ const picked = projection?.next ?? projection?.lastUsed
929
+ const raw = typeof picked === 'string' ? picked : (picked?.provider ?? picked?.providerId ?? null)
930
+ if (typeof raw === 'string' && raw !== '') return raw
931
+ } catch { /* fall through */ }
932
+ try {
933
+ const service = typeof ctxRef?.get === 'function' ? ctxRef.get('agentDefaultModel') : null
934
+ const picked = service?.currentSelection?.()
935
+ const raw = typeof picked === 'string' ? picked : (picked?.provider ?? picked?.providerId ?? null)
936
+ if (typeof raw === 'string' && raw !== '') return raw
937
+ } catch { /* fall through */ }
938
+ return null
939
+ }
940
+
941
+ function Pill(props) {
556
942
  const updateState = useUpdateSnapshot()
557
943
  const hasUpdate = updateState.phase === 'available' || updateState.phase === 'confirm'
944
+ const active = rawActiveProvider(props)
558
945
  const [summary, setSummary] = useState(null)
559
946
  const [open, setOpen] = useState(false)
560
947
  const [error, setError] = useState(false)
@@ -565,6 +952,7 @@ window.__ModuleLoader__.load({
565
952
  const [panelMaxHeight, setPanelMaxHeight] = useState('70vh')
566
953
  const [panelShift, setPanelShift] = useState(0)
567
954
  const pillRef = useRef(null)
955
+ const panelRef = useRef(null)
568
956
 
569
957
  useEffect(() => {
570
958
  try { if (window.localStorage.getItem('token-dash-hint-seen') !== '1') setHint(true) } catch { /* ignore */ }
@@ -573,7 +961,7 @@ window.__ModuleLoader__.load({
573
961
  const load = useCallback(async () => {
574
962
  setRefreshing(true)
575
963
  try {
576
- const data = await getJson('/summary')
964
+ const data = await getJson(summaryPath(active))
577
965
  setSummary(data)
578
966
  setError(false)
579
967
  if (Number.isFinite(data?.refreshMs) && data.refreshMs !== refreshMs) setRefreshMs(data.refreshMs)
@@ -582,17 +970,14 @@ window.__ModuleLoader__.load({
582
970
  } finally {
583
971
  setRefreshing(false)
584
972
  }
585
- }, [refreshMs])
973
+ }, [refreshMs, active])
586
974
 
587
975
  useEffect(() => {
588
976
  getJson('/prefs').then((prefs) => setRefreshMs(prefs.refreshMs ?? 60000)).catch(() => {})
589
977
  }, [])
590
978
 
591
- useEffect(() => {
592
- load()
593
- const timer = setInterval(load, refreshMs)
594
- return () => clearInterval(timer)
595
- }, [load, refreshMs])
979
+ useEffect(() => { load() }, [load])
980
+ usePolling(load, { refreshMs })
596
981
 
597
982
  const refreshSubs = useCallback(async () => {
598
983
  try { await fetch(`${API}/providers/refresh`, { method: 'POST', headers: { accept: 'application/json' } }) } catch { /* fall through */ }
@@ -610,16 +995,19 @@ window.__ModuleLoader__.load({
610
995
  const measurePanel = useCallback(() => {
611
996
  const rect = pillRef.current?.getBoundingClientRect()
612
997
  if (rect === undefined) return
613
- const width = Math.min(360, window.innerWidth - 16)
998
+ const measured = panelRef.current?.getBoundingClientRect().width
999
+ const width = Math.round(Number.isFinite(measured) && measured > 0
1000
+ ? measured
1001
+ : Math.min(480, window.innerWidth - 16))
614
1002
  setPanelShift(Math.min(0, window.innerWidth - 8 - rect.left - width))
615
1003
  const available = Math.round(rect.top) - 16
616
1004
  setPanelMaxHeight(`${Math.max(200, Math.min(window.innerHeight * 0.7, available))}px`)
617
1005
  }, [])
618
1006
  useEffect(() => {
619
- if (!open) return
620
- const node = pillRef.current
1007
+ if (!open) return undefined
621
1008
  const observer = typeof ResizeObserver === 'function' ? new ResizeObserver(() => measurePanel()) : null
622
- if (node !== null) observer?.observe(node)
1009
+ if (pillRef.current !== null) observer?.observe(pillRef.current)
1010
+ if (panelRef.current !== null) observer?.observe(panelRef.current)
623
1011
  window.addEventListener('resize', measurePanel)
624
1012
  const raf = requestAnimationFrame(measurePanel)
625
1013
  const timer = setTimeout(measurePanel, 120)
@@ -632,7 +1020,11 @@ window.__ModuleLoader__.load({
632
1020
  }, [open, summary, measurePanel])
633
1021
  const toggle = () => {
634
1022
  dismissHint()
635
- if (!open) measurePanel()
1023
+ if (!open) {
1024
+ const updatedAt = Number(summary?.updatedAt)
1025
+ if (!Number.isFinite(updatedAt) || Date.now() - updatedAt > STALE_MS) void load()
1026
+ requestAnimationFrame(measurePanel)
1027
+ }
636
1028
  setOpen((value) => !value)
637
1029
  }
638
1030
 
@@ -643,28 +1035,39 @@ window.__ModuleLoader__.load({
643
1035
  let ariaText = tr('按量 API')
644
1036
  if (current?.kind === 'subscription') {
645
1037
  prefix = `[${tr('订阅')}]`
646
- bodyNodes = [h('span', { key: 'windows' }, ...subscriptionNodes(current, true))]
1038
+ bodyNodes = subscriptionNodes(current)
647
1039
  ariaText = tr('{name},订阅,账户套餐,{value}', { name: current.name, value: subscriptionText(current) })
648
1040
  } else if (current !== undefined) {
649
1041
  const budget = current.budget
650
1042
  const hasBudget = budget !== undefined && budget.state !== 'unset' && budget.amount > 0
1043
+ const percent = hasBudget ? Number(budget.percent) * 100 : null
651
1044
  const balance = balanceText(current, summary?.showBalance)
652
1045
  bodyNodes = [
653
- h('span', { key: 'budget' }, `${tr('预算')} `, hasBudget
654
- ? h('b', { style: { ...styles.num, color: budgetColor(budget.state) } }, fmtRatio(budget.percent))
655
- : tr('未设置')),
656
- h('span', { key: 'today' }, tr('今日 {value}', { value: fmtMoney(current.usage?.todayCost, current.currency) })),
657
- balance === null ? null : h('span', { key: 'balance' }, tr('余额 {value}', { value: balance })),
1046
+ h('span', { key: 'budget', style: styles.inlineWrap },
1047
+ h('span', { 'data-td-label': true, style: styles.summaryLabel }, tr('预算')),
1048
+ h(InlineRing, {
1049
+ percent: hasBudget ? percent : null,
1050
+ state: hasBudget ? stateOf(percent, API_CRITICAL) : 'empty',
1051
+ size: 14, stroke: 2,
1052
+ text: hasBudget ? fmtRatio(budget.percent) : tr('未设置'),
1053
+ testid: 'token-dash-pill-ring-budget',
1054
+ })),
1055
+ h('span', { key: 'today', style: styles.inlineWrap },
1056
+ h('span', { 'data-td-label': true, style: styles.summaryLabel }, tr('今日')),
1057
+ h('span', { style: styles.num }, fmtMoney(current.usage?.todayCost, current.currency))),
1058
+ balance === null ? null : h('span', { key: 'balance', style: styles.inlineWrap },
1059
+ h('span', { 'data-td-label': true, style: styles.summaryLabel }, tr('余额')),
1060
+ h('span', { style: styles.num }, balance)),
658
1061
  ].filter(Boolean)
659
1062
  ariaText = tr('{name},按量 API,{budget},今日 {today}{balance}', { name: current.name, budget: hasBudget ? tr('预算已用 {value}', { value: fmtRatio(budget.percent) }) : tr('预算未设置'), today: fmtMoney(current.usage?.todayCost, current.currency), balance: balance === null ? '' : `,${tr('余额 {value}', { value: balance })}` })
660
1063
  }
661
1064
  const hoverTitle = tr('{name} · {action} Token 看板', { name: current?.name ?? '', action: open ? tr('收起') : tr('展开') })
662
1065
 
663
1066
  return h('div', { style: styles.pillWrap },
664
- h('style', null, SPIN_CSS),
1067
+ h('style', null, TD_CSS),
665
1068
  hint && !open ? h('span', { style: styles.hint, role: 'status' }, tr('点击查看 Token 看板')) : null,
666
1069
  h('span', {
667
- ref: pillRef, 'data-testid': 'token-dash-pill',
1070
+ ref: pillRef, 'data-testid': 'token-dash-pill', 'data-td-pill': true,
668
1071
  style: { ...styles.pill, ...(hover || open ? styles.pillHover : {}) },
669
1072
  onClick: toggle, onMouseEnter: () => setHover(true), onMouseLeave: () => setHover(false),
670
1073
  onFocus: () => setHover(true), onBlur: () => setHover(false),
@@ -672,44 +1075,34 @@ window.__ModuleLoader__.load({
672
1075
  role: 'button', tabIndex: 0, 'aria-expanded': open, 'aria-haspopup': 'dialog',
673
1076
  'aria-label': tr('Token 看板:{text}', { text: ariaText }), title: hoverTitle,
674
1077
  }, h('span', { key: 'prefix', style: styles.num }, prefix), ...bodyNodes,
675
- h('span', { key: 'chevron', style: styles.chevron }, open ? '⌄' : '⌃')),
1078
+ h('span', { key: 'chevron', style: styles.chevron },
1079
+ h(Icon, { name: 'chevron', size: 12, style: { transform: open ? 'rotate(180deg)' : 'none', transition: 'transform 120ms' } }))),
676
1080
  open ? h(Panel, {
677
- summary, error, refreshing, maxHeight: panelMaxHeight, left: panelShift, hasUpdate,
678
- onRefresh: load, onRefreshSubs: refreshSubs, onClose: closePanel,
1081
+ summary, error, refreshing, maxHeight: panelMaxHeight, left: panelShift, active,
1082
+ panelRef, onRefresh: load, onRefreshSubs: refreshSubs, onClose: closePanel,
679
1083
  }) : null)
680
1084
  }
681
1085
 
682
- function PanelHeader({ tab, onTab, onRefresh, refreshing, onClose, showInfo, stale = false, hasUpdate = false }) {
683
- const settingsLabel = h('span', { style: { display: 'inline-flex', alignItems: 'center', gap: 4 } },
684
- tr('设置'),
685
- hasUpdate ? h('span', {
686
- 'aria-hidden': true,
687
- style: { width: 4, height: 4, borderRadius: 999, background: T.accent },
688
- }) : null)
1086
+ function PanelHeader({ onRefresh, refreshing, onClose, stale = false }) {
689
1087
  return h('div', { style: styles.header },
690
- h('div', { style: styles.headerTabs }, h(Segmented, {
691
- value: tab, onChange: onTab, label: tr('看板页面'),
692
- options: [{ value: 'usage', label: tr('用量') }, { value: 'settings', label: settingsLabel }],
693
- })),
694
- h('div', { style: styles.headerActions },
695
- showInfo ? h(InfoTip, {
1088
+ h('b', { style: styles.title }, tr('当前模型')),
1089
+ h('div', { style: { ...styles.headerActions, marginInlineEnd: -5 } },
1090
+ h(InfoTip, {
696
1091
  label: tr('查看支持的 API Key 范围'),
697
1092
  text: tr('目前支持 DeepSeek / Kimi / GLM / OpenRouter / Qwen API Key'),
698
- }) : null,
1093
+ }),
699
1094
  h(IconButton, {
700
1095
  label: tr('刷新'), testid: 'token-dash-refresh', disabled: refreshing, onClick: onRefresh, dot: stale,
701
1096
  }, h(Icon, { name: refreshing ? 'loader' : 'refresh', size: 13 })),
702
1097
  h(IconButton, { label: tr('关闭'), testid: 'token-dash-close', onClick: onClose }, h(Icon, { name: 'close', size: 13 }))))
703
1098
  }
704
1099
 
705
- function Panel({ summary, error, refreshing, maxHeight, left = 0, hasUpdate = false, onRefresh, onRefreshSubs, onClose }) {
706
- const [tab, setTab] = useState('usage')
1100
+ function Panel({ summary, error, refreshing, maxHeight, left = 0, panelRef, onRefresh, onClose }) {
707
1101
  const [range, setRange] = useState('today')
708
1102
  const [usage, setUsage] = useState(null)
709
1103
  const [usageLoading, setUsageLoading] = useState(false)
710
1104
  const [usageError, setUsageError] = useState(false)
711
1105
  const [panelError, setPanelError] = useState(false)
712
- const panelRef = useRef(null)
713
1106
 
714
1107
  const usageSeq = useRef(0)
715
1108
  const loadUsage = useCallback(async () => {
@@ -728,189 +1121,188 @@ window.__ModuleLoader__.load({
728
1121
  }
729
1122
  }, [range])
730
1123
 
731
- useEffect(() => { if (tab === 'usage') loadUsage() }, [tab, loadUsage])
1124
+ useEffect(() => { loadUsage() }, [loadUsage])
732
1125
  useEffect(() => { setPanelError(error === true) }, [error])
733
1126
 
734
1127
  useEffect(() => {
735
1128
  const onDown = (event) => {
736
- const node = panelRef.current
737
- if (node === null || node.contains(event.target)) return
1129
+ const node = panelRef?.current
1130
+ if (node === null || node === undefined || node.contains(event.target)) return
738
1131
  const wrap = node.parentElement
739
1132
  if (wrap !== null && wrap.contains(event.target)) return
740
1133
  onClose()
741
1134
  }
742
1135
  document.addEventListener('mousedown', onDown)
743
1136
  return () => document.removeEventListener('mousedown', onDown)
1137
+ }, [onClose, panelRef])
1138
+
1139
+ useEffect(() => {
1140
+ const onKey = (event) => { if (event.key === 'Escape') onClose() }
1141
+ document.addEventListener('keydown', onKey)
1142
+ return () => document.removeEventListener('keydown', onKey)
744
1143
  }, [onClose])
745
1144
 
746
1145
  const refreshAll = useCallback(async () => {
747
1146
  await onRefresh?.()
748
- if (tab === 'usage') await loadUsage()
749
- }, [onRefresh, tab, loadUsage])
750
-
751
- const body = tab === 'usage'
752
- ? h(UsageContent, {
753
- summary, usage, range, loading: usageLoading, usageError, error: panelError,
754
- onRange: setRange, onRetry: refreshAll, onRefreshSubs,
755
- })
756
- : h(SettingsContent, { summary, onRefresh, onRefreshSubs })
1147
+ await loadUsage()
1148
+ }, [onRefresh, loadUsage])
757
1149
 
1150
+ const providers = summary?.providers ?? []
1151
+ const current = providers.find((provider) => provider.id === summary?.currentProviderId) ?? providers[0]
1152
+ const models = Array.isArray(usage?.models) ? usage.models : []
1153
+ const scoped = models.filter((model) => model.providerId === current?.id)
1154
+ const rows = scoped.length > 0 ? scoped : models
1155
+ const updated = fmtClock(summary?.updatedAt)
758
1156
  const stale = Number.isFinite(summary?.updatedAt)
759
1157
  && Date.now() - summary.updatedAt > (Number(summary?.refreshMs) || 60000) * 2
1158
+ // 布局服务可用就显示入口;注册时序可能导致 hasMainPanel 暂时为 false,点击时再判。
1159
+ const canOpen = layoutRef !== null
1160
+
1161
+ const strip = error || usageError
1162
+ ? h('div', { style: styles.errorStrip, role: 'alert' },
1163
+ h('span', null, error ? tr('刷新失败,保留上次数据') : tr('范围数据加载失败')),
1164
+ h('button', { type: 'button', style: styles.button, onClick: refreshAll }, tr('重试')))
1165
+ : null
1166
+
1167
+ let body
1168
+ if (summary === null) {
1169
+ body = h('div', { style: styles.empty }, panelError ? tr('Token 数据不可用') : tr('Token 数据加载中…'))
1170
+ } else if (current === undefined) {
1171
+ const degraded = summary?.providersDegraded === true
1172
+ body = h('div', { style: styles.empty },
1173
+ degraded ? tr('供应商探测失败') : tr('未检测到已配置供应商'),
1174
+ degraded ? h('button', { type: 'button', style: styles.button, onClick: refreshAll }, tr('重试')) : null)
1175
+ } else {
1176
+ body = h(React.Fragment, null,
1177
+ current.kind === 'subscription'
1178
+ ? h(P2Windows, { provider: current })
1179
+ : h(P2Summary, { provider: current, summary }),
1180
+ h('div', { style: { marginTop: 12, ...styles.rangeCapsule } }, h(Segmented, {
1181
+ value: range, onChange: setRange, label: tr('时间范围'),
1182
+ options: RANGES.map(([value, label]) => ({ value, label: tr(label) })),
1183
+ })),
1184
+ strip,
1185
+ usage === null && usageLoading
1186
+ ? h('div', { style: styles.empty }, tr('范围数据加载中…'))
1187
+ : h(TokenTable, { rows }),
1188
+ h('div', { style: styles.footer },
1189
+ h('span', { 'data-testid': 'token-dash-updated', style: { color: T.weak, fontSize: 12 } },
1190
+ updated === null ? '' : tr('更新于 {time}', { time: updated })),
1191
+ canOpen
1192
+ ? h('button', {
1193
+ type: 'button', 'data-td-btn': true, 'data-testid': 'token-dash-open-board',
1194
+ style: styles.button, onClick: openBoardPage,
1195
+ }, tr('全量看板'))
1196
+ : null))
1197
+ }
1198
+
760
1199
  return h('div', {
761
1200
  ref: panelRef, tabIndex: -1, role: 'dialog', 'aria-label': tr('Token 看板'),
762
1201
  'data-testid': 'token-dash-panel',
763
1202
  style: { ...styles.panel, maxHeight, left },
764
1203
  },
765
- h(PanelHeader, {
766
- tab, onTab: setTab, onRefresh: refreshAll, refreshing: refreshing || usageLoading,
767
- onClose, showInfo: tab === 'usage', stale, hasUpdate,
768
- }),
1204
+ h(PanelHeader, { onRefresh: refreshAll, refreshing: refreshing || usageLoading, onClose, stale }),
769
1205
  body)
770
1206
  }
771
1207
 
772
- function BudgetRow({ provider }) {
773
- const budget = provider.budget
774
- const hasBudget = budget !== undefined && budget.state !== 'unset' && budget.amount > 0
775
- const color = budgetColor(budget?.state)
776
- return h('div', { 'data-testid': `token-dash-api-row-${provider.id}`, style: styles.budgetRow },
777
- h('div', { style: styles.budgetHead },
778
- h('span', { style: styles.budgetName, title: provider.name }, provider.name),
779
- h('span', { style: { color, fontWeight: 600, fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' } },
780
- hasBudget ? fmtRatio(budget.percent) : tr('未设置')),
781
- h('span', { 'data-testid': `token-dash-budget-cost-${provider.id}`, style: { color: T.muted, fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' } },
782
- hasBudget ? `${fmtMoney(budget.used, provider.currency)}/${fmtMoney(budget.amount, provider.currency)}` : '—'),
783
- h('span', { 'data-testid': `token-dash-budget-balance-${provider.id}`, style: { textAlign: 'left', color: T.muted, fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' } },
784
- `${tr('余额 {value}', { value: balanceText(provider, true) ?? '—' })}`)),
785
- h('div', { 'data-testid': `token-dash-budget-bar-${provider.id}` },
786
- h(MiniBar, { ratio: hasBudget ? budget.percent : 1, neutral: !hasBudget, stretch: true })))
787
- }
788
-
789
- /** 重置时间标准块:`3 小时后 · 11-03 20:15 重置`,P2 订阅行与 P3 共用。 */
790
- function ResetLabel({ ts, style }) {
1208
+ /** 重置时间标准块:P2 带「重置」,P3 传 suffix='' 只用两段。 */
1209
+ function ResetLabel({ ts, suffix = tr('重置'), style }) {
791
1210
  const text = fmtReset(ts)
792
1211
  if (text === null) return null
793
- return h('span', { 'data-testid': 'token-dash-reset', style: style ?? { marginLeft: 'auto', color: T.weak, fontSize: 10.5 } },
794
- `${text} ${tr('重置')}`)
1212
+ return h('span', {
1213
+ 'data-testid': 'token-dash-reset',
1214
+ style: style ?? { marginLeft: 'auto', color: T.weak, fontSize: 12 },
1215
+ }, suffix === '' ? text : `${text} ${suffix}`)
795
1216
  }
796
1217
 
797
- function QuotaRow({ provider, reset = false, heading = true }) {
798
- const windows = Array.isArray(provider.windows) ? provider.windows : []
799
- const resetTs = reset && windows.length > 0 ? windows[windows.length - 1].resetAt : null
800
- const resetNode = resetTs === null ? null : h(ResetLabel, { ts: resetTs })
801
- return h('div', { 'data-testid': `token-dash-sub-row-${provider.id}`, style: { display: 'grid', gap: 2, padding: '2px 0' } },
802
- heading ? h('div', { style: { display: 'flex', alignItems: 'center', gap: 6 } },
803
- h('span', { style: styles.quotaName, title: provider.name }, provider.name),
804
- resetNode) : null,
805
- windows.length === 0
806
- ? h('span', { style: styles.muted }, tr('套餐查询失败'))
807
- : h('div', {
808
- 'data-testid': `token-dash-quota-windows-${provider.id}`,
809
- style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, flexWrap: 'wrap' },
1218
+ /** P2 API 主区:环+% / 已用·预算 / 真实余额 / 本月已花。 */
1219
+ function P2Summary({ provider, summary }) {
1220
+ const budget = provider.budget
1221
+ const hasBudget = budget !== undefined && budget.state !== 'unset' && budget.amount > 0
1222
+ const percent = hasBudget ? Number(budget.percent) * 100 : null
1223
+ const balance = balanceText(provider, summary?.showBalance)
1224
+ return h(React.Fragment, null,
1225
+ h('div', { style: styles.providerLine },
1226
+ h('span', { style: styles.title, title: provider.name }, provider.name),
1227
+ h('span', { style: styles.providerChip }, `[ ${tr('按量 API')} ]`)),
1228
+ h('div', { 'data-testid': 'token-dash-summary-row', style: styles.summaryRow },
1229
+ h('span', { style: styles.summaryCell },
1230
+ h(InlineRing, {
1231
+ percent: hasBudget ? percent : null,
1232
+ state: hasBudget ? stateOf(percent, API_CRITICAL) : 'empty',
1233
+ size: 20, stroke: 2.5,
1234
+ testid: 'token-dash-summary-ring',
1235
+ })),
1236
+ h('span', { 'data-testid': 'token-dash-summary-used', style: styles.summaryCell },
1237
+ h('span', { style: styles.summaryLabel }, tr('已用 / 预算')),
1238
+ h('span', { style: styles.summaryValue },
1239
+ hasBudget ? `${fmtMoney(budget.used, provider.currency)} / ${fmtMoney(budget.amount, provider.currency)}` : '—')),
1240
+ h('span', {
1241
+ 'data-testid': 'token-dash-summary-balance', style: styles.summaryCell,
1242
+ title: tr('账户真实余额,不受预算影响'),
1243
+ },
1244
+ h('span', { style: styles.summaryLabel }, tr('真实余额')),
1245
+ h('span', { style: styles.summaryValue }, balance ?? '—')),
1246
+ h('span', {
1247
+ 'data-testid': 'token-dash-summary-month',
1248
+ style: { ...styles.summaryCell, alignItems: 'flex-end', textAlign: 'right' },
1249
+ title: tr('本月累计消耗,等于已用/预算 的分子'),
810
1250
  },
811
- ...windows.map((plan) => h('span', { key: plan.key, style: { display: 'inline-flex', alignItems: 'center', gap: 4 } },
812
- h('span', { style: { color: T.muted } }, windowLabel(plan.key)),
813
- h('b', { style: { color: percentColor(plan.usedPercent ?? 0), fontVariantNumeric: 'tabular-nums', display: 'inline-block', minWidth: 34 } }, fmtPercent(plan.usedPercent)),
814
- h(MiniBar, { ratio: (Number(plan.usedPercent) || 0) / 100 })))))
1251
+ h('span', { style: styles.summaryLabel }, tr('本月已花')),
1252
+ h('span', { style: styles.summaryValue }, fmtMoney(provider.usage?.monthCost, provider.currency)))))
815
1253
  }
816
1254
 
817
- function DetailGroup({ rows }) {
818
- return h('div', { style: styles.group },
819
- h('div', { style: styles.groupName }, rows[0]?.providerName ?? rows[0]?.providerId ?? ''),
820
- ...rows.map((model) => h('div', { key: `${model.providerId}:${model.modelId}`, style: { display: 'grid', gap: 1 } },
821
- h('div', { style: styles.modelRow },
822
- h('span', { style: styles.modelName, title: model.displayName ?? model.modelId }, model.displayName ?? model.modelId),
823
- model.kind === 'api'
824
- ? h('span', { style: styles.modelCost }, model.priced === false
825
- ? tr('未定价')
826
- : `${model.approximate === true ? '≈' : ''}${fmtMoney(model.cost, model.currency)}`)
827
- : null),
828
- h('div', { 'data-testid': 'token-dash-usage-line', style: styles.usageLine },
829
- h('span', { style: styles.usagePrimary },
830
- h('span', { style: styles.usageLabel }, 'Tokens '),
831
- h('span', { style: styles.usageValue }, fmtTokens(model.tokens?.total ?? 0)),
832
- h('span', { style: { ...styles.usageValue, color: T.muted } },
833
- ` [${fmtTokens(model.tokens?.input ?? 0)}/${fmtTokens(model.tokens?.cache ?? 0)}/${fmtTokens(model.tokens?.output ?? 0)}]`)),
834
- h('span', { style: { ...styles.usageMeta, marginLeft: 'auto' } },
835
- h('span', { style: styles.usageLabel }, `${tr('请求')} `), h('span', { style: styles.usageValue }, model.requests)),
836
- h('span', { style: styles.usageMeta },
837
- h('span', { style: styles.usageLabel }, `${tr('命中')} `), h('span', { style: styles.usageValue }, model.hitRate === null || model.hitRate === undefined ? '—' : fmtRatio(model.hitRate)))))))
1255
+ /** P2 订阅窗口行:两段数字 + 倒计时 + 绝对时间(无「重置」后缀)。 */
1256
+ function WindowRow({ providerId, plan, align = 'left' }) {
1257
+ const percent = plan === undefined || plan === null ? null : Number(plan.usedPercent)
1258
+ const hasValue = Number.isFinite(percent)
1259
+ const parts = hasValue ? resetParts(plan.resetAt) : { relative: null, absolute: null }
1260
+ const left = hasValue ? Math.max(0, Math.round(100 - percent)) : null
1261
+ const testKey = `${providerId}-${plan?.key ?? 'none'}`
1262
+ return h('div', {
1263
+ 'data-testid': `token-dash-sub-window-${testKey}`,
1264
+ title: parts.absolute ?? undefined,
1265
+ style: {
1266
+ display: 'flex', flexDirection: 'column', gap: 2, minWidth: 0,
1267
+ alignItems: align === 'right' ? 'flex-end' : align === 'center' ? 'center' : 'flex-start',
1268
+ textAlign: align,
1269
+ justifySelf: align === 'right' ? 'end' : align === 'center' ? 'center' : 'start',
1270
+ },
1271
+ },
1272
+ h('span', { style: { display: 'inline-flex', alignItems: 'center', gap: 4, whiteSpace: 'nowrap' } },
1273
+ h('span', { style: styles.summaryLabel }, plan?.key ? windowLabel(plan.key) : '—'),
1274
+ h(InlineRing, {
1275
+ percent, state: hasValue ? stateOf(percent, SUB_CRITICAL) : 'empty', size: 20, stroke: 2.5,
1276
+ })),
1277
+ h('span', {
1278
+ 'data-testid': `token-dash-sub-left-${testKey}`,
1279
+ style: { fontSize: 11, color: T.muted, whiteSpace: 'nowrap' },
1280
+ },
1281
+ left === null ? '—' : tr('剩余 {value}', { value: `${left}%` }),
1282
+ ' · ',
1283
+ h('span', { 'data-testid': `token-dash-sub-rel-${testKey}` }, parts.relative ?? '—')))
838
1284
  }
839
1285
 
840
- function UsageContent({ summary, usage, range, loading, usageError, error, onRange, onRetry, onRefreshSubs }) {
841
- if (summary === null) {
842
- return h('div', { style: styles.section },
843
- h('div', { style: styles.empty }, error ? tr('Token 数据不可用') : tr('Token 数据加载中…')),
844
- error ? h('button', { type: 'button', style: styles.button, onClick: onRetry }, tr('重试')) : null)
845
- }
846
- const providers = summary?.providers ?? []
847
- const api = providers.filter((provider) => provider.kind === 'api')
848
- const subscriptions = providers.filter((provider) => provider.kind === 'subscription')
849
- const models = Array.isArray(usage?.models) ? usage.models : []
850
- const groups = new Map()
851
- for (const model of models) {
852
- const list = groups.get(model.providerId) ?? []
853
- list.push(model)
854
- groups.set(model.providerId, list)
855
- }
856
- const pending = usage === null
857
- const total = usage?.total ?? null
858
- const costEntries = Object.entries(usage?.totals ?? {})
859
- const hasUsage = usage !== null
860
- const fixed = []
861
- if (api.length > 0) {
862
- fixed.push(h('div', { key: 'api-head', style: styles.sectionHead }, h('b', { style: styles.title }, tr('本月预算'))))
863
- fixed.push(...api.map((provider) => h(BudgetRow, { key: provider.id, provider })))
864
- }
865
- if (subscriptions.length > 0) {
866
- fixed.push(h('div', { key: 'sub-head', style: { ...styles.sectionHead, marginTop: 4 } },
867
- h('b', { style: styles.title }, tr('订阅套餐(账户级)')),
868
- h(IconButton, { label: tr('重新检测订阅配额'), testid: 'token-dash-rescan', onClick: () => { void onRefreshSubs?.() } },
869
- h(Icon, { name: 'refresh', size: 12 }))))
870
- fixed.push(...subscriptions.map((provider) => h(QuotaRow, { key: provider.id, provider, reset: true })))
871
- }
872
- if (fixed.length === 0) {
873
- const degraded = summary?.providersDegraded === true
874
- fixed.push(h('div', { key: 'empty', style: styles.empty },
875
- degraded ? tr('供应商探测失败') : tr('未检测到已配置供应商'),
876
- degraded ? h('button', { type: 'button', style: styles.button, onClick: onRetry }, tr('重试')) : null))
877
- }
1286
+ function P2Windows({ provider }) {
1287
+ const windows = Array.isArray(provider.windows) ? provider.windows : []
878
1288
  return h(React.Fragment, null,
879
- h('div', { style: styles.section }, ...fixed),
880
- h('div', { style: { marginTop: 10 } }, h(Segmented, {
881
- value: range, onChange: onRange, label: tr('时间范围'),
882
- options: RANGES.map(([value, label]) => ({ value, label: tr(label) })),
883
- })),
884
- error || usageError ? h('div', { style: styles.errorStrip, role: 'alert' },
885
- h('span', null, error ? tr('刷新失败,保留上次数据') : tr('范围数据加载失败')),
886
- h('button', { type: 'button', style: styles.button, onClick: onRetry }, tr('重试'))) : null,
887
- h('div', { style: styles.section },
888
- h('div', { style: styles.rangeCard },
889
- h('div', { style: styles.tile },
890
- h('div', { style: styles.tileLabel }, tr('总费用')),
891
- ...costEntries.map(([currency, value]) => h('div', { key: currency, style: { ...styles.tileValue, fontSize: 14, color: T.accent } }, fmtMoney(value.cost, currency))),
892
- pending ? h('div', { key: 'pending', style: { ...styles.tileValue, fontSize: 14, color: T.accent } }, '—') : null),
893
- h('div', { style: styles.tile },
894
- h('div', { style: styles.tileLabel },
895
- `${tr('真实 Tokens')} `,
896
- h(InfoTip, {
897
- label: tr('Tokens 括号说明'),
898
- text: tr('Tokens 括号顺序:输入 / 缓存(读+写)/ 输出'),
899
- variant: 'inline',
900
- }, h(Icon, { name: 'info', size: 11 }))),
901
- h('div', { style: styles.tileValue }, pending ? '—' : fmtTokens(total?.tokens ?? 0)),
902
- h('div', { style: styles.tileDetail }, pending
903
- ? '—'
904
- : `${fmtTokens(total?.input ?? 0)} · ${fmtTokens(total?.cache ?? 0)} · ${fmtTokens(total?.output ?? 0)}`))),
905
- !hasUsage && loading ? h('div', { style: styles.empty }, tr('范围数据加载中…')) : null,
906
- hasUsage && models.length === 0 ? h('div', { style: styles.empty }, tr('范围内暂无消耗')) : null,
907
- hasUsage && models.length > 0 ? [...groups.entries()].map(([providerId, rows]) => h(DetailGroup, { key: providerId, rows })) : null))
1289
+ h('div', { style: styles.providerLine },
1290
+ h('span', { style: styles.title, title: provider.name }, provider.name),
1291
+ h('span', { style: styles.providerChip }, `[ ${tr('订阅')} ]`)),
1292
+ windows.length === 0
1293
+ ? h('div', { style: styles.empty }, tr('套餐查询失败'))
1294
+ : h('div', {
1295
+ style: { display: 'grid', gridTemplateColumns: 'repeat(3, minmax(0, 1fr))', gap: 12 },
1296
+ }, windows.map((plan, index) => h(WindowRow, {
1297
+ key: plan.key,
1298
+ providerId: provider.id,
1299
+ plan,
1300
+ align: ['left', 'center', 'right'][index] ?? 'left',
1301
+ }))))
908
1302
  }
909
1303
 
910
- function SettingsContent({ summary, onRefresh, onRefreshSubs }) {
911
- const [prefs, setPrefs] = useState(null)
912
- const [budgetText, setBudgetText] = useState({})
913
- const [fieldErrors, setFieldErrors] = useState({})
1304
+ /** P3 底部胶囊:三行设置;prefs 由 BoardPage 持有。 */
1305
+ function SettingsRows({ summary, prefs, onSave, onRefresh, onRefreshSubs }) {
914
1306
  const [status, setStatus] = useState(null)
915
1307
  const [subRefreshing, setSubRefreshing] = useState(false)
916
1308
  const update = useUpdateSnapshot()
@@ -918,61 +1310,22 @@ window.__ModuleLoader__.load({
918
1310
  const [importing, setImporting] = useState(false)
919
1311
  const fileRef = useRef(null)
920
1312
 
921
- const loadPrefs = useCallback(async () => {
922
- try {
923
- const data = await getJson('/prefs')
924
- setPrefs(data)
925
- const next = {}
926
- for (const [id, value] of Object.entries(data.budgets ?? {})) next[id] = value.amount > 0 ? String(value.amount) : ''
927
- setBudgetText(next)
928
- } catch {
929
- setStatus({ text: tr('设置加载失败'), error: true })
930
- }
931
- }, [])
932
-
933
- useEffect(() => { loadPrefs() }, [loadPrefs])
934
-
935
1313
  function flash(text, error = false) {
936
1314
  setStatus({ text, error })
937
1315
  if (error !== true) setTimeout(() => setStatus((current) => (current?.text === text ? null : current)), 1600)
938
1316
  }
939
1317
 
940
1318
  async function savePrefs(patch) {
941
- if (prefs === null) return null
942
- try {
943
- const saved = await putPrefs({ ...prefs, ...patch })
944
- setPrefs(saved)
945
- flash(tr('已保存'))
946
- void onRefresh?.()
947
- return saved
948
- } catch (error) {
949
- setStatus({ text: tr('保存失败:{reason}', { reason: error.message }), error: true })
1319
+ const result = await onSave?.(patch)
1320
+ if (result?.ok !== true) {
1321
+ setStatus({ text: tr('保存失败:{reason}', { reason: result?.reason ?? 'unknown' }), error: true })
950
1322
  return null
951
1323
  }
1324
+ flash(tr('已保存'))
1325
+ return result.prefs
952
1326
  }
953
1327
 
954
- async function saveBudget(provider, raw) {
955
- const text = String(raw).trim()
956
- const budgets = { ...(prefs?.budgets ?? {}) }
957
- if (text === '') {
958
- // 显式 0:清空后不再被 DEFAULT_BUDGET 覆盖
959
- budgets[provider.id] = { amount: 0, currency: provider.currency }
960
- const saved = await savePrefs({ budgets })
961
- if (saved !== null) { setBudgetText((current) => ({ ...current, [provider.id]: '' })); setFieldErrors((current) => ({ ...current, [provider.id]: null })) }
962
- return
963
- }
964
- const amount = Number(text)
965
- if (!/^\d+(?:\.\d{1,2})?$/.test(text) || !Number.isFinite(amount) || amount > 9999999.99) {
966
- setFieldErrors((current) => ({ ...current, [provider.id]: tr('请输入 0 或正数') }))
967
- return
968
- }
969
- budgets[provider.id] = { amount, currency: provider.currency }
970
- const saved = await savePrefs({ budgets })
971
- if (saved !== null) {
972
- setBudgetText((current) => ({ ...current, [provider.id]: String(saved.budgets[provider.id]?.amount ?? '') }))
973
- setFieldErrors((current) => ({ ...current, [provider.id]: null }))
974
- }
975
- }
1328
+ const retryPrefs = () => { void onRefresh?.() }
976
1329
 
977
1330
  async function refreshSubscriptions() {
978
1331
  setSubRefreshing(true)
@@ -1044,7 +1397,6 @@ window.__ModuleLoader__.load({
1044
1397
  try {
1045
1398
  const bundle = JSON.parse(await file.text())
1046
1399
  const result = await postJson('/import', bundle)
1047
- await loadPrefs()
1048
1400
  await onRefresh?.()
1049
1401
  flash(tr('已导入 {month} 数据', { month: result.month }))
1050
1402
  } catch (error) {
@@ -1065,39 +1417,11 @@ window.__ModuleLoader__.load({
1065
1417
  if (prefs === null) {
1066
1418
  return h('div', { 'data-testid': 'token-dash-settings', style: { display: 'grid', gap: 10 } },
1067
1419
  h('div', { style: styles.empty }, status?.text ?? tr('设置加载中…')),
1068
- status?.error === true ? h('button', { type: 'button', style: styles.button, onClick: loadPrefs }, tr('重试')) : null)
1420
+ status?.error === true ? h('button', { type: 'button', style: styles.button, onClick: retryPrefs }, tr('重试')) : null)
1069
1421
  }
1070
1422
 
1071
- const providers = summary?.providers ?? []
1072
- const api = providers.filter((provider) => provider.kind === 'api')
1073
- const subscriptions = providers.filter((provider) => provider.kind === 'subscription')
1074
1423
  const version = summary?.version ?? ''
1075
1424
  const catalog = summary?.catalog
1076
- const section = (title, body, action = null, testid) => h('div', { 'data-testid': testid, style: styles.section },
1077
- h('div', { style: styles.sectionHead }, h('b', { style: styles.title }, title), action), body)
1078
-
1079
- const apiRows = api.map((provider) => h('div', { key: provider.id, style: { display: 'grid', gap: 3, padding: '3px 0' } },
1080
- h('div', { style: styles.row }, h('b', { style: styles.budgetName, title: provider.name }, provider.name), h('span', { style: styles.weak }, tr('按量 API'))),
1081
- h('div', { style: styles.row }, h('span', { style: styles.muted }, tr('月度预算')),
1082
- h('span', { style: styles.rowStart },
1083
- h('input', {
1084
- type: 'text', inputMode: 'decimal', 'data-testid': `token-dash-budget-input-${provider.id}`,
1085
- 'aria-label': tr('{name} 月度预算', { name: provider.name }), 'aria-invalid': fieldErrors[provider.id] !== undefined && fieldErrors[provider.id] !== null,
1086
- value: budgetText[provider.id] ?? String(provider.budget?.amount ?? ''), onChange: (event) => setBudgetText({ ...budgetText, [provider.id]: event.target.value }),
1087
- onBlur: (event) => saveBudget(provider, event.currentTarget.value),
1088
- onKeyDown: (event) => { if (event.key === 'Enter') { event.preventDefault(); event.currentTarget.blur() } },
1089
- style: { ...styles.input, borderColor: fieldErrors[provider.id] ? T.over : T.border },
1090
- }), h('span', { style: styles.muted }, provider.currency))),
1091
- fieldErrors[provider.id] ? h('div', { style: { color: T.over, fontSize: 10.5, textAlign: 'right' }, role: 'alert' }, fieldErrors[provider.id]) : null))
1092
-
1093
- const subRows = subscriptions.map((provider) => {
1094
- const windows = Array.isArray(provider.windows) ? provider.windows : []
1095
- const resetTs = windows.length > 0 ? windows[windows.length - 1].resetAt : null
1096
- return h('div', { key: provider.id, style: { padding: '3px 0' } },
1097
- h('div', { style: styles.row },
1098
- h('b', { style: styles.budgetName, title: provider.name }, provider.name),
1099
- resetTs === null ? null : h(ResetLabel, { ts: resetTs, style: styles.weak })))
1100
- })
1101
1425
 
1102
1426
  let updateControl
1103
1427
  const updateBusy = update.phase === 'checking' || update.phase === 'installing'
@@ -1127,45 +1451,371 @@ window.__ModuleLoader__.load({
1127
1451
  })))
1128
1452
  }
1129
1453
 
1130
- const statusText = update.text ?? status?.text ?? tr('版本 {version}', { version })
1131
- return h('div', { 'data-testid': 'token-dash-settings', style: { display: 'grid', gridTemplateColumns: 'minmax(0,1fr)', gap: 0, minWidth: 0 } },
1132
- api.length > 0 ? section(tr('API 计费'), h('div', null, ...apiRows)) : null,
1133
- subscriptions.length > 0 ? section(tr('订阅'),
1134
- h('div', null, ...subRows),
1135
- h(IconButton, { label: tr('重新检测订阅配额'), testid: 'token-dash-settings-rescan', disabled: subRefreshing, onClick: refreshSubscriptions }, h(Icon, { name: subRefreshing ? 'loader' : 'refresh', size: 12 }))) : null,
1136
- section(tr('显示'), h('div', { style: { display: 'grid', gap: 7 } },
1137
- h('div', { style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 } },
1138
- h('span', { style: { whiteSpace: 'nowrap' } }, tr('刷新间隔')),
1139
- h('div', { 'data-testid': 'token-dash-refresh-segment', style: { width: 168, flex: '0 1 168px', minWidth: 0 } }, h(Segmented, { value: prefs.refreshMs, onChange: (ms) => savePrefs({ refreshMs: ms }), label: tr('刷新间隔'), kind: 'radiogroup', options: REFRESH_OPTIONS.map(([value, label]) => ({ value, label: tr(label) })) }))),
1140
- h('div', { style: styles.row }, h('span', null, tr('账户余额')), h(Toggle, { checked: prefs.showBalance, label: tr('账户余额'), onChange: (next) => savePrefs({ showBalance: next }) })))),
1141
- section(tr('数据与日志'), [
1142
- h('div', { key: 'log', style: styles.row },
1143
- h('span', null, tr('日志')),
1144
- h('span', { style: styles.rowStart },
1145
- h('button', { type: 'button', 'data-testid': 'token-dash-log-open', style: styles.button, onClick: openLogs }, tr('打开日志文件夹')),
1146
- h('button', { type: 'button', 'data-testid': 'token-dash-log-export', style: styles.button, onClick: exportLogs }, tr('导出日志')))),
1147
- h('div', { key: 'data', style: styles.row },
1148
- h('span', null, tr('备份与恢复')),
1149
- h('span', { style: styles.rowStart },
1150
- h('button', { type: 'button', 'data-testid': 'token-dash-data-export', style: styles.button, onClick: () => { void exportData() } }, tr('导出数据')),
1151
- h('button', { type: 'button', 'data-testid': 'token-dash-data-import', disabled: importing, style: styles.button, onClick: () => fileRef.current?.click() }, importing ? tr('导入中…') : tr('导入数据')),
1152
- h('input', { ref: fileRef, type: 'file', accept: 'application/json', style: { display: 'none' }, onChange: (event) => { void importData(event.target.files?.[0]) } })))],
1153
- null, 'token-dash-data-log-section'),
1154
- section(tr('价格与版本'), h('div', { style: { display: 'grid', gap: 6 } },
1155
- h('div', { 'data-testid': 'token-dash-price-links', style: styles.priceLinks },
1156
- (summary?.pricingLinks ?? []).map((link) => h('a', { key: link.id ?? link.label, href: link.url, target: '_blank', rel: 'noopener', style: styles.link }, linkLabel(link)))),
1157
- h('div', { style: { ...styles.muted, fontSize: 10 } },
1158
- `${tr('价格表')} `, formatCatalogTime(catalog?.updatedAt), ' · ',
1159
- catalog?.url
1160
- ? h('a', { href: catalog.url, target: '_blank', rel: 'noopener', style: { ...styles.link, color: T.muted } }, tr('社区'))
1161
- : h('span', null, sourceLabel(catalog?.source))),
1162
- h('div', { style: styles.row }, h('span', { style: { ...styles.status, color: status?.error ? T.over : T.muted }, role: 'status', 'aria-live': 'polite', title: statusText }, statusText), updateControl)), null, 'token-dash-price-section'),
1163
- api.length === 0 && subscriptions.length === 0 ? h('div', { style: styles.empty }, tr('未检测到已配置供应商')) : null)
1454
+ const statusText = update.text ?? status?.text ?? ''
1455
+ return h('div', { 'data-testid': 'token-dash-settings', style: { display: 'grid', minWidth: 0 } },
1456
+ h('div', {
1457
+ 'data-testid': 'token-dash-settings-row-1',
1458
+ style: { ...styles.settingsRow, ...styles.settingsRowRefresh },
1459
+ },
1460
+ h('div', {
1461
+ 'data-testid': 'token-dash-settings-refresh-left',
1462
+ style: { ...styles.settingsGroup, ...styles.settingsGroupLeft },
1463
+ },
1464
+ h('span', { style: styles.settingsLabel }, tr('刷新间隔')),
1465
+ h('div', {
1466
+ 'data-testid': 'token-dash-refresh-segment',
1467
+ style: { width: 168, flex: '0 1 168px', minWidth: 0 },
1468
+ }, h(Segmented, {
1469
+ value: prefs.refreshMs, onChange: (ms) => savePrefs({ refreshMs: ms }), label: tr('刷新间隔'),
1470
+ kind: 'radiogroup', options: REFRESH_OPTIONS.map(([value, label]) => ({ value, label: tr(label) })),
1471
+ }))),
1472
+ h('div', {
1473
+ 'data-testid': 'token-dash-settings-refresh-right',
1474
+ style: { ...styles.settingsGroup, ...styles.settingsGroupRight },
1475
+ },
1476
+ h('span', { style: styles.settingsLabel }, tr('账户余额')),
1477
+ h(Toggle, { checked: prefs.showBalance, label: tr('账户余额'), onChange: (next) => savePrefs({ showBalance: next }) }))),
1478
+ h('div', { 'data-testid': 'token-dash-settings-row-2', style: styles.settingsRow },
1479
+ h('span', { style: styles.settingsLabel }, tr('日志')),
1480
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', minWidth: 0 } },
1481
+ h('button', { type: 'button', 'data-testid': 'token-dash-log-open', style: styles.ghost, onClick: openLogs }, tr('打开日志文件夹')),
1482
+ h('button', { type: 'button', 'data-testid': 'token-dash-log-export', style: styles.ghost, onClick: exportLogs }, tr('导出日志')),
1483
+ h('button', { type: 'button', 'data-testid': 'token-dash-data-export', style: styles.ghost, onClick: () => { void exportData() } }, tr('导出数据')),
1484
+ h('button', { type: 'button', 'data-testid': 'token-dash-data-import', disabled: importing, style: styles.ghost, onClick: () => fileRef.current?.click() }, importing ? tr('导入中…') : tr('导入数据')),
1485
+ h('input', { ref: fileRef, type: 'file', accept: 'application/json', style: { display: 'none' }, onChange: (event) => { void importData(event.target.files?.[0]) } }))),
1486
+ h('div', { 'data-testid': 'token-dash-settings-row-3', style: styles.settingsRow },
1487
+ h('span', { style: styles.settingsLabel }, tr('版本')),
1488
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', minWidth: 0 } },
1489
+ h('span', { style: { ...styles.muted, fontSize: 11 } },
1490
+ `v${version} · ${tr('价格表')} ${formatCatalogTime(catalog?.updatedAt)}`,
1491
+ catalog?.url
1492
+ ? h('a', { href: catalog.url, target: '_blank', rel: 'noopener', style: { ...styles.link, color: T.muted, marginLeft: 4 } }, tr('社区'))
1493
+ : h('span', { style: { marginLeft: 4 } }, sourceLabel(catalog?.source))),
1494
+ h('span', { style: { flex: 1 } }),
1495
+ h('span', {
1496
+ 'data-testid': 'token-dash-settings-status', role: 'status', 'aria-live': 'polite',
1497
+ style: { ...styles.status, color: status?.error ? T.over : T.muted }, title: statusText,
1498
+ }, statusText),
1499
+ updateControl)))
1500
+ }
1501
+
1502
+ /** P3 按量卡:每 provider 一张,竖排 Gauge + 常显预算输入 + 三行字段。 */
1503
+ function BudgetTable({ providers, prefs, onSave }) {
1504
+ const [errors, setErrors] = useState({})
1505
+ const [saving, setSaving] = useState(null)
1506
+
1507
+ const commit = async (provider, raw, input) => {
1508
+ const text = String(raw ?? '').trim()
1509
+ if (text !== '' && (!/^\d+(?:\.\d{1,2})?$/.test(text) || Number(text) > 9999999.99)) {
1510
+ setErrors((prev) => ({ ...prev, [provider.id]: tr('请输入 0 或正数') }))
1511
+ return
1512
+ }
1513
+ const amount = text === '' ? 0 : Number(text)
1514
+ if (input !== undefined && input !== null) input.value = amount > 0 ? amount.toFixed(2) : ''
1515
+ const budgets = { ...(prefs?.budgets ?? {}) }
1516
+ budgets[provider.id] = { amount, currency: provider.currency }
1517
+ setSaving(provider.id)
1518
+ const result = await onSave?.({ budgets })
1519
+ setSaving(null)
1520
+ if (result?.ok !== true) {
1521
+ setErrors((prev) => ({ ...prev, [provider.id]: tr('保存失败:{reason}', { reason: result?.reason ?? 'unknown' }) }))
1522
+ return
1523
+ }
1524
+ setErrors((prev) => {
1525
+ const next = { ...prev }
1526
+ delete next[provider.id]
1527
+ return next
1528
+ })
1529
+ if (input !== undefined && input !== null) input.value = amount > 0 ? amount.toFixed(2) : ''
1530
+ }
1531
+
1532
+ return h('div', { 'data-testid': 'token-dash-budget-table', style: styles.apiCards },
1533
+ ...providers.map((provider) => {
1534
+ const budget = provider.budget
1535
+ const hasBudget = budget !== undefined && budget.state !== 'unset' && budget.amount > 0
1536
+ const percent = hasBudget ? Number(budget.percent) * 100 : null
1537
+ const used = Number(budget?.used ?? 0)
1538
+ const plan = hasBudget ? Number(budget.amount) - used : null
1539
+ const balance = balanceText(provider, true)
1540
+ const entry = prefs?.budgets?.[provider.id]
1541
+ const initial = entry === undefined ? '' : (entry.amount > 0 ? entry.amount.toFixed(2) : '')
1542
+ const error = errors[provider.id]
1543
+ return h('div', {
1544
+ key: provider.id,
1545
+ 'data-testid': `token-dash-budget-row-${provider.id}`,
1546
+ style: styles.apiCard,
1547
+ },
1548
+ h('div', { style: styles.apiCardHead },
1549
+ h('span', { style: styles.apiCardName, title: provider.name }, provider.name),
1550
+ h('span', { style: styles.apiChip }, `[ ${tr('按量 API')} ]`)),
1551
+ h('div', { style: styles.apiGaugeWrap },
1552
+ h(QuotaGauge, {
1553
+ label: tr('已用'), percent,
1554
+ state: hasBudget ? stateOf(percent, API_CRITICAL) : 'empty',
1555
+ size: 40, stroke: 4,
1556
+ labelTestid: `token-dash-budget-gauge-label-${provider.id}`,
1557
+ percentTestid: `token-dash-budget-used-${provider.id}`,
1558
+ }),
1559
+ h('span', { style: styles.budgetLabel }, tr('月度预算')),
1560
+ h('div', { style: styles.budgetInputWrap },
1561
+ h('span', { style: { fontSize: 12, color: T.weak } }, provider.currency === 'USD' ? '$' : '¥'),
1562
+ h('input', {
1563
+ type: 'text', inputMode: 'decimal', disabled: saving === provider.id,
1564
+ 'data-testid': `token-dash-budget-input-${provider.id}`,
1565
+ 'aria-label': tr('{name} 月度预算', { name: provider.name }),
1566
+ 'aria-invalid': error !== undefined,
1567
+ defaultValue: initial,
1568
+ placeholder: tr('未设置'),
1569
+ onBlur: (event) => { void commit(provider, event.currentTarget.value, event.currentTarget) },
1570
+ onKeyDown: (event) => {
1571
+ if (event.key === 'Escape') {
1572
+ event.preventDefault()
1573
+ event.currentTarget.value = initial
1574
+ event.currentTarget.blur()
1575
+ return
1576
+ }
1577
+ if (event.key === 'Enter') {
1578
+ event.preventDefault()
1579
+ void commit(provider, event.currentTarget.value, event.currentTarget)
1580
+ event.currentTarget.blur()
1581
+ }
1582
+ },
1583
+ style: { ...styles.budgetInput, borderBottom: `1px solid ${error === undefined ? 'transparent' : T.over}` },
1584
+ })),
1585
+ error === undefined ? null : h('span', { style: { color: T.over, fontSize: 11 }, role: 'alert' }, error)),
1586
+ h('div', { style: styles.kvRow },
1587
+ h('span', { style: styles.kvLabel }, tr('计划余额')),
1588
+ h('span', {
1589
+ 'data-testid': `token-dash-budget-plan-${provider.id}`,
1590
+ style: { ...styles.kvValue, color: plan !== null && plan < 0 ? T.over : T.text },
1591
+ }, plan === null ? '—' : `${plan < 0 ? '-' : ''}${fmtMoney(Math.abs(plan), provider.currency)}`)),
1592
+ h('div', { style: styles.kvRow },
1593
+ h('span', { style: styles.kvLabel }, tr('真实余额')),
1594
+ h('span', { 'data-testid': `token-dash-budget-balance-${provider.id}`, style: styles.kvValue }, balance ?? '—')),
1595
+ h('div', { style: styles.kvRow },
1596
+ h('span', { style: styles.kvLabel }, tr('本月已花')),
1597
+ h('span', { 'data-testid': `token-dash-budget-month-${provider.id}`, style: styles.kvValue },
1598
+ fmtMoney(provider.usage?.monthCost, provider.currency))),
1599
+ h('div', { style: styles.cardCaption },
1600
+ `${hasBudget ? stateOf(percent, API_CRITICAL) : 'unset'} · ${hasBudget ? fmtRatio(budget.percent) : '—'}`))
1601
+ }))
1602
+ }
1603
+
1604
+ function QuotaCell({ providerId, plan, windowKey }) {
1605
+ const percent = plan === undefined ? null : Number(plan.usedPercent)
1606
+ const hasValue = Number.isFinite(percent)
1607
+ const parts = hasValue ? resetParts(plan.resetAt) : { relative: null, absolute: null }
1608
+ const left = hasValue ? Math.max(0, Math.round(100 - percent)) : null
1609
+ const testKey = `${providerId}-${windowKey}`
1610
+ return h(QuotaGauge, {
1611
+ testid: `token-dash-quota-cell-${testKey}`,
1612
+ label: windowLabel(windowKey),
1613
+ percent,
1614
+ state: hasValue ? stateOf(percent, SUB_CRITICAL) : 'empty',
1615
+ remaining: left === null ? '—' : tr('剩余 {value}', { value: `${left}%` }),
1616
+ relative: parts.relative ?? '—',
1617
+ absolute: parts.absolute ?? '—',
1618
+ remainingTestid: `token-dash-quota-left-${testKey}`,
1619
+ relativeTestid: `token-dash-quota-rel-${testKey}`,
1620
+ absoluteTestid: `token-dash-quota-abs-${testKey}`,
1621
+ })
1622
+ }
1623
+
1624
+ /** P3 订阅卡:每 provider 一张,窗口按实际数量一排等分。 */
1625
+ function QuotaTable({ providers }) {
1626
+ return h('div', { 'data-testid': 'token-dash-quota-table', style: styles.quotaCards },
1627
+ ...providers.map((provider) => {
1628
+ const windows = Array.isArray(provider.windows) ? provider.windows : []
1629
+ return h('div', {
1630
+ key: provider.id, 'data-testid': `token-dash-quota-row-${provider.id}`, style: styles.quotaCard,
1631
+ },
1632
+ h('div', { style: styles.apiCardHead },
1633
+ h('span', { style: styles.apiCardName, title: provider.name }, provider.name),
1634
+ h('span', { style: styles.apiChip }, `[ ${tr('订阅')} ]`)),
1635
+ windows.length === 0
1636
+ ? h('div', { style: styles.empty }, tr('套餐查询失败'))
1637
+ : h('div', {
1638
+ style: { ...styles.quotaWindows, gridTemplateColumns: `repeat(${windows.length}, minmax(0,1fr))` },
1639
+ }, windows.map((plan) => h(QuotaCell, {
1640
+ key: plan.key, providerId: provider.id, plan, windowKey: plan.key,
1641
+ }))),
1642
+ h('div', { style: styles.cardCaption }, `${windows.length} ${tr('窗')}`))
1643
+ }))
1644
+ }
1645
+
1646
+ /** 预算保存后就地重算 budget,避免等下一轮轮询。 */
1647
+ function mergeBudgets(summary, prefs) {
1648
+ const providers = (summary?.providers ?? []).map((provider) => {
1649
+ const entry = prefs?.budgets?.[provider.id]
1650
+ if (entry === undefined) return provider
1651
+ const amount = Number(entry.amount) || 0
1652
+ const used = Number(provider.budget?.used ?? provider.usage?.monthCost ?? 0)
1653
+ const percent = amount > 0 ? Math.min(9.99, used / amount) : 0
1654
+ const state = amount <= 0 ? 'unset' : percent >= 1 ? 'over' : percent >= 0.8 ? 'warn' : 'ok'
1655
+ return {
1656
+ ...provider,
1657
+ budget: { ...(provider.budget ?? {}), amount, used, remaining: Math.max(0, amount - used), percent, state, currency: provider.currency },
1658
+ }
1659
+ })
1660
+ return { ...summary, providers }
1661
+ }
1662
+
1663
+ const openBoardPage = () => {
1664
+ try {
1665
+ const layout = layoutRef ?? (typeof ctxRef?.get === 'function' ? ctxRef.get('layout') : null)
1666
+ if (layout === null || layout === undefined) return
1667
+ if (typeof layout.hasMainPanel === 'function' && layout.hasMainPanel(PAGE_ID) !== true) return
1668
+ layout.selectPanel?.(PAGE_ID)
1669
+ } catch { /* 宿主未注册时保持当前页 */ }
1670
+ }
1671
+
1672
+ function BoardEntry() {
1673
+ return h('span', {
1674
+ 'data-testid': 'token-dash-sidebar-entry', 'aria-hidden': true,
1675
+ style: { display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 16, height: 16 },
1676
+ }, h('svg', {
1677
+ width: 16, height: 16, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor',
1678
+ strokeWidth: 2, strokeLinecap: 'round', strokeLinejoin: 'round',
1679
+ },
1680
+ h('path', { d: 'M4 19V9' }), h('path', { d: 'M10 19V5' }), h('path', { d: 'M16 19v-6' }), h('path', { d: 'M2 19h20' })))
1681
+ }
1682
+
1683
+ /** P3 整页:自取数 + 两表 + 两格卡与明细 + 底部设置胶囊。 */
1684
+ function BoardPage(props) {
1685
+ const active = rawActiveProvider(props)
1686
+ const [summary, setSummary] = useState(null)
1687
+ const [usage, setUsage] = useState(null)
1688
+ const [prefs, setPrefs] = useState(null)
1689
+ const [range, setRange] = useState('all')
1690
+ const [refreshing, setRefreshing] = useState(false)
1691
+ const [error, setError] = useState(false)
1692
+ const [usageError, setUsageError] = useState(false)
1693
+ const prefsRef = useRef(null)
1694
+ prefsRef.current = prefs
1695
+
1696
+ const loadSummary = useCallback(async () => {
1697
+ try {
1698
+ const data = await getJson(summaryPath(active))
1699
+ setSummary(data)
1700
+ setError(false)
1701
+ } catch {
1702
+ setError(true)
1703
+ }
1704
+ }, [active])
1705
+
1706
+ const loadPrefs = useCallback(async () => {
1707
+ try { setPrefs(await getJson('/prefs')) } catch { /* keep previous */ }
1708
+ }, [])
1709
+
1710
+ const loadUsage = useCallback(async () => {
1711
+ try {
1712
+ const data = await getJson(`/usage?range=${encodeURIComponent(range)}`)
1713
+ setUsage(data)
1714
+ setUsageError(false)
1715
+ } catch {
1716
+ setUsageError(true)
1717
+ }
1718
+ }, [range])
1719
+
1720
+ const refresh = useCallback(async () => {
1721
+ setRefreshing(true)
1722
+ try {
1723
+ await Promise.all([loadSummary(), loadPrefs(), loadUsage()])
1724
+ } finally {
1725
+ setRefreshing(false)
1726
+ }
1727
+ }, [loadSummary, loadPrefs, loadUsage])
1728
+
1729
+ useEffect(() => { void refresh() }, [refresh])
1730
+ usePolling(() => { void loadSummary() }, { refreshMs: Number(summary?.refreshMs) || 60000 })
1731
+
1732
+ const savePrefs = useCallback(async (patch) => {
1733
+ if (prefsRef.current === null) return { ok: false, reason: 'not-ready' }
1734
+ try {
1735
+ const saved = await putPrefs({ ...prefsRef.current, ...patch })
1736
+ prefsRef.current = saved
1737
+ setPrefs(saved)
1738
+ setSummary((current) => (current === null ? current : mergeBudgets(current, saved)))
1739
+ return { ok: true, prefs: saved }
1740
+ } catch (error) {
1741
+ return { ok: false, reason: error.message }
1742
+ }
1743
+ }, [])
1744
+
1745
+ const refreshSubs = useCallback(async () => {
1746
+ try { await fetch(`${API}/providers/refresh`, { method: 'POST', headers: { accept: 'application/json' } }) } catch { /* ignore */ }
1747
+ await refresh()
1748
+ }, [refresh])
1749
+
1750
+ const providers = summary?.providers ?? []
1751
+ const api = providers.filter((provider) => provider.kind === 'api')
1752
+ const subscriptions = providers.filter((provider) => provider.kind === 'subscription')
1753
+ const models = Array.isArray(usage?.models) ? usage.models : []
1754
+ const updated = fmtClock(summary?.updatedAt)
1755
+ const degraded = summary?.providersDegraded === true
1756
+ const emptyAll = summary !== null && api.length === 0 && subscriptions.length === 0
1757
+
1758
+ return h('div', { 'data-testid': 'token-dash-board-scroll', style: styles.boardScroll },
1759
+ h('div', { 'data-testid': 'token-dash-board', style: styles.board },
1760
+ h('style', null, TD_CSS),
1761
+ h('div', { style: styles.boardHead },
1762
+ h('div', { style: styles.boardTitleRow },
1763
+ h('div', { style: styles.boardTitle }, tr('Token 看板')),
1764
+ h('div', { style: styles.boardMeta },
1765
+ `${tr('数据来自本机会话记录')}${updated === null ? '' : ` · ${tr('更新于 {time}', { time: updated })}`}`)),
1766
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 8 } },
1767
+ h('a', {
1768
+ href: REPO_URL, target: '_blank', rel: 'noopener',
1769
+ 'data-testid': 'token-dash-repo', title: tr('查看仓库'), style: styles.boardAction,
1770
+ }, '★'),
1771
+ h('button', {
1772
+ type: 'button', 'data-testid': 'token-dash-board-head-refresh',
1773
+ 'aria-label': tr('刷新'), title: tr('刷新'), disabled: refreshing,
1774
+ style: { ...styles.boardAction, cursor: refreshing ? 'default' : 'pointer', opacity: refreshing ? 0.6 : 1 },
1775
+ onClick: () => { void refresh() },
1776
+ }, h(Icon, { name: refreshing ? 'loader' : 'refresh', size: 13 })))),
1777
+ error ? h('div', { style: styles.errorStrip, role: 'alert' },
1778
+ h('span', null, tr('刷新失败,保留上次数据')),
1779
+ h('button', { type: 'button', style: styles.button, onClick: () => { void refresh() } }, tr('重试'))) : null,
1780
+ api.length > 0 ? h('section', { style: styles.boardSection },
1781
+ h('div', { style: styles.boardSectionHead }, h('b', { style: styles.sectionTitle }, tr('按量计价(按供应商)'))),
1782
+ h(BudgetTable, { providers: api, prefs, onSave: savePrefs })) : null,
1783
+ subscriptions.length > 0 ? h('section', { style: styles.boardSection },
1784
+ h('div', { style: styles.boardSectionHead },
1785
+ h('b', { style: styles.sectionTitle }, tr('订阅套餐(按供应商)')),
1786
+ h(IconButton, {
1787
+ label: tr('重新检测订阅配额'), testid: 'token-dash-board-rescan',
1788
+ disabled: refreshing, onClick: () => { void refreshSubs() },
1789
+ }, h(Icon, { name: refreshing ? 'loader' : 'refresh', size: 13 }))),
1790
+ h(QuotaTable, { providers: subscriptions })) : null,
1791
+ emptyAll ? h('div', { 'data-testid': 'token-dash-board-empty', style: styles.cardBox },
1792
+ h('div', { style: styles.empty }, degraded ? tr('供应商探测失败') : tr('未检测到已配置供应商')),
1793
+ degraded ? h('button', { type: 'button', style: styles.button, onClick: () => { void refresh() } }, tr('重试')) : null) : null,
1794
+ h('section', { style: styles.boardSection },
1795
+ h('div', { style: styles.boardSectionHead }, h('b', { style: styles.sectionTitle }, tr('范围与明细'))),
1796
+ h('div', { style: styles.rangeBox },
1797
+ h('div', { style: styles.rangeHead },
1798
+ h('div', { style: { width: 300, maxWidth: '100%', flex: '0 0 300px', minWidth: 0 } }, h(Segmented, {
1799
+ value: range, onChange: setRange, label: tr('时间范围'),
1800
+ options: RANGES.map(([value, label]) => ({ value, label: tr(label) })),
1801
+ })),
1802
+ h('span', { style: styles.rangeMeta },
1803
+ `${tr('共 {n} 个模型', { n: models.length })}${updated === null ? '' : ` · ${tr('更新于 {time}', { time: updated })}`}`)),
1804
+ usageError ? h('div', { style: styles.errorStrip, role: 'alert' },
1805
+ h('span', null, tr('范围数据加载失败')),
1806
+ h('button', { type: 'button', style: styles.button, onClick: () => { void loadUsage() } }, tr('重试'))) : null,
1807
+ h(RangeCards, { usage }),
1808
+ h('div', { style: styles.detailWrap }, h(DetailTable, {
1809
+ rows: models,
1810
+ providerNames: Object.fromEntries(providers.map((provider) => [provider.id, provider.name])),
1811
+ })))),
1812
+ h('div', { 'data-testid': 'token-dash-settings-capsule', style: styles.capsule },
1813
+ h(SettingsRows, { summary, prefs, onSave: savePrefs, onRefresh: refresh, onRefreshSubs: refreshSubs }))))
1164
1814
  }
1165
1815
 
1166
1816
  return {
1167
1817
  name: PKG,
1168
- inject: ['slots', 'locale'],
1818
+ inject: ['slots', 'locale', 'layout'],
1169
1819
  apply(ctx) {
1170
1820
  if (ctx.locale !== undefined) {
1171
1821
  localeService = ctx.locale
@@ -1181,6 +1831,12 @@ window.__ModuleLoader__.load({
1181
1831
  return () => clearTimeout(timer)
1182
1832
  }, 'update:startup')
1183
1833
  }
1834
+ ctxRef = typeof ctx === 'object' ? ctx : null
1835
+ try {
1836
+ layoutRef = typeof ctx.get === 'function' ? ctx.get('layout') ?? null : ctx.layout ?? null
1837
+ } catch {
1838
+ layoutRef = null
1839
+ }
1184
1840
  const slots = typeof ctx.get === 'function' ? ctx.get('slots') : ctx.slots
1185
1841
  if (slots === undefined || typeof slots.inject !== 'function') return
1186
1842
  const reportMount = (slot) => {
@@ -1199,6 +1855,14 @@ window.__ModuleLoader__.load({
1199
1855
  reportMount('conversation.composer.dock')
1200
1856
  return slots.register({ name: 'conversation.composer.dock', id: 'token-dash-input', order: -1 }, LocaleRoot)
1201
1857
  })
1858
+ slots.inject('main', () => {
1859
+ reportMount('main')
1860
+ return slots.register({ name: 'main', key: PAGE_ID, label: tr('Token 看板') }, BoardPage)
1861
+ })
1862
+ slots.inject('sidebar.panellist', () => {
1863
+ reportMount('sidebar.panellist')
1864
+ return slots.register({ name: 'sidebar.panellist', id: PAGE_ID, order: 6, label: tr('Token 看板') }, BoardEntry)
1865
+ })
1202
1866
  },
1203
1867
  }
1204
1868
  },