Public: anyone can read this; the crew can change it.

Migrated from github.com/Trevato/SO-ARM100

workbenchthis machine

The page's metrics panel script lives in src/ui/metrics-panel.js - no behaviour change #118

Merged opened this

Check · Review · Land done · Live — Landed; nothing deploys from this branch, so this is the end of its path.

Merged

smith/arm:smith/96-the-page-s-metrics-panel-script-lives-in → main 2 commits fork 1 thread · 1 unresolved

  • Merged. smith/96-the-page-s-metrics-panel-script-lives-in was merged into main as b4a6aaa.

Review

Sign in to review this change.
5 files changed +101 −25
Software/so101/src/server.test.ts +6 −2
@@ -144,7 +144,10 @@ describe("viewer page", () => {
144144 const sinks = html.split("\n").filter((line) => /\.innerHTML\s*=/.test(line));
145145 expect(sinks.length).toBeGreaterThan(0);
146146 for (const line of sinks) expect(line).not.toMatch(/detail|\.by\b|estop|chat|\bname\b/);
147 expect(html).toContain('$("events").replaceChildren(');
147 // The events sink moved with the Metrics panel into its module: same rule there.
148 const module = await (await fetch(`${base}${html.match(/import\("(\/ui\/[^"]+\/metrics-panel\.js)"\)/)![1]}`)).text();
149 for (const line of module.split("\n").filter((l) => /\.innerHTML\s*=/.test(l))) expect(line).not.toMatch(/detail|\.by\b|estop|chat|\bname\b/);
150 expect(module).toContain('$("events").replaceChildren(');
148151 });
149152
150153 test("a first visit downloads under 50 KB gzipped: the page and the modules it imports up front; the rest comes when needed", async () => {
@@ -160,10 +163,11 @@ describe("viewer page", () => {
160163 }
161164 expect(bytes).toBeLessThan(50_000);
162165 // three.js, the leader's mapping, the calibration panel and the Machine panel are imported where they are used, not up front.
163 for (const lazy of ["three", "/leader-map.js", "calibration.js", "reach.js", "machine-panel.js", "machine.js"]) expect([...upfront].some((p) => p === lazy || p.endsWith(`/${lazy}`))).toBe(false);
166 for (const lazy of ["three", "/leader-map.js", "calibration.js", "reach.js", "machine-panel.js", "machine.js", "metrics-panel.js"]) expect([...upfront].some((p) => p === lazy || p.endsWith(`/${lazy}`))).toBe(false);
164167 expect(script).toContain('import("/leader-map.js")');
165168 expect(script).toMatch(/import\("\/ui\/[0-9a-f]{12}\/calibration\.js"\)/);
166169 expect(script).toMatch(/import\("\/ui\/[0-9a-f]{12}\/machine-panel\.js"\)/);
170 expect(script).toMatch(/import\("\/ui\/[0-9a-f]{12}\/metrics-panel\.js"\)/);
167171 });
168172
169173 test("names its modules by their content, serves them for good, and serves nothing else from src/ui", async () => {
Software/so101/src/ui/metrics-panel.js added +62
@@ -0,0 +1,62 @@
1 // @ts-check
2 /**
3 * The Metrics panel on the page: counters, peaks per joint and the recent events, from the arm server's /metrics.
4 * Loaded the first time the panel opens, so a first visit never pays for it. The renderers are pure and escape what
5 * they print; an event's detail carries people's names (who pressed the E-stop) and error strings.
6 */
7
8 /** @type {Record<string, string>} */
9 const ENTITIES = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" };
10 /** @param {unknown} v */
11 export const esc = (v) => String(v).replace(/[&<>"']/g, (c) => ENTITIES[c]);
12
13 /**
14 * @param {any} m the /metrics summary
15 * @param {{ p50: number, p95: number, n: number } | null | undefined} lag this browser's teleop lag
16 * @returns {[string, unknown][]}
17 */
18 export function summaryRows(m, lag) {
19 const c = m.counters;
20 return [
21 ["since", (m.since ?? "").replace("T", " ").slice(0, 19)],
22 ["jams", c.jam], ["zone blocks", c.block], ["stalls on moves", c.stall], ["lost servos", c.missing], ["hot joints", c.hot],
23 ["sessions", `${c.stream} streams · ${c.move} moves · ${c.play} playbacks · ${c.record} recordings`],
24 ["teleop lag, this browser", lag ? `p50 ${lag.p50} ms · p95 ${lag.p95} ms over ${lag.n} samples` : "—"],
25 ["closest to the table", m.closest ? `${(m.closest.z * 1000).toFixed(0)} mm (${m.closest.link.replace(/_link$/, "")}, ${m.closest.at.slice(11, 19)})` : "—"],
26 ];
27 }
28
29 /** @param {[string, unknown][]} rows */
30 export const summaryHtml = (rows) => rows.map(([k, v]) => `<b>${esc(k)}</b><span>${esc(v)}</span>`).join("");
31
32 /**
33 * @param {Record<string, { load: number, temperature: number }>} peaks by servo id
34 * @param {Record<string, string>} names joint names by servo id
35 */
36 export const peaksHtml = (peaks, names) =>
37 "<tr><th>joint</th><th>peak load</th><th>peak temperature</th></tr>" +
38 Object.entries(peaks).map(([id, p]) => `<tr><td>${esc(names[id] ?? id)}</td><td>${esc(p.load.toFixed(0))} %</td><td>${esc(p.temperature)} °C</td></tr>`).join("");
39
40 /** An event as the three pieces the page prints, newest first is the caller's order; all are text. @param {any} e */
41 export const eventParts = (e) => ({
42 when: String(e.t).slice(5, 19).replace("T", " "),
43 kind: String(e.kind),
44 detail: Object.entries(e.detail ?? {}).map(([k, v]) => `${k}=${typeof v === "object" ? JSON.stringify(v) : v}`).join(" "),
45 });
46
47 /**
48 * Fetch /metrics and fill the panel, then show it.
49 * @param {{ api: (path: string) => Promise<any>, lag: () => ({ p50: number, p95: number, n: number } | null | undefined), names: Record<string, string> }} options
50 */
51 export async function showMetrics({ api, lag, names }) {
52 const doc = /** @type {any} */ (globalThis).document;
53 const $ = (/** @type {string} */ id) => doc.getElementById(id);
54 const el = (/** @type {string} */ tag, /** @type {Record<string, unknown>} */ props, /** @type {any[]} */ ...children) => { const e = Object.assign(doc.createElement(tag), props); e.append(...children); return e; };
55 const m = await api("/metrics");
56 $("metricsSummary").innerHTML = summaryHtml(summaryRows(m, lag()));
57 $("peaks").innerHTML = peaksHtml(m.peaks, names);
58 // Built from text nodes, so nothing an event carries is ever read as markup.
59 const recent = [...(m.recent ?? [])].reverse();
60 $("events").replaceChildren(...(recent.length ? recent.map((e) => { const p = eventParts(e); return el("div", {}, `${p.when} `, el("b", { textContent: p.kind }), ` ${p.detail}`); }) : [el("div", { textContent: "none yet" })]));
61 $("metricsPanel").hidden = false;
62 }
Software/so101/src/ui/metrics-panel.test.ts added +29
@@ -0,0 +1,29 @@
1 import { describe, expect, test } from "bun:test";
2 import { esc, eventParts, peaksHtml, summaryHtml, summaryRows } from "./metrics-panel.js";
3
4 const counters = { jam: 1, block: 2, stall: 3, missing: 4, hot: 5, stream: 6, move: 7, play: 8, record: 9 };
5
6 describe("the Metrics panel's rendering", () => {
7 test("escapes everything it prints", () => {
8 expect(esc(`<img src=x onerror="a('b')">&`)).toBe("&lt;img src=x onerror=&quot;a(&#39;b&#39;)&quot;&gt;&amp;");
9 expect(summaryHtml([["<k>", "<script>"]])).toBe("<b>&lt;k&gt;</b><span>&lt;script&gt;</span>");
10 expect(peaksHtml({ 9: { load: 12.4, temperature: 40 } }, { 9: "<b>x</b>" })).toContain("<td>&lt;b&gt;x&lt;/b&gt;</td><td>12 %</td><td>40 °C</td>");
11 expect(peaksHtml({ 3: { load: 1, temperature: 30 } }, { 3: "elbow_flex" })).toContain("<td>elbow_flex</td>");
12 });
13
14 test("the summary reads the counters, the lag and the closest approach", () => {
15 const rows = Object.fromEntries(summaryRows({ since: "2026-10-20T22:00:00.000Z", counters, closest: { z: 0.0123, link: "wrist_link", at: "2026-10-20T22:01:02.000Z" } }, { p50: 5, p95: 9, n: 40 }));
16 expect(rows).toEqual({
17 since: "2026-10-20 22:00:00", jams: 1, "zone blocks": 2, "stalls on moves": 3, "lost servos": 4, "hot joints": 5,
18 sessions: "6 streams · 7 moves · 8 playbacks · 9 recordings", "teleop lag, this browser": "p50 5 ms · p95 9 ms over 40 samples", "closest to the table": "12 mm (wrist, 22:01:02)",
19 });
20 const bare = Object.fromEntries(summaryRows({ counters }, null));
21 expect(bare["teleop lag, this browser"]).toBe("—");
22 expect(bare["closest to the table"]).toBe("—");
23 });
24
25 test("an event is three pieces of text", () => {
26 expect(eventParts({ t: "2026-10-20T22:00:00.000Z", kind: "estop", detail: { by: "<ana>", stalled: [1, 2] } })).toEqual({ when: "10-20 22:00:00", kind: "estop", detail: "by=<ana> stalled=[1,2]" });
27 expect(eventParts({ t: "2026-10-20T22:00:00.000Z", kind: "play" }).detail).toBe("");
28 });
29 });
Software/so101/src/viewer.html +3 −16
@@ -1527,23 +1527,10 @@
15271527 $("baseMargin").onchange = () => saveSettings({ baseMarginMm: Number($("baseMargin").value) });
15281528
15291529 // ---------------------------------------------------------------- metrics
1530 // src/ui/metrics-panel.js, fetched the first time the panel opens.
15301531 async function showMetrics() {

Await the module call so the catch covers fetch failures too, not just the import.

1531 const m = await api("/metrics");
1532 const c = m.counters;
1533 $("metricsSummary").innerHTML = [
1534 ["since", (m.since ?? "").replace("T", " ").slice(0, 19)],
1535 ["jams", c.jam], ["zone blocks", c.block], ["stalls on moves", c.stall], ["lost servos", c.missing], ["hot joints", c.hot],
1536 ["sessions", `${c.stream} streams · ${c.move} moves · ${c.play} playbacks · ${c.record} recordings`],
1537 ["teleop lag, this browser", (() => { const lag = teleop?.lag(); return lag ? `p50 ${lag.p50} ms · p95 ${lag.p95} ms over ${lag.n} samples` : "—"; })()],
1538 ["closest to the table", m.closest ? `${(m.closest.z * 1000).toFixed(0)} mm (${m.closest.link.replace(/_link$/, "")}, ${m.closest.at.slice(11, 19)})` : "—"],
1539 ].map(([k, v]) => `<b>${k}</b><span>${v}</span>`).join("");
1540 $("peaks").innerHTML = "<tr><th>joint</th><th>peak load</th><th>peak temperature</th></tr>" + Object.entries(m.peaks).map(([id, p]) => `<tr><td>${NAMES[id] ?? id}</td><td>${p.load.toFixed(0)} %</td><td>${p.temperature} °C</td></tr>`).join("");
1541 // Built from text nodes: an event's detail carries people's names (who pressed the E-stop) and error strings.
1542 const recent = [...(m.recent ?? [])].reverse();
1543 $("events").replaceChildren(...(recent.length ? recent.map((e) => el("div", {},
1544 `${String(e.t).slice(5, 19).replace("T", " ")} `, el("b", { textContent: String(e.kind) }),
1545 ` ${Object.entries(e.detail ?? {}).map(([k, v]) => `${k}=${typeof v === "object" ? JSON.stringify(v) : v}`).join(" ")}`)) : [el("div", { textContent: "none yet" })]));
1546 $("metricsPanel").hidden = false;
1532 try { (await import("/ui/__VERSION__/metrics-panel.js")).showMetrics({ api, lag: () => teleop?.lag(), names: NAMES }); }
1533 catch (err) { console.error(err); msg("the Metrics panel did not load", true); }
15471534 }
15481535 $("metricsBtn").onclick = showMetrics;
15491536 setInterval(() => { if (!$("metricsPanel").hidden) showMetrics(); }, 5000);
forge.json +1 −7
@@ -14,11 +14,5 @@
1414 "100.89.95.68:8080",
1515 "100.89.95.68:8081",
1616 "100.89.95.68:8101"
17 ],
18 "check": {
19 "limits": {
20 "cpus": 6,
21 "memory": 6144
22 }
23 }
17 ]
2418 }

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs