dsh-usage-peak 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js ADDED
@@ -0,0 +1,845 @@
1
+ /**
2
+ * dsh-usage-peak — Client half.
3
+ *
4
+ * Two surfaces over one data feed (/plugin/dsh-usage-peak/data):
5
+ * - a compact pill on its own row in the sidebar panel list,
6
+ * - a details page in Settings.
7
+ *
8
+ * Locale dictionaries are FLAT (`Record<string, string>`), as the client locale
9
+ * service requires: nested objects silently fall back to the bare key.
10
+ */
11
+ window.__ModuleLoader__.load({
12
+ id: 'dsh-usage-peak',
13
+ factory(require) {
14
+ const React = require('react');
15
+ const h = React.createElement;
16
+ const { useState, useEffect, useCallback } = React;
17
+
18
+ const NS = 'dsh-usage-peak';
19
+ const DATA_URL = '/plugin/dsh-usage-peak/data';
20
+
21
+ const dicts = {
22
+ zh: {
23
+ 'settings.title': '用量仪表盘',
24
+ 'settings.description': '峰谷时段与每天的花费、请求量、缓存命中',
25
+
26
+ 'widget.today': '今日',
27
+ 'widget.peak': '峰时',
28
+ 'widget.valley': '谷时',
29
+ 'widget.toPeak': '后转峰',
30
+ 'widget.toValley': '后转谷',
31
+ 'widget.soon': '即将切换',
32
+ 'widget.rail': '用量',
33
+ 'widget.railTitle': '用量仪表盘',
34
+ 'widget.failed': '读取失败',
35
+ 'widget.loading': '读取中',
36
+
37
+ 'page.title': '用量仪表盘',
38
+ 'page.subtitle': 'DeepSeek 峰谷计价 · 北京时区',
39
+ 'page.refresh': '刷新',
40
+ 'page.updated': '更新于',
41
+ 'page.loading': '正在统计会话日志…',
42
+ 'page.error': '读取失败',
43
+ 'page.retry': '重试',
44
+
45
+ 'status.peak': '峰时',
46
+ 'status.valley': '谷时',
47
+ 'status.switchIn': '距转',
48
+
49
+ 'kpi.calls': '今日请求',
50
+ 'kpi.tokens': 'tokens',
51
+ 'kpi.hit': '缓存命中',
52
+ 'kpi.peakShare': '峰时占比',
53
+ 'kpi.perCall': '平均每次',
54
+ 'kpi.balance': '余额',
55
+ 'kpi.today': '今日',
56
+ 'kpi.cache': '缓存',
57
+ 'kpi.out': '输出',
58
+ 'kpi.peakCost': '峰',
59
+ 'kpi.valleyCost': '谷',
60
+
61
+ 'chart.hours': '今日每小时花费',
62
+ 'chart.hoursHint': '橙 峰时 · 绿 谷时',
63
+ 'chart.days': '近 14 天',
64
+ 'chart.daysHint': '橙 峰时 · 绿 谷时',
65
+
66
+ 'cost.title': '今日花费构成',
67
+ 'cost.cache': '缓存命中',
68
+ 'cost.miss': '未命中输入',
69
+ 'cost.out': '输出',
70
+
71
+ 'price.title': '价目表',
72
+ 'price.hint': '元 / 百万 tokens',
73
+ 'price.model': '模型',
74
+ 'price.period': '时段',
75
+ 'price.hit': '命中',
76
+ 'price.miss': '未命中',
77
+ 'price.out': '输出',
78
+ 'price.current': '当前',
79
+ },
80
+ en: {
81
+ 'settings.title': 'Usage dashboard',
82
+ 'settings.description': 'Peak/valley windows with daily spend, requests and cache hits',
83
+
84
+ 'widget.today': 'Today',
85
+ 'widget.peak': 'Peak',
86
+ 'widget.valley': 'Valley',
87
+ 'widget.toPeak': ' to peak',
88
+ 'widget.toValley': ' to valley',
89
+ 'widget.soon': 'switching',
90
+ 'widget.rail': 'Usage',
91
+ 'widget.railTitle': 'Usage dashboard',
92
+ 'widget.failed': 'failed',
93
+ 'widget.loading': 'loading',
94
+
95
+ 'page.title': 'Usage dashboard',
96
+ 'page.subtitle': 'DeepSeek peak/valley pricing · Beijing time',
97
+ 'page.refresh': 'Refresh',
98
+ 'page.updated': 'Updated',
99
+ 'page.loading': 'Reading session logs…',
100
+ 'page.error': 'Failed to load',
101
+ 'page.retry': 'Retry',
102
+
103
+ 'status.peak': 'Peak',
104
+ 'status.valley': 'Valley',
105
+ 'status.switchIn': 'in',
106
+
107
+ 'kpi.calls': 'Requests',
108
+ 'kpi.tokens': 'tokens',
109
+ 'kpi.hit': 'Cache hit',
110
+ 'kpi.peakShare': 'Peak share',
111
+ 'kpi.perCall': 'per request',
112
+ 'kpi.balance': 'Balance',
113
+ 'kpi.today': 'today',
114
+ 'kpi.cache': 'cache',
115
+ 'kpi.out': 'output',
116
+ 'kpi.peakCost': 'peak',
117
+ 'kpi.valleyCost': 'valley',
118
+
119
+ 'chart.hours': 'Cost per hour today',
120
+ 'chart.hoursHint': 'orange peak · green valley',
121
+ 'chart.days': 'Last 14 days',
122
+ 'chart.daysHint': 'orange peak · green valley',
123
+
124
+ 'cost.title': 'Today by token type',
125
+ 'cost.cache': 'Cache hits',
126
+ 'cost.miss': 'Missed input',
127
+ 'cost.out': 'Output',
128
+
129
+ 'price.title': 'Price list',
130
+ 'price.hint': 'CNY per million tokens',
131
+ 'price.model': 'Model',
132
+ 'price.period': 'Period',
133
+ 'price.hit': 'Hit',
134
+ 'price.miss': 'Miss',
135
+ 'price.out': 'Output',
136
+ 'price.current': 'now',
137
+ },
138
+ };
139
+
140
+ const C = {
141
+ text: 'var(--dsw-alias-label-primary)',
142
+ text2: 'var(--dsw-alias-label-secondary)',
143
+ text3: 'var(--dsw-alias-label-tertiary)',
144
+ border: 'var(--dsw-alias-border-l2)',
145
+ layer1: 'var(--dsw-alias-bg-layer-1)',
146
+ layer2: 'var(--dsw-alias-bg-layer-2)',
147
+ peak: 'var(--dsw-alias-state-warn-primary)',
148
+ valley: 'var(--dsw-alias-state-success-primary)',
149
+ cache: 'var(--dsw-alias-state-business-primary)',
150
+ miss: 'var(--dsw-alias-state-warn-primary)',
151
+ out: 'var(--dsw-alias-brand-primary)',
152
+ };
153
+
154
+ /* ------------------------------ formatting ------------------------------ */
155
+
156
+ const yuan = (value, digits) =>
157
+ value === null || value === undefined || Number.isNaN(value)
158
+ ? '—'
159
+ : `¥${Number(value).toFixed(digits === undefined ? 2 : digits)}`;
160
+
161
+ function tokens(value) {
162
+ if (!value) return '0';
163
+ if (value >= 1e8) return `${(value / 1e8).toFixed(2)} 亿`;
164
+ if (value >= 1e4) return `${(value / 1e4).toFixed(1)} 万`;
165
+ return String(Math.round(value));
166
+ }
167
+
168
+ /** Ultra compact for the pill: 1.2B / 12.8M / 942K. */
169
+ function shortTokens(value) {
170
+ if (!value) return '0';
171
+ if (value >= 1e9) return `${(value / 1e9).toFixed(1)}B`;
172
+ if (value >= 1e6) return `${(value / 1e6).toFixed(1)}M`;
173
+ if (value >= 1e3) return `${Math.round(value / 1e3)}K`;
174
+ return String(Math.round(value));
175
+ }
176
+
177
+ const percent = (value, digits) =>
178
+ value === null || value === undefined || Number.isNaN(value)
179
+ ? '—'
180
+ : `${(value * 100).toFixed(digits === undefined ? 1 : digits)}%`;
181
+
182
+ function clock(ts) {
183
+ const date = new Date(ts);
184
+ return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
185
+ }
186
+
187
+ /** Short numeric countdown: 27分 / 1:27 / 3:19. */
188
+ function countdown(ms) {
189
+ const total = Math.max(0, Math.round(ms / 60000));
190
+ const hours = Math.floor(total / 60);
191
+ const minutes = total % 60;
192
+ return hours > 0 ? `${hours}:${String(minutes).padStart(2, '0')}` : `${minutes}分`;
193
+ }
194
+
195
+ /* --------------------------------- data --------------------------------- */
196
+
197
+ function useFeed() {
198
+ const [state, setState] = useState({ loading: true, error: null, data: null });
199
+ const [tick, setTick] = useState(0);
200
+
201
+ const load = useCallback((fresh) => {
202
+ const url = fresh ? `${DATA_URL}?fresh=1` : DATA_URL;
203
+ fetch(url, { headers: { accept: 'application/json' } })
204
+ .then((response) => {
205
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
206
+ return response.json();
207
+ })
208
+ .then((data) => {
209
+ if (!data || data.ok === false) throw new Error((data && data.error) || 'bad payload');
210
+ setState({ loading: false, error: null, data });
211
+ })
212
+ .catch((error) =>
213
+ setState((previous) => ({ loading: false, error: String(error && error.message), data: previous.data })),
214
+ );
215
+ }, []);
216
+
217
+ useEffect(() => {
218
+ load(false);
219
+ const timer = setInterval(() => load(false), 60_000);
220
+ return () => clearInterval(timer);
221
+ }, [load]);
222
+
223
+ // A failed start (the host half may register its route a moment after the
224
+ // page boots) should not leave the widget stuck on "读取失败" for a minute.
225
+ const failing = !!state.error;
226
+ useEffect(() => {
227
+ if (!failing) return undefined;
228
+ const timer = setTimeout(() => load(false), 5_000);
229
+ return () => clearTimeout(timer);
230
+ }, [failing, load, state.error]);
231
+
232
+ useEffect(() => {
233
+ const timer = setInterval(() => setTick((value) => value + 1), 15_000);
234
+ return () => clearInterval(timer);
235
+ }, []);
236
+
237
+ return { ...state, tick, reload: load };
238
+ }
239
+
240
+ /* -------------------------------- atoms --------------------------------- */
241
+
242
+ function Pill(props) {
243
+ return h(
244
+ 'span',
245
+ {
246
+ style: {
247
+ display: 'inline-flex',
248
+ alignItems: 'center',
249
+ gap: 6,
250
+ padding: '4px 11px',
251
+ borderRadius: 999,
252
+ background: C.layer2,
253
+ border: `1px solid ${C.border}`,
254
+ fontSize: 12,
255
+ lineHeight: '18px',
256
+ color: C.text2,
257
+ whiteSpace: 'nowrap',
258
+ ...(props.style || {}),
259
+ },
260
+ },
261
+ props.children,
262
+ );
263
+ }
264
+
265
+ function Dot(props) {
266
+ return h('span', {
267
+ style: {
268
+ width: 7,
269
+ height: 7,
270
+ borderRadius: 4,
271
+ flex: 'none',
272
+ background: props.tone,
273
+ boxShadow: props.glow ? `0 0 0 3px ${props.tone}22` : 'none',
274
+ },
275
+ });
276
+ }
277
+
278
+ function Sep() {
279
+ return h('span', { style: { color: C.text3, opacity: 0.7 } }, '·');
280
+ }
281
+
282
+ /* ----------------------------- sidebar widget ---------------------------- */
283
+
284
+ /**
285
+ * A row of its own in the sidebar's panel list.
286
+ *
287
+ * The list row is a normal nav row (36px), so the pill sits there as the
288
+ * row's glyph with an empty label: nothing to squeeze, nothing to overlap.
289
+ * Clicking the row opens the details page as a main panel.
290
+ */
291
+ function PanelGlyph(props) {
292
+ const t = props.t;
293
+ const { data } = useFeed();
294
+ const rail = !!props.rail;
295
+ const open = typeof props.onOpen === 'function' ? props.onOpen : null;
296
+ const rootProps = { 'data-usage-widget': '', title: '' };
297
+
298
+ const peak = data ? data.now.peak : null;
299
+ const loading = !data;
300
+ const tone = loading ? C.text3 : peak ? C.peak : C.valley;
301
+ const word = loading ? t('widget.loading') : peak ? t('widget.peak') : t('widget.valley');
302
+ const short = word.slice(0, 1) === '峰' ? '峰' : word.slice(0, 1) === '谷' ? '谷' : word;
303
+ const remain = data ? Math.max(0, data.now.nextAt - Date.now()) : 0;
304
+ const switchText =
305
+ data && remain > 30_000
306
+ ? `${countdown(remain)} ${peak ? t('widget.toValley') : t('widget.toPeak')}`
307
+ : t('widget.soon');
308
+ const today = data && data.today ? data.today.cost : null;
309
+ const tip = data
310
+ ? `${word} · ${t('widget.today')} ${yuan(today)} · ${tokens(data.today ? data.today.tokens : 0)} tokens · ${t('status.switchIn')} ${switchText}`
311
+ : word;
312
+
313
+ // The seat is the shell's own flex row: the root takes a whole line (see
314
+ // CSS) and the pill keeps its intrinsic width on it.
315
+ const rootStyle = { display: 'flex', alignItems: 'center', minWidth: 0 };
316
+ if (open) rootStyle.cursor = 'pointer';
317
+
318
+ const pillStyle = {
319
+ display: 'inline-flex',
320
+ alignItems: 'center',
321
+ gap: 4,
322
+ height: 21,
323
+ padding: '0 8px',
324
+ borderRadius: 999,
325
+ border: `1px solid ${C.border}`,
326
+ fontSize: 10.5,
327
+ lineHeight: '19px',
328
+ color: C.text2,
329
+ maxWidth: '100%',
330
+ overflow: 'hidden',
331
+ whiteSpace: 'nowrap',
332
+ boxSizing: 'border-box',
333
+ };
334
+
335
+ const pill = rail
336
+ ? h(Dot, { tone })
337
+ : h(
338
+ 'span',
339
+ { style: pillStyle },
340
+ h(Dot, { tone, glow: true }),
341
+ h('span', { style: { color: tone, fontWeight: 600, flex: 'none' } }, short),
342
+ h('span', { style: { color: C.text, fontWeight: 600, fontVariantNumeric: 'tabular-nums', flex: 'none' } }, yuan(today)),
343
+ h(Sep),
344
+ h(
345
+ 'span',
346
+ { style: { color: C.text2, flex: 'none', fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' } },
347
+ data && data.today ? shortTokens(data.today.tokens) : '—',
348
+ h('span', { style: { color: C.text3, marginLeft: 2 } }, 'tok'),
349
+ ),
350
+ h(Sep),
351
+ h('span', { style: { color: C.text3, fontVariantNumeric: 'tabular-nums', overflow: 'hidden', textOverflow: 'ellipsis' } }, data ? switchText : ''),
352
+ );
353
+
354
+ return h('div', { ...rootProps, title: tip, onClick: open || undefined, style: rootStyle }, pill);
355
+ }
356
+
357
+ /* ------------------------------- page bits ------------------------------- */
358
+
359
+ function Card(props) {
360
+ return h(
361
+ 'section',
362
+ {
363
+ style: {
364
+ background: C.layer1,
365
+ border: `1px solid ${C.border}`,
366
+ borderRadius: 12,
367
+ padding: '14px 16px',
368
+ display: 'flex',
369
+ flexDirection: 'column',
370
+ gap: 8,
371
+ minWidth: 0,
372
+ ...(props.style || {}),
373
+ },
374
+ },
375
+ props.children,
376
+ );
377
+ }
378
+
379
+ function CardTitle(props) {
380
+ return h(
381
+ 'header',
382
+ { style: { display: 'flex', alignItems: 'baseline', gap: 8, justifyContent: 'space-between' } },
383
+ h('h3', { style: { margin: 0, fontSize: 12.5, fontWeight: 600, color: C.text } }, props.title),
384
+ props.hint ? h('span', { style: { fontSize: 10.5, color: C.text3 } }, props.hint) : null,
385
+ );
386
+ }
387
+
388
+ function Kpi(props) {
389
+ return h(
390
+ 'div',
391
+ {
392
+ style: {
393
+ display: 'flex',
394
+ flexDirection: 'column',
395
+ gap: 2,
396
+ padding: '10px 14px',
397
+ borderRadius: 10,
398
+ border: `1px solid ${C.border}`,
399
+ background: C.layer1,
400
+ minWidth: 0,
401
+ },
402
+ },
403
+ h('span', { style: { fontSize: 11, color: C.text3 } }, props.label),
404
+ h(
405
+ 'strong',
406
+ {
407
+ style: {
408
+ fontSize: 19,
409
+ fontWeight: 600,
410
+ lineHeight: 1.2,
411
+ color: props.tone || C.text,
412
+ fontVariantNumeric: 'tabular-nums',
413
+ },
414
+ },
415
+ props.value,
416
+ ),
417
+ props.hint ? h('span', { style: { fontSize: 10.5, color: C.text3 } }, props.hint) : null,
418
+ );
419
+ }
420
+
421
+ function HourChart(props) {
422
+ const hours = props.hours || [];
423
+ const max = Math.max(0.0001, ...hours.map((entry) => entry.cost));
424
+ return h(
425
+ 'div',
426
+ { style: { display: 'flex', alignItems: 'flex-end', gap: 3, height: 108, marginTop: 2 } },
427
+ hours.map((entry) =>
428
+ h(
429
+ 'div',
430
+ {
431
+ key: entry.hour,
432
+ title: `${String(entry.hour).padStart(2, '0')}:00 · ${yuan(entry.cost)} · ${entry.calls} 次`,
433
+ style: {
434
+ flex: 1,
435
+ display: 'flex',
436
+ flexDirection: 'column',
437
+ justifyContent: 'flex-end',
438
+ height: '100%',
439
+ minWidth: 5,
440
+ borderRadius: 4,
441
+ outline: entry.hour === props.nowHour ? `1px solid ${C.border}` : 'none',
442
+ outlineOffset: 1,
443
+ },
444
+ },
445
+ h('div', {
446
+ style: {
447
+ height: `${Math.max(entry.cost > 0 ? 3 : 0, (entry.cost / max) * 100)}%`,
448
+ background: entry.peak ? C.peak : C.valley,
449
+ opacity: entry.cost > 0 ? 0.9 : 0,
450
+ borderRadius: 3,
451
+ },
452
+ }),
453
+ ),
454
+ ),
455
+ );
456
+ }
457
+
458
+ function DayChart(props) {
459
+ const days = props.days || [];
460
+ const max = Math.max(0.0001, ...days.map((entry) => entry.cost));
461
+ return h(
462
+ 'div',
463
+ { style: { display: 'flex', alignItems: 'flex-end', gap: 8, height: 128, marginTop: 4 } },
464
+ days.map((entry) =>
465
+ h(
466
+ 'div',
467
+ {
468
+ key: entry.day,
469
+ style: { flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3, height: '100%' },
470
+ },
471
+ h(
472
+ 'span',
473
+ { style: { fontSize: 9.5, color: C.text3, fontVariantNumeric: 'tabular-nums' } },
474
+ entry.cost > 0 ? entry.cost.toFixed(1) : '',
475
+ ),
476
+ h(
477
+ 'div',
478
+ {
479
+ title: `${entry.day} · ${yuan(entry.cost)} · ${entry.calls} 次`,
480
+ style: {
481
+ flex: 1,
482
+ width: '100%',
483
+ display: 'flex',
484
+ flexDirection: 'column',
485
+ justifyContent: 'flex-end',
486
+ borderRadius: 4,
487
+ overflow: 'hidden',
488
+ },
489
+ },
490
+ h('div', { style: { height: `${(entry.peakCost / max) * 100}%`, background: C.peak, opacity: 0.9 } }),
491
+ h('div', { style: { height: `${(entry.valleyCost / max) * 100}%`, background: C.valley, opacity: 0.9 } }),
492
+ ),
493
+ h('span', { style: { fontSize: 9.5, color: C.text2 } }, entry.day.slice(5)),
494
+ ),
495
+ ),
496
+ );
497
+ }
498
+
499
+ function CostSplit(props) {
500
+ const total = Math.max(0.0001, props.cost || 0);
501
+ const rows = [
502
+ { key: 'cache', label: props.t('cost.cache'), value: props.costCache, fill: C.cache },
503
+ { key: 'miss', label: props.t('cost.miss'), value: props.costMiss, fill: C.miss },
504
+ { key: 'out', label: props.t('cost.out'), value: props.costOut, fill: C.out },
505
+ ];
506
+ return h(
507
+ 'div',
508
+ { style: { display: 'flex', flexDirection: 'column', gap: 7 } },
509
+ h(
510
+ 'div',
511
+ { style: { display: 'flex', height: 8, borderRadius: 4, overflow: 'hidden', background: C.layer2 } },
512
+ rows.map((row) =>
513
+ h('div', {
514
+ key: row.key,
515
+ title: `${row.label} ${yuan(row.value)}`,
516
+ style: { width: `${((row.value || 0) / total) * 100}%`, background: row.fill },
517
+ }),
518
+ ),
519
+ ),
520
+ rows.map((row) =>
521
+ h(
522
+ 'div',
523
+ { key: row.key, style: { display: 'flex', alignItems: 'center', gap: 7, fontSize: 11.5 } },
524
+ h('span', { style: { width: 7, height: 7, borderRadius: 2, background: row.fill, flex: 'none' } }),
525
+ h('span', { style: { color: C.text2, flex: 1 } }, row.label),
526
+ h('span', { style: { color: C.text, fontVariantNumeric: 'tabular-nums' } }, yuan(row.value)),
527
+ h('span', { style: { color: C.text3, width: 42, textAlign: 'right' } }, percent((row.value || 0) / total)),
528
+ ),
529
+ ),
530
+ );
531
+ }
532
+
533
+ function PriceTable(props) {
534
+ const { pricing, peakNow, t } = props;
535
+ const head = [t('price.model'), t('price.period'), t('price.hit'), t('price.miss'), t('price.out')];
536
+ const rows = [];
537
+ for (const model of pricing) {
538
+ for (const offset of [0, 1]) {
539
+ const isPeak = offset === 1;
540
+ const current = isPeak === peakNow;
541
+ rows.push(
542
+ h(
543
+ 'tr',
544
+ { key: `${model.id}-${offset}`, style: { background: current ? C.layer2 : 'transparent' } },
545
+ h('td', { style: { padding: '4px 8px', color: C.text } }, offset === 0 ? model.label : ''),
546
+ h(
547
+ 'td',
548
+ { style: { padding: '4px 8px', color: C.text2 } },
549
+ isPeak ? t('status.peak') : t('status.valley'),
550
+ current ? ` · ${t('price.current')}` : '',
551
+ ),
552
+ h('td', { style: { padding: '4px 8px', textAlign: 'right', color: C.text } }, model.hit[offset]),
553
+ h('td', { style: { padding: '4px 8px', textAlign: 'right', color: C.text } }, model.miss[offset]),
554
+ h('td', { style: { padding: '4px 8px', textAlign: 'right', color: C.text } }, model.out[offset]),
555
+ ),
556
+ );
557
+ }
558
+ }
559
+ return h(
560
+ 'table',
561
+ { style: { width: '100%', borderCollapse: 'collapse', fontSize: 11.5 } },
562
+ h(
563
+ 'thead',
564
+ null,
565
+ h(
566
+ 'tr',
567
+ null,
568
+ head.map((label, index) =>
569
+ h(
570
+ 'th',
571
+ {
572
+ key: label,
573
+ style: {
574
+ padding: '3px 8px',
575
+ textAlign: index >= 2 ? 'right' : 'left',
576
+ fontWeight: 500,
577
+ color: C.text3,
578
+ borderBottom: `1px solid ${C.border}`,
579
+ },
580
+ },
581
+ label,
582
+ ),
583
+ ),
584
+ ),
585
+ ),
586
+ h('tbody', null, rows),
587
+ );
588
+ }
589
+
590
+ /* -------------------------------- settings ------------------------------- */
591
+
592
+ function Dashboard(props) {
593
+ const t = props.t;
594
+ const feed = useFeed();
595
+ const data = feed.data;
596
+ const peakNow = data ? data.now.peak : false;
597
+ const remain = data ? Math.max(0, data.now.nextAt - Date.now()) : 0;
598
+ const switchText =
599
+ data && remain > 30_000
600
+ ? `${countdown(remain)} ${t(data.now.nextStatus === 'peak' ? 'widget.toPeak' : 'widget.toValley')}`
601
+ : t('widget.soon');
602
+
603
+ const body = [];
604
+
605
+ if (feed.loading && !data) {
606
+ body.push(h('div', { key: 'loading', style: { color: C.text2, fontSize: 13 } }, t('page.loading')));
607
+ } else if (feed.error && !data) {
608
+ body.push(
609
+ h(
610
+ Card,
611
+ { key: 'error', style: { gap: 8 } },
612
+ h(
613
+ 'span',
614
+ { style: { color: 'var(--dsw-alias-state-error-primary)', fontSize: 12.5 } },
615
+ `${t('page.error')}: ${feed.error}`,
616
+ ),
617
+ h(
618
+ 'button',
619
+ {
620
+ onClick: () => feed.reload(true),
621
+ style: {
622
+ alignSelf: 'flex-start',
623
+ padding: '5px 13px',
624
+ borderRadius: 8,
625
+ border: `1px solid ${C.border}`,
626
+ background: C.layer2,
627
+ color: C.text,
628
+ cursor: 'pointer',
629
+ fontSize: 12,
630
+ },
631
+ },
632
+ t('page.retry'),
633
+ ),
634
+ ),
635
+ );
636
+ } else if (data) {
637
+ const today = data.today || {};
638
+
639
+ body.push(
640
+ h(
641
+ 'div',
642
+ { key: 'pills', style: { display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' } },
643
+ h(
644
+ Pill,
645
+ { style: { background: peakNow ? `${C.peak}1a` : `${C.valley}1a`, borderColor: 'transparent' } },
646
+ h(Dot, { tone: peakNow ? C.peak : C.valley, glow: true }),
647
+ h(
648
+ 'span',
649
+ { style: { color: peakNow ? C.peak : C.valley, fontWeight: 600 } },
650
+ peakNow ? t('status.peak') : t('status.valley'),
651
+ ),
652
+ h(Sep),
653
+ h('span', { style: { color: C.text } }, yuan(today.cost)),
654
+ h(Sep),
655
+ h('span', { style: { color: C.text3 } }, `${t('status.switchIn')} ${switchText}`),
656
+ ),
657
+ h(
658
+ Pill,
659
+ null,
660
+ `${t('kpi.balance')} `,
661
+ h(
662
+ 'span',
663
+ { style: { color: C.text } },
664
+ data.ledger && typeof data.ledger.balance === 'number' ? yuan(data.ledger.balance) : '—',
665
+ ),
666
+ ),
667
+ h(Pill, null, `${today.calls || 0} 次 · ${tokens(today.tokens)} tokens`),
668
+ ),
669
+ );
670
+
671
+ body.push(
672
+ h(
673
+ 'div',
674
+ { key: 'kpi', style: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(140px, 1fr))', gap: 10 } },
675
+ h(Kpi, {
676
+ label: t('kpi.calls'),
677
+ value: today.calls || 0,
678
+ hint: `${t('kpi.perCall')} ${tokens(today.avgTokens)}`,
679
+ }),
680
+ h(Kpi, {
681
+ label: t('kpi.tokens'),
682
+ value: tokens(today.tokens),
683
+ hint: `${t('kpi.cache')} ${tokens(today.cacheTokens)} · ${t('kpi.out')} ${tokens(today.outputTokens)}`,
684
+ }),
685
+ h(Kpi, { label: t('kpi.hit'), value: percent(today.hitRate), hint: '命中价 1/50' }),
686
+ h(Kpi, {
687
+ label: t('kpi.peakShare'),
688
+ value: percent(today.peakShare, 0),
689
+ tone: (today.peakShare || 0) > 0.5 ? C.peak : C.valley,
690
+ hint: `${t('kpi.peakCost')} ${yuan(today.peakCost)} · ${t('kpi.valleyCost')} ${yuan(today.valleyCost)}`,
691
+ }),
692
+ ),
693
+ );
694
+
695
+ body.push(
696
+ h(
697
+ 'div',
698
+ { key: 'charts', style: { display: 'grid', gridTemplateColumns: 'minmax(0, 1.5fr) minmax(0, 1fr)', gap: 10 } },
699
+ h(
700
+ Card,
701
+ null,
702
+ h(CardTitle, { title: t('chart.hours'), hint: t('chart.hoursHint') }),
703
+ h(HourChart, { hours: data.hours, nowHour: data.now.hour }),
704
+ h(
705
+ 'div',
706
+ { style: { display: 'flex', justifyContent: 'space-between', fontSize: 9.5, color: C.text3 } },
707
+ ['00', '06', '12', '18', '23'].map((label) => h('span', { key: label }, label)),
708
+ ),
709
+ ),
710
+ h(
711
+ Card,
712
+ null,
713
+ h(CardTitle, { title: t('cost.title') }),
714
+ h(CostSplit, {
715
+ t,
716
+ cost: today.cost || 0,
717
+ costCache: today.costCache || 0,
718
+ costMiss: today.costMiss || 0,
719
+ costOut: today.costOut || 0,
720
+ }),
721
+ ),
722
+ ),
723
+ );
724
+
725
+ body.push(
726
+ h(
727
+ Card,
728
+ { key: 'days' },
729
+ h(CardTitle, {
730
+ title: t('chart.days'),
731
+ hint: `${t('kpi.today')} ${yuan(today.cost)} · ${t('kpi.perCall')} ${yuan(data.week.avgPerCall)}`,
732
+ }),
733
+ h(DayChart, { days: data.days }),
734
+ h('span', { style: { fontSize: 9.5, color: C.text3 } }, t('chart.daysHint')),
735
+ ),
736
+ );
737
+
738
+ body.push(
739
+ h(
740
+ Card,
741
+ { key: 'price' },
742
+ h(CardTitle, { title: t('price.title'), hint: t('price.hint') }),
743
+ h(PriceTable, { pricing: data.pricing, peakNow, t }),
744
+ ),
745
+ );
746
+ }
747
+
748
+ return h(
749
+ 'div',
750
+ {
751
+ style: {
752
+ padding: '20px 24px 32px',
753
+ display: 'flex',
754
+ flexDirection: 'column',
755
+ gap: 10,
756
+ color: C.text,
757
+ height: '100%',
758
+ overflowY: 'auto',
759
+ boxSizing: 'border-box',
760
+ },
761
+ },
762
+ h(
763
+ 'header',
764
+ { style: { display: 'flex', alignItems: 'flex-end', gap: 10, flexWrap: 'wrap' } },
765
+ h(
766
+ 'div',
767
+ { style: { display: 'flex', flexDirection: 'column', gap: 1, flex: 1 } },
768
+ h('h2', { style: { margin: 0, fontSize: 16, fontWeight: 600 } }, t('page.title')),
769
+ h('span', { style: { fontSize: 11.5, color: C.text2 } }, t('page.subtitle')),
770
+ ),
771
+ h(
772
+ 'span',
773
+ { style: { fontSize: 10.5, color: C.text3 } },
774
+ data ? `${t('page.updated')} ${clock(data.generatedAt)}` : '',
775
+ ),
776
+ h(
777
+ 'button',
778
+ {
779
+ onClick: () => feed.reload(true),
780
+ style: {
781
+ padding: '4px 12px',
782
+ borderRadius: 8,
783
+ border: `1px solid ${C.border}`,
784
+ background: C.layer1,
785
+ color: C.text,
786
+ cursor: 'pointer',
787
+ fontSize: 11.5,
788
+ },
789
+ },
790
+ t('page.refresh'),
791
+ ),
792
+ ),
793
+ body,
794
+ );
795
+ }
796
+
797
+ /* --------------------------------- apply --------------------------------- */
798
+
799
+ function makeT(ctx) {
800
+ const { locale } = ctx;
801
+ if (!locale || typeof locale.bind !== 'function') {
802
+ return (key, fallback) => dicts.zh[key] || fallback || key;
803
+ }
804
+ const bound = locale.bind(NS);
805
+ return (key, fallback) => {
806
+ const value = bound(key);
807
+ return value === key && fallback ? fallback : value;
808
+ };
809
+ }
810
+
811
+ return {
812
+ inject: ['slots', 'locale', 'layout'],
813
+ apply(ctx) {
814
+ ctx.effect(() => ctx.locale && ctx.locale.register(NS, dicts), 'dsh-usage-peak: dictionaries');
815
+ const t = makeT(ctx);
816
+
817
+ const openPanel = () => {
818
+ try {
819
+ ctx.layout && typeof ctx.layout.selectPanel === 'function' && ctx.layout.selectPanel('usage');
820
+ } catch (err) {
821
+ console.warn('[dsh-usage-peak] open panel failed', err);
822
+ }
823
+ };
824
+
825
+ ctx.slots.inject('sidebar.panellist', () =>
826
+ ctx.slots.register(
827
+ { name: 'sidebar.panellist', id: 'usage', order: -10, label: () => '' },
828
+ (props) => h(PanelGlyph, { ...props, t, rail: (props.size || 0) >= 18, onOpen: openPanel }),
829
+ ),
830
+ );
831
+
832
+ ctx.slots.inject('main', () =>
833
+ ctx.slots.register({ name: 'main', key: 'usage' }, () => h(Dashboard, { t })),
834
+ );
835
+
836
+ ctx.slots.inject('settings.section', () =>
837
+ ctx.slots.register(
838
+ { name: 'settings.section', id: 'dsh-usage-peak', order: 47, label: () => t('settings.title') },
839
+ () => h(Dashboard, { t }),
840
+ ),
841
+ );
842
+ },
843
+ };
844
+ },
845
+ });