dsh-usage-overview 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/lib/client.js ADDED
@@ -0,0 +1,2185 @@
1
+ window.__ModuleLoader__.load({
2
+ id: "dsh-usage-overview",
3
+ factory: (require) => {
4
+ var module = { exports: {} };
5
+ var exports = module.exports;
6
+ // ---- src/protocol.js ----
7
+ const __m0 = (() => {
8
+
9
+
10
+ const USAGE_SCHEMA_VERSION = 1;
11
+
12
+ const PANEL_ID = 'usage-overview';
13
+
14
+ const NS = 'usage-overview';
15
+
16
+ const USAGE_STATS_PATH = '/plugins/dsh-usage-overview/stats';
17
+
18
+
19
+ const RANGE_PRESETS = Object.freeze([
20
+ { id: '7d', days: 7 },
21
+ { id: '30d', days: 30 },
22
+ { id: '90d', days: 90 },
23
+ { id: 'all', days: null },
24
+ ]);
25
+
26
+ const PROVIDER_SOURCE_LABELS = Object.freeze({
27
+ 'workbuddy-ai': 'WorkBuddy AI',
28
+ 'workbuddy': 'WorkBuddy',
29
+ 'opencode-go': 'OpenCode Go',
30
+ 'deepseek-official': 'DeepSeek Official',
31
+ 'deepseek': 'DeepSeek',
32
+ });
33
+
34
+ const SERIES_COLORS = Object.freeze([
35
+ '#4f8ef7',
36
+ '#39c07a',
37
+ '#f2a33c',
38
+ '#c471f5',
39
+ '#f2557a',
40
+ '#3cc8d6',
41
+ '#9aa7ff',
42
+ '#e0c341',
43
+ ]);
44
+
45
+ const TOKEN_BUCKETS = Object.freeze([
46
+ 'uncachedInputTokens',
47
+ 'cacheReadTokens',
48
+ 'cacheWriteTokens',
49
+ 'outputTokens',
50
+ ]);
51
+
52
+ function cacheHitRate(buckets) {
53
+ const read = numberOr0(buckets?.cacheReadTokens);
54
+ const write = numberOr0(buckets?.cacheWriteTokens);
55
+ const uncached = numberOr0(buckets?.uncachedInputTokens);
56
+ const input = read + write + uncached;
57
+ if (input <= 0) return null;
58
+ return (read / input) * 100;
59
+ }
60
+
61
+ function numberOr0(value) {
62
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0;
63
+ }
64
+
65
+ function isUsageDocument(value) {
66
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;
67
+ if (value.schemaVersion !== USAGE_SCHEMA_VERSION) return false;
68
+ if (typeof value.generatedAt !== 'number') return false;
69
+ if (typeof value.totals !== 'object' || value.totals === null) return false;
70
+ if (!Array.isArray(value.days)) return false;
71
+ if (!Array.isArray(value.models)) return false;
72
+ return true;
73
+ }
74
+
75
+ function formatTokens(value) {
76
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) return '—';
77
+ if (value < 1000) return String(Math.round(value));
78
+ if (value < 10000) return `${(value / 1000).toFixed(2)}K`;
79
+ if (value < 1000000) return `${(value / 1000).toFixed(1)}K`;
80
+ if (value < 100000000) return `${(value / 1000000).toFixed(1)}M`;
81
+ return `${(value / 100000000).toFixed(2)}亿`;
82
+ }
83
+
84
+ function formatTokensZh(value) {
85
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) return '—';
86
+ if (value < 10000) return String(Math.round(value));
87
+ if (value < 100000000) return `${(value / 10000).toFixed(1)}万`;
88
+ return `${(value / 100000000).toFixed(1)}亿`;
89
+ }
90
+
91
+ function formatDuration(ms) {
92
+ if (typeof ms !== 'number' || !Number.isFinite(ms) || ms < 0) return '—';
93
+ const seconds = Math.round(ms / 1000);
94
+ if (seconds < 60) return `${String(seconds)}秒`;
95
+ const minutes = Math.floor(seconds / 60);
96
+ if (minutes < 60) return `${String(minutes)}分${String(seconds % 60)}秒`;
97
+ const hours = Math.floor(minutes / 60);
98
+ if (hours < 24) return `${String(hours)}小时${String(minutes % 60)}分`;
99
+ const days = Math.floor(hours / 24);
100
+ return `${String(days)}天${String(hours % 24)}小时`;
101
+ }
102
+
103
+ function formatPercent(value) {
104
+ if (typeof value !== 'number' || !Number.isFinite(value)) return '—';
105
+ return `${value.toFixed(2)}%`;
106
+ }
107
+
108
+ function dayKeyOf(ms) {
109
+ const date = new Date(ms);
110
+ const month = String(date.getMonth() + 1).padStart(2, '0');
111
+ const day = String(date.getDate()).padStart(2, '0');
112
+ return `${String(date.getFullYear())}-${month}-${day}`;
113
+ }
114
+ return { USAGE_SCHEMA_VERSION, PANEL_ID, NS, USAGE_STATS_PATH, RANGE_PRESETS, PROVIDER_SOURCE_LABELS, SERIES_COLORS, TOKEN_BUCKETS, cacheHitRate, isUsageDocument, formatTokens, formatTokensZh, formatDuration, formatPercent, dayKeyOf };
115
+ })();
116
+
117
+ // ---- src/client/charts.js ----
118
+ const __m1 = (() => {
119
+ const { createElement: h, useEffect: useEffect, useMemo: useMemo, useRef: useRef, useState: useState } = require("react");
120
+ const { SERIES_COLORS: SERIES_COLORS, cacheHitRate: cacheHitRate, formatPercent: formatPercent, formatTokensZh: formatTokensZh } = __m0;
121
+
122
+ const DAYS_PER_WEEK = 7;
123
+
124
+ const HEATMAP_DAYS = 365;
125
+
126
+ const FALLBACK_CHART_WIDTH = 920;
127
+
128
+ function useMeasuredWidth(fallback = FALLBACK_CHART_WIDTH) {
129
+ const [width, setWidth] = useState(fallback);
130
+ const host = useRef(null);
131
+
132
+ useEffect(() => {
133
+ const node = host.current;
134
+ if (node === null) return undefined;
135
+ const measure = () => {
136
+ const next = Math.round(node.clientWidth);
137
+ if (next > 0) setWidth(next);
138
+ };
139
+ measure();
140
+ if (typeof ResizeObserver !== 'function') {
141
+ window.addEventListener('resize', measure);
142
+ return () => {
143
+ window.removeEventListener('resize', measure);
144
+ };
145
+ }
146
+ const observer = new ResizeObserver(measure);
147
+ observer.observe(node);
148
+ return () => {
149
+ observer.disconnect();
150
+ };
151
+ }, []);
152
+
153
+ return { host, width };
154
+ }
155
+
156
+ function buildDayWindow(days, rangeDays) {
157
+ const count = rangeDays === null ? Math.max(days.length, 2) : Math.max(rangeDays, 2);
158
+ const byDay = new Map(days.map((entry) => [entry.day, entry]));
159
+
160
+ const labels = [];
161
+ const cursor = new Date();
162
+ cursor.setHours(0, 0, 0, 0);
163
+ cursor.setDate(cursor.getDate() - (count - 1));
164
+ for (let index = 0; index < count; index += 1) {
165
+ const key = `${String(cursor.getFullYear())}-${String(cursor.getMonth() + 1).padStart(2, '0')}-${String(cursor.getDate()).padStart(2, '0')}`;
166
+ labels.push({ key, date: new Date(cursor), entry: byDay.get(key) });
167
+ cursor.setDate(cursor.getDate() + 1);
168
+ }
169
+ return labels;
170
+ }
171
+
172
+ function buildUsageBuckets(days, rangeDays, granularity) {
173
+ const labels = buildDayWindow(days, rangeDays);
174
+ if (granularity !== 'week') {
175
+ return labels.map((label) => ({
176
+ key: label.key,
177
+ date: label.date,
178
+ title: label.key,
179
+ byModel: new Map(Object.entries(label.entry?.byModel ?? {})),
180
+ }));
181
+ }
182
+
183
+ const weeks = new Map();
184
+ for (const label of labels) {
185
+ const date = label.date;
186
+ const offset = (date.getDay() + 6) % 7;
187
+ const start = new Date(date);
188
+ start.setDate(start.getDate() - offset);
189
+ const key = `${String(start.getFullYear())}-${String(start.getMonth() + 1).padStart(2, '0')}-${String(start.getDate()).padStart(2, '0')}`;
190
+ let bucket = weeks.get(key);
191
+ if (bucket === undefined) {
192
+ bucket = {
193
+ key,
194
+ date: start,
195
+ title: `${String(start.getMonth() + 1)}月${String(start.getDate())}日 当周`,
196
+ byModel: new Map(),
197
+ };
198
+ weeks.set(key, bucket);
199
+ }
200
+ for (const [route, value] of Object.entries(label.entry?.byModel ?? {})) {
201
+ bucket.byModel.set(route, (bucket.byModel.get(route) ?? 0) + value);
202
+ }
203
+ }
204
+ return [...weeks.values()].sort((a, b) => a.date - b.date);
205
+ }
206
+
207
+ function pickDateTicks(labels, xOf, usableWidth, width) {
208
+ const count = labels.length;
209
+ const targetTicks = Math.max(2, Math.min(8, Math.floor(usableWidth / 64)));
210
+ const step = Math.max(1, Math.ceil(count / targetTicks));
211
+ const minGap = Math.max(46, Math.min(54, width * 0.055));
212
+ const chosen = [];
213
+ for (let index = 0; index < count; index += step) chosen.push(index);
214
+ const lastIndex = count - 1;
215
+ if (chosen[chosen.length - 1] !== lastIndex) {
216
+ if (xOf(lastIndex) - xOf(chosen[chosen.length - 1] ?? 0) < minGap) chosen.pop();
217
+ chosen.push(lastIndex);
218
+ }
219
+ return chosen.map((index) => ({
220
+ label: labels[index],
221
+ index,
222
+ x: xOf(index),
223
+ text: `${String(labels[index].date.getMonth() + 1)}月${String(labels[index].date.getDate())}日`,
224
+ }));
225
+ }
226
+
227
+ function leadingBlanks(first) {
228
+ return first.getDay();
229
+ }
230
+
231
+ function buildHeatGrid(days, rangeDays, now) {
232
+ const byDay = new Map(days.map((entry) => [entry.day, entry]));
233
+ const length = rangeDays === null ? 365 : rangeDays;
234
+
235
+ const end = new Date(now);
236
+ end.setHours(0, 0, 0, 0);
237
+ const start = new Date(end);
238
+ start.setDate(start.getDate() - (length - 1));
239
+
240
+ const cells = [];
241
+ const cursor = new Date(start);
242
+ cursor.setDate(cursor.getDate() - leadingBlanks(start));
243
+ const last = end.getTime();
244
+
245
+ let guard = 0;
246
+ while (cursor.getTime() <= last && guard < 800) {
247
+ const key = `${String(cursor.getFullYear())}-${String(cursor.getMonth() + 1).padStart(2, '0')}-${String(cursor.getDate()).padStart(2, '0')}`;
248
+ const entry = byDay.get(key);
249
+ cells.push({
250
+ key,
251
+ date: new Date(cursor),
252
+ total: entry?.total ?? 0,
253
+ sessions: entry?.sessions ?? 0,
254
+ turns: entry?.turns ?? 0,
255
+ inRange: cursor.getTime() >= start.getTime(),
256
+ });
257
+ cursor.setDate(cursor.getDate() + 1);
258
+ guard += 1;
259
+ }
260
+
261
+ const columns = [];
262
+ for (let index = 0; index < cells.length; index += DAYS_PER_WEEK) {
263
+ columns.push(cells.slice(index, index + DAYS_PER_WEEK));
264
+ }
265
+
266
+ const monthLabels = [];
267
+ let lastLabelled = Number.NEGATIVE_INFINITY;
268
+ columns.forEach((column, index) => {
269
+ const firstOfMonth = column.find((cell) => cell.inRange && cell.date.getDate() === 1);
270
+ if (firstOfMonth === undefined || index - lastLabelled < 3) {
271
+ monthLabels.push('');
272
+ return;
273
+ }
274
+ monthLabels.push(`${String(firstOfMonth.date.getMonth() + 1)}月`);
275
+ lastLabelled = index;
276
+ });
277
+
278
+ return { columns, monthLabels };
279
+ }
280
+
281
+ function levelOf(total, peak) {
282
+ if (total <= 0 || peak <= 0) return 0;
283
+ const ratio = total / peak;
284
+ if (ratio <= 0.15) return 1;
285
+ if (ratio <= 0.4) return 2;
286
+ if (ratio <= 0.7) return 3;
287
+ return 4;
288
+ }
289
+
290
+ function Tooltip({ anchor, title, rows }) {
291
+ if (anchor === null) return null;
292
+ const style = {
293
+ left: `${String(Math.min(anchor.x + 14, window.innerWidth - 280))}px`,
294
+ top: `${String(Math.max(anchor.y - 12, 8))}px`,
295
+ };
296
+ return h(
297
+ 'div',
298
+ { className: 'dus-tip', style, role: 'tooltip' },
299
+ h('div', { className: 'dus-tip-title' }, title),
300
+ ...rows.map((row) => h('div', { className: 'dus-tip-row', key: row }, row)),
301
+ );
302
+ }
303
+
304
+ function TokenHeatmap({ days, rangeDays, now }) {
305
+ const [anchor, setAnchor] = useState(null);
306
+ const [hovered, setHovered] = useState(null);
307
+ const [available, setAvailable] = useState(0);
308
+ const [scrollable, setScrollable] = useState(false);
309
+ const host = useRef(null);
310
+ const wrap = useRef(null);
311
+ const scrollState = useRef({ overflowing: false, atRight: true });
312
+
313
+ const grid = useMemo(() => buildHeatGrid(days, HEATMAP_DAYS, now), [days, now]);
314
+ const peak = useMemo(() => days.reduce((max, day) => Math.max(max, day.total ?? 0), 0), [days]);
315
+
316
+ useEffect(() => {
317
+ const node = host.current;
318
+ if (node === null) return undefined;
319
+ const measure = () => {
320
+ setAvailable(node.clientWidth);
321
+ };
322
+ measure();
323
+ if (typeof ResizeObserver !== 'function') {
324
+ window.addEventListener('resize', measure);
325
+ return () => {
326
+ window.removeEventListener('resize', measure);
327
+ };
328
+ }
329
+ const observer = new ResizeObserver(measure);
330
+ observer.observe(node);
331
+ return () => {
332
+ observer.disconnect();
333
+ };
334
+ }, []);
335
+
336
+ const columnCount = Math.max(1, grid.columns.length);
337
+ const gap = available > 0 ? 2 + Math.min(1, Math.max(0, (available - 300) / 780)) : 3;
338
+ const fitted = available > 0 ? Math.floor((available - gap * (columnCount - 1)) / columnCount) : 11;
339
+ const cell = Math.max(8, Math.min(22, fitted));
340
+
341
+ useEffect(() => {
342
+ if (available <= 0) return;
343
+ const node = wrap.current;
344
+ if (node === null) return;
345
+ const maxScroll = Math.max(0, node.scrollWidth - node.clientWidth);
346
+ const overflowing = maxScroll > 1;
347
+ const previous = scrollState.current;
348
+ setScrollable(overflowing);
349
+ if (overflowing && (!previous.overflowing || previous.atRight)) {
350
+ node.scrollLeft = maxScroll;
351
+ }
352
+ scrollState.current = {
353
+ overflowing,
354
+ atRight: overflowing && Math.abs(node.scrollLeft - maxScroll) <= 2,
355
+ };
356
+ }, [available, cell, gap, grid]);
357
+
358
+ const show = (day, event) => {
359
+ const rect = event.currentTarget.getBoundingClientRect();
360
+ setAnchor({ x: rect.left + rect.width / 2, y: rect.top });
361
+ setHovered(day);
362
+ };
363
+
364
+ return h(
365
+ 'div',
366
+ { ref: host },
367
+ h(
368
+ 'div',
369
+ {
370
+ className: 'dus-heat-wrap',
371
+ ref: wrap,
372
+ 'data-overflow': scrollable ? '' : undefined,
373
+ 'data-cell': String(cell),
374
+ },
375
+ h(
376
+ 'div',
377
+ { className: 'dus-heat-months', style: { gap: `${String(gap)}px` } },
378
+ ...grid.monthLabels.map((label, index) =>
379
+ h(
380
+ 'div',
381
+ {
382
+ className: 'dus-heat-month',
383
+ key: `m-${String(index)}`,
384
+ style: { width: `${String(cell)}px`, flex: `0 0 ${String(cell)}px` },
385
+ },
386
+ label.length === 0 ? null : h('span', null, label),
387
+ ),
388
+ ),
389
+ ),
390
+ h(
391
+ 'div',
392
+ { className: 'dus-heat' },
393
+ ...grid.columns.map((column, columnIndex) =>
394
+ h(
395
+ 'div',
396
+ { className: 'dus-heat-col', key: `c-${String(columnIndex)}`, style: { gap: `${String(gap)}px` } },
397
+ ...column.map((day) => {
398
+ const level = day.inRange ? levelOf(day.total, peak) : 0;
399
+ return h('div', {
400
+ key: day.key,
401
+ className: 'dus-heat-cell',
402
+ 'data-level': String(level),
403
+ style: {
404
+ width: `${String(cell)}px`,
405
+ height: `${String(cell)}px`,
406
+ ...(day.inRange ? {} : { opacity: 0.35 }),
407
+ },
408
+ onMouseEnter: (event) => {
409
+ show(day, event);
410
+ },
411
+ onMouseLeave: () => {
412
+ setAnchor(null);
413
+ setHovered(null);
414
+ },
415
+ 'aria-label': `${day.key}: ${formatTokensZh(day.total)} tokens`,
416
+ });
417
+ }),
418
+ ),
419
+ ),
420
+ ),
421
+ ),
422
+ h(
423
+ 'div',
424
+ { className: 'dus-heat-legend' },
425
+ scrollable ? h('span', { className: 'dus-heat-hint' }, '← 左右滑动 →') : null,
426
+ h('span', null, '少'),
427
+ ...[0, 1, 2, 3, 4].map((level) =>
428
+ h('div', { key: `l-${String(level)}`, className: 'dus-heat-cell', 'data-level': String(level), style: { width: '10px', height: '10px' } }),
429
+ ),
430
+ h('span', null, '多'),
431
+ ),
432
+ h(Tooltip, {
433
+ anchor: hovered === null ? null : anchor,
434
+ title: hovered?.key ?? '',
435
+ rows:
436
+ hovered === null
437
+ ? []
438
+ : [
439
+ `${formatTokensZh(hovered.total)} tokens`,
440
+ `${String(hovered.turns)}轮消息 · ${String(hovered.sessions)} 个会话`
441
+ ],
442
+ }),
443
+ );
444
+ }
445
+
446
+ function TokenTrend({ days, series, rangeDays }) {
447
+ const [hoverIndex, setHoverIndex] = useState(null);
448
+ const [hoverAnchor, setHoverAnchor] = useState(null);
449
+ const { host, width } = useMeasuredWidth();
450
+
451
+ const height = Math.round(Math.max(190, Math.min(260, 150 + width * 0.11)));
452
+ const padTop = Math.round(Math.max(12, Math.min(16, 6 + width * 0.01)));
453
+ const padRight = Math.round(Math.max(26, Math.min(32, 10 + width * 0.02)));
454
+ const padBottom = Math.round(Math.max(24, Math.min(30, 18 + width * 0.0115)));
455
+ const padLeft = Math.round(Math.max(38, Math.min(56, width * 0.054)));
456
+ const axisSize = Math.max(10, Math.min(11, 9.5 + width * 0.0015));
457
+
458
+ const plot = useMemo(() => {
459
+ const usableWidth = width - padLeft - padRight;
460
+ const usableHeight = height - padTop - padBottom;
461
+
462
+ const labels = buildDayWindow(days, rangeDays);
463
+ const count = labels.length;
464
+
465
+ const valueAt = (label, item) =>
466
+ label.entry?.byModel?.[item.key] ?? label.entry?.byModel?.[item.model] ?? 0;
467
+
468
+ let peak = 0;
469
+ for (const label of labels) {
470
+ for (const item of series) {
471
+ peak = Math.max(peak, valueAt(label, item));
472
+ }
473
+ }
474
+ if (peak <= 0) peak = 1;
475
+
476
+ const xOf = (index) => padLeft + (count === 1 ? usableWidth / 2 : (index / (count - 1)) * usableWidth);
477
+ const yOf = (value) => padTop + usableHeight - (value / peak) * usableHeight;
478
+
479
+ const lines = series.map((item, seriesIndex) => {
480
+ const points = labels.map((label, index) => ({
481
+ x: xOf(index),
482
+ y: yOf(valueAt(label, item)),
483
+ value: valueAt(label, item),
484
+ }));
485
+ return {
486
+ ...item,
487
+ color: SERIES_COLORS[seriesIndex % SERIES_COLORS.length],
488
+ points,
489
+ path: smoothPath(points),
490
+ value: points.reduce((sum, point) => sum + point.value, 0),
491
+ };
492
+ });
493
+
494
+ const gridLines = [0, 0.25, 0.5, 0.75, 1].map((ratio) => ({
495
+ y: padTop + usableHeight * ratio,
496
+ label: formatTokensZh(peak * (1 - ratio)),
497
+ }));
498
+
499
+ const ticks = pickDateTicks(labels, xOf, usableWidth, width);
500
+
501
+ return { count, labels, lines, gridLines, ticks, xOf, peak };
502
+ }, [days, series, rangeDays, width, height, padTop, padRight, padBottom, padLeft]);
503
+
504
+ const hover = hoverIndex === null ? null : (plot.labels[hoverIndex] ?? null);
505
+
506
+ return h(
507
+ 'div',
508
+ { className: 'dus-chart-host', ref: host, 'data-chart': 'tokens' },
509
+ h(
510
+ 'div',
511
+ { className: 'dus-legend' },
512
+ ...plot.lines.map((line) =>
513
+ h(
514
+ 'div',
515
+ { className: 'dus-legend-item', key: line.key },
516
+ h('span', { className: 'dus-legend-dot', style: { background: line.color } }),
517
+ h('span', null, line.model),
518
+ h('span', { className: 'dus-legend-src', title: `来源:${line.provider}` }, line.source),
519
+ h('span', { className: 'dus-legend-val' }, `${formatTokensZh(line.value)} tokens`),
520
+ ),
521
+ ),
522
+ ),
523
+ h(
524
+ 'svg',
525
+ {
526
+ viewBox: `0 0 ${String(width)} ${String(height)}`,
527
+ width: '100%',
528
+ height: String(height),
529
+ role: 'img',
530
+ 'aria-label': '每日 Token 趋势图',
531
+ onMouseLeave: () => {
532
+ setHoverIndex(null);
533
+ setHoverAnchor(null);
534
+ },
535
+ onMouseMove: (event) => {
536
+ const svg = event.currentTarget;
537
+ const local = pointerToViewBox(svg, event.clientX, event.clientY);
538
+ const usable = width - padLeft - padRight;
539
+ if (usable <= 0) return;
540
+ const index = Math.round(((local.x - padLeft) / usable) * (plot.count - 1));
541
+ const clamped = Math.max(0, Math.min(plot.count - 1, index));
542
+ setHoverIndex(clamped);
543
+ const point = plot.lines[0]?.points[clamped];
544
+ if (point !== undefined && point !== null) {
545
+ const screen = viewBoxToClient(svg, point.x, point.y);
546
+ setHoverAnchor({ x: screen.x, y: screen.y });
547
+ } else {
548
+ setHoverAnchor({ x: event.clientX, y: event.clientY });
549
+ }
550
+ },
551
+ },
552
+ ...plot.gridLines.map((line, index) =>
553
+ h('line', {
554
+ key: `g-${String(index)}`,
555
+ x1: String(padLeft),
556
+ x2: String(width - padRight),
557
+ y1: String(line.y),
558
+ y2: String(line.y),
559
+ stroke: 'var(--dsw-alias-border-l2)',
560
+ 'stroke-width': '1',
561
+ 'stroke-dasharray': index === plot.gridLines.length - 1 ? undefined : '3 5',
562
+ }),
563
+ ),
564
+ ...plot.gridLines.map((line, index) =>
565
+ h(
566
+ 'text',
567
+ {
568
+ key: `gl-${String(index)}`,
569
+ x: String(padLeft - 10),
570
+ y: String(line.y + 4),
571
+ 'text-anchor': 'end',
572
+ fill: 'var(--dsw-alias-label-secondary)',
573
+ 'font-size': String(axisSize),
574
+ },
575
+ line.label,
576
+ ),
577
+ ),
578
+ ...plot.lines.map((line) =>
579
+ h('path', {
580
+ key: `p-${line.key}`,
581
+ d: line.path,
582
+ fill: 'none',
583
+ stroke: line.color,
584
+ 'stroke-width': '2',
585
+ 'stroke-linecap': 'round',
586
+ 'stroke-linejoin': 'round',
587
+ }),
588
+ ),
589
+ hoverIndex !== null &&
590
+ h('line', {
591
+ x1: String(plot.xOf(hoverIndex)),
592
+ x2: String(plot.xOf(hoverIndex)),
593
+ y1: String(padTop),
594
+ y2: String(height - padBottom),
595
+ stroke: 'var(--dsw-alias-border-l3)',
596
+ 'stroke-width': '1',
597
+ }),
598
+ hoverIndex !== null &&
599
+ plot.lines.map((line) =>
600
+ h('circle', {
601
+ key: `d-${line.key}`,
602
+ cx: String(line.points[hoverIndex]?.x ?? 0),
603
+ cy: String(line.points[hoverIndex]?.y ?? 0),
604
+ r: '3.5',
605
+ fill: line.color,
606
+ stroke: 'var(--dsw-alias-bg-layer-2)',
607
+ 'stroke-width': '1.5',
608
+ }),
609
+ ),
610
+ ...plot.ticks.map((tick) =>
611
+ h(
612
+ 'text',
613
+ {
614
+ key: `t-${String(tick.index)}`,
615
+ x: String(tick.x),
616
+ y: String(height - 8),
617
+ 'text-anchor': 'middle',
618
+ fill: 'var(--dsw-alias-label-secondary)',
619
+ 'font-size': String(axisSize),
620
+ },
621
+ tick.text,
622
+ ),
623
+ ),
624
+ ),
625
+ hover !== undefined &&
626
+ hover !== null &&
627
+ h(Tooltip, {
628
+ anchor: hoverAnchor,
629
+ title: hover.key,
630
+ rows: plot.lines.map(
631
+ (line) => `${line.model} ${formatTokensZh(line.points[hoverIndex]?.value ?? 0)} tokens`,
632
+ ),
633
+ }),
634
+ );
635
+ }
636
+
637
+ function TokenCacheRate({ days, rangeDays }) {
638
+ const [hoverIndex, setHoverIndex] = useState(null);
639
+ const [hoverAnchor, setHoverAnchor] = useState(null);
640
+ const { host, width } = useMeasuredWidth();
641
+
642
+ const height = Math.round(Math.max(170, Math.min(220, 130 + width * 0.09)));
643
+ const padTop = Math.round(Math.max(12, Math.min(16, 6 + width * 0.01)));
644
+ const padRight = Math.round(Math.max(26, Math.min(32, 10 + width * 0.02)));
645
+ const padBottom = Math.round(Math.max(24, Math.min(28, 18 + width * 0.01)));
646
+ const padLeft = Math.round(Math.max(38, Math.min(50, width * 0.05)));
647
+ const axisSize = Math.max(10, Math.min(11, 9.5 + width * 0.0015));
648
+
649
+ const plot = useMemo(() => {
650
+ const usableWidth = width - padLeft - padRight;
651
+ const usableHeight = height - padTop - padBottom;
652
+ const labels = buildDayWindow(days, rangeDays);
653
+ const count = labels.length;
654
+
655
+ const rates = labels.map((label) => cacheHitRate(label.entry?.totals));
656
+ const values = rates.filter((rate) => rate !== null);
657
+
658
+ const low =
659
+ values.length === 0 ? 0 : Math.max(0, Math.min(95, Math.floor(Math.min(...values) / 5) * 5));
660
+ const high = 100;
661
+
662
+ const xOf = (index) => padLeft + (count === 1 ? usableWidth / 2 : (index / (count - 1)) * usableWidth);
663
+ const yOf = (rate) => padTop + usableHeight - ((rate - low) / (high - low)) * usableHeight;
664
+
665
+ const points = labels.map((label, index) => {
666
+ const rate = rates[index];
667
+ return rate === null ? null : { x: xOf(index), y: yOf(rate), value: rate };
668
+ });
669
+
670
+ const segments = [];
671
+ let segment = [];
672
+ for (const point of points) {
673
+ if (point === null) {
674
+ if (segment.length > 0) segments.push(segment);
675
+ segment = [];
676
+ } else {
677
+ segment.push(point);
678
+ }
679
+ }
680
+ if (segment.length > 0) segments.push(segment);
681
+
682
+ const steps = 5;
683
+ const gridLines = Array.from({ length: steps + 1 }, (_, index) => {
684
+ const value = high - ((high - low) / steps) * index;
685
+ return { y: yOf(value), label: `${String(Math.round(value))}%` };
686
+ });
687
+
688
+ const ticks = pickDateTicks(labels, xOf, usableWidth, width);
689
+
690
+ return { count, labels, rates, points, segments, gridLines, ticks, xOf, yOf, low, high, values };
691
+ }, [days, rangeDays, width, height, padTop, padRight, padBottom, padLeft]);
692
+
693
+ const empty = plot.values.length === 0;
694
+
695
+ const hover = hoverIndex === null ? null : (plot.labels[hoverIndex] ?? null);
696
+ const hoverRate = hoverIndex === null ? null : (plot.rates[hoverIndex] ?? null);
697
+ const hoverTotals = hover?.entry?.totals;
698
+ const hoverRead = hoverTotals?.cacheReadTokens ?? 0;
699
+ const hoverInput =
700
+ (hoverTotals?.cacheReadTokens ?? 0) +
701
+ (hoverTotals?.cacheWriteTokens ?? 0) +
702
+ (hoverTotals?.uncachedInputTokens ?? 0);
703
+ const color = 'var(--dus-cache-line, #39c07a)';
704
+
705
+ return h(
706
+ 'div',
707
+ { className: 'dus-chart-host', ref: host, 'data-chart': 'cache' },
708
+ empty &&
709
+ h(
710
+ 'div',
711
+ { className: 'dus-state', style: { padding: '40px 0' } },
712
+ h('div', { className: 'dus-state-desc' }, '这个时间范围内还没有输入 token 记录。'),
713
+ ),
714
+ !empty &&
715
+ h(
716
+ 'div',
717
+ { className: 'dus-legend' },
718
+ h(
719
+ 'div',
720
+ { className: 'dus-legend-item' },
721
+ h('span', { className: 'dus-legend-dot', style: { background: color } }),
722
+ h('span', null, '每日命中率'),
723
+ h('span', { className: 'dus-legend-val' }, `纵轴 ${String(plot.low)}–100%`),
724
+ ),
725
+ ),
726
+ !empty &&
727
+ h(
728
+ 'svg',
729
+ {
730
+ key: 'chart',
731
+ viewBox: `0 0 ${String(width)} ${String(height)}`,
732
+ width: '100%',
733
+ height: String(height),
734
+ role: 'img',
735
+ 'aria-label': '每日平均缓存命中率',
736
+ onMouseLeave: () => {
737
+ setHoverIndex(null);
738
+ setHoverAnchor(null);
739
+ },
740
+ onMouseMove: (event) => {
741
+ const svg = event.currentTarget;
742
+ const local = pointerToViewBox(svg, event.clientX, event.clientY);
743
+ const usable = width - padLeft - padRight;
744
+ if (usable <= 0) return;
745
+ const index = Math.round(((local.x - padLeft) / usable) * (plot.count - 1));
746
+ const clamped = Math.max(0, Math.min(plot.count - 1, index));
747
+ setHoverIndex(clamped);
748
+ const rate = plot.rates[clamped];
749
+ if (rate !== null) {
750
+ const screen = viewBoxToClient(svg, plot.xOf(clamped), plot.yOf(rate));
751
+ setHoverAnchor({ x: screen.x, y: screen.y });
752
+ } else {
753
+ setHoverAnchor({ x: event.clientX, y: event.clientY });
754
+ }
755
+ },
756
+ },
757
+ ...plot.gridLines.map((line, index) =>
758
+ h('line', {
759
+ key: `g-${String(index)}`,
760
+ x1: String(padLeft),
761
+ x2: String(width - padRight),
762
+ y1: String(line.y),
763
+ y2: String(line.y),
764
+ stroke: 'var(--dsw-alias-border-l2)',
765
+ 'stroke-width': '1',
766
+ 'stroke-dasharray': index === plot.gridLines.length - 1 ? undefined : '3 5',
767
+ }),
768
+ ),
769
+ ...plot.gridLines.map((line, index) =>
770
+ h(
771
+ 'text',
772
+ {
773
+ key: `gl-${String(index)}`,
774
+ x: String(padLeft - 10),
775
+ y: String(line.y + 4),
776
+ 'text-anchor': 'end',
777
+ fill: 'var(--dsw-alias-label-secondary)',
778
+ 'font-size': String(axisSize),
779
+ },
780
+ line.label,
781
+ ),
782
+ ),
783
+ ...plot.segments.map((segment, index) =>
784
+ segment.length > 1
785
+ ? h('path', {
786
+ key: `s-${String(index)}`,
787
+ d: smoothPath(segment),
788
+ fill: 'none',
789
+ stroke: color,
790
+ 'stroke-width': '2',
791
+ 'stroke-linecap': 'round',
792
+ 'stroke-linejoin': 'round',
793
+ })
794
+ : h('circle', {
795
+ key: `s-${String(index)}`,
796
+ cx: String(segment[0].x),
797
+ cy: String(segment[0].y),
798
+ r: '2.5',
799
+ fill: color,
800
+ }),
801
+ ),
802
+ plot.count <= 45 &&
803
+ plot.points.map((point, index) =>
804
+ point === null
805
+ ? null
806
+ : h('circle', {
807
+ key: `d-${String(index)}`,
808
+ cx: String(point.x),
809
+ cy: String(point.y),
810
+ r: '1.8',
811
+ fill: color,
812
+ opacity: '0.75',
813
+ }),
814
+ ),
815
+ hoverIndex !== null &&
816
+ h('line', {
817
+ x1: String(plot.xOf(hoverIndex)),
818
+ x2: String(plot.xOf(hoverIndex)),
819
+ y1: String(padTop),
820
+ y2: String(height - padBottom),
821
+ stroke: 'var(--dsw-alias-border-l3)',
822
+ 'stroke-width': '1',
823
+ }),
824
+ hoverIndex !== null &&
825
+ hoverRate !== null &&
826
+ h('circle', {
827
+ cx: String(plot.xOf(hoverIndex)),
828
+ cy: String(plot.yOf(hoverRate)),
829
+ r: '3.5',
830
+ fill: color,
831
+ stroke: 'var(--dsw-alias-bg-layer-2)',
832
+ 'stroke-width': '1.5',
833
+ }),
834
+ ...plot.ticks.map((tick) =>
835
+ h(
836
+ 'text',
837
+ {
838
+ key: `t-${String(tick.index)}`,
839
+ x: String(tick.x),
840
+ y: String(height - 8),
841
+ 'text-anchor': 'middle',
842
+ fill: 'var(--dsw-alias-label-secondary)',
843
+ 'font-size': String(axisSize),
844
+ },
845
+ tick.text,
846
+ ),
847
+ ),
848
+ ),
849
+ hover !== null &&
850
+ h(Tooltip, {
851
+ anchor: hoverAnchor,
852
+ title: hover.key,
853
+ rows:
854
+ hoverRate === null
855
+ ? ['当天没有输入 token 记录']
856
+ : [
857
+ `缓存命中率 ${formatPercent(hoverRate)}`,
858
+ `缓存读取 ${formatTokensZh(hoverRead)} · 输入合计 ${formatTokensZh(hoverInput)}`,
859
+ ],
860
+ }),
861
+ );
862
+ }
863
+
864
+ function smoothPath(points) {
865
+ if (points.length === 0) return '';
866
+ if (points.length === 1) return `M ${points[0].x} ${points[0].y}`;
867
+
868
+ let path = `M ${points[0].x} ${points[0].y}`;
869
+ for (let index = 0; index < points.length - 1; index += 1) {
870
+ const current = points[index];
871
+ const next = points[index + 1];
872
+ const midX = (current.x + next.x) / 2;
873
+ path += ` C ${midX} ${current.y}, ${midX} ${next.y}, ${next.x} ${next.y}`;
874
+ }
875
+ return path;
876
+ }
877
+
878
+ function pointerToViewBox(svg, clientX, clientY) {
879
+ const ctm = typeof svg.getScreenCTM === 'function' ? svg.getScreenCTM() : null;
880
+ if (ctm !== null && typeof svg.createSVGPoint === 'function') {
881
+ const point = svg.createSVGPoint();
882
+ point.x = clientX;
883
+ point.y = clientY;
884
+ const local = point.matrixTransform(ctm.inverse());
885
+ return { x: local.x, y: local.y };
886
+ }
887
+
888
+ const rect = svg.getBoundingClientRect();
889
+ const viewBox = svg.viewBox.baseVal;
890
+ if (viewBox.width <= 0 || viewBox.height <= 0 || rect.width <= 0 || rect.height <= 0) {
891
+ return { x: 0, y: 0 };
892
+ }
893
+ const scale = Math.min(rect.width / viewBox.width, rect.height / viewBox.height);
894
+ const offsetX = rect.left + (rect.width - viewBox.width * scale) / 2;
895
+ const offsetY = rect.top + (rect.height - viewBox.height * scale) / 2;
896
+ return {
897
+ x: viewBox.x + (clientX - offsetX) / scale,
898
+ y: viewBox.y + (clientY - offsetY) / scale,
899
+ };
900
+ }
901
+
902
+ function viewBoxToClient(svg, x, y) {
903
+ const ctm = typeof svg.getScreenCTM === 'function' ? svg.getScreenCTM() : null;
904
+ if (ctm !== null && typeof svg.createSVGPoint === 'function') {
905
+ const point = svg.createSVGPoint();
906
+ point.x = x;
907
+ point.y = y;
908
+ const screen = point.matrixTransform(ctm);
909
+ return { x: screen.x, y: screen.y };
910
+ }
911
+
912
+ const rect = svg.getBoundingClientRect();
913
+ const viewBox = svg.viewBox.baseVal;
914
+ if (viewBox.width <= 0 || viewBox.height <= 0) return { x: rect.left, y: rect.top };
915
+ const scale = Math.min(rect.width / viewBox.width, rect.height / viewBox.height);
916
+ const offsetX = rect.left + (rect.width - viewBox.width * scale) / 2;
917
+ const offsetY = rect.top + (rect.height - viewBox.height * scale) / 2;
918
+ return {
919
+ x: offsetX + (x - viewBox.x) * scale,
920
+ y: offsetY + (y - viewBox.y) * scale,
921
+ };
922
+ }
923
+
924
+ function ModelDonut({ models }) {
925
+ const [activeKey, setActiveKey] = useState(null);
926
+ const [tipAnchor, setTipAnchor] = useState(null);
927
+ const size = 220;
928
+ const stroke = 26;
929
+ const radius = (size - stroke) / 2;
930
+ const circumference = 2 * Math.PI * radius;
931
+
932
+ const total = models.reduce((sum, model) => sum + model.total, 0);
933
+
934
+ const arcs = useMemo(() => {
935
+ let offset = 0;
936
+ return models.map((model, index) => {
937
+ const fraction = total > 0 ? model.total / total : 0;
938
+ const length = fraction * circumference;
939
+ const arc = {
940
+ ...model,
941
+ key: `${model.provider}/${model.model}`,
942
+ color: SERIES_COLORS[index % SERIES_COLORS.length],
943
+ dash: `${String(length)} ${String(circumference - length)}`,
944
+ offset: -offset,
945
+ percent: total > 0 ? (model.total / total) * 100 : 0,
946
+ };
947
+ offset += length;
948
+ return arc;
949
+ });
950
+ }, [models, total, circumference]);
951
+
952
+ if (total <= 0) {
953
+ return h(
954
+ 'div',
955
+ { className: 'dus-state', style: { padding: '40px 0' } },
956
+ h('div', { className: 'dus-state-desc' }, '这个时间范围内还没有模型用量。'),
957
+ );
958
+ }
959
+
960
+ const active = arcs.find((arc) => arc.key === activeKey) ?? null;
961
+
962
+ return h(
963
+ 'div',
964
+ { className: 'dus-split' },
965
+ h(
966
+ 'div',
967
+ { className: 'dus-donut-wrap' },
968
+ h(
969
+ 'svg',
970
+ {
971
+ width: String(size),
972
+ height: String(size),
973
+ viewBox: `0 0 ${String(size)} ${String(size)}`,
974
+ role: 'img',
975
+ 'aria-label': '模型用量',
976
+ onMouseLeave: () => {
977
+ setActiveKey(null);
978
+ setTipAnchor(null);
979
+ },
980
+ },
981
+ h('circle', {
982
+ cx: String(size / 2),
983
+ cy: String(size / 2),
984
+ r: String(radius),
985
+ fill: 'none',
986
+ stroke: 'var(--dus-subtle-fill)',
987
+ 'stroke-width': String(stroke),
988
+ }),
989
+ ...arcs.map((arc) =>
990
+ h('circle', {
991
+ key: arc.key,
992
+ cx: String(size / 2),
993
+ cy: String(size / 2),
994
+ r: String(radius),
995
+ fill: 'none',
996
+ stroke: arc.color,
997
+ 'stroke-width': String(activeKey === null || activeKey === arc.key ? stroke : stroke - 8),
998
+ 'stroke-dasharray': arc.dash,
999
+ 'stroke-dashoffset': String(arc.offset),
1000
+ transform: `rotate(-90 ${String(size / 2)} ${String(size / 2)})`,
1001
+ 'stroke-linecap': 'butt',
1002
+ opacity: activeKey === null || activeKey === arc.key ? '1' : '0.35',
1003
+ style: { transition: 'stroke-width 120ms ease, opacity 120ms ease', cursor: 'pointer' },
1004
+ onMouseEnter: (event) => {
1005
+ setActiveKey(arc.key);
1006
+ setTipAnchor({ x: event.clientX, y: event.clientY });
1007
+ },
1008
+ onMouseMove: (event) => {
1009
+ setTipAnchor({ x: event.clientX, y: event.clientY });
1010
+ },
1011
+ }),
1012
+ ),
1013
+ ),
1014
+ h(
1015
+ 'div',
1016
+ { className: 'dus-donut-center' },
1017
+ h('div', { className: 'dus-donut-total' }, formatTokensZh(total)),
1018
+ h('div', { className: 'dus-donut-unit' }, 'tokens'),
1019
+ ),
1020
+ ),
1021
+ h(
1022
+ 'div',
1023
+ { className: 'dus-model-list' },
1024
+ ...arcs.map((arc) =>
1025
+ h(
1026
+ 'div',
1027
+ {
1028
+ className: 'dus-model-row',
1029
+ key: arc.key,
1030
+ 'data-active': activeKey === arc.key ? '' : undefined,
1031
+ onMouseEnter: (event) => {
1032
+ setActiveKey(arc.key);
1033
+ setTipAnchor({ x: event.clientX, y: event.clientY });
1034
+ },
1035
+ onMouseMove: (event) => {
1036
+ setTipAnchor({ x: event.clientX, y: event.clientY });
1037
+ },
1038
+ onMouseLeave: () => {
1039
+ setActiveKey(null);
1040
+ setTipAnchor(null);
1041
+ },
1042
+ },
1043
+ h('span', { className: 'dus-model-dot', style: { background: arc.color } }),
1044
+ h(
1045
+ 'div',
1046
+ { className: 'dus-model-main' },
1047
+ h(
1048
+ 'div',
1049
+ { className: 'dus-model-name', title: arc.model },
1050
+ arc.model,
1051
+ h('span', { className: 'dus-model-src', title: `来源:${arc.provider}` }, arc.source),
1052
+ ),
1053
+ h(
1054
+ 'div',
1055
+ { className: 'dus-model-meta' },
1056
+ `${String(arc.sessions)} 个会话 · ${String(arc.turns)} 轮`,
1057
+ ),
1058
+ ),
1059
+ h(
1060
+ 'div',
1061
+ { className: 'dus-model-right' },
1062
+ h('div', { className: 'dus-model-tokens' }, `${formatTokensZh(arc.total)} tokens`),
1063
+ h('div', { className: 'dus-model-pct' }, formatPercent(arc.percent)),
1064
+ ),
1065
+ ),
1066
+ ),
1067
+ ),
1068
+ h(Tooltip, {
1069
+ anchor: active === null ? null : tipAnchor,
1070
+ title: active?.model ?? '',
1071
+ rows:
1072
+ active === null
1073
+ ? []
1074
+ : [
1075
+ `来源:${active.source}`,
1076
+ `${formatPercent(active.percent)} · ${formatTokensZh(active.total)} tokens`,
1077
+ `${String(active.sessions)} 个会话 · ${String(active.turns)} 轮`,
1078
+ ],
1079
+ }),
1080
+ );
1081
+ }
1082
+
1083
+ function ModelUsageChart({ days, models, rangeDays }) {
1084
+ const [granularity, setGranularity] = useState('day');
1085
+ const [hoverIndex, setHoverIndex] = useState(null);
1086
+ const [hoverAnchor, setHoverAnchor] = useState(null);
1087
+ const { host, width } = useMeasuredWidth();
1088
+
1089
+ const height = Math.round(Math.max(200, Math.min(300, 150 + width * 0.14)));
1090
+ const padTop = Math.round(Math.max(12, Math.min(16, 6 + width * 0.01)));
1091
+ const padRight = Math.round(Math.max(26, Math.min(32, 10 + width * 0.02)));
1092
+ const padBottom = Math.round(Math.max(24, Math.min(30, 18 + width * 0.0115)));
1093
+ const padLeft = Math.round(Math.max(40, Math.min(56, width * 0.054)));
1094
+ const axisSize = Math.max(10, Math.min(11, 9.5 + width * 0.0015));
1095
+
1096
+ const plot = useMemo(() => {
1097
+ const series = models.map((model, index) => ({
1098
+ key: `${model.provider}/${model.model}`,
1099
+ model: model.model,
1100
+ provider: model.provider,
1101
+ source: model.source,
1102
+ color: SERIES_COLORS[index % SERIES_COLORS.length],
1103
+ }));
1104
+ const buckets = buildUsageBuckets(days, rangeDays, granularity);
1105
+ const count = buckets.length;
1106
+ const values = buckets.map((bucket) =>
1107
+ series.reduce((sum, item) => sum + (bucket.byModel.get(item.key) ?? 0), 0),
1108
+ );
1109
+ const peak = Math.max(1, ...values);
1110
+ const usableWidth = Math.max(1, width - padLeft - padRight);
1111
+ const usableHeight = Math.max(1, height - padTop - padBottom);
1112
+ const slot = usableWidth / Math.max(1, count);
1113
+ const barWidth = Math.max(3, Math.min(44, slot * 0.62));
1114
+
1115
+ const xOf = (index) => padLeft + slot * index + slot / 2;
1116
+ const yOf = (value) => padTop + usableHeight - (value / peak) * usableHeight;
1117
+
1118
+ const gridLines = [0, 0.25, 0.5, 0.75, 1].map((ratio) => ({
1119
+ y: padTop + usableHeight * ratio,
1120
+ label: formatTokensZh(peak * (1 - ratio)),
1121
+ }));
1122
+
1123
+ const bars = buckets.map((bucket, index) => {
1124
+ let cumulative = 0;
1125
+ const segments = [];
1126
+ for (const item of series) {
1127
+ const value = bucket.byModel.get(item.key) ?? 0;
1128
+ if (value <= 0) continue;
1129
+ const bottom = yOf(cumulative);
1130
+ cumulative += value;
1131
+ const top = yOf(cumulative);
1132
+ segments.push({
1133
+ key: `${bucket.key}/${item.key}`,
1134
+ color: item.color,
1135
+ x: xOf(index) - barWidth / 2,
1136
+ y: top,
1137
+ width: barWidth,
1138
+ height: Math.max(0.8, bottom - top),
1139
+ });
1140
+ }
1141
+ return {
1142
+ index,
1143
+ key: bucket.key,
1144
+ title: bucket.title,
1145
+ total: cumulative,
1146
+ x: xOf(index),
1147
+ top: yOf(cumulative),
1148
+ segments,
1149
+ };
1150
+ });
1151
+
1152
+ const ticks = pickDateTicks(buckets, xOf, usableWidth, width);
1153
+
1154
+ return { buckets, series, values, peak, usableWidth, usableHeight, slot, bars, gridLines, ticks, xOf, yOf };
1155
+ }, [days, models, rangeDays, granularity, width, height, padTop, padRight, padBottom, padLeft]);
1156
+
1157
+ const empty = models.length === 0 || plot.values.every((value) => value <= 0);
1158
+ const hover = hoverIndex === null ? null : (plot.bars[hoverIndex] ?? null);
1159
+ const hoverRows = [];
1160
+ if (hover !== null) {
1161
+ hoverRows.push(`总计 ${formatTokensZh(hover.total)} tokens`);
1162
+ for (const item of plot.series) {
1163
+ const value = plot.buckets[hover.index].byModel.get(item.key) ?? 0;
1164
+ if (value > 0) hoverRows.push(`${item.model} ${formatTokensZh(value)} tokens`);
1165
+ }
1166
+ }
1167
+
1168
+ const chooseGranularity = (next) => {
1169
+ setGranularity(next);
1170
+ setHoverIndex(null);
1171
+ setHoverAnchor(null);
1172
+ };
1173
+
1174
+ return h(
1175
+ 'div',
1176
+ { className: 'dus-model-trend' },
1177
+ models.length > 0 &&
1178
+ h(
1179
+ 'div',
1180
+ { className: 'dus-bars-head' },
1181
+ h(
1182
+ 'div',
1183
+ { className: 'dus-bars-heading' },
1184
+ h('h3', { className: 'dus-bars-title' }, '各模型用量趋势'),
1185
+ h('span', { className: 'dus-bars-note' }, '堆叠高度 = Token 总量 · 颜色对应上方模型'),
1186
+ ),
1187
+ h(
1188
+ 'div',
1189
+ {
1190
+ className: 'dus-seg dus-seg-sm dus-trend-toggle',
1191
+ role: 'tablist',
1192
+ 'aria-label': '聚合粒度',
1193
+ },
1194
+ ...[
1195
+ ['day', '每日'],
1196
+ ['week', '每周'],
1197
+ ].map(([id, label]) =>
1198
+ h(
1199
+ 'button',
1200
+ {
1201
+ key: id,
1202
+ type: 'button',
1203
+ role: 'tab',
1204
+ className: 'dus-seg-btn',
1205
+ 'data-active': granularity === id ? '' : undefined,
1206
+ 'aria-selected': granularity === id,
1207
+ onClick: () => {
1208
+ chooseGranularity(id);
1209
+ },
1210
+ },
1211
+ label,
1212
+ ),
1213
+ ),
1214
+ ),
1215
+ ),
1216
+ h(
1217
+ 'div',
1218
+ { className: 'dus-chart-host', ref: host, 'data-chart': 'models' },
1219
+ empty
1220
+ ? models.length > 0 &&
1221
+ h(
1222
+ 'div',
1223
+ { className: 'dus-state', style: { padding: '40px 0' } },
1224
+ h('div', { className: 'dus-state-desc' }, '这个时间范围内还没有模型用量。'),
1225
+ )
1226
+ : [
1227
+ h(
1228
+ 'svg',
1229
+ {
1230
+ key: 'chart',
1231
+ viewBox: `0 0 ${String(width)} ${String(height)}`,
1232
+ width: '100%',
1233
+ height: String(height),
1234
+ role: 'img',
1235
+ 'aria-label': '各模型用量趋势',
1236
+ onMouseLeave: () => {
1237
+ setHoverIndex(null);
1238
+ setHoverAnchor(null);
1239
+ },
1240
+ onMouseMove: (event) => {
1241
+ const svg = event.currentTarget;
1242
+ const local = pointerToViewBox(svg, event.clientX, event.clientY);
1243
+ if (plot.bars.length === 0) return;
1244
+ const index = Math.floor((local.x - padLeft) / plot.slot);
1245
+ const clamped = Math.max(0, Math.min(plot.bars.length - 1, index));
1246
+ setHoverIndex(clamped);
1247
+ const bar = plot.bars[clamped];
1248
+ if (bar.total > 0) {
1249
+ const screen = viewBoxToClient(svg, bar.x, bar.top);
1250
+ setHoverAnchor({ x: screen.x, y: screen.y });
1251
+ } else {
1252
+ setHoverAnchor({ x: event.clientX, y: event.clientY });
1253
+ }
1254
+ },
1255
+ },
1256
+ ...plot.gridLines.map((line, index) =>
1257
+ h('line', {
1258
+ key: `g-${String(index)}`,
1259
+ x1: String(padLeft),
1260
+ x2: String(width - padRight),
1261
+ y1: String(line.y),
1262
+ y2: String(line.y),
1263
+ stroke: 'var(--dsw-alias-border-l2)',
1264
+ 'stroke-width': '1',
1265
+ 'stroke-dasharray': index === plot.gridLines.length - 1 ? undefined : '3 5',
1266
+ }),
1267
+ ),
1268
+ ...plot.gridLines.map((line, index) =>
1269
+ h(
1270
+ 'text',
1271
+ {
1272
+ key: `gl-${String(index)}`,
1273
+ x: String(padLeft - 10),
1274
+ y: String(line.y + 4),
1275
+ 'text-anchor': 'end',
1276
+ fill: 'var(--dsw-alias-label-secondary)',
1277
+ 'font-size': String(axisSize),
1278
+ },
1279
+ line.label,
1280
+ ),
1281
+ ),
1282
+ hoverIndex !== null &&
1283
+ h('rect', {
1284
+ x: String(padLeft + plot.slot * hoverIndex + 1),
1285
+ y: String(padTop),
1286
+ width: String(Math.max(0, plot.slot - 2)),
1287
+ height: String(plot.usableHeight),
1288
+ rx: '3',
1289
+ fill: 'var(--dsw-alias-bg-layer-3)',
1290
+ opacity: '0.35',
1291
+ }),
1292
+ ...plot.bars.map((bar) =>
1293
+ h(
1294
+ 'g',
1295
+ { key: bar.key, className: 'dus-stack-bar', 'data-bucket': String(bar.index) },
1296
+ ...bar.segments.map((segment) =>
1297
+ h('rect', {
1298
+ key: segment.key,
1299
+ className: 'dus-stack-seg',
1300
+ x: String(segment.x),
1301
+ y: String(segment.y),
1302
+ width: String(segment.width),
1303
+ height: String(segment.height),
1304
+ rx: '1',
1305
+ fill: segment.color,
1306
+ }),
1307
+ ),
1308
+ ),
1309
+ ),
1310
+ ...plot.ticks.map((tick) =>
1311
+ h(
1312
+ 'text',
1313
+ {
1314
+ key: `t-${String(tick.index)}`,
1315
+ x: String(tick.x),
1316
+ y: String(height - 8),
1317
+ 'text-anchor': 'middle',
1318
+ fill: 'var(--dsw-alias-label-secondary)',
1319
+ 'font-size': String(axisSize),
1320
+ },
1321
+ tick.text,
1322
+ ),
1323
+ ),
1324
+ ),
1325
+ h(Tooltip, {
1326
+ key: 'tip',
1327
+ anchor: hover === null ? null : hoverAnchor,
1328
+ title: hover?.title ?? '',
1329
+ rows: hoverRows,
1330
+ }),
1331
+ ],
1332
+ ),
1333
+ );
1334
+ }
1335
+ return { TokenHeatmap, TokenTrend, TokenCacheRate, ModelDonut, ModelUsageChart };
1336
+ })();
1337
+
1338
+ // ---- src/client/dashboard.js ----
1339
+ const __m2 = (() => {
1340
+ const { createElement: h, useCallback: useCallback, useEffect: useEffect, useMemo: useMemo, useRef: useRef, useState: useState } = require("react");
1341
+ const { RANGE_PRESETS: RANGE_PRESETS, USAGE_STATS_PATH: USAGE_STATS_PATH, formatDuration: formatDuration, formatPercent: formatPercent, formatTokensZh: formatTokensZh, isUsageDocument: isUsageDocument } = __m0;
1342
+ const { ModelDonut: ModelDonut, ModelUsageChart: ModelUsageChart, TokenCacheRate: TokenCacheRate, TokenHeatmap: TokenHeatmap, TokenTrend: TokenTrend } = __m1;
1343
+
1344
+ const POLL_INTERVAL_MS = 30000;
1345
+
1346
+ async function fetchUsage({ range, signal }) {
1347
+ const query = range === null ? 'all' : range;
1348
+ const response = await fetch(`${USAGE_STATS_PATH}?range=${encodeURIComponent(query)}`, {
1349
+ method: 'GET',
1350
+ credentials: 'same-origin',
1351
+ headers: { accept: 'application/json' },
1352
+ signal,
1353
+ });
1354
+ if (!response.ok) throw new Error(`HTTP ${String(response.status)}`);
1355
+ const body = await response.json();
1356
+ if (!isUsageDocument(body)) throw new Error('malformed usage document');
1357
+ return body;
1358
+ }
1359
+
1360
+ function useUsageDocument() {
1361
+ const [rangeId, setRangeId] = useState('30d');
1362
+ const [state, setState] = useState({ status: 'loading', document: null, error: null });
1363
+ const [reloadToken, setReloadToken] = useState(0);
1364
+ const inFlight = useRef(null);
1365
+
1366
+ const range = useMemo(() => {
1367
+ const preset = RANGE_PRESETS.find((item) => item.id === rangeId);
1368
+ return preset === undefined ? 30 : preset.days;
1369
+ }, [rangeId]);
1370
+
1371
+ useEffect(() => {
1372
+ const controller = new AbortController();
1373
+ let active = true;
1374
+ setState((previous) => ({ ...previous, status: previous.document === null ? 'loading' : 'refreshing' }));
1375
+
1376
+ void (async () => {
1377
+ try {
1378
+ const document = await fetchUsage({ range, signal: controller.signal });
1379
+ if (!active) return;
1380
+ setState({ status: 'ready', document, error: null });
1381
+ } catch (error) {
1382
+ if (!active || controller.signal.aborted) return;
1383
+ setState((previous) => ({
1384
+ status: 'error',
1385
+ document: previous.document,
1386
+ error: error instanceof Error ? error.message : String(error),
1387
+ }));
1388
+ }
1389
+ })();
1390
+
1391
+ return () => {
1392
+ active = false;
1393
+ controller.abort();
1394
+ };
1395
+ }, [range, reloadToken]);
1396
+
1397
+ useEffect(() => {
1398
+ const tick = () => {
1399
+ if (document.visibilityState !== 'visible') return;
1400
+ setReloadToken((value) => value + 1);
1401
+ };
1402
+ const timer = window.setInterval(tick, POLL_INTERVAL_MS);
1403
+ return () => {
1404
+ window.clearInterval(timer);
1405
+ };
1406
+ }, []);
1407
+
1408
+ const refresh = useCallback(() => {
1409
+ if (inFlight.current !== null) return;
1410
+ inFlight.current = true;
1411
+ setReloadToken((value) => value + 1);
1412
+ window.setTimeout(() => {
1413
+ inFlight.current = null;
1414
+ }, 600);
1415
+ }, []);
1416
+
1417
+ return { rangeId, setRangeId, range, state, refresh };
1418
+ }
1419
+
1420
+ function StatCard({ value, label, title }) {
1421
+ return h(
1422
+ 'div',
1423
+ { className: 'dus-card', title },
1424
+ h('div', { className: 'dus-card-value' }, value),
1425
+ h('div', { className: 'dus-card-label' }, label),
1426
+ );
1427
+ }
1428
+
1429
+ function CacheHitCard({ totals }) {
1430
+ const rate = typeof totals?.cacheHitRate === 'number' ? totals.cacheHitRate : null;
1431
+ const cached = totals?.cacheReadTokens ?? 0;
1432
+ const written = totals?.cacheWriteTokens ?? 0;
1433
+ const uncached = totals?.uncachedInputTokens ?? 0;
1434
+ const input = cached + written + uncached;
1435
+
1436
+ const detail =
1437
+ rate === null
1438
+ ? '这个范围内还没有输入 token 记录。'
1439
+ : [
1440
+ `缓存读取 ${formatTokensZh(cached)}`,
1441
+ `缓存写入 ${formatTokensZh(written)}`,
1442
+ `未缓存 ${formatTokensZh(uncached)}`,
1443
+ `输入合计 ${formatTokensZh(input)}`,
1444
+ ].join(' · ');
1445
+
1446
+ return h(
1447
+ 'div',
1448
+ { className: 'dus-card', title: detail },
1449
+ h(
1450
+ 'div',
1451
+ { className: 'dus-card-value' },
1452
+ rate === null ? '—' : formatPercent(rate),
1453
+ ),
1454
+ h('div', { className: 'dus-card-label' }, '缓存命中率'),
1455
+ rate !== null &&
1456
+ h(
1457
+ 'div',
1458
+ { className: 'dus-meter', role: 'img', 'aria-label': `缓存命中率 ${formatPercent(rate)}` },
1459
+ h('div', { className: 'dus-meter-fill', style: { width: `${String(Math.min(100, rate))}%` } }),
1460
+ ),
1461
+ );
1462
+ }
1463
+
1464
+ function rangeLabel(id) {
1465
+ if (id === '7d') return '近 7 日';
1466
+ if (id === '30d') return '近 30 日';
1467
+ if (id === '90d') return '近 90 日';
1468
+ return '全部';
1469
+ }
1470
+
1471
+ function StateView({ status, error, onRetry }) {
1472
+ if (status === 'loading') {
1473
+ return h(
1474
+ 'div',
1475
+ { className: 'dus-state' },
1476
+ h('div', { className: 'dus-state-icon' }, h(SpinnerIcon, { size: 18 })),
1477
+ h('div', { className: 'dus-state-desc' }, '正在统计用量…'),
1478
+ );
1479
+ }
1480
+ return h(
1481
+ 'div',
1482
+ { className: 'dus-state' },
1483
+ h(
1484
+ 'div',
1485
+ { className: 'dus-state-icon' },
1486
+ h(
1487
+ 'svg',
1488
+ { width: '18', height: '18', viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', 'stroke-width': '1.8', 'stroke-linecap': 'round' },
1489
+ h('circle', { cx: '12', cy: '12', r: '9' }),
1490
+ h('path', { d: 'M12 8v5' }),
1491
+ h('path', { d: 'M12 16.5v.01' }),
1492
+ ),
1493
+ ),
1494
+ h('div', { className: 'dus-state-title' }, '无法读取用量统计'),
1495
+ h('div', { className: 'dus-state-desc' }, error ?? '宿主未返回可用的统计数据。'),
1496
+ h(
1497
+ 'button',
1498
+ { type: 'button', className: 'dus-btn dus-btn-primary', onClick: onRetry },
1499
+ '重试',
1500
+ ),
1501
+ );
1502
+ }
1503
+
1504
+ function SpinnerIcon({ size = 14 }) {
1505
+ return h(
1506
+ 'svg',
1507
+ { className: 'dus-spin', width: String(size), height: String(size), viewBox: '0 0 24 24', fill: 'none', 'aria-hidden': 'true' },
1508
+ h('path', {
1509
+ d: 'M12 3a9 9 0 1 0 9 9',
1510
+ stroke: 'currentColor',
1511
+ 'stroke-width': '2.2',
1512
+ 'stroke-linecap': 'round',
1513
+ }),
1514
+ );
1515
+ }
1516
+
1517
+ function RefreshButton({ onRefresh, busy }) {
1518
+ return h(
1519
+ 'button',
1520
+ {
1521
+ type: 'button',
1522
+ className: 'dus-btn dus-refresh',
1523
+ onClick: onRefresh,
1524
+ 'aria-label': '刷新用量统计',
1525
+ title: '刷新',
1526
+ },
1527
+ busy ? h(SpinnerIcon, { size: 14 }) : h(RefreshIcon, { size: 14 }),
1528
+ h('span', null, busy ? '刷新中' : '刷新'),
1529
+ );
1530
+ }
1531
+
1532
+ function RefreshIcon({ size = 14 }) {
1533
+ return h(
1534
+ 'svg',
1535
+ { width: String(size), height: String(size), viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', 'stroke-width': '2', 'stroke-linecap': 'round', 'stroke-linejoin': 'round', 'aria-hidden': 'true' },
1536
+ h('path', { d: 'M21 12a9 9 0 1 1-2.64-6.36' }),
1537
+ h('path', { d: 'M21 3v6h-6' }),
1538
+ );
1539
+ }
1540
+
1541
+ function UsageDashboard() {
1542
+ const { rangeId, setRangeId, range, state, refresh } = useUsageDocument();
1543
+ const document_ = state.document;
1544
+
1545
+ const modelsWithUsage = useMemo(
1546
+ () => (document_?.models ?? []).filter((model) => model.total > 0),
1547
+ [document_],
1548
+ );
1549
+
1550
+ const series = useMemo(
1551
+ () =>
1552
+ modelsWithUsage.map((model) => ({
1553
+ key: `${model.provider}/${model.model}`,
1554
+ model: model.model,
1555
+ provider: model.provider,
1556
+ source: model.source,
1557
+ })),
1558
+ [modelsWithUsage],
1559
+ );
1560
+
1561
+ const days = document_?.days ?? [];
1562
+ const now = document_?.generatedAt ?? Date.now();
1563
+
1564
+ return h(
1565
+ 'div',
1566
+ { className: 'dus-root' },
1567
+ h(
1568
+ 'div',
1569
+ { className: 'dus-shell' },
1570
+ h(
1571
+ 'div',
1572
+ { className: 'dus-inner' },
1573
+ h(
1574
+ 'div',
1575
+ { className: 'dus-head' },
1576
+ h('h1', { className: 'dus-title' }, '使用统计'),
1577
+ h('span', { className: 'dus-badge' }, '应用用量'),
1578
+ document_ !== null &&
1579
+ h(
1580
+ 'span',
1581
+ { className: 'dus-live' },
1582
+ h('span', { className: 'dus-live-dot', style: { background: 'var(--dsw-alias-state-success-primary)' } }),
1583
+ `${String(document_.scope.sessionCount)} 个会话`,
1584
+ ),
1585
+ ),
1586
+
1587
+ state.status === 'error' && document_ === null
1588
+ ? h(StateView, { status: state.status, error: state.error, onRetry: refresh })
1589
+ : [
1590
+ h(
1591
+ 'div',
1592
+ { className: 'dus-cards', key: 'cards' },
1593
+ h(StatCard, { value: formatTokensZh(document_?.totals.total ?? 0), label: '累计 Token 数' }),
1594
+ h(StatCard, {
1595
+ value: formatTokensZh(document_?.totals.peakDayTokens ?? 0),
1596
+ label: '单日峰值 Token 数',
1597
+ title:
1598
+ document_?.totals.peakDay == null
1599
+ ? undefined
1600
+ : `用量最高的一天:${document_.totals.peakDay}`,
1601
+ }),
1602
+ h(StatCard, {
1603
+ value: formatDuration(document_?.totals.longestSessionMs ?? 0),
1604
+ label: '最长聊天时长',
1605
+ }),
1606
+ h(StatCard, {
1607
+ value: `${String(document_?.totals.currentStreak ?? 0)} 天`,
1608
+ label: '当前连续天数',
1609
+ }),
1610
+ h(StatCard, {
1611
+ value: `${String(document_?.totals.longestStreak ?? 0)} 天`,
1612
+ label: '最长连续天数',
1613
+ }),
1614
+ h(CacheHitCard, { totals: document_?.totals }),
1615
+ ),
1616
+
1617
+ h(
1618
+ 'div',
1619
+ { className: 'dus-range-row', key: 'range' },
1620
+ h('span', { className: 'dus-range-label' }, '时间范围'),
1621
+ h(
1622
+ 'div',
1623
+ { className: 'dus-seg', role: 'tablist', 'aria-label': '时间范围' },
1624
+ ...RANGE_PRESETS.map((preset) =>
1625
+ h(
1626
+ 'button',
1627
+ {
1628
+ key: preset.id,
1629
+ type: 'button',
1630
+ role: 'tab',
1631
+ className: 'dus-seg-btn',
1632
+ 'data-active': preset.id === rangeId ? '' : undefined,
1633
+ 'aria-selected': preset.id === rangeId,
1634
+ onClick: () => {
1635
+ setRangeId(preset.id);
1636
+ },
1637
+ },
1638
+ rangeLabel(preset.id),
1639
+ ),
1640
+ ),
1641
+ ),
1642
+ ),
1643
+
1644
+ h(
1645
+ 'section',
1646
+ { className: 'dus-panel', key: 'heatmap' },
1647
+ h(
1648
+ 'div',
1649
+ { className: 'dus-panel-head' },
1650
+ h('h2', { className: 'dus-panel-title' }, 'Token 活动'),
1651
+ h('div', { className: 'dus-head-spacer' }),
1652
+ h('span', { className: 'dus-panel-sub' }, '最近一年'),
1653
+ ),
1654
+ h(TokenHeatmap, { days, rangeDays: range, now }),
1655
+ ),
1656
+
1657
+ h(
1658
+ 'section',
1659
+ { className: 'dus-panel', key: 'trend' },
1660
+ h(
1661
+ 'div',
1662
+ { className: 'dus-panel-head' },
1663
+ h('h2', { className: 'dus-panel-title' }, '每日 Token 趋势图'),
1664
+ h('div', { className: 'dus-head-spacer' }),
1665
+ h('span', { className: 'dus-panel-sub' }, rangeLabel(rangeId)),
1666
+ ),
1667
+ series.length === 0
1668
+ ? h('div', { className: 'dus-state', style: { padding: '48px 0' } }, h('div', { className: 'dus-state-desc' }, '这个时间范围内还没有模型调用记录。'))
1669
+ : h(TokenTrend, { days, series, rangeDays: range }),
1670
+ ),
1671
+
1672
+ h(
1673
+ 'section',
1674
+ { className: 'dus-panel', key: 'cache' },
1675
+ h(
1676
+ 'div',
1677
+ { className: 'dus-panel-head' },
1678
+ h('h2', { className: 'dus-panel-title' }, '每日平均缓存命中率'),
1679
+ h('div', { className: 'dus-head-spacer' }),
1680
+ h('span', { className: 'dus-panel-sub' }, `${rangeLabel(rangeId)} · 按输入 token 加权`),
1681
+ ),
1682
+ h(TokenCacheRate, { days, rangeDays: range }),
1683
+ ),
1684
+
1685
+ h(
1686
+ 'section',
1687
+ { className: 'dus-panel', key: 'models' },
1688
+ h(
1689
+ 'div',
1690
+ { className: 'dus-panel-head' },
1691
+ h('h2', { className: 'dus-panel-title' }, '模型用量'),
1692
+ h('div', { className: 'dus-head-spacer' }),
1693
+ h('span', { className: 'dus-panel-sub' }, '来源 = 模型接入的提供方'),
1694
+ ),
1695
+ h(ModelDonut, { models: modelsWithUsage }),
1696
+ h(ModelUsageChart, { days, models: modelsWithUsage, rangeDays: range }),
1697
+ ),
1698
+ ],
1699
+ ),
1700
+ ),
1701
+ h(RefreshButton, { onRefresh: refresh, busy: state.status === 'refreshing' }),
1702
+ );
1703
+ }
1704
+ return { UsageDashboard };
1705
+ })();
1706
+
1707
+ // ---- src/client/styles.js ----
1708
+ const __m3 = (() => {
1709
+
1710
+
1711
+ const STYLE_ID = 'dsh-usage-overview/dashboard.css';
1712
+
1713
+ const CSS = `.dus-root {
1714
+ --dus-accent: var(--dsw-alias-state-business-primary, var(--dsw-static-deepseek-450, #5686fe));
1715
+ --dus-subtle-fill: var(--dsw-alias-bg-overlay);
1716
+ --dus-subtle-fill: color-mix(in srgb, var(--dsw-alias-label-primary) 10%, transparent);
1717
+ --dus-cache-line: color-mix(in srgb, var(--dsw-alias-state-success-primary) 60%, var(--dsw-alias-label-primary));
1718
+ height: 100%;
1719
+ overflow-y: auto;
1720
+ overscroll-behavior: contain;
1721
+ padding: calc(var(--dsh-frame-top-clearance, 0px) + clamp(16px, 3vw, 28px)) clamp(14px, 4%, 40px) clamp(64px, 6.5vw, 76px);
1722
+ box-sizing: border-box;
1723
+ color: var(--dsw-alias-label-primary);
1724
+ font-family: var(--dsw-font-family);
1725
+ font-size: 14px;
1726
+ line-height: 1.5;
1727
+ }
1728
+
1729
+ .dus-shell {
1730
+ width: 100%;
1731
+ max-width: 1080px;
1732
+ margin: 0 auto;
1733
+ container-type: inline-size;
1734
+ container-name: dus;
1735
+ }
1736
+ .dus-inner {
1737
+ display: flex;
1738
+ flex-direction: column;
1739
+ gap: 16px;
1740
+ gap: clamp(12px, 1.5cqw, 16px);
1741
+ }
1742
+
1743
+ .dus-head { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 12px; margin-bottom: 4px; }
1744
+ .dus-title {
1745
+ font-size: 28px;
1746
+ font-size: clamp(21px, 2.6cqw + 14px, 28px);
1747
+ font-weight: 700; letter-spacing: -0.01em; margin: 0;
1748
+ line-height: 1.2;
1749
+ }
1750
+ .dus-badge {
1751
+ display: inline-flex; align-items: center; gap: 6px;
1752
+ padding: 3px 10px; border-radius: 999px;
1753
+ background: var(--dsw-alias-bg-layer-3);
1754
+ border: 1px solid var(--dsw-alias-border-l2);
1755
+ color: var(--dsw-alias-label-secondary);
1756
+ font-size: 12px; font-weight: 500;
1757
+ white-space: nowrap;
1758
+ }
1759
+ .dus-head-spacer { flex: 1 1 auto; min-width: 0; }
1760
+ .dus-live {
1761
+ display: inline-flex; align-items: center; gap: 6px;
1762
+ margin-left: auto; white-space: nowrap;
1763
+ font-size: 12px; color: var(--dsw-alias-label-secondary);
1764
+ }
1765
+ .dus-live-dot {
1766
+ width: 6px; height: 6px; border-radius: 50%;
1767
+ background: var(--dsw-alias-state-success-primary);
1768
+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--dsw-alias-state-success-primary) 20%, transparent);
1769
+ }
1770
+
1771
+ .dus-cards {
1772
+ display: flex; flex-wrap: wrap; gap: 1px;
1773
+ background: var(--dsw-alias-border-l1);
1774
+ border: 1px solid var(--dsw-alias-border-l1);
1775
+ border-radius: var(--dsw-radius-lg);
1776
+ overflow: hidden;
1777
+ }
1778
+ .dus-card {
1779
+ flex: 1 1 150px;
1780
+ box-sizing: border-box;
1781
+ background: var(--dsw-alias-bg-layer-2);
1782
+ padding: 18px 16px;
1783
+ padding: clamp(12px, 2.6cqw, 18px) clamp(8px, 1.6cqw, 16px);
1784
+ text-align: center;
1785
+ display: flex; flex-direction: column; gap: 6px;
1786
+ justify-content: center;
1787
+ min-width: 0;
1788
+ }
1789
+ .dus-card-value {
1790
+ font-size: 24px;
1791
+ font-size: clamp(17px, 2.3cqw + 8px, 24px);
1792
+ font-weight: 650; letter-spacing: -0.02em;
1793
+ font-variant-numeric: tabular-nums;
1794
+ white-space: nowrap;
1795
+ }
1796
+ .dus-card-label {
1797
+ font-size: 12px;
1798
+ font-size: clamp(10.5px, 1.05cqw, 12px);
1799
+ color: var(--dsw-alias-label-secondary);
1800
+ line-height: 1.35;
1801
+ overflow-wrap: anywhere;
1802
+ }
1803
+
1804
+ .dus-meter {
1805
+ height: 4px; border-radius: 2px; overflow: hidden;
1806
+ background: var(--dus-subtle-fill);
1807
+ margin-top: 2px;
1808
+ }
1809
+ .dus-meter-fill {
1810
+ height: 100%; border-radius: 2px;
1811
+ background: var(--dus-accent);
1812
+ transition: width 200ms ease;
1813
+ }
1814
+
1815
+ .dus-panel {
1816
+ background: var(--dsw-alias-bg-layer-2);
1817
+ border: 1px solid var(--dsw-alias-border-l1);
1818
+ border-radius: var(--dsw-radius-lg);
1819
+ padding: 18px 20px 20px;
1820
+ padding: clamp(14px, 2cqw, 18px) clamp(12px, 2cqw, 20px) clamp(14px, 2.2cqw, 20px);
1821
+ min-width: 0;
1822
+ }
1823
+ .dus-panel-head {
1824
+ display: flex; flex-wrap: wrap; align-items: center; gap: 6px 12px;
1825
+ margin-bottom: 16px; min-height: 28px;
1826
+ }
1827
+ .dus-panel-title { font-size: 15px; font-weight: 600; margin: 0; line-height: 1.3; }
1828
+ .dus-panel-sub { font-size: 12px; color: var(--dsw-alias-label-secondary); margin-left: auto; }
1829
+
1830
+ .dus-range-row {
1831
+ display: flex; flex-wrap: wrap; align-items: center; gap: 10px 12px;
1832
+ margin-top: 2px;
1833
+ }
1834
+ .dus-range-label {
1835
+ flex: none;
1836
+ font-size: 13px; font-weight: 550; color: var(--dsw-alias-label-secondary);
1837
+ }
1838
+ .dus-range-row .dus-seg {
1839
+ flex: 1 1 240px;
1840
+ max-width: 320px;
1841
+ margin-left: auto;
1842
+ }
1843
+
1844
+ .dus-seg {
1845
+ display: flex; align-items: center; gap: 2px;
1846
+ padding: 2px; border-radius: var(--dsw-radius-md);
1847
+ background: var(--dsw-alias-bg-layer-3);
1848
+ border: 1px solid var(--dsw-alias-border-l1);
1849
+ box-sizing: border-box;
1850
+ }
1851
+ .dus-seg-btn {
1852
+ flex: 1 1 0; min-width: 0;
1853
+ appearance: none; border: none; cursor: pointer;
1854
+ background: transparent; color: var(--dsw-alias-label-secondary);
1855
+ font-family: inherit; font-size: 12px; font-weight: 500;
1856
+ padding: 4px 12px;
1857
+ padding-inline: clamp(4px, 1cqw, 12px);
1858
+ border-radius: var(--dsw-radius-sm);
1859
+ transition: background 120ms ease, color 120ms ease;
1860
+ white-space: nowrap; text-align: center;
1861
+ }
1862
+ .dus-seg-btn:hover { color: var(--dsw-alias-label-primary); }
1863
+ .dus-seg-btn[data-active] {
1864
+ background: var(--dsw-alias-bg-layer-1);
1865
+ color: var(--dsw-alias-label-primary);
1866
+ box-shadow: var(--dsw-elevation-soft);
1867
+ }
1868
+
1869
+ .dus-heat-wrap {
1870
+ position: relative; overflow-x: auto; padding-bottom: 6px;
1871
+ scrollbar-width: thin; overscroll-behavior-inline: contain;
1872
+ -webkit-overflow-scrolling: touch;
1873
+ }
1874
+ .dus-heat { display: flex; gap: 3px; min-width: min-content; }
1875
+ .dus-heat-col { display: flex; flex-direction: column; gap: 3px; }
1876
+ .dus-heat-cell {
1877
+ border-radius: 2px;
1878
+ background: var(--dus-subtle-fill);
1879
+ transition: transform 90ms ease;
1880
+ }
1881
+ .dus-heat-cell[data-level="1"] { background: color-mix(in srgb, var(--dus-accent) 26%, var(--dsw-alias-bg-layer-3)); }
1882
+ .dus-heat-cell[data-level="2"] { background: color-mix(in srgb, var(--dus-accent) 48%, var(--dsw-alias-bg-layer-3)); }
1883
+ .dus-heat-cell[data-level="3"] { background: color-mix(in srgb, var(--dus-accent) 72%, var(--dsw-alias-bg-layer-3)); }
1884
+ .dus-heat-cell[data-level="4"] { background: var(--dus-accent); }
1885
+ .dus-heat-cell:hover { transform: scale(1.35); }
1886
+ .dus-heat-months {
1887
+ display: flex; gap: 3px; margin-bottom: 6px; min-width: min-content;
1888
+ }
1889
+
1890
+ .dus-heat-month {
1891
+ position: relative; height: 14px;
1892
+ font-size: 11px; line-height: 14px; color: var(--dsw-alias-label-secondary);
1893
+ white-space: nowrap; overflow: visible;
1894
+ }
1895
+ .dus-heat-month > span { position: absolute; left: 0; top: 0; }
1896
+ .dus-heat-legend {
1897
+ display: flex; flex-wrap: wrap; align-items: center; gap: 6px; justify-content: flex-end;
1898
+ margin-top: 10px; font-size: 11px; color: var(--dsw-alias-label-secondary);
1899
+ }
1900
+ .dus-heat-legend .dus-heat-cell { width: 10px; height: 10px; }
1901
+ .dus-heat-hint { margin-right: auto; color: var(--dsw-alias-label-secondary); }
1902
+
1903
+ .dus-tip {
1904
+ position: fixed; z-index: 60; pointer-events: none;
1905
+ background: var(--dsw-alias-tooltip-bg, #2c2c2e);
1906
+ color: var(--dsw-alias-tooltip-label, #ffffff);
1907
+ border: 1px solid var(--dsw-alias-tooltip-key-bg, color-mix(in srgb, #ffffff 18%, transparent));
1908
+ border-radius: var(--dsw-radius-md);
1909
+ padding: 8px 10px; font-size: 12px; line-height: 1.45;
1910
+ box-shadow: var(--dsw-elevation-prominent);
1911
+ max-width: min(260px, calc(100vw - 24px));
1912
+ }
1913
+ .dus-tip-title { color: inherit; font-weight: 600; margin-bottom: 2px; }
1914
+ .dus-tip-row { color: inherit; opacity: 0.8; font-variant-numeric: tabular-nums; }
1915
+
1916
+ .dus-chart-host { position: relative; width: 100%; min-width: 0; }
1917
+ .dus-chart-host svg { display: block; max-width: 100%; }
1918
+ .dus-legend {
1919
+ display: flex; flex-wrap: wrap; gap: 8px 18px;
1920
+ gap: clamp(6px, 1cqw, 8px) clamp(10px, 1.6cqw, 18px);
1921
+ margin-bottom: 10px;
1922
+ }
1923
+ .dus-legend-item {
1924
+ display: inline-flex; align-items: center; gap: 7px;
1925
+ font-size: 12px; color: var(--dsw-alias-label-secondary);
1926
+ cursor: default; min-width: 0; max-width: 100%;
1927
+ flex-wrap: wrap; row-gap: 2px;
1928
+ }
1929
+ .dus-legend-item[data-dim] { opacity: 0.4; }
1930
+ .dus-legend-dot { width: 9px; height: 9px; border-radius: 50%; flex: none; }
1931
+ .dus-legend-src {
1932
+ padding: 0 5px; border-radius: var(--dsw-radius-xs);
1933
+ background: var(--dsw-alias-bg-layer-3);
1934
+ border: 1px solid var(--dsw-alias-border-l2);
1935
+ color: var(--dsw-alias-label-secondary);
1936
+ font-size: 10.5px; font-weight: 500;
1937
+ }
1938
+ .dus-legend-val { color: var(--dsw-alias-label-secondary); font-variant-numeric: tabular-nums; }
1939
+
1940
+ .dus-split {
1941
+ display: flex; flex-wrap: wrap; align-items: center;
1942
+ gap: 28px;
1943
+ gap: clamp(16px, 2.6cqw, 28px);
1944
+ }
1945
+ .dus-donut-wrap {
1946
+ flex: 0 0 auto;
1947
+ position: relative; display: flex; justify-content: center;
1948
+ min-width: 0; max-width: 100%;
1949
+ }
1950
+
1951
+ .dus-root .dus-donut-wrap svg {
1952
+ width: 220px;
1953
+ width: clamp(150px, 24cqw, 220px);
1954
+ height: auto;
1955
+ }
1956
+ .dus-donut-center {
1957
+ position: absolute; inset: 0;
1958
+ display: flex; flex-direction: column; align-items: center; justify-content: center;
1959
+ pointer-events: none; text-align: center;
1960
+ }
1961
+ .dus-donut-total {
1962
+ font-size: 22px;
1963
+ font-size: clamp(16px, 2.2cqw + 6px, 22px);
1964
+ font-weight: 650; letter-spacing: -0.02em;
1965
+ font-variant-numeric: tabular-nums;
1966
+ }
1967
+ .dus-donut-unit { font-size: 11px; color: var(--dsw-alias-label-secondary); }
1968
+ .dus-donut-hint {
1969
+ margin-top: 3px; max-width: 118px;
1970
+ font-size: 10.5px; line-height: 1.3;
1971
+ color: var(--dsw-alias-label-secondary);
1972
+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
1973
+ }
1974
+
1975
+ .dus-model-list {
1976
+ display: flex; flex-direction: column; gap: 2px;
1977
+ flex: 1 1 310px;
1978
+ min-width: 0;
1979
+ }
1980
+ .dus-model-row {
1981
+ display: grid; grid-template-columns: 10px minmax(0, 1fr) auto;
1982
+ align-items: center; gap: 10px;
1983
+ padding: 9px 8px; border-radius: var(--dsw-radius-md);
1984
+ padding: clamp(6px, 1cqw, 9px) clamp(4px, 0.8cqw, 8px);
1985
+ gap: clamp(6px, 1cqw, 10px);
1986
+ transition: background 120ms ease;
1987
+ min-width: 0;
1988
+ }
1989
+ .dus-model-row:hover { background: var(--dsw-alias-interactive-bg-hover); }
1990
+ .dus-model-row[data-active] { background: var(--dsw-alias-interactive-bg-hover); }
1991
+ .dus-model-dot { width: 9px; height: 9px; border-radius: 50%; }
1992
+ .dus-model-main { min-width: 0; }
1993
+
1994
+ .dus-model-name {
1995
+ font-weight: 550; font-size: 13px;
1996
+ font-size: clamp(12px, 1.3cqw, 13px);
1997
+ white-space: normal; overflow-wrap: anywhere;
1998
+ line-height: 1.35;
1999
+ }
2000
+ .dus-model-meta {
2001
+ font-size: 11.5px; color: var(--dsw-alias-label-secondary);
2002
+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
2003
+ }
2004
+ .dus-model-src {
2005
+ display: inline-flex; align-items: center;
2006
+ padding: 0 5px; margin-left: 4px;
2007
+ border-radius: var(--dsw-radius-xs);
2008
+ background: var(--dsw-alias-bg-layer-3);
2009
+ border: 1px solid var(--dsw-alias-border-l2);
2010
+ color: var(--dsw-alias-label-secondary);
2011
+ font-size: 10.5px; font-weight: 500;
2012
+ vertical-align: 1px;
2013
+ }
2014
+ .dus-model-right { text-align: right; white-space: nowrap; }
2015
+ .dus-model-tokens {
2016
+ font-weight: 600; font-size: 13px;
2017
+ font-size: clamp(12px, 1.3cqw, 13px);
2018
+ font-variant-numeric: tabular-nums;
2019
+ }
2020
+ .dus-model-pct { font-size: 11.5px; color: var(--dsw-alias-label-secondary); font-variant-numeric: tabular-nums; }
2021
+
2022
+ .dus-model-trend {
2023
+ margin-top: 16px;
2024
+ margin-top: clamp(14px, 2.2cqw, 22px);
2025
+ padding-top: 14px;
2026
+ padding-top: clamp(12px, 1.8cqw, 18px);
2027
+ border-top: 1px solid var(--dsw-alias-border-l1);
2028
+ }
2029
+ .dus-bars-head {
2030
+ display: flex; flex-wrap: wrap; align-items: center;
2031
+ gap: 8px 12px; margin-bottom: 10px;
2032
+ }
2033
+ .dus-bars-heading {
2034
+ display: flex; flex-wrap: wrap; align-items: baseline;
2035
+ gap: 4px 10px; min-width: 0; flex: 1 1 200px;
2036
+ }
2037
+ .dus-bars-title { font-size: 13.5px; font-weight: 600; margin: 0; line-height: 1.3; }
2038
+ .dus-bars-note { font-size: 11px; color: var(--dsw-alias-label-secondary); }
2039
+ .dus-trend-toggle { margin-left: auto; flex: none; }
2040
+ .dus-seg-sm .dus-seg-btn { padding: 3px 10px; font-size: 11px; }
2041
+
2042
+ .dus-state {
2043
+ display: flex; flex-direction: column; align-items: center; justify-content: center;
2044
+ gap: 12px; padding: 72px 24px; text-align: center;
2045
+ color: var(--dsw-alias-label-secondary);
2046
+ }
2047
+ .dus-state-icon {
2048
+ width: 34px; height: 34px; border-radius: 50%;
2049
+ display: grid; place-items: center;
2050
+ background: var(--dus-subtle-fill);
2051
+ color: var(--dsw-alias-label-secondary);
2052
+ }
2053
+ .dus-state-title { font-size: 15px; font-weight: 600; color: var(--dsw-alias-label-primary); }
2054
+ .dus-state-desc { font-size: 13px; max-width: 420px; }
2055
+ .dus-btn {
2056
+ appearance: none; cursor: pointer; font-family: inherit; font-size: 13px; font-weight: 500;
2057
+ display: inline-flex; align-items: center; gap: 7px;
2058
+ padding: 7px 14px; border-radius: var(--dsw-radius-md);
2059
+ background: var(--dsw-alias-bg-layer-3);
2060
+ color: var(--dsw-alias-label-primary);
2061
+ border: 1px solid var(--dsw-alias-border-l2);
2062
+ transition: background 120ms ease, border-color 120ms ease;
2063
+ }
2064
+ .dus-btn:hover { background: var(--dsw-alias-bg-layer-4, var(--dsw-alias-interactive-bg-hover)); }
2065
+ .dus-btn[disabled] { opacity: 0.55; cursor: default; }
2066
+ .dus-btn-primary {
2067
+ background: var(--dsw-alias-brand-primary);
2068
+ color: var(--dsw-alias-bg-base);
2069
+ border-color: transparent;
2070
+ }
2071
+ .dus-btn-primary:hover { background: var(--dsw-alias-button-primary-hover, var(--dsw-alias-brand-primary)); }
2072
+
2073
+ .dus-refresh {
2074
+ position: fixed; right: 28px;
2075
+ bottom: calc(24px + env(safe-area-inset-bottom, 0px));
2076
+ z-index: 20;
2077
+ }
2078
+ .dus-spin { animation: dus-rotate 900ms linear infinite; }
2079
+ @keyframes dus-rotate { to { transform: rotate(360deg); } }
2080
+ @media (prefers-reduced-motion: reduce) {
2081
+ .dus-spin { animation-duration: 2200ms; }
2082
+ .dus-heat-cell { transition: none; }
2083
+ }
2084
+ `;
2085
+ return { STYLE_ID, CSS };
2086
+ })();
2087
+
2088
+ // ---- src/client/index.js ----
2089
+ const __m4 = (() => {
2090
+ const { createElement: h } = require("react");
2091
+ const { PANEL_ID: PANEL_ID, NS: NS } = __m0;
2092
+ const { UsageDashboard: UsageDashboard } = __m2;
2093
+ const { CSS: CSS, STYLE_ID: STYLE_ID } = __m3;
2094
+
2095
+ const inject = ['slots', 'layout', 'locale'];
2096
+
2097
+ const en = {
2098
+ 'panel.label': 'Usage',
2099
+ 'panel.tooltip': 'Usage statistics',
2100
+ };
2101
+
2102
+ const zh = {
2103
+ 'panel.label': '用量统计',
2104
+ 'panel.tooltip': '使用统计',
2105
+ };
2106
+
2107
+ function installStyles() {
2108
+ if (typeof document === 'undefined') return;
2109
+ if (document.querySelector(`style[data-plugin-css="${STYLE_ID}"]`) !== null) return;
2110
+ const tag = document.createElement('style');
2111
+ tag.dataset.plugin = 'dsh-usage-overview';
2112
+ tag.dataset.pluginCss = STYLE_ID;
2113
+ tag.textContent = CSS;
2114
+ document.head.appendChild(tag);
2115
+ }
2116
+
2117
+ function UsagePanelIcon({ size = 16 } = {}) {
2118
+ return h(
2119
+ 'svg',
2120
+ {
2121
+ width: String(size),
2122
+ height: String(size),
2123
+ viewBox: '0 0 16 16',
2124
+ fill: 'none',
2125
+ xmlns: 'http://www.w3.org/2000/svg',
2126
+ 'stroke-width': '1',
2127
+ 'aria-hidden': 'true',
2128
+ },
2129
+ h('path', {
2130
+ d: 'M3.4041 13.096C2.49514 12.187 1.87614 11.0288 1.62537 9.76798C1.37459 8.50716 1.50331 7.20028 1.99525 6.01261C2.48719 4.82494 3.32025 3.80981 4.3891 3.09557C5.45795 2.38134 6.71458 2.00008 8.0001 2C9.28563 2.00008 10.5423 2.38134 11.6111 3.09557C12.68 3.80981 13.513 4.82494 14.005 6.01261C14.4969 7.20028 14.6256 8.50716 14.3748 9.76798C14.1241 11.0288 13.5051 12.187 12.5961 13.096',
2131
+ stroke: 'currentColor',
2132
+ }),
2133
+ h('path', { d: 'M8 8.49994L11.6114 4.88855', stroke: 'currentColor' }),
2134
+ h('path', {
2135
+ d: 'M8 9.75C8.69036 9.75 9.25 9.19036 9.25 8.5C9.25 7.80964 8.69036 7.25 8 7.25C7.30964 7.25 6.75 7.80964 6.75 8.5C6.75 9.19036 7.30964 9.75 8 9.75Z',
2136
+ fill: 'currentColor',
2137
+ }),
2138
+ );
2139
+ }
2140
+
2141
+ function apply(ctx) {
2142
+ installStyles();
2143
+
2144
+ ctx.effect(
2145
+ () =>
2146
+ ctx.locale.register(NS, {
2147
+ zh,
2148
+ en,
2149
+ }),
2150
+ 'dsh-usage-overview: dictionaries',
2151
+ );
2152
+
2153
+ const t = ctx.locale.bind(NS);
2154
+
2155
+ ctx.slots.inject('main', () =>
2156
+ ctx.slots.register(
2157
+ {
2158
+ name: 'main',
2159
+ key: PANEL_ID,
2160
+ locale: NS,
2161
+ },
2162
+ UsageDashboard,
2163
+ ),
2164
+ );
2165
+
2166
+ ctx.slots.inject('sidebar.panellist', () =>
2167
+ ctx.slots.register(
2168
+ {
2169
+ name: 'sidebar.panellist',
2170
+ id: PANEL_ID,
2171
+ order: 20,
2172
+ label: () => t('panel.label'),
2173
+ locale: NS,
2174
+ },
2175
+ UsagePanelIcon,
2176
+ ),
2177
+ );
2178
+ }
2179
+ return { inject, apply };
2180
+ })();
2181
+ module.exports.apply = __m4.apply;
2182
+ module.exports.inject = __m4.inject;
2183
+ return module.exports;
2184
+ }
2185
+ });