dsh-token-dash 1.0.7 → 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/AGENTS.md +6 -0
- package/client.js +883 -452
- package/index.js +89 -14
- package/locale/en.json +108 -6
- package/locale/zh.json +108 -6
- package/package.json +1 -1
- package/src/adapters.js +31 -18
- package/src/backup.js +61 -0
- package/src/core.js +208 -12
- package/src/pricing.js +5 -1
- package/src/store.js +13 -7
package/client.js
CHANGED
|
@@ -1,45 +1,152 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* dsh-token-dash — client half. P1 constraint pill, P2
|
|
3
|
-
*
|
|
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
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
const
|
|
21
|
-
const
|
|
22
|
-
const
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
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
|
-
|
|
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
|
|
39
|
-
|
|
40
|
-
|
|
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
|
-
|
|
66
|
-
|
|
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: '
|
|
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:
|
|
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
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
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
|
-
|
|
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:
|
|
102
|
-
muted: {
|
|
103
|
-
|
|
104
|
-
|
|
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: COLORS.primary },
|
|
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
|
|
121
|
-
|
|
122
|
-
|
|
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
|
-
|
|
125
|
-
|
|
126
|
-
|
|
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
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
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
|
-
|
|
136
|
-
|
|
137
|
-
|
|
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
|
|
348
|
+
function IconButton({ label, children, onClick, disabled = false, testid, dot = false, dotColor = T.warn }) {
|
|
141
349
|
return h('button', {
|
|
142
|
-
type: 'button',
|
|
143
|
-
|
|
144
|
-
|
|
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
|
-
|
|
359
|
+
function Tooltip({ open, anchorRef, text, onClose }) {
|
|
360
|
+
const tipRef = useRef(null)
|
|
361
|
+
const [pos, setPos] = useState(null)
|
|
148
362
|
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
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
|
-
|
|
160
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
187
|
-
h('b', { style: { ...styles.num, color: percentColor(plan.usedPercent ?? 0) } },
|
|
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 =
|
|
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,193 +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
|
|
256
|
-
dismissHint()
|
|
257
|
-
// #30 三次定案:浮层从 pill 正上方弹出;pill 上方空间不足时收紧 maxHeight(视口顶 8px 间隙 + pill 间距 8px),内容内部滚动
|
|
596
|
+
const measurePanel = useCallback(() => {
|
|
258
597
|
const rect = pillRef.current?.getBoundingClientRect()
|
|
259
|
-
if (rect
|
|
260
|
-
|
|
261
|
-
|
|
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
|
-
|
|
264
|
-
|
|
265
|
-
|
|
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
|
-
|
|
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
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
h('span', { key: '
|
|
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 =
|
|
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 =
|
|
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
|
-
|
|
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':
|
|
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,
|
|
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
|
|
321
|
-
const
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
...styles.barFill,
|
|
342
|
-
background: hasBudget ? color : styles.barNeutral.background,
|
|
343
|
-
width: hasBudget ? `${Math.min(100, (budget.percent ?? 0) * 100)}%` : '100%',
|
|
344
|
-
},
|
|
345
|
-
})))
|
|
346
|
-
}
|
|
347
|
-
|
|
348
|
-
function SubscriptionCard({ provider }) {
|
|
349
|
-
const windows = Array.isArray(provider.windows) ? provider.windows : []
|
|
350
|
-
const resets = windows.map((plan) => plan.resetAt).filter((ts) => Number.isFinite(ts) && ts > 0)
|
|
351
|
-
const nextReset = resets.length > 0 ? Math.min(...resets) : null
|
|
352
|
-
return h('div', { 'data-testid': `token-dash-sub-card-${provider.id}`, style: { ...styles.card, marginTop: 0 } },
|
|
353
|
-
h('div', { style: styles.row }, h('b', { style: styles.nameEllipsis, title: provider.name }, provider.name), h('span', { style: styles.muted }, '订阅')),
|
|
354
|
-
windows.length === 0
|
|
355
|
-
? h('div', { style: { ...styles.muted, marginTop: 6 } }, '套餐查询失败')
|
|
356
|
-
: h(React.Fragment, null,
|
|
357
|
-
h('div', { style: { ...styles.row, marginTop: 6, flexWrap: 'wrap', justifyContent: 'flex-start' } }, subscriptionNodes(provider)),
|
|
358
|
-
windows.map((plan) => h('div', { key: plan.key, style: styles.bar },
|
|
359
|
-
h('div', { style: { ...styles.barFill, width: `${Math.min(100, plan.usedPercent ?? 0)}%` } }))),
|
|
360
|
-
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 }))))
|
|
361
689
|
}
|
|
362
690
|
|
|
363
|
-
function
|
|
364
|
-
const
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
}
|
|
371
|
-
if (groups.size === 0) {
|
|
372
|
-
// #40:空态保留表格结构(对齐 #32 用量表空态口径),不再整体隐藏
|
|
373
|
-
return h('div', { 'data-testid': 'token-dash-cost-table', style: styles.card },
|
|
374
|
-
h('div', { style: styles.row }, h('b', { style: styles.headerTitle }, 'API 费用明细 / 本月'), h('span', { style: styles.muted }, 'DSH 本机估算')),
|
|
375
|
-
h('div', { style: { ...styles.muted, marginTop: 8 } }, `CNY 合计 ${fmtMoney(0, 'CNY')}`),
|
|
376
|
-
h('div', { style: { overflowX: 'auto' } },
|
|
377
|
-
h('table', { style: styles.table },
|
|
378
|
-
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 } }, '费用'))),
|
|
379
|
-
h('tbody', null, h('tr', { key: 'empty' },
|
|
380
|
-
h('td', { style: styles.modelCell }, '—'),
|
|
381
|
-
h('td', { style: styles.tdRight }, fmtRatio(0)),
|
|
382
|
-
h('td', { style: styles.tdRight }, fmtMoney(0, 'CNY')))))))
|
|
383
|
-
}
|
|
384
|
-
return h('div', { 'data-testid': 'token-dash-cost-table', style: styles.card },
|
|
385
|
-
h('div', { style: styles.row }, h('b', { style: styles.headerTitle }, 'API 费用明细 / 本月'), h('span', { style: styles.muted }, 'DSH 本机估算')),
|
|
386
|
-
...[...groups.entries()].flatMap(([currency, rows]) => [
|
|
387
|
-
h('div', { key: `${currency}-head`, style: { ...styles.muted, marginTop: 8 } }, `${currency} 合计 ${fmtMoney(rows.reduce((sum, row) => sum + row.cost, 0), currency)}`),
|
|
388
|
-
h('div', { key: `${currency}-wrap`, style: { overflowX: 'auto' } },
|
|
389
|
-
h('table', { style: styles.table },
|
|
390
|
-
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 } }, '费用'))),
|
|
391
|
-
h('tbody', null, rows.map((model) => h('tr', { key: `${model.providerId}:${model.modelId}` },
|
|
392
|
-
h('td', { style: styles.modelCell, title: modelTitle(model) }, modelTitle(model)),
|
|
393
|
-
h('td', { style: styles.tdRight }, fmtRatio(model.share)),
|
|
394
|
-
h('td', { style: { ...styles.tdRight, fontWeight: 600 } }, model.priced === false ? '未定价' : fmtMoney(model.cost, currency))))))),
|
|
395
|
-
]))
|
|
396
|
-
}
|
|
397
|
-
|
|
398
|
-
function UsageTable({ models }) {
|
|
399
|
-
// #32:空态保留表格结构,数值显示 0(不再用 colSpan 文案行)
|
|
400
|
-
const emptyRow = models.length === 0
|
|
401
|
-
? h('tr', { key: 'empty' },
|
|
402
|
-
h('td', { style: styles.modelCell }, '—'),
|
|
403
|
-
h('td', { style: styles.tdRight }, 0),
|
|
404
|
-
h('td', { style: styles.tdRight }, fmtM(0)),
|
|
405
|
-
h('td', { style: styles.tdRight }, fmtM(0)),
|
|
406
|
-
h('td', { style: styles.tdRight }, fmtM(0)),
|
|
407
|
-
h('td', { style: styles.tdRight }, '—'))
|
|
408
|
-
: null
|
|
409
|
-
return h('div', { 'data-testid': 'token-dash-usage-table', style: styles.card },
|
|
410
|
-
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))}`)),
|
|
411
|
-
h('div', { style: { overflowX: 'auto' } },
|
|
412
|
-
h('table', { style: styles.table },
|
|
413
|
-
h('thead', null, h('tr', null,
|
|
414
|
-
h('th', { key: '模型', style: styles.th }, '模型'),
|
|
415
|
-
h('th', { key: '请求', style: { ...styles.thRight, width: 44 } }, '请求'),
|
|
416
|
-
h('th', { key: '输入', style: { ...styles.thRight, width: 56 } }, '输入'),
|
|
417
|
-
h('th', { key: '命中', style: { ...styles.thRight, width: 56 } }, '命中'),
|
|
418
|
-
h('th', { key: '输出', style: { ...styles.thRight, width: 56 } }, '输出'),
|
|
419
|
-
h('th', { key: '命中率', style: { ...styles.thRight, width: 52 } }, '命中率'))),
|
|
420
|
-
h('tbody', null,
|
|
421
|
-
models.map((model) => h('tr', { key: `${model.providerId}:${model.modelId}` },
|
|
422
|
-
h('td', { style: styles.modelCell, title: modelTitle(model) }, modelTitle(model)),
|
|
423
|
-
h('td', { style: styles.tdRight }, model.requests),
|
|
424
|
-
h('td', { style: styles.tdRight }, fmtM(model.tokens?.input ?? 0)),
|
|
425
|
-
h('td', { style: styles.tdRight }, fmtM(model.tokens?.cacheRead ?? 0)),
|
|
426
|
-
h('td', { style: styles.tdRight }, fmtM(model.tokens?.output ?? 0)),
|
|
427
|
-
h('td', { style: styles.tdRight }, model.hitRate === null || model.hitRate === undefined ? '—' : fmtRatio(model.hitRate)))),
|
|
428
|
-
emptyRow))))
|
|
429
|
-
}
|
|
430
|
-
|
|
431
|
-
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)
|
|
432
698
|
const panelRef = useRef(null)
|
|
433
699
|
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
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])
|
|
437
719
|
|
|
438
|
-
// #35:点击浮层外部关闭(Esc 按 D-15 修订不做);命中 pill/hint 时交给 pill 的 toggle,不视为外部
|
|
439
720
|
useEffect(() => {
|
|
440
721
|
const onDown = (event) => {
|
|
441
722
|
const node = panelRef.current
|
|
@@ -448,80 +729,189 @@ window.__ModuleLoader__.load({
|
|
|
448
729
|
return () => document.removeEventListener('mousedown', onDown)
|
|
449
730
|
}, [onClose])
|
|
450
731
|
|
|
451
|
-
const
|
|
452
|
-
|
|
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 看板'),
|
|
453
748
|
'data-testid': 'token-dash-panel',
|
|
454
|
-
style: { ...styles.panel, maxHeight },
|
|
455
|
-
}
|
|
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
|
+
}
|
|
456
757
|
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
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
|
+
}
|
|
461
811
|
|
|
462
|
-
|
|
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
|
+
}
|
|
463
818
|
const providers = summary?.providers ?? []
|
|
464
819
|
const api = providers.filter((provider) => provider.kind === 'api')
|
|
465
820
|
const subscriptions = providers.filter((provider) => provider.kind === 'subscription')
|
|
466
|
-
const
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
h('
|
|
485
|
-
|
|
486
|
-
h(
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
return h(
|
|
496
|
-
|
|
497
|
-
'
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
h('
|
|
502
|
-
|
|
503
|
-
|
|
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))
|
|
504
885
|
}
|
|
505
886
|
|
|
506
|
-
function
|
|
887
|
+
function SettingsContent({ summary, onRefresh, onRefreshSubs }) {
|
|
507
888
|
const [prefs, setPrefs] = useState(null)
|
|
508
889
|
const [budgetText, setBudgetText] = useState({})
|
|
890
|
+
const [fieldErrors, setFieldErrors] = useState({})
|
|
509
891
|
const [status, setStatus] = useState(null)
|
|
510
|
-
const [
|
|
892
|
+
const [subRefreshing, setSubRefreshing] = useState(false)
|
|
893
|
+
const update = useUpdateSnapshot()
|
|
511
894
|
const [logMeta, setLogMeta] = useState(null)
|
|
895
|
+
const [importing, setImporting] = useState(false)
|
|
896
|
+
const fileRef = useRef(null)
|
|
512
897
|
|
|
513
|
-
|
|
514
|
-
|
|
898
|
+
const loadPrefs = useCallback(async () => {
|
|
899
|
+
try {
|
|
900
|
+
const data = await getJson('/prefs')
|
|
515
901
|
setPrefs(data)
|
|
516
902
|
const next = {}
|
|
517
|
-
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) : ''
|
|
518
904
|
setBudgetText(next)
|
|
519
|
-
}
|
|
905
|
+
} catch {
|
|
906
|
+
setStatus({ text: tr('设置加载失败'), error: true })
|
|
907
|
+
}
|
|
520
908
|
}, [])
|
|
521
909
|
|
|
910
|
+
useEffect(() => { loadPrefs() }, [loadPrefs])
|
|
911
|
+
|
|
522
912
|
function flash(text, error = false) {
|
|
523
913
|
setStatus({ text, error })
|
|
524
|
-
if (error !== true) setTimeout(() => setStatus((current) => (current?.text === text ? null : current)),
|
|
914
|
+
if (error !== true) setTimeout(() => setStatus((current) => (current?.text === text ? null : current)), 1600)
|
|
525
915
|
}
|
|
526
916
|
|
|
527
917
|
async function savePrefs(patch) {
|
|
@@ -529,31 +919,46 @@ window.__ModuleLoader__.load({
|
|
|
529
919
|
try {
|
|
530
920
|
const saved = await putPrefs({ ...prefs, ...patch })
|
|
531
921
|
setPrefs(saved)
|
|
532
|
-
flash('已保存')
|
|
922
|
+
flash(tr('已保存'))
|
|
533
923
|
void onRefresh?.()
|
|
534
924
|
return saved
|
|
535
925
|
} catch (error) {
|
|
536
|
-
setStatus({ text:
|
|
926
|
+
setStatus({ text: tr('保存失败:{reason}', { reason: error.message }), error: true })
|
|
537
927
|
return null
|
|
538
928
|
}
|
|
539
929
|
}
|
|
540
930
|
|
|
541
931
|
async function saveBudget(provider, raw) {
|
|
542
|
-
const text = String(raw).
|
|
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
|
+
}
|
|
543
941
|
const amount = Number(text)
|
|
544
|
-
if (text
|
|
545
|
-
|
|
942
|
+
if (!/^\d+(?:\.\d{1,2})?$/.test(text) || !Number.isFinite(amount) || amount > 9999999.99) {
|
|
943
|
+
setFieldErrors((current) => ({ ...current, [provider.id]: tr('请输入 0 或正数') }))
|
|
546
944
|
return
|
|
547
945
|
}
|
|
548
|
-
|
|
946
|
+
budgets[provider.id] = { amount, currency: provider.currency }
|
|
549
947
|
const saved = await savePrefs({ budgets })
|
|
550
|
-
if (saved !== null)
|
|
948
|
+
if (saved !== null) {
|
|
949
|
+
setBudgetText((current) => ({ ...current, [provider.id]: String(saved.budgets[provider.id]?.amount ?? '') }))
|
|
950
|
+
setFieldErrors((current) => ({ ...current, [provider.id]: null }))
|
|
951
|
+
}
|
|
551
952
|
}
|
|
552
953
|
|
|
553
954
|
async function refreshSubscriptions() {
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
955
|
+
setSubRefreshing(true)
|
|
956
|
+
try {
|
|
957
|
+
await onRefreshSubs?.()
|
|
958
|
+
flash(tr('已重新检测'))
|
|
959
|
+
} finally {
|
|
960
|
+
setSubRefreshing(false)
|
|
961
|
+
}
|
|
557
962
|
}
|
|
558
963
|
|
|
559
964
|
async function openLogs() {
|
|
@@ -562,19 +967,18 @@ window.__ModuleLoader__.load({
|
|
|
562
967
|
setLogMeta(meta)
|
|
563
968
|
const app = /Mac|iPhone|iPad/.test(navigator.platform) ? 'finder' : /Linux/.test(navigator.platform) ? 'filemanager' : 'explorer'
|
|
564
969
|
const response = await fetch('/open-in-app/open', {
|
|
565
|
-
method: 'POST',
|
|
566
|
-
headers: { 'content-type': 'application/json' },
|
|
970
|
+
method: 'POST', headers: { 'content-type': 'application/json' },
|
|
567
971
|
body: JSON.stringify({ app, path: meta.dir }),
|
|
568
972
|
})
|
|
569
973
|
if (!response.ok) throw new Error('open-failed')
|
|
570
|
-
flash('已打开日志文件夹')
|
|
974
|
+
flash(tr('已打开日志文件夹'))
|
|
571
975
|
} catch {
|
|
572
976
|
try {
|
|
573
977
|
const meta = logMeta ?? await getJson('/logs/meta')
|
|
574
978
|
await navigator.clipboard.writeText(meta.dir)
|
|
575
|
-
flash('无法打开,已复制路径')
|
|
979
|
+
flash(tr('无法打开,已复制路径'))
|
|
576
980
|
} catch {
|
|
577
|
-
setStatus({ text: '打开日志失败', error: true })
|
|
981
|
+
setStatus({ text: tr('打开日志失败'), error: true })
|
|
578
982
|
}
|
|
579
983
|
}
|
|
580
984
|
}
|
|
@@ -589,156 +993,183 @@ window.__ModuleLoader__.load({
|
|
|
589
993
|
link.download = 'dsh-token-dash.log'
|
|
590
994
|
link.click()
|
|
591
995
|
URL.revokeObjectURL(url)
|
|
592
|
-
flash('日志已导出')
|
|
996
|
+
flash(tr('日志已导出'))
|
|
593
997
|
} catch {
|
|
594
|
-
setStatus({ text: '日志导出失败', error: true })
|
|
998
|
+
setStatus({ text: tr('日志导出失败'), error: true })
|
|
595
999
|
}
|
|
596
1000
|
}
|
|
597
1001
|
|
|
598
|
-
async function
|
|
599
|
-
setUpdate({ phase: 'checking' })
|
|
1002
|
+
async function exportData() {
|
|
600
1003
|
try {
|
|
601
|
-
const data = await getJson('/
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
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('数据已导出'))
|
|
605
1013
|
} catch {
|
|
606
|
-
|
|
1014
|
+
setStatus({ text: tr('数据导出失败'), error: true })
|
|
607
1015
|
}
|
|
608
1016
|
}
|
|
609
1017
|
|
|
610
|
-
async function
|
|
611
|
-
|
|
1018
|
+
async function importData(file) {
|
|
1019
|
+
if (file === null || file === undefined) return
|
|
1020
|
+
setImporting(true)
|
|
612
1021
|
try {
|
|
613
|
-
const
|
|
614
|
-
const
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
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 }))
|
|
618
1027
|
} catch (error) {
|
|
619
|
-
|
|
1028
|
+
setStatus({ text: tr('导入失败:{reason}', { reason: error.message }), error: true })
|
|
1029
|
+
} finally {
|
|
1030
|
+
setImporting(false)
|
|
1031
|
+
if (fileRef.current !== null) fileRef.current.value = ''
|
|
620
1032
|
}
|
|
621
1033
|
}
|
|
622
1034
|
|
|
1035
|
+
const checkUpdate = () => { void checkForUpdate({ manual: true }) }
|
|
1036
|
+
const installUpdate = () => { void installUpdateRequest() }
|
|
1037
|
+
|
|
623
1038
|
async function copyCommand() {
|
|
624
|
-
try {
|
|
625
|
-
await navigator.clipboard.writeText(update.command ?? '')
|
|
626
|
-
flash('命令已复制')
|
|
627
|
-
} catch {
|
|
628
|
-
setStatus({ text: '复制失败', error: true })
|
|
629
|
-
}
|
|
1039
|
+
try { await navigator.clipboard.writeText(update.command ?? ''); flash(tr('命令已复制')) } catch { setStatus({ text: tr('复制失败'), error: true }) }
|
|
630
1040
|
}
|
|
631
1041
|
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
}
|
|
637
|
-
|
|
638
|
-
const header = h('div', { style: styles.titleBar },
|
|
639
|
-
h('div', { style: styles.rowStart },
|
|
640
|
-
h('button', { style: styles.button, onClick: onBack }, '← 返回'),
|
|
641
|
-
h('b', { style: styles.headerTitle }, 'Token 看板')),
|
|
642
|
-
h('span', { style: styles.rowStart }, statusSlot, h('button', { style: styles.button, onClick: onClose }, '关闭')))
|
|
643
|
-
|
|
644
|
-
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
|
+
}
|
|
645
1047
|
|
|
646
1048
|
const providers = summary?.providers ?? []
|
|
647
1049
|
const api = providers.filter((provider) => provider.kind === 'api')
|
|
648
1050
|
const subscriptions = providers.filter((provider) => provider.kind === 'subscription')
|
|
649
1051
|
const version = summary?.version ?? ''
|
|
650
|
-
const
|
|
651
|
-
const section = (title, body, action = null) => h('
|
|
652
|
-
h('div', { style: styles.
|
|
653
|
-
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)
|
|
654
1055
|
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
h('div', { style: styles.row },
|
|
658
|
-
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('月度预算')),
|
|
659
1059
|
h('span', { style: styles.rowStart },
|
|
660
|
-
h('span', { style: styles.muted }, '月度预算'),
|
|
661
1060
|
h('input', {
|
|
662
|
-
type: 'text', inputMode: 'decimal', '
|
|
663
|
-
|
|
664
|
-
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 }),
|
|
665
1064
|
onBlur: (event) => saveBudget(provider, event.currentTarget.value),
|
|
666
1065
|
onKeyDown: (event) => { if (event.key === 'Enter') { event.preventDefault(); event.currentTarget.blur() } },
|
|
667
|
-
style: styles.input,
|
|
668
|
-
}),
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
const
|
|
672
|
-
h('
|
|
673
|
-
h('
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
h('span',
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
else
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
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('备份与恢复')),
|
|
703
1121
|
h('span', { style: styles.rowStart },
|
|
704
|
-
h('button', { 'data-testid': 'token-dash-
|
|
705
|
-
h('button', { 'data-testid': 'token-dash-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
h('div', { style: styles.
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
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)
|
|
715
1136
|
}
|
|
716
1137
|
|
|
717
1138
|
return {
|
|
718
1139
|
name: PKG,
|
|
719
|
-
inject: ['slots'],
|
|
1140
|
+
inject: ['slots', 'locale'],
|
|
720
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
|
+
}
|
|
721
1156
|
const slots = typeof ctx.get === 'function' ? ctx.get('slots') : ctx.slots
|
|
722
1157
|
if (slots === undefined || typeof slots.inject !== 'function') return
|
|
723
|
-
// #46:slot 挂载上报 host 落盘(§2.5 slot 模块;fire-and-forget,失败静默)
|
|
724
1158
|
const reportMount = (slot) => {
|
|
725
1159
|
try {
|
|
726
1160
|
void fetch(`${API}/log`, {
|
|
727
|
-
method: 'POST',
|
|
728
|
-
headers: { 'content-type': 'application/json' },
|
|
1161
|
+
method: 'POST', headers: { 'content-type': 'application/json' },
|
|
729
1162
|
body: JSON.stringify({ module: 'slot', event: 'mount.ok', meta: { slot } }),
|
|
730
1163
|
}).catch(() => {})
|
|
731
|
-
} catch {
|
|
732
|
-
// ignore
|
|
733
|
-
}
|
|
1164
|
+
} catch { /* ignore */ }
|
|
734
1165
|
}
|
|
735
1166
|
slots.inject('conversation.hero.agentPreset', () => {
|
|
736
1167
|
reportMount('conversation.hero.agentPreset')
|
|
737
|
-
return slots.register({ name: 'conversation.hero.agentPreset', id: 'token-dash-home', order: 10 },
|
|
1168
|
+
return slots.register({ name: 'conversation.hero.agentPreset', id: 'token-dash-home', order: 10 }, LocaleRoot)
|
|
738
1169
|
})
|
|
739
1170
|
slots.inject('conversation.composer.dock', () => {
|
|
740
1171
|
reportMount('conversation.composer.dock')
|
|
741
|
-
return slots.register({ name: 'conversation.composer.dock', id: 'token-dash-input', order: -1 },
|
|
1172
|
+
return slots.register({ name: 'conversation.composer.dock', id: 'token-dash-input', order: -1 }, LocaleRoot)
|
|
742
1173
|
})
|
|
743
1174
|
},
|
|
744
1175
|
}
|