dsh-nvtop-panel 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 zhifan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,103 @@
1
- # Temporary Holding Version
1
+ # dsh-nvtop-panel
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A [DeepSeek Harness (DSH)](https://www.npmjs.com/package/@deepseek-ai/dsh) web plugin that
4
+ adds an **nvtop-style GPU dashboard** to the Web UI: one sidebar icon, one full-width
5
+ panel, live data from `nvidia-smi`.
6
+
7
+ Built for multi-GPU, multi-user servers: per-GPU metric cards plus a full
8
+ nvtop-like process table, so you can see *who* is using *which* GPU.
9
+
10
+ ```
11
+ GPU monitor 4 GPUs
12
+
13
+ ┌ GPU 0 · NVIDIA RTX PRO 6000 ────┐ ┌ GPU 1 · … ┐
14
+ │ Utilization ▓▓▓░░░░░░ 12 % │ │ │
15
+ │ Memory ▓▓▓▓▓░░░░ 14/96GiB │ │ │
16
+ │ Power ▓░░░░░░░ 34.6/600W│ │ │
17
+ │ Temp 28°C · Fan — · Power 34.6W│ └───────────┘
18
+ └─────────────────────────────────┘
19
+
20
+ Processes
21
+ PID USER DEV TYPE GPU GPU MEM CPU HOST MEM Command
22
+ 283443 ronghua 2 C 89% 87.2 GiB 18.3% 2.6 GiB VLLM::EngineCore
23
+ …
24
+ ```
25
+
26
+ ## Features
27
+
28
+ - **Per-GPU cards**: utilization, memory used/total, power draw vs limit (metered bars,
29
+ amber ≥ 70 %, red ≥ 90 %), temperature, fan speed when the GPU reports it.
30
+ - **nvtop-style process table**: `PID · USER · DEV · TYPE · GPU · GPU MEM · CPU ·
31
+ HOST MEM · Command`. GPU memory comes from `nvidia-smi --query-compute-apps`; user,
32
+ CPU %, host RSS, and full command line come from one batched `ps` call; each process
33
+ is mapped to its device via GPU UUID.
34
+ - `TYPE` is `C` (compute) — the CSV interface only lists compute contexts.
35
+ - `GPU` is the process's device utilization; per-process SM utilization is a
36
+ driver-level statistic that `nvidia-smi`'s query interface does not expose.
37
+ - **Auto-refresh**, interval configurable per profile (default 2 s), server samples
38
+ cached 1 s so overlapping polls share one `nvidia-smi` run.
39
+ - **Theme-native UI**: all styling uses DSH theme tokens (`--dsw-alias-*`), light/dark
40
+ aware, English locale.
41
+ - **Owner-authenticated data route**: served on the shared `/api` channel
42
+ (`GET /api/nvtop`), so it carries the same cookie trust as the rest of the DSH web
43
+ API; unauthenticated requests get 401.
44
+
45
+ ## Requirements
46
+
47
+ - DSH web profile (`dsh web`) with the standard `dsh-base` + `dsh-web-app` bundles.
48
+ - NVIDIA driver with `nvidia-smi` on the host PATH. (AMD/Intel GPUs are not supported;
49
+ for AMD see community rocm-smi plugins.)
50
+
51
+ ## Install
52
+
53
+ From npm:
54
+
55
+ ```sh
56
+ dsh plugin --profile web add dsh-nvtop-panel
57
+ ```
58
+
59
+ Then restart `dsh web` (or rely on live patch reload) and refresh the browser. A GPU
60
+ icon appears in the left sidebar panel list.
61
+
62
+ From a git checkout:
63
+
64
+ ```sh
65
+ git clone <this repo> && cd dsh-nvtop-panel
66
+ dsh plugin --profile web add "$PWD"
67
+ ```
68
+
69
+ ## Configuration
70
+
71
+ Tunable in your profile's `cordis.patch.yml`:
72
+
73
+ ```yaml
74
+ - id: dsh-nvtop-panel
75
+ config:
76
+ intervalMs: 2000 # client poll interval, 500–60000 ms
77
+ ```
78
+
79
+ Editing the interval restarts the plugin and the panel picks up the new value on the
80
+ next poll.
81
+
82
+ ## Verify
83
+
84
+ ```sh
85
+ dsh --profile web --dump-config | grep dsh-nvtop-panel
86
+ curl -s -b <browser-cookie-jar> http://127.0.0.1:3080/api/nvtop | head
87
+ # {"ok":true,"sampledAt":...,"gpus":[...],"processes":[...],"intervalMs":2000}
88
+ ```
89
+
90
+ ## Architecture
91
+
92
+ One dual-face package:
93
+
94
+ - `index.js` (host) — registers the owner-authenticated `/api/nvtop` fetch route on the
95
+ shared Connection channel, samples `nvidia-smi` (1 s cache, in-flight dedup), merges
96
+ `ps` details, and returns JSON.
97
+ - `client.js` (browser) — registers the `main` panel and the `sidebar.panellist` icon
98
+ via Cordis slots, polls the route, and renders with React from the page module table.
99
+ No build tooling; plain JS.
100
+
101
+ ## License
102
+
103
+ MIT
package/client.js ADDED
@@ -0,0 +1,279 @@
1
+ window.__ModuleLoader__.load({
2
+ id: 'dsh-nvtop-panel',
3
+ factory(require) {
4
+ const React = require('react');
5
+ const h = React.createElement;
6
+ const { useEffect, useRef, useState } = React;
7
+
8
+ const NS = 'nvtop.panel';
9
+ const PANEL_ID = 'nvtop';
10
+ const POLL_MS = 2000;
11
+
12
+ const dict = {
13
+ en: {
14
+ panel: 'GPU monitor',
15
+ gpus: '{n} GPU',
16
+ gpusOther: '{n} GPUs',
17
+ utilization: 'Utilization',
18
+ memory: 'Memory',
19
+ temperature: 'Temp',
20
+ fan: 'Fan',
21
+ power: 'Power',
22
+ processes: 'Processes',
23
+ noProcesses: 'No GPU processes',
24
+ unavailable: 'GPU stats unavailable',
25
+ stale: 'Waiting for data…',
26
+ pid: 'PID',
27
+ user: 'USER',
28
+ dev: 'DEV',
29
+ type: 'TYPE',
30
+ gpu: 'GPU',
31
+ gpuMem: 'GPU MEM',
32
+ cpu: 'CPU',
33
+ hostMem: 'HOST MEM',
34
+ command: 'Command',
35
+ },
36
+ };
37
+
38
+ function fmtInt(value) {
39
+ return value === null || value === undefined ? '—' : `${Math.round(value)}`;
40
+ }
41
+
42
+ function fmtMemory(mib) {
43
+ if (mib === null || mib === undefined) return '—';
44
+ if (mib >= 1024) return `${(mib / 1024).toFixed(1)} GiB`;
45
+ return `${Math.round(mib)} MiB`;
46
+ }
47
+
48
+ function fmtHostMemory(kib) {
49
+ if (kib === null || kib === undefined) return '—';
50
+ if (kib >= 1024 * 1024) return `${(kib / (1024 * 1024)).toFixed(1)} GiB`;
51
+ if (kib >= 1024) return `${(kib / 1024).toFixed(1)} MiB`;
52
+ return `${Math.round(kib)} KiB`;
53
+ }
54
+
55
+ function fmtPower(watt) {
56
+ return watt === null || watt === undefined ? '—' : `${watt.toFixed ? watt.toFixed(1) : watt} W`;
57
+ }
58
+
59
+ function fmtPercent(value) {
60
+ return value === null || value === undefined ? '—' : `${Math.round(value)}%`;
61
+ }
62
+
63
+ function levelClass(ratio) {
64
+ if (ratio === null || ratio === undefined) return 'nvtp-empty';
65
+ if (ratio >= 0.9) return 'nvtp-hot';
66
+ if (ratio >= 0.7) return 'nvtp-warm';
67
+ return 'nvtp-ok';
68
+ }
69
+
70
+ function Bar(props) {
71
+ const ratio = props.ratio;
72
+ const pct = ratio === null || ratio === undefined ? 0 : Math.max(0, Math.min(100, ratio * 100));
73
+ return h('div', { className: 'nvtp-bar ' + levelClass(ratio) },
74
+ h('div', { className: 'nvtp-bar-fill', style: { width: pct + '%' } }));
75
+ }
76
+
77
+ function Stat(props) {
78
+ return h('div', { className: 'nvtp-stat' },
79
+ h('div', { className: 'nvtp-stat-label' }, props.label),
80
+ h('div', { className: 'nvtp-stat-value' }, props.value));
81
+ }
82
+
83
+ function GpuCard(props) {
84
+ const { gpu, t } = props;
85
+ const memRatio = gpu.memoryUsed !== null && gpu.memoryTotal
86
+ ? gpu.memoryUsed / gpu.memoryTotal : null;
87
+ const powerRatio = gpu.powerDraw !== null && gpu.powerLimit
88
+ ? gpu.powerDraw / gpu.powerLimit : null;
89
+ return h('section', { className: 'nvtp-card' },
90
+ h('header', { className: 'nvtp-card-head' },
91
+ h('span', { className: 'nvtp-card-name' }, gpu.name),
92
+ h('span', { className: 'nvtp-card-index' }, `GPU ${gpu.index}`)),
93
+ h('div', { className: 'nvtp-rows' },
94
+ h('div', { className: 'nvtp-row' },
95
+ h('span', { className: 'nvtp-row-label' }, t('utilization')),
96
+ h(Bar, { ratio: gpu.utilization === null ? null : gpu.utilization / 100 }),
97
+ h('span', { className: 'nvtp-row-value' }, fmtPercent(gpu.utilization))),
98
+ h('div', { className: 'nvtp-row' },
99
+ h('span', { className: 'nvtp-row-label' }, t('memory')),
100
+ h(Bar, { ratio: memRatio }),
101
+ h('span', { className: 'nvtp-row-value' },
102
+ `${fmtMemory(gpu.memoryUsed)} / ${fmtMemory(gpu.memoryTotal)}`)),
103
+ h('div', { className: 'nvtp-row' },
104
+ h('span', { className: 'nvtp-row-label' }, t('power')),
105
+ h(Bar, { ratio: powerRatio }),
106
+ h('span', { className: 'nvtp-row-value' },
107
+ powerRatio === null ? fmtPower(gpu.powerDraw) : fmtPower(gpu.powerLimit)))),
108
+ h('div', { className: 'nvtp-stats' },
109
+ h(Stat, { label: t('temperature'), value: gpu.temperature === null ? '—' : `${Math.round(gpu.temperature)}°C` }),
110
+ h(Stat, { label: t('fan'), value: gpu.fan === null ? '—' : `${Math.round(gpu.fan)}%` }),
111
+ h(Stat, { label: t('power'), value: fmtPower(gpu.powerDraw) })));
112
+ }
113
+
114
+ function ProcessTable(props) {
115
+ const { processes, t } = props;
116
+ if (processes.length === 0) {
117
+ return h('div', { className: 'nvtp-empty-note' }, t('noProcesses'));
118
+ }
119
+ return h('table', { className: 'nvtp-table nvtp-procs-table' },
120
+ h('thead', null,
121
+ h('tr', null,
122
+ h('th', { className: 'nvtp-num' }, t('pid')),
123
+ h('th', null, t('user')),
124
+ h('th', { className: 'nvtp-num' }, t('dev')),
125
+ h('th', null, t('type')),
126
+ h('th', { className: 'nvtp-num' }, t('gpu')),
127
+ h('th', { className: 'nvtp-num' }, t('gpuMem')),
128
+ h('th', { className: 'nvtp-num' }, t('cpu')),
129
+ h('th', { className: 'nvtp-num' }, t('hostMem')),
130
+ h('th', { className: 'nvtp-cmd' }, t('command')))),
131
+ h('tbody', null,
132
+ processes.map((p) => h('tr', { key: p.pid + ':' + (p.device ?? '') + ':' + p.command.slice(0, 24) },
133
+ h('td', { className: 'nvtp-num' }, fmtInt(p.pid)),
134
+ h('td', { className: 'nvtp-user' }, p.user ?? '—'),
135
+ h('td', { className: 'nvtp-num' }, p.device === null || p.device === undefined ? '—' : String(p.device)),
136
+ h('td', { className: 'nvtp-type' }, p.type ?? '—'),
137
+ h('td', { className: 'nvtp-num' }, fmtPercent(p.gpuUtilization)),
138
+ h('td', { className: 'nvtp-num' }, fmtMemory(p.memoryUsed)),
139
+ h('td', { className: 'nvtp-num' }, p.cpuPercent === null || p.cpuPercent === undefined ? '—' : `${p.cpuPercent.toFixed(1)}%`),
140
+ h('td', { className: 'nvtp-num' }, fmtHostMemory(p.hostMemKib)),
141
+ h('td', { className: 'nvtp-cmd nvtp-name' }, p.command)))));
142
+ }
143
+
144
+ const CSS = `
145
+ .nvtp-page{box-sizing:border-box;height:100%;overflow:auto;padding:24px;display:flex;flex-direction:column;gap:16px;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-base)}
146
+ .nvtp-title{margin:0;font-size:18px;font-weight:600}
147
+ .nvtp-sub{color:var(--dsw-alias-label-secondary);font-size:12px}
148
+ .nvtp-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(340px,1fr));gap:16px}
149
+ .nvtp-card{box-sizing:border-box;border:1px solid var(--dsw-alias-border-l1);border-radius:10px;background:var(--dsw-alias-bg-layer-1);padding:14px 16px;display:flex;flex-direction:column;gap:10px}
150
+ .nvtp-card-head{display:flex;justify-content:space-between;align-items:baseline;gap:8px}
151
+ .nvtp-card-name{font-weight:600;font-size:14px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
152
+ .nvtp-card-index{color:var(--dsw-alias-label-secondary);font-size:12px;flex:none}
153
+ .nvtp-rows{display:flex;flex-direction:column;gap:8px}
154
+ .nvtp-row{display:grid;grid-template-columns:64px 1fr 130px;gap:10px;align-items:center;font-size:12px}
155
+ .nvtp-row-label{color:var(--dsw-alias-label-secondary)}
156
+ .nvtp-row-value{text-align:right;font-variant-numeric:tabular-nums}
157
+ .nvtp-bar{height:8px;border-radius:4px;background:var(--dsw-alias-bg-layer-2);overflow:hidden}
158
+ .nvtp-bar-fill{height:100%;border-radius:4px;background:var(--dsw-alias-brand-primary);transition:width .4s ease}
159
+ .nvtp-ok .nvtp-bar-fill{background:var(--dsw-alias-brand-primary)}
160
+ .nvtp-warm .nvtp-bar-fill{background:var(--dsw-alias-state-warn-primary)}
161
+ .nvtp-hot .nvtp-bar-fill{background:var(--dsw-alias-state-error-primary)}
162
+ .nvtp-empty .nvtp-bar-fill{background:var(--dsw-alias-state-idle-primary)}
163
+ .nvtp-stats{display:flex;gap:18px;flex-wrap:wrap}
164
+ .nvtp-stat-label{color:var(--dsw-alias-label-secondary);font-size:11px}
165
+ .nvtp-stat-value{font-size:14px;font-variant-numeric:tabular-nums}
166
+ .nvtp-procs{border:1px solid var(--dsw-alias-border-l1);border-radius:10px;background:var(--dsw-alias-bg-layer-1);padding:14px 16px}
167
+ .nvtp-procs h2{margin:0 0 10px;font-size:14px;font-weight:600}
168
+ .nvtp-table{width:100%;border-collapse:collapse;font-size:13px}
169
+ .nvtp-table th{color:var(--dsw-alias-label-secondary);font-weight:500;text-align:left;padding:4px 8px;border-bottom:1px solid var(--dsw-alias-border-l2);font-size:12px;white-space:nowrap}
170
+ .nvtp-table td{padding:5px 8px;border-bottom:1px solid var(--dsw-alias-border-l1);white-space:nowrap}
171
+ .nvtp-num{text-align:right;font-variant-numeric:tabular-nums}
172
+ .nvtp-name{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
173
+ .nvtp-procs-table .nvtp-cmd{max-width:420px;overflow:hidden;text-overflow:ellipsis}
174
+ .nvtp-empty-note{color:var(--dsw-alias-label-secondary);font-size:13px}
175
+ .nvtp-error{border:1px solid var(--dsw-alias-state-error-primary);border-radius:10px;padding:14px 16px;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-layer-1)}
176
+ .nvtp-error-label{color:var(--dsw-alias-state-error-primary);font-weight:600;margin-bottom:6px}
177
+ `;
178
+
179
+ function pluralize(template, other, count) {
180
+ return (count === 1 ? template : other).replace('{n}', String(count));
181
+ }
182
+
183
+ return {
184
+ inject: ['slots', 'locale'],
185
+ apply(ctx) {
186
+ ctx.effect(() => ctx.locale.register(NS, dict), 'dsh-nvtop: dictionaries');
187
+ const t = ctx.locale.bind(NS);
188
+ const translate = (key) => t(key);
189
+
190
+ function Panel() {
191
+ const [data, setData] = useState(null);
192
+ const [error, setError] = useState(null);
193
+ const alive = useRef(true);
194
+
195
+ useEffect(() => {
196
+ alive.current = true;
197
+ let timer = 0;
198
+ let intervalMs = POLL_MS;
199
+ const tick = async () => {
200
+ try {
201
+ const response = await fetch('/api/nvtop', { credentials: 'same-origin' });
202
+ const body = await response.json();
203
+ if (!alive.current) return;
204
+ if (!response.ok || body.ok === false) {
205
+ setError(body?.message || `HTTP ${response.status}`);
206
+ setData(null);
207
+ } else {
208
+ setError(null);
209
+ setData(body);
210
+ if (Number.isFinite(body?.intervalMs)) {
211
+ intervalMs = Math.max(250, Math.min(60000, body.intervalMs));
212
+ }
213
+ }
214
+ } catch (e) {
215
+ if (alive.current) setError(String(e?.message ?? e));
216
+ } finally {
217
+ if (alive.current) timer = window.setTimeout(tick, intervalMs);
218
+ }
219
+ };
220
+ tick();
221
+ return () => {
222
+ alive.current = false;
223
+ window.clearTimeout(timer);
224
+ };
225
+ }, []);
226
+
227
+ const gpus = data?.gpus ?? [];
228
+ return h('div', { className: 'nvtp-page' },
229
+ h('style', null, CSS),
230
+ h('h1', { className: 'nvtp-title' }, translate('panel')),
231
+ h('div', { className: 'nvtp-sub' },
232
+ data === null && error === null ? translate('stale')
233
+ : gpus.length > 0
234
+ ? pluralize(translate('gpus'), translate('gpusOther'), gpus.length)
235
+ : ''),
236
+ error !== null
237
+ ? h('div', { className: 'nvtp-error' },
238
+ h('div', { className: 'nvtp-error-label' }, translate('unavailable')),
239
+ h('div', null, error))
240
+ : null,
241
+ gpus.length > 0
242
+ ? h('div', { className: 'nvtp-grid' },
243
+ gpus.map((gpu) => h(GpuCard, { key: gpu.index, gpu, t: translate })))
244
+ : null,
245
+ data !== null && error === null
246
+ ? h('section', { className: 'nvtp-procs' },
247
+ h('h2', null, translate('processes')),
248
+ h(ProcessTable, { processes: data.processes ?? [], t: translate }))
249
+ : null);
250
+ }
251
+
252
+ function PanelIcon() {
253
+ return h('svg', {
254
+ viewBox: '0 0 24 24', width: 22, height: 22, 'aria-hidden': true,
255
+ style: { display: 'block' },
256
+ },
257
+ h('rect', { x: 2.5, y: 5.5, width: 19, height: 12, rx: 2,
258
+ fill: 'none', stroke: 'currentColor', strokeWidth: 1.6 }),
259
+ h('path', { d: 'M6 21v-3M12 21v-3M18 21v-3M6 5V3M12 5V3M18 5V3',
260
+ stroke: 'currentColor', strokeWidth: 1.6, strokeLinecap: 'round', fill: 'none' }),
261
+ h('rect', { x: 5.5, y: 8.5, width: 5, height: 3.2, rx: 0.8,
262
+ fill: 'currentColor', opacity: 0.9 }),
263
+ h('rect', { x: 5.5, y: 13, width: 8, height: 3.2, rx: 0.8,
264
+ fill: 'currentColor', opacity: 0.55 }),
265
+ h('rect', { x: 13, y: 8.5, width: 5.5, height: 3.2, rx: 0.8,
266
+ fill: 'currentColor', opacity: 0.3 }));
267
+ }
268
+
269
+ ctx.effect(() => ctx.slots.inject('main', () => ctx.slots.register({
270
+ name: 'main', key: PANEL_ID, locale: NS,
271
+ }, Panel)), 'dsh-nvtop: main panel');
272
+ ctx.effect(() => ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({
273
+ name: 'sidebar.panellist', id: PANEL_ID, order: 40, locale: NS,
274
+ label: () => translate('panel'),
275
+ }, PanelIcon)), 'dsh-nvtop: sidebar icon');
276
+ },
277
+ };
278
+ },
279
+ });
@@ -0,0 +1,4 @@
1
+ - insert:
2
+ - id: dsh-nvtop-panel
3
+ name: dsh-nvtop-panel
4
+ config: {}
package/icon.svg ADDED
@@ -0,0 +1,9 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64">
2
+ <rect x="6" y="14" width="52" height="32" rx="5" fill="#1f2a38"/>
3
+ <rect x="6" y="14" width="52" height="32" rx="5" fill="none" stroke="#4da3ff" stroke-width="2.5"/>
4
+ <path d="M16 54v-8M32 54v-8M48 54v-8M16 14V8M32 14V8M48 14V8" stroke="#4da3ff" stroke-width="2.5" stroke-linecap="round" fill="none"/>
5
+ <rect x="12" y="20" width="13" height="8" rx="2" fill="#4da3ff"/>
6
+ <rect x="12" y="32" width="22" height="8" rx="2" fill="#4da3ff" opacity="0.6"/>
7
+ <rect x="29" y="20" width="15" height="8" rx="2" fill="#4da3ff" opacity="0.35"/>
8
+ <rect x="38" y="32" width="13" height="8" rx="2" fill="#4da3ff" opacity="0.85"/>
9
+ </svg>
package/index.js ADDED
@@ -0,0 +1,233 @@
1
+ import { execFile } from 'node:child_process';
2
+ import Schema from '@deepseek-ai/schemastery';
3
+
4
+ const inject = ['connection', 'webServer'];
5
+
6
+ /** User-tunable settings; the recommended poll interval travels with every sample. */
7
+ const Config = Schema.object({
8
+ intervalMs: Schema.number().step(1).min(500).max(60000).default(2000)
9
+ .description('Recommended client poll interval in milliseconds (500-60000, default 2000)'),
10
+ });
11
+
12
+ const QUERY_FIELDS = [
13
+ 'index',
14
+ 'name',
15
+ 'utilization.gpu',
16
+ 'memory.used',
17
+ 'memory.total',
18
+ 'temperature.gpu',
19
+ 'fan.speed',
20
+ 'power.draw',
21
+ 'power.limit',
22
+ 'uuid',
23
+ ].join(',');
24
+
25
+ const APP_FIELDS = ['pid', 'gpu_uuid', 'used_memory', 'process_name'].join(',');
26
+
27
+ /** Milliseconds a successful or failed sample stays cached. */
28
+ const CACHE_MS = 1000;
29
+ /** nvidia-smi hard timeout per invocation. */
30
+ const SMI_TIMEOUT_MS = 5000;
31
+
32
+ let cached;
33
+ let cachedAt = 0;
34
+ let sampling;
35
+
36
+ function run(command, args) {
37
+ return new Promise((resolve, reject) => {
38
+ execFile(
39
+ command,
40
+ args,
41
+ { timeout: SMI_TIMEOUT_MS, maxBuffer: 4 * 1024 * 1024 },
42
+ (error, stdout) => {
43
+ if (error) reject(error);
44
+ else resolve(stdout);
45
+ },
46
+ );
47
+ });
48
+ }
49
+
50
+ function runSmi(args) {
51
+ return run('nvidia-smi', args);
52
+ }
53
+
54
+ function splitCsv(line) {
55
+ const out = [];
56
+ let current = '';
57
+ let quoted = false;
58
+ for (let i = 0; i < line.length; i += 1) {
59
+ const ch = line[i];
60
+ if (quoted) {
61
+ if (ch === '"') quoted = false;
62
+ else current += ch;
63
+ } else if (ch === '"') quoted = true;
64
+ else if (ch === ',') {
65
+ out.push(current.trim());
66
+ current = '';
67
+ } else current += ch;
68
+ }
69
+ out.push(current.trim());
70
+ return out;
71
+ }
72
+
73
+ /** Parse a numeric field, keeping null for "[Not Supported]" or empty values. */
74
+ function numeric(value) {
75
+ if (value === undefined || value === '' || value.startsWith('[')) return null;
76
+ const n = Number(value.replace(/[^\d.\-+]/g, ''));
77
+ return Number.isFinite(n) ? n : null;
78
+ }
79
+
80
+ /** One `ps` call for every listed PID: user, cpu %, rss, full command line. */
81
+ async function processDetails(pids) {
82
+ const unique = [...new Set(pids)].filter((pid) => Number.isInteger(pid) && pid > 0);
83
+ const details = new Map();
84
+ if (unique.length === 0) return details;
85
+ try {
86
+ const text = await run('ps', [
87
+ '-o', 'pid=,user=,%cpu=,rss=,args=',
88
+ '-p', unique.join(','),
89
+ ]);
90
+ for (const line of text.split('\n')) {
91
+ if (line.trim() === '') continue;
92
+ const match = line.trim().match(/^(\d+)\s+(\S+)\s+([\d.]+)\s+(\d+)\s+(.*)$/);
93
+ if (match === null) continue;
94
+ details.set(Number(match[1]), {
95
+ user: match[2],
96
+ cpu: Number(match[3]),
97
+ rssKib: Number(match[4]),
98
+ command: match[5],
99
+ });
100
+ }
101
+ } catch {
102
+ // A process may exit between nvidia-smi and ps; leave its details absent.
103
+ }
104
+ return details;
105
+ }
106
+
107
+ async function sample() {
108
+ const [gpuText, appText] = await Promise.all([
109
+ runSmi(['--query-gpu', QUERY_FIELDS, '--format=csv,noheader,nounits']),
110
+ runSmi(['--query-compute-apps', APP_FIELDS, '--format=csv,noheader,nounits'])
111
+ .catch(() => ''),
112
+ ]);
113
+
114
+ const gpus = gpuText
115
+ .split('\n')
116
+ .map((line) => line.trim())
117
+ .filter((line) => line !== '')
118
+ .map((line) => {
119
+ const f = splitCsv(line);
120
+ return {
121
+ index: numeric(f[0]) ?? 0,
122
+ name: f[1] ?? 'GPU',
123
+ utilization: numeric(f[2]),
124
+ memoryUsed: numeric(f[3]),
125
+ memoryTotal: numeric(f[4]),
126
+ temperature: numeric(f[5]),
127
+ fan: numeric(f[6]),
128
+ powerDraw: numeric(f[7]),
129
+ powerLimit: numeric(f[8]),
130
+ uuid: f[9] ?? '',
131
+ };
132
+ });
133
+
134
+ const deviceOfUuid = new Map(gpus.map((gpu) => [gpu.uuid, gpu.index]));
135
+
136
+ const entries = appText
137
+ .split('\n')
138
+ .map((line) => line.trim())
139
+ .filter((line) => line !== '')
140
+ .map((line) => {
141
+ const f = splitCsv(line);
142
+ return {
143
+ pid: numeric(f[0]) ?? 0,
144
+ device: deviceOfUuid.get(f[1]) ?? null,
145
+ memoryUsed: numeric(f[2]),
146
+ name: f[3] ?? '',
147
+ };
148
+ });
149
+
150
+ const details = await processDetails(entries.map((entry) => entry.pid));
151
+
152
+ const processes = entries.map((entry) => {
153
+ const extra = details.get(entry.pid);
154
+ const device = gpus.find((gpu) => gpu.index === entry.device);
155
+ return {
156
+ pid: entry.pid,
157
+ user: extra?.user ?? null,
158
+ device: entry.device,
159
+ // nvidia-smi lists compute contexts; nvtop labels them "C".
160
+ type: 'C',
161
+ gpuUtilization: device?.utilization ?? null,
162
+ memoryUsed: entry.memoryUsed,
163
+ cpuPercent: extra?.cpu ?? null,
164
+ hostMemKib: extra?.rssKib ?? null,
165
+ command: extra?.command ?? entry.name,
166
+ };
167
+ });
168
+
169
+ return { ok: true, sampledAt: Date.now(), gpus, processes };
170
+ }
171
+
172
+ function jsonResponse(body) {
173
+ return new Response(JSON.stringify(body), {
174
+ headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' },
175
+ });
176
+ }
177
+
178
+ async function fetchStats() {
179
+ const now = Date.now();
180
+ if (cached !== undefined && now - cachedAt < CACHE_MS) return cached;
181
+ if (sampling !== undefined) return sampling;
182
+ sampling = (async () => {
183
+ try {
184
+ cached = await sample();
185
+ cachedAt = Date.now();
186
+ return cached;
187
+ } catch (error) {
188
+ const body = {
189
+ ok: false,
190
+ sampledAt: now,
191
+ message: error?.code === 'ENOENT'
192
+ ? 'nvidia-smi not found on the host'
193
+ : String(error?.message ?? error),
194
+ };
195
+ return new Response(JSON.stringify(body), {
196
+ status: 503,
197
+ headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' },
198
+ });
199
+ } finally {
200
+ sampling = undefined;
201
+ }
202
+ })();
203
+ return sampling;
204
+ }
205
+
206
+ /**
207
+ * Host half: expose one owner-authenticated GET route on the shared /api
208
+ * channel that returns a live nvidia-smi sample as JSON.
209
+ */
210
+ function apply(ctx, config) {
211
+ const intervalMs = config?.intervalMs ?? 2000;
212
+ const dispose = ctx.connection.registerFetchRoute(ctx, {
213
+ path: '/api/nvtop',
214
+ methods: ['GET'],
215
+ requestBody: 'buffered',
216
+ fetch: async () => {
217
+ try {
218
+ const result = await fetchStats();
219
+ if (result instanceof Response) return result;
220
+ return jsonResponse({ ...result, intervalMs });
221
+ } catch (error) {
222
+ console.error('[dsh-nvtop] stats route failed:', error);
223
+ return new Response(JSON.stringify({ ok: false, message: String(error?.message ?? error) }), {
224
+ status: 500,
225
+ headers: { 'content-type': 'application/json; charset=utf-8' },
226
+ });
227
+ }
228
+ },
229
+ });
230
+ ctx.effect(() => dispose, 'dsh-nvtop: /api/nvtop stats route');
231
+ }
232
+
233
+ export { Config, apply, inject };
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "GPU monitor (nvtop)",
4
+ "description": "Live nvtop-style GPU dashboard: utilization, memory, temperature, fan, power, and per-process GPU memory, refreshed automatically."
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,46 @@
1
1
  {
2
2
  "name": "dsh-nvtop-panel",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.1.0",
4
+ "private": false,
5
+ "type": "module",
6
+ "description": "nvtop-style live GPU dashboard panel for the DeepSeek Harness (DSH) Web UI: per-GPU utilization/memory/temperature/power cards plus a full nvtop-like process table (PID, USER, DEV, TYPE, GPU, GPU MEM, CPU, HOST MEM, Command).",
7
+ "license": "MIT",
8
+ "dependencies": {
9
+ "@deepseek-ai/schemastery": "^3.19.0"
10
+ },
11
+ "keywords": [
12
+ "dsh",
13
+ "deepseek-harness",
14
+ "nvtop",
15
+ "nvidia-smi",
16
+ "gpu",
17
+ "monitoring",
18
+ "dashboard"
19
+ ],
20
+ "exports": {
21
+ ".": "./index.js",
22
+ "./client": "./client.js",
23
+ "./locale/*.json": "./locale/*.json",
24
+ "./icon": "./icon.svg"
25
+ },
26
+ "files": [
27
+ "index.js",
28
+ "client.js",
29
+ "cordis.patch.yml",
30
+ "locale/*.json",
31
+ "icon.svg",
32
+ "README.md",
33
+ "LICENSE"
34
+ ],
35
+ "dsh": {
36
+ "bundle": { "patch": "./cordis.patch.yml" },
37
+ "client": {
38
+ "platform": "web",
39
+ "immediately": true,
40
+ "inject": [
41
+ "@deepseek-ai/dsh-client-ui-sidebar",
42
+ "@deepseek-ai/dsh-client-ui-layout"
43
+ ]
44
+ }
45
+ }
46
+ }