dsh-token-dash 1.0.6 → 1.1.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,45 +1,152 @@
1
1
  /**
2
- * dsh-token-dash — client half. P1 constraint pill, P2 dynamic provider cards,
3
- * P3 provider settings, log export and in-place update.
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.
4
4
  */
5
5
  window.__ModuleLoader__.load({
6
6
  id: 'dsh-token-dash',
7
7
  factory(require) {
8
8
  const React = require('react')
9
9
  const h = React.createElement
10
- const { useCallback, useEffect, useRef, useState } = React
10
+ const { useCallback, useEffect, useLayoutEffect, useRef, useState } = React
11
11
 
12
12
  const API = '/token-dash/api'
13
13
  const PKG = 'dsh-token-dash'
14
- const COLORS = { primary: '#6ea8ff', warn: '#f0a020', over: '#e05a5a' }
15
- const budgetColor = (state) => (state === 'over' ? COLORS.over : state === 'warn' ? COLORS.warn : COLORS.primary)
16
- const percentColor = (value) => (value >= 100 ? COLORS.over : value >= 80 ? COLORS.warn : COLORS.primary)
17
-
18
- const fmtMoney = (value, currency = 'CNY') => `${currency === 'USD' ? '$' : '¥'}${Number(value ?? 0).toFixed(2)}`
19
- const fmtM = (value) => `${(Number(value ?? 0) / 1e6).toFixed(2)}M`
20
- const fmtRatio = (value) => `${(Number(value ?? 0) * 100).toFixed(1)}%`
21
- const fmtUsed = (value) => `${Number(value ?? 0).toFixed(1)}%`
22
- const fmtAgo = (ts) => {
23
- if (!Number.isFinite(ts)) return '加载中'
24
- const seconds = Math.max(0, Math.round((Date.now() - ts) / 1000))
25
- if (seconds < 60) return '刚刚'
26
- if (seconds < 3600) return `${Math.floor(seconds / 60)} 分钟前`
27
- return `${Math.floor(seconds / 3600)} 小时前`
28
- }
29
- const fmtReset = (ts) => {
14
+ const RANGES = [
15
+ ['today', '当天'],
16
+ ['7d', '近7天'],
17
+ ['30d', '近30天'],
18
+ ['all', '全部'],
19
+ ]
20
+ const REFRESH_OPTIONS = [[30000, '30秒'], [60000, '1分钟'], [300000, '5分钟']]
21
+ const PRICE_LABELS = { zhipu: 'GLM', qwen: 'Qwen' }
22
+ const SPIN_CSS = '@keyframes td-spin{to{transform:rotate(360deg)}}'
23
+ const EN = {
24
+ '当天': 'Today', '近7天': 'Last 7 days', '近30天': 'Last 30 days', '全部': 'All',
25
+ '30秒': '30s', '1分钟': '1m', '5分钟': '5m',
26
+ '社区': 'Community', '内置兜底': 'Built-in fallback',
27
+ '查询失败': 'Query failed', '套餐查询失败': 'Quota query failed',
28
+ '周': 'Week', '月': 'Month', '重置': 'Reset',
29
+ '按量 API': 'Pay-as-you-go', '订阅': 'Subscription', '账户套餐': 'Account plan',
30
+ '预算': 'Budget', '未设置': 'Not set', '今日 {value}': 'Today {value}',
31
+ '余额 {value}': 'Balance {value}', '预算已用 {value}': 'Budget used {value}',
32
+ '预算未设置': 'Budget not set', '收起': 'Collapse', '展开': 'Expand',
33
+ 'Token 看板': 'Token dashboard', '点击查看 Token 看板': 'Click to view Token dashboard',
34
+ 'Token 看板:{text}': 'Token dashboard: {text}', '看板页面': 'Dashboard page',
35
+ '用量': 'Usage', '设置': 'Settings',
36
+ '查看支持的 API Key 范围': 'View supported API Key scope',
37
+ '目前支持 DeepSeek / Kimi / GLM / OpenRouter / Qwen API Key': 'Supports DeepSeek / Kimi / GLM / OpenRouter / Qwen API Keys',
38
+ '刷新': 'Refresh', '关闭': 'Close',
39
+ '未定价': 'Unpriced', '请求': 'Req', '命中': 'Hit',
40
+ '本月预算(已检测 {count})': 'Monthly budget ({count} detected)',
41
+ '订阅套餐(账户级,已检测 {count})': 'Subscription plan (account-wide, {count} detected)',
42
+ '重新检测订阅配额': 'Recheck subscription quota',
43
+ '未检测到已配置供应商': 'No configured provider detected',
44
+ '供应商探测失败': 'Provider probe failed',
45
+ '时间范围': 'Time range',
46
+ '刷新失败,保留上次数据': 'Refresh failed; keeping previous data',
47
+ '范围数据加载失败': 'Range data failed to load',
48
+ '重试': 'Retry', '总费用': 'Total cost', '按币种': 'By currency',
49
+ '真实 Tokens': 'Real Tokens', '入 {input} · 缓存 {cache} · 出 {output}': 'In {input} · Cache {cache} · Out {output}',
50
+ '范围数据加载中…': 'Loading range data…', '范围内暂无消耗': 'No usage in this range',
51
+ 'Tokens 括号说明': 'Tokens bracket legend',
52
+ 'Tokens 括号顺序:输入 / 缓存(读+写)/ 输出': 'Tokens bracket order: input / cache (read+write) / output',
53
+ 'Token 数据不可用': 'Token data unavailable', 'Token 数据加载中…': 'Loading Token data…',
54
+ '设置加载失败': 'Failed to load settings', '已保存': 'Saved',
55
+ '保存失败:{reason}': 'Save failed: {reason}', '请输入 0 或正数': 'Enter 0 or a positive number',
56
+ '月度预算': 'Monthly budget', '账户余额': 'Account balance',
57
+ '刷新间隔': 'Refresh interval', '显示': 'Display', '日志': 'Logs',
58
+ '查看日志': 'View logs', '打开日志文件夹': 'Open log folder', '导出日志': 'Export logs',
59
+ '价格与版本': 'Prices and version', '价格表': 'Price table',
60
+ '已重新检测': 'Rechecked', '已打开日志文件夹': 'Log folder opened',
61
+ '无法打开,已复制路径': 'Could not open; path copied', '打开日志失败': 'Failed to open logs',
62
+ '日志已导出': 'Logs exported', '日志导出失败': 'Log export failed',
63
+ '数据': 'Data', '备份与恢复': 'Backup and restore', '导出数据': 'Export data', '导入数据': 'Import data',
64
+ '导入中…': 'Importing…', '数据已导出': 'Data exported', '数据导出失败': 'Data export failed',
65
+ '已导入 {month} 数据': 'Imported {month} data', '导入失败:{reason}': 'Import failed: {reason}',
66
+ '检查失败': 'Check failed', '未发布': 'Not published', '已是最新': 'Up to date',
67
+ '发现 {version}': 'Found {version}', '更新': 'Update', '取消': 'Cancel',
68
+ '复制命令': 'Copy command', '命令已复制': 'Command copied', '复制失败': 'Copy failed',
69
+ '设置加载中…': 'Loading settings…', '检查更新': 'Check for updates',
70
+ '更新失败({reason})': 'Update failed ({reason})',
71
+ '已更新到 {version},重启 DSH 后生效': 'Updated to {version}; restart DSH to apply',
72
+ '已更新,重启 DSH 后生效': 'Updated; restart DSH to apply',
73
+ 'API 计费(已检测 {count})': 'API billing ({count} detected)',
74
+ '订阅(已检测 {count})': 'Subscription ({count} detected)',
75
+ '发现 {version},点击更新': 'Found {version}; click to update',
76
+ '版本 {version}': 'Version {version}',
77
+ '{name} · {action} Token 看板': '{name} · {action} Token dashboard',
78
+ '{name} 月度预算': '{name} monthly budget',
79
+ '{name},按量 API,{budget},今日 {today}{balance}': '{name}, pay-as-you-go, {budget}, today {today}{balance}',
80
+ '{name},订阅,账户套餐,{value}': '{name}, subscription, account plan, {value}',
81
+ }
82
+ const ZH = Object.fromEntries(Object.keys(EN).map((key) => [key, key]))
83
+ const MESSAGES = { zh: ZH, en: EN }
84
+ let localeService = null
85
+ let activeTranslate = (key, params) => {
86
+ const template = ZH[key] ?? key
87
+ if (!params) return template
88
+ return template.replace(/\{(\w+)\}/g, (match, name) => name in params ? String(params[name]) : match)
89
+ }
90
+ const tr = (key, params) => activeTranslate(key, params)
91
+
92
+ const T = {
93
+ text: 'var(--dsw-alias-label-primary, var(--dsh-text, #eee))',
94
+ muted: 'var(--dsw-alias-label-secondary, rgba(235,235,235,.65))',
95
+ weak: 'var(--dsw-alias-label-tertiary, rgba(235,235,235,.45))',
96
+ accent: 'var(--dsw-alias-state-business-primary, #6ea8ff)',
97
+ warn: 'var(--dsw-alias-state-warn-primary, #f0a020)',
98
+ over: 'var(--dsw-alias-state-error-primary, #e05a5a)',
99
+ ok: 'var(--dsw-alias-state-success-primary, #4ed17e)',
100
+ border: 'var(--dsw-alias-border-l2, rgba(128,128,128,.25))',
101
+ section: 'color-mix(in srgb, var(--dsw-alias-label-primary, #eee) 3%, transparent)',
102
+ tile: 'color-mix(in srgb, var(--dsw-alias-label-primary, #eee) 4%, transparent)',
103
+ input: 'color-mix(in srgb, var(--dsw-alias-label-primary, #eee) 5%, transparent)',
104
+ segment: 'var(--dsw-alias-bg-module-platform, rgba(127,127,127,.10))',
105
+ segmentOn: 'var(--dsw-alias-button-elevated-fill, #fff)',
106
+ tooltip: 'var(--dsw-alias-tooltip-bg, #333)',
107
+ tooltipText: 'var(--dsw-alias-toast-label, #fff)',
108
+ focus: 'var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary, #6ea8ff))',
109
+ }
110
+
111
+ const fmtMoney = (value, currency = 'CNY') => `${currency === 'USD' ? '$' : '¥'}${(Number(value ?? 0) || 0).toFixed(2)}`
112
+ const fmtTokens = (value) => {
113
+ const n = Math.max(0, Number(value) || 0)
114
+ const trim = (text) => text.replace(/\.0$/, '')
115
+ if (n < 1000) return String(Math.round(n))
116
+ if (n < 1e6) return `${trim((n / 1e3).toFixed(1))}k`
117
+ if (n < 1e9) return `${trim((n / 1e6).toFixed(1))}M`
118
+ return `${trim((n / 1e9).toFixed(1))}B`
119
+ }
120
+ const fmtRatio = (value) => `${trimZeros((Math.max(0, Number(value) || 0) * 100).toFixed(1))}%`
121
+ const fmtPercent = (value) => `${trimZeros((Number(value) || 0).toFixed(1))}%`
122
+ const trimZeros = (text) => text.replace(/\.0$/, '')
123
+ const fmtTime = (ts) => {
30
124
  if (!Number.isFinite(ts) || ts <= 0) return null
31
125
  const date = new Date(ts)
32
126
  const now = new Date()
33
127
  const pad = (value) => String(value).padStart(2, '0')
34
128
  const hm = `${pad(date.getHours())}:${pad(date.getMinutes())}`
35
- if (date.toDateString() === now.toDateString()) return hm
36
- return `${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${hm}`
129
+ return date.toDateString() === now.toDateString() ? hm : `${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${hm}`
37
130
  }
38
- const modelTitle = (model) => {
39
- if (!model.providerId || model.providerId === 'unknown') return model.displayName ?? model.modelId
40
- return [model.providerName, model.displayName ?? model.modelId].filter(Boolean).join(' / ')
131
+ const budgetColor = (state) => (state === 'over' ? T.over : state === 'warn' ? T.warn : T.accent)
132
+ const percentColor = (value) => (value >= 100 ? T.over : value >= 80 ? T.warn : T.accent)
133
+ const sourceLabel = (source) => String(source ?? '').includes('community') ? tr('社区') : tr('内置兜底')
134
+ const linkLabel = (link) => PRICE_LABELS[link.id] ?? link.label
135
+ const formatCatalogTime = (value) => {
136
+ if (value === null || value === undefined || String(value).trim() === '') return '—'
137
+ const text = String(value).trim()
138
+ const pad = (number) => String(number).padStart(2, '0')
139
+ if (/^\d{10}$/.test(text) || /^\d{13}$/.test(text)) {
140
+ const stamp = Number(text) * (text.length === 10 ? 1000 : 1)
141
+ const date = new Date(stamp)
142
+ if (!Number.isFinite(date.getTime())) return '—'
143
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`
144
+ }
145
+ if (/^\d{4}-\d{2}-\d{2}$/.test(text)) return text
146
+ const date = new Date(text)
147
+ if (!Number.isFinite(date.getTime())) return text
148
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`
41
149
  }
42
- const windowLabel = { '5h': '5h', week: '周', month: '月' }
43
150
 
44
151
  async function getJson(path) {
45
152
  const res = await fetch(`${API}${path}`, { headers: { accept: 'application/json' } })
@@ -59,155 +166,394 @@ window.__ModuleLoader__.load({
59
166
  return body.data
60
167
  }
61
168
 
169
+ async function postJson(path, payload) {
170
+ const res = await fetch(`${API}${path}`, {
171
+ method: 'POST',
172
+ headers: { 'content-type': 'application/json' },
173
+ body: JSON.stringify(payload),
174
+ })
175
+ const body = await res.json().catch(() => ({}))
176
+ if (!res.ok || body?.ok !== true) throw new Error(body?.reason ?? `http-${res.status}`)
177
+ return body.data
178
+ }
179
+
180
+ const updateListeners = new Set()
181
+ let updateSnapshot = { phase: 'idle', text: null, latest: null, command: null }
182
+ let updateRequest = null
183
+ let updateResetTimer = null
184
+ let autoUpdateChecked = false
185
+
186
+ function emitUpdate(patch) {
187
+ updateSnapshot = { ...updateSnapshot, ...patch }
188
+ for (const listener of updateListeners) listener()
189
+ }
190
+
191
+ function resetUpdateLater() {
192
+ if (updateResetTimer !== null) clearTimeout(updateResetTimer)
193
+ updateResetTimer = setTimeout(() => {
194
+ updateResetTimer = null
195
+ if (updateSnapshot.phase === 'done') emitUpdate({ phase: 'idle', text: null, latest: null, command: null })
196
+ }, 1600)
197
+ }
198
+
199
+ function useUpdateSnapshot() {
200
+ const [snapshot, setSnapshot] = useState(updateSnapshot)
201
+ useEffect(() => {
202
+ const listener = () => setSnapshot(updateSnapshot)
203
+ updateListeners.add(listener)
204
+ return () => updateListeners.delete(listener)
205
+ }, [])
206
+ return snapshot
207
+ }
208
+
209
+ async function checkForUpdate({ manual = true } = {}) {
210
+ if (updateSnapshot.phase === 'checking' || updateSnapshot.phase === 'installing') return
211
+ if (updateRequest !== null) return updateRequest
212
+ if (updateResetTimer !== null) { clearTimeout(updateResetTimer); updateResetTimer = null }
213
+ emitUpdate({ phase: 'checking', text: null, command: null })
214
+ updateRequest = (async () => {
215
+ try {
216
+ const data = await getJson('/update')
217
+ if (data.published === false) {
218
+ if (manual) { emitUpdate({ phase: 'done', text: tr('未发布') }); resetUpdateLater() }
219
+ else emitUpdate({ phase: 'idle', text: null })
220
+ } else if (data.hasUpdate) {
221
+ emitUpdate({ phase: manual ? 'confirm' : 'available', latest: data.latest, text: null })
222
+ } else if (manual) {
223
+ emitUpdate({ phase: 'done', text: tr('已是最新') })
224
+ resetUpdateLater()
225
+ } else {
226
+ emitUpdate({ phase: 'idle', text: null })
227
+ }
228
+ } catch {
229
+ if (manual) emitUpdate({ phase: 'error', text: tr('检查失败') })
230
+ else emitUpdate({ phase: 'idle', text: null })
231
+ } finally {
232
+ updateRequest = null
233
+ }
234
+ })()
235
+ return updateRequest
236
+ }
237
+
238
+ async function installUpdateRequest() {
239
+ if (updateSnapshot.phase === 'installing') return
240
+ emitUpdate({ phase: 'installing', text: null })
241
+ try {
242
+ const res = await fetch(`${API}/update/install`, { method: 'POST', headers: { accept: 'application/json' } })
243
+ const body = await res.json().catch(() => ({}))
244
+ const data = body?.data
245
+ if (body?.ok === true) {
246
+ emitUpdate({ phase: 'done', text: data?.to ? tr('已更新到 {version},重启 DSH 后生效', { version: data.to }) : tr('已更新,重启 DSH 后生效'), latest: null })
247
+ resetUpdateLater()
248
+ } else {
249
+ emitUpdate({ phase: 'error', text: tr('更新失败({reason})', { reason: data?.reason ?? 'unknown' }), command: data?.command ?? null })
250
+ }
251
+ } catch (error) {
252
+ emitUpdate({ phase: 'error', text: tr('更新失败({reason})', { reason: error.message }), command: null })
253
+ }
254
+ }
255
+
62
256
  const styles = {
63
257
  pill: {
64
- display: 'inline-flex',
65
- alignItems: 'center',
66
- gap: 6,
67
- height: 24,
68
- padding: '0 8px',
69
- borderRadius: 999,
70
- cursor: 'pointer',
71
- maxWidth: '100%',
72
- fontVariantNumeric: 'tabular-nums',
73
- border: '1px solid var(--dsh-border, rgba(128,128,128,.25))',
74
- color: 'var(--dsh-text, inherit)',
258
+ display: 'inline-flex', alignItems: 'center', gap: 6, height: 24, padding: '0 8px',
259
+ borderRadius: 999, cursor: 'pointer', maxWidth: '100%', fontVariantNumeric: 'tabular-nums',
260
+ border: `1px solid ${T.border}`, color: T.text,
75
261
  },
76
262
  pillWrap: { position: 'relative', display: 'inline-flex', alignItems: 'center', marginLeft: 8 },
77
- pillHover: { background: 'rgba(127,127,127,.12)' },
78
- nameEllipsis: { maxWidth: '12em', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
263
+ pillHover: { background: 'color-mix(in srgb, currentColor 8%, transparent)' },
79
264
  hint: {
80
265
  position: 'absolute', right: 12, bottom: 30, padding: '5px 8px', borderRadius: 6,
81
- background: 'var(--dsh-bg-elevated, #2a2a2a)', border: '1px solid var(--dsh-border, rgba(128,128,128,.25))',
266
+ background: T.tooltip, color: T.tooltipText, border: `1px solid ${T.border}`,
82
267
  fontSize: 11, whiteSpace: 'nowrap', boxShadow: '0 4px 16px rgba(0,0,0,.25)',
83
268
  },
84
- chevron: {
85
- marginLeft: 2, padding: '0 1px', borderRadius: 4, background: 'rgba(77,141,255,.16)',
86
- color: 'var(--dsw-alias-state-business-primary, #6ea8ff)', fontSize: 10,
87
- },
88
- sep: { width: 1, height: 12, background: 'currentColor', opacity: 0.2 },
269
+ chevron: { marginLeft: 2, padding: '0 1px', color: T.accent, fontSize: 10 },
89
270
  num: { fontWeight: 600, fontVariantNumeric: 'tabular-nums' },
90
271
  panel: {
91
- // #30 三次定案:从 pill 正上方弹出——左缘对齐 pill 左缘、底边距 pill 顶 8px,允许遮挡输入框
92
- position: 'absolute', bottom: 'calc(100% + 8px)', left: 0, width: 'max-content',
93
- minWidth: 'min(380px, calc(100vw - 32px))', maxWidth: 'min(600px, calc(100vw - 32px))',
94
- boxSizing: 'border-box', maxHeight: '70vh', overflow: 'auto', zIndex: 9999,
95
- padding: 12, borderRadius: 12, background: 'var(--dsh-bg-elevated, #1f1f1f)',
96
- color: 'var(--dsh-text, #eee)', boxShadow: '0 12px 40px rgba(0,0,0,.35)', fontSize: 12,
97
- outline: 'none',
272
+ position: 'absolute', bottom: 'calc(100% + 8px)', left: 0,
273
+ width: 'min(320px, calc(100vw - 16px))', boxSizing: 'border-box', maxHeight: '70vh',
274
+ overflow: 'auto', zIndex: 9999, padding: 12, borderRadius: 12,
275
+ background: 'var(--dsw-alias-bg-layer-2, var(--dsh-bg-elevated, #1f1f1f))', color: T.text,
276
+ border: `1px solid ${T.border}`, boxShadow: '0 12px 40px rgba(0,0,0,.35)', fontSize: 12, outline: 'none',
98
277
  },
99
- card: { border: '1px solid var(--dsh-border, rgba(128,128,128,.25))', borderRadius: 10, padding: 12, marginTop: 10 },
278
+ header: { display: 'flex', alignItems: 'center', gap: 6, minHeight: 28 },
279
+ headerTabs: { flex: 1, minWidth: 0 },
280
+ headerActions: { display: 'flex', alignItems: 'center', gap: 4, flex: '0 0 auto' },
100
281
  row: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 },
101
- rowStart: { display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' },
102
- muted: { opacity: 0.65, fontSize: 11 },
103
- headerTitle: { fontSize: 13, fontWeight: 600 },
104
- titleBar: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, minHeight: 36 },
105
- buttonGroup: { display: 'flex', gap: 12 },
106
- bar: { height: 6, borderRadius: 3, background: 'rgba(128,128,128,.25)', overflow: 'hidden', margin: '8px 0' },
107
- barFill: { height: '100%', background: '#6ea8ff' },
108
- barNeutral: { height: '100%', background: 'rgba(128,128,128,.45)' },
109
- cols: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 0, marginTop: 8 },
110
- subGrid: { display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(240px, 1fr))', gap: 8 },
111
- scrollList: { maxHeight: 280, overflowY: 'auto', paddingRight: 4 },
112
- table: { width: 'max-content', minWidth: '100%', borderCollapse: 'collapse', tableLayout: 'auto', marginTop: 6 },
113
- th: { textAlign: 'left', opacity: 0.6, fontWeight: 400, padding: '4px 8px', whiteSpace: 'nowrap' },
114
- thRight: { textAlign: 'right', opacity: 0.6, fontWeight: 400, padding: '4px 8px', borderLeft: '1px solid rgba(128,128,128,.15)', whiteSpace: 'nowrap' },
115
- td: { padding: '4px 8px', borderTop: '1px solid rgba(128,128,128,.15)', whiteSpace: 'nowrap' },
116
- tdRight: { padding: '4px 8px', textAlign: 'right', borderTop: '1px solid rgba(128,128,128,.15)', borderLeft: '1px solid rgba(128,128,128,.15)', whiteSpace: 'nowrap' },
117
- modelCell: { padding: '4px 8px', borderTop: '1px solid rgba(128,128,128,.15)', whiteSpace: 'nowrap', maxWidth: 220, overflow: 'hidden', textOverflow: 'ellipsis' },
118
- link: { color: 'inherit', textDecoration: 'underline', cursor: 'pointer', marginLeft: 10 },
282
+ rowStart: { display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' },
283
+ muted: { color: T.muted, fontSize: 11 },
284
+ weak: { color: T.weak, fontSize: 10.5 },
285
+ title: { fontSize: 13, fontWeight: 600 },
119
286
  button: {
120
- border: '1px solid rgba(77,141,255,.32)', background: 'rgba(77,141,255,.16)',
121
- color: 'var(--dsw-alias-state-business-primary, #6ea8ff)', borderRadius: 6,
122
- padding: '2px 8px', cursor: 'pointer',
287
+ boxSizing: 'border-box', border: '1px solid color-mix(in srgb, var(--td-accent) 32%, transparent)',
288
+ background: 'color-mix(in srgb, var(--td-accent) 16%, transparent)',
289
+ color: 'var(--td-accent)', borderRadius: 6, height: 22, minHeight: 22, padding: '0 7px',
290
+ fontSize: 11, lineHeight: '20px', cursor: 'pointer', font: 'inherit',
291
+ display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
123
292
  },
124
- select: { background: 'transparent', color: 'inherit', border: '1px solid rgba(128,128,128,.35)', borderRadius: 5, padding: '2px 4px' },
125
- input: { width: 110, height: 28, boxSizing: 'border-box', textAlign: 'right', background: 'transparent', color: 'inherit', border: '1px solid rgba(128,128,128,.35)', borderRadius: 5, padding: '2px 4px' },
126
- segButton: {
127
- width: 72, height: 28, borderRadius: 6, border: '1px solid rgba(128,128,128,.35)',
128
- background: 'transparent', color: 'inherit', cursor: 'pointer', fontSize: 12,
293
+ iconButton: {
294
+ width: 22, height: 22, minHeight: 22, boxSizing: 'border-box', padding: 0,
295
+ borderRadius: 6, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flex: '0 0 auto',
129
296
  },
130
- segActive: { borderColor: 'rgba(77,141,255,.64)', color: 'var(--dsw-alias-state-business-primary, #6ea8ff)', background: 'rgba(77,141,255,.12)' },
131
- toggleTrack: {
132
- width: 44, height: 24, borderRadius: 999, border: 'none', padding: 2, display: 'flex', alignItems: 'center',
133
- background: 'rgba(128,128,128,.35)', cursor: 'pointer', transition: 'background .15s',
297
+ inlineInfoButton: {
298
+ width: 20, height: 20, minHeight: 20, boxSizing: 'border-box', padding: 0, border: 'none',
299
+ background: 'transparent', color: T.weak, borderRadius: 4, display: 'inline-flex',
300
+ alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
134
301
  },
135
- toggleOn: { background: '#2ea36f' },
136
- toggleKnob: { width: 20, height: 20, borderRadius: 999, background: '#fff', transition: 'transform .15s' },
137
- toggleKnobOn: { transform: 'translateX(20px)' },
302
+ section: { background: T.section, borderRadius: 10, padding: 10, marginTop: 10, display: 'grid', gridTemplateColumns: 'minmax(0,1fr)', alignContent: 'start', gap: 6, minWidth: 0 },
303
+ sectionHead: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 6, minHeight: 20 },
304
+ budgetRow: { display: 'grid', gridTemplateColumns: 'minmax(0,1fr) 28px 48px 78px 58px', alignItems: 'center', columnGap: 2, minHeight: 22, fontSize: 10.5 },
305
+ budgetName: { fontSize: 12, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
306
+ quotaRow: { display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap', minHeight: 22, fontSize: 11 },
307
+ quotaName: { fontSize: 12, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: 88 },
308
+ rangeCard: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginTop: 10 },
309
+ tile: { background: T.tile, borderRadius: 8, padding: '8px 9px', minWidth: 0 },
310
+ tileLabel: { color: T.muted, fontSize: 11 },
311
+ tileValue: { fontSize: 17, fontWeight: 600, marginTop: 2, fontVariantNumeric: 'tabular-nums' },
312
+ tileDetail: { color: T.muted, fontSize: 10.5, marginTop: 1, fontVariantNumeric: 'tabular-nums' },
313
+ group: { marginTop: 9, display: 'grid', gap: 3 },
314
+ groupName: { fontSize: 13, fontWeight: 600 },
315
+ modelRow: { display: 'flex', alignItems: 'baseline', gap: 8, minHeight: 18 },
316
+ modelName: { minWidth: 0, flex: 1, fontSize: 12, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
317
+ modelCost: { fontSize: 11, fontWeight: 600, whiteSpace: 'nowrap', fontVariantNumeric: 'tabular-nums' },
318
+ usageLine: { display: 'flex', alignItems: 'baseline', gap: 6, minWidth: 0, whiteSpace: 'nowrap' },
319
+ usagePrimary: { flex: '1 1 auto', minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
320
+ usageMeta: { flex: '0 0 auto', whiteSpace: 'nowrap' },
321
+ usageLabel: { color: T.muted, fontSize: 9.5, marginRight: 3 },
322
+ usageValue: { fontWeight: 600, fontVariantNumeric: 'tabular-nums' },
323
+ errorStrip: { display: 'flex', alignItems: 'center', gap: 6, color: T.over, fontSize: 11, marginTop: 6 },
324
+ empty: { color: T.muted, fontSize: 11, padding: '10px 0' },
325
+ input: {
326
+ width: 72, height: 22, boxSizing: 'border-box', textAlign: 'right',
327
+ background: T.input, color: T.text, border: `1px solid ${T.border}`,
328
+ borderRadius: 6, padding: '0 5px', font: 'inherit', fontVariantNumeric: 'tabular-nums',
329
+ },
330
+ card: { background: T.section, borderRadius: 10, padding: 10, marginTop: 10, display: 'grid', gap: 8 },
331
+ link: { color: T.text, textDecoration: 'underline', cursor: 'pointer' },
332
+ status: { minHeight: 15, fontSize: 10.5, color: T.muted, textAlign: 'right' },
333
+ priceLinks: { display: 'flex', gap: 7, alignItems: 'center', overflowX: 'auto', whiteSpace: 'nowrap', paddingBottom: 1 },
334
+ }
335
+ styles.button['--td-accent'] = T.accent
336
+ styles.iconButton = { ...styles.button, ...styles.iconButton, minHeight: 22, boxSizing: 'border-box' }
337
+
338
+ function Icon({ name, size = 14, style }) {
339
+ 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 }
340
+ 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' }))
341
+ if (name === 'close') return h('svg', props, h('path', { d: 'M6 6l12 12M18 6L6 18' }))
342
+ if (name === 'check') return h('svg', props, h('path', { d: 'M20 6L9 17l-5-5' }))
343
+ 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' }))
344
+ 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' }))
345
+ 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' }))
138
346
  }
139
347
 
140
- function Toggle({ checked, onChange }) {
348
+ function IconButton({ label, children, onClick, disabled = false, testid, dot = false, dotColor = T.warn }) {
141
349
  return h('button', {
142
- type: 'button', role: 'switch', 'aria-checked': checked, onClick: () => onChange(!checked),
143
- style: { ...styles.toggleTrack, ...(checked ? styles.toggleOn : {}) },
144
- }, h('span', { style: { ...styles.toggleKnob, ...(checked ? styles.toggleKnobOn : {}) } }))
350
+ type: 'button', 'aria-label': label, title: label, disabled, onClick,
351
+ 'data-testid': testid,
352
+ style: { ...styles.iconButton, position: 'relative', opacity: disabled ? 0.5 : 1, cursor: disabled ? 'not-allowed' : 'pointer' },
353
+ }, children, dot ? h('span', {
354
+ 'aria-hidden': true,
355
+ style: { position: 'absolute', top: 2, right: 2, width: 4, height: 4, borderRadius: 999, background: dotColor },
356
+ }) : null)
145
357
  }
146
358
 
147
- const REFRESH_OPTIONS = [[30000, '30 秒'], [60000, '1 分钟'], [300000, '5 分钟']]
359
+ function Tooltip({ open, anchorRef, text, onClose }) {
360
+ const tipRef = useRef(null)
361
+ const [pos, setPos] = useState(null)
148
362
 
149
- function Segmented({ value, onChange }) {
150
- return h('div', { role: 'radiogroup', 'aria-label': '刷新间隔', style: { display: 'inline-flex', gap: 4 } },
151
- REFRESH_OPTIONS.map(([ms, label]) => h('button', {
152
- key: ms, type: 'button', role: 'radio', 'aria-checked': value === ms,
153
- onClick: () => onChange(ms),
154
- style: { ...styles.segButton, ...(value === ms ? styles.segActive : {}) },
155
- }, label)))
363
+ const updatePosition = useCallback(() => {
364
+ const anchor = anchorRef.current
365
+ const tip = tipRef.current
366
+ if (anchor === null || tip === null) return
367
+ const rect = anchor.getBoundingClientRect()
368
+ const tipRect = tip.getBoundingClientRect()
369
+ const width = Math.max(1, tipRect.width)
370
+ const height = Math.max(1, tipRect.height)
371
+ const gap = 6
372
+ const above = rect.top - gap - height
373
+ const below = rect.bottom + gap
374
+ const top = above >= 8
375
+ ? above
376
+ : Math.min(below, window.innerHeight - height - 8)
377
+ const left = Math.min(
378
+ Math.max(8, rect.left + rect.width / 2 - width / 2),
379
+ window.innerWidth - width - 8,
380
+ )
381
+ setPos({ top, left })
382
+ }, [anchorRef])
383
+
384
+ useLayoutEffect(() => {
385
+ if (!open) {
386
+ setPos(null)
387
+ return undefined
388
+ }
389
+ updatePosition()
390
+ const raf = requestAnimationFrame(updatePosition)
391
+ const close = () => onClose?.()
392
+ const onDown = (event) => {
393
+ if (anchorRef.current?.contains(event.target)) return
394
+ if (tipRef.current?.contains(event.target)) return
395
+ close()
396
+ }
397
+ window.addEventListener('resize', close)
398
+ window.addEventListener('scroll', close, true)
399
+ document.addEventListener('mousedown', onDown)
400
+ return () => {
401
+ cancelAnimationFrame(raf)
402
+ window.removeEventListener('resize', close)
403
+ window.removeEventListener('scroll', close, true)
404
+ document.removeEventListener('mousedown', onDown)
405
+ }
406
+ }, [open, updatePosition, onClose, anchorRef])
407
+
408
+ if (!open) return null
409
+ return h('span', {
410
+ ref: tipRef, role: 'tooltip',
411
+ style: {
412
+ position: 'fixed', top: pos?.top ?? 0, left: pos?.left ?? 0,
413
+ width: 'max-content', maxWidth: 'min(220px, calc(100vw - 16px))',
414
+ opacity: pos === null ? 0 : 1, zIndex: 10050,
415
+ padding: '6px 7px', borderRadius: 6, background: T.tooltip, color: T.tooltipText,
416
+ fontSize: 10.5, lineHeight: 1.35, boxShadow: '0 6px 20px rgba(0,0,0,.3)', whiteSpace: 'normal',
417
+ pointerEvents: 'none',
418
+ },
419
+ }, text)
420
+ }
421
+
422
+ function InfoTip({ label, text, children, style, variant = 'header' }) {
423
+ const [open, setOpen] = useState(false)
424
+ const [hover, setHover] = useState(false)
425
+ const triggerRef = useRef(null)
426
+ const close = useCallback(() => setOpen(false), [])
427
+
428
+ const inline = variant === 'inline'
429
+ const triggerStyle = inline
430
+ ? { ...styles.inlineInfoButton, ...(hover ? { background: 'color-mix(in srgb, currentColor 8%, transparent)' } : {}) }
431
+ : styles.iconButton
432
+ return h('span', {
433
+ style: { position: 'relative', display: 'inline-flex', verticalAlign: 'middle', ...style },
434
+ onMouseEnter: () => { setHover(true); setOpen(true) },
435
+ onMouseLeave: () => { setHover(false); close() },
436
+ }, h('button', {
437
+ ref: triggerRef, type: 'button', 'aria-label': label, 'aria-expanded': open,
438
+ onClick: () => setOpen((value) => !value),
439
+ onFocus: () => setOpen(true), onBlur: close,
440
+ onKeyDown: (event) => { if (event.key === 'Escape') close() },
441
+ style: triggerStyle,
442
+ }, children ?? h(Icon, { name: 'info', size: inline ? 11 : 12 })),
443
+ h(Tooltip, { open, anchorRef: triggerRef, text, onClose: close }))
156
444
  }
157
445
 
158
- /** 余额只来自账户余额接口;预算剩余不进入余额位。 */
159
- function balanceText(provider, showBalance) {
160
- if (showBalance === false) return null
446
+ function Toggle({ checked, onChange, label }) {
447
+ return h('button', {
448
+ type: 'button', role: 'switch', 'aria-checked': checked, 'aria-label': label,
449
+ onClick: () => onChange(!checked),
450
+ style: {
451
+ width: 28, height: 16, borderRadius: 999, border: 'none', padding: 2,
452
+ display: 'flex', alignItems: 'center', cursor: 'pointer',
453
+ background: checked ? T.accent : 'color-mix(in srgb, currentColor 25%, transparent)',
454
+ },
455
+ }, h('span', { style: {
456
+ width: 12, height: 12, borderRadius: 999, background: '#fff',
457
+ transform: `translateX(${checked ? 12 : 0}px)`, transition: 'transform .15s',
458
+ } }))
459
+ }
460
+
461
+ function Segmented({ value, options, onChange, label, kind = 'tablist' }) {
462
+ const itemRole = kind === 'radiogroup' ? 'radio' : 'tab'
463
+ return h('div', {
464
+ role: kind, 'aria-label': label,
465
+ style: { display: 'flex', width: '100%', height: 28, padding: 2, boxSizing: 'border-box', gap: 2, borderRadius: 8, background: T.segment },
466
+ }, options.map((option, index) => {
467
+ const selected = option.value === value
468
+ return h('button', {
469
+ key: option.value, type: 'button', role: itemRole,
470
+ 'aria-selected': itemRole === 'tab' ? selected : undefined,
471
+ 'aria-checked': itemRole === 'radio' ? selected : undefined,
472
+ tabIndex: selected ? 0 : -1,
473
+ onClick: () => onChange(option.value),
474
+ onKeyDown: (event) => {
475
+ if (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight') return
476
+ event.preventDefault()
477
+ const direction = event.key === 'ArrowRight' ? 1 : -1
478
+ onChange(options[(index + direction + options.length) % options.length].value)
479
+ },
480
+ style: {
481
+ flex: 1, minWidth: 0, height: 24, padding: '0 4px', borderRadius: 6, border: 'none',
482
+ fontSize: 11, fontWeight: 500, cursor: 'pointer', font: 'inherit',
483
+ background: selected ? T.segmentOn : 'transparent',
484
+ color: selected ? T.text : T.muted,
485
+ boxShadow: selected ? 'var(--dsw-shadow-lv1, 0 1px 2px rgba(0,0,0,.08))' : 'none',
486
+ transition: 'background .15s, color .15s',
487
+ },
488
+ }, option.label)
489
+ }))
490
+ }
491
+
492
+ function MiniBar({ ratio = 0, neutral = false }) {
493
+ return h('span', {
494
+ style: { display: 'block', width: 48, height: 4, borderRadius: 999, overflow: 'hidden', background: 'color-mix(in srgb, var(--dsw-alias-label-primary, #eee) 10%, transparent)' },
495
+ }, h('span', { style: {
496
+ display: 'block', height: '100%', width: `${Math.max(0, Math.min(100, (Number(ratio) || 0) * 100))}%`,
497
+ borderRadius: 999, background: neutral ? 'color-mix(in srgb, currentColor 30%, transparent)' : T.accent,
498
+ } }))
499
+ }
500
+
501
+ function balanceText(provider, show = true) {
502
+ if (show === false) return null
161
503
  const balance = provider.balance
162
- if (balance === undefined || balance === null) return '待配置'
163
- if (balance.status === 'ok') return Number.isFinite(balance.amount) ? fmtMoney(balance.amount, provider.currency) : '查询失败'
164
- if (balance.status === 'unconfigured') return '待配置'
165
- if (balance.status === 'unsupported') return '不支持'
166
- return '查询失败'
504
+ if (balance === undefined || balance === null) return '—'
505
+ if (balance.status === 'ok') return Number.isFinite(balance.amount) ? fmtMoney(balance.amount, provider.currency) : tr('查询失败')
506
+ if (balance.status === 'unconfigured' || balance.status === 'unsupported') return '—'
507
+ return tr('查询失败')
167
508
  }
168
509
 
510
+ function windowLabel(key) { return { '5h': '5h', week: tr('周'), month: tr('月') }[key] ?? key }
511
+
169
512
  function subscriptionText(provider) {
170
513
  const windows = Array.isArray(provider.windows) ? provider.windows : []
171
- if (windows.length === 0) return '套餐查询失败'
172
- const text = windows.slice(0, 2).map((plan) => `${windowLabel[plan.key] ?? plan.key} ${fmtUsed(plan.usedPercent)}`).join(' · ')
173
- if (windows.length === 1) {
174
- const reset = fmtReset(windows[0].resetAt)
175
- if (reset !== null) return `${text} · 重置 ${reset}`
176
- }
177
- return text
514
+ if (windows.length === 0) return tr('套餐查询失败')
515
+ return windows.slice(0, 2).map((plan) => `${windowLabel(plan.key)} ${fmtPercent(plan.usedPercent)}`).join(' · ')
178
516
  }
179
517
 
180
- /** 订阅窗口节点:百分比按官方原值着色;withReset 时单窗口附重置时间(P1)。 */
181
518
  function subscriptionNodes(provider, withReset = false) {
182
519
  const windows = Array.isArray(provider.windows) ? provider.windows : []
183
- if (windows.length === 0) return [h('span', { key: 'fail' }, '套餐查询失败')]
520
+ if (windows.length === 0) return [h('span', { key: 'fail' }, tr('套餐查询失败'))]
184
521
  const nodes = windows.slice(0, 2).map((plan, index) => h(React.Fragment, { key: plan.key },
185
522
  index > 0 ? ' · ' : null,
186
- `${windowLabel[plan.key] ?? plan.key} `,
187
- h('b', { style: { ...styles.num, color: percentColor(plan.usedPercent ?? 0) } }, fmtUsed(plan.usedPercent))))
523
+ `${windowLabel(plan.key)} `,
524
+ h('b', { style: { ...styles.num, color: percentColor(plan.usedPercent ?? 0) } }, fmtPercent(plan.usedPercent))))
188
525
  if (withReset && windows.length === 1) {
189
- const reset = fmtReset(windows[0].resetAt)
190
- if (reset !== null) nodes.push(h('span', { key: 'reset' }, ` · 重置 ${reset}`))
526
+ const reset = fmtTime(windows[0].resetAt)
527
+ if (reset !== null) nodes.push(h('span', { key: 'reset' }, ` · ${tr('重置')} ${reset}`))
191
528
  }
192
529
  return nodes
193
530
  }
194
531
 
532
+ function LocaleRoot() {
533
+ const [, setTick] = useState(0)
534
+ useEffect(() => {
535
+ if (localeService?.subscribe === undefined) return undefined
536
+ return localeService.subscribe(() => setTick((value) => value + 1))
537
+ }, [])
538
+ return h(Pill)
539
+ }
540
+
195
541
  function Pill() {
542
+ const updateState = useUpdateSnapshot()
543
+ const hasUpdate = updateState.phase === 'available' || updateState.phase === 'confirm'
196
544
  const [summary, setSummary] = useState(null)
197
545
  const [open, setOpen] = useState(false)
198
546
  const [error, setError] = useState(false)
199
547
  const [refreshMs, setRefreshMs] = useState(60000)
200
- const [view, setView] = useState('dashboard')
201
548
  const [refreshing, setRefreshing] = useState(false)
202
549
  const [hover, setHover] = useState(false)
203
550
  const [hint, setHint] = useState(false)
204
551
  const [panelMaxHeight, setPanelMaxHeight] = useState('70vh')
552
+ const [panelShift, setPanelShift] = useState(0)
205
553
  const pillRef = useRef(null)
206
554
 
207
555
  useEffect(() => {
208
- try {
209
- if (window.localStorage.getItem('token-dash-hint-seen') !== '1') setHint(true)
210
- } catch { /* ignore */ }
556
+ try { if (window.localStorage.getItem('token-dash-hint-seen') !== '1') setHint(true) } catch { /* ignore */ }
211
557
  }, [])
212
558
 
213
559
  const load = useCallback(async () => {
@@ -235,11 +581,7 @@ window.__ModuleLoader__.load({
235
581
  }, [load, refreshMs])
236
582
 
237
583
  const refreshSubs = useCallback(async () => {
238
- try {
239
- await fetch(`${API}/providers/refresh`, { method: 'POST', headers: { accept: 'application/json' } })
240
- } catch {
241
- // fall through: still refresh the summary below
242
- }
584
+ try { await fetch(`${API}/providers/refresh`, { method: 'POST', headers: { accept: 'application/json' } }) } catch { /* fall through */ }
243
585
  await load()
244
586
  }, [load])
245
587
 
@@ -249,191 +591,132 @@ window.__ModuleLoader__.load({
249
591
  }
250
592
  const closePanel = useCallback(() => {
251
593
  setOpen(false)
252
- // 等 React 移除浮层后再归还焦点,避免同步 focus 被随后的重渲染吞掉
253
594
  setTimeout(() => pillRef.current?.focus(), 0)
254
595
  }, [])
255
- const toggle = () => {
256
- dismissHint()
257
- // #30 三次定案:浮层从 pill 正上方弹出;pill 上方空间不足时收紧 maxHeight(视口顶 8px 间隙 + pill 间距 8px),内容内部滚动
596
+ const measurePanel = useCallback(() => {
258
597
  const rect = pillRef.current?.getBoundingClientRect()
259
- if (rect !== undefined) {
260
- const available = Math.round(rect.top) - 16
261
- setPanelMaxHeight(`${Math.max(200, Math.min(window.innerHeight * 0.7, available))}px`)
598
+ if (rect === undefined) return
599
+ const width = Math.min(320, window.innerWidth - 16)
600
+ setPanelShift(Math.min(0, window.innerWidth - 8 - rect.left - width))
601
+ const available = Math.round(rect.top) - 16
602
+ setPanelMaxHeight(`${Math.max(200, Math.min(window.innerHeight * 0.7, available))}px`)
603
+ }, [])
604
+ useEffect(() => {
605
+ if (!open) return
606
+ const node = pillRef.current
607
+ const observer = typeof ResizeObserver === 'function' ? new ResizeObserver(() => measurePanel()) : null
608
+ if (node !== null) observer?.observe(node)
609
+ window.addEventListener('resize', measurePanel)
610
+ const raf = requestAnimationFrame(measurePanel)
611
+ const timer = setTimeout(measurePanel, 120)
612
+ return () => {
613
+ observer?.disconnect()
614
+ window.removeEventListener('resize', measurePanel)
615
+ cancelAnimationFrame(raf)
616
+ clearTimeout(timer)
262
617
  }
263
- setOpen((value) => {
264
- if (!value) setView('dashboard')
265
- return !value
266
- })
618
+ }, [open, summary, measurePanel])
619
+ const toggle = () => {
620
+ dismissHint()
621
+ if (!open) measurePanel()
622
+ setOpen((value) => !value)
267
623
  }
268
624
 
269
625
  const providers = summary?.providers ?? []
270
626
  const current = providers.find((provider) => provider.id === summary?.currentProviderId) ?? providers[0]
271
- // #36/#38 定案:徽标 [API]/[订阅](词条统一),不显示 provider 名(hover title 与 aria-label 兜底)
272
627
  let prefix = '[API]'
273
628
  let bodyNodes = [h('span', { key: 'unknown' }, '--')]
274
- let ariaText = '按量 API'
629
+ let ariaText = tr('按量 API')
275
630
  if (current?.kind === 'subscription') {
276
- prefix = '[订阅]'
277
- bodyNodes = [
278
- h('span', { key: 'windows' }, ...subscriptionNodes(current, true)),
279
- ]
280
- ariaText = `${current.name},订阅,账户套餐,${subscriptionText(current)}`
631
+ prefix = `[${tr('订阅')}]`
632
+ bodyNodes = [h('span', { key: 'windows' }, ...subscriptionNodes(current, true))]
633
+ ariaText = tr('{name},订阅,账户套餐,{value}', { name: current.name, value: subscriptionText(current) })
281
634
  } else if (current !== undefined) {
282
635
  const budget = current.budget
283
- const hasBudget = budget !== undefined && budget.state !== 'unset'
636
+ const hasBudget = budget !== undefined && budget.state !== 'unset' && budget.amount > 0
284
637
  const balance = balanceText(current, summary?.showBalance)
285
638
  bodyNodes = [
286
- h('span', { key: 'budget' }, '预算 ',
287
- hasBudget
288
- ? h('b', { style: { ...styles.num, color: budgetColor(budget.state) } }, fmtRatio(budget.percent))
289
- : '未设置'),
290
- h('span', { key: 'today' }, `今日 ${fmtMoney(current.usage?.todayCost, current.currency)}`),
291
- balance === null ? null : h('span', { key: 'balance' }, `余额 ${balance}`),
639
+ h('span', { key: 'budget' }, `${tr('预算')} `, hasBudget
640
+ ? h('b', { style: { ...styles.num, color: budgetColor(budget.state) } }, fmtRatio(budget.percent))
641
+ : tr('未设置')),
642
+ h('span', { key: 'today' }, tr('今日 {value}', { value: fmtMoney(current.usage?.todayCost, current.currency) })),
643
+ balance === null ? null : h('span', { key: 'balance' }, tr('余额 {value}', { value: balance })),
292
644
  ].filter(Boolean)
293
- ariaText = `${current.name},按量 API,${hasBudget ? `预算已用 ${fmtRatio(budget.percent)}` : '预算未设置'},今日 ${fmtMoney(current.usage?.todayCost, current.currency)}${balance === null ? '' : `,余额 ${balance}`}`
645
+ 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 })}` })
294
646
  }
295
- const hoverTitle = `${current?.name ?? ''} · ${open ? '收起' : '展开'} Token 看板`
647
+ const hoverTitle = tr('{name} · {action} Token 看板', { name: current?.name ?? '', action: open ? tr('收起') : tr('展开') })
296
648
 
297
- // #30 三次定案 + 根因修复:Panel 必须渲染在 pillWrap 内部,
298
- // absolute 才以 pillWrap(position:relative)为锚——此前 Panel 是 pillWrap 的兄弟节点,
299
- // absolute 一直挂在宿主槽位容器上,导致 v1 起浮层位置从未真正对齐过 pill。
300
649
  return h('div', { style: styles.pillWrap },
301
- hint && !open ? h('span', { style: styles.hint, role: 'status' }, '点击查看 Token 看板') : null,
650
+ h('style', null, SPIN_CSS),
651
+ hint && !open ? h('span', { style: styles.hint, role: 'status' }, tr('点击查看 Token 看板')) : null,
302
652
  h('span', {
303
- ref: pillRef,
304
- 'data-testid': 'token-dash-pill',
653
+ ref: pillRef, 'data-testid': 'token-dash-pill',
305
654
  style: { ...styles.pill, ...(hover || open ? styles.pillHover : {}) },
306
- onClick: toggle,
307
- onMouseEnter: () => setHover(true), onMouseLeave: () => setHover(false),
655
+ onClick: toggle, onMouseEnter: () => setHover(true), onMouseLeave: () => setHover(false),
308
656
  onFocus: () => setHover(true), onBlur: () => setHover(false),
309
657
  onKeyDown: (event) => { if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); toggle() } },
310
658
  role: 'button', tabIndex: 0, 'aria-expanded': open, 'aria-haspopup': 'dialog',
311
- 'aria-label': `Token 看板:${ariaText}`,
312
- title: hoverTitle,
659
+ 'aria-label': tr('Token 看板:{text}', { text: ariaText }), title: hoverTitle,
313
660
  }, h('span', { key: 'prefix', style: styles.num }, prefix), ...bodyNodes,
314
661
  h('span', { key: 'chevron', style: styles.chevron }, open ? '⌄' : '⌃')),
315
662
  open ? h(Panel, {
316
- summary, error, view, refreshing, maxHeight: panelMaxHeight, onView: setView, onRefresh: load, onRefreshSubs: refreshSubs, onClose: closePanel,
663
+ summary, error, refreshing, maxHeight: panelMaxHeight, left: panelShift, hasUpdate,
664
+ onRefresh: load, onRefreshSubs: refreshSubs, onClose: closePanel,
317
665
  }) : null)
318
666
  }
319
667
 
320
- function ApiCard({ provider }) {
321
- const budget = provider.budget
322
- const hasBudget = budget !== undefined && budget.state !== 'unset'
323
- const color = budgetColor(budget?.state)
324
- // #37:单行紧凑式(框线图)——名称 + 预算段(#33 总额度并入)+ 今日 + 余额,第二行进度条
325
- return h('div', { 'data-testid': `token-dash-api-card-${provider.id}`, style: styles.card },
326
- h('div', { style: styles.row },
327
- h('b', { style: styles.nameEllipsis, title: provider.name }, provider.name),
328
- h('span', { style: styles.rowStart },
329
- hasBudget
330
- ? h('span', { 'data-testid': `token-dash-budget-${provider.id}` },
331
- '预算 ', h('b', { style: { color } }, fmtMoney(budget.used, provider.currency)),
332
- ` / ${fmtMoney(budget.amount, provider.currency)} · `,
333
- h('b', { style: { color } }, fmtRatio(budget.percent)))
334
- : h('span', { style: styles.muted }, '预算 未设置'),
335
- h('span', null, `今日 ${fmtMoney(provider.usage?.todayCost, provider.currency)}`),
336
- h('span', null, `余额 ${balanceText(provider, true) ?? '--'}`))),
337
- h('div', { style: { ...styles.bar, marginTop: 6, marginBottom: 0 } },
338
- h('div', {
339
- style: {
340
- ...(hasBudget ? { background: color } : styles.barNeutral),
341
- width: hasBudget ? `${Math.min(100, (budget.percent ?? 0) * 100)}%` : '100%',
342
- },
343
- })))
344
- }
345
-
346
- function SubscriptionCard({ provider }) {
347
- const windows = Array.isArray(provider.windows) ? provider.windows : []
348
- const resets = windows.map((plan) => plan.resetAt).filter((ts) => Number.isFinite(ts) && ts > 0)
349
- const nextReset = resets.length > 0 ? Math.min(...resets) : null
350
- return h('div', { 'data-testid': `token-dash-sub-card-${provider.id}`, style: { ...styles.card, marginTop: 0 } },
351
- h('div', { style: styles.row }, h('b', { style: styles.nameEllipsis, title: provider.name }, provider.name), h('span', { style: styles.muted }, '订阅')),
352
- windows.length === 0
353
- ? h('div', { style: { ...styles.muted, marginTop: 6 } }, '套餐查询失败')
354
- : h(React.Fragment, null,
355
- h('div', { style: { ...styles.row, marginTop: 6, flexWrap: 'wrap', justifyContent: 'flex-start' } }, subscriptionNodes(provider)),
356
- windows.map((plan) => h('div', { key: plan.key, style: styles.bar },
357
- h('div', { style: { ...styles.barFill, width: `${Math.min(100, plan.usedPercent ?? 0)}%` } }))),
358
- nextReset !== null ? h('div', { style: { ...styles.muted, marginTop: 2 } }, `重置 ${fmtReset(nextReset)}`) : null))
668
+ function PanelHeader({ tab, onTab, onRefresh, refreshing, onClose, showInfo, stale = false, hasUpdate = false }) {
669
+ const settingsLabel = h('span', { style: { display: 'inline-flex', alignItems: 'center', gap: 4 } },
670
+ tr('设置'),
671
+ hasUpdate ? h('span', {
672
+ 'aria-hidden': true,
673
+ style: { width: 4, height: 4, borderRadius: 999, background: T.accent },
674
+ }) : null)
675
+ return h('div', { style: styles.header },
676
+ h('div', { style: styles.headerTabs }, h(Segmented, {
677
+ value: tab, onChange: onTab, label: tr('看板页面'),
678
+ options: [{ value: 'usage', label: tr('用量') }, { value: 'settings', label: settingsLabel }],
679
+ })),
680
+ h('div', { style: styles.headerActions },
681
+ showInfo ? h(InfoTip, {
682
+ label: tr('查看支持的 API Key 范围'),
683
+ text: tr('目前支持 DeepSeek / Kimi / GLM / OpenRouter / Qwen API Key'),
684
+ }) : null,
685
+ h(IconButton, {
686
+ label: tr('刷新'), testid: 'token-dash-refresh', disabled: refreshing, onClick: onRefresh, dot: stale,
687
+ }, h(Icon, { name: refreshing ? 'loader' : 'refresh', size: 13 })),
688
+ h(IconButton, { label: tr('关闭'), testid: 'token-dash-close', onClick: onClose }, h(Icon, { name: 'close', size: 13 }))))
359
689
  }
360
690
 
361
- function ApiCostTable({ models }) {
362
- const groups = new Map()
363
- for (const model of models) {
364
- if (model.kind !== 'api') continue
365
- const list = groups.get(model.currency) ?? []
366
- list.push(model)
367
- groups.set(model.currency, list)
368
- }
369
- if (groups.size === 0) {
370
- // #40:空态保留表格结构(对齐 #32 用量表空态口径),不再整体隐藏
371
- return h('div', { 'data-testid': 'token-dash-cost-table', style: styles.card },
372
- h('div', { style: styles.row }, h('b', { style: styles.headerTitle }, 'API 费用明细 / 本月'), h('span', { style: styles.muted }, 'DSH 本机估算')),
373
- h('div', { style: { ...styles.muted, marginTop: 8 } }, `CNY 合计 ${fmtMoney(0, 'CNY')}`),
374
- h('div', { style: { overflowX: 'auto' } },
375
- h('table', { style: styles.table },
376
- h('thead', null, h('tr', null, h('th', { style: styles.th }, '模型'), h('th', { style: { ...styles.thRight, width: 64 } }, '占比'), h('th', { style: { ...styles.thRight, width: 96 } }, '费用'))),
377
- h('tbody', null, h('tr', { key: 'empty' },
378
- h('td', { style: styles.modelCell }, '—'),
379
- h('td', { style: styles.tdRight }, fmtRatio(0)),
380
- h('td', { style: styles.tdRight }, fmtMoney(0, 'CNY')))))))
381
- }
382
- return h('div', { 'data-testid': 'token-dash-cost-table', style: styles.card },
383
- h('div', { style: styles.row }, h('b', { style: styles.headerTitle }, 'API 费用明细 / 本月'), h('span', { style: styles.muted }, 'DSH 本机估算')),
384
- ...[...groups.entries()].flatMap(([currency, rows]) => [
385
- h('div', { key: `${currency}-head`, style: { ...styles.muted, marginTop: 8 } }, `${currency} 合计 ${fmtMoney(rows.reduce((sum, row) => sum + row.cost, 0), currency)}`),
386
- h('div', { key: `${currency}-wrap`, style: { overflowX: 'auto' } },
387
- h('table', { style: styles.table },
388
- h('thead', null, h('tr', null, h('th', { style: styles.th }, '模型'), h('th', { style: { ...styles.thRight, width: 64 } }, '占比'), h('th', { style: { ...styles.thRight, width: 96 } }, '费用'))),
389
- h('tbody', null, rows.map((model) => h('tr', { key: `${model.providerId}:${model.modelId}` },
390
- h('td', { style: styles.modelCell, title: modelTitle(model) }, modelTitle(model)),
391
- h('td', { style: styles.tdRight }, fmtRatio(model.share)),
392
- h('td', { style: { ...styles.tdRight, fontWeight: 600 } }, model.priced === false ? '未定价' : fmtMoney(model.cost, currency))))))),
393
- ]))
394
- }
395
-
396
- function UsageTable({ models }) {
397
- // #32:空态保留表格结构,数值显示 0(不再用 colSpan 文案行)
398
- const emptyRow = models.length === 0
399
- ? h('tr', { key: 'empty' },
400
- h('td', { style: styles.modelCell }, '—'),
401
- h('td', { style: styles.tdRight }, 0),
402
- h('td', { style: styles.tdRight }, fmtM(0)),
403
- h('td', { style: styles.tdRight }, fmtM(0)),
404
- h('td', { style: styles.tdRight }, fmtM(0)),
405
- h('td', { style: styles.tdRight }, '—'))
406
- : null
407
- return h('div', { 'data-testid': 'token-dash-usage-table', style: styles.card },
408
- h('div', { style: styles.row }, h('b', { style: styles.headerTitle }, '模型用量明细 / 本月'), h('span', { style: styles.muted }, `合计 ${fmtM(models.reduce((sum, model) => sum + (model.tokens?.total ?? 0), 0))}`)),
409
- h('div', { style: { overflowX: 'auto' } },
410
- h('table', { style: styles.table },
411
- h('thead', null, h('tr', null,
412
- h('th', { key: '模型', style: styles.th }, '模型'),
413
- h('th', { key: '请求', style: { ...styles.thRight, width: 44 } }, '请求'),
414
- h('th', { key: '输入', style: { ...styles.thRight, width: 56 } }, '输入'),
415
- h('th', { key: '命中', style: { ...styles.thRight, width: 56 } }, '命中'),
416
- h('th', { key: '输出', style: { ...styles.thRight, width: 56 } }, '输出'),
417
- h('th', { key: '命中率', style: { ...styles.thRight, width: 52 } }, '命中率'))),
418
- h('tbody', null,
419
- models.map((model) => h('tr', { key: `${model.providerId}:${model.modelId}` },
420
- h('td', { style: styles.modelCell, title: modelTitle(model) }, modelTitle(model)),
421
- h('td', { style: styles.tdRight }, model.requests),
422
- h('td', { style: styles.tdRight }, fmtM(model.tokens?.input ?? 0)),
423
- h('td', { style: styles.tdRight }, fmtM(model.tokens?.cacheRead ?? 0)),
424
- h('td', { style: styles.tdRight }, fmtM(model.tokens?.output ?? 0)),
425
- h('td', { style: styles.tdRight }, model.hitRate === null || model.hitRate === undefined ? '—' : fmtRatio(model.hitRate)))),
426
- emptyRow))))
427
- }
428
-
429
- function Panel({ summary, error, view, refreshing, maxHeight = '70vh', onView, onRefresh, onRefreshSubs, onClose }) {
691
+ function Panel({ summary, error, refreshing, maxHeight, left = 0, hasUpdate = false, onRefresh, onRefreshSubs, onClose }) {
692
+ const [tab, setTab] = useState('usage')
693
+ const [range, setRange] = useState('today')
694
+ const [usage, setUsage] = useState(null)
695
+ const [usageLoading, setUsageLoading] = useState(false)
696
+ const [usageError, setUsageError] = useState(false)
697
+ const [panelError, setPanelError] = useState(false)
430
698
  const panelRef = useRef(null)
431
699
 
432
- useEffect(() => {
433
- panelRef.current?.focus?.()
434
- }, [])
700
+ const usageSeq = useRef(0)
701
+ const loadUsage = useCallback(async () => {
702
+ const seq = ++usageSeq.current
703
+ setUsageLoading(true)
704
+ setUsageError(false)
705
+ try {
706
+ const data = await getJson(`/usage?range=${encodeURIComponent(range)}`)
707
+ if (seq !== usageSeq.current) return
708
+ setUsage(data)
709
+ } catch {
710
+ if (seq !== usageSeq.current) return
711
+ setUsageError(true)
712
+ } finally {
713
+ if (seq === usageSeq.current) setUsageLoading(false)
714
+ }
715
+ }, [range])
716
+
717
+ useEffect(() => { if (tab === 'usage') loadUsage() }, [tab, loadUsage])
718
+ useEffect(() => { setPanelError(error === true) }, [error])
435
719
 
436
- // #35:点击浮层外部关闭(Esc 按 D-15 修订不做);命中 pill/hint 时交给 pill 的 toggle,不视为外部
437
720
  useEffect(() => {
438
721
  const onDown = (event) => {
439
722
  const node = panelRef.current
@@ -446,80 +729,189 @@ window.__ModuleLoader__.load({
446
729
  return () => document.removeEventListener('mousedown', onDown)
447
730
  }, [onClose])
448
731
 
449
- const panelProps = {
450
- ref: panelRef, tabIndex: -1, role: 'dialog', 'aria-label': 'Token 看板',
732
+ const refreshAll = useCallback(async () => {
733
+ await onRefresh?.()
734
+ if (tab === 'usage') await loadUsage()
735
+ }, [onRefresh, tab, loadUsage])
736
+
737
+ const body = tab === 'usage'
738
+ ? h(UsageContent, {
739
+ summary, usage, range, loading: usageLoading, usageError, error: panelError,
740
+ onRange: setRange, onRetry: refreshAll, onRefreshSubs,
741
+ })
742
+ : h(SettingsContent, { summary, onRefresh, onRefreshSubs })
743
+
744
+ const stale = Number.isFinite(summary?.updatedAt)
745
+ && Date.now() - summary.updatedAt > (Number(summary?.refreshMs) || 60000) * 2
746
+ return h('div', {
747
+ ref: panelRef, tabIndex: -1, role: 'dialog', 'aria-label': tr('Token 看板'),
451
748
  'data-testid': 'token-dash-panel',
452
- style: { ...styles.panel, maxHeight },
453
- }
749
+ style: { ...styles.panel, maxHeight, left },
750
+ },
751
+ h(PanelHeader, {
752
+ tab, onTab: setTab, onRefresh: refreshAll, refreshing: refreshing || usageLoading,
753
+ onClose, showInfo: tab === 'usage', stale, hasUpdate,
754
+ }),
755
+ body)
756
+ }
454
757
 
455
- if (view === 'settings') {
456
- return h('div', panelProps,
457
- h(Settings, { summary, onBack: () => onView('dashboard'), onClose, onRefresh, onRefreshSubs }))
458
- }
758
+ function BudgetRow({ provider }) {
759
+ const budget = provider.budget
760
+ const hasBudget = budget !== undefined && budget.state !== 'unset' && budget.amount > 0
761
+ const color = budgetColor(budget?.state)
762
+ return h('div', { 'data-testid': `token-dash-api-row-${provider.id}`, style: styles.budgetRow },
763
+ h('span', { style: styles.budgetName, title: provider.name }, provider.name),
764
+ h('span', { style: { color, textAlign: 'right', fontWeight: 600, fontVariantNumeric: 'tabular-nums' } },
765
+ hasBudget ? fmtRatio(budget.percent) : tr('未设置')),
766
+ h(MiniBar, { ratio: hasBudget ? budget.percent : 1, neutral: !hasBudget }),
767
+ h('span', { style: { textAlign: 'right', color: T.muted, fontVariantNumeric: 'tabular-nums' } },
768
+ hasBudget ? `${fmtMoney(budget.used, provider.currency)}/${fmtMoney(budget.amount, provider.currency)}` : '—'),
769
+ h('span', { style: { textAlign: 'right', color: T.muted, fontVariantNumeric: 'tabular-nums' } },
770
+ `${tr('余额 {value}', { value: balanceText(provider, true) ?? '—' })}`))
771
+ }
772
+
773
+ function QuotaRow({ provider, reset = false }) {
774
+ const windows = Array.isArray(provider.windows) ? provider.windows : []
775
+ const resetText = reset && windows.length > 0 ? fmtTime(windows[windows.length - 1].resetAt) : null
776
+ return h('div', { 'data-testid': `token-dash-sub-row-${provider.id}`, style: { display: 'grid', gap: 2, padding: '2px 0' } },
777
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 6 } },
778
+ h('span', { style: styles.quotaName, title: provider.name }, provider.name),
779
+ resetText === null ? null : h('span', { style: { marginLeft: 'auto', color: T.weak, fontSize: 10.5 } }, `${resetText} ${tr('重置')}`)),
780
+ windows.length === 0
781
+ ? h('span', { style: styles.muted }, tr('套餐查询失败'))
782
+ : h('div', { style: { display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' } },
783
+ ...windows.map((plan) => h('span', { key: plan.key, style: { display: 'inline-flex', alignItems: 'center', gap: 4 } },
784
+ h('span', { style: { color: T.muted } }, windowLabel(plan.key)),
785
+ h('b', { style: { color: percentColor(plan.usedPercent ?? 0), fontVariantNumeric: 'tabular-nums' } }, fmtPercent(plan.usedPercent)),
786
+ h(MiniBar, { ratio: (Number(plan.usedPercent) || 0) / 100 })))))
787
+ }
788
+
789
+ function DetailGroup({ rows }) {
790
+ return h('div', { style: styles.group },
791
+ h('div', { style: styles.groupName }, rows[0]?.providerName ?? rows[0]?.providerId ?? ''),
792
+ ...rows.map((model) => h('div', { key: `${model.providerId}:${model.modelId}`, style: { display: 'grid', gap: 1 } },
793
+ h('div', { style: styles.modelRow },
794
+ h('span', { style: styles.modelName, title: model.displayName ?? model.modelId }, model.displayName ?? model.modelId),
795
+ model.kind === 'api'
796
+ ? h('span', { style: styles.modelCost }, model.priced === false
797
+ ? tr('未定价')
798
+ : `${model.approximate === true ? '≈' : ''}${fmtMoney(model.cost, model.currency)}`)
799
+ : null),
800
+ h('div', { 'data-testid': 'token-dash-usage-line', style: styles.usageLine },
801
+ h('span', { style: styles.usagePrimary },
802
+ h('span', { style: styles.usageLabel }, 'Tokens '),
803
+ h('span', { style: styles.usageValue }, fmtTokens(model.tokens?.total ?? 0)),
804
+ h('span', { style: { ...styles.usageValue, color: T.muted } },
805
+ ` [${fmtTokens(model.tokens?.input ?? 0)}/${fmtTokens(model.tokens?.cache ?? 0)}/${fmtTokens(model.tokens?.output ?? 0)}]`)),
806
+ h('span', { style: { ...styles.usageMeta, marginLeft: 'auto' } },
807
+ h('span', { style: styles.usageLabel }, `${tr('请求')} `), h('span', { style: styles.usageValue }, model.requests)),
808
+ h('span', { style: styles.usageMeta },
809
+ h('span', { style: styles.usageLabel }, `${tr('命中')} `), h('span', { style: styles.usageValue }, model.hitRate === null || model.hitRate === undefined ? '—' : fmtRatio(model.hitRate)))))))
810
+ }
459
811
 
460
- const models = summary?.breakdown?.models ?? []
812
+ function UsageContent({ summary, usage, range, loading, usageError, error, onRange, onRetry, onRefreshSubs }) {
813
+ if (summary === null) {
814
+ return h('div', { style: styles.section },
815
+ h('div', { style: styles.empty }, error ? tr('Token 数据不可用') : tr('Token 数据加载中…')),
816
+ error ? h('button', { type: 'button', style: styles.button, onClick: onRetry }, tr('重试')) : null)
817
+ }
461
818
  const providers = summary?.providers ?? []
462
819
  const api = providers.filter((provider) => provider.kind === 'api')
463
820
  const subscriptions = providers.filter((provider) => provider.kind === 'subscription')
464
- const ago = fmtAgo(summary?.updatedAt)
465
- return h('div', panelProps,
466
- h('div', { style: styles.titleBar },
467
- h('b', { style: styles.headerTitle }, 'Token 看板'),
468
- h('span', { style: styles.buttonGroup },
469
- h('button', { style: { ...styles.button, opacity: refreshing ? 0.6 : 1 }, disabled: refreshing, onClick: onRefresh }, refreshing ? '刷新中…' : '刷新'),
470
- h('button', { style: styles.button, onClick: () => onView('settings') }, '设置'),
471
- h('button', { style: styles.button, onClick: onClose }, '关闭'))),
472
- error ? h('div', { style: { ...styles.row, color: '#e05a5a', marginTop: 6 } },
473
- h('span', null, 'Token 数据不可用'),
474
- h('button', { 'data-testid': 'token-dash-retry', style: styles.button, onClick: onRefresh }, '重试')) : null,
475
- h('div', { style: { ...styles.muted, marginTop: 6 } }, '自动侦测 API Key 类型:DeepSeek / Kimi / GLM / OpenRouter / Qwen'),
476
- providers.length === 0 ? h('div', { style: { ...styles.muted, marginTop: 10 } }, '未检测到已配置供应商') : null,
477
- api.length > 0 ? h('div', { 'data-testid': 'token-dash-api-section', style: { marginTop: 8 } },
478
- h('div', { style: styles.row }, h('b', { style: styles.headerTitle }, 'API 按量'), h('span', { style: styles.muted }, `已检测 ${api.length} · ${ago}`)),
479
- h('div', { style: api.length > 3 ? styles.scrollList : null },
480
- api.map((provider) => h(ApiCard, { key: provider.id, provider })))) : null,
481
- subscriptions.length > 0 ? h('div', { 'data-testid': 'token-dash-sub-section', style: { marginTop: 8 } },
482
- h('div', { style: styles.row },
483
- h('b', { style: styles.headerTitle }, '订阅套餐'),
484
- h('span', { style: styles.rowStart }, api.length === 0 ? h('span', { style: styles.muted }, ago) : null,
485
- h('button', { 'data-testid': 'token-dash-rescan', style: styles.button, onClick: onRefreshSubs }, '重新检测'))),
486
- h('div', { style: styles.subGrid }, subscriptions.map((provider) => h(SubscriptionCard, { key: provider.id, provider })))) : null,
487
- h(ApiCostTable, { models }),
488
- h(UsageTable, { models }))
489
- }
490
-
491
- function modeSelect(provider, prefs, savePrefs) {
492
- const value = prefs.billingModes?.[provider.id] ?? (provider.kind === 'subscription' ? 'subscription' : 'api')
493
- return h('select', {
494
- value,
495
- 'aria-label': `${provider.name} 计费模式`,
496
- onChange: (event) => savePrefs({ billingModes: { ...(prefs.billingModes ?? {}), [provider.id]: event.target.value } }),
497
- style: styles.select,
498
- },
499
- h('option', { value: 'api' }, '按量 API'),
500
- provider.canSubscribe === true ? h('option', { value: 'subscription' }, '订阅套餐') : null,
501
- h('option', { value: 'hide' }, '不显示'))
821
+ const models = Array.isArray(usage?.models) ? usage.models : []
822
+ const groups = new Map()
823
+ for (const model of models) {
824
+ const list = groups.get(model.providerId) ?? []
825
+ list.push(model)
826
+ groups.set(model.providerId, list)
827
+ }
828
+ const pending = usage === null
829
+ const total = usage?.total ?? null
830
+ const costEntries = Object.entries(usage?.totals ?? {})
831
+ const hasUsage = usage !== null
832
+ const fixed = []
833
+ if (api.length > 0) {
834
+ fixed.push(h('div', { key: 'api-head', style: styles.sectionHead }, h('b', { style: styles.title }, tr('本月预算(已检测 {count})', { count: api.length }))))
835
+ fixed.push(...api.map((provider) => h(BudgetRow, { key: provider.id, provider })))
836
+ }
837
+ if (subscriptions.length > 0) {
838
+ fixed.push(h('div', { key: 'sub-head', style: { ...styles.sectionHead, marginTop: 4 } },
839
+ h('b', { style: styles.title }, tr('订阅套餐(账户级,已检测 {count})', { count: subscriptions.length })),
840
+ h(IconButton, { label: tr('重新检测订阅配额'), testid: 'token-dash-rescan', onClick: () => { void onRefreshSubs?.() } },
841
+ h(Icon, { name: 'refresh', size: 12 }))))
842
+ fixed.push(...subscriptions.map((provider) => h(QuotaRow, { key: provider.id, provider, reset: true })))
843
+ }
844
+ if (fixed.length === 0) {
845
+ const degraded = summary?.providersDegraded === true
846
+ fixed.push(h('div', { key: 'empty', style: styles.empty },
847
+ degraded ? tr('供应商探测失败') : tr('未检测到已配置供应商'),
848
+ degraded ? h('button', { type: 'button', style: styles.button, onClick: onRetry }, tr('重试')) : null))
849
+ }
850
+ return h(React.Fragment, null,
851
+ h('div', { style: styles.section }, ...fixed),
852
+ h('div', { style: { marginTop: 10 } }, h(Segmented, {
853
+ value: range, onChange: onRange, label: tr('时间范围'),
854
+ options: RANGES.map(([value, label]) => ({ value, label: tr(label) })),
855
+ })),
856
+ error || usageError ? h('div', { style: styles.errorStrip, role: 'alert' },
857
+ h('span', null, error ? tr('刷新失败,保留上次数据') : tr('范围数据加载失败')),
858
+ h('button', { type: 'button', style: styles.button, onClick: onRetry }, tr('重试'))) : null,
859
+ h('div', { style: styles.section },
860
+ h('div', { style: styles.rangeCard },
861
+ h('div', { style: styles.tile },
862
+ h('div', { style: styles.tileLabel }, tr('总费用')),
863
+ ...costEntries.map(([currency, value]) => h('div', { key: currency, style: { ...styles.tileValue, fontSize: 14, color: T.ok } }, fmtMoney(value.cost, currency))),
864
+ pending ? h('div', { key: 'pending', style: { ...styles.tileValue, fontSize: 14, color: T.ok } }, '—') : null,
865
+ h('div', { style: styles.tileDetail }, tr('按币种'))),
866
+ h('div', { style: styles.tile },
867
+ h('div', { style: styles.tileLabel },
868
+ `${tr('真实 Tokens')} `,
869
+ h(InfoTip, {
870
+ label: tr('Tokens 括号说明'),
871
+ text: tr('Tokens 括号顺序:输入 / 缓存(读+写)/ 输出'),
872
+ variant: 'inline',
873
+ }, h(Icon, { name: 'info', size: 11 }))),
874
+ h('div', { style: styles.tileValue }, pending ? '—' : fmtTokens(total?.tokens ?? 0)),
875
+ h('div', { style: styles.tileDetail }, pending
876
+ ? '—'
877
+ : tr('入 {input} · 缓存 {cache} · 出 {output}', {
878
+ input: fmtTokens(total?.input ?? 0),
879
+ cache: fmtTokens(total?.cache ?? 0),
880
+ output: fmtTokens(total?.output ?? 0),
881
+ })))),
882
+ !hasUsage && loading ? h('div', { style: styles.empty }, tr('范围数据加载中…')) : null,
883
+ hasUsage && models.length === 0 ? h('div', { style: styles.empty }, tr('范围内暂无消耗')) : null,
884
+ hasUsage && models.length > 0 ? [...groups.entries()].map(([providerId, rows]) => h(DetailGroup, { key: providerId, rows })) : null))
502
885
  }
503
886
 
504
- function Settings({ summary, onBack, onClose, onRefresh, onRefreshSubs }) {
887
+ function SettingsContent({ summary, onRefresh, onRefreshSubs }) {
505
888
  const [prefs, setPrefs] = useState(null)
506
889
  const [budgetText, setBudgetText] = useState({})
890
+ const [fieldErrors, setFieldErrors] = useState({})
507
891
  const [status, setStatus] = useState(null)
508
- const [update, setUpdate] = useState({ phase: 'idle' })
892
+ const [subRefreshing, setSubRefreshing] = useState(false)
893
+ const update = useUpdateSnapshot()
509
894
  const [logMeta, setLogMeta] = useState(null)
895
+ const [importing, setImporting] = useState(false)
896
+ const fileRef = useRef(null)
510
897
 
511
- useEffect(() => {
512
- getJson('/prefs').then((data) => {
898
+ const loadPrefs = useCallback(async () => {
899
+ try {
900
+ const data = await getJson('/prefs')
513
901
  setPrefs(data)
514
902
  const next = {}
515
- for (const [id, value] of Object.entries(data.budgets ?? {})) next[id] = String(value.amount ?? '')
903
+ for (const [id, value] of Object.entries(data.budgets ?? {})) next[id] = value.amount > 0 ? String(value.amount) : ''
516
904
  setBudgetText(next)
517
- }).catch(() => setStatus({ text: '读取失败', error: true }))
905
+ } catch {
906
+ setStatus({ text: tr('设置加载失败'), error: true })
907
+ }
518
908
  }, [])
519
909
 
910
+ useEffect(() => { loadPrefs() }, [loadPrefs])
911
+
520
912
  function flash(text, error = false) {
521
913
  setStatus({ text, error })
522
- if (error !== true) setTimeout(() => setStatus((current) => (current?.text === text ? null : current)), 1500)
914
+ if (error !== true) setTimeout(() => setStatus((current) => (current?.text === text ? null : current)), 1600)
523
915
  }
524
916
 
525
917
  async function savePrefs(patch) {
@@ -527,31 +919,46 @@ window.__ModuleLoader__.load({
527
919
  try {
528
920
  const saved = await putPrefs({ ...prefs, ...patch })
529
921
  setPrefs(saved)
530
- flash('已保存')
922
+ flash(tr('已保存'))
531
923
  void onRefresh?.()
532
924
  return saved
533
925
  } catch (error) {
534
- setStatus({ text: `保存失败:${error.message}`, error: true })
926
+ setStatus({ text: tr('保存失败:{reason}', { reason: error.message }), error: true })
535
927
  return null
536
928
  }
537
929
  }
538
930
 
539
931
  async function saveBudget(provider, raw) {
540
- const text = String(raw).replace(/[\u00a5$,\s]/g, '')
932
+ const text = String(raw).trim()
933
+ const budgets = { ...(prefs?.budgets ?? {}) }
934
+ if (text === '') {
935
+ // 显式 0:清空后不再被 DEFAULT_BUDGET 覆盖
936
+ budgets[provider.id] = { amount: 0, currency: provider.currency }
937
+ const saved = await savePrefs({ budgets })
938
+ if (saved !== null) { setBudgetText((current) => ({ ...current, [provider.id]: '' })); setFieldErrors((current) => ({ ...current, [provider.id]: null })) }
939
+ return
940
+ }
541
941
  const amount = Number(text)
542
- if (text === '' || !Number.isFinite(amount) || amount < 0 || amount > 9999999.99) {
543
- setStatus({ text: '请输入 0 ~ 9,999,999.99', error: true })
942
+ if (!/^\d+(?:\.\d{1,2})?$/.test(text) || !Number.isFinite(amount) || amount > 9999999.99) {
943
+ setFieldErrors((current) => ({ ...current, [provider.id]: tr('请输入 0 或正数') }))
544
944
  return
545
945
  }
546
- const budgets = { ...(prefs?.budgets ?? {}), [provider.id]: { amount: Math.round(amount * 100) / 100, currency: provider.currency } }
946
+ budgets[provider.id] = { amount, currency: provider.currency }
547
947
  const saved = await savePrefs({ budgets })
548
- if (saved !== null) setBudgetText((current) => ({ ...current, [provider.id]: String(saved.budgets[provider.id]?.amount ?? '') }))
948
+ if (saved !== null) {
949
+ setBudgetText((current) => ({ ...current, [provider.id]: String(saved.budgets[provider.id]?.amount ?? '') }))
950
+ setFieldErrors((current) => ({ ...current, [provider.id]: null }))
951
+ }
549
952
  }
550
953
 
551
954
  async function refreshSubscriptions() {
552
- flash('检测中…')
553
- await onRefreshSubs?.()
554
- flash('已重新检测')
955
+ setSubRefreshing(true)
956
+ try {
957
+ await onRefreshSubs?.()
958
+ flash(tr('已重新检测'))
959
+ } finally {
960
+ setSubRefreshing(false)
961
+ }
555
962
  }
556
963
 
557
964
  async function openLogs() {
@@ -560,19 +967,18 @@ window.__ModuleLoader__.load({
560
967
  setLogMeta(meta)
561
968
  const app = /Mac|iPhone|iPad/.test(navigator.platform) ? 'finder' : /Linux/.test(navigator.platform) ? 'filemanager' : 'explorer'
562
969
  const response = await fetch('/open-in-app/open', {
563
- method: 'POST',
564
- headers: { 'content-type': 'application/json' },
970
+ method: 'POST', headers: { 'content-type': 'application/json' },
565
971
  body: JSON.stringify({ app, path: meta.dir }),
566
972
  })
567
973
  if (!response.ok) throw new Error('open-failed')
568
- flash('已打开日志文件夹')
974
+ flash(tr('已打开日志文件夹'))
569
975
  } catch {
570
976
  try {
571
977
  const meta = logMeta ?? await getJson('/logs/meta')
572
978
  await navigator.clipboard.writeText(meta.dir)
573
- flash('无法打开,已复制路径')
979
+ flash(tr('无法打开,已复制路径'))
574
980
  } catch {
575
- setStatus({ text: '打开日志失败', error: true })
981
+ setStatus({ text: tr('打开日志失败'), error: true })
576
982
  }
577
983
  }
578
984
  }
@@ -587,156 +993,183 @@ window.__ModuleLoader__.load({
587
993
  link.download = 'dsh-token-dash.log'
588
994
  link.click()
589
995
  URL.revokeObjectURL(url)
590
- flash('日志已导出')
996
+ flash(tr('日志已导出'))
591
997
  } catch {
592
- setStatus({ text: '日志导出失败', error: true })
998
+ setStatus({ text: tr('日志导出失败'), error: true })
593
999
  }
594
1000
  }
595
1001
 
596
- async function checkUpdate() {
597
- setUpdate({ phase: 'checking' })
1002
+ async function exportData() {
598
1003
  try {
599
- const data = await getJson('/update')
600
- if (data.published === false) setUpdate({ phase: 'done', text: '未发布' })
601
- else if (data.hasUpdate) setUpdate({ phase: 'confirm', latest: data.latest })
602
- else setUpdate({ phase: 'done', text: '已是最新' })
1004
+ const data = await getJson('/export')
1005
+ const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
1006
+ const url = URL.createObjectURL(blob)
1007
+ const link = document.createElement('a')
1008
+ link.href = url
1009
+ link.download = `dsh-token-dash-${data.month}.json`
1010
+ link.click()
1011
+ URL.revokeObjectURL(url)
1012
+ flash(tr('数据已导出'))
603
1013
  } catch {
604
- setUpdate({ phase: 'error', text: '检查失败' })
1014
+ setStatus({ text: tr('数据导出失败'), error: true })
605
1015
  }
606
1016
  }
607
1017
 
608
- async function installUpdate() {
609
- setUpdate({ phase: 'installing' })
1018
+ async function importData(file) {
1019
+ if (file === null || file === undefined) return
1020
+ setImporting(true)
610
1021
  try {
611
- const res = await fetch(`${API}/update/install`, { method: 'POST', headers: { accept: 'application/json' } })
612
- const body = await res.json().catch(() => ({}))
613
- const data = body?.data
614
- if (body?.ok === true) setUpdate({ phase: 'done', text: '已更新,重启 DSH 后生效' })
615
- else setUpdate({ phase: 'error', text: `更新失败(${data?.reason ?? 'unknown'})`, command: data?.command })
1022
+ const bundle = JSON.parse(await file.text())
1023
+ const result = await postJson('/import', bundle)
1024
+ await loadPrefs()
1025
+ await onRefresh?.()
1026
+ flash(tr('已导入 {month} 数据', { month: result.month }))
616
1027
  } catch (error) {
617
- setUpdate({ phase: 'error', text: `更新失败(${error.message})` })
1028
+ setStatus({ text: tr('导入失败:{reason}', { reason: error.message }), error: true })
1029
+ } finally {
1030
+ setImporting(false)
1031
+ if (fileRef.current !== null) fileRef.current.value = ''
618
1032
  }
619
1033
  }
620
1034
 
1035
+ const checkUpdate = () => { void checkForUpdate({ manual: true }) }
1036
+ const installUpdate = () => { void installUpdateRequest() }
1037
+
621
1038
  async function copyCommand() {
622
- try {
623
- await navigator.clipboard.writeText(update.command ?? '')
624
- flash('命令已复制')
625
- } catch {
626
- setStatus({ text: '复制失败', error: true })
627
- }
1039
+ try { await navigator.clipboard.writeText(update.command ?? ''); flash(tr('命令已复制')) } catch { setStatus({ text: tr('复制失败'), error: true }) }
628
1040
  }
629
1041
 
630
- // #34:状态提示放"关闭"左侧,固定宽度占位——出现/消失不改变标题栏布局,弹窗不 resize
631
- const statusSlot = h('span', {
632
- role: 'status', 'aria-live': 'polite',
633
- style: { minWidth: 88, textAlign: 'right', fontSize: 11, opacity: 0.85, color: status?.error === true ? '#e05a5a' : undefined },
634
- }, status?.text ?? '')
635
-
636
- const header = h('div', { style: styles.titleBar },
637
- h('div', { style: styles.rowStart },
638
- h('button', { style: styles.button, onClick: onBack }, '← 返回'),
639
- h('b', { style: styles.headerTitle }, 'Token 看板')),
640
- h('span', { style: styles.rowStart }, statusSlot, h('button', { style: styles.button, onClick: onClose }, '关闭')))
641
-
642
- if (prefs === null) return h('div', { 'data-testid': 'token-dash-settings', style: { fontSize: 12, display: 'grid', gap: 10 } }, header, '加载中…')
1042
+ if (prefs === null) {
1043
+ return h('div', { 'data-testid': 'token-dash-settings', style: { display: 'grid', gap: 10 } },
1044
+ h('div', { style: styles.empty }, status?.text ?? tr('设置加载中…')),
1045
+ status?.error === true ? h('button', { type: 'button', style: styles.button, onClick: loadPrefs }, tr('重试')) : null)
1046
+ }
643
1047
 
644
1048
  const providers = summary?.providers ?? []
645
1049
  const api = providers.filter((provider) => provider.kind === 'api')
646
1050
  const subscriptions = providers.filter((provider) => provider.kind === 'subscription')
647
1051
  const version = summary?.version ?? ''
648
- const cardStyle = { ...styles.card, marginTop: 0, display: 'grid', gap: 10, background: 'rgba(128,128,128,.05)' }
649
- const section = (title, body, action = null) => h('section', { style: { display: 'grid', gap: 8 } },
650
- h('div', { style: styles.row }, h('b', { style: styles.headerTitle }, title), action),
651
- body)
1052
+ const catalog = summary?.catalog
1053
+ const section = (title, body, action = null, testid) => h('div', { 'data-testid': testid, style: styles.section },
1054
+ h('div', { style: styles.sectionHead }, h('b', { style: styles.title }, title), action), body)
652
1055
 
653
- // #39:API 卡删除计费模式下拉——单行:provider 名 + 月度预算 + 输入框 + 币种(模式依赖自动侦测)
654
- const apiCards = api.map((provider) => h('div', { key: provider.id, style: cardStyle },
655
- h('div', { style: styles.row },
656
- h('b', { style: styles.nameEllipsis, title: provider.name }, provider.name),
1056
+ const apiRows = api.map((provider) => h('div', { key: provider.id, style: { display: 'grid', gap: 3, padding: '3px 0' } },
1057
+ h('div', { style: styles.row }, h('b', { style: styles.budgetName, title: provider.name }, provider.name), h('span', { style: styles.weak }, tr('按量 API'))),
1058
+ h('div', { style: styles.row }, h('span', { style: styles.muted }, tr('月度预算')),
657
1059
  h('span', { style: styles.rowStart },
658
- h('span', { style: styles.muted }, '月度预算'),
659
1060
  h('input', {
660
- type: 'text', inputMode: 'decimal', 'aria-label': `${provider.name} 月度预算`,
661
- value: budgetText[provider.id] ?? (provider.budget?.amount ? String(provider.budget.amount) : ''),
662
- onChange: (event) => setBudgetText({ ...budgetText, [provider.id]: event.target.value }),
1061
+ type: 'text', inputMode: 'decimal', 'data-testid': `token-dash-budget-input-${provider.id}`,
1062
+ 'aria-label': tr('{name} 月度预算', { name: provider.name }), 'aria-invalid': fieldErrors[provider.id] !== undefined && fieldErrors[provider.id] !== null,
1063
+ value: budgetText[provider.id] ?? String(provider.budget?.amount ?? ''), onChange: (event) => setBudgetText({ ...budgetText, [provider.id]: event.target.value }),
663
1064
  onBlur: (event) => saveBudget(provider, event.currentTarget.value),
664
1065
  onKeyDown: (event) => { if (event.key === 'Enter') { event.preventDefault(); event.currentTarget.blur() } },
665
- style: styles.input,
666
- }),
667
- h('span', { style: styles.muted }, provider.currency)))))
668
-
669
- const subscriptionRows = subscriptions.map((provider) => h('div', { key: provider.id, style: styles.row },
670
- h('span', { style: styles.nameEllipsis, title: provider.name }, provider.name),
671
- h('span', { style: styles.rowStart },
672
- modeSelect(provider, prefs, savePrefs),
673
- h('span', { style: styles.muted }, `${subscriptionText(provider)} · 账户套餐`))))
674
-
675
- let updateControl = h('button', { style: styles.button, onClick: checkUpdate }, '检查更新')
676
- if (update.phase === 'checking') updateControl = h('span', { style: styles.muted }, '检查中…')
677
- else if (update.phase === 'confirm') updateControl = h('span', { style: styles.rowStart },
678
- h('span', null, `发现 ${update.latest}`),
679
- h('button', { style: styles.button, onClick: installUpdate }, '更新'),
680
- h('button', { style: styles.button, onClick: () => setUpdate({ phase: 'idle' }) }, '取消'))
681
- else if (update.phase === 'installing') updateControl = h('span', { style: styles.muted }, '更新中…')
682
- else if (update.phase === 'done') updateControl = h('span', { style: styles.muted }, update.text)
683
- else if (update.phase === 'error') updateControl = h('span', { style: styles.rowStart },
684
- h('span', { style: { color: '#e05a5a' } }, update.text),
685
- update.command ? h('button', { style: styles.button, onClick: copyCommand }, '复制命令') : null)
686
-
687
- return h('div', { 'data-testid': 'token-dash-settings', style: { fontSize: 12, display: 'grid', gap: 12 } },
688
- header,
689
- api.length > 0 ? section(`API 计费(已检测 ${api.length})`, h('div', { style: { display: 'grid', gap: 8 } }, ...apiCards)) : null,
690
- subscriptions.length > 0 ? section(`订阅计费(已检测 ${subscriptions.length})`,
691
- h('div', { style: cardStyle }, ...subscriptionRows),
692
- h('button', { 'data-testid': 'token-dash-rescan', style: styles.button, onClick: refreshSubscriptions }, '重新检测')) : null,
693
- section('显示', h('div', { style: cardStyle },
694
- h('div', { style: styles.row }, h('span', null, '刷新间隔'),
695
- h(Segmented, { value: prefs.refreshMs, onChange: (ms) => savePrefs({ refreshMs: ms }) })),
696
- h('div', { style: styles.row }, h('span', null, '账户余额'),
697
- h(Toggle, { checked: prefs.showBalance, onChange: (next) => savePrefs({ showBalance: next }) })))),
698
- section('日志', h('div', { style: cardStyle },
699
- h('div', { style: styles.row },
700
- h('span', null, '查看日志'),
1066
+ style: { ...styles.input, borderColor: fieldErrors[provider.id] ? T.over : T.border },
1067
+ }), h('span', { style: styles.muted }, provider.currency))),
1068
+ fieldErrors[provider.id] ? h('div', { style: { color: T.over, fontSize: 10.5, textAlign: 'right' }, role: 'alert' }, fieldErrors[provider.id]) : null))
1069
+
1070
+ const subRows = subscriptions.map((provider) => h('div', { key: provider.id, style: { padding: '3px 0' } },
1071
+ h('div', { style: styles.row }, h('b', { style: styles.budgetName, title: provider.name }, provider.name), h('span', { style: styles.weak }, tr('账户套餐'))),
1072
+ h('div', { style: { marginTop: 3 } }, h(QuotaRow, { provider, reset: true }))))
1073
+
1074
+ let updateControl
1075
+ const updateBusy = update.phase === 'checking' || update.phase === 'installing'
1076
+ const updateAvailable = update.phase === 'available'
1077
+ const updateError = update.phase === 'error'
1078
+ if (update.phase === 'confirm') {
1079
+ updateControl = h('span', { style: styles.rowStart },
1080
+ h('span', { style: styles.muted }, tr('发现 {version}', { version: update.latest })),
1081
+ h('button', { type: 'button', style: styles.button, onClick: installUpdate }, tr('更新')),
1082
+ h('button', { type: 'button', style: styles.button, onClick: () => emitUpdate({ phase: 'idle', latest: null }) }, tr('取消')))
1083
+ } else {
1084
+ updateControl = h('span', { style: styles.rowStart },
1085
+ updateError && update.command
1086
+ ? h('button', { type: 'button', style: styles.button, onClick: copyCommand }, tr('复制命令'))
1087
+ : null,
1088
+ h(IconButton, {
1089
+ label: updateAvailable ? tr('发现 {version},点击更新', { version: update.latest }) : tr('检查更新'),
1090
+ testid: 'token-dash-update', disabled: updateBusy,
1091
+ dot: updateAvailable || updateError,
1092
+ dotColor: updateError ? T.over : T.accent,
1093
+ onClick: () => {
1094
+ if (updateAvailable) emitUpdate({ phase: 'confirm', latest: update.latest })
1095
+ else checkUpdate()
1096
+ },
1097
+ }, h(Icon, {
1098
+ name: updateBusy ? 'loader' : update.phase === 'done' ? 'check' : 'download', size: 13,
1099
+ })))
1100
+ }
1101
+
1102
+ const statusText = update.text ?? status?.text ?? tr('版本 {version}', { version })
1103
+ return h('div', { 'data-testid': 'token-dash-settings', style: { display: 'grid', gridTemplateColumns: 'minmax(0,1fr)', gap: 0, minWidth: 0 } },
1104
+ api.length > 0 ? section(tr('API 计费(已检测 {count})', { count: api.length }), h('div', null, ...apiRows)) : null,
1105
+ subscriptions.length > 0 ? section(tr('订阅(已检测 {count})', { count: subscriptions.length }),
1106
+ h('div', null, ...subRows),
1107
+ h(IconButton, { label: tr('重新检测订阅配额'), testid: 'token-dash-settings-rescan', disabled: subRefreshing, onClick: refreshSubscriptions }, h(Icon, { name: subRefreshing ? 'loader' : 'refresh', size: 12 }))) : null,
1108
+ section(tr('显示'), h('div', { style: { display: 'grid', gap: 7 } },
1109
+ h('div', { style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 } },
1110
+ h('span', { style: { whiteSpace: 'nowrap' } }, tr('刷新间隔')),
1111
+ 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) })) }))),
1112
+ h('div', { style: styles.row }, h('span', null, tr('账户余额')), h(Toggle, { checked: prefs.showBalance, label: tr('账户余额'), onChange: (next) => savePrefs({ showBalance: next }) })))),
1113
+ section(tr('数据与日志'), [
1114
+ h('div', { key: 'log', style: styles.row },
1115
+ h('span', null, tr('日志')),
1116
+ h('span', { style: styles.rowStart },
1117
+ h('button', { type: 'button', 'data-testid': 'token-dash-log-open', style: styles.button, onClick: openLogs }, tr('打开日志文件夹')),
1118
+ h('button', { type: 'button', 'data-testid': 'token-dash-log-export', style: styles.button, onClick: exportLogs }, tr('导出日志')))),
1119
+ h('div', { key: 'data', style: styles.row },
1120
+ h('span', null, tr('备份与恢复')),
701
1121
  h('span', { style: styles.rowStart },
702
- h('button', { 'data-testid': 'token-dash-log-open', style: styles.button, onClick: openLogs }, '打开日志文件夹'),
703
- h('button', { 'data-testid': 'token-dash-log-export', style: styles.button, onClick: exportLogs }, '导出日志'))))),
704
- section('价格与版本', h('div', { style: cardStyle },
705
- h('div', { style: styles.row },
706
- h('span', null, '查看价格明细'),
707
- h('span', { style: { display: 'flex', flexWrap: 'wrap', justifyContent: 'flex-end', gap: 8 } },
708
- (summary?.pricingLinks ?? []).map((link) => h('a', { key: link.id ?? link.label, href: link.url, target: '_blank', rel: 'noopener', style: { ...styles.link, marginLeft: 0 } }, link.label)))),
709
- h('div', { style: styles.row },
710
- h('span', { style: styles.muted }, `版本 ${version}`),
711
- updateControl))),
712
- h('div', { style: styles.muted }, 'API 费用按 catalog/社区价估算;订阅只显示账户配额'))
1122
+ h('button', { type: 'button', 'data-testid': 'token-dash-data-export', style: styles.button, onClick: () => { void exportData() } }, tr('导出数据')),
1123
+ h('button', { type: 'button', 'data-testid': 'token-dash-data-import', disabled: importing, style: styles.button, onClick: () => fileRef.current?.click() }, importing ? tr('导入中…') : tr('导入数据')),
1124
+ h('input', { ref: fileRef, type: 'file', accept: 'application/json', style: { display: 'none' }, onChange: (event) => { void importData(event.target.files?.[0]) } })))],
1125
+ null, 'token-dash-data-log-section'),
1126
+ section(tr('价格与版本'), h('div', { style: { display: 'grid', gap: 6 } },
1127
+ h('div', { 'data-testid': 'token-dash-price-links', style: styles.priceLinks },
1128
+ (summary?.pricingLinks ?? []).map((link) => h('a', { key: link.id ?? link.label, href: link.url, target: '_blank', rel: 'noopener', style: styles.link }, linkLabel(link)))),
1129
+ h('div', { style: { ...styles.muted, fontSize: 10 } },
1130
+ `${tr('价格表')} `, formatCatalogTime(catalog?.updatedAt), ' · ',
1131
+ catalog?.url
1132
+ ? h('a', { href: catalog.url, target: '_blank', rel: 'noopener', style: { ...styles.link, color: T.muted } }, tr('社区'))
1133
+ : h('span', null, sourceLabel(catalog?.source))),
1134
+ 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'),
1135
+ api.length === 0 && subscriptions.length === 0 ? h('div', { style: styles.empty }, tr('未检测到已配置供应商')) : null)
713
1136
  }
714
1137
 
715
1138
  return {
716
1139
  name: PKG,
717
- inject: ['slots'],
1140
+ inject: ['slots', 'locale'],
718
1141
  apply(ctx) {
1142
+ if (ctx.locale !== undefined) {
1143
+ localeService = ctx.locale
1144
+ try {
1145
+ ctx.effect?.(() => ctx.locale.register('token-dash', MESSAGES), 'locale:dictionaries')
1146
+ activeTranslate = ctx.locale.bind('token-dash')
1147
+ } catch { /* keep built-in zh fallback */ }
1148
+ }
1149
+ if (!autoUpdateChecked) {
1150
+ autoUpdateChecked = true
1151
+ ctx.effect?.(() => {
1152
+ const timer = setTimeout(() => { void checkForUpdate({ manual: false }) }, 4000)
1153
+ return () => clearTimeout(timer)
1154
+ }, 'update:startup')
1155
+ }
719
1156
  const slots = typeof ctx.get === 'function' ? ctx.get('slots') : ctx.slots
720
1157
  if (slots === undefined || typeof slots.inject !== 'function') return
721
- // #46:slot 挂载上报 host 落盘(§2.5 slot 模块;fire-and-forget,失败静默)
722
1158
  const reportMount = (slot) => {
723
1159
  try {
724
1160
  void fetch(`${API}/log`, {
725
- method: 'POST',
726
- headers: { 'content-type': 'application/json' },
1161
+ method: 'POST', headers: { 'content-type': 'application/json' },
727
1162
  body: JSON.stringify({ module: 'slot', event: 'mount.ok', meta: { slot } }),
728
1163
  }).catch(() => {})
729
- } catch {
730
- // ignore
731
- }
1164
+ } catch { /* ignore */ }
732
1165
  }
733
1166
  slots.inject('conversation.hero.agentPreset', () => {
734
1167
  reportMount('conversation.hero.agentPreset')
735
- return slots.register({ name: 'conversation.hero.agentPreset', id: 'token-dash-home', order: 10 }, Pill)
1168
+ return slots.register({ name: 'conversation.hero.agentPreset', id: 'token-dash-home', order: 10 }, LocaleRoot)
736
1169
  })
737
1170
  slots.inject('conversation.composer.dock', () => {
738
1171
  reportMount('conversation.composer.dock')
739
- return slots.register({ name: 'conversation.composer.dock', id: 'token-dash-input', order: -1 }, Pill)
1172
+ return slots.register({ name: 'conversation.composer.dock', id: 'token-dash-input', order: -1 }, LocaleRoot)
740
1173
  })
741
1174
  },
742
1175
  }