dsh-plugin-system-status 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,1086 @@
1
+ window.__ModuleLoader__.load({
2
+ id: 'dsh-plugin-system-status',
3
+ factory(require) {
4
+ const React = require('react')
5
+ const h = React.createElement
6
+
7
+ const NS = 'system-status'
8
+ const STREAM_URL = '/dsh-system-status/stream'
9
+ const HISTORY_URL = '/dsh-system-status/history'
10
+ const RANGES = ['1h', '6h', '24h', '7d']
11
+ const RANGE_MS = { '1h': 3600e3, '6h': 6 * 3600e3, '24h': 24 * 3600e3, '7d': 7 * 24 * 3600e3 }
12
+ const STALE_AFTER_MS = 8000
13
+
14
+ const DICT = {
15
+ zh: {
16
+ panelTitle: '系统状态',
17
+ barLabel: '系统状态',
18
+ openHistory: '查看历史曲线',
19
+ history: '历史',
20
+ cpu: 'CPU',
21
+ mem: '内存',
22
+ gpu: 'GPU',
23
+ vram: '显存',
24
+ temp: '温度',
25
+ unavailable: '不可用',
26
+ gpuUnavailable: '未检测到可用 GPU',
27
+ connecting: '连接中',
28
+ reconnecting: '重连中',
29
+ stale: '数据已过期',
30
+ failed: '实时连接失败',
31
+ historyTitle: '系统状态历史',
32
+ range1h: '近 1 小时',
33
+ range6h: '近 6 小时',
34
+ range24h: '近 24 小时',
35
+ range7d: '近 7 天',
36
+ rangeGroup: '时间范围',
37
+ loading: '加载中…',
38
+ empty: '这段时间没有记录。',
39
+ loadFailed: '读取历史失败',
40
+ retry: '重试',
41
+ refresh: '刷新',
42
+ disabledStorage: '历史目录不可写,只保留实时数据。',
43
+ unreadableStorage: '历史目录读取失败。',
44
+ runtimeOnly: '仅在 DSH 运行时记录;DSH 关闭期间没有数据。',
45
+ window: '窗口',
46
+ covered: '数据覆盖',
47
+ lastSample: '最后采样',
48
+ cpuTitle: 'CPU 使用率',
49
+ gpuTitle: 'GPU 使用率',
50
+ memory: '内存使用率',
51
+ vramTitle: '显存使用率',
52
+ temperature: 'GPU 温度',
53
+ disks: '磁盘已用空间',
54
+ usedPercent: '已用',
55
+ free: '剩余',
56
+ total: '总量',
57
+ hoverHint: '在图上移动查看具体数值',
58
+ latest: '最新',
59
+ singlePoint: '数据还不够画出曲线,DSH 再运行一会儿就有趋势了。',
60
+ },
61
+ en: {
62
+ panelTitle: 'System status',
63
+ barLabel: 'System status',
64
+ openHistory: 'Open history charts',
65
+ history: 'History',
66
+ cpu: 'CPU',
67
+ mem: 'Memory',
68
+ gpu: 'GPU',
69
+ vram: 'VRAM',
70
+ temp: 'Temp',
71
+ unavailable: 'unavailable',
72
+ gpuUnavailable: 'No usable GPU detected',
73
+ connecting: 'Connecting',
74
+ reconnecting: 'Reconnecting',
75
+ stale: 'Stale',
76
+ failed: 'Live connection failed',
77
+ historyTitle: 'System status history',
78
+ range1h: 'Last hour',
79
+ range6h: 'Last 6 hours',
80
+ range24h: 'Last 24 hours',
81
+ range7d: 'Last 7 days',
82
+ rangeGroup: 'Time range',
83
+ loading: 'Loading…',
84
+ empty: 'Nothing recorded in this window.',
85
+ loadFailed: 'Could not read history',
86
+ retry: 'Retry',
87
+ refresh: 'Refresh',
88
+ disabledStorage: 'The history directory is not writable, so only live data remains.',
89
+ unreadableStorage: 'The history directory could not be read.',
90
+ runtimeOnly: 'Recorded only while DSH runs; nothing is captured while it is closed.',
91
+ window: 'Window',
92
+ covered: 'Covered',
93
+ lastSample: 'Last sample',
94
+ cpuTitle: 'CPU utilization',
95
+ gpuTitle: 'GPU utilization',
96
+ memory: 'Memory in use',
97
+ vramTitle: 'VRAM in use',
98
+ temperature: 'GPU temperature',
99
+ disks: 'Disk usage',
100
+ usedPercent: 'used',
101
+ free: 'free',
102
+ total: 'total',
103
+ hoverHint: 'Move over a chart to read values',
104
+ latest: 'Latest',
105
+ singlePoint: 'Not enough samples for a curve yet; trend appears after DSH runs a little longer.',
106
+ },
107
+ }
108
+
109
+ /** Localized text through the Client locale service, with an inline fallback. */
110
+ function createTranslator(ctx) {
111
+ const locale = typeof ctx.get === 'function' ? ctx.get('locale') : null
112
+ const disposers = []
113
+ let translate = null
114
+ if (locale) {
115
+ try {
116
+ for (const [id, dict] of Object.entries(DICT)) {
117
+ const dispose = locale.register(NS, id, dict)
118
+ if (typeof dispose === 'function') disposers.push(dispose)
119
+ }
120
+ } catch {
121
+ /* the inline dictionaries below still work */
122
+ }
123
+ try {
124
+ translate = locale.bind(NS)
125
+ } catch {
126
+ translate = null
127
+ }
128
+ }
129
+ const activeIsChinese = () => {
130
+ try {
131
+ return String(locale?.getLocale?.().active ?? 'en').toLowerCase().startsWith('zh')
132
+ } catch {
133
+ return false
134
+ }
135
+ }
136
+ return {
137
+ disposers,
138
+ t(key) {
139
+ if (translate !== null) {
140
+ try {
141
+ const value = translate(key)
142
+ if (typeof value === 'string' && value !== '' && value !== key) return value
143
+ } catch {
144
+ /* fall through to the inline dictionary */
145
+ }
146
+ }
147
+ const dict = activeIsChinese() ? DICT.zh : DICT.en
148
+ return dict[key] ?? DICT.en[key] ?? key
149
+ },
150
+ subscribe: typeof locale?.subscribe === 'function' ? (fn) => locale.subscribe(fn) : null,
151
+ }
152
+ }
153
+
154
+ function useLocaleRevision(translator) {
155
+ const [, force] = React.useState(0)
156
+ React.useEffect(() => {
157
+ if (translator.subscribe === null) return undefined
158
+ return translator.subscribe(() => force((value) => value + 1))
159
+ }, [translator])
160
+ }
161
+
162
+ const formatPercent = (value) => (Number.isFinite(value) ? `${Math.round(value)}%` : '—')
163
+ const formatGiB = (bytes) => (Number.isFinite(bytes) ? `${(bytes / 1024 ** 3).toFixed(1)}G` : '—')
164
+ // nvidia-smi reports VRAM in MiB, not bytes.
165
+ const formatVram = (mib) => (Number.isFinite(mib) ? `${(mib / 1024).toFixed(1)}G` : '—')
166
+ const formatTemp = (value) => (Number.isFinite(value) ? `${Math.round(value)}°C` : '—')
167
+ const pad = (value) => String(value).padStart(2, '0')
168
+ const formatClock = (t) => {
169
+ if (!Number.isFinite(t)) return ''
170
+ const date = new Date(t)
171
+ return `${pad(date.getHours())}:${pad(date.getMinutes())}`
172
+ }
173
+ const formatClockSeconds = (t) => {
174
+ if (!Number.isFinite(t)) return ''
175
+ const date = new Date(t)
176
+ return `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
177
+ }
178
+ const formatStamp = (t) => {
179
+ if (!Number.isFinite(t)) return ''
180
+ const date = new Date(t)
181
+ return `${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${formatClockSeconds(t)}`
182
+ }
183
+
184
+ const CSS = `
185
+ .dss-dock{position:relative;display:flex;align-items:center;min-width:0;max-width:100%;flex:1 1 auto;font-family:inherit}
186
+ .dss-dock__hit{display:flex;align-items:center;gap:8px;min-width:0;max-width:100%;border:0;background:transparent;color:var(--dsw-alias-label-secondary);font:inherit;font-size:12px;line-height:18px;padding:2px 8px;border-radius:6px;cursor:pointer;text-align:left}
187
+ .dss-dock__hit:hover{background:var(--dsw-alias-border-l2);color:var(--dsw-alias-label-primary)}
188
+ .dss-dock__hit:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:1px}
189
+ .dss-dock__dot{width:6px;height:6px;border-radius:50%;flex:0 0 auto;background:var(--dsw-alias-state-success-primary)}
190
+ .dss-dock__dot[data-status="connecting"],.dss-dock__dot[data-status="reconnecting"]{background:var(--dsw-alias-state-warn-primary)}
191
+ .dss-dock__dot[data-status="stale"]{background:var(--dsw-alias-state-warn-primary)}
192
+ .dss-dock__dot[data-status="failed"]{background:var(--dsw-alias-state-error-primary)}
193
+ .dss-dock__readout{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex:0 1 auto}
194
+ .dss-dock__readout b{font-weight:500;color:var(--dsw-alias-label-primary);font-variant-numeric:tabular-nums}
195
+ .dss-dock__sep{opacity:.5;padding:0 2px}
196
+ .dss-dock__status{color:var(--dsw-alias-label-secondary);flex:0 0 auto}
197
+ .dss-sr{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0}
198
+ .dss-page{height:100%;overflow:auto;box-sizing:border-box;padding:28px 24px 48px;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-base);font-size:14px;line-height:1.6}
199
+ .dss-page__inner{max-width:960px;margin:0 auto}
200
+ .dss-page__head{display:flex;align-items:flex-start;gap:12px;flex-wrap:wrap;margin-bottom:20px}
201
+ .dss-page__titles{min-width:0}
202
+ .dss-page__title{margin:0;font-size:20px;font-weight:500;line-height:28px;outline:none}
203
+ .dss-page__sub{margin:2px 0 0;font-size:12px;color:var(--dsw-alias-label-secondary)}
204
+ .dss-page__ranges{display:flex;gap:6px;margin-left:auto;flex-wrap:wrap}
205
+ .dss-range{border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-secondary);border-radius:8px;padding:4px 12px;font:inherit;font-size:12px;line-height:20px;cursor:pointer}
206
+ .dss-range:hover{color:var(--dsw-alias-label-primary)}
207
+ .dss-range[data-active="true"]{border-color:var(--dsw-alias-brand-primary);color:var(--dsw-alias-label-primary)}
208
+ .dss-range:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:1px}
209
+ .dss-notice{border:1px solid var(--dsw-alias-border-l2);border-left:3px solid var(--dsw-alias-state-warn-primary);border-radius:8px;background:var(--dsw-alias-bg-layer-1);padding:8px 12px;margin-bottom:16px;font-size:12px;color:var(--dsw-alias-label-secondary)}
210
+ .dss-notice--error{border-left-color:var(--dsw-alias-state-error-primary)}
211
+ .dss-card{border:1px solid var(--dsw-alias-border-l2);border-radius:10px;background:var(--dsw-alias-bg-layer-1);padding:14px 16px;margin-bottom:16px}
212
+ .dss-card__head{display:flex;align-items:baseline;gap:10px;flex-wrap:wrap;margin-bottom:6px}
213
+ .dss-card__title{margin:0;font-size:14px;font-weight:500;color:var(--dsw-alias-label-primary)}
214
+ .dss-card__latest{font-size:11px;color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums}
215
+ .dss-card__legend{display:flex;gap:12px;margin-left:auto;font-size:11px;color:var(--dsw-alias-label-secondary)}
216
+ .dss-legend__swatch{display:inline-block;width:10px;height:2px;margin-right:5px;vertical-align:middle}
217
+ .dss-chart{display:block;width:100%;height:auto}
218
+ .dss-chart__grid{stroke:var(--dsw-alias-border-l2);stroke-width:0.5}
219
+ .dss-chart__axis{fill:var(--dsw-alias-label-secondary);font-size:10px}
220
+ .dss-chart__hoverline{stroke:var(--dsw-alias-label-secondary);stroke-width:0.5;opacity:.7}
221
+ .dss-chart__axisrow{display:flex;justify-content:space-between;gap:8px;font-size:11px;color:var(--dsw-alias-label-secondary);margin-top:2px}
222
+ .dss-chart__hoverinfo{color:var(--dsw-alias-label-primary);font-variant-numeric:tabular-nums;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
223
+ .dss-empty{padding:18px 0;text-align:center;color:var(--dsw-alias-label-secondary)}
224
+ .dss-error{color:var(--dsw-alias-state-error-primary)}
225
+ .dss-retry{margin-left:10px;border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-primary);border-radius:8px;padding:2px 10px;font:inherit;font-size:11px;cursor:pointer}
226
+ .dss-foot{margin-top:12px;font-size:11px;color:var(--dsw-alias-label-secondary)}
227
+ .dss-disk{display:grid;grid-template-columns:44px 1fr auto;align-items:center;gap:10px;margin-top:10px;font-size:12px}
228
+ .dss-disk__track{height:6px;border-radius:3px;background:var(--dsw-alias-border-l2);overflow:hidden}
229
+ .dss-disk__fill{display:block;height:100%;background:var(--dsw-alias-brand-primary)}
230
+ .dss-disk__value{color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums}
231
+ .dss-linkbtn{border:0;background:transparent;color:var(--dsw-alias-brand-primary);font:inherit;font-size:12px;cursor:pointer;padding:0 4px;margin-left:auto}
232
+ .dss-linkbtn:hover{text-decoration:underline}
233
+ `
234
+
235
+ const StyleTag = () => h('style', { key: 'dss-style' }, CSS)
236
+
237
+ /** Live sample stream with staleness detection and exponential-backoff reconnection. */
238
+ function useLiveSample() {
239
+ const [state, setState] = React.useState({ sample: null, status: 'connecting', lastFrameAt: 0 })
240
+ React.useEffect(() => {
241
+ let source = null
242
+ let retryTimer = null
243
+ let retryMs = 1000
244
+ let failures = 0
245
+ let disposed = false
246
+
247
+ const schedule = () => {
248
+ if (disposed) return
249
+ if (retryTimer !== null) clearTimeout(retryTimer)
250
+ retryTimer = setTimeout(connect, retryMs)
251
+ retryMs = Math.min(retryMs * 2, 30000)
252
+ }
253
+
254
+ function connect() {
255
+ if (disposed) return
256
+ let opening
257
+ try {
258
+ opening = new EventSource(STREAM_URL)
259
+ } catch {
260
+ setState((prev) => ({ ...prev, status: 'reconnecting' }))
261
+ schedule()
262
+ return
263
+ }
264
+ source = opening
265
+ opening.onopen = () => {
266
+ retryMs = 1000
267
+ failures = 0
268
+ setState((prev) => ({ ...prev, status: 'live' }))
269
+ }
270
+ opening.onmessage = (event) => {
271
+ let sample
272
+ try {
273
+ sample = JSON.parse(event.data)
274
+ } catch {
275
+ return
276
+ }
277
+ failures = 0
278
+ setState({ sample, status: 'live', lastFrameAt: Date.now() })
279
+ }
280
+ opening.onerror = () => {
281
+ failures += 1
282
+ setState((prev) => ({ ...prev, status: failures > 5 ? 'failed' : 'reconnecting' }))
283
+ try {
284
+ opening.close()
285
+ } catch {
286
+ /* already closed */
287
+ }
288
+ source = null
289
+ schedule()
290
+ }
291
+ }
292
+
293
+ connect()
294
+ const watchdog = setInterval(() => {
295
+ setState((prev) => {
296
+ if (prev.lastFrameAt === 0 || prev.status !== 'live') return prev
297
+ if (Date.now() - prev.lastFrameAt <= STALE_AFTER_MS) return prev
298
+ return { ...prev, status: 'stale' }
299
+ })
300
+ }, 1000)
301
+
302
+ return () => {
303
+ disposed = true
304
+ clearInterval(watchdog)
305
+ if (retryTimer !== null) clearTimeout(retryTimer)
306
+ if (source !== null) {
307
+ try {
308
+ source.close()
309
+ } catch {
310
+ /* already closed */
311
+ }
312
+ }
313
+ }
314
+ }, [])
315
+ return state
316
+ }
317
+
318
+ /** Ambient live readout in the composer dock: one compact line plus a history link. */
319
+ function StatusBar({ translator, onOpenHistory }) {
320
+ const { t } = translator
321
+ useLocaleRevision(translator)
322
+ const { sample, status } = useLiveSample()
323
+
324
+ const gpu = sample?.gpu ?? null
325
+ const memUsed = sample?.mem?.used
326
+ const memTotal = sample?.mem?.total
327
+ const vramUsed = gpu?.vramUsed
328
+ const vramTotal = gpu?.vramTotal
329
+
330
+ const parts = []
331
+ if (sample === null) {
332
+ parts.push(h('span', { key: 'wait' }, t('connecting')))
333
+ } else {
334
+ parts.push(
335
+ h('span', { key: 'cpu' }, t('cpu'), ' ', h('b', null, formatPercent(sample.cpu?.total))),
336
+ )
337
+ parts.push(
338
+ h(
339
+ 'span',
340
+ { key: 'mem' },
341
+ t('mem'),
342
+ ' ',
343
+ h('b', null, `${formatGiB(memUsed)}/${formatGiB(memTotal)}`),
344
+ ),
345
+ )
346
+ if (gpu === null) {
347
+ parts.push(h('span', { key: 'gpu' }, t('gpu'), ' ', h('b', null, t('unavailable'))))
348
+ } else {
349
+ parts.push(h('span', { key: 'gpu' }, t('gpu'), ' ', h('b', null, formatPercent(gpu.util))))
350
+ parts.push(
351
+ h('span', { key: 'vram' }, t('vram'), ' ', h('b', null, `${formatVram(vramUsed)}/${formatVram(vramTotal)}`)),
352
+ )
353
+ parts.push(h('span', { key: 'temp' }, t('temp'), ' ', h('b', null, formatTemp(gpu.tempC))))
354
+ }
355
+ }
356
+ const readout = []
357
+ for (const [index, part] of parts.entries()) {
358
+ if (index > 0) readout.push(h('span', { key: `sep-${index}`, className: 'dss-dock__sep' }, '·'))
359
+ readout.push(part)
360
+ }
361
+ const titleParts = []
362
+ if (sample !== null) {
363
+ titleParts.push(`${t('cpu')} ${formatPercent(sample.cpu?.total)}`)
364
+ titleParts.push(`${t('mem')} ${formatGiB(memUsed)}/${formatGiB(memTotal)}`)
365
+ if (gpu !== null) {
366
+ titleParts.push(`${t('gpu')} ${formatPercent(gpu.util)}`)
367
+ titleParts.push(`${t('vram')} ${formatVram(vramUsed)}/${formatVram(vramTotal)}`)
368
+ titleParts.push(`${t('temp')} ${formatTemp(gpu.tempC)}`)
369
+ } else {
370
+ titleParts.push(`${t('gpu')} ${t('unavailable')}`)
371
+ }
372
+ }
373
+ const statusKey = status === 'live' ? null : status
374
+ const statusText = statusKey === null ? '' : t(statusKey)
375
+ const hint = titleParts.length > 0 ? titleParts.join(' · ') : t('barLabel')
376
+
377
+ return h(
378
+ React.Fragment,
379
+ null,
380
+ h(StyleTag),
381
+ h(
382
+ 'div',
383
+ { className: 'dss-dock' },
384
+ h(
385
+ 'button',
386
+ {
387
+ type: 'button',
388
+ className: 'dss-dock__hit',
389
+ onClick: () => {
390
+ try {
391
+ onOpenHistory()
392
+ } catch {
393
+ /* history panel unavailable in this composition */
394
+ }
395
+ },
396
+ title: `${hint} — ${t('openHistory')}`,
397
+ 'aria-label': `${hint}. ${t('openHistory')}`,
398
+ },
399
+ h('span', { className: 'dss-dock__dot', 'data-status': status, 'aria-hidden': true }),
400
+ h('span', { className: 'dss-dock__readout' }, readout),
401
+ statusKey === null ? null : h('span', { className: 'dss-dock__status' }, statusText),
402
+ ),
403
+ h('span', { className: 'dss-sr', role: 'status', 'aria-live': 'polite' }, statusText),
404
+ ),
405
+ )
406
+ }
407
+
408
+ /** Which series actually carries finite values in this window. */
409
+ function availabilityOf(points) {
410
+ const has = (pick) => points.some((point) => Number.isFinite(pick(point)))
411
+ return {
412
+ cpu: has((point) => point.cpu?.total),
413
+ gpu: has((point) => point.gpu?.util),
414
+ mem: has((point) => point.mem?.total),
415
+ vram: has((point) => point.gpu?.vramTotal),
416
+ temp: has((point) => point.gpu?.tempC),
417
+ }
418
+ }
419
+
420
+ /** Split points into runs so a recording gap breaks the line. */
421
+ function segmentsOf(points, pick, bucketMs) {
422
+ const runs = []
423
+ let current = []
424
+ let previousT = null
425
+ const gapMs = Math.max(bucketMs * 2.5, 2000)
426
+ for (const point of points) {
427
+ if (!Number.isFinite(pick(point))) continue
428
+ if (previousT !== null && point.t - previousT > gapMs) {
429
+ if (current.length > 0) runs.push(current)
430
+ current = []
431
+ }
432
+ current.push(point)
433
+ previousT = point.t
434
+ }
435
+ if (current.length > 0) runs.push(current)
436
+ return runs
437
+ }
438
+
439
+ /**
440
+ * One SVG line chart over the requested window (not over the data extent),
441
+ * so switching ranges changes the time scale and a gap stays where it was.
442
+ */
443
+ function LineChart({ points, from, until, bucketMs, series, max, unit, ariaLabel, translator }) {
444
+ const WIDTH = 640
445
+ const HEIGHT = 140
446
+ const PAD_X = 8
447
+ const PAD_TOP = 10
448
+ const PAD_BOTTOM = 18
449
+ const [hoverIndex, setHoverIndex] = React.useState(null)
450
+ const { t } = translator
451
+
452
+ const span = Math.max(1, until - from)
453
+ const x = (t) => PAD_X + ((t - from) / span) * (WIDTH - PAD_X * 2)
454
+ const finiteValues = []
455
+ for (const point of points) {
456
+ for (const entry of series) {
457
+ const value = entry.get(point)
458
+ if (Number.isFinite(value)) finiteValues.push(value)
459
+ }
460
+ }
461
+ const ceiling = max ?? Math.max(10, Math.ceil((Math.max(...finiteValues, 0) * 1.1) / 10) * 10)
462
+ const y = (value) =>
463
+ HEIGHT - PAD_BOTTOM - (Math.min(Math.max(value, 0), ceiling) / ceiling) * (HEIGHT - PAD_TOP - PAD_BOTTOM)
464
+
465
+ const children = []
466
+ for (const fraction of [0, 0.5, 1]) {
467
+ const lineY = PAD_TOP + fraction * (HEIGHT - PAD_TOP - PAD_BOTTOM)
468
+ children.push(
469
+ h('line', {
470
+ key: `grid-${fraction}`,
471
+ className: 'dss-chart__grid',
472
+ x1: PAD_X,
473
+ x2: WIDTH - PAD_X,
474
+ y1: lineY,
475
+ y2: lineY,
476
+ vectorEffect: 'non-scaling-stroke',
477
+ }),
478
+ h(
479
+ 'text',
480
+ { key: `gridlabel-${fraction}`, className: 'dss-chart__axis', x: PAD_X, y: lineY - 3 },
481
+ `${Math.round(ceiling * (1 - fraction))}${unit}`,
482
+ ),
483
+ )
484
+ }
485
+
486
+ for (const entry of series) {
487
+ for (const [runIndex, run] of segmentsOf(points, entry.get, bucketMs).entries()) {
488
+ if (run.length === 1) {
489
+ children.push(
490
+ h('circle', {
491
+ key: `${entry.key}-dot-${runIndex}`,
492
+ cx: x(run[0].t),
493
+ cy: y(entry.get(run[0])),
494
+ r: 1.8,
495
+ fill: entry.color,
496
+ }),
497
+ )
498
+ continue
499
+ }
500
+ const path = run
501
+ .map(
502
+ (point, index) =>
503
+ `${index === 0 ? 'M' : 'L'}${x(point.t).toFixed(1)},${y(entry.get(point)).toFixed(1)}`,
504
+ )
505
+ .join(' ')
506
+ children.push(
507
+ h('path', {
508
+ key: `${entry.key}-${runIndex}`,
509
+ d: path,
510
+ fill: 'none',
511
+ stroke: entry.color,
512
+ strokeWidth: 1.6,
513
+ strokeLinejoin: 'round',
514
+ strokeLinecap: 'round',
515
+ vectorEffect: 'non-scaling-stroke',
516
+ }),
517
+ )
518
+ }
519
+ }
520
+
521
+ const hovered = hoverIndex === null ? null : points[hoverIndex]
522
+ if (hovered !== undefined && hovered !== null) {
523
+ const hoverX = x(hovered.t)
524
+ children.push(
525
+ h('line', {
526
+ key: 'hover',
527
+ className: 'dss-chart__hoverline',
528
+ x1: hoverX,
529
+ x2: hoverX,
530
+ y1: PAD_TOP,
531
+ y2: HEIGHT - PAD_BOTTOM,
532
+ vectorEffect: 'non-scaling-stroke',
533
+ }),
534
+ )
535
+ for (const entry of series) {
536
+ const value = entry.get(hovered)
537
+ if (!Number.isFinite(value)) continue
538
+ children.push(
539
+ h('circle', { key: `hover-${entry.key}`, cx: hoverX, cy: y(value), r: 2.2, fill: entry.color }),
540
+ )
541
+ }
542
+ }
543
+
544
+ const onMove = (event) => {
545
+ const rect = event.currentTarget.getBoundingClientRect()
546
+ if (rect.width <= 0 || points.length === 0) return
547
+ const targetT = from + ((event.clientX - rect.left) / rect.width) * span
548
+ let best = 0
549
+ let bestDelta = Infinity
550
+ for (let index = 0; index < points.length; index += 1) {
551
+ const delta = Math.abs(points[index].t - targetT)
552
+ if (delta < bestDelta) {
553
+ bestDelta = delta
554
+ best = index
555
+ }
556
+ }
557
+ setHoverIndex(best)
558
+ }
559
+
560
+ const hoverText =
561
+ hovered === null || hovered === undefined
562
+ ? t('hoverHint')
563
+ : [
564
+ formatClockSeconds(hovered.t),
565
+ ...series
566
+ .filter((entry) => Number.isFinite(entry.get(hovered)))
567
+ .map((entry) => `${entry.label} ${entry.format ? entry.format(entry.get(hovered)) : entry.get(hovered)}`),
568
+ ].join(' · ')
569
+
570
+ return h(
571
+ 'div',
572
+ null,
573
+ h(
574
+ 'svg',
575
+ {
576
+ className: 'dss-chart',
577
+ viewBox: `0 0 ${WIDTH} ${HEIGHT}`,
578
+ role: 'img',
579
+ 'aria-label': ariaLabel,
580
+ onMouseMove: onMove,
581
+ onMouseLeave: () => setHoverIndex(null),
582
+ },
583
+ h('title', { key: 'title' }, ariaLabel),
584
+ children,
585
+ ),
586
+ h(
587
+ 'div',
588
+ { className: 'dss-chart__axisrow' },
589
+ h('span', null, formatClock(from)),
590
+ h('span', { className: 'dss-chart__hoverinfo' }, hoverText),
591
+ h('span', null, formatClock(until)),
592
+ ),
593
+ )
594
+ }
595
+
596
+ function ChartCard({ title, legend, children, translator, latest }) {
597
+ return h(
598
+ 'section',
599
+ { className: 'dss-card' },
600
+ h(
601
+ 'div',
602
+ { className: 'dss-card__head' },
603
+ h('h2', { className: 'dss-card__title' }, title),
604
+ latest === undefined || latest === null
605
+ ? null
606
+ : h('span', { className: 'dss-card__latest' }, latest),
607
+ legend === null || legend.length === 0
608
+ ? null
609
+ : h(
610
+ 'span',
611
+ { className: 'dss-card__legend' },
612
+ legend.map((entry) =>
613
+ h(
614
+ 'span',
615
+ { key: entry.label },
616
+ h('span', { className: 'dss-legend__swatch', style: { background: entry.color } }),
617
+ entry.label,
618
+ ),
619
+ ),
620
+ ),
621
+ ),
622
+ children,
623
+ )
624
+ }
625
+
626
+ /** The history panel: window selector, coverage facts, charts, disk usage. */
627
+ function HistoryPage({ translator }) {
628
+ const { t } = translator
629
+ useLocaleRevision(translator)
630
+ const [range, setRange] = React.useState('1h')
631
+ const [attempt, setAttempt] = React.useState(0)
632
+ const [state, setState] = React.useState({
633
+ loading: true,
634
+ error: null,
635
+ points: [],
636
+ from: null,
637
+ until: null,
638
+ bucketMs: 60000,
639
+ disabled: false,
640
+ reason: undefined,
641
+ lastWriteAt: null,
642
+ })
643
+ const titleRef = React.useRef(null)
644
+
645
+ React.useEffect(() => {
646
+ if (titleRef.current) titleRef.current.focus()
647
+ }, [])
648
+
649
+ React.useEffect(() => {
650
+ let cancelled = false
651
+ setState((prev) => ({ ...prev, loading: true, error: null }))
652
+ fetch(`${HISTORY_URL}?range=${encodeURIComponent(range)}`, { cache: 'no-store' })
653
+ .then((response) => {
654
+ if (!response.ok) throw new Error(`HTTP ${response.status}`)
655
+ return response.json()
656
+ })
657
+ .then((payload) => {
658
+ if (cancelled) return
659
+ const fallbackUntil = Date.now()
660
+ const windowMs = RANGE_MS[range] ?? RANGE_MS['1h']
661
+ setState({
662
+ loading: false,
663
+ error: null,
664
+ points: Array.isArray(payload?.points) ? payload.points : [],
665
+ from: Number.isFinite(payload?.from) ? payload.from : fallbackUntil - windowMs,
666
+ until: Number.isFinite(payload?.until) ? payload.until : fallbackUntil,
667
+ bucketMs: Number.isFinite(payload?.bucketMs) ? payload.bucketMs : Math.ceil(windowMs / 300),
668
+ disabled: Boolean(payload?.disabled),
669
+ reason: typeof payload?.reason === 'string' ? payload.reason : undefined,
670
+ lastWriteAt: Number.isFinite(payload?.lastWriteAt) ? payload.lastWriteAt : null,
671
+ })
672
+ })
673
+ .catch((error) => {
674
+ if (cancelled) return
675
+ const windowMs = RANGE_MS[range] ?? RANGE_MS['1h']
676
+ const now = Date.now()
677
+ setState({
678
+ loading: false,
679
+ error: String(error?.message ?? error),
680
+ points: [],
681
+ from: now - windowMs,
682
+ until: now,
683
+ bucketMs: Math.ceil(windowMs / 300),
684
+ disabled: false,
685
+ reason: undefined,
686
+ lastWriteAt: null,
687
+ })
688
+ })
689
+ return () => {
690
+ cancelled = true
691
+ }
692
+ }, [range, attempt])
693
+
694
+ // The live hour refreshes itself while the page is visible.
695
+ React.useEffect(() => {
696
+ if (range !== '1h') return undefined
697
+ const timer = setInterval(() => {
698
+ if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return
699
+ setAttempt((value) => value + 1)
700
+ }, 30000)
701
+ return () => clearInterval(timer)
702
+ }, [range])
703
+
704
+ const points = state.points
705
+ const from = state.from ?? Date.now() - (RANGE_MS[range] ?? RANGE_MS['1h'])
706
+ const until = state.until ?? Date.now()
707
+ const availability = availabilityOf(points)
708
+ const lastPoint = points.length > 0 ? points[points.length - 1] : null
709
+ const rangeLabels = { '1h': 'range1h', '6h': 'range6h', '24h': 'range24h', '7d': 'range7d' }
710
+
711
+ const header = h(
712
+ 'div',
713
+ { className: 'dss-page__head' },
714
+ h(
715
+ 'div',
716
+ { className: 'dss-page__titles' },
717
+ h('h1', { className: 'dss-page__title', tabIndex: -1, ref: titleRef }, t('historyTitle')),
718
+ h(
719
+ 'p',
720
+ { className: 'dss-page__sub' },
721
+ `${t('window')} ${formatClock(from)} – ${formatClock(until)}${
722
+ lastPoint === null ? '' : ` · ${t('lastSample')} ${formatClockSeconds(lastPoint.t)}`
723
+ }`,
724
+ ),
725
+ ),
726
+ h(
727
+ 'div',
728
+ { className: 'dss-page__ranges', role: 'group', 'aria-label': t('rangeGroup') },
729
+ RANGES.map((value) =>
730
+ h(
731
+ 'button',
732
+ {
733
+ key: value,
734
+ type: 'button',
735
+ className: 'dss-range',
736
+ 'data-active': String(value === range),
737
+ 'aria-pressed': value === range,
738
+ onClick: () => {
739
+ if (value === range) setAttempt((current) => current + 1)
740
+ else setRange(value)
741
+ },
742
+ },
743
+ t(rangeLabels[value]),
744
+ ),
745
+ ),
746
+ h(
747
+ 'button',
748
+ {
749
+ type: 'button',
750
+ className: 'dss-range',
751
+ onClick: () => setAttempt((current) => current + 1),
752
+ title: t('refresh'),
753
+ },
754
+ t('refresh'),
755
+ ),
756
+ ),
757
+ )
758
+
759
+ const notices = []
760
+ if (state.disabled) {
761
+ notices.push(
762
+ h('div', { className: 'dss-notice', key: 'disabled' }, t('disabledStorage')),
763
+ )
764
+ }
765
+ if (state.reason === 'unreadable') {
766
+ notices.push(h('div', { className: 'dss-notice dss-notice--error', key: 'unreadable' }, t('unreadableStorage')))
767
+ }
768
+
769
+ const cpuSeries = [
770
+ {
771
+ key: 'cpu',
772
+ label: t('cpu'),
773
+ color: 'var(--dsw-alias-brand-primary)',
774
+ get: (point) => point.cpu?.total,
775
+ format: formatPercent,
776
+ },
777
+ ]
778
+ const gpuSeries = [
779
+ {
780
+ key: 'gpu',
781
+ label: t('gpu'),
782
+ color: 'var(--dsw-alias-brand-primary)',
783
+ get: (point) => point.gpu?.util,
784
+ format: formatPercent,
785
+ },
786
+ ]
787
+ const memSeries = [
788
+ {
789
+ key: 'mem',
790
+ label: t('mem'),
791
+ color: 'var(--dsw-alias-brand-primary)',
792
+ get: (point) => (point.mem?.total > 0 ? (point.mem.used / point.mem.total) * 100 : NaN),
793
+ format: formatPercent,
794
+ },
795
+ ]
796
+ const vramSeries = [
797
+ {
798
+ key: 'vram',
799
+ label: t('vram'),
800
+ color: 'var(--dsw-alias-brand-primary)',
801
+ get: (point) =>
802
+ point.gpu?.vramTotal > 0 ? (point.gpu.vramUsed / point.gpu.vramTotal) * 100 : NaN,
803
+ format: formatPercent,
804
+ },
805
+ ]
806
+ const tempSeries = [
807
+ {
808
+ key: 'temp',
809
+ label: t('temp'),
810
+ color: 'var(--dsw-alias-label-primary)',
811
+ get: (point) => point.gpu?.tempC,
812
+ format: formatTemp,
813
+ },
814
+ ]
815
+ const lastCpu = lastPoint?.cpu?.total
816
+ const lastGpu = availability.gpu ? lastPoint?.gpu?.util : null
817
+ const lastMemPercent =
818
+ lastPoint?.mem?.total > 0 ? (lastPoint.mem.used / lastPoint.mem.total) * 100 : null
819
+ const lastVramPercent =
820
+ availability.vram && lastPoint?.gpu?.vramTotal > 0
821
+ ? (lastPoint.gpu.vramUsed / lastPoint.gpu.vramTotal) * 100
822
+ : null
823
+ const cpuLatest = formatPercent(lastCpu)
824
+ const gpuLatest = formatPercent(lastGpu)
825
+ const memLatest = `${formatPercent(lastMemPercent)} · ${formatGiB(lastPoint?.mem?.used)} / ${formatGiB(
826
+ lastPoint?.mem?.total,
827
+ )}`
828
+ const vramLatest = `${formatPercent(lastVramPercent)} · ${formatVram(
829
+ lastPoint?.gpu?.vramUsed,
830
+ )} / ${formatVram(lastPoint?.gpu?.vramTotal)}`
831
+
832
+ let body
833
+ if (state.error !== null) {
834
+ body = h(
835
+ 'div',
836
+ { className: 'dss-card dss-empty' },
837
+ h('span', { className: 'dss-error' }, `${t('loadFailed')}: ${state.error}`),
838
+ h(
839
+ 'button',
840
+ { type: 'button', className: 'dss-retry', onClick: () => setAttempt((value) => value + 1) },
841
+ t('retry'),
842
+ ),
843
+ )
844
+ } else if (state.loading && points.length === 0) {
845
+ body = h('div', { className: 'dss-card dss-empty' }, t('loading'))
846
+ } else if (points.length === 0) {
847
+ body = h('div', { className: 'dss-card dss-empty' }, t('empty'))
848
+ } else {
849
+ const singlePoint = points.length === 1
850
+ body = h(
851
+ React.Fragment,
852
+ null,
853
+ singlePoint ? h('div', { className: 'dss-notice' }, t('singlePoint')) : null,
854
+ h(
855
+ ChartCard,
856
+ {
857
+ title: t('cpuTitle'),
858
+ translator,
859
+ latest: cpuLatest,
860
+ legend: [{ label: t('cpu'), color: 'var(--dsw-alias-brand-primary)' }],
861
+ },
862
+ h(LineChart, {
863
+ points,
864
+ from,
865
+ until,
866
+ bucketMs: state.bucketMs,
867
+ unit: '%',
868
+ series: cpuSeries,
869
+ ariaLabel: `${t('cpuTitle')} ${formatClock(from)}–${formatClock(until)}`,
870
+ translator,
871
+ }),
872
+ ),
873
+ availability.gpu
874
+ ? h(
875
+ ChartCard,
876
+ {
877
+ title: t('gpuTitle'),
878
+ translator,
879
+ latest: gpuLatest,
880
+ legend: [{ label: t('gpu'), color: 'var(--dsw-alias-brand-primary)' }],
881
+ },
882
+ h(LineChart, {
883
+ points,
884
+ from,
885
+ until,
886
+ bucketMs: state.bucketMs,
887
+ unit: '%',
888
+ series: gpuSeries,
889
+ ariaLabel: `${t('gpuTitle')} ${formatClock(from)}–${formatClock(until)}`,
890
+ translator,
891
+ }),
892
+ )
893
+ : null,
894
+ h(
895
+ ChartCard,
896
+ {
897
+ title: t('memory'),
898
+ translator,
899
+ latest: memLatest,
900
+ legend: memSeries.map((entry) => ({ label: entry.label, color: entry.color })),
901
+ },
902
+ h(LineChart, {
903
+ points,
904
+ from,
905
+ until,
906
+ bucketMs: state.bucketMs,
907
+ max: 100,
908
+ unit: '%',
909
+ series: memSeries,
910
+ ariaLabel: `${t('memory')} ${formatClock(from)}–${formatClock(until)}`,
911
+ translator,
912
+ }),
913
+ ),
914
+ availability.vram
915
+ ? h(
916
+ ChartCard,
917
+ {
918
+ title: t('vramTitle'),
919
+ translator,
920
+ latest: vramLatest,
921
+ legend: [{ label: t('vram'), color: 'var(--dsw-alias-brand-primary)' }],
922
+ },
923
+ h(LineChart, {
924
+ points,
925
+ from,
926
+ until,
927
+ bucketMs: state.bucketMs,
928
+ unit: '%',
929
+ series: vramSeries,
930
+ ariaLabel: `${t('vramTitle')} ${formatClock(from)}–${formatClock(until)}`,
931
+ translator,
932
+ }),
933
+ )
934
+ : null,
935
+ availability.temp
936
+ ? h(
937
+ ChartCard,
938
+ {
939
+ title: t('temperature'),
940
+ translator,
941
+ latest: formatTemp(lastPoint?.gpu?.tempC),
942
+ legend: [{ label: t('temp'), color: 'var(--dsw-alias-label-primary)' }],
943
+ },
944
+ h(LineChart, {
945
+ points,
946
+ from,
947
+ until,
948
+ bucketMs: state.bucketMs,
949
+ unit: '°',
950
+ series: tempSeries,
951
+ ariaLabel: `${t('temperature')} ${formatClock(from)}–${formatClock(until)}`,
952
+ translator,
953
+ }),
954
+ )
955
+ : null,
956
+ availability.gpu
957
+ ? null
958
+ : h('div', { className: 'dss-notice' }, `${t('gpu')}: ${t('gpuUnavailable')}`),
959
+ h(
960
+ ChartCard,
961
+ { title: t('disks'), translator, legend: null },
962
+ (lastPoint?.disks ?? []).length === 0
963
+ ? h('div', { className: 'dss-empty' }, t('unavailable'))
964
+ : (lastPoint?.disks ?? []).map((disk) => {
965
+ const percent = disk.total > 0 ? ((disk.total - disk.free) / disk.total) * 100 : 0
966
+ return h(
967
+ 'div',
968
+ { className: 'dss-disk', key: disk.id },
969
+ h('span', null, disk.id),
970
+ h(
971
+ 'span',
972
+ { className: 'dss-disk__track' },
973
+ h('span', {
974
+ className: 'dss-disk__fill',
975
+ style: { width: `${Math.max(0, Math.min(100, percent)).toFixed(1)}%` },
976
+ }),
977
+ ),
978
+ h(
979
+ 'span',
980
+ { className: 'dss-disk__value' },
981
+ `${t('usedPercent')} ${formatPercent(percent)} · ${t('free')} ${formatGiB(
982
+ disk.free,
983
+ )} / ${t('total')} ${formatGiB(disk.total)}`,
984
+ ),
985
+ )
986
+ }),
987
+ ),
988
+ )
989
+ }
990
+
991
+ return h(
992
+ React.Fragment,
993
+ null,
994
+ h(StyleTag),
995
+ h(
996
+ 'div',
997
+ { className: 'dss-page' },
998
+ h('div', { className: 'dss-page__inner' }, header, notices, body, h('div', { className: 'dss-foot' }, t('runtimeOnly'))),
999
+ ),
1000
+ )
1001
+ }
1002
+
1003
+ function SidebarIcon({ size = 16, active = false }) {
1004
+ return h(
1005
+ 'svg',
1006
+ {
1007
+ width: size,
1008
+ height: size,
1009
+ viewBox: '0 0 24 24',
1010
+ fill: 'none',
1011
+ 'aria-hidden': true,
1012
+ style: { display: 'block' },
1013
+ },
1014
+ h('path', {
1015
+ d: 'M4 17.5 8 12l3.2 3.4L15 9.5l5 8',
1016
+ stroke: active ? 'var(--dsw-alias-brand-primary)' : 'currentColor',
1017
+ strokeWidth: 1.8,
1018
+ strokeLinecap: 'round',
1019
+ strokeLinejoin: 'round',
1020
+ }),
1021
+ h('path', {
1022
+ d: 'M4 20.5h16',
1023
+ stroke: active ? 'var(--dsw-alias-brand-primary)' : 'currentColor',
1024
+ strokeWidth: 1.8,
1025
+ strokeLinecap: 'round',
1026
+ opacity: 0.55,
1027
+ }),
1028
+ )
1029
+ }
1030
+
1031
+ return {
1032
+ inject: ['slots'],
1033
+ apply(ctx) {
1034
+ const translator = createTranslator(ctx)
1035
+ if (translator.disposers.length > 0) {
1036
+ ctx.effect(() => () => {
1037
+ for (const dispose of translator.disposers) {
1038
+ try {
1039
+ dispose()
1040
+ } catch {
1041
+ /* already removed */
1042
+ }
1043
+ }
1044
+ })
1045
+ }
1046
+ const openHistory = () => {
1047
+ const layout = typeof ctx.get === 'function' ? ctx.get('layout') : null
1048
+ if (layout) layout.selectPanel('system-status')
1049
+ }
1050
+
1051
+ // Live readout in the composer dock, in the dock's own compact idiom.
1052
+ ctx.slots.inject('conversation.composer.dock', () =>
1053
+ ctx.slots.register(
1054
+ {
1055
+ name: 'conversation.composer.dock',
1056
+ id: 'system-status-bar',
1057
+ order: 40,
1058
+ label: () => translator.t('barLabel'),
1059
+ },
1060
+ () => h(StatusBar, { translator, onOpenHistory: openHistory }),
1061
+ ),
1062
+ )
1063
+
1064
+ // Left sidebar entry: the shell owns the button, we own the glyph.
1065
+ ctx.slots.inject('sidebar.panellist', () =>
1066
+ ctx.slots.register(
1067
+ {
1068
+ name: 'sidebar.panellist',
1069
+ id: 'system-status',
1070
+ order: 20,
1071
+ label: () => translator.t('panelTitle'),
1072
+ },
1073
+ SidebarIcon,
1074
+ ),
1075
+ )
1076
+
1077
+ // The history page, selected by that entry's id.
1078
+ ctx.slots.inject('main', () =>
1079
+ ctx.slots.register({ name: 'main', key: 'system-status' }, () =>
1080
+ h(HistoryPage, { translator }),
1081
+ ),
1082
+ )
1083
+ },
1084
+ }
1085
+ },
1086
+ })