dsh-usage-peak 0.0.0-stage → 1.1.0

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