dsh-plugin-balance-usage 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js ADDED
@@ -0,0 +1,1349 @@
1
+ /**
2
+ * Client half of the balance & usage bundle.
3
+ *
4
+ * Registers one sidebar footer action and one floating panel. Balance and the
5
+ * official usage link come from existing account Remotes; token usage comes
6
+ * from this bundle's own Host route (see index.js).
7
+ */
8
+ window.__ModuleLoader__.load({
9
+ id: 'dsh-plugin-balance-usage',
10
+ factory(require) {
11
+ const React = require('react')
12
+ const h = React.createElement
13
+ const { useEffect, useRef, useState } = React
14
+ const nativeSyncExternalStore = React.useSyncExternalStore
15
+
16
+ function useSyncExternalStore(subscribe, getSnapshot) {
17
+ if (nativeSyncExternalStore) return nativeSyncExternalStore(subscribe, getSnapshot)
18
+ /* Fallback for a React build without the hook: same contract, coarser. */
19
+ const [value, setValue] = useState(getSnapshot)
20
+ useEffect(() => {
21
+ const unsubscribe = subscribe(() => setValue(getSnapshot()))
22
+ setValue(getSnapshot())
23
+ return unsubscribe
24
+ }, [])
25
+ return value
26
+ }
27
+
28
+ const ROUTE = '/plugins/balance-usage/summary'
29
+ const FALLBACK_USAGE_URL = 'https://platform.deepseek.com/usage'
30
+ const KEY_PRIMARY = 'dsh.balance-usage.primary'
31
+ const KEY_COLLAPSED = 'dsh.balance-usage.collapsed'
32
+ const PANEL_ID = 'dbu-panel'
33
+ const PANEL_TITLE_ID = 'dbu-panel-title'
34
+ const PLATFORM_BACK_ID = 'dbu-platform-back'
35
+ /* The footer numbers are glanceable, so they refresh on their own: often while the
36
+ panel is open, less often while it is closed, and immediately when the window
37
+ comes back to the foreground. */
38
+ const REFRESH_OPEN_MS = 15_000
39
+ const REFRESH_IDLE_MS = 30_000
40
+ const TICK_MS = 5_000
41
+ const STALE_MS = 8_000
42
+
43
+ /* ---------------------------------------------------------------- *
44
+ * Copy
45
+ * ---------------------------------------------------------------- */
46
+
47
+ const COPY = {
48
+ zh: {
49
+ entry: '余额与用量',
50
+ title: '余额与用量',
51
+ refresh: '刷新',
52
+ close: '关闭',
53
+ balance: '账户余额',
54
+ bonus: '赠送余额',
55
+ signedOut: '尚未登录 DeepSeek 账号,登录后可读取余额。',
56
+ signedOutShort: '未登录',
57
+ accountUnavailable: '账户服务不可用',
58
+ usage: 'Token 用量',
59
+ today: '今日',
60
+ total: '累计',
61
+ input: '输入',
62
+ output: '输出',
63
+ cache: '缓存读取',
64
+ requests: '请求',
65
+ primary: '主线',
66
+ auto: '自动',
67
+ setPrimary: '设为主线',
68
+ clearPrimary: '取消主线',
69
+ groups: '模型 / 运营商',
70
+ empty: '还没有用量记录,发送一条消息后再看看。',
71
+ openUsage: '打开官方 Token 用量详情',
72
+ loading: '读取中…',
73
+ failed: '数据读取失败',
74
+ noUsageRoute: '用量统计服务未就绪',
75
+ updated: '更新于',
76
+ last14: '近 14 天',
77
+ sessions: '个会话',
78
+ entryTitle: '余额与用量',
79
+ requestsSuffix: '次请求',
80
+ retry: '重试',
81
+ starHint: '星标 = 侧栏显示的主线',
82
+ stale: '(未更新)',
83
+ composition: '累计构成',
84
+ newWindow: '新窗口',
85
+ back: '返回',
86
+ usagePage: 'Token 用量',
87
+ platformLoading: '正在打开官方页面…',
88
+ platformFailed: '应用内页面打开失败',
89
+ browser: '在浏览器打开',
90
+ },
91
+ en: {
92
+ entry: 'Balance & usage',
93
+ title: 'Balance & usage',
94
+ refresh: 'Refresh',
95
+ close: 'Close',
96
+ balance: 'Account balance',
97
+ bonus: 'Bonus balance',
98
+ signedOut: 'Not signed in to a DeepSeek account. Sign in to read the balance.',
99
+ signedOutShort: 'Signed out',
100
+ accountUnavailable: 'Account service unavailable',
101
+ usage: 'Token usage',
102
+ today: 'Today',
103
+ total: 'Total',
104
+ input: 'Input',
105
+ output: 'Output',
106
+ cache: 'Cache read',
107
+ requests: 'requests',
108
+ primary: 'Main',
109
+ auto: 'Auto',
110
+ setPrimary: 'Set as main',
111
+ clearPrimary: 'Clear main',
112
+ groups: 'Models / providers',
113
+ empty: 'No usage recorded yet. Send a message first.',
114
+ openUsage: 'Open the official token usage page',
115
+ loading: 'Loading…',
116
+ failed: 'Could not load data',
117
+ noUsageRoute: 'Usage service not available',
118
+ updated: 'Updated',
119
+ last14: 'Last 14 days',
120
+ sessions: 'sessions',
121
+ entryTitle: 'Balance & usage',
122
+ requestsSuffix: 'requests',
123
+ retry: 'Retry',
124
+ starHint: 'Star picks the line the sidebar shows',
125
+ stale: ' (not updated)',
126
+ composition: 'Total breakdown',
127
+ newWindow: 'new window',
128
+ back: 'Back',
129
+ usagePage: 'Token usage',
130
+ platformLoading: 'Opening the official page…',
131
+ platformFailed: 'Could not open the page in the app',
132
+ browser: 'Open in browser',
133
+ },
134
+ }
135
+
136
+ const PROVIDERS = {
137
+ 'deepseek-account': { zh: 'DeepSeek 账号', en: 'DeepSeek account' },
138
+ deepseek: { zh: 'DeepSeek', en: 'DeepSeek' },
139
+ openrouter: { zh: 'OpenRouter', en: 'OpenRouter' },
140
+ }
141
+
142
+ /* getLocale() returns the locale snapshot ({ active, locales, revision }), not a tag. */
143
+ function activeLocale() {
144
+ const snapshot = clientCtx?.locale?.getLocale?.()
145
+ return typeof snapshot?.active === 'string' ? snapshot.active : ''
146
+ }
147
+
148
+ function isChinese() {
149
+ return activeLocale().toLowerCase().startsWith('zh')
150
+ }
151
+
152
+ function copy() {
153
+ return isChinese() ? COPY.zh : COPY.en
154
+ }
155
+
156
+ function providerLabel(id) {
157
+ const entry = PROVIDERS[id]
158
+ if (!entry) return id
159
+ return isChinese() ? entry.zh : entry.en
160
+ }
161
+
162
+ /* ---------------------------------------------------------------- *
163
+ * Formatting
164
+ * ---------------------------------------------------------------- */
165
+
166
+ function fmtTokens(value) {
167
+ const number = Number(value) || 0
168
+ if (number <= 0) return '0'
169
+ if (number >= 1e9) return `${(number / 1e9).toFixed(2)}B`
170
+ if (number >= 1e6) return `${(number / 1e6).toFixed(2)}M`
171
+ if (number >= 1e3) return `${(number / 1e3).toFixed(1)}K`
172
+ return String(Math.round(number))
173
+ }
174
+
175
+ function walletNumber(wallet) {
176
+ const parsed = Number(wallet?.balance)
177
+ return Number.isFinite(parsed) ? parsed : null
178
+ }
179
+
180
+ function fmtWallet(wallet) {
181
+ if (!wallet) return '—'
182
+ const number = walletNumber(wallet)
183
+ const currency = wallet.currency === 'USD' ? 'USD' : 'CNY'
184
+ if (number === null) return `${currency === 'USD' ? '$' : '¥'}${wallet.balance}`
185
+ try {
186
+ return new Intl.NumberFormat(isChinese() ? 'zh-CN' : 'en-US', {
187
+ style: 'currency',
188
+ currency,
189
+ minimumFractionDigits: 2,
190
+ maximumFractionDigits: 2,
191
+ }).format(number)
192
+ } catch {
193
+ return `${currency === 'USD' ? '$' : '¥'}${number.toFixed(2)}`
194
+ }
195
+ }
196
+
197
+ function mainWallet(wallets) {
198
+ if (!Array.isArray(wallets) || wallets.length === 0) return null
199
+ /* CNY is the primary wallet when both currencies are present; otherwise the
200
+ largest usable balance stands in. */
201
+ const cny = wallets.find((wallet) => wallet.currency === 'CNY' && walletNumber(wallet) !== null)
202
+ if (cny) return cny
203
+ const usable = wallets.filter((wallet) => walletNumber(wallet) !== null)
204
+ if (usable.length === 0) return wallets[0]
205
+ return usable.sort((a, b) => walletNumber(b) - walletNumber(a))[0]
206
+ }
207
+
208
+ function bonusTotal(wallets) {
209
+ if (!Array.isArray(wallets) || wallets.length === 0) return null
210
+ const usable = wallets.filter((wallet) => walletNumber(wallet) !== null)
211
+ if (usable.length === 0) return null
212
+ const currency = usable[0].currency === 'USD' ? 'USD' : 'CNY'
213
+ const total = usable
214
+ .filter((wallet) => (wallet.currency === 'USD' ? 'USD' : 'CNY') === currency)
215
+ .reduce((sum, wallet) => sum + walletNumber(wallet), 0)
216
+ return { currency, total }
217
+ }
218
+
219
+ function fmtClock(ms) {
220
+ if (!ms) return ''
221
+ const date = new Date(ms)
222
+ return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
223
+ }
224
+
225
+ function fmtRelative(ms) {
226
+ if (!ms) return ''
227
+ const diff = Date.now() - ms
228
+ const locale = isChinese() ? 'zh-CN' : 'en-US'
229
+ try {
230
+ const rtf = new Intl.RelativeTimeFormat(locale, { numeric: 'auto' })
231
+ const minutes = Math.round(diff / 60_000)
232
+ if (minutes < 1) return rtf.format(0, 'minute')
233
+ if (minutes < 60) return rtf.format(-minutes, 'minute')
234
+ const hours = Math.round(minutes / 60)
235
+ if (hours < 24) return rtf.format(-hours, 'hour')
236
+ const days = Math.round(hours / 24)
237
+ if (days < 15) return rtf.format(-days, 'day')
238
+ return new Intl.DateTimeFormat(locale, { month: 'short', day: 'numeric' }).format(new Date(ms))
239
+ } catch {
240
+ const hours = Math.round(diff / 3_600_000)
241
+ return hours < 1 ? '<1h' : `${hours}h`
242
+ }
243
+ }
244
+
245
+ /* ---------------------------------------------------------------- *
246
+ * Small persisted settings
247
+ * ---------------------------------------------------------------- */
248
+
249
+ function readPrimary() {
250
+ try {
251
+ const raw = globalThis.localStorage?.getItem(KEY_PRIMARY)
252
+ if (!raw) return null
253
+ const value = JSON.parse(raw)
254
+ if (value && typeof value.provider === 'string' && typeof value.model === 'string') return value
255
+ } catch {
256
+ /* ignore a corrupt preference */
257
+ }
258
+ return null
259
+ }
260
+
261
+ function writePrimary(value) {
262
+ try {
263
+ if (value) globalThis.localStorage?.setItem(KEY_PRIMARY, JSON.stringify(value))
264
+ else globalThis.localStorage?.removeItem(KEY_PRIMARY)
265
+ } catch {
266
+ /* storage may be unavailable */
267
+ }
268
+ }
269
+
270
+ function readCollapsed() {
271
+ try {
272
+ const raw = globalThis.localStorage?.getItem(KEY_COLLAPSED)
273
+ const value = raw ? JSON.parse(raw) : null
274
+ if (Array.isArray(value)) return value.filter((item) => typeof item === 'string')
275
+ } catch {
276
+ /* ignore */
277
+ }
278
+ return []
279
+ }
280
+
281
+ function writeCollapsed(value) {
282
+ try {
283
+ globalThis.localStorage?.setItem(KEY_COLLAPSED, JSON.stringify(value))
284
+ } catch {
285
+ /* ignore */
286
+ }
287
+ }
288
+
289
+ /* ---------------------------------------------------------------- *
290
+ * Shared store
291
+ * ---------------------------------------------------------------- */
292
+
293
+ let clientCtx = null
294
+ let state = {
295
+ open: false,
296
+ wide: true,
297
+ anchor: null,
298
+ entryEl: null,
299
+ platform: null,
300
+ collapsed: readCollapsed(),
301
+ primary: readPrimary(),
302
+ status: 'idle',
303
+ error: null,
304
+ usage: null,
305
+ usageError: null,
306
+ account: null,
307
+ accountError: null,
308
+ updatedAt: 0,
309
+ }
310
+ const listeners = new Set()
311
+
312
+ function setState(patch) {
313
+ state = { ...state, ...patch }
314
+ for (const listener of [...listeners]) listener()
315
+ }
316
+
317
+ function subscribe(listener) {
318
+ listeners.add(listener)
319
+ return () => listeners.delete(listener)
320
+ }
321
+
322
+ const getState = () => state
323
+ const useSnapshot = () => useSyncExternalStore(subscribe, getState)
324
+
325
+ /* The Desktop shell exposes a native Platform view over the page; a plain browser
326
+ has no such bridge, so the CTA falls back to an ordinary new tab. */
327
+ function platformBridge() {
328
+ const bridge = globalThis.dshPlatform
329
+ return bridge && typeof bridge.open === 'function' ? bridge : null
330
+ }
331
+
332
+ let inflight = null
333
+ let timer = null
334
+
335
+ function errorText(reason) {
336
+ if (!reason) return null
337
+ if (typeof reason === 'string') return reason
338
+ return String(reason.message || reason)
339
+ }
340
+
341
+ async function fetchUsage() {
342
+ const options = { headers: { accept: 'application/json' }, cache: 'no-store' }
343
+ /* A hung Host route must not leave the panel spinning forever. */
344
+ if (typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function') {
345
+ options.signal = AbortSignal.timeout(8000)
346
+ }
347
+ const response = await fetch(ROUTE, options)
348
+ if (!response.ok) throw new Error(`HTTP ${response.status}`)
349
+ const body = await response.json()
350
+ if (!body || body.ok !== true) throw new Error(body?.error || 'bad payload')
351
+ return body
352
+ }
353
+
354
+ function clientVersion() {
355
+ try {
356
+ const env = typeof process !== 'undefined' ? process.env : undefined
357
+ if (env && typeof env.DSH_CLIENT_VERSION === 'string' && env.DSH_CLIENT_VERSION) return env.DSH_CLIENT_VERSION
358
+ } catch {
359
+ /* no process shim */
360
+ }
361
+ const boot = globalThis.__DSH_BOOT__
362
+ const candidate = boot?.clientVersion || boot?.version
363
+ if (typeof candidate === 'string' && candidate) return candidate
364
+ return 'web'
365
+ }
366
+
367
+ function clientMetadata() {
368
+ return {
369
+ version: clientVersion(),
370
+ locale: activeLocale() || 'zh_CN',
371
+ timezoneOffsetSeconds: -new Date().getTimezoneOffset() * 60,
372
+ }
373
+ }
374
+
375
+ async function fetchAccount(ctx) {
376
+ const remote = ctx?.get?.('remote')
377
+ const account = remote?.account
378
+ if (!account) throw new Error(copy().accountUnavailable)
379
+
380
+ const meta = clientMetadata()
381
+ const view = await account.getState()
382
+ const snapshot = view && view.ok ? view.value : null
383
+ const signedIn = snapshot?.status === 'credential-stored'
384
+ const result = {
385
+ signedIn,
386
+ usageUrl: snapshot?.links?.usageUrl || null,
387
+ topUpUrl: snapshot?.links?.topUpUrl || null,
388
+ wallets: [],
389
+ bonusWallets: [],
390
+ }
391
+ if (!signedIn) return result
392
+
393
+ const balance = await account.getBalance(meta)
394
+ if (balance && balance.ok && balance.value && balance.value.status === 'ready') {
395
+ result.wallets = balance.value.value || []
396
+ result.bonusWallets = balance.value.bonusWallets || []
397
+ }
398
+ return result
399
+ }
400
+
401
+ function load(ctx, options = {}) {
402
+ if (inflight) return inflight
403
+ const fresh = state.status === 'ready' && Date.now() - state.updatedAt < STALE_MS
404
+ if (!options.force && fresh) return Promise.resolve()
405
+
406
+ inflight = (async () => {
407
+ if (state.status !== 'ready') setState({ status: 'loading' })
408
+ const [usage, account] = await Promise.allSettled([fetchUsage(), fetchAccount(ctx)])
409
+ const patch = {}
410
+ /* Only a successful round refreshes the freshness stamp; a failed refresh keeps
411
+ the previous "updated at" so the panel never claims newer data than it has. */
412
+ if (usage.status === 'fulfilled' || account.status === 'fulfilled') patch.updatedAt = Date.now()
413
+
414
+ if (usage.status === 'fulfilled') {
415
+ patch.usage = usage.value
416
+ patch.usageError = null
417
+ } else {
418
+ patch.usageError = errorText(usage.reason)
419
+ }
420
+
421
+ if (account.status === 'fulfilled') {
422
+ patch.account = account.value
423
+ patch.accountError = null
424
+ } else {
425
+ patch.accountError = errorText(account.reason)
426
+ }
427
+
428
+ const failed = patch.usageError && patch.accountError
429
+ patch.status = failed ? 'error' : 'ready'
430
+ patch.error = failed ? patch.usageError : null
431
+ setState(patch)
432
+ })().finally(() => {
433
+ inflight = null
434
+ })
435
+
436
+ return inflight
437
+ }
438
+
439
+ /* ---------------------------------------------------------------- *
440
+ * Derived data
441
+ * ---------------------------------------------------------------- */
442
+
443
+ function allModels(usage) {
444
+ if (!usage || !Array.isArray(usage.groups)) return []
445
+ const rows = []
446
+ for (const group of usage.groups) {
447
+ for (const model of group.models || []) {
448
+ rows.push({ ...model, provider: group.provider })
449
+ }
450
+ }
451
+ return rows
452
+ }
453
+
454
+ function resolveMain(usage, primary) {
455
+ const rows = allModels(usage)
456
+ if (rows.length === 0) return null
457
+ if (primary) {
458
+ const hit = rows.find((row) => row.provider === primary.provider && row.model === primary.model)
459
+ if (hit) return { row: hit, explicit: true }
460
+ }
461
+ rows.sort((a, b) => b.tokens - a.tokens || b.lastUsed - a.lastUsed)
462
+ return { row: rows[0], explicit: false }
463
+ }
464
+
465
+ /* ---------------------------------------------------------------- *
466
+ * Styles
467
+ * ---------------------------------------------------------------- */
468
+
469
+ const CSS = `
470
+ .dbu-entry{flex:0 1 auto;display:flex;align-items:center;gap:8px;min-width:0;max-width:100%;box-sizing:border-box;margin-top:4px;padding:4px 8px;border:0;border-radius:8px;background:transparent;color:inherit;font:inherit;text-align:left;cursor:pointer;transition:background-color .12s ease,color .12s ease}
471
+ .dbu-entry:hover{background:var(--dsw-alias-bg-skeleton)}
472
+ .dbu-entry[data-wide="false"]{width:32px;height:32px;padding:0;justify-content:center;position:relative}
473
+ .dbu-entry__icon{flex:none;display:inline-flex;align-items:center;color:var(--dsw-alias-label-secondary)}
474
+ .dbu-entry:hover .dbu-entry__icon{color:var(--dsw-alias-label-primary)}
475
+ .dbu-entry__body{display:flex;flex-direction:column;min-width:0;line-height:1.3}
476
+ .dbu-entry__money{font-size:12px;font-weight:600;color:var(--dsw-alias-label-primary);font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
477
+ .dbu-entry__meta{font-size:11px;color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
478
+ .dbu-entry__dot{position:absolute;top:1px;right:1px;width:7px;height:7px;border-radius:50%;background:var(--dsw-alias-chart-messages);box-shadow:0 0 0 2px var(--dsw-alias-bg-layer-1)}
479
+ .dbu-entry__dot[data-state="error"]{background:var(--dsw-alias-state-error-primary)}
480
+ .dbu-scrim{position:fixed;inset:0;z-index:998;background:transparent}
481
+ .dbu-platform{position:fixed;top:0;bottom:0;z-index:1100;box-sizing:border-box;display:flex;flex-direction:column;background:var(--dsw-alias-bg-base);color:var(--dsw-alias-label-primary);box-shadow:-1px 0 0 0 var(--dsw-alias-border-l1)}
482
+ .dbu-platform__bar{flex:none;display:flex;align-items:center;gap:8px;height:44px;box-sizing:border-box;padding:0 12px;border-bottom:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-base)}
483
+ .dbu-platform__tab{display:inline-flex;align-items:center;gap:6px;max-width:100%;height:28px;box-sizing:border-box;padding:0 4px 0 10px;border-radius:8px;border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-1)}
484
+ .dbu-platform__tabdot{flex:none;width:6px;height:6px;border-radius:50%;background:var(--dsw-alias-chart-messages)}
485
+ .dbu-platform__tablabel{font-size:12px;font-weight:550;color:var(--dsw-alias-label-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
486
+ .dbu-platform__close{flex:none;display:inline-flex;align-items:center;justify-content:center;width:20px;height:20px;padding:0;border:0;border-radius:5px;background:transparent;color:var(--dsw-alias-label-primary);opacity:.7;cursor:pointer}
487
+ .dbu-platform__close:hover{background:var(--dsw-alias-bg-skeleton);opacity:1}
488
+ .dbu-platform__close:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:1px}
489
+ .dbu-platform__viewport{position:relative;flex:1;min-height:0}
490
+ .dbu-platform__status{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:10px;padding:24px;text-align:center;font-size:12px;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-base)}
491
+ .dbu-platform__fail{opacity:.85}
492
+ .dbu-platform__actions{display:flex;align-items:center;gap:8px}
493
+ .dbu-platform__actions .dbu-retry{text-decoration:none}
494
+ .dbu-platform__spinner{width:18px;height:18px;border-radius:50%;border:2px solid var(--dsw-alias-bg-skeleton);border-top-color:var(--dsw-alias-brand-primary);animation:dbu-spin .9s linear infinite}
495
+ .dbu-panel{position:fixed;z-index:999;box-sizing:border-box;display:flex;flex-direction:column;width:336px;max-width:calc(100vw - 24px);max-height:72vh;border-radius:14px;border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-overlay);box-shadow:0 18px 48px rgba(0,0,0,.32);color:var(--dsw-alias-label-primary);font:inherit;overflow:hidden}
496
+ .dbu-panel:focus{outline:none}
497
+ .dbu-panel:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:2px}
498
+ .dbu-head{display:flex;align-items:center;gap:6px;padding:12px 12px 6px 14px}
499
+ .dbu-head__title{font-size:13px;font-weight:600;margin:0}
500
+ .dbu-head__time{font-size:11px;color:var(--dsw-alias-label-primary);opacity:.8;margin:0 auto 0 6px;font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
501
+ .dbu-iconbtn{flex:none;display:inline-flex;align-items:center;justify-content:center;width:26px;height:26px;padding:0;border:0;border-radius:7px;background:transparent;color:var(--dsw-alias-label-primary);opacity:.75;cursor:pointer}
502
+ .dbu-iconbtn:hover{background:var(--dsw-alias-bg-skeleton);opacity:1}
503
+ .dbu-iconbtn[data-busy="true"]{opacity:1;cursor:progress}
504
+ .dbu-iconbtn[data-busy="true"] svg{animation:dbu-spin .9s linear infinite}
505
+ @keyframes dbu-spin{to{transform:rotate(360deg)}}
506
+ @media (prefers-reduced-motion: reduce){.dbu-iconbtn[data-busy="true"] svg{animation:none}}
507
+ .dbu-body{display:flex;flex-direction:column;gap:10px;padding:2px 14px 14px;overflow-y:auto;scrollbar-width:thin}
508
+ .dbu-card{border-radius:10px;background:var(--dsw-alias-bg-layer-1);padding:10px 12px}
509
+ .dbu-card__label{display:flex;align-items:center;gap:6px;font-size:11px;color:var(--dsw-alias-label-primary);opacity:.8;margin-bottom:4px}
510
+ .dbu-money{font-size:22px;font-weight:650;letter-spacing:-.01em;font-variant-numeric:tabular-nums;line-height:1.2}
511
+ .dbu-chip{font-size:11px;padding:1px 7px;border-radius:999px;background:var(--dsw-alias-bg-skeleton);color:var(--dsw-alias-label-primary);white-space:nowrap;max-width:100%;overflow:hidden;text-overflow:ellipsis}
512
+ .dbu-chip--main{background:var(--dsw-alias-brand-primary);color:var(--dsw-alias-bg-base)}
513
+ .dbu-muted{font-size:11px;color:var(--dsw-alias-label-primary);opacity:.88}
514
+ .dbu-big{font-size:18px;font-weight:600;font-variant-numeric:tabular-nums;line-height:1.25}
515
+ .dbu-big--sub{font-size:15px;font-weight:500;color:var(--dsw-alias-label-primary);opacity:.85}
516
+ .dbu-row{display:flex;align-items:baseline;gap:8px}
517
+ .dbu-row--between{display:flex;align-items:baseline;justify-content:space-between;gap:8px}
518
+ .dbu-stats{display:grid;grid-template-columns:repeat(3,1fr);gap:6px;margin-top:8px}
519
+ .dbu-stat{font-size:10px;color:var(--dsw-alias-label-primary);opacity:.8}
520
+ .dbu-stat b{display:block;font-size:12px;font-weight:600;color:var(--dsw-alias-label-primary);font-variant-numeric:tabular-nums}
521
+ .dbu-chart{display:flex;align-items:flex-end;gap:3px;height:32px;margin-top:10px}
522
+ .dbu-chart i{flex:1;border-radius:2px 2px 0 0;background:var(--dsw-alias-chart-messages);opacity:.55}
523
+ .dbu-chart i[data-empty="true"]{height:2px!important;background:var(--dsw-alias-bg-skeleton);opacity:1;border-radius:1px}
524
+ .dbu-chart i[data-today="true"]{opacity:1}
525
+ .dbu-section{display:flex;flex-direction:column;gap:2px}
526
+ .dbu-section__head{display:flex;align-items:center;gap:6px;font-size:11px;color:var(--dsw-alias-label-primary);opacity:.8;padding:0 2px 2px}
527
+ .dbu-section__hint{font-size:10.5px;color:var(--dsw-alias-label-primary);opacity:.6}
528
+ .dbu-group__row{display:flex;align-items:center;gap:6px;width:100%;box-sizing:border-box;padding:5px 6px;border:0;border-radius:6px;background:transparent;color:inherit;font:inherit;text-align:left;cursor:pointer}
529
+ .dbu-group__row:hover{background:var(--dsw-alias-bg-skeleton)}
530
+ .dbu-group__name{font-size:12px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
531
+ .dbu-group__val{margin-left:auto;font-size:11px;color:var(--dsw-alias-label-primary);opacity:.8;font-variant-numeric:tabular-nums;white-space:nowrap}
532
+ .dbu-chevron{flex:none;display:inline-flex;color:var(--dsw-alias-label-primary);opacity:.6;transition:transform .12s ease}
533
+ .dbu-chevron[data-open="true"]{transform:rotate(90deg)}
534
+ .dbu-models{display:flex;flex-direction:column;padding-left:12px}
535
+ .dbu-model{display:flex;align-items:center;gap:6px;width:100%;box-sizing:border-box;padding:5px 6px;border-radius:6px;color:inherit;font:inherit;text-align:left;cursor:default}
536
+ .dbu-model[data-main="true"]{box-shadow:inset 2px 0 0 0 var(--dsw-alias-chart-messages)}
537
+ .dbu-model__name{font-size:11px;color:var(--dsw-alias-label-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
538
+ .dbu-model[data-main="true"] .dbu-model__name{font-weight:600}
539
+ .dbu-model__val{margin-left:auto;font-size:11px;color:var(--dsw-alias-label-primary);opacity:.75;font-variant-numeric:tabular-nums;white-space:nowrap}
540
+ .dbu-star{flex:none;display:inline-flex;align-items:center;justify-content:center;width:24px;height:24px;padding:0;border:0;border-radius:6px;background:transparent;color:var(--dsw-alias-label-tertiary);cursor:pointer}
541
+ .dbu-star:hover{background:var(--dsw-alias-bg-skeleton);color:var(--dsw-alias-label-secondary)}
542
+ .dbu-star[data-active="true"]{color:var(--dsw-alias-state-warn-label)}
543
+ .dbu-cta{display:flex;align-items:center;justify-content:center;gap:6px;width:100%;box-sizing:border-box;padding:8px;border-radius:8px;border:1px solid var(--dsw-alias-border-l2);background:transparent;color:var(--dsw-alias-label-primary);font-size:12px;font-family:inherit;cursor:pointer;text-decoration:none}
544
+ .dbu-cta:hover{border-color:var(--dsw-alias-brand-primary);color:var(--dsw-alias-brand-primary)}
545
+ .dbu-note{font-size:11px;color:var(--dsw-alias-label-primary);opacity:.8;padding:2px}
546
+ .dbu-danger{display:flex;align-items:flex-start;gap:6px;font-size:11.5px;font-weight:500;line-height:1.5;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-skeleton);border-left:2px solid var(--dsw-alias-state-error-primary);border-radius:4px;padding:5px 7px}
547
+ .dbu-danger b{color:var(--dsw-alias-state-error-primary);font-weight:600;flex:none}
548
+ .dbu-retry{flex:none;margin-left:auto;padding:1px 7px;border:1px solid var(--dsw-alias-border-l2);border-radius:6px;background:transparent;color:var(--dsw-alias-label-primary);font:inherit;font-size:11px;cursor:pointer}
549
+ .dbu-retry:hover{border-color:var(--dsw-alias-brand-primary)}
550
+ .dbu-skel{border-radius:6px;background:var(--dsw-alias-bg-skeleton);animation:dbu-pulse 1.4s ease-in-out infinite}
551
+ .dbu-skel--line{height:18px}
552
+ .dbu-skel--line-lg{height:26px}
553
+ @keyframes dbu-pulse{0%,100%{opacity:.6}50%{opacity:1}}
554
+ @media (prefers-reduced-motion: reduce){.dbu-skel{animation:none}}
555
+ .dbu-sr{position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0}
556
+ .dbu-entry:focus-visible,.dbu-iconbtn:focus-visible,.dbu-group__row:focus-visible,.dbu-star:focus-visible,.dbu-cta:focus-visible,.dbu-retry:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:1px}
557
+ `
558
+
559
+ function installStyles() {
560
+ const existing = document.getElementById('dsh-balance-usage-style')
561
+ if (existing) return () => {}
562
+ const style = document.createElement('style')
563
+ style.id = 'dsh-balance-usage-style'
564
+ style.textContent = CSS
565
+ document.head.appendChild(style)
566
+ return () => style.remove()
567
+ }
568
+
569
+ /* ---------------------------------------------------------------- *
570
+ * Icons
571
+ * ---------------------------------------------------------------- */
572
+
573
+ function Svg({ size = 16, children, ...rest }) {
574
+ return h(
575
+ 'svg',
576
+ {
577
+ width: size,
578
+ height: size,
579
+ viewBox: '0 0 24 24',
580
+ fill: 'none',
581
+ stroke: 'currentColor',
582
+ strokeWidth: 1.7,
583
+ strokeLinecap: 'round',
584
+ strokeLinejoin: 'round',
585
+ 'aria-hidden': true,
586
+ focusable: false,
587
+ ...rest,
588
+ },
589
+ children,
590
+ )
591
+ }
592
+
593
+ function WalletIcon({ size = 16 }) {
594
+ return h(
595
+ Svg,
596
+ { size },
597
+ h('path', { d: 'M3.5 8.2A2.7 2.7 0 0 1 6.2 5.5h11.3a3 3 0 0 1 3 3v7.2a2.8 2.8 0 0 1-2.8 2.8H6.3a2.8 2.8 0 0 1-2.8-2.8z' }),
598
+ h('path', { d: 'M3.5 9.4h14.6' }),
599
+ h('circle', { cx: 17.1, cy: 14.1, r: 1.15, fill: 'currentColor', stroke: 'none' }),
600
+ )
601
+ }
602
+
603
+ function RefreshIcon() {
604
+ return h(Svg, { size: 14 }, h('path', { d: 'M20 11.5a8 8 0 1 0-2.3 5.7' }), h('path', { d: 'M20 5.5v6h-6' }))
605
+ }
606
+
607
+ function CloseIcon() {
608
+ return h(Svg, { size: 14 }, h('path', { d: 'M6 6l12 12M18 6L6 18' }))
609
+ }
610
+
611
+ function ChevronIcon({ open }) {
612
+ return h(Svg, { size: 12, className: 'dbu-chevron', 'data-open': open ? 'true' : 'false', style: { transform: open ? 'rotate(90deg)' : 'none' } }, h('path', { d: 'M9 6l6 6-6 6' }))
613
+ }
614
+
615
+ function ExternalIcon() {
616
+ return h(Svg, { size: 13 }, h('path', { d: 'M14 4h6v6' }), h('path', { d: 'M20 4l-8.5 8.5' }), h('path', { d: 'M18.5 14v4.5a2 2 0 0 1-2 2H5.5a2 2 0 0 1-2-2V7.5a2 2 0 0 1 2-2H10' }))
617
+ }
618
+
619
+ function StarIcon({ filled }) {
620
+ return h(
621
+ Svg,
622
+ { size: 12, fill: filled ? 'currentColor' : 'none' },
623
+ h('path', { d: 'M12 4.2l2.4 4.9 5.4.8-3.9 3.8.9 5.4-4.8-2.5-4.8 2.5.9-5.4L4.2 9.9l5.4-.8z' }),
624
+ )
625
+ }
626
+
627
+ /* ---------------------------------------------------------------- *
628
+ * Sidebar footer entry
629
+ * ---------------------------------------------------------------- */
630
+
631
+ function FooterAction(props) {
632
+ const snapshot = useSnapshot()
633
+ const t = copy()
634
+ const wide = props?.wide !== false
635
+ const usage = snapshot.usage
636
+ const account = snapshot.account
637
+ const wallet = mainWallet(account?.wallets)
638
+ const todayTokens = usage?.today?.tokens || 0
639
+
640
+ const money = wallet ? fmtWallet(wallet) : account?.signedIn === false ? t.signedOutShort : '—'
641
+ const meta = usage ? `${t.today} ${fmtTokens(todayTokens)}` : snapshot.status === 'loading' ? t.loading : snapshot.status === 'error' ? t.failed : '—'
642
+ const dotState = snapshot.status === 'error' ? 'error' : 'ok'
643
+
644
+ const title = [t.entryTitle, wallet ? `${t.balance} ${fmtWallet(wallet)}` : null, usage ? `${t.total} ${fmtTokens(usage.totals?.tokens || 0)} tok` : null]
645
+ .filter(Boolean)
646
+ .join('\n')
647
+
648
+ function onClick(event) {
649
+ const rect = event.currentTarget.getBoundingClientRect()
650
+ /* The entry is content-sized, so hang the panel off the sidebar column it sits in.
651
+ Only ancestors that still look like a sidebar count: a full-width shell row
652
+ would push the panel off-screen. */
653
+ let columnRight = rect.right
654
+ let node = event.currentTarget.parentElement
655
+ for (let depth = 0; node && depth < 8; depth += 1) {
656
+ const bounds = node.getBoundingClientRect()
657
+ if (bounds.width > 520) break
658
+ if (bounds.right > columnRight + 16) {
659
+ columnRight = bounds.right
660
+ break
661
+ }
662
+ node = node.parentElement
663
+ }
664
+ const next = !state.open
665
+ setState({
666
+ open: next,
667
+ wide,
668
+ entryEl: next ? event.currentTarget : state.entryEl,
669
+ anchor: next ? { left: rect.left, right: columnRight, top: rect.top, bottom: rect.bottom, width: rect.width } : state.anchor,
670
+ })
671
+ if (next) load(clientCtx, { force: Date.now() - state.updatedAt > STALE_MS })
672
+ }
673
+
674
+ return h(
675
+ 'button',
676
+ {
677
+ type: 'button',
678
+ className: 'dbu-entry',
679
+ 'data-wide': wide ? 'true' : 'false',
680
+ title,
681
+ 'aria-label': `${t.entry} ${money} ${meta}`,
682
+ 'aria-haspopup': 'dialog',
683
+ 'aria-controls': PANEL_ID,
684
+ 'aria-expanded': snapshot.open ? 'true' : 'false',
685
+ onClick,
686
+ },
687
+ h('span', { className: 'dbu-entry__icon' }, h(WalletIcon, { size: wide ? 16 : 18 })),
688
+ wide
689
+ ? h(
690
+ 'span',
691
+ { className: 'dbu-entry__body' },
692
+ h('span', { className: 'dbu-entry__money' }, money),
693
+ h('span', { className: 'dbu-entry__meta' }, meta),
694
+ )
695
+ : todayTokens > 0
696
+ ? h('span', { className: 'dbu-entry__dot', 'data-state': dotState })
697
+ : null,
698
+ )
699
+ }
700
+
701
+ /* ---------------------------------------------------------------- *
702
+ * Panel
703
+ * ---------------------------------------------------------------- */
704
+
705
+ function Stat({ label, value }) {
706
+ return h('div', { className: 'dbu-stat' }, h('b', null, value), label)
707
+ }
708
+
709
+ function MiniChart({ series, label }) {
710
+ if (!Array.isArray(series) || series.length === 0) return null
711
+ const max = Math.max(...series.map((point) => point.tokens || 0), 1)
712
+ const last = series.length - 1
713
+ return h(
714
+ 'div',
715
+ { className: 'dbu-chart', role: 'img', 'aria-label': label || undefined },
716
+ series.map((point, index) => {
717
+ const tokens = point.tokens || 0
718
+ // Square-root scaling keeps small days visible next to a heavy today bar;
719
+ // empty days keep a 2px track so the band reads as a day axis, not a rule.
720
+ const height = tokens === 0 ? 0 : Math.max(4, Math.round(Math.sqrt(tokens / max) * 28))
721
+ return h('i', {
722
+ key: point.date,
723
+ 'data-today': index === last ? 'true' : 'false',
724
+ 'data-empty': tokens === 0 ? 'true' : 'false',
725
+ style: { height: `${height}px` },
726
+ title: `${point.date} · ${fmtTokens(tokens)}`,
727
+ })
728
+ }),
729
+ )
730
+ }
731
+
732
+ function GroupRow({ group, collapsed, onToggle, main, primary, onStar, condensed }) {
733
+ const regionId = `dbu-models-${group.provider}`
734
+ /* With a single provider/model the totals would just repeat the headline number,
735
+ so the row keeps only the name and the pin control. */
736
+ const showTotals = condensed !== true
737
+ return h(
738
+ 'div',
739
+ null,
740
+ h(
741
+ 'button',
742
+ {
743
+ type: 'button',
744
+ className: 'dbu-group__row',
745
+ 'aria-expanded': collapsed ? 'false' : 'true',
746
+ 'aria-controls': regionId,
747
+ onClick: onToggle,
748
+ },
749
+ h(ChevronIcon, { open: !collapsed }),
750
+ h('span', { className: 'dbu-group__name' }, providerLabel(group.provider)),
751
+ showTotals ? h('span', { className: 'dbu-group__val' }, fmtTokens(group.tokens)) : null,
752
+ ),
753
+ collapsed
754
+ ? null
755
+ : h(
756
+ 'div',
757
+ { className: 'dbu-models', id: regionId },
758
+ (group.models || []).map((model) => {
759
+ const isMain = Boolean(main && main.model === model.model && main.provider === group.provider)
760
+ /* The star is an explicit choice: auto resolution keeps it hollow so the
761
+ click still reads as "make this the main line". */
762
+ const pinned = Boolean(primary && primary.model === model.model && primary.provider === group.provider)
763
+ const starLabel = pinned ? copy().clearPrimary : copy().setPrimary
764
+ return h(
765
+ 'div',
766
+ { key: model.model, className: 'dbu-model', 'data-main': isMain ? 'true' : 'false' },
767
+ h('span', { className: 'dbu-model__name', title: `${model.model} · ${fmtTokens(model.tokens)}` }, model.model),
768
+ showTotals
769
+ ? h('span', { className: 'dbu-model__val' }, `${fmtTokens(model.tokens)} · ${fmtRelative(model.lastUsed)}`)
770
+ : null,
771
+ h(
772
+ 'button',
773
+ {
774
+ type: 'button',
775
+ className: 'dbu-star',
776
+ 'data-active': pinned ? 'true' : 'false',
777
+ 'aria-pressed': pinned ? 'true' : 'false',
778
+ 'aria-label': starLabel,
779
+ title: starLabel,
780
+ onClick: (event) => {
781
+ event.stopPropagation()
782
+ onStar(group.provider, model.model)
783
+ },
784
+ },
785
+ h(StarIcon, { filled: pinned }),
786
+ ),
787
+ )
788
+ }),
789
+ ),
790
+ )
791
+ }
792
+
793
+ function panelFocusables(node) {
794
+ if (!node) return []
795
+ return [...node.querySelectorAll('button:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])')].filter(
796
+ (element) => element.offsetParent !== null || element.getClientRects().length > 0,
797
+ )
798
+ }
799
+
800
+ function Panel() {
801
+ const snapshot = useSnapshot()
802
+ const t = copy()
803
+ const [, forceViewport] = useState(0)
804
+
805
+ useEffect(() => {
806
+ if (!snapshot.open) {
807
+ /* Returning focus keeps the keyboard loop closed when the popover closes. */
808
+ const entry = state.entryEl
809
+ if (entry && typeof entry.focus === 'function') entry.focus()
810
+ return undefined
811
+ }
812
+ const panel = () => document.getElementById(PANEL_ID)
813
+ const onKey = (event) => {
814
+ if (event.defaultPrevented) return
815
+ if (event.key === 'Escape') {
816
+ setState({ open: false })
817
+ return
818
+ }
819
+ if (event.key !== 'Tab') return
820
+ const items = panelFocusables(panel())
821
+ if (items.length === 0) return
822
+ const first = items[0]
823
+ const last = items[items.length - 1]
824
+ const active = document.activeElement
825
+ if (event.shiftKey && (active === first || active === panel())) {
826
+ event.preventDefault()
827
+ last.focus()
828
+ } else if (!event.shiftKey && active === last) {
829
+ event.preventDefault()
830
+ first.focus()
831
+ }
832
+ }
833
+ const onResize = () => forceViewport((value) => value + 1)
834
+ window.addEventListener('keydown', onKey)
835
+ window.addEventListener('resize', onResize)
836
+ load(clientCtx)
837
+ /* Move focus into the popover so Escape and Tab act on it, not on the page behind. */
838
+ const focusTimer = window.setTimeout(() => {
839
+ const node = panel()
840
+ if (node) {
841
+ node.focus()
842
+ if (document.activeElement !== node) panelFocusables(node)[0]?.focus()
843
+ }
844
+ }, 0)
845
+ return () => {
846
+ window.removeEventListener('keydown', onKey)
847
+ window.removeEventListener('resize', onResize)
848
+ window.clearTimeout(focusTimer)
849
+ }
850
+ }, [snapshot.open])
851
+
852
+ if (!snapshot.open) return snapshot.platform ? h(PlatformSurface, { page: snapshot.platform }) : null
853
+
854
+ const account = snapshot.account
855
+ const usage = snapshot.usage
856
+ const main = resolveMain(usage, snapshot.primary)
857
+ const wallet = mainWallet(account?.wallets)
858
+ const bonus = bonusTotal(account?.bonusWallets)
859
+ const totals = usage?.totals
860
+ const today = usage?.today
861
+
862
+ const anchor = snapshot.anchor
863
+ const viewportWidth = window.innerWidth || 1280
864
+ const viewportHeight = window.innerHeight || 800
865
+ const compact = viewportWidth < 760
866
+ const width = compact ? Math.max(240, viewportWidth - 16) : Math.min(336, viewportWidth - 24)
867
+ /* Wide sidebar: hang the panel off the entry's right edge so the session list
868
+ stays readable. Narrow rail: the same rule clears the 56px rail. Falls back
869
+ to covering the entry when neither side has room. */
870
+ const gutters = 8
871
+ const beside = anchor ? anchor.right + gutters : gutters
872
+ const above = anchor ? Math.max(gutters, viewportHeight - anchor.top + gutters) : 72
873
+ const besideFits = beside + width + gutters <= viewportWidth
874
+ const left = compact ? 8 : besideFits ? beside : Math.max(gutters, Math.min(anchor ? anchor.left : 12, viewportWidth - width - gutters))
875
+ const bottom = compact ? gutters : above
876
+ const maxHeight = Math.max(200, Math.min(viewportHeight * (compact ? 0.62 : 0.68), viewportHeight - bottom - 12))
877
+
878
+ function toggleGroup(provider) {
879
+ const collapsed = state.collapsed.includes(provider)
880
+ ? state.collapsed.filter((item) => item !== provider)
881
+ : [...state.collapsed, provider]
882
+ writeCollapsed(collapsed)
883
+ setState({ collapsed })
884
+ }
885
+
886
+ function onStar(provider, model) {
887
+ const active = state.primary && state.primary.provider === provider && state.primary.model === model
888
+ const next = active ? null : { provider, model }
889
+ writePrimary(next)
890
+ setState({ primary: next })
891
+ }
892
+
893
+ const loadingFirst = !usage && (snapshot.status === 'loading' || snapshot.status === 'idle')
894
+
895
+ function retryButton() {
896
+ return h('button', {
897
+ type: 'button',
898
+ className: 'dbu-retry',
899
+ onClick: () => load(clientCtx, { force: true }),
900
+ }, t.retry)
901
+ }
902
+
903
+ const statusNote = () => {
904
+ if (!snapshot.usageError) return null
905
+ const routeMissing = /HTTP 404|HTTP 405|Failed to fetch|NetworkError/i.test(snapshot.usageError)
906
+ return h(
907
+ 'div',
908
+ { className: 'dbu-danger', role: 'status' },
909
+ h('b', null, routeMissing ? t.noUsageRoute : t.failed),
910
+ h('span', { style: { minWidth: 0, wordBreak: 'break-word' } }, snapshot.usageError),
911
+ retryButton(),
912
+ )
913
+ }
914
+
915
+ const accountErrorBlock = () =>
916
+ snapshot.accountError
917
+ ? h(
918
+ 'div',
919
+ { className: 'dbu-danger', style: { marginTop: '6px' }, role: 'status' },
920
+ h('b', null, t.failed),
921
+ h('span', { style: { minWidth: 0, wordBreak: 'break-word' } }, snapshot.accountError),
922
+ retryButton(),
923
+ )
924
+ : null
925
+
926
+ const cacheShare = totals && totals.tokens ? Math.round(((totals.cacheReadTokens || 0) / totals.tokens) * 100) : 0
927
+ const chartsLabel = `${t.last14}: ${t.today} ${fmtTokens(today?.tokens || 0)} · ${t.total} ${fmtTokens(totals?.tokens || 0)}`
928
+
929
+ return h(
930
+ React.Fragment,
931
+ null,
932
+ h('div', { className: 'dbu-scrim', onPointerDown: () => setState({ open: false }) }),
933
+ h(
934
+ 'section',
935
+ {
936
+ id: PANEL_ID,
937
+ className: 'dbu-panel',
938
+ role: 'dialog',
939
+ tabIndex: -1,
940
+ 'aria-modal': 'true',
941
+ 'aria-labelledby': PANEL_TITLE_ID,
942
+ style: { left: `${left}px`, bottom: `${bottom}px`, width: `${width}px`, maxHeight: `${maxHeight}px` },
943
+ },
944
+ h(
945
+ 'header',
946
+ { className: 'dbu-head' },
947
+ h('h2', { className: 'dbu-head__title', id: PANEL_TITLE_ID }, t.title),
948
+ h(
949
+ 'span',
950
+ { className: 'dbu-head__time' },
951
+ snapshot.updatedAt ? `${t.updated} ${fmtClock(snapshot.updatedAt)}` : '',
952
+ snapshot.updatedAt && (snapshot.usageError || snapshot.accountError) ? t.stale : '',
953
+ ),
954
+ h(
955
+ 'button',
956
+ {
957
+ type: 'button',
958
+ className: 'dbu-iconbtn',
959
+ title: t.refresh,
960
+ 'aria-label': t.refresh,
961
+ 'aria-busy': snapshot.status === 'loading' ? 'true' : 'false',
962
+ 'data-busy': snapshot.status === 'loading' ? 'true' : 'false',
963
+ onClick: () => load(clientCtx, { force: true }),
964
+ },
965
+ h(RefreshIcon),
966
+ ),
967
+ h(
968
+ 'button',
969
+ { type: 'button', className: 'dbu-iconbtn', title: t.close, 'aria-label': t.close, onClick: () => setState({ open: false }) },
970
+ h(CloseIcon),
971
+ ),
972
+ ),
973
+ h(
974
+ 'div',
975
+ { className: 'dbu-body' },
976
+ h(
977
+ 'div',
978
+ { className: 'dbu-card' },
979
+ h('div', { className: 'dbu-card__label' }, t.balance),
980
+ account?.signedIn === false
981
+ ? h('div', { className: 'dbu-muted', style: { lineHeight: 1.45 } }, t.signedOut)
982
+ : loadingFirst
983
+ ? h('div', { className: 'dbu-skel dbu-skel--line-lg', style: { width: '52%' } })
984
+ : h(
985
+ React.Fragment,
986
+ null,
987
+ h('div', { className: 'dbu-money' }, wallet ? fmtWallet(wallet) : '—'),
988
+ bonus && bonus.total > 0
989
+ ? h(
990
+ 'div',
991
+ { className: 'dbu-row', style: { marginTop: '4px' } },
992
+ h('span', { className: 'dbu-muted' }, t.bonus),
993
+ h('span', { className: 'dbu-muted', style: { marginLeft: 'auto' } }, fmtWallet({ currency: bonus.currency, balance: String(bonus.total) })),
994
+ )
995
+ : null,
996
+ accountErrorBlock(),
997
+ ),
998
+ ),
999
+ h(
1000
+ 'div',
1001
+ { className: 'dbu-card' },
1002
+ h(
1003
+ 'div',
1004
+ { className: 'dbu-card__label' },
1005
+ t.usage,
1006
+ main
1007
+ ? h('span', { className: 'dbu-chip', title: `${providerLabel(main.row.provider)} · ${main.row.model}` }, `${providerLabel(main.row.provider)} · ${main.row.model}`)
1008
+ : h('span', { className: 'dbu-chip' }, t.auto),
1009
+ ),
1010
+ loadingFirst
1011
+ ? h(
1012
+ React.Fragment,
1013
+ null,
1014
+ h('div', { className: 'dbu-skel dbu-skel--line-lg', style: { width: '38%' } }),
1015
+ h('div', { className: 'dbu-skel dbu-skel--line', style: { marginTop: '10px', width: '100%' } }),
1016
+ h('div', { className: 'dbu-skel dbu-skel--line', style: { marginTop: '6px', width: '100%', height: '32px' } }),
1017
+ )
1018
+ : usage
1019
+ ? h(
1020
+ React.Fragment,
1021
+ null,
1022
+ h(
1023
+ 'div',
1024
+ { className: 'dbu-row--between' },
1025
+ h('div', null, h('div', { className: 'dbu-big' }, fmtTokens(today?.tokens || 0)), h('div', { className: 'dbu-muted' }, t.today)),
1026
+ h(
1027
+ 'div',
1028
+ { style: { textAlign: 'right' } },
1029
+ h('div', { className: 'dbu-big--sub' }, fmtTokens(totals?.tokens || 0)),
1030
+ h('div', { className: 'dbu-muted' }, t.total),
1031
+ ),
1032
+ ),
1033
+ h(
1034
+ 'div',
1035
+ { className: 'dbu-stats' },
1036
+ h(Stat, { label: t.input, value: fmtTokens(totals?.inputTokens || 0) }),
1037
+ h(Stat, { label: t.output, value: fmtTokens(totals?.outputTokens || 0) }),
1038
+ h(Stat, { label: cacheShare ? `${t.cache} ${cacheShare}%` : t.cache, value: fmtTokens(totals?.cacheReadTokens || 0) }),
1039
+ ),
1040
+ h(MiniChart, { series: usage.series, label: chartsLabel }),
1041
+ h(
1042
+ 'div',
1043
+ { className: 'dbu-muted', style: { marginTop: '4px' } },
1044
+ `${t.last14} · ${(totals?.requests || 0).toLocaleString()} ${t.requestsSuffix}`,
1045
+ ),
1046
+ )
1047
+ : h('div', { className: 'dbu-note' }, t.empty),
1048
+ ),
1049
+ statusNote(),
1050
+ usage && usage.groups && usage.groups.length > 0
1051
+ ? h(
1052
+ 'div',
1053
+ { className: 'dbu-section' },
1054
+ h(
1055
+ 'div',
1056
+ { className: 'dbu-section__head' },
1057
+ t.groups,
1058
+ h('span', { className: 'dbu-section__hint' }, t.starHint),
1059
+ ),
1060
+ usage.groups.map((group) =>
1061
+ h(GroupRow, {
1062
+ key: group.provider,
1063
+ group,
1064
+ main: main?.row,
1065
+ primary: snapshot.primary,
1066
+ condensed: usage.groups.length === 1 && (group.models || []).length === 1,
1067
+ collapsed: snapshot.collapsed.includes(group.provider),
1068
+ onToggle: () => toggleGroup(group.provider),
1069
+ onStar,
1070
+ }),
1071
+ ),
1072
+ )
1073
+ : null,
1074
+ platformBridge()
1075
+ ? h(
1076
+ 'button',
1077
+ {
1078
+ type: 'button',
1079
+ className: 'dbu-cta',
1080
+ title: t.openUsage,
1081
+ onClick: () => setState({ open: false, platform: 'usage' }),
1082
+ },
1083
+ h(ExternalIcon),
1084
+ t.openUsage,
1085
+ )
1086
+ : h(
1087
+ 'a',
1088
+ {
1089
+ className: 'dbu-cta',
1090
+ href: account?.usageUrl || FALLBACK_USAGE_URL,
1091
+ target: '_blank',
1092
+ rel: 'noopener noreferrer',
1093
+ title: `${t.openUsage} · ${account?.usageUrl || FALLBACK_USAGE_URL}`,
1094
+ },
1095
+ h(ExternalIcon),
1096
+ t.openUsage,
1097
+ h('span', { className: 'dbu-sr' }, ` (${t.newWindow})`),
1098
+ ),
1099
+ ),
1100
+ ),
1101
+ snapshot.platform ? h(PlatformSurface, { page: snapshot.platform }) : null,
1102
+ )
1103
+ }
1104
+
1105
+ /* ---------------------------------------------------------------- *
1106
+ * Native Platform page (Desktop only)
1107
+ * ---------------------------------------------------------------- */
1108
+
1109
+ /* The Desktop shell owns one WebContentsView that renders the official Platform
1110
+ document above the page, with the account session injected by the main process.
1111
+ The view takes the main content area beside the sidebar — the strip on top is
1112
+ dressed as a page tab, so the sidebar and the rest of the shell stay usable. */
1113
+ function contentAreaRect() {
1114
+ const entry = state.entryEl
1115
+ let left = 0
1116
+ if (entry) {
1117
+ left = entry.getBoundingClientRect().right
1118
+ /* Walk out to the sidebar column, but stop before the column that spans the
1119
+ whole window (that is the app shell, not the sidebar). */
1120
+ let node = entry.parentElement
1121
+ for (let depth = 0; node && depth < 8; depth += 1) {
1122
+ const bounds = node.getBoundingClientRect()
1123
+ if (bounds.width > 480) break
1124
+ if (bounds.right > left) left = bounds.right
1125
+ node = node.parentElement
1126
+ }
1127
+ }
1128
+ const viewport = window.innerWidth || 1280
1129
+ return { left, width: Math.max(320, viewport - left) }
1130
+ }
1131
+
1132
+ function PlatformSurface({ page }) {
1133
+ const t = copy()
1134
+ const hostRef = useRef(null)
1135
+ const [status, setStatus] = useState('loading')
1136
+ const [attempt, setAttempt] = useState(0)
1137
+ const [area, setArea] = useState(contentAreaRect)
1138
+ const bridge = platformBridge()
1139
+ const usageUrl = state.account?.usageUrl || FALLBACK_USAGE_URL
1140
+
1141
+ function closePlatform() {
1142
+ setState({ platform: null, open: true })
1143
+ load(clientCtx, { force: true })
1144
+ }
1145
+
1146
+ /* Keep clearing the sidebar when the window is resized or the sidebar toggles. */
1147
+ useEffect(() => {
1148
+ const onResize = () => setArea(contentAreaRect())
1149
+ window.addEventListener('resize', onResize)
1150
+ return () => window.removeEventListener('resize', onResize)
1151
+ }, [])
1152
+
1153
+ useEffect(() => {
1154
+ const node = hostRef.current
1155
+ if (!node || !bridge) return undefined
1156
+ let closed = false
1157
+ const bounds = () => {
1158
+ const rect = node.getBoundingClientRect()
1159
+ return { x: rect.x, y: rect.y, width: rect.width, height: rect.height }
1160
+ }
1161
+ const fail = () => {
1162
+ if (!closed) setStatus('failed')
1163
+ }
1164
+ setStatus('loading')
1165
+ Promise.resolve()
1166
+ .then(() => bridge.open(page, bounds()))
1167
+ .then(() => {
1168
+ if (!closed) setStatus('loaded')
1169
+ })
1170
+ .catch(fail)
1171
+ const observer = typeof ResizeObserver === 'function'
1172
+ ? new ResizeObserver(() => {
1173
+ Promise.resolve(bridge.setBounds(bounds())).catch(fail)
1174
+ })
1175
+ : null
1176
+ observer?.observe(node)
1177
+ return () => {
1178
+ closed = true
1179
+ observer?.disconnect()
1180
+ /* The window teardown may drop the IPC receiver before React unmounts. */
1181
+ Promise.resolve(bridge.close()).catch(() => {})
1182
+ }
1183
+ }, [bridge, page, attempt])
1184
+
1185
+ useEffect(() => {
1186
+ const onKey = (event) => {
1187
+ if (event.defaultPrevented || event.key !== 'Escape') return
1188
+ event.preventDefault()
1189
+ closePlatform()
1190
+ }
1191
+ window.addEventListener('keydown', onKey)
1192
+ const focusTimer = window.setTimeout(() => {
1193
+ const close = document.getElementById(PLATFORM_BACK_ID)
1194
+ if (close) close.focus()
1195
+ }, 0)
1196
+ return () => {
1197
+ window.removeEventListener('keydown', onKey)
1198
+ window.clearTimeout(focusTimer)
1199
+ }
1200
+ // eslint-disable-next-line react-hooks/exhaustive-deps
1201
+ }, [])
1202
+
1203
+ /* Clicking anywhere else in the shell hands the page back to the app. */
1204
+ useEffect(() => {
1205
+ const onPointer = (event) => {
1206
+ const surface = document.querySelector('.dbu-platform')
1207
+ if (!surface || surface.contains(event.target)) return
1208
+ closePlatform()
1209
+ }
1210
+ window.addEventListener('pointerdown', onPointer, true)
1211
+ return () => window.removeEventListener('pointerdown', onPointer, true)
1212
+ // eslint-disable-next-line react-hooks/exhaustive-deps
1213
+ }, [])
1214
+
1215
+ return h(
1216
+ 'div',
1217
+ {
1218
+ className: 'dbu-platform',
1219
+ style: { left: `${area.left}px`, width: `${area.width}px` },
1220
+ role: 'region',
1221
+ 'aria-label': t.usagePage,
1222
+ },
1223
+ h(
1224
+ 'div',
1225
+ { className: 'dbu-platform__bar' },
1226
+ h(
1227
+ 'div',
1228
+ { className: 'dbu-platform__tab' },
1229
+ h('span', { className: 'dbu-platform__tabdot', 'aria-hidden': 'true' }),
1230
+ h('span', { className: 'dbu-platform__tablabel' }, t.usagePage),
1231
+ h(
1232
+ 'button',
1233
+ {
1234
+ id: PLATFORM_BACK_ID,
1235
+ type: 'button',
1236
+ className: 'dbu-platform__close',
1237
+ title: t.close,
1238
+ 'aria-label': t.close,
1239
+ onClick: closePlatform,
1240
+ },
1241
+ h(CloseIcon),
1242
+ ),
1243
+ ),
1244
+ ),
1245
+ h(
1246
+ 'div',
1247
+ { ref: hostRef, className: 'dbu-platform__viewport' },
1248
+ status === 'loaded'
1249
+ ? null
1250
+ : h(
1251
+ 'div',
1252
+ { className: 'dbu-platform__status', role: 'status' },
1253
+ status === 'failed'
1254
+ ? h(
1255
+ React.Fragment,
1256
+ null,
1257
+ h('span', { className: 'dbu-platform__fail' }, t.platformFailed),
1258
+ h(
1259
+ 'div',
1260
+ { className: 'dbu-platform__actions' },
1261
+ h(
1262
+ 'button',
1263
+ { type: 'button', className: 'dbu-retry', onClick: () => setAttempt((value) => value + 1) },
1264
+ t.retry,
1265
+ ),
1266
+ h(
1267
+ 'a',
1268
+ { className: 'dbu-retry', href: usageUrl, target: '_blank', rel: 'noopener noreferrer' },
1269
+ t.browser,
1270
+ ),
1271
+ ),
1272
+ )
1273
+ : h(
1274
+ React.Fragment,
1275
+ null,
1276
+ h('span', { className: 'dbu-platform__spinner', 'aria-hidden': 'true' }),
1277
+ h('span', null, t.platformLoading),
1278
+ ),
1279
+ ),
1280
+ ),
1281
+ )
1282
+ }
1283
+
1284
+ /* ---------------------------------------------------------------- *
1285
+ * Plugin
1286
+ * ---------------------------------------------------------------- */
1287
+
1288
+ return {
1289
+ inject: ['slots', 'locale', 'remote', 'remote.account'],
1290
+
1291
+ apply(ctx) {
1292
+ clientCtx = ctx
1293
+
1294
+ ctx.effect(installStyles)
1295
+
1296
+ /* Repaint copy when the reader switches the UI language. */
1297
+ ctx.effect(() => {
1298
+ if (typeof ctx.on !== 'function') return () => {}
1299
+ const dispose = ctx.on('locale/change', () => setState({}))
1300
+ return () => dispose()
1301
+ })
1302
+
1303
+ ctx.slots.inject('sidebar.footer.action', () =>
1304
+ ctx.slots.register(
1305
+ {
1306
+ name: 'sidebar.footer.action',
1307
+ id: 'balance-usage',
1308
+ order: 40,
1309
+ label: () => copy().entryTitle,
1310
+ },
1311
+ FooterAction,
1312
+ ),
1313
+ )
1314
+
1315
+ ctx.slots.inject('shell.overlay', () =>
1316
+ ctx.slots.register({ name: 'shell.overlay', id: 'balance-usage-panel', order: 40 }, Panel),
1317
+ )
1318
+
1319
+ ctx.effect(() => {
1320
+ const warm = setTimeout(() => load(ctx).catch(() => {}), 1_500)
1321
+
1322
+ const due = () => Date.now() - state.updatedAt >= (state.open ? REFRESH_OPEN_MS : REFRESH_IDLE_MS)
1323
+
1324
+ timer = setInterval(() => {
1325
+ if (due()) load(ctx).catch(() => {})
1326
+ }, TICK_MS)
1327
+
1328
+ /* Coming back to the app should never show numbers from the last time it was
1329
+ in front, even if the interval has not elapsed yet. */
1330
+ const wake = () => {
1331
+ if (document.visibilityState === 'hidden') return
1332
+ if (Date.now() - state.updatedAt < 2_000) return
1333
+ load(ctx, { force: true }).catch(() => {})
1334
+ }
1335
+ window.addEventListener('focus', wake)
1336
+ document.addEventListener('visibilitychange', wake)
1337
+
1338
+ return () => {
1339
+ clearTimeout(warm)
1340
+ if (timer) clearInterval(timer)
1341
+ timer = null
1342
+ window.removeEventListener('focus', wake)
1343
+ document.removeEventListener('visibilitychange', wake)
1344
+ }
1345
+ })
1346
+ },
1347
+ }
1348
+ },
1349
+ })