dsh-plugin-system-status 0.0.0-stage → 0.1.1

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