fix(apple): read ioreg PerformanceStatistics correctly and use physical RAM as VRAM total
ioreg prints the whole PerformanceStatistics dictionary on one line, so taking everything after the first '=' parsed the sub-dictionary opener and every Apple counter came back empty. Locate the key, then its '='. The '(driver)' sibling must be skipped without ending the search. Line buffer raised to 128 KB because that line is routinely 42 KB on an M1 Max. Unified memory means the honest VRAM total on a Mac is hw.memsize. Also: single-sample sparklines draw a dot instead of an invisible line, the VRAM KPI no longer truncates, the legend hides when there are no GPUs, and tests/e2e.py asserts rendered values at 1440/1024/390.
AuthorPico <picobot@scorpioplayer.com>
Date2026-11-11 08:33:08
Commit3681daaf
Parents1075888d
Changed files
.gitignore+2−0■■
src/plugin_nvtop.c+107−26■■■■■
tests/e2e.py+167−0■■■■■
4 files+276−26
Diff
.gitignore+2−0■■
index 8568772..da2ffe9 100644
--- a/.gitignore
+++ b/.gitignore
@@ -11,3 +11,5 @@ bin/
1111 __pycache__/
1212 *.pyc
1313 tests/fixtures/*.tmp
14+
15+tests/fixtures/*.json
plugin_nvtop.musl.x+0−0■
11new file mode 100755
index 0000000..5105b66
Binary file changed
src/plugin_nvtop.c+107−26■■■■■
index b04d270..cd5645b 100644
--- a/src/plugin_nvtop.c
+++ b/src/plugin_nvtop.c
@@ -51,6 +51,9 @@
5151 #else
5252 # include <unistd.h>
5353 # include <sys/types.h>
54+# if defined(__APPLE__)
55+# include <sys/sysctl.h>
56+# endif
5457 #endif
5558
5659 #define PLUGIN_SLUG "nvtop"
@@ -62,6 +65,10 @@
6265 #define MAX_NAME 96
6366 #define MAX_UUID 64
6467 #define MAX_DRIVER 48
68+/* ioreg prints the whole PerformanceStatistics dictionary on one line, which is
69+ * routinely several kilobytes. A 1 KB read buffer silently truncated it and the
70+ * utilisation counter looked like it was missing. */
71+#define LINE_MAX_BUF 131072
6572
6673 /* popen is the only external-process mechanism used, and every command string
6774 * is a compile-time constant. stderr redirection differs per platform because
@@ -321,7 +328,7 @@ static int feed_file_lines(const char *path, line_fn fn, void *ctx);
321328 static int run_cmd_lines(const char *cmd, line_fn fn, void *ctx)
322329 {
323330 FILE *fp;
324- char buf[1024];
331+ char buf[LINE_MAX_BUF];
325332 int any = 0;
326333
327334 fp = popen(cmd, "r");
@@ -389,7 +396,7 @@ static void mock_line(char *line, void *ctx)
389396 static int load_mock(snap_t *s, const char *path)
390397 {
391398 FILE *fp;
392- char buf[1024];
399+ char buf[LINE_MAX_BUF];
393400 int any = 0;
394401
395402 fp = fopen(path, "r");
@@ -475,7 +482,7 @@ static int collect_nvidia(snap_t *s)
475482 /* Fixture may interleave raw nvidia-smi GPU csv lines and "APP,..."
476483 * process lines; dispatch each line to the parser it belongs to. */
477484 FILE *fp = fopen(mocksmi, "r");
478- char buf[1024];
485+ char buf[LINE_MAX_BUF];
479486 got = 0;
480487 if (fp) {
481488 while (fgets(buf, (int)sizeof(buf), fp)) {
@@ -576,7 +583,7 @@ static void amd_line(char *line, void *ctx)
576583 static int feed_file_lines(const char *path, line_fn fn, void *ctx)
577584 {
578585 FILE *fp;
579- char buf[1024];
586+ char buf[LINE_MAX_BUF];
580587 int any = 0;
581588
582589 fp = fopen(path, "r");
@@ -615,11 +622,67 @@ static int collect_amd(snap_t *s)
615622
616623 /* ---- Apple Silicon (ioreg IOAccelerator) -------------------------- */
617624
625+/*
626+ * ioreg prints one big nested dictionary, and several counters live inside the
627+ * "PerformanceStatistics" sub-dictionary on the SAME physical line:
628+ *
629+ * "PerformanceStatistics" = {"In use system memory (driver)"=0, ...,
630+ * "Device Utilization %"=19,
631+ * "In use system memory"=51597524992}
632+ *
633+ * So the value of a counter is not "everything after the first '=' in the
634+ * line" - that would parse the sub-dictionary opener. Locate the key first,
635+ * then take the '=' that follows it.
636+ */
618637 #if defined(__APPLE__)
638+static const char *apple_value(const char *line, const char *key, int skip_paren)
639+{
640+ const char *p = line;
641+ size_t klen = strlen(key);
642+
643+ while ((p = strstr(p, key)) != NULL) {
644+ const char *v = p + klen;
645+ /* "In use system memory (driver)" also starts with the same text, so a
646+ * paren-suffixed hit must be skipped rather than ending the search. */
647+ if (skip_paren && v[0] == ' ') { p = v; continue; }
648+ while (*v == '"' || *v == ' ') v++;
649+ if (*v != '=') { p = v; continue; }
650+ v++;
651+ while (*v == ' ') v++;
652+ return v;
653+ }
654+ return NULL;
655+}
656+
657+static void apple_quoted(const char *v, char *out, size_t outsz)
658+{
659+ const char *end;
660+ size_t n;
661+ if (!v || !*v) return;
662+ if (*v == '"') {
663+ v++;
664+ end = strchr(v, '"');
665+ n = end ? (size_t)(end - v) : strlen(v);
666+ } else if (*v == '<') {
667+ v++;
668+ end = strchr(v, '>');
669+ n = end ? (size_t)(end - v) : strlen(v);
670+ } else {
671+ end = v;
672+ while (*end && *end != ',' && *end != '}') end++;
673+ n = (size_t)(end - v);
674+ while (n && v[n - 1] == ' ') n--;
675+ }
676+ if (n >= outsz) n = outsz - 1;
677+ if (n) { memcpy(out, v, n); out[n] = '\0'; }
678+}
679+
619680 static void apple_line(char *line, void *ctx)
620681 {
621682 snap_t *s = (snap_t *)ctx;
622683 gpu_t *g;
684+ const char *v;
685+ double num = 0;
623686
624687 if (s->ngpu == 0) {
625688 memset(&s->gpus[0], 0, sizeof(s->gpus[0]));
@@ -628,30 +691,34 @@ static void apple_line(char *line, void *ctx)
628691 }
629692 g = &s->gpus[0];
630693
631- if (strstr(line, "\"model\" =")) {
632- const char *p = strchr(line, '<');
633- const char *q = p ? strchr(p, '>') : NULL;
634- if (p && q && q > p + 1) {
635- size_t n = (size_t)(q - p - 1);
636- if (n >= sizeof(g->name)) n = sizeof(g->name) - 1;
637- memcpy(g->name, p + 1, n);
638- g->name[n] = '\0';
639- }
640- } else if (strstr(line, "Device Utilization %")) {
641- const char *p = strchr(line, '=');
642- double v = 0;
643- if (p && parse_num(p + 1, &v)) g->util_gpu = v;
644- } else if (strstr(line, "In use system memory")) {
645- const char *p = strchr(line, '=');
646- double v = 0;
647- if (p && parse_num(p + 1, &v)) g->mem_used_mb = v / (1024.0 * 1024.0);
648- }
694+ if ((v = apple_value(line, "\"model\"", 0)) != NULL)
695+ apple_quoted(v, g->name, sizeof(g->name));
696+
697+ if ((v = apple_value(line, "Device Utilization %", 0)) != NULL &&
698+ parse_num(v, &num))
699+ g->util_gpu = num;
700+
701+ /* Prefer the plain "In use system memory" over "(driver)". */
702+ if ((v = apple_value(line, "In use system memory", 1)) != NULL &&
703+ parse_num(v, &num))
704+ g->mem_used_mb = num / (1024.0 * 1024.0);
705+
706+ (void)v;
649707 }
650708
651709 static int collect_apple(snap_t *s)
652710 {
653711 int got = run_cmd_lines("ioreg -rc IOAccelerator -d 1" DEV_NULL, apple_line, s);
712+ unsigned long long memsize = 0;
713+ size_t len = sizeof(memsize);
714+
654715 if (!got || s->ngpu == 0) return 0;
716+
717+ /* Apple GPUs share the unified memory pool, so the honest "VRAM total" on a
718+ * Mac is the machine's physical RAM, not an allocation counter. */
719+ if (sysctlbyname("hw.memsize", &memsize, &len, NULL, 0) == 0 && memsize > 0)
720+ s->gpus[0].mem_total_mb = (double)memsize / (1024.0 * 1024.0);
721+
655722 copy_str(s->source, sizeof(s->source), "apple");
656723 s->available = 1;
657724 s->note[0] = '\0';
@@ -954,7 +1021,7 @@ static void mode_html(int embed)
9541021 "own collection step, rebuild with <code>make</code> and the dashboard "
9551022 "works unchanged.</div>"
9561023 "</div>"
957- "<div class='legend'><span><i class='dotc'></i>compute %</span>"
1024+ "<div class='legend' id='legend'><span><i class='dotc'></i>compute %</span>"
9581025 "<span><i class='dotv'></i>VRAM</span>"
9591026 "<span>rolling 60 samples</span></div>"
9601027 "</div>", stdout);
@@ -1041,6 +1108,16 @@ static void mode_html(int embed)
10411108 " var y = H - 1 - (v / 100) * (H - 3);\n"
10421109 " pts.push(x.toFixed(2) + ',' + y.toFixed(2));\n"
10431110 " }\n"
1111+" if (n === 1){\n"
1112+" var dot = document.createElementNS('http://www.w3.org/2000/svg', 'circle');\n"
1113+" var v1 = Math.max(0, Math.min(100, hist[0]));\n"
1114+" dot.setAttribute('cx', String(W));\n"
1115+" dot.setAttribute('cy', String(H - 1 - (v1 / 100) * (H - 3)));\n"
1116+" dot.setAttribute('r', '1.6');\n"
1117+" dot.setAttribute('fill', colour);\n"
1118+" svg.appendChild(dot);\n"
1119+" return svg;\n"
1120+" }\n"
10441121 " var poly = document.createElementNS('http://www.w3.org/2000/svg', 'polyline');\n"
10451122 " poly.setAttribute('points', pts.join(' '));\n"
10461123 " poly.setAttribute('fill', 'none');\n"
@@ -1090,11 +1167,15 @@ static void mode_html(int embed)
10901167 " card.appendChild(spark(h.m, 'var(--vram)'));\n"
10911168 " box.appendChild(card);\n"
10921169 " });\n"
1093-" if (gpus.length) $('emptyState').classList.add('hide');\n"
1094-" else $('emptyState').classList.remove('hide');\n"
1170+" if (gpus.length) { $('emptyState').classList.add('hide');\n"
1171+" $('legend').classList.remove('hide'); }\n"
1172+" else { $('emptyState').classList.remove('hide');\n"
1173+" $('legend').classList.add('hide'); }\n"
10951174 " txt('kGpus', String(gpus.length));\n"
10961175 " txt('kUtil', gpus.length ? Number(d.util_gpu_avg).toFixed(0) + '%' : '\\u2014');\n"
1097-" txt('kMem', gpus.length ? mb(d.mem_used_mb) + ' / ' + mb(d.mem_total_mb) : '\\u2014');\n"
1176+" txt('kMem', gpus.length\n"
1177+" ? (mb(d.mem_used_mb) + ' / ' + mb(d.mem_total_mb)).replace(' GB / ', '/').replace(' MB / ', '/')\n"
1178+" : '\\u2014');\n"
10981179 " txt('kPower', (d.power_w === null || d.power_w === undefined)\n"
10991180 " ? '\\u2014' : Math.round(d.power_w) + ' W');\n"
11001181 " txt('kProcs', String((d.processes || []).length));\n"
tests/e2e.py+167−0■■■■■
11new file mode 100644
index 0000000..810b8d8
--- /dev/null
+++ b/tests/e2e.py
@@ -0,0 +1,167 @@
1+#!/usr/bin/env python3
2+"""tests/e2e.py - viewport + rendering checks for the plugin_nvtop dashboard.
3+
4+Serves the plugin through a tiny CGI-ish HTTP shim on a loopback port, opens it
5+with Playwright at 1440 / 1024 / 390 CSS pixels, and asserts:
6+
7+ * no horizontal overflow,
8+ * no console errors,
9+ * the overview KPIs rendered numbers,
10+ * the per-GPU cards rendered (mock 4-GPU fixture), each with two sparklines,
11+ * the compute process table rendered rows.
12+
13+The fixture is injected through NVTOP_MOCK_CSV so the checks are deterministic
14+on any host, GPU or not. Skips cleanly (exit 0) when Playwright is missing, so
15+`make test` stays offline-only.
16+
17+ python3 tests/e2e.py # run if Playwright is available
18+ python3 tests/e2e.py --strict # exit 2 when Playwright is missing
19+"""
20+
21+import argparse
22+import http.server
23+import os
24+import subprocess
25+import socketserver
26+import sys
27+import threading
28+
29+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
30+BIN = os.path.join(ROOT, "plugin_nvtop")
31+FIXTURE = os.path.join(ROOT, "tests", "fixtures", "mock-4gpu.csv")
32+VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)]
33+
34+
35+class Handler(http.server.BaseHTTPRequestHandler):
36+ def do_GET(self): # noqa: N802
37+ from urllib.parse import urlparse
38+ u = urlparse(self.path)
39+ env = dict(os.environ)
40+ env["QUERY_STRING"] = u.query
41+ env["REQUEST_METHOD"] = "GET"
42+ env.pop("BOT_PASSWORD", None)
43+ env["NVTOP_MOCK_CSV"] = FIXTURE
44+ out = subprocess.run([BIN], capture_output=True, env=env, timeout=60).stdout
45+ sep = out.find(b"\r\n\r\n")
46+ headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else ""
47+ body = out[sep + 4:] if sep >= 0 else out
48+ ctype = "text/html; charset=utf-8"
49+ for line in headers.splitlines():
50+ if line.lower().startswith("content-type:"):
51+ ctype = line.split(":", 1)[1].strip()
52+ self.send_response(200)
53+ self.send_header("Content-Type", ctype)
54+ self.send_header("Cache-Control", "no-store")
55+ # no Content-Length from the plugin; the shim sets its own framing
56+ self.send_header("Content-Length", str(len(body)))
57+ self.end_headers()
58+ self.wfile.write(body)
59+
60+ def log_message(self, *_a):
61+ pass
62+
63+
64+def main():
65+ ap = argparse.ArgumentParser()
66+ ap.add_argument("--strict", action="store_true")
67+ args = ap.parse_args()
68+
69+ if not os.path.exists(BIN):
70+ print("plugin_nvtop is not built; run make first", file=sys.stderr)
71+ return 1
72+
73+ try:
74+ from playwright.sync_api import sync_playwright
75+ except Exception:
76+ msg = "playwright not installed - skipping viewport e2e"
77+ if args.strict:
78+ print(msg, file=sys.stderr)
79+ return 2
80+ print(msg)
81+ return 0
82+
83+ with socketserver.TCPServer(("127.0.0.1", 0), Handler) as srv:
84+ port = srv.server_address[1]
85+ threading.Thread(target=srv.serve_forever, daemon=True).start()
86+ url = "http://127.0.0.1:%d/plugin_nvtop" % port
87+
88+ failures = []
89+ with sync_playwright() as p:
90+ browser = p.chromium.launch()
91+ for (w, h) in VIEWPORTS:
92+ page = browser.new_page(viewport={"width": w, "height": h})
93+ errors = []
94+ page.on("console", lambda m: errors.append(m.text)
95+ if m.type == "error" else None)
96+ page.goto(url, wait_until="load")
97+ page.wait_for_timeout(3200)
98+
99+ sw = page.evaluate("document.documentElement.scrollWidth")
100+ iw = page.evaluate("window.innerWidth")
101+ if sw > iw + 1:
102+ failures.append("%dx%d horizontal overflow %d > %d" % (w, h, sw, iw))
103+
104+ kpis = page.evaluate(
105+ "['kGpus','kUtil','kMem','kProcs'].map(function(i){"
106+ "var e=document.getElementById(i);"
107+ "return e?e.textContent.trim():'';})")
108+ cards = page.evaluate(
109+ "document.querySelectorAll('#gpuGrid .gpu').length")
110+ sparks = page.evaluate(
111+ "document.querySelectorAll('#gpuGrid svg.spark').length")
112+ rows = page.evaluate(
113+ "document.querySelectorAll('#procRows tr').length")
114+ chips = page.evaluate(
115+ "document.querySelectorAll('#gpuGrid .chip').length")
116+ empty_hidden = page.evaluate(
117+ "document.getElementById('emptyState')"
118+ ".classList.contains('hide')")
119+
120+ if kpis[0] != "4":
121+ failures.append("%dx%d GPU KPI did not render 4 (%r)"
122+ % (w, h, kpis[0]))
123+ if not kpis[1].endswith("%"):
124+ failures.append("%dx%d compute KPI missing %% (%r)"
125+ % (w, h, kpis[1]))
126+ if "GB" not in kpis[2] and "MB" not in kpis[2]:
127+ failures.append("%dx%d VRAM KPI missing units (%r)"
128+ % (w, h, kpis[2]))
129+ if kpis[3] != "4":
130+ failures.append("%dx%d process KPI did not render 4 (%r)"
131+ % (w, h, kpis[3]))
132+ if cards != 4:
133+ failures.append("%dx%d expected 4 GPU cards, got %d"
134+ % (w, h, cards))
135+ if sparks < 8:
136+ failures.append("%dx%d expected >=8 sparklines, got %d"
137+ % (w, h, sparks))
138+ if chips < 12:
139+ failures.append("%dx%d expected >=12 chips, got %d"
140+ % (w, h, chips))
141+ if rows != 4:
142+ failures.append("%dx%d expected 4 process rows, got %d"
143+ % (w, h, rows))
144+ if not empty_hidden:
145+ failures.append("%dx%d empty state still visible with GPUs"
146+ % (w, h))
147+
148+ real = [e for e in errors if "favicon" not in e.lower()]
149+ if real:
150+ failures.append("%dx%d console errors: %s" % (w, h, real[:3]))
151+
152+ print(" %dx%d scroll=%d/%d cards=%d sparks=%d rows=%d kpis=%s"
153+ % (w, h, sw, iw, cards, sparks, rows, ",".join(kpis)))
154+ page.close()
155+ browser.close()
156+ srv.shutdown()
157+
158+ if failures:
159+ for f in failures:
160+ print(" FAIL " + f)
161+ return 1
162+ print(" viewport e2e passed at %d sizes" % len(VIEWPORTS))
163+ return 0
164+
165+
166+if __name__ == "__main__":
167+ sys.exit(main())
0168
.gitignore+2−0■■
index 8568772..da2ffe9 100644index 8568772..da2ffe9 100644
--- a/.gitignore--- a/.gitignore
+++ b/.gitignore+++ b/.gitignore
@@ -11,3 +11,5 @@ bin/@@ -11,3 +11,5 @@ bin/
11 __pycache__/11 __pycache__/
12 *.pyc12 *.pyc
13 tests/fixtures/*.tmp13 tests/fixtures/*.tmp
14+
15+tests/fixtures/*.json
plugin_nvtop.musl.x+0−0■
1new file mode 1007551new file mode 100755
index 0000000..5105b66index 0000000..5105b66
Binary file changed
src/plugin_nvtop.c+107−26■■■■■
index b04d270..cd5645b 100644index b04d270..cd5645b 100644
--- a/src/plugin_nvtop.c--- a/src/plugin_nvtop.c
+++ b/src/plugin_nvtop.c+++ b/src/plugin_nvtop.c
@@ -51,6 +51,9 @@@@ -51,6 +51,9 @@
51 #else51 #else
52 # include <unistd.h>52 # include <unistd.h>
53 # include <sys/types.h>53 # include <sys/types.h>
54+# if defined(__APPLE__)
55+# include <sys/sysctl.h>
56+# endif
54 #endif57 #endif
55 58
56 #define PLUGIN_SLUG "nvtop"59 #define PLUGIN_SLUG "nvtop"
@@ -62,6 +65,10 @@@@ -62,6 +65,10 @@
62 #define MAX_NAME 9665 #define MAX_NAME 96
63 #define MAX_UUID 6466 #define MAX_UUID 64
64 #define MAX_DRIVER 4867 #define MAX_DRIVER 48
68+/* ioreg prints the whole PerformanceStatistics dictionary on one line, which is
69+ * routinely several kilobytes. A 1 KB read buffer silently truncated it and the
70+ * utilisation counter looked like it was missing. */
71+#define LINE_MAX_BUF 131072
65 72
66 /* popen is the only external-process mechanism used, and every command string73 /* popen is the only external-process mechanism used, and every command string
67 * is a compile-time constant. stderr redirection differs per platform because74 * is a compile-time constant. stderr redirection differs per platform because
@@ -321,7 +328,7 @@ static int feed_file_lines(const char *path, line_fn fn, void *ctx);@@ -321,7 +328,7 @@ static int feed_file_lines(const char *path, line_fn fn, void *ctx);
321 static int run_cmd_lines(const char *cmd, line_fn fn, void *ctx)328 static int run_cmd_lines(const char *cmd, line_fn fn, void *ctx)
322 {329 {
323 FILE *fp;330 FILE *fp;
324- char buf[1024];331+ char buf[LINE_MAX_BUF];
325 int any = 0;332 int any = 0;
326 333
327 fp = popen(cmd, "r");334 fp = popen(cmd, "r");
@@ -389,7 +396,7 @@ static void mock_line(char *line, void *ctx)@@ -389,7 +396,7 @@ static void mock_line(char *line, void *ctx)
389 static int load_mock(snap_t *s, const char *path)396 static int load_mock(snap_t *s, const char *path)
390 {397 {
391 FILE *fp;398 FILE *fp;
392- char buf[1024];399+ char buf[LINE_MAX_BUF];
393 int any = 0;400 int any = 0;
394 401
395 fp = fopen(path, "r");402 fp = fopen(path, "r");
@@ -475,7 +482,7 @@ static int collect_nvidia(snap_t *s)@@ -475,7 +482,7 @@ static int collect_nvidia(snap_t *s)
475 /* Fixture may interleave raw nvidia-smi GPU csv lines and "APP,..."482 /* Fixture may interleave raw nvidia-smi GPU csv lines and "APP,..."
476 * process lines; dispatch each line to the parser it belongs to. */483 * process lines; dispatch each line to the parser it belongs to. */
477 FILE *fp = fopen(mocksmi, "r");484 FILE *fp = fopen(mocksmi, "r");
478- char buf[1024];485+ char buf[LINE_MAX_BUF];
479 got = 0;486 got = 0;
480 if (fp) {487 if (fp) {
481 while (fgets(buf, (int)sizeof(buf), fp)) {488 while (fgets(buf, (int)sizeof(buf), fp)) {
@@ -576,7 +583,7 @@ static void amd_line(char *line, void *ctx)@@ -576,7 +583,7 @@ static void amd_line(char *line, void *ctx)
576 static int feed_file_lines(const char *path, line_fn fn, void *ctx)583 static int feed_file_lines(const char *path, line_fn fn, void *ctx)
577 {584 {
578 FILE *fp;585 FILE *fp;
579- char buf[1024];586+ char buf[LINE_MAX_BUF];
580 int any = 0;587 int any = 0;
581 588
582 fp = fopen(path, "r");589 fp = fopen(path, "r");
@@ -615,11 +622,67 @@ static int collect_amd(snap_t *s)@@ -615,11 +622,67 @@ static int collect_amd(snap_t *s)
615 622
616 /* ---- Apple Silicon (ioreg IOAccelerator) -------------------------- */623 /* ---- Apple Silicon (ioreg IOAccelerator) -------------------------- */
617 624
625+/*
626+ * ioreg prints one big nested dictionary, and several counters live inside the
627+ * "PerformanceStatistics" sub-dictionary on the SAME physical line:
628+ *
629+ * "PerformanceStatistics" = {"In use system memory (driver)"=0, ...,
630+ * "Device Utilization %"=19,
631+ * "In use system memory"=51597524992}
632+ *
633+ * So the value of a counter is not "everything after the first '=' in the
634+ * line" - that would parse the sub-dictionary opener. Locate the key first,
635+ * then take the '=' that follows it.
636+ */
618 #if defined(__APPLE__)637 #if defined(__APPLE__)
638+static const char *apple_value(const char *line, const char *key, int skip_paren)
639+{
640+ const char *p = line;
641+ size_t klen = strlen(key);
642+
643+ while ((p = strstr(p, key)) != NULL) {
644+ const char *v = p + klen;
645+ /* "In use system memory (driver)" also starts with the same text, so a
646+ * paren-suffixed hit must be skipped rather than ending the search. */
647+ if (skip_paren && v[0] == ' ') { p = v; continue; }
648+ while (*v == '"' || *v == ' ') v++;
649+ if (*v != '=') { p = v; continue; }
650+ v++;
651+ while (*v == ' ') v++;
652+ return v;
653+ }
654+ return NULL;
655+}
656+
657+static void apple_quoted(const char *v, char *out, size_t outsz)
658+{
659+ const char *end;
660+ size_t n;
661+ if (!v || !*v) return;
662+ if (*v == '"') {
663+ v++;
664+ end = strchr(v, '"');
665+ n = end ? (size_t)(end - v) : strlen(v);
666+ } else if (*v == '<') {
667+ v++;
668+ end = strchr(v, '>');
669+ n = end ? (size_t)(end - v) : strlen(v);
670+ } else {
671+ end = v;
672+ while (*end && *end != ',' && *end != '}') end++;
673+ n = (size_t)(end - v);
674+ while (n && v[n - 1] == ' ') n--;
675+ }
676+ if (n >= outsz) n = outsz - 1;
677+ if (n) { memcpy(out, v, n); out[n] = '\0'; }
678+}
679+
619 static void apple_line(char *line, void *ctx)680 static void apple_line(char *line, void *ctx)
620 {681 {
621 snap_t *s = (snap_t *)ctx;682 snap_t *s = (snap_t *)ctx;
622 gpu_t *g;683 gpu_t *g;
684+ const char *v;
685+ double num = 0;
623 686
624 if (s->ngpu == 0) {687 if (s->ngpu == 0) {
625 memset(&s->gpus[0], 0, sizeof(s->gpus[0]));688 memset(&s->gpus[0], 0, sizeof(s->gpus[0]));
@@ -628,30 +691,34 @@ static void apple_line(char *line, void *ctx)@@ -628,30 +691,34 @@ static void apple_line(char *line, void *ctx)
628 }691 }
629 g = &s->gpus[0];692 g = &s->gpus[0];
630 693
631- if (strstr(line, "\"model\" =")) {694+ if ((v = apple_value(line, "\"model\"", 0)) != NULL)
632- const char *p = strchr(line, '<');695+ apple_quoted(v, g->name, sizeof(g->name));
633- const char *q = p ? strchr(p, '>') : NULL;696+
634- if (p && q && q > p + 1) {697+ if ((v = apple_value(line, "Device Utilization %", 0)) != NULL &&
635- size_t n = (size_t)(q - p - 1);698+ parse_num(v, &num))
636- if (n >= sizeof(g->name)) n = sizeof(g->name) - 1;699+ g->util_gpu = num;
637- memcpy(g->name, p + 1, n);700+
638- g->name[n] = '\0';701+ /* Prefer the plain "In use system memory" over "(driver)". */
639- }702+ if ((v = apple_value(line, "In use system memory", 1)) != NULL &&
640- } else if (strstr(line, "Device Utilization %")) {703+ parse_num(v, &num))
641- const char *p = strchr(line, '=');704+ g->mem_used_mb = num / (1024.0 * 1024.0);
642- double v = 0;705+
643- if (p && parse_num(p + 1, &v)) g->util_gpu = v;706+ (void)v;
644- } else if (strstr(line, "In use system memory")) {
645- const char *p = strchr(line, '=');
646- double v = 0;
647- if (p && parse_num(p + 1, &v)) g->mem_used_mb = v / (1024.0 * 1024.0);
648- }
649 }707 }
650 708
651 static int collect_apple(snap_t *s)709 static int collect_apple(snap_t *s)
652 {710 {
653 int got = run_cmd_lines("ioreg -rc IOAccelerator -d 1" DEV_NULL, apple_line, s);711 int got = run_cmd_lines("ioreg -rc IOAccelerator -d 1" DEV_NULL, apple_line, s);
712+ unsigned long long memsize = 0;
713+ size_t len = sizeof(memsize);
714+
654 if (!got || s->ngpu == 0) return 0;715 if (!got || s->ngpu == 0) return 0;
716+
717+ /* Apple GPUs share the unified memory pool, so the honest "VRAM total" on a
718+ * Mac is the machine's physical RAM, not an allocation counter. */
719+ if (sysctlbyname("hw.memsize", &memsize, &len, NULL, 0) == 0 && memsize > 0)
720+ s->gpus[0].mem_total_mb = (double)memsize / (1024.0 * 1024.0);
721+
655 copy_str(s->source, sizeof(s->source), "apple");722 copy_str(s->source, sizeof(s->source), "apple");
656 s->available = 1;723 s->available = 1;
657 s->note[0] = '\0';724 s->note[0] = '\0';
@@ -954,7 +1021,7 @@ static void mode_html(int embed)@@ -954,7 +1021,7 @@ static void mode_html(int embed)
954 "own collection step, rebuild with <code>make</code> and the dashboard "1021 "own collection step, rebuild with <code>make</code> and the dashboard "
955 "works unchanged.</div>"1022 "works unchanged.</div>"
956 "</div>"1023 "</div>"
957- "<div class='legend'><span><i class='dotc'></i>compute %</span>"1024+ "<div class='legend' id='legend'><span><i class='dotc'></i>compute %</span>"
958 "<span><i class='dotv'></i>VRAM</span>"1025 "<span><i class='dotv'></i>VRAM</span>"
959 "<span>rolling 60 samples</span></div>"1026 "<span>rolling 60 samples</span></div>"
960 "</div>", stdout);1027 "</div>", stdout);
@@ -1041,6 +1108,16 @@ static void mode_html(int embed)@@ -1041,6 +1108,16 @@ static void mode_html(int embed)
1041 " var y = H - 1 - (v / 100) * (H - 3);\n"1108 " var y = H - 1 - (v / 100) * (H - 3);\n"
1042 " pts.push(x.toFixed(2) + ',' + y.toFixed(2));\n"1109 " pts.push(x.toFixed(2) + ',' + y.toFixed(2));\n"
1043 " }\n"1110 " }\n"
1111+" if (n === 1){\n"
1112+" var dot = document.createElementNS('http://www.w3.org/2000/svg', 'circle');\n"
1113+" var v1 = Math.max(0, Math.min(100, hist[0]));\n"
1114+" dot.setAttribute('cx', String(W));\n"
1115+" dot.setAttribute('cy', String(H - 1 - (v1 / 100) * (H - 3)));\n"
1116+" dot.setAttribute('r', '1.6');\n"
1117+" dot.setAttribute('fill', colour);\n"
1118+" svg.appendChild(dot);\n"
1119+" return svg;\n"
1120+" }\n"
1044 " var poly = document.createElementNS('http://www.w3.org/2000/svg', 'polyline');\n"1121 " var poly = document.createElementNS('http://www.w3.org/2000/svg', 'polyline');\n"
1045 " poly.setAttribute('points', pts.join(' '));\n"1122 " poly.setAttribute('points', pts.join(' '));\n"
1046 " poly.setAttribute('fill', 'none');\n"1123 " poly.setAttribute('fill', 'none');\n"
@@ -1090,11 +1167,15 @@ static void mode_html(int embed)@@ -1090,11 +1167,15 @@ static void mode_html(int embed)
1090 " card.appendChild(spark(h.m, 'var(--vram)'));\n"1167 " card.appendChild(spark(h.m, 'var(--vram)'));\n"
1091 " box.appendChild(card);\n"1168 " box.appendChild(card);\n"
1092 " });\n"1169 " });\n"
1093-" if (gpus.length) $('emptyState').classList.add('hide');\n"1170+" if (gpus.length) { $('emptyState').classList.add('hide');\n"
1094-" else $('emptyState').classList.remove('hide');\n"1171+" $('legend').classList.remove('hide'); }\n"
1172+" else { $('emptyState').classList.remove('hide');\n"
1173+" $('legend').classList.add('hide'); }\n"
1095 " txt('kGpus', String(gpus.length));\n"1174 " txt('kGpus', String(gpus.length));\n"
1096 " txt('kUtil', gpus.length ? Number(d.util_gpu_avg).toFixed(0) + '%' : '\\u2014');\n"1175 " txt('kUtil', gpus.length ? Number(d.util_gpu_avg).toFixed(0) + '%' : '\\u2014');\n"
1097-" txt('kMem', gpus.length ? mb(d.mem_used_mb) + ' / ' + mb(d.mem_total_mb) : '\\u2014');\n"1176+" txt('kMem', gpus.length\n"
1177+" ? (mb(d.mem_used_mb) + ' / ' + mb(d.mem_total_mb)).replace(' GB / ', '/').replace(' MB / ', '/')\n"
1178+" : '\\u2014');\n"
1098 " txt('kPower', (d.power_w === null || d.power_w === undefined)\n"1179 " txt('kPower', (d.power_w === null || d.power_w === undefined)\n"
1099 " ? '\\u2014' : Math.round(d.power_w) + ' W');\n"1180 " ? '\\u2014' : Math.round(d.power_w) + ' W');\n"
1100 " txt('kProcs', String((d.processes || []).length));\n"1181 " txt('kProcs', String((d.processes || []).length));\n"
tests/e2e.py+167−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..810b8d8index 0000000..810b8d8
--- /dev/null--- /dev/null
+++ b/tests/e2e.py+++ b/tests/e2e.py
@@ -0,0 +1,167 @@@@ -0,0 +1,167 @@
1+#!/usr/bin/env python3
2+"""tests/e2e.py - viewport + rendering checks for the plugin_nvtop dashboard.
3+
4+Serves the plugin through a tiny CGI-ish HTTP shim on a loopback port, opens it
5+with Playwright at 1440 / 1024 / 390 CSS pixels, and asserts:
6+
7+ * no horizontal overflow,
8+ * no console errors,
9+ * the overview KPIs rendered numbers,
10+ * the per-GPU cards rendered (mock 4-GPU fixture), each with two sparklines,
11+ * the compute process table rendered rows.
12+
13+The fixture is injected through NVTOP_MOCK_CSV so the checks are deterministic
14+on any host, GPU or not. Skips cleanly (exit 0) when Playwright is missing, so
15+`make test` stays offline-only.
16+
17+ python3 tests/e2e.py # run if Playwright is available
18+ python3 tests/e2e.py --strict # exit 2 when Playwright is missing
19+"""
20+
21+import argparse
22+import http.server
23+import os
24+import subprocess
25+import socketserver
26+import sys
27+import threading
28+
29+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
30+BIN = os.path.join(ROOT, "plugin_nvtop")
31+FIXTURE = os.path.join(ROOT, "tests", "fixtures", "mock-4gpu.csv")
32+VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)]
33+
34+
35+class Handler(http.server.BaseHTTPRequestHandler):
36+ def do_GET(self): # noqa: N802
37+ from urllib.parse import urlparse
38+ u = urlparse(self.path)
39+ env = dict(os.environ)
40+ env["QUERY_STRING"] = u.query
41+ env["REQUEST_METHOD"] = "GET"
42+ env.pop("BOT_PASSWORD", None)
43+ env["NVTOP_MOCK_CSV"] = FIXTURE
44+ out = subprocess.run([BIN], capture_output=True, env=env, timeout=60).stdout
45+ sep = out.find(b"\r\n\r\n")
46+ headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else ""
47+ body = out[sep + 4:] if sep >= 0 else out
48+ ctype = "text/html; charset=utf-8"
49+ for line in headers.splitlines():
50+ if line.lower().startswith("content-type:"):
51+ ctype = line.split(":", 1)[1].strip()
52+ self.send_response(200)
53+ self.send_header("Content-Type", ctype)
54+ self.send_header("Cache-Control", "no-store")
55+ # no Content-Length from the plugin; the shim sets its own framing
56+ self.send_header("Content-Length", str(len(body)))
57+ self.end_headers()
58+ self.wfile.write(body)
59+
60+ def log_message(self, *_a):
61+ pass
62+
63+
64+def main():
65+ ap = argparse.ArgumentParser()
66+ ap.add_argument("--strict", action="store_true")
67+ args = ap.parse_args()
68+
69+ if not os.path.exists(BIN):
70+ print("plugin_nvtop is not built; run make first", file=sys.stderr)
71+ return 1
72+
73+ try:
74+ from playwright.sync_api import sync_playwright
75+ except Exception:
76+ msg = "playwright not installed - skipping viewport e2e"
77+ if args.strict:
78+ print(msg, file=sys.stderr)
79+ return 2
80+ print(msg)
81+ return 0
82+
83+ with socketserver.TCPServer(("127.0.0.1", 0), Handler) as srv:
84+ port = srv.server_address[1]
85+ threading.Thread(target=srv.serve_forever, daemon=True).start()
86+ url = "http://127.0.0.1:%d/plugin_nvtop" % port
87+
88+ failures = []
89+ with sync_playwright() as p:
90+ browser = p.chromium.launch()
91+ for (w, h) in VIEWPORTS:
92+ page = browser.new_page(viewport={"width": w, "height": h})
93+ errors = []
94+ page.on("console", lambda m: errors.append(m.text)
95+ if m.type == "error" else None)
96+ page.goto(url, wait_until="load")
97+ page.wait_for_timeout(3200)
98+
99+ sw = page.evaluate("document.documentElement.scrollWidth")
100+ iw = page.evaluate("window.innerWidth")
101+ if sw > iw + 1:
102+ failures.append("%dx%d horizontal overflow %d > %d" % (w, h, sw, iw))
103+
104+ kpis = page.evaluate(
105+ "['kGpus','kUtil','kMem','kProcs'].map(function(i){"
106+ "var e=document.getElementById(i);"
107+ "return e?e.textContent.trim():'';})")
108+ cards = page.evaluate(
109+ "document.querySelectorAll('#gpuGrid .gpu').length")
110+ sparks = page.evaluate(
111+ "document.querySelectorAll('#gpuGrid svg.spark').length")
112+ rows = page.evaluate(
113+ "document.querySelectorAll('#procRows tr').length")
114+ chips = page.evaluate(
115+ "document.querySelectorAll('#gpuGrid .chip').length")
116+ empty_hidden = page.evaluate(
117+ "document.getElementById('emptyState')"
118+ ".classList.contains('hide')")
119+
120+ if kpis[0] != "4":
121+ failures.append("%dx%d GPU KPI did not render 4 (%r)"
122+ % (w, h, kpis[0]))
123+ if not kpis[1].endswith("%"):
124+ failures.append("%dx%d compute KPI missing %% (%r)"
125+ % (w, h, kpis[1]))
126+ if "GB" not in kpis[2] and "MB" not in kpis[2]:
127+ failures.append("%dx%d VRAM KPI missing units (%r)"
128+ % (w, h, kpis[2]))
129+ if kpis[3] != "4":
130+ failures.append("%dx%d process KPI did not render 4 (%r)"
131+ % (w, h, kpis[3]))
132+ if cards != 4:
133+ failures.append("%dx%d expected 4 GPU cards, got %d"
134+ % (w, h, cards))
135+ if sparks < 8:
136+ failures.append("%dx%d expected >=8 sparklines, got %d"
137+ % (w, h, sparks))
138+ if chips < 12:
139+ failures.append("%dx%d expected >=12 chips, got %d"
140+ % (w, h, chips))
141+ if rows != 4:
142+ failures.append("%dx%d expected 4 process rows, got %d"
143+ % (w, h, rows))
144+ if not empty_hidden:
145+ failures.append("%dx%d empty state still visible with GPUs"
146+ % (w, h))
147+
148+ real = [e for e in errors if "favicon" not in e.lower()]
149+ if real:
150+ failures.append("%dx%d console errors: %s" % (w, h, real[:3]))
151+
152+ print(" %dx%d scroll=%d/%d cards=%d sparks=%d rows=%d kpis=%s"
153+ % (w, h, sw, iw, cards, sparks, rows, ",".join(kpis)))
154+ page.close()
155+ browser.close()
156+ srv.shutdown()
157+
158+ if failures:
159+ for f in failures:
160+ print(" FAIL " + f)
161+ return 1
162+ print(" viewport e2e passed at %d sizes" % len(VIEWPORTS))
163+ return 0
164+
165+
166+if __name__ == "__main__":
167+ sys.exit(main())
0168