dsh-usage-overview 0.0.0-stage → 1.0.0

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