Files
the_kurgan/kurgan/web/static/app.js
T
paul ba39016d52 Sensor health in the API and UI; balloon tips when something starts going wrong
- telemetry: _source() now remembers each failing source's error message, not
  just the log timestamp; health() reports them and every snapshot carries a
  "health" key, so /api/state shows which sensor source is failing and since
  when. A source that reads again clears its entry.
- Web UI: a header pill counts the failing sources; hovering lists the errors.
- tray: notify() shows a balloon tip from any thread (queued on the tray
  window, NIF_INFO). app.py grows an alert monitor: every 5 s it diffs the
  current bad states (fan failsafes/control errors, AI backend errors, failing
  sensor sources) against the last look and balloons only what is new. The
  first look is the baseline: problems that predate the tray icon stay quiet.
- Tests: test_telemetry.py (5) and test_alerts.py (7); README updated.
2026-12-05 17:51:00 +13:00

810 lines
39 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* The Kurgan - control UI. Polls /api/state once a second while the page is visible. */
"use strict";
const SVGNS = "http://www.w3.org/2000/svg";
const WINDOW_S = 600;
const $ = (id) => document.getElementById(id);
/* Elements are built with textContent only: names and messages come from devices and servers. */
function el(tag, attrs = {}, ...children) {
const node = document.createElement(tag);
for (const [k, v] of Object.entries(attrs)) {
if (v == null || v === false) continue;
if (k === "class") node.className = v;
else if (k === "style") node.style.cssText = v;
else if (k.startsWith("on")) node.addEventListener(k.slice(2), v);
else if (k === "text") node.textContent = v;
else node.setAttribute(k, v === true ? "" : v);
}
for (const child of children.flat()) {
if (child == null || child === false) continue;
node.append(child instanceof Node ? child : document.createTextNode(String(child)));
}
return node;
}
function svg(tag, attrs = {}) {
const node = document.createElementNS(SVGNS, tag);
for (const [k, v] of Object.entries(attrs)) if (v != null) node.setAttribute(k, v);
return node;
}
function setText(id, text) {
const node = typeof id === "string" ? $(id) : id;
if (node && node.textContent !== text) node.textContent = text;
}
const fmt = {
n0: (v) => (v == null ? "--" : Math.round(v).toLocaleString()),
n1: (v) => (v == null ? "--" : (Math.round(v * 10) / 10).toLocaleString(undefined, { minimumFractionDigits: 1 })),
gib: (bytes) => (bytes == null ? "--" : (bytes / 2 ** 30).toFixed(1)),
dur(s) {
if (s == null) return "--";
s = Math.round(s);
if (s < 60) return `${s} s`;
if (s < 3600) return `${Math.floor(s / 60)} min ${s % 60} s`;
const h = Math.floor(s / 3600), m = Math.floor((s % 3600) / 60);
return h >= 24 ? `${Math.floor(h / 24)} d ${h % 24} h` : `${h} h ${m} min`;
},
clock: (t) => new Date(t * 1000).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" }),
};
const ICON = {
warning: "M8 1.5 15 14H1L8 1.5Zm0 4.2v4m0 2.2v.1",
critical: "M8 1a7 7 0 1 0 0 14A7 7 0 0 0 8 1Zm0 3.8v4.4m0 2.2v.1",
info: "M8 1a7 7 0 1 0 0 14A7 7 0 0 0 8 1Zm0 6v4.5m0-6.7v.1",
};
function note(kind, text) {
const icon = svg("svg", { viewBox: "0 0 16 16", "aria-hidden": "true" });
icon.append(svg("path", { d: ICON[kind], fill: "none", stroke: "currentColor", "stroke-width": "1.6",
"stroke-linecap": "round", "stroke-linejoin": "round" }));
const label = { warning: "Warning", critical: "Problem", info: "Note" }[kind];
return el("div", { class: `note ${kind}` }, icon, el("span", {}, el("b", { text: `${label}: ` }), text));
}
/* ------------------------------------------------------------------ API */
async function api(path, body) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), body ? 15000 : 4000);
try {
const response = await fetch(path, body === undefined ? { signal: controller.signal } : {
method: "POST", signal: controller.signal,
headers: { "Content-Type": "application/json", "X-Kurgan": "1" }, body: JSON.stringify(body),
});
const data = await response.json().catch(() => ({}));
if (!response.ok) throw new Error(data.error || `HTTP ${response.status}`);
return data;
} finally {
clearTimeout(timer);
}
}
let bannerTimer = null;
function banner(kind, text, sticky = false) {
const node = $("banner");
clearTimeout(bannerTimer);
if (!text) { node.hidden = true; node.dataset.kind = ""; return; }
node.replaceChildren(note(kind, text));
node.dataset.kind = kind;
node.hidden = false;
if (!sticky) bannerTimer = setTimeout(() => { node.hidden = true; }, 9000);
}
/* Send a change; the group is disabled until the answer arrives, then the new state is drawn. */
async function change(group, path, body) {
group?.classList.add("busy");
try {
const state = await api(path, body);
render(state);
} catch (error) {
banner("critical", error.message);
if (lastState) render(lastState);
} finally {
group?.classList.remove("busy");
}
}
/* ------------------------------------------------------------------ tooltip */
const tip = {
node: null,
show(x, y, title, rows) {
this.node ??= $("tooltip");
const items = rows.map((r) => el("div", { class: "tip-row" },
el("span", { class: "key line", style: `background:${r.color}` }), el("b", { text: r.value }), el("span", { text: r.label })));
this.node.replaceChildren(el("div", { class: "when", text: title }), ...items);
this.node.hidden = false;
const w = this.node.offsetWidth, h = this.node.offsetHeight;
const left = x + 16 + w > innerWidth ? x - 16 - w : x + 16;
this.node.style.left = `${Math.max(4, left)}px`;
this.node.style.top = `${Math.min(innerHeight - h - 4, Math.max(4, y - h / 2))}px`;
},
hide() { if (this.node) this.node.hidden = true; },
};
/* ------------------------------------------------------------------ charts */
function niceMax(v) {
if (!(v > 0)) return 1;
const p = 10 ** Math.floor(Math.log10(v)), m = v / p;
return (m <= 1 ? 1 : m <= 2 ? 2 : m <= 2.5 ? 2.5 : m <= 5 ? 5 : 10) * p;
}
/**
* One chart: lines (or a stacked area) over time or over a numeric x, a crosshair tooltip,
* selective end labels, an optional legend (2+ series) and a table view.
*/
class Chart {
constructor(fig, opts) {
this.o = { height: 210, unit: "", digits: 0, stacked: false, x: { type: "time" }, refs: [], ...opts };
this.fig = fig;
this.xs = [];
this.cols = {};
this.markers = [];
const legend = this.o.series.length > 1 ? el("div", { class: "legend" },
this.o.series.map((s) => el("span", {}, el("span", { class: this.o.stacked ? "key" : "key line",
style: `background:var(${s.color})` }), s.label))) : null;
this.toggle = el("button", { class: "btn table-toggle", type: "button", "aria-expanded": "false",
onclick: () => this.toggleTable() }, "Table");
this.titleNode = el("h3", { text: this.o.title });
this.subNode = el("div", { class: "sub", style: "margin:2px 0 0", text: this.o.subtitle || "" });
this.plot = el("div", { class: "plot" });
this.svg = svg("svg", { role: "img", "aria-label": this.o.title });
this.plot.append(this.svg);
this.tableNode = el("div", { class: "chart-table", hidden: true });
fig.replaceChildren(el("div", { class: "chart-head" }, el("div", {}, this.titleNode, this.subNode, legend), this.toggle),
this.plot, this.tableNode);
this.svg.addEventListener("pointermove", (e) => this.hover(e));
this.svg.addEventListener("pointerleave", () => this.unhover());
new ResizeObserver(() => this.draw()).observe(this.plot);
}
setTitle(title, subtitle) {
setText(this.titleNode, title);
setText(this.subNode, subtitle || "");
this.svg.setAttribute("aria-label", title);
}
setData(xs, cols, markers = []) {
this.xs = xs;
this.cols = cols;
this.markers = markers;
this.draw();
if (!this.tableNode.hidden) this.renderTable();
}
value(key, i) { const v = this.cols[key]?.[i]; return v == null || Number.isNaN(v) ? null : v; }
/* Stacked: each layer's top edge; plain: the value. */
levels() {
const n = this.xs.length, out = {};
let base = new Array(n).fill(0);
for (const s of this.o.series) {
const top = new Array(n);
for (let i = 0; i < n; i++) {
const v = this.value(s.key, i);
top[i] = v == null ? null : (this.o.stacked ? base[i] + v : v);
}
out[s.key] = { base, top };
if (this.o.stacked) base = top.map((v, i) => (v == null ? base[i] : v));
}
return out;
}
draw() {
const width = this.plot.clientWidth;
if (!width) return;
const H = this.o.height, m = { l: 44, r: 64, t: 10, b: 24 };
const w = width - m.l - m.r, h = H - m.t - m.b;
this.svg.setAttribute("viewBox", `0 0 ${width} ${H}`);
this.svg.replaceChildren();
const xo = this.o.x;
let x0, x1;
if (xo.type === "time") {
x1 = this.xs.length ? this.xs[this.xs.length - 1] : Date.now() / 1000;
x0 = x1 - WINDOW_S;
} else {
[x0, x1] = [xo.min, xo.max];
}
const levels = this.levels();
let dataMax = 0;
for (const s of this.o.series) for (const v of levels[s.key].top) if (v != null && v > dataMax) dataMax = v;
const yMax = typeof this.o.yMax === "function" ? this.o.yMax(dataMax) : (this.o.yMax ?? niceMax(dataMax * 1.1));
const X = (x) => m.l + ((x - x0) / (x1 - x0)) * w;
const Y = (y) => m.t + h - (Math.max(0, Math.min(yMax, y)) / yMax) * h;
this.geom = { X, Y, m, w, h, x0, x1, yMax, width, levels };
// grid + y ticks
const grid = svg("g", { class: "grid" });
// 4 steps unless that gives a ragged step (25 GiB / 4 = 6.25); then 5.
const ticks = Number.isInteger((yMax / 4) * 10) ? 4 : 5;
for (let i = 0; i <= ticks; i++) {
const v = (yMax / ticks) * i, y = Y(v);
if (i > 0) grid.append(svg("line", { x1: m.l, x2: m.l + w, y1: y, y2: y }));
const t = svg("text", { x: m.l - 8, y: y + 4, "text-anchor": "end", class: "tick" });
t.textContent = `${Number.isInteger(v) ? v.toLocaleString() : v.toFixed(1)}${this.o.unit}`;
this.svg.append(t);
}
this.svg.append(grid);
this.svg.append(svg("line", { class: "baseline", x1: m.l, x2: m.l + w, y1: Y(0), y2: Y(0) }));
// x ticks
const xticks = xo.type === "time" ? [0, 120, 240, 360, 480, 600].map((s) => x1 - WINDOW_S + s) : xo.ticks;
for (const xv of xticks) {
const t = svg("text", { x: X(xv), y: H - 6, "text-anchor": "middle", class: "tick" });
t.textContent = xo.type === "time" ? (x1 - xv < 1 ? "now" : `−${Math.round((x1 - xv) / 60)} min`) : xo.fmt(xv);
this.svg.append(t);
}
// reference lines (e.g. the warn/hot temperatures)
for (const r of this.o.refs) {
if (r.value > yMax) continue;
this.svg.append(svg("line", { class: "ref", x1: m.l, x2: m.l + w, y1: Y(r.value), y2: Y(r.value) }));
const t = svg("text", { x: m.l + 6, y: Y(r.value) - 5, class: "ref-label" });
t.textContent = r.label;
this.svg.append(t);
}
// series
const ends = [];
for (const s of this.o.series) {
const { base, top } = levels[s.key];
const segs = [];
let cur = [];
for (let i = 0; i < this.xs.length; i++) {
if (top[i] == null || this.xs[i] < x0) { if (cur.length) segs.push(cur); cur = []; continue; }
cur.push(i);
}
if (cur.length) segs.push(cur);
for (const seg of segs) {
const line = seg.map((i, k) => `${k ? "L" : "M"}${X(this.xs[i]).toFixed(1)},${Y(top[i]).toFixed(1)}`).join("");
if (this.o.stacked || this.o.area) {
const back = seg.slice().reverse().map((i) => `L${X(this.xs[i]).toFixed(1)},${Y(this.o.stacked ? base[i] : 0).toFixed(1)}`).join("");
this.svg.append(svg("path", { d: line + back + "Z", class: "series-area", fill: `var(${s.color})` }));
}
this.svg.append(svg("path", { d: line, class: "series-line", stroke: `var(${s.color})` }));
}
const last = this.lastIndex(s.key);
if (last != null && !this.o.noEndLabels) ends.push({ s, i: last, y: Y(top[last]) });
}
// operating points (fan curves): a dot with a surface ring
for (const mk of this.markers) {
if (mk.x == null || mk.y == null) continue;
this.svg.append(svg("circle", { cx: X(Math.max(x0, Math.min(x1, mk.x))), cy: Y(mk.y), r: 5, class: "marker", fill: `var(${mk.color})` }));
}
// end labels: only where they don't collide (the legend and tooltip carry the rest)
ends.sort((a, b) => a.y - b.y);
let lastY = -Infinity;
const placed = [];
for (const e of ends) {
if (e.y - lastY < 14) { placed.pop(); lastY = e.y; continue; }
placed.push(e);
lastY = e.y;
}
for (const e of placed) {
const v = this.o.stacked ? this.value(e.s.key, e.i) : levels[e.s.key].top[e.i];
const t = svg("text", { x: m.l + w + 6, y: e.y + 4, class: "end-label" });
t.textContent = `${v.toFixed(this.o.digits)}${this.o.unit}`;
this.svg.append(t);
}
this.cross = svg("line", { class: "cross", y1: m.t, y2: m.t + h, visibility: "hidden" });
this.svg.append(this.cross);
}
lastIndex(key) {
for (let i = this.xs.length - 1; i >= 0; i--) if (this.value(key, i) != null) return i;
return null;
}
hover(e) {
const g = this.geom;
if (!g || !this.xs.length) return;
const rect = this.svg.getBoundingClientRect();
const px = ((e.clientX - rect.left) / rect.width) * g.width;
const xv = g.x0 + ((px - g.m.l) / g.w) * (g.x1 - g.x0);
let best = null, bestD = Infinity;
for (let i = 0; i < this.xs.length; i++) {
const d = Math.abs(this.xs[i] - xv);
if (d < bestD && this.xs[i] >= g.x0) { best = i; bestD = d; }
}
if (best == null) return this.unhover();
const cx = g.X(this.xs[best]);
this.cross.setAttribute("x1", cx);
this.cross.setAttribute("x2", cx);
this.cross.setAttribute("visibility", "visible");
const title = this.o.x.type === "time" ? fmt.clock(this.xs[best]) : this.o.x.fmt(this.xs[best]);
const rows = this.o.series.slice().reverse().map((s) => {
const v = this.value(s.key, best);
return { color: `var(${s.color})`, label: s.label, value: v == null ? "--" : `${v.toFixed(this.o.digits)}${this.o.unit}` };
});
if (this.o.stacked && this.o.totalLabel) {
const total = this.o.series.reduce((a, s) => a + (this.value(s.key, best) ?? 0), 0);
rows.unshift({ color: "transparent", label: this.o.totalLabel, value: `${total.toFixed(this.o.digits)}${this.o.unit}` });
}
tip.show(e.clientX, e.clientY, title, rows);
}
unhover() {
this.cross?.setAttribute("visibility", "hidden");
tip.hide();
}
toggleTable() {
const open = this.tableNode.hidden;
this.tableNode.hidden = !open;
this.toggle.setAttribute("aria-expanded", String(open));
this.toggle.textContent = open ? "Hide table" : "Table";
if (open) this.renderTable();
}
renderTable() {
const time = this.o.x.type === "time";
const head = el("tr", {}, el("th", { text: time ? "Time" : this.o.x.label }),
this.o.series.map((s) => el("th", { class: "r", text: s.label })));
const rows = [];
let lastT = Infinity;
const order = time ? [...this.xs.keys()].reverse() : [...this.xs.keys()];
for (const i of order) {
if (time && lastT - this.xs[i] < 29.5) continue; // one row per 30 s
lastT = this.xs[i];
if (!time && this.xs[i] % 5 !== 0) continue;
rows.push(el("tr", {}, el("td", { class: "num", text: time ? fmt.clock(this.xs[i]) : this.o.x.fmt(this.xs[i]) }),
this.o.series.map((s) => { const v = this.value(s.key, i); return el("td", { class: "r", text: v == null ? "--" : `${v.toFixed(this.o.digits)}${this.o.unit}` }); })));
}
this.tableNode.replaceChildren(el("table", {}, el("caption", { class: "muted", style: "text-align:left;caption-side:top;padding:0 0 6px",
text: time ? "Every 30 seconds, newest first" : "" }), el("thead", {}, head), el("tbody", {}, rows)));
}
stale(on) { this.plot.classList.toggle("stale", on); }
}
/* ------------------------------------------------------------------ history */
class Series {
constructor(names) { this.names = names; this.t = []; this.cols = Object.fromEntries(names.slice(1).map((n) => [n, []])); }
load(rows) { this.t = []; for (const k in this.cols) this.cols[k] = []; for (const r of rows) this.push(r); }
push(row) {
if (!row || (this.t.length && row[0] <= this.t[this.t.length - 1])) return false;
this.t.push(row[0]);
this.names.slice(1).forEach((n, i) => this.cols[n].push(row[i + 1]));
const cutoff = row[0] - WINDOW_S - 2;
let drop = 0;
while (drop < this.t.length && this.t[drop] < cutoff) drop++;
if (drop) { this.t.splice(0, drop); for (const k in this.cols) this.cols[k].splice(0, drop); }
return true;
}
}
/* ------------------------------------------------------------------ app state */
let config = null;
let lastState = null;
let telemetry = null, fanHistory = null;
let charts = {};
let built = { profiles: false, groups: "", zones: false, backends: "" };
let strataVariant = null;
let profileShown = null;
function buildCharts() {
const temps = config.theme;
charts.power = new Chart($("chart-power"), {
title: "Power", subtitle: `Whole PC, last 10 minutes (DC watts; ${fmt.n0(temps.psu_watts)} W supply)`,
stacked: true, unit: " W", totalLabel: "Total",
series: [{ key: "other_w", label: "Other", color: "--other" }, { key: "cpu_w", label: "CPU", color: "--cpu" },
{ key: "gpu_w", label: "GPU", color: "--gpu" }],
});
charts.temps = new Chart($("chart-temps"), {
title: "Temperatures", subtitle: "Last 10 minutes", unit: "°", yMax: (m) => Math.max(100, niceMax(m)),
series: [{ key: "cpu_temp", label: "CPU", color: "--cpu" }, { key: "gpu_temp", label: "GPU", color: "--gpu" }],
refs: [{ value: temps.temp_warn, label: `warm ${temps.temp_warn}°` }, { value: temps.temp_hot, label: `hot ${temps.temp_hot}°` }],
});
charts.fans = new Chart($("chart-fans"), {
title: "Fan speeds", subtitle: "PWM duty, last 10 minutes", unit: "%", yMax: 100,
series: [{ key: "cpu_duty", label: "CPU side", color: "--cpu" }, { key: "gpu_duty", label: "GPU side", color: "--gpu" },
{ key: "top_duty", label: "Top", color: "--top" }],
});
charts.curves = new Chart($("chart-curves"), {
title: "Profile curves", unit: "%", yMax: 100, noEndLabels: true,
x: { type: "linear", min: 20, max: 100, ticks: [20, 30, 40, 50, 60, 70, 80, 90, 100], fmt: (v) => `${v} °C`, label: "Temperature" },
series: [{ key: "cpu", label: "CPU side", color: "--cpu" }, { key: "gpu", label: "GPU side", color: "--gpu" },
{ key: "top", label: "Top", color: "--top" }],
});
charts.vram = new Chart($("chart-vram"), {
title: "GPU memory used", subtitle: "Last 10 minutes", unit: " GiB", digits: 1, area: true,
series: [{ key: "vram", label: "GPU memory", color: "--gpu" }],
yMax: () => niceMax((lastState?.telemetry?.gpu?.vram_total ?? 24 * 2 ** 30) / 2 ** 30),
});
}
function curveDuty(curve, t) {
if (t <= curve[0][0]) return curve[0][1];
for (let i = 1; i < curve.length; i++) {
const [t0, d0] = curve[i - 1], [t1, d1] = curve[i];
if (t <= t1) return Math.ceil(d0 + (t - t0) * (d1 - d0) / (t1 - t0));
}
return 100;
}
function drawCurves(state) {
const p = config.profiles.find((x) => x.key === (profileShown ?? state.cooling.profile)) ?? config.profiles[0];
const xs = [], cols = { cpu: [], gpu: [], top: [] };
for (let t = 20; t <= 100; t++) {
xs.push(t);
cols.cpu.push(curveDuty(p.cpu_curve, t));
cols.gpu.push(curveDuty(p.gpu_curve, t));
cols.top.push(t < p.top_start ? 0 : curveDuty(p.top_curve, t));
}
const markers = [];
for (const g of state.cooling.groups) markers.push({ x: g.temp, y: g.duty, color: g.name === "GPU" ? "--gpu" : "--cpu" });
if (state.cooling.top) markers.push({ x: state.cooling.top.temp, y: state.cooling.top.duty, color: "--top" });
charts.curves.setTitle(`${p.name} profile curves`,
`Dots: each group now. Top fans start at ${p.top_start} °C and stop below ${p.top_stop} °C.`);
charts.curves.setData(xs, cols, state.cooling.groups.length || state.cooling.top ? markers : []);
}
/* ------------------------------------------------------------------ render: header & system */
function renderHeader(s) {
const power = s.telemetry.power;
setText("hero-total", (power?.partial ? "≈" : "") + fmt.n0(power?.total));
const meta = $("meta");
const elevated = s.app.token?.elevated;
const health = Object.entries(s.telemetry.health ?? {});
meta.replaceChildren(
el("span", { class: "pill" }, el("span", { class: "dot good" }), "Live"),
el("span", { text: `Up ${fmt.dur(s.app.uptime)}` }),
el("span", { class: "pill", title: "PawnIO sensors, top fans and RAM lighting need admin rights" },
el("span", { class: `dot ${elevated ? "good" : "warning"}` }), elevated ? "Admin rights" : "No admin rights"),
...(health.length
? [el("span", { class: "pill", title: health.map(([name, h]) => `${name}: ${h.error}`).join("\n") },
el("span", { class: "dot warning" }),
`${health.length} sensor source${health.length > 1 ? "s are" : " is"} failing`)]
: []),
);
setText("footer", `${s.app.name} ${s.app.version} · pid ${s.app.pid} · log: %LOCALAPPDATA%\\Kurgan\\kurgan.log · JSON: /api/state`);
}
function renderSystem(s) {
const t = s.telemetry;
if (!t.cpu) return;
setText("cpu-temp", fmt.n0(t.cpu.temp));
setText("cpu-detail", `${fmt.n0(t.cpu.load)}% load · ${fmt.n0(t.cpu.clock)} MHz · ${fmt.n0(t.cpu.power)} W`);
setText("gpu-temp", fmt.n0(t.gpu.temp));
setText("gpu-detail", `${fmt.n0(t.gpu.load)}% load · ${fmt.n0(t.gpu.clock)} MHz · ${fmt.n0(t.gpu.power)} W`);
setText("vram-used", fmt.gib(t.gpu.vram_used));
setText("vram-total", t.gpu.vram_total ? ` / ${fmt.gib(t.gpu.vram_total)} GiB` : "");
const share = t.gpu.vram_total ? (100 * t.gpu.vram_used) / t.gpu.vram_total : 0;
$("vram-meter").firstChild.style.width = `${share.toFixed(1)}%`;
$("vram-meter").setAttribute("aria-valuenow", share.toFixed(0));
$("vram-meter").className = `meter ${share > 92 ? "warning" : "gpu"}`;
setText("lcd-status", s.display.status);
setText("lcd-detail", s.display.frames != null ? `${fmt.n0(s.display.frames)} frames sent` : "");
}
/* ------------------------------------------------------------------ render: cooling */
function buildProfiles() {
const group = $("profiles");
group.replaceChildren(...config.profiles.map((p) => el("label", {},
el("input", { type: "radio", name: "profile", value: p.key,
onchange: () => { profileShown = p.key; change(group, "/api/cooling/profile", { profile: p.key }); } }),
el("span", { text: p.name }))));
group.addEventListener("mouseover", (e) => {
const key = e.target.closest("label")?.querySelector("input")?.value;
if (key && key !== profileShown) { profileShown = key; drawCurves(lastState); describeProfile(); }
});
group.addEventListener("mouseleave", () => { profileShown = null; drawCurves(lastState); describeProfile(); });
built.profiles = true;
}
function describeProfile() {
const key = profileShown ?? lastState.cooling.profile;
const p = config.profiles.find((x) => x.key === key);
setText("profile-desc", p ? (key === lastState.cooling.profile ? p.description : `Preview: ${p.description}`) : "");
}
function fanCard(g, kind) {
const ports = Object.entries(g.rpms ?? {});
return el("div", { class: "card", "data-group": kind },
el("div", { class: "tile" }, el("div", { class: "label" }, el("span", { class: "key", style: `background:var(--${kind})` }),
kind === "top" ? `Top fans · channels ${g.channels.join(", ")}` : `${g.name}-side case fans · ports ${g.ports.join(", ")}`)),
el("div", { class: "fan-head", style: "margin-top:4px" }, el("span", { class: "fan-duty", "data-f": "duty" }),
el("span", { class: "muted", "data-f": "temp" })),
el("div", { class: `meter ${kind}`, role: "meter", "aria-label": "PWM duty", "data-f": "meter" }, el("span")),
el("div", { class: "fan-ports", "data-f": "ports" }, ports.map(([p]) => el("span", {}, `Port ${p} `, el("b", { "data-port": p }), " rpm"))),
el("div", { "data-f": "note" }));
}
function updateFanCard(card, g, kind) {
const q = (f) => card.querySelector(`[data-f="${f}"]`);
setText(q("duty"), `${g.duty}%`);
const temp = g.temp == null ? "temperature unavailable" : `at ${fmt.n0(g.temp)} °C ${kind === "top" ? "(hotter of CPU/GPU)" : g.name}`;
setText(q("temp"), kind === "top" && !g.running ? `stopped · ${fmt.n0(g.temp)} °C` : temp);
const meter = q("meter");
meter.firstChild.style.width = `${g.duty}%`;
meter.setAttribute("aria-valuenow", g.duty);
meter.className = `meter ${g.failsafe ? "critical" : kind}`;
for (const [p, rpm] of Object.entries(g.rpms ?? {})) setText(card.querySelector(`[data-port="${p}"]`), fmt.n0(rpm));
const n = q("note");
const text = g.failsafe ? g.status : kind === "top" && g.boosted ? "Held at 100% while a case-fan group runs at 85% or more." : "";
if (n.dataset.text !== text) {
n.dataset.text = text;
n.replaceChildren(...(text ? [note(g.failsafe ? "critical" : "info", text)] : []));
}
}
function renderCooling(s) {
const c = s.cooling;
if (!built.profiles) buildProfiles();
if (!$("profiles").classList.contains("busy")) {
for (const input of $("profiles").querySelectorAll("input")) input.checked = input.value === c.profile;
}
describeProfile();
const noteNode = $("cooling-note");
if ((noteNode.dataset.text ?? "") !== (c.note ?? "")) {
noteNode.dataset.text = c.note ?? "";
noteNode.replaceChildren(...(c.note ? [note("warning", c.note)] : []));
}
const kinds = c.groups.map((g) => [g, g.name === "GPU" ? "gpu" : "cpu"]);
if (c.top) kinds.push([c.top, "top"]);
const signature = kinds.map(([g, k]) => k + (g.ports ?? g.channels).join()).join("|");
if (built.groups !== signature) {
$("fan-groups").replaceChildren(...kinds.map(([g, k]) => fanCard(g, k)));
built.groups = signature;
}
for (const [g, k] of kinds) updateFanCard($("fan-groups").querySelector(`[data-group="${k}"]`), g, k);
if (fanHistory.push(c.row)) charts.fans.setData(fanHistory.t, fanHistory.cols);
$("chart-fans").hidden = !c.groups.length;
drawCurves(s);
}
/* ------------------------------------------------------------------ render: lighting */
function buildZones(lighting) {
$("light-zones").replaceChildren(...lighting.zones.map((z) => {
const group = el("div", { class: "seg", role: "radiogroup", "aria-label": z.label });
group.append(...z.modes.map((m) => el("label", {},
el("input", { type: "radio", name: `zone-${z.key}`, value: m.key,
onchange: () => change(group, "/api/lighting", { zone: z.key, mode: m.key }) }),
el("span", { text: m.label }))));
return el("div", { class: "card zone", "data-zone": z.key }, el("h3", { text: z.label, style: "margin-bottom:10px" }),
group, el("div", { class: "status" }), el("div", { "data-f": "note" }));
}));
built.zones = true;
}
function renderLighting(s) {
if (!built.zones) buildZones(s.lighting);
for (const z of s.lighting.zones) {
const card = $("light-zones").querySelector(`[data-zone="${z.key}"]`);
const group = card.querySelector(".seg");
if (!group.classList.contains("busy")) for (const i of group.querySelectorAll("input")) i.checked = i.value === z.mode;
const bad = /unavailable|busy|error|stopped/i.test(z.status);
setText(card.querySelector(".status"), bad ? "" : (z.status === "off" ? "Off" : z.status));
const n = card.querySelector('[data-f="note"]');
const text = (bad ? z.status : "") + (z.this_run_only ? (bad ? " " : "") + "Set by a command-line option for this run; choosing here saves it." : "");
if (n.dataset.text !== text) {
n.dataset.text = text;
n.replaceChildren(...(text ? [note(bad ? "warning" : "info", text)] : []));
}
}
setText("chase-note", s.lighting.chase_ms_per_led
? `The chases share one clock: ${s.lighting.chase_ms_per_led} ms per LED now, faster as total power rises.` : "");
}
/* ------------------------------------------------------------------ render: AI */
const MODEL_STATE = {
offline: ["Not answering", ""], unloaded: ["Model unloaded · loads on the first request", ""],
sleeping: ["Model asleep · loads on the first request", ""], loading: ["Loading model", "warning"],
idle: ["Model loaded · idle", "good"], reading: ["Reading the prompt", "good"], generating: ["Generating", "good"],
failed: ["Model failed to load", "critical"],
};
const PROCESS = { running: "Running", starting: "Starting", stopping: "Stopping", external: "Running outside The Kurgan", stopped: "Stopped" };
function busyBackend(ai) {
return ai.backends.find((b) => b.key === ai.active && b.live);
}
function chooseBackend(key, variant) {
const ai = lastState.ai, busy = busyBackend(ai);
if (busy && (key !== busy.key || (variant && variant !== busy.variant)) &&
!confirm(`${busy.label} is answering a request right now. Switching stops it. Switch anyway?`)) {
render(lastState);
return;
}
change($("backends"), "/api/ai/active", variant ? { backend: key, variant } : { backend: key });
}
function buildBackends(ai) {
const cards = ai.backends.map((b) => {
const select = b.variants.length ? el("select", { "aria-label": `${b.label} model`,
onchange: (e) => { strataVariant = e.target.value; if (ai.active === b.key || lastState.ai.active === b.key) chooseBackend(b.key, strataVariant); } },
b.variants.map((v) => el("option", { value: v.key, text: v.label }))) : null;
return el("label", { class: "choice", "data-key": b.key },
el("input", { type: "radio", name: "backend", value: b.key,
onchange: () => chooseBackend(b.key, b.variants.length ? (strataVariant ?? b.variant) : null) }),
el("div", { class: "name" }, b.label, el("span", { class: "check" })),
el("div", { class: "what", "data-f": "what" }), select,
el("div", { class: "state", "data-f": "state" }));
});
cards.push(el("label", { class: "choice", "data-key": "" },
el("input", { type: "radio", name: "backend", value: "", onchange: () => chooseBackend(null) }),
el("div", { class: "name" }, "None", el("span", { class: "check" })),
el("div", { class: "what", text: "Nothing running; the GPU's memory is free. The next request to either address starts its server." }),
el("div", { class: "state", "data-f": "state" })));
$("backends").replaceChildren(...cards);
built.backends = ai.backends.map((b) => b.key).join();
}
function stateLine(b) {
const [text, kind] = b.process === "running" || b.process === "external" ? MODEL_STATE[b.model.state] ?? [b.model.state, ""]
: [PROCESS[b.process], b.process === "starting" || b.process === "stopping" ? "warning" : ""];
const pill = el("span", { class: "pill" }, el("span", { class: `dot ${kind}` }), text);
if (b.process !== "external") return pill;
return el("span", { class: "pills" }, el("span", { class: "pill" }, el("span", { class: "dot warning" }), "Outside The Kurgan"), pill);
}
function renderAI(s) {
const ai = s.ai;
if (!ai) { $("ai").hidden = true; return; }
if (built.backends !== ai.backends.map((b) => b.key).join()) buildBackends(ai);
const group = $("backends");
group.classList.toggle("busy", !!ai.transition);
for (const b of ai.backends) {
const card = group.querySelector(`[data-key="${b.key}"]`);
setText(card.querySelector('[data-f="what"]'), `${b.model_label} · ${b.route}v1`);
const select = card.querySelector("select");
if (select && document.activeElement !== select) select.value = ai.active === b.key ? b.variant : (strataVariant ?? b.variant);
card.querySelector('[data-f="state"]').replaceChildren(stateLine(b));
}
const noneState = group.querySelector('[data-key=""] [data-f="state"]');
const serving = ai.backends.some((b) => b.process !== "stopped");
noneState.replaceChildren(...(ai.active == null && !serving
? [el("span", { class: "pill" }, el("span", { class: "dot good" }), "GPU memory free")] : []));
if (!group.classList.contains("pending")) {
for (const input of group.querySelectorAll('input[type="radio"]')) input.checked = input.value === (ai.active ?? "");
}
const m = ai.idle_stop_minutes;
setText("ai-idle", m ? `A server nobody uses for ${m} minutes stops and frees the GPU's memory; the next request starts it again.`
: "Servers keep running when nobody uses them (ai.idle_stop_minutes is 0).");
const notes = [];
if (ai.transition) notes.push(note("info", `${ai.transition}…`));
if (ai.warning) notes.push(note("warning", ai.warning));
if (ai.message) notes.push(note("critical", ai.message));
$("ai-notes").replaceChildren(...notes);
renderActive(ai);
const vram = telemetry.cols.vram_used.map((v) => (v == null ? null : v / 2 ** 30));
charts.vram.setData(telemetry.t, { vram });
}
function renderActive(ai) {
const box = $("ai-active");
const b = ai.backends.find((x) => x.key === ai.active);
if (!b) {
const kv = el("dl", { class: "kv" }, ai.backends.flatMap((x) => [
el("dt", { text: x.label }), el("dd", {}, el("code", { text: x.links.api }))]));
box.replaceChildren(el("h3", { text: "No LLM server running" }),
el("p", { class: "sub", text: "A request to either address starts its server, or pick one above. The Kurgan remembers a choice made here and starts it at every logon." }),
kv);
renderRequests(null);
return;
}
const running = b.process === "running" || b.process === "external";
const st = b.model.state;
const adminLevel = b.token && ["high", "system"].includes(b.token.integrity);
const token = !b.token ? null : adminLevel ? `admin rights, ${b.token.integrity} integrity (unexpected)`
: `${b.token.elevated ? "restricted token" : "normal user"}, ${b.token.integrity} integrity`;
const kv = el("dl", { class: "kv" },
el("dt", { text: "Model" }), el("dd", { text: b.model.id ?? b.model_label }),
b.model.context ? [el("dt", { text: "Context" }), el("dd", { text: `${fmt.n0(b.model.context)} tokens` })] : null,
el("dt", { text: "API" }), el("dd", {}, el("code", { text: b.links.api }), " · no API key needed"),
b.pid ? [el("dt", { text: "Process" }), el("dd", { text: `pid ${b.pid}${b.external_program ? ` (${b.external_program})` : ""} · port ${b.port}${token ? ` · ${token}` : ""}` })] : null,
b.uptime != null ? [el("dt", { text: "Up" }), el("dd", { text: fmt.dur(b.uptime) + (b.restarts ? ` · ${b.restarts} restart${b.restarts > 1 ? "s" : ""}` : "") })] : null,
b.inflight ? [el("dt", { text: "Requests" }), el("dd", { text: `${b.inflight} in progress` })] : null,
b.idle_stop_in != null ? [el("dt", { text: "Idle stop" }), el("dd", { text: `in ${fmt.dur(b.idle_stop_in)} if unused` })] : null,
);
const canLoad = running && ["unloaded", "sleeping"].includes(st);
const canUnload = running && ["idle", "loading"].includes(st);
const actions = el("div", { class: "row", style: "margin-top:14px" },
el("button", { class: "btn", type: "button", disabled: !(canLoad || canUnload) || !!ai.action,
onclick: (e) => change(e.target, "/api/ai/model", { action: canLoad ? "load" : "unload" }) },
ai.action ? `${ai.action}…` : canUnload ? "Unload model" : "Load model"),
el("a", { class: "btn", href: b.links.chat, target: "_blank", rel: "noopener" }, `Open ${b.label} chat ↗`));
let live = null;
if (b.live) {
const L = b.live;
const text = L.phase === "reading"
? `Reading the prompt${L.progress != null ? ` · ${Math.round(L.progress * 100)}%` : ""}${L.read != null ? ` · ${fmt.n0(L.read)}${L.total ? ` of ${fmt.n0(L.total)}` : ""} tokens` : ""}`
: `Generating · ${fmt.n0(L.generated)} tokens`;
live = el("div", { class: "live" }, el("div", { class: "row" }, el("b", { text }), el("span", { class: "spacer" }),
el("span", { class: "muted num", text: `${L.tok_s != null ? `${fmt.n1(L.tok_s)} tok/s · ` : ""}${fmt.dur(L.elapsed)}` })),
L.phase === "reading" && L.progress != null
? el("div", { class: "meter", role: "progressbar", "aria-valuenow": Math.round(L.progress * 100) },
el("span", { style: `width:${(L.progress * 100).toFixed(1)}%` })) : null);
}
const avg = b.averages;
const speeds = el("div", { class: "speeds" },
el("div", {}, el("div", { class: "value", text: fmt.n1(avg.prefill_tps) }), el("div", { class: "label", text: "tok/s reading (average)" })),
el("div", {}, el("div", { class: "value", text: fmt.n1(avg.decode_tps) }), el("div", { class: "label", text: "tok/s writing (average)" })),
el("div", {}, el("div", { class: "value", text: fmt.n0(avg.requests) }), el("div", { class: "label", text: "requests" })));
const notes = [];
if (b.process === "external") notes.push(note("info", `Started outside The Kurgan${b.external_program ? ` by ${b.external_program}` : ""}. The Kurgan only watches it; retire that program's own startup task so The Kurgan can manage it.`));
if (b.error) notes.push(note("critical", b.error));
if (b.model.state === "failed" && b.model.detail) notes.push(note("critical", b.model.detail));
if (adminLevel) notes.push(note("warning", "This server is running with admin rights; it should not be."));
// replaceChildren would print a null as the text "null", so drop the empty parts first.
box.replaceChildren(...[el("div", { class: "row" }, el("h3", { text: b.label }), stateLine(b)),
kv, live, running && avg.requests ? speeds : null, ...notes, actions].filter(Boolean));
renderRequests(b);
}
function renderRequests(b) {
const list = b?.requests ?? [];
setText("requests-sub", b ? `${b.label}, newest first${list.length ? "" : " · none yet"}` : "No server selected");
if (!list.length) { $("requests").replaceChildren(); return; }
const head = el("tr", {}, ["Time", "Prompt", "Cached", "Output", "Reading tok/s", "Writing tok/s", "Took", "Result"]
.map((h, i) => el("th", { class: i && i < 7 ? "r" : "", text: h })));
const rows = list.map((r) => el("tr", {},
el("td", { class: "num", text: r.time ?? "--" }), el("td", { class: "r", text: fmt.n0(r.prompt) }),
el("td", { class: "r", text: fmt.n0(r.reused) }), el("td", { class: "r", text: fmt.n0(r.output) }),
el("td", { class: "r", text: fmt.n1(r.prefill_tps) }), el("td", { class: "r", text: fmt.n1(r.decode_tps) }),
el("td", { class: "r", text: r.duration != null ? `${fmt.n1(r.duration)} s` : "--" }), el("td", { text: r.status })));
$("requests").replaceChildren(el("table", {}, el("thead", {}, head), el("tbody", {}, rows)));
}
/* ------------------------------------------------------------------ main loop */
function render(s) {
lastState = s;
renderHeader(s);
renderSystem(s);
if (telemetry.push(s.telemetry.row)) {
charts.power.setData(telemetry.t, telemetry.cols);
charts.temps.setData(telemetry.t, telemetry.cols);
}
renderCooling(s);
renderLighting(s);
renderAI(s);
}
let failures = 0;
async function poll() {
if (document.hidden) return;
try {
const s = await api("/api/state");
if (failures) { banner(null); Object.values(charts).forEach((c) => c.stale(false)); }
failures = 0;
render(s);
} catch (error) {
failures++;
if (failures === 2) {
banner("critical", "Can't reach The Kurgan. It may be restarting; this page keeps trying.", true);
Object.values(charts).forEach((c) => c.stale(true));
$("meta").replaceChildren(el("span", { class: "pill" }, el("span", { class: "dot critical" }), "Disconnected"));
}
}
}
async function start() {
try {
config = await api("/api/config");
const history = await api("/api/history");
telemetry = new Series(history.series);
telemetry.load(history.rows);
fanHistory = new Series(history.fans.series);
fanHistory.load(history.fans.rows);
} catch (error) {
banner("critical", `Can't load The Kurgan's data: ${error.message}. Reload the page to try again.`, true);
return;
}
buildCharts();
charts.power.setData(telemetry.t, telemetry.cols);
charts.temps.setData(telemetry.t, telemetry.cols);
charts.fans.setData(fanHistory.t, fanHistory.cols);
await poll();
setInterval(poll, 1000);
document.addEventListener("visibilitychange", () => { if (!document.hidden) poll(); });
}
start();