dsh-usage-prism 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js ADDED
@@ -0,0 +1,1080 @@
1
+ /**
2
+ * Client 半边:左侧栏里的「用量」面板。
3
+ *
4
+ * 这一半只负责画面:打开面板、切换尺度时各取一次快照,然后把数字摆出来,
5
+ * 悬浮时显示那一格的明细。数据全部来自 Host 的 `GET /api/usage-prism?scope=…`,
6
+ * 浏览器不自己折会话事件——折叠口径只存在一个地方。
7
+ *
8
+ * 颜色分两层:容器、文字、分隔线一律用 `--dsw-alias-*`(跟着深浅色与主题走);
9
+ * 只有热力图色阶和两条进度条是数据色——它们是图,不是外壳。
10
+ */
11
+
12
+ const PANEL_ID = 'usage-prism'
13
+ const SCOPES = ['day', 'week', 'month', 'year']
14
+
15
+ /** 文案只备简体中文与英语:`zh*` 走中文,其余一律英语(跟随 dsh 的语言配置)。 */
16
+ const TEXT = {
17
+ zh: {
18
+ panel: '用量',
19
+ sub: '近况',
20
+ through: '统计到',
21
+ scopes: { day: '本日', week: '本周', month: '本月', year: '本年' },
22
+ tokens: 'tokens',
23
+ runtime: '运行',
24
+ inLabel: '输入',
25
+ outLabel: '输出',
26
+ cache: '缓存',
27
+ sessions: '会话',
28
+ turns: '轮次',
29
+ steps: '步',
30
+ tools: '次工具',
31
+ timeSplit: '时间去向',
32
+ wait: '等待',
33
+ gen: '生成',
34
+ tool: '工具',
35
+ detail: '详情',
36
+ columns: { model: '模型', n: 'n', tokens: 'tokens', ttft: '首 token', tps: 't/s', cache: '缓存命中' },
37
+ loading: '统计中…',
38
+ loadError: '读不到用量:',
39
+ nothingHere: '这个范围没有记录',
40
+ noModels: '这个范围没有模型记录',
41
+ noRecord: '没有记录',
42
+ otherModels: (n) => `其他 ${n} 个模型`,
43
+ today: '今天',
44
+ skipped: (n) => `有 ${n} 个会话的日志读不出来,已跳过。`,
45
+ weekday: ['日', '一', '二', '三', '四', '五', '六'],
46
+ months: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
47
+ },
48
+ en: {
49
+ panel: 'Usage',
50
+ sub: 'Recent',
51
+ through: 'Through',
52
+ scopes: { day: 'Today', week: 'This week', month: 'This month', year: 'This year' },
53
+ tokens: 'tokens',
54
+ runtime: 'runtime',
55
+ inLabel: 'In',
56
+ outLabel: 'Out',
57
+ cache: 'Cache',
58
+ sessions: 'sessions',
59
+ turns: 'turns',
60
+ steps: 'steps',
61
+ tools: 'tool calls',
62
+ timeSplit: 'Where time went',
63
+ wait: 'Waiting',
64
+ gen: 'Generating',
65
+ tool: 'Tools',
66
+ detail: 'Details',
67
+ columns: { model: 'Model', n: 'n', tokens: 'tokens', ttft: 'First token', tps: 't/s', cache: 'Cache hit' },
68
+ loading: 'Counting…',
69
+ loadError: 'Cannot read usage: ',
70
+ nothingHere: 'Nothing recorded in this range',
71
+ noModels: 'No model activity in this range',
72
+ noRecord: 'no record',
73
+ otherModels: (n) => `${n} more model${n === 1 ? '' : 's'}`,
74
+ today: 'today',
75
+ skipped: (n) => `${n} session log(s) could not be read and were skipped.`,
76
+ weekday: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
77
+ months: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
78
+ },
79
+ }
80
+
81
+ const CSS = `
82
+ .up-root{container-type:inline-size;display:block;height:100%;overflow:auto;color:var(--dsw-alias-label-primary);
83
+ background:var(--dsw-alias-bg-base);font:14px/1.6 -apple-system,"Hiragino Sans","Noto Sans SC",sans-serif;
84
+ --up-rose-1:light-dark(#fde8f0,#a76080);--up-rose-2:light-dark(#fbcee0,#c57197);
85
+ --up-rose-3:light-dark(#f7b4d0,#df85ae);--up-rose-4:light-dark(#f09bc0,#efa2c3);
86
+ --up-rose-5:light-dark(#e584b0,#fcc0d9);--up-rose-6:light-dark(#da6ca0,#fee3ed);
87
+ --up-rose:light-dark(#dd79a7,#f198bb);--up-mint:light-dark(#88d7b9,#7fd9b8);
88
+ --up-lilac:light-dark(#c4bcf1,#bbaff6);--up-accent:light-dark(#bf4a7f,#fe9ac2);
89
+ --up-dim:var(--dsw-alias-label-secondary);--up-rule:var(--dsw-alias-border-l1);
90
+ --up-track:color-mix(in oklab,var(--dsw-alias-label-primary) 9%,transparent)}
91
+ .up-inner{max-width:1120px;margin:0 auto;padding:22px 26px 40px;box-sizing:border-box}
92
+ .up-head{display:flex;align-items:baseline;gap:10px;margin-bottom:16px}
93
+ .up-head h1{font-size:15px;font-weight:600;margin:0}
94
+ .up-head .up-sub{font-size:12px;color:var(--up-dim)}
95
+ .up-head .up-sp{flex:1}
96
+ .up-head .up-stamp{font-size:11px;color:var(--up-dim);font-variant-numeric:tabular-nums}
97
+ .up-chips{display:flex;gap:6px;margin-bottom:18px}
98
+ .up-chip{line-height:1;padding:6px 12px;border-radius:999px;cursor:pointer;font:inherit;font-size:12px;
99
+ border:1px solid var(--dsw-alias-border-l1);background:transparent;color:var(--up-dim)}
100
+ .up-chip:hover{border-color:var(--dsw-alias-border-l2);color:var(--dsw-alias-label-primary)}
101
+ .up-chip[data-on="1"]{border-color:var(--up-rose);color:var(--up-accent);font-weight:600;
102
+ background:color-mix(in oklab,var(--up-rose) 14%,transparent)}
103
+ .up-cal{position:relative;margin-bottom:24px}
104
+ .up-grid{display:grid}
105
+ .up-cell{position:relative;border-radius:3px;background:transparent;box-sizing:border-box;cursor:default}
106
+ .up-cell[data-lv="0"]{background:light-dark(transparent,color-mix(in oklab,var(--up-rose-4) 16%,transparent))}
107
+ .up-cell[data-lv="1"]{background:var(--up-rose-1)}
108
+ .up-cell[data-lv="2"]{background:var(--up-rose-2)}
109
+ .up-cell[data-lv="3"]{background:var(--up-rose-3)}
110
+ .up-cell[data-lv="4"]{background:var(--up-rose-4)}
111
+ .up-cell[data-lv="5"]{background:var(--up-rose-5)}
112
+ .up-cell[data-lv="6"]{background:var(--up-rose-6)}
113
+ .up-cell[data-now="1"]{box-shadow:inset 0 0 0 1.5px var(--up-accent)}
114
+ .up-cell[data-lv="5"][data-now="1"],.up-cell[data-lv="6"][data-now="1"]{box-shadow:inset 0 0 0 1.5px light-dark(#fff,rgba(22,16,19,.6))}
115
+ .up-cell[data-hover="1"]{outline:1.5px solid var(--up-accent);outline-offset:1px}
116
+ .up-cal[data-kind="day"] .up-cell{height:54px;border-radius:4px}
117
+ .up-cal[data-kind="week"] .up-cell{height:58px;border-radius:5px}
118
+ .up-cal[data-kind="month"] .up-cell{height:42px}
119
+ .up-cal[data-kind="year"] .up-cell{aspect-ratio:1 / 1}
120
+ .up-cell .up-num{position:absolute;left:3px;top:1px;font-size:9px;line-height:1.2;color:var(--up-dim);font-variant-numeric:tabular-nums}
121
+ .up-cell:not([data-lv="0"]) .up-num{color:light-dark(rgba(74,38,54,.55),rgba(22,14,18,.72))}
122
+ .up-labels{display:grid;margin-top:5px;font-size:10px;color:var(--up-dim);text-align:center}
123
+ .up-labels .up-tdy{color:var(--up-accent)}
124
+ .up-months{display:grid;height:14px;margin-left:22px;font-size:9px;color:var(--up-dim);line-height:1}
125
+ .up-months span{white-space:nowrap;overflow:visible}
126
+ .up-tip{position:absolute;z-index:20;pointer-events:none;background:var(--dsw-alias-hovercard-bg);
127
+ border-radius:10px;box-shadow:var(--dsw-shadow-lv3,rgba(0,0,0,.28) 0 8px 24px);padding:8px 12px;
128
+ font-size:11px;line-height:1.55;white-space:nowrap;color:var(--dsw-alias-hovercard-label-secondary)}
129
+ .up-tip b{display:block;color:var(--dsw-alias-hovercard-label-primary);font-weight:600;font-variant-numeric:tabular-nums}
130
+ .up-tip .up-tp{display:flex;align-items:baseline;gap:6px;margin-top:2px}
131
+ .up-tip .up-dot{flex:none;width:6px;height:6px;border-radius:2px}
132
+ .up-tip .up-tp b{margin-left:auto;font-weight:600}
133
+ .up-tip .up-x{margin-top:2px}
134
+ .up-cols{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:0 26px;align-items:start}
135
+ .up-col{display:grid;grid-template-rows:18px 46px auto auto;align-content:start}
136
+ .up-c1{display:flex;align-items:baseline;gap:8px;min-width:0}
137
+ .up-c2{display:flex;align-items:flex-start;min-width:0}
138
+ .up-c3{padding:10px 0}
139
+ .up-buckets{display:flex;align-items:center;gap:14px;row-gap:6px;flex-wrap:wrap;font-size:10.5px;
140
+ color:var(--up-dim);font-variant-numeric:tabular-nums;white-space:nowrap}
141
+ .up-buckets .up-bk{display:flex;align-items:center;gap:4px}
142
+ .up-buckets .up-sw{width:6px;height:6px;border-radius:2px;flex:none;display:inline-block}
143
+ .up-buckets b{color:var(--dsw-alias-label-primary);font-weight:600;font-size:11px}
144
+ .up-buckets em{font-style:normal;font-size:10px}
145
+ /* 小标题(两张卡共用):行高写死成 .up-col 网格第一行的高度(18px);右边的日期范围
146
+ 是同一行的副文本,也取 18px,两者才落在同一条基线上。
147
+ 这里不能用 .up-c1 的 align-items:baseline:标题 12px、日期 11px,字号不一样时
148
+ 基线对齐会把整行往下顶,标题就压到大数字上。
149
+ 日期用自己的 .up-range,别借 .up-note——那是面板底部「读不出的会话」那一行,带 margin-top。 */
150
+ .up-c1.up-sec-h{align-items:flex-start}
151
+ .up-sec-h h2{font-size:12px;font-weight:600;margin:0;color:var(--up-dim);letter-spacing:.06em;line-height:18px}
152
+ .up-sec-h .up-range{font-size:11px;line-height:18px;color:var(--up-dim);font-variant-numeric:tabular-nums}
153
+ .up-sum-row{display:flex;align-items:baseline;gap:26px}
154
+ .up-big{display:flex;align-items:baseline;gap:7px;min-width:0}
155
+ .up-big b{font-size:27px;font-weight:600;line-height:1.1;letter-spacing:-.01em;font-variant-numeric:tabular-nums}
156
+ .up-big span{font-size:11px;color:var(--up-dim)}
157
+ .up-bar{display:flex;height:9px;border-radius:5px;overflow:hidden;background:var(--up-track)}
158
+ .up-bar i{display:block;height:100%}
159
+ .up-bar .up-wait{background:var(--up-lilac)}
160
+ .up-bar .up-gen,.up-bar .up-in{background:var(--up-rose)}
161
+ .up-bar .up-cached{background:var(--up-rose-2)}
162
+ .up-bar .up-tool,.up-bar .up-out{background:var(--up-mint)}
163
+ .up-ioms{display:flex;align-items:center;gap:12px;font-size:10.5px;color:var(--up-dim);
164
+ font-variant-numeric:tabular-nums;white-space:nowrap;flex-wrap:wrap;row-gap:6px}
165
+ .up-ioms .up-lg{display:flex;align-items:center;gap:4px}
166
+ .up-ioms .up-sw{width:6px;height:6px;border-radius:2px;flex:none;display:inline-block}
167
+ .up-ioms b{color:var(--dsw-alias-label-primary);font-weight:600;font-size:11px}
168
+ .up-ioms em{font-style:normal;font-size:10px}
169
+ .up-ioms .up-cache{margin-left:auto;display:flex;align-items:center;gap:5px}
170
+ .up-meter{display:inline-block;width:42px;height:5px;border-radius:3px;background:var(--up-track);overflow:hidden}
171
+ .up-meter i{display:block;height:100%;background:var(--up-rose-2);border-radius:3px}
172
+ .up-meta{display:flex;gap:18px;margin-top:14px;font-size:12px;color:var(--up-dim);font-variant-numeric:tabular-nums;flex-wrap:wrap}
173
+ .up-meta b{color:var(--dsw-alias-label-primary);font-weight:600}
174
+ .up-legend{display:flex;gap:8px;row-gap:4px;font-size:10.5px;color:var(--up-dim);flex-wrap:wrap;white-space:nowrap;margin-top:9px}
175
+ .up-legend span{display:flex;align-items:baseline;gap:4px;font-variant-numeric:tabular-nums}
176
+ .up-legend b{color:var(--dsw-alias-label-primary);font-weight:600;font-size:12px}
177
+ .up-legend em{font-style:normal;font-size:10px}
178
+ .up-legend .up-sw{width:7px;height:7px;border-radius:2px;margin-right:4px;flex:none;display:inline-block}
179
+ .up-detail{margin-top:26px;border-top:1px solid var(--up-rule);padding-top:16px}
180
+ .up-rows{border-top:1px solid var(--up-rule);border-bottom:1px solid var(--up-rule)}
181
+ .up-row{display:grid;grid-template-columns:minmax(0,1fr) 34px 62px 66px 46px 62px;align-items:center;gap:10px;
182
+ padding:9px 0;border-bottom:1px solid var(--up-rule);font-size:13px}
183
+ .up-row:last-child{border-bottom:none}
184
+ .up-row.up-th{font-size:11px;color:var(--up-dim);letter-spacing:.04em;padding:7px 0}
185
+ .up-th button{background:none;border:0;padding:0;font:inherit;color:inherit;cursor:pointer;text-align:right;
186
+ white-space:nowrap;letter-spacing:inherit}
187
+ .up-th button:first-child{text-align:left}
188
+ .up-th button:hover{color:var(--dsw-alias-label-primary)}
189
+ .up-th button[data-on="1"]{color:var(--dsw-alias-label-primary);font-weight:600}
190
+ .up-th .up-ar{display:inline-block;width:10px;text-align:right;font-size:9px;opacity:0}
191
+ .up-th button[data-on="1"] .up-ar{opacity:.7}
192
+ .up-name{min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
193
+ .up-name .up-pv{color:var(--up-dim)}
194
+ .up-v{text-align:right;font-variant-numeric:tabular-nums;color:var(--up-dim)}
195
+ .up-v[data-on="1"]{color:var(--dsw-alias-label-primary);font-weight:600}
196
+ .up-n{text-align:right;font-size:12px;color:var(--up-dim);font-variant-numeric:tabular-nums}
197
+ .up-n[data-on="1"]{color:var(--dsw-alias-label-primary);font-weight:600}
198
+ .up-empty{padding:26px 0;font-size:12px;color:var(--up-dim)}
199
+ .up-err{padding:20px 0;font-size:12px;color:var(--dsw-alias-state-error-primary)}
200
+ .up-note{margin-top:10px;font-size:11px;color:var(--up-dim)}
201
+ @container (max-width:720px){
202
+ .up-inner{padding:16px 16px 32px}
203
+ .up-cols{grid-template-columns:minmax(0,1fr);gap:18px}
204
+ .up-col{grid-template-rows:auto auto auto auto;gap:8px}
205
+ .up-c2{min-height:0}
206
+ .up-c3{padding:2px 0}
207
+ .up-buckets{gap:2px 12px}
208
+ .up-ioms{white-space:normal}
209
+ .up-big b{font-size:22px}
210
+ .up-row{grid-template-columns:minmax(0,1fr) 26px 52px 56px 40px 52px;gap:8px;font-size:12px}
211
+ .up-legend{gap:6px;font-size:9.5px}
212
+ .up-sum-row{gap:18px}
213
+ .up-ioms{font-size:9.5px;gap:9px}
214
+ }
215
+ `
216
+
217
+ /**
218
+ * 带单位的 token 数。边界值必须进位:999999 不该写成「1000k」,999999999 也不该写成
219
+ * 「1000M」。所以先判断「换算成这个单位会不会凑满 1000」再定单位;k 取整数,其余两位小数。
220
+ */
221
+ function fmtTok(value) {
222
+ const n = Math.max(0, Number(value) || 0)
223
+ if (n < 1000) return String(Math.round(n))
224
+ const units = [
225
+ ['k', 1e3, 0],
226
+ ['M', 1e6, 2],
227
+ ['G', 1e9, 2],
228
+ ['T', 1e12, 2],
229
+ ]
230
+ for (let index = 0; index < units.length; index += 1) {
231
+ const [suffix, size, digits] = units[index]
232
+ const scaled = n / size
233
+ const limit = digits === 0 ? 999.5 : 999.995
234
+ if (scaled < limit || index === units.length - 1) {
235
+ if (digits === 0) return `${Math.round(scaled)}${suffix}`
236
+ return `${scaled.toFixed(digits).replace(/\.?0+$/, '')}${suffix}`
237
+ }
238
+ }
239
+ return String(n)
240
+ }
241
+
242
+ function pct(part, whole) {
243
+ if (!whole) return 0
244
+ return Math.round((Number(part) / Number(whole)) * 100)
245
+ }
246
+
247
+ function fmtDur(ms) {
248
+ const sec = Math.max(0, Math.round((Number(ms) || 0) / 1000))
249
+ if (sec < 60) return `${sec}s`
250
+ const min = Math.floor(sec / 60)
251
+ const hour = Math.floor(min / 60)
252
+ if (hour >= 48) return `${Math.round(sec / 3600)}h`
253
+ if (hour > 0) return `${hour}h ${String(min % 60).padStart(2, '0')}m`
254
+ return `${min}m`
255
+ }
256
+
257
+ function two(n) {
258
+ return String(n).padStart(2, '0')
259
+ }
260
+
261
+ function parseDay(key) {
262
+ const [y, m, d] = String(key).split('-').map(Number)
263
+ return new Date(y, (m || 1) - 1, d || 1)
264
+ }
265
+
266
+ function shortDay(key) {
267
+ if (typeof key !== 'string' || key.length < 10) return '—'
268
+ const date = parseDay(key)
269
+ return `${date.getMonth() + 1}/${date.getDate()}`
270
+ }
271
+
272
+ /**
273
+ * 热力分档:只在「本期有记录」的格子里按名次分 6 档,同值同档。
274
+ * 不用 tokens / max 的比例:一周里几天常常都挤在最大值附近,按比例分会整片落进最深一档,
275
+ * 看不出差别;按名次分才能看出相对高低。
276
+ * 颜色只表示本期内的相对高低,绝对值看悬浮卡和下面的明细表。
277
+ */
278
+ function levelScale(cells) {
279
+ const values = cells
280
+ .filter((cell) => !cell.blank && cell.tokens > 0)
281
+ .map((cell) => cell.tokens)
282
+ .sort((a, b) => a - b)
283
+ if (values.length === 0) return () => 0
284
+ const ranks = new Map()
285
+ // 同一个值取**最后**一个下标:取第一个的话,并列最高的那几天永远到不了最深档
286
+ // (一周里两天并列时最深只到 4/6,全周同值时整片停在最浅)。
287
+ values.forEach((value, index) => ranks.set(value, index))
288
+ const last = values.length - 1
289
+ return (tokens) => {
290
+ if (!tokens) return 0
291
+ if (last === 0) return 6
292
+ return 1 + Math.floor((5 * (ranks.get(tokens) ?? 0)) / last)
293
+ }
294
+ }
295
+
296
+ /**
297
+ * 悬浮卡落在哪(坐标都相对日历容器)。
298
+ * 先贴格子右侧,右边塞不下换到左侧;两侧都塞不下(面板太窄)就挪到格子下方或上方,
299
+ * 横向跟格子居中。纵向夹进面板可见的那一段(view 也是相对容器的上下沿)。
300
+ * 无论走哪条路,落点都跟格子不重叠——光标正压在格子上,卡片压上去就看不见了。
301
+ */
302
+ function placeTip(anchor, host, view, size) {
303
+ const gap = 8
304
+ const pad = 2
305
+ const maxLeft = Math.max(pad, host.width - size.width - pad)
306
+ const clampLeft = (x) => Math.max(pad, Math.min(maxLeft, x))
307
+ const lowTop = view.top + gap
308
+ const highTop = view.bottom - size.height - gap
309
+ const clampTop = (y) => (highTop > lowTop ? Math.max(lowTop, Math.min(highTop, y)) : lowTop)
310
+ const middle = (anchor.top + anchor.bottom) / 2 - size.height / 2
311
+ // 先右后左:这两个落点都不会跟格子相交。
312
+ const right = anchor.right + gap
313
+ if (right + size.width <= host.width - pad) return { left: right, top: clampTop(middle) }
314
+ const leftSide = anchor.left - gap - size.width
315
+ if (leftSide >= pad) return { left: leftSide, top: clampTop(middle) }
316
+ // 面板窄到卡片横着塞不下:挪到格子下方或上方,横向跟格子居中对齐。
317
+ const centered = clampLeft(anchor.left + (anchor.right - anchor.left) / 2 - size.width / 2)
318
+ if (anchor.bottom + gap + size.height <= view.bottom) return { left: centered, top: anchor.bottom + gap }
319
+ if (anchor.top - gap - size.height >= view.top) return { left: centered, top: anchor.top - gap - size.height }
320
+ // 上下也放不下(可见段比卡片还矮):挑空间大的那一侧夹进去。
321
+ const roomBelow = view.bottom - (anchor.bottom + gap)
322
+ const roomAbove = anchor.top - gap - view.top
323
+ return {
324
+ left: centered,
325
+ top: clampTop(roomBelow >= roomAbove ? anchor.bottom + gap : anchor.top - gap - size.height),
326
+ }
327
+ }
328
+
329
+ function buildCalendar(data, t) {
330
+ const to = parseDay(data.to)
331
+ const todayKey = data.today
332
+ if (data.scope === 'day') {
333
+ const byHour = new Map()
334
+ for (const row of data.hours ?? []) byHour.set(Number(row.hour.slice(11, 13)), row)
335
+ const cells = []
336
+ for (let hour = 0; hour < 24; hour += 1) {
337
+ const row = byHour.get(hour) ?? null
338
+ cells.push({
339
+ key: row?.hour ?? `${data.today}T${two(hour)}`,
340
+ label: `${two(hour)}:00 – ${two((hour + 1) % 24)}:00`,
341
+ hour,
342
+ row,
343
+ tokens: row?.tokens ?? 0,
344
+ })
345
+ }
346
+ return { kind: 'hours', cells }
347
+ }
348
+
349
+ const byDay = new Map()
350
+ for (const row of data.days ?? []) byDay.set(row.day, row)
351
+ const cellOf = (date) => {
352
+ const key = `${date.getFullYear()}-${two(date.getMonth() + 1)}-${two(date.getDate())}`
353
+ const row = byDay.get(key) ?? null
354
+ return {
355
+ key,
356
+ row,
357
+ tokens: row?.tokens ?? 0,
358
+ dayNum: date.getDate(),
359
+ future: key > todayKey,
360
+ now: key === todayKey,
361
+ }
362
+ }
363
+
364
+ if (data.scope === 'week') {
365
+ const monday = new Date(to)
366
+ monday.setDate(to.getDate() - ((to.getDay() + 6) % 7))
367
+ const cells = []
368
+ for (let i = 0; i < 7; i += 1) {
369
+ const date = new Date(monday)
370
+ date.setDate(monday.getDate() + i)
371
+ const cell = cellOf(date)
372
+ cell.label = `${shortDay(cell.key)} ${t.weekday[date.getDay()]}`
373
+ cells.push(cell)
374
+ }
375
+ return { kind: 'week', cells }
376
+ }
377
+
378
+ if (data.scope === 'month') {
379
+ const first = new Date(to.getFullYear(), to.getMonth(), 1)
380
+ const last = new Date(to.getFullYear(), to.getMonth() + 1, 0)
381
+ const lead = (first.getDay() + 6) % 7
382
+ const cells = []
383
+ for (let i = 0; i < lead; i += 1) cells.push({ key: `blank-${i}`, blank: true })
384
+ for (let d = 1; d <= last.getDate(); d += 1) {
385
+ const cell = cellOf(new Date(to.getFullYear(), to.getMonth(), d))
386
+ cell.label = shortDay(cell.key)
387
+ cells.push(cell)
388
+ }
389
+ return { kind: 'month', cells }
390
+ }
391
+
392
+ // 年:按周分列,周一起头
393
+ const yearStart = new Date(to.getFullYear(), 0, 1)
394
+ const yearEnd = new Date(to.getFullYear(), 11, 31)
395
+ const cursor = new Date(yearStart)
396
+ cursor.setDate(cursor.getDate() - ((cursor.getDay() + 6) % 7))
397
+ const cells = []
398
+ const months = []
399
+ let lastMonth = -1
400
+ while (cursor <= yearEnd) {
401
+ const inside = new Date(Math.max(cursor.getTime(), yearStart.getTime()))
402
+ months.push(inside.getMonth() !== lastMonth ? t.months[inside.getMonth()] : '')
403
+ lastMonth = inside.getMonth()
404
+ for (let i = 0; i < 7; i += 1) {
405
+ const date = new Date(cursor)
406
+ date.setDate(cursor.getDate() + i)
407
+ if (date < yearStart || date > yearEnd || date > to) {
408
+ cells.push({ key: `${date.getTime()}`, blank: true })
409
+ continue
410
+ }
411
+ const cell = cellOf(date)
412
+ cell.label = shortDay(cell.key)
413
+ cells.push(cell)
414
+ }
415
+ cursor.setDate(cursor.getDate() + 7)
416
+ }
417
+ return { kind: 'year', cells, months, columns: months.length }
418
+ }
419
+
420
+ window.__ModuleLoader__.load({
421
+ id: 'dsh-usage-prism',
422
+ factory(require) {
423
+ const React = require('react')
424
+ const h = React.createElement
425
+
426
+ /** `apply()` 给的 ctx,这里只用来读语言配置。 */
427
+ let clientCtx = null
428
+
429
+ /**
430
+ * 当前语言的一份文案。优先问 locale 服务(`resolveText` 走回退链:简体中文拿 zh,
431
+ * 其余落到 en);服务形状不对时退回自己读 active 语言。
432
+ */
433
+ function currentText() {
434
+ const locale = clientCtx?.locale
435
+ try {
436
+ const resolved = locale?.resolveText?.(TEXT)
437
+ if (resolved !== null && typeof resolved === 'object') return resolved
438
+ } catch {
439
+ /* 服务形状变了就退到下面那条路 */
440
+ }
441
+ try {
442
+ const snapshot = locale?.getLocale?.() ?? locale?.getSnapshot?.() ?? {}
443
+ const id = String(snapshot.active ?? snapshot.id ?? 'en')
444
+ return /^zh/i.test(id) ? TEXT.zh : TEXT.en
445
+ } catch {
446
+ return TEXT.en
447
+ }
448
+ }
449
+
450
+ /** 跟着 dsh 的语言设置走:切语言不重载页面,只重渲染这一块。 */
451
+ function useText() {
452
+ const [text, setText] = React.useState(currentText)
453
+ React.useEffect(() => {
454
+ const locale = clientCtx?.locale
455
+ if (typeof locale?.subscribe !== 'function') return undefined
456
+ return locale.subscribe(() => setText(currentText()))
457
+ }, [])
458
+ return text
459
+ }
460
+
461
+ function UsageIcon(props) {
462
+ const size = props?.size ?? 20
463
+ const active = props?.active === true
464
+ return h(
465
+ 'svg',
466
+ {
467
+ width: size,
468
+ height: size,
469
+ viewBox: '0 0 20 20',
470
+ fill: 'none',
471
+ 'aria-hidden': true,
472
+ style: { display: 'block' },
473
+ },
474
+ h('rect', { x: 3, y: 10, width: 3.2, height: 7, rx: 1, fill: 'currentColor', opacity: active ? 1 : 0.55 }),
475
+ h('rect', { x: 8.4, y: 5, width: 3.2, height: 12, rx: 1, fill: 'currentColor', opacity: active ? 1 : 0.8 }),
476
+ h('rect', { x: 13.8, y: 8, width: 3.2, height: 9, rx: 1, fill: 'currentColor', opacity: active ? 1 : 0.4 }),
477
+ )
478
+ }
479
+
480
+ function useSnapshot(scope) {
481
+ // 先清空再取:切换尺度时旧尺度的数字不能在标题边上留一秒。
482
+ const [state, setState] = React.useState({ status: 'loading' })
483
+ React.useEffect(() => {
484
+ let alive = true
485
+ setState((prev) => (prev.status === 'ready' && prev.scope === scope ? { ...prev, status: 'ready' } : { status: 'loading', scope }))
486
+ fetch(`/api/usage-prism?scope=${encodeURIComponent(scope)}`, { headers: { accept: 'application/json' } })
487
+ .then(async (response) => {
488
+ const body = await response.json().catch(() => ({}))
489
+ if (!response.ok) throw new Error(body?.error ?? `HTTP ${response.status}`)
490
+ return body
491
+ })
492
+ .then((body) => {
493
+ if (alive) setState({ status: 'ready', scope, data: body })
494
+ })
495
+ .catch((error) => {
496
+ if (alive) setState({ status: 'error', scope, error: error instanceof Error ? error.message : String(error) })
497
+ })
498
+ return () => {
499
+ alive = false
500
+ }
501
+ }, [scope])
502
+ return state
503
+ }
504
+
505
+ /**
506
+ * 悬浮卡:贴光标所在格子的右侧,右边放不下换左侧,纵向跟格子居中对齐。
507
+ * 位置在首次绘制前按实际尺寸算好,所以卡片不压在格子上;纵向又夹在面板可见范围里,
508
+ * 面板滚到顶时也不会被上沿切掉。
509
+ */
510
+ function HoverCard({ tip }) {
511
+ const ref = React.useRef(null)
512
+ const anchor = tip?.anchor ?? null
513
+ React.useLayoutEffect(() => {
514
+ const node = ref.current
515
+ const host = node?.parentElement
516
+ if (!node || !host || anchor === null) return
517
+ const box = host.getBoundingClientRect()
518
+ const root = node.closest('.up-root')
519
+ const view = (root ?? host).getBoundingClientRect()
520
+ const spot = placeTip(
521
+ anchor,
522
+ { width: host.clientWidth },
523
+ { top: view.top - box.top, bottom: view.bottom - box.top },
524
+ { width: node.offsetWidth, height: node.offsetHeight },
525
+ )
526
+ node.style.left = `${spot.left}px`
527
+ node.style.top = `${spot.top}px`
528
+ }, [anchor])
529
+
530
+ if (!tip) return null
531
+ return h(
532
+ 'div',
533
+ { ref, className: 'up-tip' },
534
+ h('b', null, tip.head),
535
+ ...tip.models.map((row, index) =>
536
+ h(
537
+ 'div',
538
+ { className: 'up-tp', key: `m${index}` },
539
+ h('i', { className: 'up-dot', style: { background: ['var(--up-rose-4)', 'var(--up-mint)', 'light-dark(#d3cbd0,#776f74)'][index % 3] } }),
540
+ row.key,
541
+ h('b', null, `${fmtTok(row.tokens)}`),
542
+ ),
543
+ ),
544
+ tip.other === null || tip.other === undefined
545
+ ? null
546
+ : h(
547
+ 'div',
548
+ { className: 'up-tp', key: 'other' },
549
+ h('i', { className: 'up-dot', style: { background: 'light-dark(#d3cbd0,#776f74)' } }),
550
+ tip.other.label,
551
+ h('b', null, fmtTok(tip.other.tokens)),
552
+ ),
553
+ ...tip.subs.map((text, index) => h('div', { className: 'up-x', key: `s${index}` }, text)),
554
+ )
555
+ }
556
+
557
+ function Calendar({ data, cal, onHover, tip, t = TEXT.en }) {
558
+ if (cal === null) return null
559
+ const cells = cal.cells
560
+ const level = levelScale(cells)
561
+
562
+ const cellNode = (cell, index) => {
563
+ if (cell.blank) return h('div', { className: 'up-cell', key: cell.key ?? `b${index}`, style: { opacity: 0 } })
564
+ const common = {
565
+ className: 'up-cell',
566
+ key: cell.key,
567
+ 'data-lv': String(level(cell.tokens)),
568
+ 'data-now': cell.now || (cal.kind === 'hours' && cell.hour === new Date().getHours() && data.scope === 'day') ? '1' : '0',
569
+ onMouseEnter: (event) => onHover(cell, event.currentTarget),
570
+ onMouseLeave: () => onHover(null, null),
571
+ }
572
+ return h('div', common, cal.kind === 'month' || cal.kind === 'week' ? h('span', { className: 'up-num' }, cell.dayNum) : null)
573
+ }
574
+
575
+ if (cal.kind === 'hours') {
576
+ return h(
577
+ 'div',
578
+ { className: 'up-cal', 'data-kind': 'day' },
579
+ h('div', { className: 'up-grid', style: { gridTemplateColumns: 'repeat(24,minmax(0,1fr))', gap: '3px' } }, ...cells.map(cellNode)),
580
+ h(
581
+ 'div',
582
+ { className: 'up-labels', style: { gridTemplateColumns: 'repeat(24,minmax(0,1fr))', gap: '3px' } },
583
+ ...cells.map((cell) => h('span', { key: `l${cell.hour}` }, cell.hour % 3 === 0 ? String(cell.hour) : '')),
584
+ ),
585
+ h(HoverCard, { tip }),
586
+ )
587
+ }
588
+
589
+ if (cal.kind === 'week') {
590
+ return h(
591
+ 'div',
592
+ { className: 'up-cal', 'data-kind': 'week' },
593
+ h('div', { className: 'up-grid', style: { gridTemplateColumns: 'repeat(7,minmax(0,1fr))', gap: '6px', maxWidth: '520px' } },
594
+ ...cells.map((cell) =>
595
+ h(
596
+ 'div',
597
+ {
598
+ className: 'up-cell',
599
+ key: cell.key,
600
+ 'data-lv': String(level(cell.tokens)),
601
+ 'data-now': cell.now ? '1' : '0',
602
+ onMouseEnter: (event) => onHover(cell, event.currentTarget),
603
+ onMouseLeave: () => onHover(null, null),
604
+ },
605
+ h('span', { className: 'up-num', style: { left: '5px', top: '3px', fontSize: '10px' } }, cell.dayNum),
606
+ ),
607
+ )),
608
+ h(
609
+ 'div',
610
+ { className: 'up-labels', style: { gridTemplateColumns: 'repeat(7,minmax(0,1fr))', gap: '6px', maxWidth: '520px' } },
611
+ ...cells.map((cell, index) => {
612
+ const date = parseDay(cell.key)
613
+ return h(
614
+ 'span',
615
+ { key: `d${index}` },
616
+ t.weekday[date.getDay()],
617
+ cell.now ? h('span', { className: 'up-tdy' }, ` ${t.today}`) : null,
618
+ )
619
+ }),
620
+ ),
621
+ h(HoverCard, { tip }),
622
+ )
623
+ }
624
+
625
+ if (cal.kind === 'month') {
626
+ return h(
627
+ 'div',
628
+ { className: 'up-cal', 'data-kind': 'month' },
629
+ h(
630
+ 'div',
631
+ { className: 'up-labels', style: { gridTemplateColumns: 'repeat(7,minmax(0,1fr))', gap: '4px', maxWidth: '560px', marginTop: 0, marginBottom: '4px' } },
632
+ ...[1, 2, 3, 4, 5, 6, 0].map((index) => h('span', { key: index }, t.weekday[index])),
633
+ ),
634
+ h(
635
+ 'div',
636
+ { className: 'up-grid', style: { gridTemplateColumns: 'repeat(7,minmax(0,1fr))', gap: '4px', maxWidth: '560px' } },
637
+ ...cells.map((cell, index) =>
638
+ cell.blank
639
+ ? h('div', { key: `b${index}` })
640
+ : h(
641
+ 'div',
642
+ {
643
+ className: 'up-cell',
644
+ key: cell.key,
645
+ 'data-lv': String(level(cell.tokens)),
646
+ 'data-now': cell.now ? '1' : '0',
647
+ onMouseEnter: (event) => onHover(cell, event.currentTarget),
648
+ onMouseLeave: () => onHover(null, null),
649
+ },
650
+ h('span', { className: 'up-num' }, cell.dayNum),
651
+ ),
652
+ ),
653
+ ),
654
+ h(HoverCard, { tip }),
655
+ )
656
+ }
657
+
658
+ // 年
659
+ const columns = cal.columns
660
+ return h(
661
+ 'div',
662
+ { className: 'up-cal', 'data-kind': 'year' },
663
+ h(
664
+ 'div',
665
+ { className: 'up-months', style: { gridTemplateColumns: `repeat(${columns},minmax(0,1fr))`, columnGap: '2px' } },
666
+ ...cal.months.map((label, index) => h('span', { key: `m${index}` }, label)),
667
+ ),
668
+ h(
669
+ 'div',
670
+ {
671
+ className: 'up-grid',
672
+ style: {
673
+ gridTemplateColumns: `repeat(${columns},minmax(0,1fr))`,
674
+ gridTemplateRows: 'repeat(7,1fr)',
675
+ gridAutoFlow: 'column',
676
+ columnGap: '2px',
677
+ rowGap: '2px',
678
+ marginLeft: '22px',
679
+ },
680
+ },
681
+ ...cells.map((cell, index) =>
682
+ cell.blank
683
+ ? h('div', { key: `b${index}`, className: 'up-cell' })
684
+ : h('div', {
685
+ className: 'up-cell',
686
+ key: cell.key,
687
+ 'data-lv': String(level(cell.tokens)),
688
+ 'data-now': cell.now ? '1' : '0',
689
+ onMouseEnter: (event) => onHover(cell, event.currentTarget),
690
+ onMouseLeave: () => onHover(null, null),
691
+ }),
692
+ ),
693
+ ),
694
+ h(HoverCard, { tip }),
695
+ )
696
+ }
697
+
698
+ function Summary({ data, t = TEXT.en }) {
699
+ const totals = data.totals ?? {}
700
+ const cacheRate = (totals.inTok ?? 0) > 0 ? pct(totals.cacheRead, totals.inTok) : null
701
+ // 图例上的占比:输入 / 输出是同一个总量的两半(tokens = inTok + outTok)。
702
+ // 输入四舍五入到一位小数、输出直接取补数,两项必然正好合 100.0;
703
+ // 这样也避开了「99.5 / 0.5 各自取整后变成 100% / 0%」。
704
+ const tokens = Math.max(0, totals.tokens ?? 0)
705
+ const inShare = tokens > 0 ? Math.round((Math.min(totals.inTok ?? 0, tokens) / tokens) * 1000) / 10 : null
706
+ const outShare = inShare === null ? null : Math.round((100 - inShare) * 10) / 10
707
+ // 输入侧几乎全是缓存重读,整条画成一个颜色就看不出别的了,
708
+ // 所以这条进度条分三段:缓存读 / 新输入 / 输出。
709
+ const cached = Math.max(0, Math.min(totals.cacheRead ?? 0, totals.inTok ?? 0))
710
+ const fresh = Math.max(0, (totals.inTok ?? 0) - cached)
711
+ const total = Math.max(1, tokens)
712
+ return h(
713
+ 'div',
714
+ { className: 'up-col' },
715
+ h(
716
+ 'div',
717
+ { className: 'up-c1 up-sec-h' },
718
+ h('h2', null, t.scopes[data.scope]),
719
+ h('span', { className: 'up-range' }, `${shortDay(data.from)}${data.from === data.to ? '' : ` – ${shortDay(data.to)}`}`),
720
+ ),
721
+ // 用量卡只说量:时间(运行时长与三个桶)都归右边的时间卡
722
+ h(
723
+ 'div',
724
+ { className: 'up-c2 up-sum-row' },
725
+ h('div', { className: 'up-big' }, h('b', null, fmtTok(totals.tokens)), h('span', null, t.tokens)),
726
+ ),
727
+ h(
728
+ 'div',
729
+ { className: 'up-c3' },
730
+ h(
731
+ 'div',
732
+ { className: 'up-bar' },
733
+ h('i', { className: 'up-cached', style: { width: `${pct(cached, total)}%` } }),
734
+ h('i', { className: 'up-in', style: { width: `${pct(fresh, total)}%` } }),
735
+ h('i', { className: 'up-out', style: { width: `${pct(totals.outTok, total)}%` } }),
736
+ ),
737
+ ),
738
+ h(
739
+ 'div',
740
+ { className: 'up-c4' },
741
+ h(
742
+ 'div',
743
+ { className: 'up-ioms' },
744
+ h(
745
+ 'span',
746
+ { className: 'up-lg' },
747
+ h('i', { className: 'up-sw', style: { background: 'var(--up-rose)' } }),
748
+ `${t.inLabel} `,
749
+ h('b', null, fmtTok(totals.inTok)),
750
+ inShare === null ? null : h('em', null, `${inShare}%`),
751
+ ),
752
+ h(
753
+ 'span',
754
+ { className: 'up-lg' },
755
+ h('i', { className: 'up-sw', style: { background: 'var(--up-mint)' } }),
756
+ `${t.outLabel} `,
757
+ h('b', null, fmtTok(totals.outTok)),
758
+ outShare === null ? null : h('em', null, `${outShare}%`),
759
+ ),
760
+ cacheRate === null
761
+ ? null
762
+ : h(
763
+ 'span',
764
+ { className: 'up-cache' },
765
+ t.cache,
766
+ h('i', { className: 'up-meter' }, h('i', { style: { width: `${cacheRate}%` } })),
767
+ h('b', null, `${cacheRate}%`),
768
+ ),
769
+ ),
770
+ h(
771
+ 'div',
772
+ { className: 'up-meta' },
773
+ h('span', null, h('b', null, totals.sessions ?? 0), ` ${t.sessions}`),
774
+ h('span', null, h('b', null, totals.turns ?? 0), ` ${t.turns}`),
775
+ h('span', null, h('b', null, totals.steps ?? 0), ` ${t.steps}`),
776
+ h('span', null, h('b', null, totals.tools ?? 0), ` ${t.tools}`),
777
+ ),
778
+ ),
779
+ )
780
+ }
781
+
782
+ function TimeSplit({ data, t = TEXT.en }) {
783
+ const totals = data.totals ?? {}
784
+ const wait = totals.waitMs ?? 0
785
+ const gen = totals.genMs ?? 0
786
+ const tool = totals.toolMs ?? 0
787
+ const total = wait + gen + tool
788
+ const parts = [
789
+ { key: 'wait', label: t.wait, ms: wait, color: '--up-lilac' },
790
+ { key: 'gen', label: t.gen, ms: gen, color: '--up-rose' },
791
+ { key: 'tool', label: t.tool, ms: tool, color: '--up-mint' },
792
+ ]
793
+ return h(
794
+ 'div',
795
+ { className: 'up-col' },
796
+ h('div', { className: 'up-c1 up-sec-h' }, h('h2', null, t.timeSplit)),
797
+ // 时间卡只说时间:大数字就是下面三个桶相加
798
+ h(
799
+ 'div',
800
+ { className: 'up-c2 up-sum-row' },
801
+ h('div', { className: 'up-big' }, h('b', null, fmtDur(total)), h('span', null, t.runtime)),
802
+ ),
803
+ h(
804
+ 'div',
805
+ { className: 'up-c3' },
806
+ h(
807
+ 'div',
808
+ { className: 'up-bar' },
809
+ ...parts.map((part) => h('i', { key: part.key, className: `up-${part.key}`, style: { width: `${pct(part.ms, total)}%` } })),
810
+ ),
811
+ ),
812
+ h(
813
+ 'div',
814
+ { className: 'up-c4' },
815
+ total === 0
816
+ ? h('div', { className: 'up-empty' }, t.nothingHere)
817
+ : h(
818
+ 'div',
819
+ { className: 'up-buckets' },
820
+ ...parts.map((part) =>
821
+ h(
822
+ 'span',
823
+ { className: 'up-bk', key: part.key },
824
+ h('i', { className: 'up-sw', style: { background: `var(${part.color})` } }),
825
+ part.label,
826
+ h('b', null, fmtDur(part.ms)),
827
+ h('em', null, `${pct(part.ms, total)}%`),
828
+ ),
829
+ ),
830
+ ),
831
+ ),
832
+ )
833
+ }
834
+
835
+ const COLUMNS = ['model', 'n', 'tokens', 'ttft', 'tps', 'cache']
836
+
837
+ function valueOf(row, key) {
838
+ if (key === 'model') return `${row.provider}/${row.model}`
839
+ if (key === 'ttft') return typeof row.ttftMs === 'number' ? row.ttftMs : null
840
+ if (key === 'cache') return typeof row.cacheRate === 'number' ? row.cacheRate : null
841
+ if (key === 'tps') return typeof row.tps === 'number' ? row.tps : null
842
+ return Number(row[key] ?? 0)
843
+ }
844
+
845
+ function Detail({ data, t = TEXT.en }) {
846
+ const [sort, setSort] = React.useState({ key: 'tokens', dir: -1 })
847
+ const rows = React.useMemo(() => {
848
+ const list = [...(data.models ?? [])]
849
+ list.sort((a, b) => {
850
+ const left = valueOf(a, sort.key)
851
+ const right = valueOf(b, sort.key)
852
+ if (typeof left === 'string' || typeof right === 'string') {
853
+ return sort.dir * String(left).localeCompare(String(right))
854
+ }
855
+ if (left === null && right === null) return 0
856
+ if (left === null) return 1
857
+ if (right === null) return -1
858
+ return sort.dir * (left - right)
859
+ })
860
+ return list
861
+ }, [data, sort])
862
+
863
+ const toggle = (key) => {
864
+ setSort((prev) => (prev.key === key ? { key, dir: -prev.dir } : { key, dir: -1 }))
865
+ }
866
+
867
+ const header = h(
868
+ 'div',
869
+ { className: 'up-row up-th' },
870
+ ...COLUMNS.map((key) =>
871
+ h(
872
+ 'button',
873
+ {
874
+ key,
875
+ type: 'button',
876
+ 'data-on': sort.key === key ? '1' : '0',
877
+ onClick: () => toggle(key),
878
+ },
879
+ t.columns[key],
880
+ h('span', { className: 'up-ar' }, sort.key === key ? (sort.dir < 0 ? '↓' : '↑') : ''),
881
+ ),
882
+ ),
883
+ )
884
+
885
+ const body = rows.map((row) => {
886
+ const dim = (key) => (sort.key === key ? '1' : '0')
887
+ return h(
888
+ 'div',
889
+ { className: 'up-row', key: row.key },
890
+ h('div', { className: 'up-name', title: row.key },
891
+ h('span', { className: 'up-pv' }, `${row.provider}/`),
892
+ row.model),
893
+ h('div', { className: 'up-n', 'data-on': dim('n') }, String(row.n ?? 0)),
894
+ h('div', { className: 'up-v', 'data-on': dim('tokens') }, fmtTok(row.tokens)),
895
+ h('div', { className: 'up-v', 'data-on': dim('ttft') }, typeof row.ttftMs === 'number' ? `${(row.ttftMs / 1000).toFixed(1)}s` : '—'),
896
+ h('div', { className: 'up-v', 'data-on': dim('tps') }, typeof row.tps === 'number' ? String(Math.round(row.tps)) : '—'),
897
+ h('div', { className: 'up-v', 'data-on': dim('cache') }, typeof row.cacheRate === 'number' ? `${Math.round(row.cacheRate * 100)}%` : '—'),
898
+ )
899
+ })
900
+
901
+ return h(
902
+ 'div',
903
+ { className: 'up-detail' },
904
+ h('div', { className: 'up-sec-h' }, h('h2', null, t.detail)),
905
+ rows.length === 0
906
+ ? h('div', { className: 'up-empty' }, t.noModels)
907
+ : h('div', { className: 'up-rows' }, header, ...body),
908
+ )
909
+ }
910
+
911
+ /** 渲染兜底:面板里哪一处抛了异常,就把原因画出来,别留一块白。 */
912
+ class Boundary extends React.Component {
913
+ constructor(props) {
914
+ super(props)
915
+ this.state = { error: null }
916
+ }
917
+
918
+ static getDerivedStateFromError(error) {
919
+ return { error }
920
+ }
921
+
922
+ render() {
923
+ if (this.state.error !== null) {
924
+ const message = this.state.error?.message ?? String(this.state.error)
925
+ return h(
926
+ 'div',
927
+ { className: 'up-root' },
928
+ h('style', null, CSS),
929
+ h('div', { className: 'up-inner' }, h('div', { className: 'up-err' }, `panel crashed: ${message}`)),
930
+ )
931
+ }
932
+ return this.props.children
933
+ }
934
+ }
935
+
936
+ /**
937
+ * `snapshot` / `initialScope` 是给测试与截图留的入口:直接给一份快照就照着画,
938
+ * 不去取数据。dsh 装载面板时不传这两个参数,行为完全不变。
939
+ */
940
+ function Panel({ snapshot = null, initialScope = 'week' } = {}) {
941
+ const t = useText()
942
+ const [scope, setScope] = React.useState(initialScope)
943
+ const live = useSnapshot(scope)
944
+ const state = snapshot === null ? live : { status: 'ready', scope, data: snapshot[scope] }
945
+ const [tip, setTip] = React.useState(null)
946
+ const calRef = React.useRef(null)
947
+
948
+ const onHover = React.useCallback((cell, node) => {
949
+ if (cell === null || node === null || !calRef.current) {
950
+ setTip(null)
951
+ return
952
+ }
953
+ const host = calRef.current
954
+ const box = node.getBoundingClientRect()
955
+ const origin = host.getBoundingClientRect()
956
+ setTip({
957
+ anchor: {
958
+ left: box.left - origin.left,
959
+ right: box.right - origin.left,
960
+ top: box.top - origin.top,
961
+ bottom: box.bottom - origin.top,
962
+ },
963
+ head: `${cell.label ?? cell.key} · ${fmtTok(cell.tokens)} tokens`,
964
+ models: (cell.row?.models ?? []).map((row) => ({ key: row.key, tokens: row.tokens })),
965
+ // 只列前 3 名,剩下的并成一行,否则卡片各行的和跟格子的 tokens 对不上。
966
+ other:
967
+ (cell.row?.otherTokens ?? 0) > 0
968
+ ? {
969
+ label: t.otherModels(Math.max(1, (cell.row?.modelCount ?? 0) - (cell.row?.models?.length ?? 0))),
970
+ tokens: cell.row.otherTokens,
971
+ }
972
+ : null,
973
+ subs: cell.row === null
974
+ ? [t.noRecord]
975
+ : [
976
+ `${t.inLabel} ${fmtTok(cell.row.inTok)} · ${t.outLabel} ${fmtTok(cell.row.outTok)}`,
977
+ (cell.row.inTok ?? 0) > 0
978
+ ? `${t.columns.cache} ${pct(cell.row.cacheRead, cell.row.inTok)}%`
979
+ : null,
980
+ [cell.row.sessions ? `${cell.row.sessions} ${t.sessions}` : null, `${cell.row.turns ?? 0} ${t.turns}`, `${cell.row.steps ?? 0} ${t.steps}`, `${cell.row.tools ?? 0} ${t.tools}`]
981
+ .filter(Boolean)
982
+ .join(' · '),
983
+ ].filter(Boolean),
984
+ })
985
+ }, [])
986
+
987
+ const data = state.status === 'ready' ? state.data : null
988
+ const cal = data === null ? null : buildCalendar(data, t)
989
+
990
+ return h(
991
+ Boundary,
992
+ null,
993
+ h(
994
+ 'div',
995
+ { className: 'up-root' },
996
+ h('style', null, CSS),
997
+ h(
998
+ 'div',
999
+ { className: 'up-inner' },
1000
+ h(
1001
+ 'div',
1002
+ { className: 'up-head' },
1003
+ h('h1', null, t.panel),
1004
+ h('span', { className: 'up-sub' }, t.sub),
1005
+ h('span', { className: 'up-sp' }),
1006
+ h('span', { className: 'up-stamp' }, data === null ? '' : `${t.through} ${shortDay(data.today)}`),
1007
+ ),
1008
+ h(
1009
+ 'div',
1010
+ { className: 'up-chips' },
1011
+ ...SCOPES.map((item) =>
1012
+ h(
1013
+ 'button',
1014
+ {
1015
+ key: item,
1016
+ type: 'button',
1017
+ className: 'up-chip',
1018
+ 'data-on': item === scope ? '1' : '0',
1019
+ onClick: () => setScope(item),
1020
+ },
1021
+ t.scopes[item],
1022
+ ),
1023
+ ),
1024
+ ),
1025
+ state.status === 'error'
1026
+ ? h('div', { className: 'up-err' }, `${t.loadError}${state.error}`)
1027
+ : data === null
1028
+ ? h('div', { className: 'up-empty' }, t.loading)
1029
+ : h(
1030
+ 'div',
1031
+ { ref: calRef },
1032
+ h(Calendar, { data, cal, onHover, tip, t }),
1033
+ ),
1034
+ data === null
1035
+ ? null
1036
+ : h(
1037
+ 'div',
1038
+ { className: 'up-cols' },
1039
+ h(Summary, { data, t }),
1040
+ h(TimeSplit, { data, t }),
1041
+ ),
1042
+ data === null ? null : h(Detail, { data, t }),
1043
+ data === null || (data.corpus?.skipped ?? 0) === 0
1044
+ ? null
1045
+ : h('div', { className: 'up-note' }, t.skipped(data.corpus.skipped)),
1046
+ ),
1047
+ ),
1048
+ )
1049
+ }
1050
+
1051
+ return {
1052
+ inject: ['slots', 'locale'],
1053
+ // 测试缝:`test/render.test.mjs` 用假 React 直接调这些组件,不需要浏览器。
1054
+ __parts: {
1055
+ Panel,
1056
+ Summary,
1057
+ TimeSplit,
1058
+ Detail,
1059
+ Calendar,
1060
+ HoverCard,
1061
+ buildCalendar,
1062
+ placeTip,
1063
+ levelScale,
1064
+ fmtTok,
1065
+ TEXT,
1066
+ CSS,
1067
+ },
1068
+ apply(ctx) {
1069
+ clientCtx = ctx
1070
+ ctx.slots.inject('sidebar.panellist', () =>
1071
+ ctx.slots.register(
1072
+ { name: 'sidebar.panellist', id: PANEL_ID, order: 12, label: () => currentText().panel },
1073
+ UsageIcon,
1074
+ ),
1075
+ )
1076
+ ctx.slots.inject('main', () => ctx.slots.register({ name: 'main', key: PANEL_ID }, Panel))
1077
+ },
1078
+ }
1079
+ },
1080
+ })