The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Worker: live hardware stats in the beat (GPU, CPU, memory, sensors file)
Adarsh8c4eded1214f
diff --git a/bin/lib/worker/config.mjs b/bin/lib/worker/config.mjsindex ecaa0604..e3b98abc 100644--- a/bin/lib/worker/config.mjs+++ b/bin/lib/worker/config.mjs@@ -63,6 +63,11 @@ export const DEFAULTS = {yieldMaxHoursPerDay: 20,interruptGapMin: 30,neverInterrupt: false,+ /**+ * A sensors file another program on this PC writes (CPU and motherboard temperatures, stats.mjs readSensors). None: no+ * such readings. The worker only reads it, with its GPU reading.+ */+ sensorsFile: null,};const file = (home, name) => path.join(home, name);diff --git a/bin/lib/worker/gpu.mjs b/bin/lib/worker/gpu.mjsindex 94bc804c..373c13b2 100644--- a/bin/lib/worker/gpu.mjs+++ b/bin/lib/worker/gpu.mjs@@ -21,7 +21,8 @@ const num = (s) => {};/**- * `nvidia-smi --query-gpu=memory.used,temperature.gpu,utilization.gpu --format=csv,noheader,nounits` → the first GPU.+ * `nvidia-smi --query-gpu=memory.used,temperature.gpu,utilization.gpu[,...] --format=csv,noheader,nounits` → the first+ * GPU. Fields after the third are ignored here (parseGpuStats reads them).* `busyPct`: how busy it is (0-100), null when nvidia-smi said nothing there ([N/A], or an answer without it).*/export function parseGpu(text) {@@ -47,6 +48,56 @@ export function parseApps(text) {.filter((a) => a.pid > 0);}+/**+ * What one GPU reading asks nvidia-smi for, in this order: the first three are what the busy check reads (parseGpu), the+ * rest are the live hardware stats (parseGpuStats). One process for all of them. No admin rights.+ */+export const GPU_FIELDS = "memory.used,temperature.gpu,utilization.gpu,power.draw,power.limit,clocks.gr,clocks.mem,memory.total,fan.speed,pstate";+/** The busy check's own fields: the fallback for an nvidia-smi that refuses a field of GPU_FIELDS. */+export const GPU_FIELDS_SHORT = "memory.used,temperature.gpu,utilization.gpu";+/** After a refused GPU_FIELDS query, the short one is used for this long before GPU_FIELDS is tried again. */+export const FULL_QUERY_RETRY_MS = 10 * 60_000;+/** Above this many watts while the GPU idles, its power reading is flagged (`powerSuspect`): some cards report far too much. */+export const IDLE_POWER_SUSPECT_W = 150;++// A field nvidia-smi can't give ("[N/A]", "[Not Supported]", nothing): null, never 0.+const field = (s) => {+ const t = String(s ?? "").trim();+ if (!t) return null;+ const v = Number(t);+ return Number.isFinite(v) ? v : null;+};+const within = (v, lo, hi) => (v === null ? null : Math.max(lo, Math.min(hi, Math.round(v))));++/**+ * The live hardware stats from a GPU_FIELDS line (the first GPU), or null when there is no line or no memory reading.+ * Every number is whole and clamped; a field nvidia-smi didn't give is null. `powerSuspect`: the card idles (P8, or under+ * 5% busy and under 50 °C) yet says it draws over IDLE_POWER_SUSPECT_W. The reading itself is kept as reported.+ */+export function parseGpuStats(text) {+ const line = String(text ?? "").split(/\r?\n/).find((l) => l.trim());+ if (!line) return null;+ const f = line.split(",");+ const vramUsedMb = within(field(f[0]), 0, 1_000_000);+ if (vramUsedMb === null) return null;+ const ps = String(f[9] ?? "").trim();+ const pstate = /^P\d{1,2}$/.test(ps) ? ps : null;+ const stats = {+ busyPct: within(field(f[2]), 0, 100),+ tempC: within(field(f[1]), -50, 150),+ powerW: within(field(f[3]), 0, 5000),+ powerLimitW: within(field(f[4]), 0, 5000),+ coreMHz: within(field(f[5]), 0, 20_000),+ memMHz: within(field(f[6]), 0, 50_000),+ vramUsedMb,+ vramTotalMb: within(field(f[7]), 0, 1_000_000),+ fanPct: within(field(f[8]), 0, 100),+ pstate,+ };+ const idle = pstate === "P8" || (stats.busyPct !== null && stats.busyPct < 5 && stats.tempC !== null && stats.tempC < 50);+ return idle && stats.powerW !== null && stats.powerW > IDLE_POWER_SUSPECT_W ? { ...stats, powerSuspect: true } : stats;+}+const run = (cmd, args) =>new Promise((resolve) => {execFile(cmd, args, { timeout: 5000, windowsHide: true }, (err, stdout) => resolve(err ? null : String(stdout)));@@ -55,18 +106,31 @@ const run = (cmd, args) =>/*** One reading of the GPU, or null when nvidia-smi isn't there (no NVIDIA GPU: nothing to watch). `cmd`: its path, or a* command and its first arguments (["node", "fake-smi.mjs"] in the tests).+ *+ * @param {string | string[]} [cmd]*/export async function readGpu(cmd = "nvidia-smi") {const [bin, ...pre] = Array.isArray(cmd) ? cmd : [cmd];const call = (args) => run(bin, [...pre, ...args]);- const gpu = await call(["--query-gpu=memory.used,temperature.gpu,utilization.gpu", "--format=csv,noheader,nounits"]);+ // One query for the busy check and the live stats. An nvidia-smi that refuses one of its fields answers the short one,+ // and the whole one is tried again after FULL_QUERY_RETRY_MS.+ const key = [bin, ...pre].join("\u0000");+ const full = !((shortUntil.get(key) ?? 0) > Date.now());+ let gpu = full ? await call([`--query-gpu=${GPU_FIELDS}`, "--format=csv,noheader,nounits"]) : null;+ if (gpu === null) {+ gpu = await call([`--query-gpu=${GPU_FIELDS_SHORT}`, "--format=csv,noheader,nounits"]);+ if (gpu !== null && full) shortUntil.set(key, Date.now() + FULL_QUERY_RETRY_MS);+ }if (gpu === null) return null;const g = parseGpu(gpu);if (!g) return null;const apps = parseApps((await call(["--query-compute-apps=pid,process_name,used_memory", "--format=csv,noheader,nounits"])) ?? "");- return { ...g, apps };+ return { ...g, apps, stats: parseGpuStats(gpu) };}+/** The nvidia-smi commands that refused GPU_FIELDS, and until when they get the short query. */+const shortUntil = new Map();+/** The first GPU's memory in MB (`--query-gpu=memory.total`), or null when nvidia-smi can't say. */export async function readGpuTotal(cmd = "nvidia-smi") {const [bin, ...pre] = Array.isArray(cmd) ? cmd : [cmd];diff --git a/bin/lib/worker/run.mjs b/bin/lib/worker/run.mjsindex e8373952..7e0243df 100644--- a/bin/lib/worker/run.mjs+++ b/bin/lib/worker/run.mjs@@ -44,6 +44,7 @@ import { LogRing } from "./log-ring.mjs";import { failure, Reach, retrying } from "./retry.mjs";import { builtCatalogVersion, ceilingOf, ceilingWords, graphInside, laneMap, readPcAnswers, workerCatalog } from "./tickets.mjs";import { TEXT_DRAIN_MS, TextSlot, textSlotOf, textTurn } from "./text.mjs";+import { CpuMeter, ramNow, readSensors, STATS_SEND_MS, statsOf } from "./stats.mjs";import { readLocalWork, SiteTurns, writeMode, writeSite } from "./turns.mjs";import { CodeWatch, headOf, restartDue, UPDATE_DEFER_MAX_MS } from "./update.mjs";@@ -331,6 +332,9 @@ async function work(saved, deps, owner) {let packs = [];let invHash = null;let gpuInfo = { otherApps: [], tempC: null, busyPct: null };+ // The PC's live hardware stats (stats.mjs), read with the GPU: the last reading goes in each beat.+ let hwStats = null;+ const cpuMeter = new CpuMeter(deps.cpuTimes);let lastGpuAt = 0;// When the GPU was last read: a reading older than GPU_BUSY_FRESH_MS says nothing about how busy it is now.let gpuReadAt = 0;@@ -774,6 +778,9 @@ async function work(saved, deps, owner) {canRotateToken: canRotate,local: pause,gpu: gpuInfo,+ // The PC's live hardware stats (GPU, CPU, memory, sensors); older studios ignore them.+ // Only a recent reading: one the loop could not renew for a while never reaches the studio as new.+ ...(hwStats && now() - hwStats.at <= STATS_SEND_MS && { stats: hwStats }),inventoryHash: invHash,warmLane: null,// The catalog its build composes job tickets for, and what its PC may ever run.@@ -1065,6 +1072,12 @@ async function work(saved, deps, owner) {if (t - lastGpuAt >= (deps.gpuEveryMs ?? 5000)) {lastGpuAt = t;const reading = await (deps.readGpu ?? readGpu)(cfg.nvidiaSmi);+ // The live stats from the same reading, with the CPU, the memory and the sensors file (never fails the turn).+ try {+ hwStats = statsOf({ at: now(), gpu: reading?.stats ?? null, cpu: cpuMeter.read(), ram: (deps.ramNow ?? ramNow)(), sensors: readSensors(cfg.sensorsFile, Date.now(), deps.readSensorsFile) });+ } catch {+ hwStats = null;+ }if (reading) {const mine = text?.own() ?? { pids: [], mb: 0 };const own = { running: comfy.alive(), mb: await comfy.vramMb(), pid: comfy.pid, port: comfy.alive() ? comfy.port : null, job: busyJob && jobUsesGpu, extraPids: mine.pids, extraMb: mine.mb };diff --git a/bin/lib/worker/stats.mjs b/bin/lib/worker/stats.mjsnew file mode 100644index 00000000..ae4f0c4f--- /dev/null+++ b/bin/lib/worker/stats.mjs@@ -0,0 +1,147 @@+// The PC's live hardware stats in the worker's beat (WorkerBeat.stats in src/lib/relay.ts): its GPU (gpu.mjs+// parseGpuStats, from the same nvidia-smi reading as the busy check), its CPU's load from the CPU times between two+// readings, its memory, and, when worker.json names a sensors file, the CPU and motherboard sensors another program on the+// PC writes there. Read every 5 s with the GPU. No extra process and no admin rights.+import fs from "node:fs";+import os from "node:os";++/** A sensors file older than this (its own `at`) says nothing about now: it is left out. */+export const SENSORS_FRESH_MS = 30_000;+/** A beat carries the last stats only while they are at most this old (the studio judges freshness by when it heard them). */+export const STATS_SEND_MS = 30_000;+/** At most this many motherboard temperatures and fans from the sensors file. */+export const BOARD_MAX = 8;++const finite = (v) => (typeof v === "number" && Number.isFinite(v) ? v : null);+const within = (v, lo, hi, digits = 0) => {+ const n = finite(v);+ if (n === null) return null;+ const f = 10 ** digits;+ return Math.max(lo, Math.min(hi, Math.round(n * f) / f));+};++/**+ * The CPU times of all cores together (os.cpus()): idle and total, in ms, and how many cores.+ *+ * @param {{ times?: { user?: number; nice?: number; sys?: number; idle?: number; irq?: number } }[]} [cpus]+ */+export function cpuTimes(cpus = os.cpus()) {+ let idle = 0;+ let total = 0;+ for (const c of cpus ?? []) {+ const t = c?.times ?? {};+ const parts = [t.user, t.nice, t.sys, t.idle, t.irq].map((x) => finite(x) ?? 0);+ idle += finite(t.idle) ?? 0;+ total += parts.reduce((a, b) => a + b, 0);+ }+ return { idle, total, cores: (cpus ?? []).length };+}++/** How busy the CPU was between two cpuTimes readings (0-100, whole), or null without two readings that moved forward. */+export function cpuBusyPct(prev, next) {+ if (!prev || !next) return null;+ const dt = next.total - prev.total;+ const di = next.idle - prev.idle;+ if (!(dt > 0) || di < 0 || di > dt) return null;+ return Math.max(0, Math.min(100, Math.round((1 - di / dt) * 100)));+}++/** Keeps the last CPU times: each read gives the load since the one before (the first one says null). */+export class CpuMeter {+ constructor(read = () => cpuTimes()) {+ this.readTimes = read;+ this.prev = null;+ }++ read() {+ let next;+ try {+ next = this.readTimes();+ } catch {+ return { busyPct: null, cores: null };+ }+ const busyPct = cpuBusyPct(this.prev, next);+ this.prev = next;+ return { busyPct, cores: next?.cores > 0 ? next.cores : null };+ }+}++/** The PC's memory in MB: used (total less free) and total. Null when it can't say. */+export function ramNow(total = os.totalmem(), free = os.freemem()) {+ const t = finite(total);+ const f = finite(free);+ if (t === null || t <= 0 || f === null) return { usedMb: null, totalMb: null };+ const mb = 2 ** 20;+ return { usedMb: Math.round(Math.max(0, Math.min(t, t - f)) / mb), totalMb: Math.round(t / mb) };+}++/** A sensor's name: printable, short, no markup characters. Null when nothing is left. */+export function sensorName(v) {+ if (typeof v !== "string") return null;+ const s = v+ .replace(/[^\w .:#()+/-]+/g, " ")+ .replace(/\s+/g, " ")+ .trim()+ .slice(0, 32)+ .trim();+ return s || null;+}++/**+ * The sensors file's readings worth sending, or null when there is none to send: no file, a file being written (not+ * whole JSON yet), one without a time, or one older than SENSORS_FRESH_MS. A byte order mark at its start is fine.+ * Values are clamped; a missing one is left out.+ *+ * File: { at: ISO time, cpu: { packageC, coreMaxC, powerW, clockMhz, vcoreV, ... }, board: { tempsC: [{ name, c }],+ * fansRpm: [{ name, rpm }] } }.+ */+export function readSensors(file, now = Date.now(), read = (p) => fs.readFileSync(p, "utf8")) {+ if (!file) return null;+ let raw;+ try {+ raw = JSON.parse(String(read(file)).replace(/^/, ""));+ } catch {+ return null;+ }+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;+ const at = typeof raw.at === "string" ? Date.parse(raw.at) : NaN;+ if (!Number.isFinite(at) || Math.abs(now - at) > SENSORS_FRESH_MS) return null;+ const cpu = raw.cpu && typeof raw.cpu === "object" ? raw.cpu : {};+ const board = raw.board && typeof raw.board === "object" ? raw.board : {};+ const out = {};+ const temp = within(cpu.packageC, -50, 150) ?? within(cpu.coreMaxC, -50, 150);+ if (temp !== null) out.cpuTempC = temp;+ const power = within(cpu.powerW, 0, 2000);+ if (power !== null) out.cpuPowerW = power;+ const clock = within(cpu.clockMhz, 0, 20_000);+ if (clock !== null) out.cpuClockMhz = clock;+ const vcore = within(cpu.vcoreV, 0, 3, 3);+ if (vcore !== null) out.vcoreV = vcore;+ const list = (v) => (Array.isArray(v) ? v : []);+ const temps = list(board.tempsC)+ .map((t) => ({ name: sensorName(t?.name), c: within(t?.c, -50, 150) }))+ .filter((t) => t.name && t.c !== null)+ .slice(0, BOARD_MAX);+ const fans = list(board.fansRpm)+ .map((f) => ({ name: sensorName(f?.name), rpm: within(f?.rpm, 0, 30_000) }))+ .filter((f) => f.name && f.rpm !== null)+ .slice(0, BOARD_MAX);+ if (temps.length || fans.length) out.board = { temps, fans };+ return Object.keys(out).length ? out : null;+}++/**+ * The beat's `stats`: when it was read (this PC's clock), the GPU (null: no NVIDIA GPU, or no reading), the CPU's load+ * and cores, the memory, and the sensors file's readings when there are fresh ones.+ */+export function statsOf({ at, gpu, cpu, ram, sensors }) {+ return {+ at,+ gpu: gpu ?? null,+ cpuPct: cpu?.busyPct ?? null,+ cpuCores: cpu?.cores ?? null,+ ramUsedMb: ram?.usedMb ?? null,+ ramTotalMb: ram?.totalMb ?? null,+ ...(sensors ?? {}),+ };+}diff --git a/docs/gpu-workers.md b/docs/gpu-workers.mdindex c80cc58e..11c7664b 100644--- a/docs/gpu-workers.md+++ b/docs/gpu-workers.md@@ -852,6 +852,26 @@ again with ffmpeg first: at most 512 pixels on its long side, from a local PNG oWithout ffmpeg, only small JPEG previews go; a picture that still doesn't fit in 64 KB is not sent. The studio keeps apreview only from the attempt that holds the job, and drops a larger one (the progress stays).+### Live hardware stats++With each GPU reading (every 5 seconds) the worker also reads its PC's live hardware stats and sends the last ones in+its beat as `stats` (src/lib/relay.ts `WorkerStats`, bin/lib/worker/stats.mjs). No extra process and no admin rights:++- The GPU from the same nvidia-smi query as the busy check: load, temperature, power draw and limit, core and memory+ clocks, VRAM used and total, fan and power state. A field nvidia-smi can't give is null. When the card idles (P8, or+ under 5% busy and under 50 °C) yet reports more than 150 W, `powerSuspect` is true and the watts are kept as+ reported. An nvidia-smi that refuses one of the fields gets the busy check's short query, and the whole one again+ after 10 minutes.+- The CPU's load from the CPU times between two readings, and the memory used and total.+- `sensorsFile` in worker.json (none by default): a JSON file another program on the PC writes, with `at` (an ISO time),+ `cpu` (`packageC`, `coreMaxC`, `powerW`, `clockMhz`, `vcoreV`) and `board` (`tempsC: [{ name, c }]`,+ `fansRpm: [{ name, rpm }]`). It is read only when its `at` is within 30 seconds. A missing or half-written file, or one+ with a byte order mark, is fine. It adds `cpuTempC` (`packageC`, else `coreMaxC`), `cpuPowerW`, `cpuClockMhz`,+ `vcoreV` and `board` (at most 8 temperatures and 8 fans, short plain names).++The studio keeps the newest per worker, cleaned and clamped, with its own receive time (`receivedAt`). A beat without+`stats` (an older worker) leaves none. Only `GET /api/admin/workers` shows them.+### When something goes wrongThe worker keeps its jobs going by itself:@@ -1059,7 +1079,8 @@ Each worker counts against its own rate limits, so three workers that beat everyis the studio's (`catalogCurrent`). Its state is `update-worker` while it is built from another catalog and accounts'runs may come to the install's GPUs. `asked` is its last claim for its GPU and the answer in words, `jobs` every job itholds now in either slot (stage, progress, typical run and ETA; `current` stays its GPU's job), and `lastEvent` the- newest row of its timeline other than a log line.+ newest row of its timeline other than a log line. `stats` is its PC's live hardware stats from its last beat, with+ `receivedAt` (null: none).- `GET /api/admin/workers/events`: the workers' timeline (above), newest first, by worker, kinds and run, in pages.- `PATCH /api/admin/workers/<id>`: `{ paused, pauseNow, drain, autoResume, hours, allow, claimAfterMs, switchAfterMs,rotate, revoke }`. Hours are `{ "always": true }` or `{ "tz": "Asia/Kolkata", "days": { "mon": [["01:00", "09:00"]] } }`.diff --git a/src/lib/relay.ts b/src/lib/relay.tsindex 4817d780..6dc2b27f 100644--- a/src/lib/relay.ts+++ b/src/lib/relay.ts@@ -349,6 +349,45 @@ export interface WorkerBeat {log?: WorkerLogLine[];/** Local work on its PC, as the helper there last wrote it (absent: none written, or an older worker program). */localWork?: LocalWork | null;+ /** Its PC's live hardware stats, read every few seconds (absent: an older worker program). For the owner only. */+ stats?: WorkerStats;+}++/** A worker PC's GPU in its live stats (nvidia-smi). Whole numbers; null where the card doesn't say. */+export interface WorkerGpuStats {+ busyPct: number | null;+ tempC: number | null;+ powerW: number | null;+ powerLimitW: number | null;+ /** The card idles yet reports a high power draw: the watts are as reported, and likely wrong. */+ powerSuspect?: true;+ coreMHz: number | null;+ memMHz: number | null;+ vramUsedMb: number | null;+ vramTotalMb: number | null;+ fanPct: number | null;+ /** Its power state ("P0" busiest to "P8" idle, or more). */+ pstate: string | null;+}++/** A worker PC's live hardware stats in its beat (bin/lib/worker/stats.mjs). Sensor fields only when the PC has them. */+export interface WorkerStats {+ /** When the PC read them (its own clock). */+ at: number;+ /** Null: no NVIDIA GPU, or no reading. */+ gpu: WorkerGpuStats | null;+ cpuPct: number | null;+ cpuCores: number | null;+ ramUsedMb: number | null;+ ramTotalMb: number | null;+ /** From a sensors file on the PC, when there is a fresh one. */+ cpuTempC?: number;+ cpuPowerW?: number;+ cpuClockMhz?: number;+ vcoreV?: number;+ board?: { temps: { name: string; c: number }[]; fans: { name: string; rpm: number }[] };+ /** Free space per drive, when a later worker sends it. */+ disks?: { drive: string; freeBytes: number; totalBytes: number }[];}/** A worker's log line in its beat. */diff --git a/src/server/computer/pool.ts b/src/server/computer/pool.tsindex 7b35227d..3080a2a5 100644--- a/src/server/computer/pool.ts+++ b/src/server/computer/pool.ts@@ -19,7 +19,7 @@ import { queueSettings, runCeilingMs } from "../queue-settings";import { createWorker, offerNextToken, revokeWorker, rotateWorker, type WorkerRow } from "./workers";import { modelLabel } from "./queue-live";import { effectiveMode, workerModeOf, LOCAL_WORK, lineControls, liveOverrides, modeClass, modeClassSql, overrideTargets, plainLine, poolMode, sweepControls, taskControl, DEFAULT_MODE, type EffectiveMode, type LineControls, type QueueMode, type TaskControl } from "./queue-controls";-import type { LocalWork } from "@/lib/relay";+import type { LocalWork, WorkerGpuStats, WorkerStats } from "@/lib/relay";import { cleanLogLines, lastEventOf, lastOfKind, logWorkerEvent, logWorkerEvents, setEventNames, type NewWorkerEvent, type WorkerEventKind } from "./worker-events";/**@@ -306,9 +306,96 @@ export function cleanBeat(b: unknown): WorkerBeat {...(Array.isArray(o.log) && o.log.length > 0 && { log: cleanLogLines(o.log) }),// Local work on its PC (counts and codes only); an older worker sends none....(o.localWork !== undefined && { localWork: cleanLocalWork(o.localWork) }),+ // Its PC's live hardware stats; an older worker sends none.+ ...(cleanStats(o.stats) && { stats: cleanStats(o.stats)! }),};}+const whole = (v: unknown, lo: number, hi: number, digits = 0): number | null => {+ const n = num(v);+ if (n === null) return null;+ const f = 10 ** digits;+ return Math.max(lo, Math.min(hi, Math.round(n * f) / f));+};+const sensorName = (v: unknown): string | null => {+ if (typeof v !== "string") return null;+ const s = v.replace(/[^\w .:#()+/-]+/g, " ").replace(/\s+/g, " ").trim().slice(0, 32).trim();+ return s || null;+};++/** A beat's GPU stats as they may be kept: whole numbers in range, null where unknown; else null. */+function cleanGpuStats(v: unknown): WorkerGpuStats | null {+ if (!v || typeof v !== "object" || Array.isArray(v)) return null;+ const o = v as Record<string, unknown>;+ const pstate = typeof o.pstate === "string" && /^P\d{1,2}$/.test(o.pstate) ? o.pstate : null;+ return {+ busyPct: whole(o.busyPct, 0, 100),+ tempC: whole(o.tempC, -50, 150),+ powerW: whole(o.powerW, 0, 5000),+ powerLimitW: whole(o.powerLimitW, 0, 5000),+ ...(o.powerSuspect === true && { powerSuspect: true as const }),+ coreMHz: whole(o.coreMHz, 0, 20_000),+ memMHz: whole(o.memMHz, 0, 50_000),+ vramUsedMb: whole(o.vramUsedMb, 0, 1_000_000),+ vramTotalMb: whole(o.vramTotalMb, 0, 1_000_000),+ fanPct: whole(o.fanPct, 0, 100),+ pstate,+ };+}++/**+ * A beat's live hardware stats as they may be kept (WorkerStats): known fields only, numbers clamped, sensor names short+ * and plain, at most 8 board temperatures and fans and 26 drives. Null when it has no reading time.+ */+export function cleanStats(v: unknown): WorkerStats | null {+ if (!v || typeof v !== "object" || Array.isArray(v)) return null;+ const o = v as Record<string, unknown>;+ const at = num(o.at);+ if (at === null || at <= 0) return null;+ const opt = <K extends string>(k: K, n: number | null) => (n === null ? {} : ({ [k]: n } as Record<K, number>));+ const list = (x: unknown) => (Array.isArray(x) ? x : []);+ const b = (o.board && typeof o.board === "object" ? o.board : null) as Record<string, unknown> | null;+ const temps = list(b?.temps)+ .map((t) => ({ name: sensorName((t as Record<string, unknown>)?.name), c: whole((t as Record<string, unknown>)?.c, -50, 150) }))+ .filter((t): t is { name: string; c: number } => !!t.name && t.c !== null)+ .slice(0, 8);+ const fans = list(b?.fans)+ .map((f) => ({ name: sensorName((f as Record<string, unknown>)?.name), rpm: whole((f as Record<string, unknown>)?.rpm, 0, 30_000) }))+ .filter((f): f is { name: string; rpm: number } => !!f.name && f.rpm !== null)+ .slice(0, 8);+ const disks = list(o.disks)+ .map((d) => d as Record<string, unknown>)+ .filter((d) => typeof d?.drive === "string" && /^[A-Z]$/.test(d.drive) && (num(d.freeBytes) ?? -1) >= 0 && (num(d.totalBytes) ?? -1) >= 0)+ .map((d) => ({ drive: d.drive as string, freeBytes: Math.floor(num(d.freeBytes)!), totalBytes: Math.floor(num(d.totalBytes)!) }))+ .slice(0, 26);+ return {+ at,+ gpu: cleanGpuStats(o.gpu),+ cpuPct: whole(o.cpuPct, 0, 100),+ cpuCores: whole(o.cpuCores, 0, 4096),+ ramUsedMb: whole(o.ramUsedMb, 0, 1e8),+ ramTotalMb: whole(o.ramTotalMb, 0, 1e8),+ ...opt("cpuTempC", whole(o.cpuTempC, -50, 150)),+ ...opt("cpuPowerW", whole(o.cpuPowerW, 0, 2000)),+ ...opt("cpuClockMhz", whole(o.cpuClockMhz, 0, 20_000)),+ ...opt("vcoreV", whole(o.vcoreV, 0, 3, 3)),+ ...((temps.length > 0 || fans.length > 0) && { board: { temps, fans } }),+ ...(disks.length > 0 && { disks }),+ };+}++/** A worker's live hardware stats as its last beat said, with when the studio heard them (`receivedAt`, its own clock). */+export type WorkerStatsView = WorkerStats & { receivedAt: number };++/** The stats a worker's last beat carried (null: none, or an older worker). The panel judges how fresh they are. */+export function workerStatsOf(w: Pick<WorkerRow, "stats_json">): WorkerStatsView | null {+ if (!w.stats_json) return null;+ const raw = json<Record<string, unknown> | null>(w.stats_json, null);+ const s = cleanStats(raw);+ const receivedAt = num(raw?.receivedAt);+ return s && receivedAt ? { ...s, receivedAt } : null;+}+/** A beat's `localWork` as it may be kept: a known state, a short code, a count, whether one runs, when; else null. */export function cleanLocalWork(v: unknown): LocalWork | null {if (!v || typeof v !== "object" || Array.isArray(v)) return null;@@ -372,7 +459,7 @@ export function workerBeat(w: WorkerRow, b: WorkerBeat, now = Date.now()): BeatAd.prepare("UPDATE relay_workers SET commit_sha = ?, behind_since = ?, update_asked_at = ? WHERE id = ?").run(b.commit ?? null, behindSince, askDone ? null : asked, w.id);d.prepare(`UPDATE relay_workers SET seen_at = ?, device = ?, protocol = ?, version = ?, paused_local = ?, local_why = ?, local_until = ?,- warm_lane = ?, facts_json = COALESCE(?, facts_json), catalog_version = ?, ceiling_json = ?, cpu_slot_json = ?, holding_json = ?, local_work_json = ? WHERE id = ?`,+ warm_lane = ?, facts_json = COALESCE(?, facts_json), catalog_version = ?, ceiling_json = ?, cpu_slot_json = ?, holding_json = ?, local_work_json = ?, stats_json = ? WHERE id = ?`,).run(now,device,@@ -390,6 +477,8 @@ export function workerBeat(w: WorkerRow, b: WorkerBeat, now = Date.now()): BeatAb.holding ? JSON.stringify({ ...b.holding, since: Math.min(b.holding.since, now) }) : null,// Local work on its PC: its time never later than now either.b.localWork ? JSON.stringify({ ...b.localWork, at: Math.min(b.localWork.at, now) }) : null,+ // Its PC's live stats, with when the studio heard them (none from an older worker: nothing old stays).+ b.stats ? JSON.stringify({ ...b.stats, receivedAt: now }) : null,w.id,);// Its PC slept: a job taken back from it for going quiet meanwhile counts against no one.@@ -1736,6 +1825,8 @@ export interface WorkerView {localWork: LocalWork | null;/** Its program against the studio's version: current, updating by itself, or behind long enough for the owner to act. */update: WorkerUpdate;+ /** Its PC's live hardware stats from its last beat, with when the studio heard them (null: none). */+ stats: WorkerStatsView | null;}/** A worker's program against the studio's version (WorkerView.update). Versions and commits as their first 12 hex. */@@ -1961,6 +2052,7 @@ export function workerView(w: WorkerRow, now = Date.now(), typical: (lane: strinownMode: workerModeOf(w),localWork: localWorkOf(w, now),update: updateOf(w, now),+ stats: workerStatsOf(w),};}diff --git a/src/server/computer/workers.ts b/src/server/computer/workers.tsindex f17228b1..52a3ce36 100644--- a/src/server/computer/workers.ts+++ b/src/server/computer/workers.ts@@ -93,6 +93,8 @@ export interface WorkerRow {update_asked_at?: number | null;update_asked_by?: string | null;update_asked_commit?: string | null;+ /** Its PC's live hardware stats (src/lib/relay.ts WorkerStats) and when the studio heard them, as its last beat said. */+ stats_json?: string | null;}const sha = (s: string) => crypto.createHash("sha256").update(s).digest("hex");diff --git a/src/server/db.ts b/src/server/db.tsindex 39db74a6..e450273d 100644--- a/src/server/db.ts+++ b/src/server/db.ts@@ -1147,6 +1147,8 @@ const RELAY_COLUMNS: [string, string, string][] = [["relay_workers", "update_asked_at", "INTEGER"],["relay_workers", "update_asked_by", "TEXT"],["relay_workers", "update_asked_commit", "TEXT"],+ // A worker PC's live hardware stats as its last beat said, with when the studio heard them (WorkerBeat.stats).+ ["relay_workers", "stats_json", "TEXT"],];declare global {diff --git a/tests/helpers/fake-nvidia-smi.mjs b/tests/helpers/fake-nvidia-smi.mjsindex 284fe01c..9123abc3 100644--- a/tests/helpers/fake-nvidia-smi.mjs+++ b/tests/helpers/fake-nvidia-smi.mjs@@ -1,6 +1,8 @@// A stand-in for nvidia-smi (the worker's GPU check, bin/lib/worker/gpu.mjs): it answers the queries the worker makes// from a JSON file the test writes: { "usedMb": 900, "tempC": 50, "busyPct": 97, "computeCap": "8.9", "apps": [{ "pid": 1, "name":// "python.exe", "usedMb": null }] } (usedMb null prints [N/A], as Windows does; no computeCap: an older nvidia-smi).+// "statsLine": the whole answer to the worker's full query (with power.draw and the rest). "refuseFull": true answers+// that query as an nvidia-smi that doesn't know one of its fields (an error), so the worker asks the short one.//// node tests/helpers/fake-nvidia-smi.mjs <state.json> --query-gpu=memory.used,temperature.gpu --format=csv,noheader,nounitsimport fs from "node:fs";@@ -10,6 +12,9 @@ const s = JSON.parse(fs.readFileSync(file, "utf8"));if (args.includes("--query-gpu=compute_cap")) {if (!s.computeCap) process.exit(2);process.stdout.write(`${s.computeCap}\n`);+} else if (args.some((a) => a.startsWith("--query-gpu") && a.includes("power.draw"))) {+ if (s.refuseFull) process.exit(2);+ process.stdout.write(`${s.statsLine ?? `${s.usedMb}, ${s.tempC ?? 40}, ${s.busyPct ?? "[N/A]"}`}\n`);} else if (args.some((a) => a.startsWith("--query-gpu"))) process.stdout.write(`${s.usedMb}, ${s.tempC ?? 40}, ${s.busyPct ?? "[N/A]"}\n`);else if (args.some((a) => a.startsWith("--query-compute-apps"))) for (const a of s.apps ?? []) process.stdout.write(`${a.pid}, ${a.name}, ${a.usedMb === null || a.usedMb === undefined ? "[N/A]" : a.usedMb}\n`);else process.exit(2);diff --git a/tests/worker-stats-run.test.ts b/tests/worker-stats-run.test.tsnew file mode 100644index 00000000..0c9bd4ae--- /dev/null+++ b/tests/worker-stats-run.test.ts@@ -0,0 +1,185 @@+/**+ * The worker PC's live hardware stats end to end: the worker program (bin/lib/worker/run.mjs) reads them with its GPU+ * reading and sends them in its beat, the studio keeps the newest per worker with its own receive time, and the admin+ * workers API shows them. Its readings are stand-ins: never a real GPU, never a real ComfyUI job.+ */+import fs from "node:fs";+import path from "node:path";+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import { NextRequest } from "next/server";+import { runWorker } from "../bin/lib/worker/run.mjs";+import { parseGpuStats } from "../bin/lib/worker/gpu.mjs";+import { apiAs, loadRoutes, type ComputerRoutes } from "./helpers/computer-tab";+import { tempDir } from "./helpers/temp-dir";++vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));+vi.setConfig({ testTimeout: 60_000 });++const dir = tempDir("fuobe-worker-stats-run-");+process.env.FUOBE_DATA_DIR = dir;+process.env.COMFYUI_URL = "http://127.0.0.1:7";+delete process.env.FUOBE_PASSWORD;+delete process.env.FUOBE_HOSTED_RUNS;++const { db } = await import("@/server/db");+const { resetRates } = await import("@/server/rate");+const admin = await import("@/server/admin-tokens");+const pool = await import("@/server/computer/pool");+const workers = await import("@/server/computer/workers");+const { ComputerRunner } = await import("@/lib/computer-runner");+const workersRoute = await import("@/app/api/admin/workers/route");+const beatRoute = await import("@/app/api/gpu/computer/beat/route");++const SITE = "http://127.0.0.1:9";+const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));+const LINE = "1200, 62, 0, 255.3, 575, 210, 405, 32607, 0, P8";++let routes: ComputerRoutes;+let adminToken = "";+beforeAll(async () => {+ routes = await loadRoutes();+ adminToken = admin.createAdminToken({ name: "stats reader", scopes: ["workers:read"] }).token;+});+beforeEach(() => {+ resetRates();+ db().prepare("DELETE FROM relay_workers").run();+});++const running: { ctrl: AbortController; done: Promise<unknown> }[] = [];+afterEach(async () => {+ for (const r of running.splice(0)) {+ r.ctrl.abort();+ await r.done.catch(() => {});+ }+});++const adminWorkers = async () => {+ const res = await workersRoute.GET(new NextRequest("http://localhost:3000/api/admin/workers", { headers: { authorization: `Bearer ${adminToken}` } }));+ expect(res.status).toBe(200);+ return ((await res.json()) as { workers: { id: string; stats: Record<string, unknown> | null }[] }).workers;+};++async function until<T>(fn: () => T | Promise<T>, ms = 30_000): Promise<Exclude<T, false | null | undefined>> {+ const end = Date.now() + ms;+ for (;;) {+ const v = await fn();+ if (v) return v as Exclude<T, false | null | undefined>;+ if (Date.now() > end) throw new Error(`Timed out after ${ms} ms`);+ await sleep(50);+ }+}++describe("live hardware stats from the worker to the admin API", () => {+ it("the worker sends them in its beat, the studio keeps them with its receive time, the API shows them", async () => {+ // A worker the owner keeps paused on the website: it only beats.+ const w = pool.addWorker("stats-pc");+ const home = tempDir("fuobe-worker-stats-home-");+ const sensors = path.join(home, "sensors.json");+ fs.writeFileSync(sensors, `${JSON.stringify({ at: new Date().toISOString(), cpu: { packageC: 68.4, powerW: 120, clockMhz: 5300, vcoreV: 1.21 }, board: { tempsC: [{ name: "VRM", c: 49 }], fansRpm: [{ name: "Pump", rpm: 2400 }] } })}`);+ const beats: Record<string, unknown>[] = [];+ const api = apiAs(routes, null);+ let cpuTick = 0;+ const ctrl = new AbortController();+ const done = runWorker(+ { site: SITE, token: w.token, comfyDir: path.join(home, "comfy"), workDir: path.join(home, "work"), modelDirs: [], comfyCommand: [process.execPath, "-e", "setTimeout(()=>{},60000)"], ffmpeg: null, sensorsFile: sensors },+ {+ fetch: async (url: string, init: RequestInit = {}) => {+ const u = new URL(url);+ if (u.pathname === "/api/gpu/computer/beat" && typeof init.body === "string") beats.push(JSON.parse(init.body));+ return api(u.pathname + u.search, init);+ },+ home,+ signal: ctrl.signal,+ requirements: { folders: [], files: {}, packs: {}, workflows: {} },+ ComputerRunner,+ rules: {},+ pins: {},+ allowed: new Set<string>(),+ readGpu: async () => ({ usedMb: 1200, tempC: 62, busyPct: 0, apps: [], stats: parseGpuStats(LINE) }),+ readGpuGen: async () => "12.0",+ gpuEveryMs: 50,+ // Two cores: 40% busy between readings.+ cpuTimes: () => {+ cpuTick++;+ return { idle: cpuTick * 600, total: cpuTick * 1000, cores: 2 };+ },+ ramNow: () => ({ usedMb: 40_000, totalMb: 65_536 }),+ ffmpegVersion: async () => null,+ awake: { set: () => {} },+ sleep: (ms: number) => sleep(Math.min(ms, 50)),+ log: () => {},+ catalogVersion: "0".repeat(64),+ allLanes: () => [],+ },+ );+ running.push({ ctrl, done });++ // A beat with the stats, its CPU load known (the second reading on).+ const sent = await until(() => beats.find((b) => (b.stats as { cpuPct?: number } | undefined)?.cpuPct === 40));+ expect(sent.stats).toMatchObject({+ gpu: { busyPct: 0, tempC: 62, powerW: 255, powerLimitW: 575, powerSuspect: true, coreMHz: 210, memMHz: 405, vramUsedMb: 1200, vramTotalMb: 32607, fanPct: 0, pstate: "P8" },+ cpuPct: 40,+ cpuCores: 2,+ ramUsedMb: 40_000,+ ramTotalMb: 65_536,+ cpuTempC: 68,+ cpuPowerW: 120,+ cpuClockMhz: 5300,+ vcoreV: 1.21,+ board: { temps: [{ name: "VRM", c: 49 }], fans: [{ name: "Pump", rpm: 2400 }] },+ });+ expect(typeof (sent.stats as { at: number }).at).toBe("number");++ // The studio kept the newest, with its own receive time, and the admin API shows them.+ const view = await until(async () => (await adminWorkers()).find((x) => x.id === w.id && (x.stats as { cpuPct?: number } | null)?.cpuPct === 40));+ expect(view.stats).toMatchObject({ gpu: { powerW: 255, powerSuspect: true, pstate: "P8" }, ramTotalMb: 65_536, cpuTempC: 68, board: { fans: [{ name: "Pump", rpm: 2400 }] } });+ expect(Math.abs(Date.now() - (view.stats!.receivedAt as number))).toBeLessThan(30_000);+ });++ it("the studio cleans what a beat says and an older worker's beat leaves none", async () => {+ const w = pool.addWorker("stats-clean");+ const headers = { host: "localhost:3000", authorization: `Bearer ${w.token}`, "content-type": "application/json" };+ const post = (body: unknown) => beatRoute.POST(new Request("http://localhost:3000/api/gpu/computer/beat", { method: "POST", headers, body: JSON.stringify(body) }));+ const base = { device: `wkr-${w.id}`, protocol: 2, version: "1", local: { paused: false, why: null, until: null }, gpu: { otherApps: [], tempC: 60 }, inventoryHash: null, running: [], stopped: [] };+ const res = await post({+ ...base,+ stats: {+ at: 1234,+ gpu: { busyPct: 250, tempC: 61.4, powerW: "lots", powerLimitW: 575, coreMHz: 2600, memMHz: 13800, vramUsedMb: 900, vramTotalMb: 32607, fanPct: 30, pstate: "<P1>", extra: "dropped" },+ cpuPct: 33,+ cpuCores: 32,+ ramUsedMb: 1000,+ ramTotalMb: 2000,+ cpuTempC: 999,+ vcoreV: 1.23456,+ board: { temps: Array.from({ length: 12 }, (_, i) => ({ name: `T${i}<b>`, c: 40 })), fans: [{ name: "", rpm: 1 }] },+ disks: [{ drive: "C", freeBytes: 5e10, totalBytes: 1e12 }, { drive: "../etc", freeBytes: 1, totalBytes: 1 }],+ secret: "never kept",+ },+ });+ expect(res.status).toBe(200);+ const kept = pool.workerStatsOf(workers.getWorker(w.id)!)!;+ expect(kept).toMatchObject({+ at: 1234,+ gpu: { busyPct: 100, tempC: 61, powerW: null, powerLimitW: 575, pstate: null },+ cpuPct: 33,+ cpuTempC: 150,+ vcoreV: 1.235,+ disks: [{ drive: "C", freeBytes: 5e10, totalBytes: 1e12 }],+ });+ expect(kept.gpu).not.toHaveProperty("extra");+ expect(kept).not.toHaveProperty("secret");+ expect(kept.board?.temps).toHaveLength(8);+ expect(kept.board?.temps[0].name).toBe("T0 b");+ expect(kept.board?.fans).toEqual([]);+ expect(typeof kept.receivedAt).toBe("number");++ // A beat without stats (an older worker program): nothing old stays.+ expect((await post(base)).status).toBe(200);+ expect(pool.workerStatsOf(workers.getWorker(w.id)!)).toBeNull();+ expect((await adminWorkers()).find((x) => x.id === w.id)?.stats).toBeNull();+ // Stats without a reading time are not kept.+ expect(pool.cleanStats({ gpu: null, cpuPct: 1 })).toBeNull();+ expect(pool.cleanBeat({ ...base, stats: "x" })).not.toHaveProperty("stats");+ });+});diff --git a/tests/worker-stats.test.ts b/tests/worker-stats.test.tsnew file mode 100644index 00000000..a23d269d--- /dev/null+++ b/tests/worker-stats.test.ts@@ -0,0 +1,216 @@+/**+ * The worker PC's live hardware stats (bin/lib/worker/gpu.mjs parseGpuStats, bin/lib/worker/stats.mjs): the GPU line from+ * nvidia-smi, the CPU's load from CPU times, the memory, and the optional sensors file. Never a real GPU.+ */+import fs from "node:fs";+import path from "node:path";+import { describe, expect, it } from "vitest";+import { GPU_FIELDS, parseGpu, parseGpuStats, readGpu } from "../bin/lib/worker/gpu.mjs";+import { CpuMeter, cpuBusyPct, cpuTimes, ramNow, readSensors, sensorName, SENSORS_FRESH_MS, statsOf } from "../bin/lib/worker/stats.mjs";+import { tempDir } from "./helpers/temp-dir";++const FAKE_SMI = path.resolve(__dirname, "helpers/fake-nvidia-smi.mjs");++describe("the GPU's live stats from nvidia-smi", () => {+ it("asks for every field in one query, the busy check's three first", () => {+ expect(GPU_FIELDS.split(",")).toEqual(["memory.used", "temperature.gpu", "utilization.gpu", "power.draw", "power.limit", "clocks.gr", "clocks.mem", "memory.total", "fan.speed", "pstate"]);+ });++ it("reads a whole line, whole numbers", () => {+ const line = "19714, 40.04, 100, 566.97, 575.00, 2602, 13801, 32607, 30, P1\n";+ expect(parseGpuStats(line)).toEqual({ busyPct: 100, tempC: 40, powerW: 567, powerLimitW: 575, coreMHz: 2602, memMHz: 13801, vramUsedMb: 19714, vramTotalMb: 32607, fanPct: 30, pstate: "P1" });+ // The busy check reads the same line as before.+ expect(parseGpu(line)).toEqual({ usedMb: 19714, tempC: 40.04, busyPct: 100 });+ });++ it("[N/A] and [Not Supported] fields are null, never 0", () => {+ expect(parseGpuStats("6144, 61, 12, [N/A], [Not Supported], 1800, , 24576, [N/A], [N/A]")).toEqual({+ busyPct: 12,+ tempC: 61,+ powerW: null,+ powerLimitW: null,+ coreMHz: 1800,+ memMHz: null,+ vramUsedMb: 6144,+ vramTotalMb: 24576,+ fanPct: null,+ pstate: null,+ });+ // A line from an older query (three fields): the rest are null.+ expect(parseGpuStats("900, 50, 97")).toMatchObject({ vramUsedMb: 900, busyPct: 97, powerW: null, pstate: null });+ // No memory reading, no line: nothing.+ expect(parseGpuStats("[N/A], 50, 97")).toBeNull();+ expect(parseGpuStats("")).toBeNull();+ });++ it("clamps what is out of range", () => {+ expect(parseGpuStats("-5, 400, 180, 99999, -3, 1e9, 70000, 2e7, 140, P99")).toEqual({+ busyPct: 100,+ tempC: 150,+ powerW: 5000,+ powerLimitW: 0,+ coreMHz: 20000,+ memMHz: 50000,+ vramUsedMb: 0,+ vramTotalMb: 1000000,+ fanPct: 100,+ pstate: "P99",+ });+ expect(parseGpuStats("1, 1, 1, 1, 1, 1, 1, 1, 1, <b>")?.pstate).toBeNull();+ });++ it("flags a high power reading while the card idles, and keeps the reading", () => {+ // P8 with 255 W: an idle card that reports far too much.+ expect(parseGpuStats("1200, 62, 0, 255.3, 575, 210, 405, 32607, 0, P8")).toMatchObject({ powerW: 255, powerSuspect: true });+ // Not P8, but under 5% busy and under 50 °C.+ expect(parseGpuStats("1200, 41, 3, 160, 575, 210, 405, 32607, 0, P2")).toMatchObject({ powerW: 160, powerSuspect: true });+ // Busy, or warm, or a plausible draw: no flag.+ expect(parseGpuStats("1200, 41, 90, 560, 575, 2600, 13801, 32607, 30, P1")).not.toHaveProperty("powerSuspect");+ expect(parseGpuStats("1200, 55, 2, 160, 575, 210, 405, 32607, 0, P2")).not.toHaveProperty("powerSuspect");+ expect(parseGpuStats("1200, 30, 0, 30, 575, 210, 405, 32607, 0, P8")).not.toHaveProperty("powerSuspect");+ expect(parseGpuStats("1200, 30, 0, 150, 575, 210, 405, 32607, 0, P8")).not.toHaveProperty("powerSuspect");+ });++ it("readGpu gives the stats beside the busy check's reading", async () => {+ const dir = tempDir("fuobe-worker-stats-smi-");+ const state = path.join(dir, "state.json");+ fs.writeFileSync(state, JSON.stringify({ usedMb: 19714, tempC: 40, busyPct: 100, statsLine: "19714, 40, 100, 566.97, 575.00, 2602, 13801, 32607, 30, P1", apps: [{ pid: 7, name: "python.exe", usedMb: null }] }));+ const r = await readGpu([process.execPath, FAKE_SMI, state]);+ expect(r).toMatchObject({ usedMb: 19714, busyPct: 100, apps: [{ pid: 7, name: "python.exe", usedMb: null }] });+ expect(r?.stats).toMatchObject({ powerW: 567, powerLimitW: 575, coreMHz: 2602, memMHz: 13801, vramTotalMb: 32607, fanPct: 30, pstate: "P1" });+ });++ it("an nvidia-smi that refuses a field: the short query keeps the busy check working", async () => {+ const dir = tempDir("fuobe-worker-stats-smi-old-");+ const state = path.join(dir, "state.json");+ fs.writeFileSync(state, JSON.stringify({ usedMb: 5000, tempC: 60, busyPct: 40, refuseFull: true }));+ const r = await readGpu([process.execPath, FAKE_SMI, state]);+ expect(r).toMatchObject({ usedMb: 5000, tempC: 60, busyPct: 40, apps: [] });+ expect(r?.stats).toMatchObject({ vramUsedMb: 5000, busyPct: 40, tempC: 60, powerW: null });+ // The next reading asks the short query at once.+ const again = await readGpu([process.execPath, FAKE_SMI, state]);+ expect(again?.usedMb).toBe(5000);+ });+});++describe("the CPU's load and the memory", () => {+ const cpu = (user: number, idle: number) => ({ times: { user, nice: 0, sys: 0, idle, irq: 0 } });++ it("CPU load is the busy share of the CPU time between two readings", () => {+ const a = cpuTimes([cpu(1000, 9000), cpu(1000, 9000)]);+ expect(a).toEqual({ idle: 18000, total: 20000, cores: 2 });+ // 1000 ms more busy and 3000 ms more idle in all: 25% busy.+ const b = cpuTimes([cpu(1500, 10500), cpu(1500, 10500)]);+ expect(cpuBusyPct(a, b)).toBe(25);+ // Nothing moved, a counter that went back, no first reading: unknown.+ expect(cpuBusyPct(a, a)).toBeNull();+ expect(cpuBusyPct(b, a)).toBeNull();+ expect(cpuBusyPct(null, a)).toBeNull();+ // All busy, all idle.+ expect(cpuBusyPct(a, cpuTimes([cpu(2000, 9000), cpu(2000, 9000)]))).toBe(100);+ expect(cpuBusyPct(a, cpuTimes([cpu(1000, 10000), cpu(1000, 10000)]))).toBe(0);+ });++ it("the meter says null first, then the load since its last reading", () => {+ const readings = [cpuTimes([cpu(0, 0)]), cpuTimes([cpu(600, 400)]), cpuTimes([cpu(700, 1300)])];+ const m = new CpuMeter(() => readings.shift()!);+ expect(m.read()).toEqual({ busyPct: null, cores: 1 });+ expect(m.read()).toEqual({ busyPct: 60, cores: 1 });+ expect(m.read()).toEqual({ busyPct: 10, cores: 1 });+ // A failing read says unknown and doesn't throw.+ expect(new CpuMeter(() => { throw new Error("no"); }).read()).toEqual({ busyPct: null, cores: null });+ // The real one works here.+ const real = new CpuMeter();+ expect(real.read().cores).toBeGreaterThan(0);+ });++ it("memory used is total less free, in MB", () => {+ expect(ramNow(32 * 2 ** 30, 8 * 2 ** 30)).toEqual({ usedMb: 24576, totalMb: 32768 });+ expect(ramNow(0, 0)).toEqual({ usedMb: null, totalMb: null });+ expect(ramNow(2 ** 30, 2 * 2 ** 30)).toEqual({ usedMb: 0, totalMb: 1024 });+ expect(ramNow().totalMb).toBeGreaterThan(0);+ });+});++describe("the sensors file", () => {+ const NOW = Date.UTC(2026, 10, 12, 10, 0, 0);+ const iso = (ms: number) => new Date(ms).toISOString();+ const FULL = {+ at: iso(NOW - 4000),+ cpu: { name: "AMD Ryzen 9 9950X3D", packageC: 71.6, coreMaxC: 78, coreAvgC: 66, powerW: 142.4, loadPct: 37, clockMhz: 5420.5, vcoreV: 1.2345 },+ board: {+ name: "X870E",+ tempsC: [{ name: "System", c: 38.2 }, { name: "VRM MOS", c: 51 }, { name: "<script>", c: 40 }, { name: "Chipset", c: null }],+ fansRpm: [{ name: "CPU Fan", rpm: 1180.4 }, { name: "Pump", rpm: 2400 }],+ },+ };+ const from = (v: unknown) => () => (typeof v === "string" ? v : JSON.stringify(v));++ it("a fresh file gives the CPU temperature, power, clock, Vcore and the board's sensors", () => {+ expect(readSensors("C:/x/sensors.json", NOW, from(FULL))).toEqual({+ cpuTempC: 72,+ cpuPowerW: 142,+ cpuClockMhz: 5421,+ vcoreV: 1.235,+ board: { temps: [{ name: "System", c: 38 }, { name: "VRM MOS", c: 51 }, { name: "script", c: 40 }], fans: [{ name: "CPU Fan", rpm: 1180 }, { name: "Pump", rpm: 2400 }] },+ });+ });++ it("the hottest core when there is no package temperature", () => {+ expect(readSensors("f", NOW, from({ at: iso(NOW), cpu: { coreMaxC: 81 } }))).toEqual({ cpuTempC: 81 });+ });++ it("a stale file, a file with no time, or nothing worth sending: nothing", () => {+ expect(readSensors("f", NOW, from({ ...FULL, at: iso(NOW - SENSORS_FRESH_MS - 1000) }))).toBeNull();+ expect(readSensors("f", NOW, from({ ...FULL, at: iso(NOW + SENSORS_FRESH_MS + 1000) }))).toBeNull();+ expect(readSensors("f", NOW, from({ ...FULL, at: undefined }))).toBeNull();+ expect(readSensors("f", NOW, from({ ...FULL, at: "yesterday" }))).toBeNull();+ expect(readSensors("f", NOW, from({ at: iso(NOW), cpu: { packageC: null } }))).toBeNull();+ expect(readSensors("f", NOW, from([1, 2]))).toBeNull();+ });++ it("no file named, a missing file, a half-written one: nothing, and no error", () => {+ expect(readSensors(null, NOW)).toBeNull();+ expect(readSensors(path.join(tempDir("fuobe-sensors-none-"), "sensors.json"), NOW)).toBeNull();+ const half = JSON.stringify(FULL).slice(0, 60);+ expect(readSensors("f", NOW, from(half))).toBeNull();+ expect(readSensors("f", NOW, from(""))).toBeNull();+ });++ it("a byte order mark at the start is fine (a real file on disk)", () => {+ const file = path.join(tempDir("fuobe-sensors-bom-"), "sensors.json");+ fs.writeFileSync(file, `\uFEFF${JSON.stringify({ ...FULL, at: new Date().toISOString() })}`, "utf8");+ expect(readSensors(file)).toMatchObject({ cpuTempC: 72, vcoreV: 1.235 });+ });++ it("clamps values and keeps at most 8 temperatures and 8 fans with short names", () => {+ const many = Array.from({ length: 12 }, (_, i) => ({ name: `Sensor ${i} ${"x".repeat(60)}`, c: 500, rpm: -10 }));+ const r = readSensors("f", NOW, from({ at: iso(NOW), cpu: { packageC: -400, powerW: 1e9, clockMhz: -1, vcoreV: 9 }, board: { tempsC: many, fansRpm: many } }));+ expect(r).toMatchObject({ cpuTempC: -50, cpuPowerW: 2000, cpuClockMhz: 0, vcoreV: 3 });+ expect(r?.board?.temps).toHaveLength(8);+ expect(r?.board?.fans).toHaveLength(8);+ expect(r?.board?.temps[0]).toEqual({ name: expect.stringMatching(/^Sensor 0 x+$/), c: 150 });+ expect(r?.board?.temps[0]?.name?.length).toBeLessThanOrEqual(32);+ expect(r?.board?.fans[0].rpm).toBe(0);+ expect(sensorName(" \u0000\u001b[31mCPU ")).toBe("31mCPU");+ expect(sensorName(" \u0000\u001b<> ")).toBeNull();+ expect(sensorName(42)).toBeNull();+ });+});++describe("the beat's stats", () => {+ it("puts the GPU, CPU, memory and sensors together", () => {+ const gpu = parseGpuStats("1200, 62, 0, 255, 575, 210, 405, 32607, 0, P8");+ expect(statsOf({ at: 5, gpu, cpu: { busyPct: 12, cores: 32 }, ram: { usedMb: 20000, totalMb: 65536 }, sensors: { cpuTempC: 70 } })).toEqual({+ at: 5,+ gpu,+ cpuPct: 12,+ cpuCores: 32,+ ramUsedMb: 20000,+ ramTotalMb: 65536,+ cpuTempC: 70,+ });+ // No GPU, no sensors: the rest still goes.+ expect(statsOf({ at: 5, gpu: null, cpu: { busyPct: null, cores: 8 }, ram: { usedMb: 1, totalMb: 2 }, sensors: null })).toEqual({ at: 5, gpu: null, cpuPct: null, cpuCores: 8, ramUsedMb: 1, ramTotalMb: 2 });+ });+});