dsh-token-dash 0.0.0-stage → 1.0.2
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 +72 -0
- package/LICENSE +21 -0
- package/README.en.md +169 -0
- package/README.md +192 -2
- package/client.js +752 -0
- package/cordis.patch.yml +5 -0
- package/doc/pic/panel-dashboard.png +0 -0
- package/doc/pic/pill-home.png +0 -0
- package/doc/pic/pill-session.png +0 -0
- package/doc/pic/settings.png +0 -0
- package/index.js +342 -0
- package/locale/en.json +8 -0
- package/locale/zh.json +8 -0
- package/package.json +64 -4
- package/src/adapters.js +297 -0
- package/src/catalog.json +154 -0
- package/src/collect.js +103 -0
- package/src/core.js +399 -0
- package/src/diagnostics.js +113 -0
- package/src/pricing.js +241 -0
- package/src/providers.js +129 -0
- package/src/store.js +127 -0
package/client.js
ADDED
|
@@ -0,0 +1,752 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-token-dash — client half. P1 constraint pill, P2 dynamic provider cards,
|
|
3
|
+
* P3 provider settings, log export and in-place update.
|
|
4
|
+
*/
|
|
5
|
+
window.__ModuleLoader__.load({
|
|
6
|
+
id: 'dsh-token-dash',
|
|
7
|
+
factory(require) {
|
|
8
|
+
const React = require('react')
|
|
9
|
+
const h = React.createElement
|
|
10
|
+
const { useCallback, useEffect, useRef, useState } = React
|
|
11
|
+
|
|
12
|
+
const API = '/token-dash/api'
|
|
13
|
+
const PKG = 'dsh-token-dash'
|
|
14
|
+
const LINKS = [
|
|
15
|
+
['DeepSeek', 'https://api-docs.deepseek.com/quick_start/pricing'],
|
|
16
|
+
['GLM', 'https://docs.bigmodel.cn/cn/guide/start/pricing'],
|
|
17
|
+
['Kimi', 'https://platform.moonshot.cn/docs/pricing/chat'],
|
|
18
|
+
['OpenRouter', 'https://openrouter.ai/models'],
|
|
19
|
+
['Qwen', 'https://help.aliyun.com/zh/model-studio/billing-for-alibaba-cloud-model-studio'],
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
const COLORS = { primary: '#6ea8ff', warn: '#f0a020', over: '#e05a5a' }
|
|
23
|
+
const budgetColor = (state) => (state === 'over' ? COLORS.over : state === 'warn' ? COLORS.warn : COLORS.primary)
|
|
24
|
+
const percentColor = (value) => (value >= 100 ? COLORS.over : value >= 80 ? COLORS.warn : COLORS.primary)
|
|
25
|
+
|
|
26
|
+
const fmtMoney = (value, currency = 'CNY') => `${currency === 'USD' ? '$' : '¥'}${Number(value ?? 0).toFixed(2)}`
|
|
27
|
+
const fmtM = (value) => `${(Number(value ?? 0) / 1e6).toFixed(2)}M`
|
|
28
|
+
const fmtRatio = (value) => `${(Number(value ?? 0) * 100).toFixed(1)}%`
|
|
29
|
+
const fmtUsed = (value) => `${Number(value ?? 0).toFixed(1)}%`
|
|
30
|
+
const fmtAgo = (ts) => {
|
|
31
|
+
if (!Number.isFinite(ts)) return '加载中'
|
|
32
|
+
const seconds = Math.max(0, Math.round((Date.now() - ts) / 1000))
|
|
33
|
+
if (seconds < 60) return '刚刚'
|
|
34
|
+
if (seconds < 3600) return `${Math.floor(seconds / 60)} 分钟前`
|
|
35
|
+
return `${Math.floor(seconds / 3600)} 小时前`
|
|
36
|
+
}
|
|
37
|
+
const fmtReset = (ts) => {
|
|
38
|
+
if (!Number.isFinite(ts) || ts <= 0) return null
|
|
39
|
+
const date = new Date(ts)
|
|
40
|
+
const now = new Date()
|
|
41
|
+
const pad = (value) => String(value).padStart(2, '0')
|
|
42
|
+
const hm = `${pad(date.getHours())}:${pad(date.getMinutes())}`
|
|
43
|
+
if (date.toDateString() === now.toDateString()) return hm
|
|
44
|
+
return `${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${hm}`
|
|
45
|
+
}
|
|
46
|
+
const modelTitle = (model) => {
|
|
47
|
+
if (!model.providerId || model.providerId === 'unknown') return model.displayName ?? model.modelId
|
|
48
|
+
return [model.providerName, model.displayName ?? model.modelId].filter(Boolean).join(' / ')
|
|
49
|
+
}
|
|
50
|
+
const windowLabel = { '5h': '5h', week: '周', month: '月' }
|
|
51
|
+
|
|
52
|
+
async function getJson(path) {
|
|
53
|
+
const res = await fetch(`${API}${path}`, { headers: { accept: 'application/json' } })
|
|
54
|
+
const body = await res.json().catch(() => ({}))
|
|
55
|
+
if (!res.ok || body?.ok !== true) throw new Error(body?.reason ?? `http-${res.status}`)
|
|
56
|
+
return body.data
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async function putPrefs(prefs) {
|
|
60
|
+
const res = await fetch(`${API}/prefs`, {
|
|
61
|
+
method: 'PUT',
|
|
62
|
+
headers: { 'content-type': 'application/json' },
|
|
63
|
+
body: JSON.stringify(prefs),
|
|
64
|
+
})
|
|
65
|
+
const body = await res.json().catch(() => ({}))
|
|
66
|
+
if (!res.ok || body?.ok !== true) throw new Error(body?.reason ?? `http-${res.status}`)
|
|
67
|
+
return body.data
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const styles = {
|
|
71
|
+
pill: {
|
|
72
|
+
display: 'inline-flex',
|
|
73
|
+
alignItems: 'center',
|
|
74
|
+
gap: 6,
|
|
75
|
+
height: 24,
|
|
76
|
+
padding: '0 8px',
|
|
77
|
+
borderRadius: 999,
|
|
78
|
+
cursor: 'pointer',
|
|
79
|
+
maxWidth: '100%',
|
|
80
|
+
fontVariantNumeric: 'tabular-nums',
|
|
81
|
+
border: '1px solid var(--dsh-border, rgba(128,128,128,.25))',
|
|
82
|
+
color: 'var(--dsh-text, inherit)',
|
|
83
|
+
},
|
|
84
|
+
pillWrap: { position: 'relative', display: 'inline-flex', alignItems: 'center', marginLeft: 8 },
|
|
85
|
+
pillHover: { background: 'rgba(127,127,127,.12)' },
|
|
86
|
+
nameEllipsis: { maxWidth: '12em', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
|
|
87
|
+
hint: {
|
|
88
|
+
position: 'absolute', right: 12, bottom: 30, padding: '5px 8px', borderRadius: 6,
|
|
89
|
+
background: 'var(--dsh-bg-elevated, #2a2a2a)', border: '1px solid var(--dsh-border, rgba(128,128,128,.25))',
|
|
90
|
+
fontSize: 11, whiteSpace: 'nowrap', boxShadow: '0 4px 16px rgba(0,0,0,.25)',
|
|
91
|
+
},
|
|
92
|
+
chevron: {
|
|
93
|
+
marginLeft: 2, padding: '0 1px', borderRadius: 4, background: 'rgba(77,141,255,.16)',
|
|
94
|
+
color: 'var(--dsw-alias-state-business-primary, #6ea8ff)', fontSize: 10,
|
|
95
|
+
},
|
|
96
|
+
sep: { width: 1, height: 12, background: 'currentColor', opacity: 0.2 },
|
|
97
|
+
num: { fontWeight: 600, fontVariantNumeric: 'tabular-nums' },
|
|
98
|
+
panel: {
|
|
99
|
+
// #30 三次定案:从 pill 正上方弹出——左缘对齐 pill 左缘、底边距 pill 顶 8px,允许遮挡输入框
|
|
100
|
+
position: 'absolute', bottom: 'calc(100% + 8px)', left: 0, width: 'max-content',
|
|
101
|
+
minWidth: 'min(380px, calc(100vw - 32px))', maxWidth: 'min(600px, calc(100vw - 32px))',
|
|
102
|
+
boxSizing: 'border-box', maxHeight: '70vh', overflow: 'auto', zIndex: 9999,
|
|
103
|
+
padding: 12, borderRadius: 12, background: 'var(--dsh-bg-elevated, #1f1f1f)',
|
|
104
|
+
color: 'var(--dsh-text, #eee)', boxShadow: '0 12px 40px rgba(0,0,0,.35)', fontSize: 12,
|
|
105
|
+
outline: 'none',
|
|
106
|
+
},
|
|
107
|
+
card: { border: '1px solid var(--dsh-border, rgba(128,128,128,.25))', borderRadius: 10, padding: 12, marginTop: 10 },
|
|
108
|
+
row: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 },
|
|
109
|
+
rowStart: { display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' },
|
|
110
|
+
muted: { opacity: 0.65, fontSize: 11 },
|
|
111
|
+
headerTitle: { fontSize: 13, fontWeight: 600 },
|
|
112
|
+
titleBar: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, minHeight: 36 },
|
|
113
|
+
buttonGroup: { display: 'flex', gap: 12 },
|
|
114
|
+
bar: { height: 6, borderRadius: 3, background: 'rgba(128,128,128,.25)', overflow: 'hidden', margin: '8px 0' },
|
|
115
|
+
barFill: { height: '100%', background: '#6ea8ff' },
|
|
116
|
+
barNeutral: { height: '100%', background: 'rgba(128,128,128,.45)' },
|
|
117
|
+
cols: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 0, marginTop: 8 },
|
|
118
|
+
subGrid: { display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(240px, 1fr))', gap: 8 },
|
|
119
|
+
scrollList: { maxHeight: 280, overflowY: 'auto', paddingRight: 4 },
|
|
120
|
+
table: { width: 'max-content', minWidth: '100%', borderCollapse: 'collapse', tableLayout: 'auto', marginTop: 6 },
|
|
121
|
+
th: { textAlign: 'left', opacity: 0.6, fontWeight: 400, padding: '4px 8px', whiteSpace: 'nowrap' },
|
|
122
|
+
thRight: { textAlign: 'right', opacity: 0.6, fontWeight: 400, padding: '4px 8px', borderLeft: '1px solid rgba(128,128,128,.15)', whiteSpace: 'nowrap' },
|
|
123
|
+
td: { padding: '4px 8px', borderTop: '1px solid rgba(128,128,128,.15)', whiteSpace: 'nowrap' },
|
|
124
|
+
tdRight: { padding: '4px 8px', textAlign: 'right', borderTop: '1px solid rgba(128,128,128,.15)', borderLeft: '1px solid rgba(128,128,128,.15)', whiteSpace: 'nowrap' },
|
|
125
|
+
modelCell: { padding: '4px 8px', borderTop: '1px solid rgba(128,128,128,.15)', whiteSpace: 'nowrap', maxWidth: 220, overflow: 'hidden', textOverflow: 'ellipsis' },
|
|
126
|
+
link: { color: 'inherit', textDecoration: 'underline', cursor: 'pointer', marginLeft: 10 },
|
|
127
|
+
button: {
|
|
128
|
+
border: '1px solid rgba(77,141,255,.32)', background: 'rgba(77,141,255,.16)',
|
|
129
|
+
color: 'var(--dsw-alias-state-business-primary, #6ea8ff)', borderRadius: 6,
|
|
130
|
+
padding: '2px 8px', cursor: 'pointer',
|
|
131
|
+
},
|
|
132
|
+
select: { background: 'transparent', color: 'inherit', border: '1px solid rgba(128,128,128,.35)', borderRadius: 5, padding: '2px 4px' },
|
|
133
|
+
input: { width: 110, height: 28, boxSizing: 'border-box', textAlign: 'right', background: 'transparent', color: 'inherit', border: '1px solid rgba(128,128,128,.35)', borderRadius: 5, padding: '2px 4px' },
|
|
134
|
+
segButton: {
|
|
135
|
+
width: 72, height: 28, borderRadius: 6, border: '1px solid rgba(128,128,128,.35)',
|
|
136
|
+
background: 'transparent', color: 'inherit', cursor: 'pointer', fontSize: 12,
|
|
137
|
+
},
|
|
138
|
+
segActive: { borderColor: 'rgba(77,141,255,.64)', color: 'var(--dsw-alias-state-business-primary, #6ea8ff)', background: 'rgba(77,141,255,.12)' },
|
|
139
|
+
toggleTrack: {
|
|
140
|
+
width: 44, height: 24, borderRadius: 999, border: 'none', padding: 2, display: 'flex', alignItems: 'center',
|
|
141
|
+
background: 'rgba(128,128,128,.35)', cursor: 'pointer', transition: 'background .15s',
|
|
142
|
+
},
|
|
143
|
+
toggleOn: { background: '#2ea36f' },
|
|
144
|
+
toggleKnob: { width: 20, height: 20, borderRadius: 999, background: '#fff', transition: 'transform .15s' },
|
|
145
|
+
toggleKnobOn: { transform: 'translateX(20px)' },
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function Toggle({ checked, onChange }) {
|
|
149
|
+
return h('button', {
|
|
150
|
+
type: 'button', role: 'switch', 'aria-checked': checked, onClick: () => onChange(!checked),
|
|
151
|
+
style: { ...styles.toggleTrack, ...(checked ? styles.toggleOn : {}) },
|
|
152
|
+
}, h('span', { style: { ...styles.toggleKnob, ...(checked ? styles.toggleKnobOn : {}) } }))
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const REFRESH_OPTIONS = [[30000, '30 秒'], [60000, '1 分钟'], [300000, '5 分钟']]
|
|
156
|
+
|
|
157
|
+
function Segmented({ value, onChange }) {
|
|
158
|
+
return h('div', { role: 'radiogroup', 'aria-label': '刷新间隔', style: { display: 'inline-flex', gap: 4 } },
|
|
159
|
+
REFRESH_OPTIONS.map(([ms, label]) => h('button', {
|
|
160
|
+
key: ms, type: 'button', role: 'radio', 'aria-checked': value === ms,
|
|
161
|
+
onClick: () => onChange(ms),
|
|
162
|
+
style: { ...styles.segButton, ...(value === ms ? styles.segActive : {}) },
|
|
163
|
+
}, label)))
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** 余额只来自账户余额接口;预算剩余不进入余额位。 */
|
|
167
|
+
function balanceText(provider, showBalance) {
|
|
168
|
+
if (showBalance === false) return null
|
|
169
|
+
const balance = provider.balance
|
|
170
|
+
if (balance === undefined || balance === null) return '待配置'
|
|
171
|
+
if (balance.status === 'ok') return Number.isFinite(balance.amount) ? fmtMoney(balance.amount, provider.currency) : '查询失败'
|
|
172
|
+
if (balance.status === 'unconfigured') return '待配置'
|
|
173
|
+
if (balance.status === 'unsupported') return '不支持'
|
|
174
|
+
return '查询失败'
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function subscriptionText(provider) {
|
|
178
|
+
const plans = Array.isArray(provider.plans) ? provider.plans : []
|
|
179
|
+
if (plans.length === 0) return '套餐查询失败'
|
|
180
|
+
const text = plans.slice(0, 2).map((plan) => `${windowLabel[plan.key] ?? plan.key} ${fmtUsed(plan.usedPercent)}`).join(' · ')
|
|
181
|
+
if (plans.length === 1) {
|
|
182
|
+
const reset = fmtReset(plans[0].resetAt)
|
|
183
|
+
if (reset !== null) return `${text} · 重置 ${reset}`
|
|
184
|
+
}
|
|
185
|
+
return text
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** 订阅窗口节点:百分比按官方原值着色;withReset 时单窗口附重置时间(P1)。 */
|
|
189
|
+
function subscriptionNodes(provider, withReset = false) {
|
|
190
|
+
const plans = Array.isArray(provider.plans) ? provider.plans : []
|
|
191
|
+
if (plans.length === 0) return [h('span', { key: 'fail' }, '套餐查询失败')]
|
|
192
|
+
const nodes = plans.slice(0, 2).map((plan, index) => h(React.Fragment, { key: plan.key },
|
|
193
|
+
index > 0 ? ' · ' : null,
|
|
194
|
+
`${windowLabel[plan.key] ?? plan.key} `,
|
|
195
|
+
h('b', { style: { ...styles.num, color: percentColor(plan.usedPercent ?? 0) } }, fmtUsed(plan.usedPercent))))
|
|
196
|
+
if (withReset && plans.length === 1) {
|
|
197
|
+
const reset = fmtReset(plans[0].resetAt)
|
|
198
|
+
if (reset !== null) nodes.push(h('span', { key: 'reset' }, ` · 重置 ${reset}`))
|
|
199
|
+
}
|
|
200
|
+
return nodes
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function Pill() {
|
|
204
|
+
const [summary, setSummary] = useState(null)
|
|
205
|
+
const [open, setOpen] = useState(false)
|
|
206
|
+
const [error, setError] = useState(false)
|
|
207
|
+
const [refreshMs, setRefreshMs] = useState(60000)
|
|
208
|
+
const [view, setView] = useState('dashboard')
|
|
209
|
+
const [refreshing, setRefreshing] = useState(false)
|
|
210
|
+
const [hover, setHover] = useState(false)
|
|
211
|
+
const [hint, setHint] = useState(false)
|
|
212
|
+
const [panelMaxHeight, setPanelMaxHeight] = useState('70vh')
|
|
213
|
+
const pillRef = useRef(null)
|
|
214
|
+
|
|
215
|
+
useEffect(() => {
|
|
216
|
+
try {
|
|
217
|
+
if (window.localStorage.getItem('token-dash-hint-seen') !== '1') setHint(true)
|
|
218
|
+
} catch { /* ignore */ }
|
|
219
|
+
}, [])
|
|
220
|
+
|
|
221
|
+
const load = useCallback(async () => {
|
|
222
|
+
setRefreshing(true)
|
|
223
|
+
try {
|
|
224
|
+
const data = await getJson('/summary')
|
|
225
|
+
setSummary(data)
|
|
226
|
+
setError(false)
|
|
227
|
+
if (Number.isFinite(data?.refreshMs) && data.refreshMs !== refreshMs) setRefreshMs(data.refreshMs)
|
|
228
|
+
} catch {
|
|
229
|
+
setError(true)
|
|
230
|
+
} finally {
|
|
231
|
+
setRefreshing(false)
|
|
232
|
+
}
|
|
233
|
+
}, [refreshMs])
|
|
234
|
+
|
|
235
|
+
useEffect(() => {
|
|
236
|
+
getJson('/prefs').then((prefs) => setRefreshMs(prefs.refreshMs ?? 60000)).catch(() => {})
|
|
237
|
+
}, [])
|
|
238
|
+
|
|
239
|
+
useEffect(() => {
|
|
240
|
+
load()
|
|
241
|
+
const timer = setInterval(load, refreshMs)
|
|
242
|
+
return () => clearInterval(timer)
|
|
243
|
+
}, [load, refreshMs])
|
|
244
|
+
|
|
245
|
+
const refreshSubs = useCallback(async () => {
|
|
246
|
+
try {
|
|
247
|
+
await fetch(`${API}/providers/refresh`, { method: 'POST', headers: { accept: 'application/json' } })
|
|
248
|
+
} catch {
|
|
249
|
+
// fall through: still refresh the summary below
|
|
250
|
+
}
|
|
251
|
+
await load()
|
|
252
|
+
}, [load])
|
|
253
|
+
|
|
254
|
+
const dismissHint = () => {
|
|
255
|
+
setHint(false)
|
|
256
|
+
try { window.localStorage.setItem('token-dash-hint-seen', '1') } catch { /* ignore */ }
|
|
257
|
+
}
|
|
258
|
+
const closePanel = useCallback(() => {
|
|
259
|
+
setOpen(false)
|
|
260
|
+
// 等 React 移除浮层后再归还焦点,避免同步 focus 被随后的重渲染吞掉
|
|
261
|
+
setTimeout(() => pillRef.current?.focus(), 0)
|
|
262
|
+
}, [])
|
|
263
|
+
const toggle = () => {
|
|
264
|
+
dismissHint()
|
|
265
|
+
// #30 三次定案:浮层从 pill 正上方弹出;pill 上方空间不足时收紧 maxHeight(视口顶 8px 间隙 + pill 间距 8px),内容内部滚动
|
|
266
|
+
const rect = pillRef.current?.getBoundingClientRect()
|
|
267
|
+
if (rect !== undefined) {
|
|
268
|
+
const available = Math.round(rect.top) - 16
|
|
269
|
+
setPanelMaxHeight(`${Math.max(200, Math.min(window.innerHeight * 0.7, available))}px`)
|
|
270
|
+
}
|
|
271
|
+
setOpen((value) => {
|
|
272
|
+
if (!value) setView('dashboard')
|
|
273
|
+
return !value
|
|
274
|
+
})
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
const providers = summary?.providers ?? []
|
|
278
|
+
const current = providers.find((provider) => provider.id === summary?.currentProviderId) ?? providers[0]
|
|
279
|
+
// #36/#38 定案:徽标 [API]/[订阅](词条统一),不显示 provider 名(hover title 与 aria-label 兜底)
|
|
280
|
+
let prefix = '[API]'
|
|
281
|
+
let bodyNodes = [h('span', { key: 'unknown' }, '--')]
|
|
282
|
+
let ariaText = '按量 API'
|
|
283
|
+
if (current?.kind === 'subscription') {
|
|
284
|
+
prefix = '[订阅]'
|
|
285
|
+
bodyNodes = [
|
|
286
|
+
h('span', { key: 'plans' }, ...subscriptionNodes(current, true)),
|
|
287
|
+
]
|
|
288
|
+
ariaText = `${current.name},订阅,账户套餐,${subscriptionText(current)}`
|
|
289
|
+
} else if (current !== undefined) {
|
|
290
|
+
const budget = current.budget
|
|
291
|
+
const hasBudget = budget !== undefined && budget.state !== 'unset'
|
|
292
|
+
const balance = balanceText(current, summary?.showBalance)
|
|
293
|
+
bodyNodes = [
|
|
294
|
+
h('span', { key: 'budget' }, '预算 ',
|
|
295
|
+
hasBudget
|
|
296
|
+
? h('b', { style: { ...styles.num, color: budgetColor(budget.state) } }, fmtRatio(budget.percent))
|
|
297
|
+
: '未设置'),
|
|
298
|
+
h('span', { key: 'today' }, `今日 ${fmtMoney(current.usage?.todayCost, current.currency)}`),
|
|
299
|
+
balance === null ? null : h('span', { key: 'balance' }, `余额 ${balance}`),
|
|
300
|
+
].filter(Boolean)
|
|
301
|
+
ariaText = `${current.name},按量 API,${hasBudget ? `预算已用 ${fmtRatio(budget.percent)}` : '预算未设置'},今日 ${fmtMoney(current.usage?.todayCost, current.currency)}${balance === null ? '' : `,余额 ${balance}`}`
|
|
302
|
+
}
|
|
303
|
+
const hoverTitle = `${current?.name ?? ''} · ${open ? '收起' : '展开'} Token 看板`
|
|
304
|
+
|
|
305
|
+
// #30 三次定案 + 根因修复:Panel 必须渲染在 pillWrap 内部,
|
|
306
|
+
// absolute 才以 pillWrap(position:relative)为锚——此前 Panel 是 pillWrap 的兄弟节点,
|
|
307
|
+
// absolute 一直挂在宿主槽位容器上,导致 v1 起浮层位置从未真正对齐过 pill。
|
|
308
|
+
return h('div', { style: styles.pillWrap },
|
|
309
|
+
hint && !open ? h('span', { style: styles.hint, role: 'status' }, '点击查看 Token 看板') : null,
|
|
310
|
+
h('span', {
|
|
311
|
+
ref: pillRef,
|
|
312
|
+
'data-testid': 'token-dash-pill',
|
|
313
|
+
style: { ...styles.pill, ...(hover || open ? styles.pillHover : {}) },
|
|
314
|
+
onClick: toggle,
|
|
315
|
+
onMouseEnter: () => setHover(true), onMouseLeave: () => setHover(false),
|
|
316
|
+
onFocus: () => setHover(true), onBlur: () => setHover(false),
|
|
317
|
+
onKeyDown: (event) => { if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); toggle() } },
|
|
318
|
+
role: 'button', tabIndex: 0, 'aria-expanded': open, 'aria-haspopup': 'dialog',
|
|
319
|
+
'aria-label': `Token 看板:${ariaText}`,
|
|
320
|
+
title: hoverTitle,
|
|
321
|
+
}, h('span', { key: 'prefix', style: styles.num }, prefix), ...bodyNodes,
|
|
322
|
+
h('span', { key: 'chevron', style: styles.chevron }, open ? '⌄' : '⌃')),
|
|
323
|
+
open ? h(Panel, {
|
|
324
|
+
summary, error, view, refreshing, maxHeight: panelMaxHeight, onView: setView, onRefresh: load, onRefreshSubs: refreshSubs, onClose: closePanel,
|
|
325
|
+
}) : null)
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
function ApiCard({ provider }) {
|
|
329
|
+
const budget = provider.budget
|
|
330
|
+
const hasBudget = budget !== undefined && budget.state !== 'unset'
|
|
331
|
+
const color = budgetColor(budget?.state)
|
|
332
|
+
// #37:单行紧凑式(框线图)——名称 + 预算段(#33 总额度并入)+ 今日 + 余额,第二行进度条
|
|
333
|
+
return h('div', { 'data-testid': `token-dash-api-card-${provider.id}`, style: styles.card },
|
|
334
|
+
h('div', { style: styles.row },
|
|
335
|
+
h('b', { style: styles.nameEllipsis, title: provider.name }, provider.name),
|
|
336
|
+
h('span', { style: styles.rowStart },
|
|
337
|
+
hasBudget
|
|
338
|
+
? h('span', { 'data-testid': `token-dash-budget-${provider.id}` },
|
|
339
|
+
'预算 ', h('b', { style: { color } }, fmtMoney(budget.used, provider.currency)),
|
|
340
|
+
` / ${fmtMoney(budget.amount, provider.currency)} · `,
|
|
341
|
+
h('b', { style: { color } }, fmtRatio(budget.percent)))
|
|
342
|
+
: h('span', { style: styles.muted }, '预算 未设置'),
|
|
343
|
+
h('span', null, `今日 ${fmtMoney(provider.usage?.todayCost, provider.currency)}`),
|
|
344
|
+
h('span', null, `余额 ${balanceText(provider, true) ?? '--'}`))),
|
|
345
|
+
h('div', { style: { ...styles.bar, marginTop: 6, marginBottom: 0 } },
|
|
346
|
+
h('div', {
|
|
347
|
+
style: {
|
|
348
|
+
...(hasBudget ? { background: color } : styles.barNeutral),
|
|
349
|
+
width: hasBudget ? `${Math.min(100, (budget.percent ?? 0) * 100)}%` : '100%',
|
|
350
|
+
},
|
|
351
|
+
})))
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
function SubscriptionCard({ provider }) {
|
|
355
|
+
const plans = Array.isArray(provider.plans) ? provider.plans : []
|
|
356
|
+
const resets = plans.map((plan) => plan.resetAt).filter((ts) => Number.isFinite(ts) && ts > 0)
|
|
357
|
+
const nextReset = resets.length > 0 ? Math.min(...resets) : null
|
|
358
|
+
return h('div', { 'data-testid': `token-dash-sub-card-${provider.id}`, style: { ...styles.card, marginTop: 0 } },
|
|
359
|
+
h('div', { style: styles.row }, h('b', { style: styles.nameEllipsis, title: provider.name }, provider.name), h('span', { style: styles.muted }, '订阅')),
|
|
360
|
+
plans.length === 0
|
|
361
|
+
? h('div', { style: { ...styles.muted, marginTop: 6 } }, '套餐查询失败')
|
|
362
|
+
: h(React.Fragment, null,
|
|
363
|
+
h('div', { style: { ...styles.row, marginTop: 6, flexWrap: 'wrap', justifyContent: 'flex-start' } }, subscriptionNodes(provider)),
|
|
364
|
+
plans.map((plan) => h('div', { key: plan.key, style: styles.bar },
|
|
365
|
+
h('div', { style: { ...styles.barFill, width: `${Math.min(100, plan.usedPercent ?? 0)}%` } }))),
|
|
366
|
+
nextReset !== null ? h('div', { style: { ...styles.muted, marginTop: 2 } }, `重置 ${fmtReset(nextReset)}`) : null))
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
function ApiCostTable({ models }) {
|
|
370
|
+
const groups = new Map()
|
|
371
|
+
for (const model of models) {
|
|
372
|
+
if (model.kind !== 'api') continue
|
|
373
|
+
const list = groups.get(model.currency) ?? []
|
|
374
|
+
list.push(model)
|
|
375
|
+
groups.set(model.currency, list)
|
|
376
|
+
}
|
|
377
|
+
if (groups.size === 0) {
|
|
378
|
+
// #40:空态保留表格结构(对齐 #32 用量表空态口径),不再整体隐藏
|
|
379
|
+
return h('div', { 'data-testid': 'token-dash-cost-table', style: styles.card },
|
|
380
|
+
h('div', { style: styles.row }, h('b', { style: styles.headerTitle }, 'API 费用明细 / 本月'), h('span', { style: styles.muted }, 'DSH 本机估算')),
|
|
381
|
+
h('div', { style: { ...styles.muted, marginTop: 8 } }, `CNY 合计 ${fmtMoney(0, 'CNY')}`),
|
|
382
|
+
h('div', { style: { overflowX: 'auto' } },
|
|
383
|
+
h('table', { style: styles.table },
|
|
384
|
+
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 } }, '费用'))),
|
|
385
|
+
h('tbody', null, h('tr', { key: 'empty' },
|
|
386
|
+
h('td', { style: styles.modelCell }, '—'),
|
|
387
|
+
h('td', { style: styles.tdRight }, fmtRatio(0)),
|
|
388
|
+
h('td', { style: styles.tdRight }, fmtMoney(0, 'CNY')))))))
|
|
389
|
+
}
|
|
390
|
+
return h('div', { 'data-testid': 'token-dash-cost-table', style: styles.card },
|
|
391
|
+
h('div', { style: styles.row }, h('b', { style: styles.headerTitle }, 'API 费用明细 / 本月'), h('span', { style: styles.muted }, 'DSH 本机估算')),
|
|
392
|
+
...[...groups.entries()].flatMap(([currency, rows]) => [
|
|
393
|
+
h('div', { key: `${currency}-head`, style: { ...styles.muted, marginTop: 8 } }, `${currency} 合计 ${fmtMoney(rows.reduce((sum, row) => sum + row.cost, 0), currency)}`),
|
|
394
|
+
h('div', { key: `${currency}-wrap`, style: { overflowX: 'auto' } },
|
|
395
|
+
h('table', { style: styles.table },
|
|
396
|
+
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 } }, '费用'))),
|
|
397
|
+
h('tbody', null, rows.map((model) => h('tr', { key: `${model.providerId}:${model.modelId}` },
|
|
398
|
+
h('td', { style: styles.modelCell, title: modelTitle(model) }, modelTitle(model)),
|
|
399
|
+
h('td', { style: styles.tdRight }, fmtRatio(model.share)),
|
|
400
|
+
h('td', { style: { ...styles.tdRight, fontWeight: 600 } }, model.priced === false ? '未定价' : fmtMoney(model.cost, currency))))))),
|
|
401
|
+
]))
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
function UsageTable({ models }) {
|
|
405
|
+
// #32:空态保留表格结构,数值显示 0(不再用 colSpan 文案行)
|
|
406
|
+
const emptyRow = models.length === 0
|
|
407
|
+
? h('tr', { key: 'empty' },
|
|
408
|
+
h('td', { style: styles.modelCell }, '—'),
|
|
409
|
+
h('td', { style: styles.tdRight }, 0),
|
|
410
|
+
h('td', { style: styles.tdRight }, fmtM(0)),
|
|
411
|
+
h('td', { style: styles.tdRight }, fmtM(0)),
|
|
412
|
+
h('td', { style: styles.tdRight }, fmtM(0)),
|
|
413
|
+
h('td', { style: styles.tdRight }, '—'))
|
|
414
|
+
: null
|
|
415
|
+
return h('div', { 'data-testid': 'token-dash-usage-table', style: styles.card },
|
|
416
|
+
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))}`)),
|
|
417
|
+
h('div', { style: { overflowX: 'auto' } },
|
|
418
|
+
h('table', { style: styles.table },
|
|
419
|
+
h('thead', null, h('tr', null,
|
|
420
|
+
h('th', { key: '模型', style: styles.th }, '模型'),
|
|
421
|
+
h('th', { key: '请求', style: { ...styles.thRight, width: 44 } }, '请求'),
|
|
422
|
+
h('th', { key: '输入', style: { ...styles.thRight, width: 56 } }, '输入'),
|
|
423
|
+
h('th', { key: '命中', style: { ...styles.thRight, width: 56 } }, '命中'),
|
|
424
|
+
h('th', { key: '输出', style: { ...styles.thRight, width: 56 } }, '输出'),
|
|
425
|
+
h('th', { key: '命中率', style: { ...styles.thRight, width: 52 } }, '命中率'))),
|
|
426
|
+
h('tbody', null,
|
|
427
|
+
models.map((model) => h('tr', { key: `${model.providerId}:${model.modelId}` },
|
|
428
|
+
h('td', { style: styles.modelCell, title: modelTitle(model) }, modelTitle(model)),
|
|
429
|
+
h('td', { style: styles.tdRight }, model.requests),
|
|
430
|
+
h('td', { style: styles.tdRight }, fmtM(model.tokens?.input ?? 0)),
|
|
431
|
+
h('td', { style: styles.tdRight }, fmtM(model.tokens?.cacheRead ?? 0)),
|
|
432
|
+
h('td', { style: styles.tdRight }, fmtM(model.tokens?.output ?? 0)),
|
|
433
|
+
h('td', { style: styles.tdRight }, model.hitRate === null || model.hitRate === undefined ? '—' : fmtRatio(model.hitRate)))),
|
|
434
|
+
emptyRow))))
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
function Panel({ summary, error, view, refreshing, maxHeight = '70vh', onView, onRefresh, onRefreshSubs, onClose }) {
|
|
438
|
+
const panelRef = useRef(null)
|
|
439
|
+
|
|
440
|
+
useEffect(() => {
|
|
441
|
+
panelRef.current?.focus?.()
|
|
442
|
+
}, [])
|
|
443
|
+
|
|
444
|
+
// #35:点击浮层外部关闭(Esc 按 D-15 修订不做);命中 pill/hint 时交给 pill 的 toggle,不视为外部
|
|
445
|
+
useEffect(() => {
|
|
446
|
+
const onDown = (event) => {
|
|
447
|
+
const node = panelRef.current
|
|
448
|
+
if (node === null || node.contains(event.target)) return
|
|
449
|
+
const wrap = node.parentElement
|
|
450
|
+
if (wrap !== null && wrap.contains(event.target)) return
|
|
451
|
+
onClose()
|
|
452
|
+
}
|
|
453
|
+
document.addEventListener('mousedown', onDown)
|
|
454
|
+
return () => document.removeEventListener('mousedown', onDown)
|
|
455
|
+
}, [onClose])
|
|
456
|
+
|
|
457
|
+
const panelProps = {
|
|
458
|
+
ref: panelRef, tabIndex: -1, role: 'dialog', 'aria-label': 'Token 看板',
|
|
459
|
+
'data-testid': 'token-dash-panel',
|
|
460
|
+
style: { ...styles.panel, maxHeight },
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
if (view === 'settings') {
|
|
464
|
+
return h('div', panelProps,
|
|
465
|
+
h(Settings, { summary, onBack: () => onView('dashboard'), onClose, onRefresh, onRefreshSubs }))
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
const models = summary?.breakdown?.models ?? []
|
|
469
|
+
const providers = summary?.providers ?? []
|
|
470
|
+
const api = providers.filter((provider) => provider.kind === 'api')
|
|
471
|
+
const subscriptions = providers.filter((provider) => provider.kind === 'subscription')
|
|
472
|
+
const ago = fmtAgo(summary?.updatedAt)
|
|
473
|
+
return h('div', panelProps,
|
|
474
|
+
h('div', { style: styles.titleBar },
|
|
475
|
+
h('b', { style: styles.headerTitle }, 'Token 看板'),
|
|
476
|
+
h('span', { style: styles.buttonGroup },
|
|
477
|
+
h('button', { style: { ...styles.button, opacity: refreshing ? 0.6 : 1 }, disabled: refreshing, onClick: onRefresh }, refreshing ? '刷新中…' : '刷新'),
|
|
478
|
+
h('button', { style: styles.button, onClick: () => onView('settings') }, '设置'),
|
|
479
|
+
h('button', { style: styles.button, onClick: onClose }, '关闭'))),
|
|
480
|
+
error ? h('div', { style: { ...styles.row, color: '#e05a5a', marginTop: 6 } },
|
|
481
|
+
h('span', null, 'Token 数据不可用'),
|
|
482
|
+
h('button', { 'data-testid': 'token-dash-retry', style: styles.button, onClick: onRefresh }, '重试')) : null,
|
|
483
|
+
h('div', { style: { ...styles.muted, marginTop: 6 } }, '自动侦测 API Key 类型:DeepSeek / Kimi / GLM / OpenRouter / Qwen'),
|
|
484
|
+
providers.length === 0 ? h('div', { style: { ...styles.muted, marginTop: 10 } }, '未检测到已配置供应商') : null,
|
|
485
|
+
api.length > 0 ? h('div', { 'data-testid': 'token-dash-api-section', style: { marginTop: 8 } },
|
|
486
|
+
h('div', { style: styles.row }, h('b', { style: styles.headerTitle }, 'API 按量'), h('span', { style: styles.muted }, `已检测 ${api.length} · ${ago}`)),
|
|
487
|
+
h('div', { style: api.length > 3 ? styles.scrollList : null },
|
|
488
|
+
api.map((provider) => h(ApiCard, { key: provider.id, provider })))) : null,
|
|
489
|
+
subscriptions.length > 0 ? h('div', { 'data-testid': 'token-dash-sub-section', style: { marginTop: 8 } },
|
|
490
|
+
h('div', { style: styles.row },
|
|
491
|
+
h('b', { style: styles.headerTitle }, '订阅套餐'),
|
|
492
|
+
h('span', { style: styles.rowStart }, api.length === 0 ? h('span', { style: styles.muted }, ago) : null,
|
|
493
|
+
h('button', { 'data-testid': 'token-dash-rescan', style: styles.button, onClick: onRefreshSubs }, '重新检测'))),
|
|
494
|
+
h('div', { style: styles.subGrid }, subscriptions.map((provider) => h(SubscriptionCard, { key: provider.id, provider })))) : null,
|
|
495
|
+
h(ApiCostTable, { models }),
|
|
496
|
+
h(UsageTable, { models }))
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
function modeSelect(provider, prefs, savePrefs) {
|
|
500
|
+
const value = prefs.billingModes?.[provider.id] ?? (provider.kind === 'subscription' ? 'subscription' : 'api')
|
|
501
|
+
return h('select', {
|
|
502
|
+
value,
|
|
503
|
+
'aria-label': `${provider.name} 计费模式`,
|
|
504
|
+
onChange: (event) => savePrefs({ billingModes: { ...(prefs.billingModes ?? {}), [provider.id]: event.target.value } }),
|
|
505
|
+
style: styles.select,
|
|
506
|
+
},
|
|
507
|
+
h('option', { value: 'api' }, '按量 API'),
|
|
508
|
+
provider.canSubscribe === true ? h('option', { value: 'subscription' }, '订阅套餐') : null,
|
|
509
|
+
h('option', { value: 'hide' }, '不显示'))
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
function Settings({ summary, onBack, onClose, onRefresh, onRefreshSubs }) {
|
|
513
|
+
const [prefs, setPrefs] = useState(null)
|
|
514
|
+
const [budgetText, setBudgetText] = useState({})
|
|
515
|
+
const [status, setStatus] = useState(null)
|
|
516
|
+
const [update, setUpdate] = useState({ phase: 'idle' })
|
|
517
|
+
const [logMeta, setLogMeta] = useState(null)
|
|
518
|
+
|
|
519
|
+
useEffect(() => {
|
|
520
|
+
getJson('/prefs').then((data) => {
|
|
521
|
+
setPrefs(data)
|
|
522
|
+
const next = {}
|
|
523
|
+
for (const [id, value] of Object.entries(data.budgets ?? {})) next[id] = String(value.amount ?? '')
|
|
524
|
+
setBudgetText(next)
|
|
525
|
+
}).catch(() => setStatus({ text: '读取失败', error: true }))
|
|
526
|
+
}, [])
|
|
527
|
+
|
|
528
|
+
function flash(text, error = false) {
|
|
529
|
+
setStatus({ text, error })
|
|
530
|
+
if (error !== true) setTimeout(() => setStatus((current) => (current?.text === text ? null : current)), 1500)
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
async function savePrefs(patch) {
|
|
534
|
+
if (prefs === null) return null
|
|
535
|
+
try {
|
|
536
|
+
const saved = await putPrefs({ ...prefs, ...patch })
|
|
537
|
+
setPrefs(saved)
|
|
538
|
+
flash('已保存')
|
|
539
|
+
void onRefresh?.()
|
|
540
|
+
return saved
|
|
541
|
+
} catch (error) {
|
|
542
|
+
setStatus({ text: `保存失败:${error.message}`, error: true })
|
|
543
|
+
return null
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
async function saveBudget(provider, raw) {
|
|
548
|
+
const text = String(raw).replace(/[\u00a5$,\s]/g, '')
|
|
549
|
+
const amount = Number(text)
|
|
550
|
+
if (text === '' || !Number.isFinite(amount) || amount < 0 || amount > 9999999.99) {
|
|
551
|
+
setStatus({ text: '请输入 0 ~ 9,999,999.99', error: true })
|
|
552
|
+
return
|
|
553
|
+
}
|
|
554
|
+
const budgets = { ...(prefs?.budgets ?? {}), [provider.id]: { amount: Math.round(amount * 100) / 100, currency: provider.currency } }
|
|
555
|
+
const saved = await savePrefs({ budgets })
|
|
556
|
+
if (saved !== null) setBudgetText((current) => ({ ...current, [provider.id]: String(saved.budgets[provider.id]?.amount ?? '') }))
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
async function refreshSubscriptions() {
|
|
560
|
+
flash('检测中…')
|
|
561
|
+
await onRefreshSubs?.()
|
|
562
|
+
flash('已重新检测')
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
async function openLogs() {
|
|
566
|
+
try {
|
|
567
|
+
const meta = logMeta ?? await getJson('/logs/meta')
|
|
568
|
+
setLogMeta(meta)
|
|
569
|
+
const app = /Mac|iPhone|iPad/.test(navigator.platform) ? 'finder' : /Linux/.test(navigator.platform) ? 'filemanager' : 'explorer'
|
|
570
|
+
const response = await fetch('/open-in-app/open', {
|
|
571
|
+
method: 'POST',
|
|
572
|
+
headers: { 'content-type': 'application/json' },
|
|
573
|
+
body: JSON.stringify({ app, path: meta.dir }),
|
|
574
|
+
})
|
|
575
|
+
if (!response.ok) throw new Error('open-failed')
|
|
576
|
+
flash('已打开日志文件夹')
|
|
577
|
+
} catch {
|
|
578
|
+
try {
|
|
579
|
+
const meta = logMeta ?? await getJson('/logs/meta')
|
|
580
|
+
await navigator.clipboard.writeText(meta.dir)
|
|
581
|
+
flash('无法打开,已复制路径')
|
|
582
|
+
} catch {
|
|
583
|
+
setStatus({ text: '打开日志失败', error: true })
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
async function exportLogs() {
|
|
589
|
+
try {
|
|
590
|
+
const data = await getJson('/logs/export')
|
|
591
|
+
const blob = new Blob([data.content], { type: 'text/plain;charset=utf-8' })
|
|
592
|
+
const url = URL.createObjectURL(blob)
|
|
593
|
+
const link = document.createElement('a')
|
|
594
|
+
link.href = url
|
|
595
|
+
link.download = 'dsh-token-dash.log'
|
|
596
|
+
link.click()
|
|
597
|
+
URL.revokeObjectURL(url)
|
|
598
|
+
flash('日志已导出')
|
|
599
|
+
} catch {
|
|
600
|
+
setStatus({ text: '日志导出失败', error: true })
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
async function checkUpdate() {
|
|
605
|
+
setUpdate({ phase: 'checking' })
|
|
606
|
+
try {
|
|
607
|
+
const data = await getJson('/update')
|
|
608
|
+
if (data.published === false) setUpdate({ phase: 'done', text: '未发布' })
|
|
609
|
+
else if (data.hasUpdate) setUpdate({ phase: 'confirm', latest: data.latest })
|
|
610
|
+
else setUpdate({ phase: 'done', text: '已是最新' })
|
|
611
|
+
} catch {
|
|
612
|
+
setUpdate({ phase: 'error', text: '检查失败' })
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
async function installUpdate() {
|
|
617
|
+
setUpdate({ phase: 'installing' })
|
|
618
|
+
try {
|
|
619
|
+
const res = await fetch(`${API}/update/install`, { method: 'POST', headers: { accept: 'application/json' } })
|
|
620
|
+
const body = await res.json().catch(() => ({}))
|
|
621
|
+
const data = body?.data
|
|
622
|
+
if (body?.ok === true) setUpdate({ phase: 'done', text: '已更新,重启 DSH 后生效' })
|
|
623
|
+
else setUpdate({ phase: 'error', text: `更新失败(${data?.reason ?? 'unknown'})`, command: data?.command })
|
|
624
|
+
} catch (error) {
|
|
625
|
+
setUpdate({ phase: 'error', text: `更新失败(${error.message})` })
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
async function copyCommand() {
|
|
630
|
+
try {
|
|
631
|
+
await navigator.clipboard.writeText(update.command ?? '')
|
|
632
|
+
flash('命令已复制')
|
|
633
|
+
} catch {
|
|
634
|
+
setStatus({ text: '复制失败', error: true })
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
// #34:状态提示放"关闭"左侧,固定宽度占位——出现/消失不改变标题栏布局,弹窗不 resize
|
|
639
|
+
const statusSlot = h('span', {
|
|
640
|
+
role: 'status', 'aria-live': 'polite',
|
|
641
|
+
style: { minWidth: 88, textAlign: 'right', fontSize: 11, opacity: 0.85, color: status?.error === true ? '#e05a5a' : undefined },
|
|
642
|
+
}, status?.text ?? '')
|
|
643
|
+
|
|
644
|
+
const header = h('div', { style: styles.titleBar },
|
|
645
|
+
h('div', { style: styles.rowStart },
|
|
646
|
+
h('button', { style: styles.button, onClick: onBack }, '← 返回'),
|
|
647
|
+
h('b', { style: styles.headerTitle }, 'Token 看板')),
|
|
648
|
+
h('span', { style: styles.rowStart }, statusSlot, h('button', { style: styles.button, onClick: onClose }, '关闭')))
|
|
649
|
+
|
|
650
|
+
if (prefs === null) return h('div', { 'data-testid': 'token-dash-settings', style: { fontSize: 12, display: 'grid', gap: 10 } }, header, '加载中…')
|
|
651
|
+
|
|
652
|
+
const providers = summary?.providers ?? []
|
|
653
|
+
const api = providers.filter((provider) => provider.kind === 'api')
|
|
654
|
+
const subscriptions = providers.filter((provider) => provider.kind === 'subscription')
|
|
655
|
+
const version = summary?.version ?? ''
|
|
656
|
+
const cardStyle = { ...styles.card, marginTop: 0, display: 'grid', gap: 10, background: 'rgba(128,128,128,.05)' }
|
|
657
|
+
const section = (title, body, action = null) => h('section', { style: { display: 'grid', gap: 8 } },
|
|
658
|
+
h('div', { style: styles.row }, h('b', { style: styles.headerTitle }, title), action),
|
|
659
|
+
body)
|
|
660
|
+
|
|
661
|
+
// #39:API 卡删除计费模式下拉——单行:provider 名 + 月度预算 + 输入框 + 币种(模式依赖自动侦测)
|
|
662
|
+
const apiCards = api.map((provider) => h('div', { key: provider.id, style: cardStyle },
|
|
663
|
+
h('div', { style: styles.row },
|
|
664
|
+
h('b', { style: styles.nameEllipsis, title: provider.name }, provider.name),
|
|
665
|
+
h('span', { style: styles.rowStart },
|
|
666
|
+
h('span', { style: styles.muted }, '月度预算'),
|
|
667
|
+
h('input', {
|
|
668
|
+
type: 'text', inputMode: 'decimal', 'aria-label': `${provider.name} 月度预算`,
|
|
669
|
+
value: budgetText[provider.id] ?? (provider.budget?.amount ? String(provider.budget.amount) : ''),
|
|
670
|
+
onChange: (event) => setBudgetText({ ...budgetText, [provider.id]: event.target.value }),
|
|
671
|
+
onBlur: (event) => saveBudget(provider, event.currentTarget.value),
|
|
672
|
+
onKeyDown: (event) => { if (event.key === 'Enter') { event.preventDefault(); event.currentTarget.blur() } },
|
|
673
|
+
style: styles.input,
|
|
674
|
+
}),
|
|
675
|
+
h('span', { style: styles.muted }, provider.currency)))))
|
|
676
|
+
|
|
677
|
+
const subscriptionRows = subscriptions.map((provider) => h('div', { key: provider.id, style: styles.row },
|
|
678
|
+
h('span', { style: styles.nameEllipsis, title: provider.name }, provider.name),
|
|
679
|
+
h('span', { style: styles.rowStart },
|
|
680
|
+
modeSelect(provider, prefs, savePrefs),
|
|
681
|
+
h('span', { style: styles.muted }, `${subscriptionText(provider)} · 账户套餐`))))
|
|
682
|
+
|
|
683
|
+
let updateControl = h('button', { style: styles.button, onClick: checkUpdate }, '检查更新')
|
|
684
|
+
if (update.phase === 'checking') updateControl = h('span', { style: styles.muted }, '检查中…')
|
|
685
|
+
else if (update.phase === 'confirm') updateControl = h('span', { style: styles.rowStart },
|
|
686
|
+
h('span', null, `发现 ${update.latest}`),
|
|
687
|
+
h('button', { style: styles.button, onClick: installUpdate }, '更新'),
|
|
688
|
+
h('button', { style: styles.button, onClick: () => setUpdate({ phase: 'idle' }) }, '取消'))
|
|
689
|
+
else if (update.phase === 'installing') updateControl = h('span', { style: styles.muted }, '更新中…')
|
|
690
|
+
else if (update.phase === 'done') updateControl = h('span', { style: styles.muted }, update.text)
|
|
691
|
+
else if (update.phase === 'error') updateControl = h('span', { style: styles.rowStart },
|
|
692
|
+
h('span', { style: { color: '#e05a5a' } }, update.text),
|
|
693
|
+
update.command ? h('button', { style: styles.button, onClick: copyCommand }, '复制命令') : null)
|
|
694
|
+
|
|
695
|
+
return h('div', { 'data-testid': 'token-dash-settings', style: { fontSize: 12, display: 'grid', gap: 12 } },
|
|
696
|
+
header,
|
|
697
|
+
api.length > 0 ? section(`API 计费(已检测 ${api.length})`, h('div', { style: { display: 'grid', gap: 8 } }, ...apiCards)) : null,
|
|
698
|
+
subscriptions.length > 0 ? section(`订阅计费(已检测 ${subscriptions.length})`,
|
|
699
|
+
h('div', { style: cardStyle }, ...subscriptionRows),
|
|
700
|
+
h('button', { 'data-testid': 'token-dash-rescan', style: styles.button, onClick: refreshSubscriptions }, '重新检测')) : null,
|
|
701
|
+
section('显示', h('div', { style: cardStyle },
|
|
702
|
+
h('div', { style: styles.row }, h('span', null, '刷新间隔'),
|
|
703
|
+
h(Segmented, { value: prefs.refreshMs, onChange: (ms) => savePrefs({ refreshMs: ms }) })),
|
|
704
|
+
h('div', { style: styles.row }, h('span', null, '账户余额'),
|
|
705
|
+
h(Toggle, { checked: prefs.showBalance, onChange: (next) => savePrefs({ showBalance: next }) })))),
|
|
706
|
+
section('日志', h('div', { style: cardStyle },
|
|
707
|
+
h('div', { style: styles.row },
|
|
708
|
+
h('span', null, '查看日志'),
|
|
709
|
+
h('span', { style: styles.rowStart },
|
|
710
|
+
h('button', { 'data-testid': 'token-dash-log-open', style: styles.button, onClick: openLogs }, '打开日志文件夹'),
|
|
711
|
+
h('button', { 'data-testid': 'token-dash-log-export', style: styles.button, onClick: exportLogs }, '导出日志'))))),
|
|
712
|
+
section('价格与版本', h('div', { style: cardStyle },
|
|
713
|
+
h('div', { style: styles.row },
|
|
714
|
+
h('span', null, '查看价格明细'),
|
|
715
|
+
h('span', { style: { display: 'flex', flexWrap: 'wrap', justifyContent: 'flex-end', gap: 8 } },
|
|
716
|
+
LINKS.map(([label, url]) => h('a', { key: label, href: url, target: '_blank', rel: 'noopener', style: { ...styles.link, marginLeft: 0 } }, label)))),
|
|
717
|
+
h('div', { style: styles.row },
|
|
718
|
+
h('span', { style: styles.muted }, `版本 ${version}`),
|
|
719
|
+
updateControl))),
|
|
720
|
+
h('div', { style: styles.muted }, 'API 费用按 catalog/社区价估算;订阅只显示账户配额'))
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
return {
|
|
724
|
+
name: PKG,
|
|
725
|
+
inject: ['slots'],
|
|
726
|
+
apply(ctx) {
|
|
727
|
+
const slots = typeof ctx.get === 'function' ? ctx.get('slots') : ctx.slots
|
|
728
|
+
if (slots === undefined || typeof slots.inject !== 'function') return
|
|
729
|
+
// #46:slot 挂载上报 host 落盘(§2.5 slot 模块;fire-and-forget,失败静默)
|
|
730
|
+
const reportMount = (slot) => {
|
|
731
|
+
try {
|
|
732
|
+
void fetch(`${API}/log`, {
|
|
733
|
+
method: 'POST',
|
|
734
|
+
headers: { 'content-type': 'application/json' },
|
|
735
|
+
body: JSON.stringify({ module: 'slot', event: 'mount.ok', meta: { slot } }),
|
|
736
|
+
}).catch(() => {})
|
|
737
|
+
} catch {
|
|
738
|
+
// ignore
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
slots.inject('conversation.hero.agentPreset', () => {
|
|
742
|
+
reportMount('conversation.hero.agentPreset')
|
|
743
|
+
return slots.register({ name: 'conversation.hero.agentPreset', id: 'token-dash-home', order: 10 }, Pill)
|
|
744
|
+
})
|
|
745
|
+
slots.inject('conversation.composer.dock', () => {
|
|
746
|
+
reportMount('conversation.composer.dock')
|
|
747
|
+
return slots.register({ name: 'conversation.composer.dock', id: 'token-dash-input', order: -1 }, Pill)
|
|
748
|
+
})
|
|
749
|
+
},
|
|
750
|
+
}
|
|
751
|
+
},
|
|
752
|
+
})
|