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