import ReadActivity from "./ReadActivity"; // What a section of the machine panel did over time. // // Every section there answers "what is it NOW" — 61°C, 22.2 GB of 32, a load of // 84. None of them can answer "what did it do while that build was running", // and that is the question you have after a long run rather than during one. So // each section opens this, and which section you pressed decides what it plots. // // ONE MODAL PER SECTION, EVERY SERIES IN IT, ONE TIME AXIS. The series inside a // section are causally linked and a chart per row would put the cause and the // effect on two screens that cannot be compared: heat is why throttling // happens, and "all cores at 20% with the busiest at 100%" is one pinned core // rather than a busy machine. Neither reading means much without the other. // // TWO CHARTS STACKED, NOT TWO AXES ON ONE. Degrees and a percentage share // nothing but a range; drawing them against a single y-axis would invite a // reading of one shape against the other that means nothing at all. That both // happen to run 0-100 is a coincidence of units, and a coincidence is a bad // reason to overlay two quantities. // // SVG, not a library and not the canvas the radar uses. A temperature is // continuous, so it wants a line rather than the usage chart's bar columns, // which assert buckets that do not exist. Chart.js would be ~200KB on a bundle // that already warns at 647KB, for a deck people install through npx and wait // for — the whole of what it would buy here is a path string. import React, { useEffect, useMemo, useRef, useState } from "react"; import { createPortal } from "react-dom"; import { useModalDismiss, useScrimDismiss } from "./use-modal-dismiss"; import { figureText, latencyFigure, rateFigure, type Figure } from "../net-format"; import { currentLanguage, t as translate, useT, type TFunction } from "../i18n"; export interface Point { t: number; v: number } export interface Series { /** The stable name the ring records this reading under — `mem:swap`, not * `Swap`. The label is what the eye reads and is platform-dependent (`Swap` * is `Commit` on Windows); anything joining a live reading to its history * has to join on this. */ key: string; label: string; /** Empty for a quantity that has no unit — a load average is a count of * queued work, not a percentage of anything. `B/s` and `ms` are the network * section's, and are written by net-format.ts so the chart and the panel * print one reading the same way. */ unit: "C" | "%" | "" | "B/s" | "ms"; /** The top of this series' scale. 100 wherever the panel draws the same * number against a 0-100 track; fitted for load average, which is unbounded * and whose section draws no track to contradict. */ top: number; /** Null on a series with no bands — a throttle percentage has no comfortable * range to be inside, since any of it at all is the machine being slowed. */ warnAt: number | null; critAt: number | null; /** Whether zero is this reading's normal value. Only throttling is. */ restsAtZero: boolean; points: Point[]; /** The core count a queue is measured against. Only the load chart carries * it, and its reading uses it to say how many times over the cores a point * was. */ cores?: number; /** Moments something outside the reading changed — the network's route — * drawn as marks on the chart, so a line that jumps where a mark sits * explains itself. */ changes?: { t: number; label: string; from: string | null }[]; } /** A reading as the eye reads it: a speed in KB/s or MB/s rather than a count * of bytes, a round trip in ms, and the older units exactly as they were. */ export function figureOf(v: number, unit: Series["unit"]): Figure { if (unit === "B/s") return rateFigure(v); if (unit === "ms") return latencyFigure(v); return { value: String(v), unit: unit === "C" ? "°C" : unit }; } export interface History { ok: boolean; sinceMs: number; stepMs: number; series: Series[] } /** The plot box inside the SVG. Room at the left for the axis numbers, at the * bottom for the clock, and one pixel at the top so a reading at the ceiling * is not clipped by its own stroke. */ const PAD = { l: 30, r: 6, t: 6, b: 2 }; export type Pad = { l: number; r: number; t: number; b: number }; /** The same shapes at a size with no axis to leave room for. A footer sparkline * is 96px wide, and PAD.l alone is 30 of them — a third of the cell spent on * numbers that are not drawn there. Passed in rather than branched on, so the * two sizes share one arithmetic instead of growing a second. */ export const SPARK_PAD: Pad = { l: 0, r: 0, t: 2, b: 1 }; /** * How tall a chart is, and why the two are not the same. * * A reading that moves through its scale needs the room — a temperature has to * keep 75 and 90 apart, a load average has a spike worth seeing. A reading * whose NORMAL VALUE IS ZERO does not: throttling spends nearly all its life * flat on the floor, and at full height four fifths of its box is empty. * * `restsAtZero` comes from the server with the series and is the whole of the * rule. It was inferred from "has no bands" first and that was wrong: CPU has * no bands deliberately — the panel refuses to alarm at 90% because 90% is the * machine doing the work you asked for — and it uses the entire scale, so it * was getting the short box for a reason that is not true of it. * * The SCALE is unchanged either way, so nothing is exaggerated by being given * less space, and the two heights invite no false comparison because the units * already forbid one. */ const H = 104; const H_FLAT = 64; /** * Where a value sits, top-down, inside the plot box. * * `top` comes from the server with the series, and it is fixed at 100 wherever * the panel draws the same number against a 0-100 track: a scale that grew with * the reading would redraw a calm afternoon as a dramatic climb the moment the * numbers moved two degrees, and two pictures of one reading that disagree * about how alarming it is are worse than either alone. Load average is the * exception — genuinely unbounded, measured at 114 on twelve cores — and its * section draws no track for a fitted scale to contradict. */ export function yFor(v: number, top = 100, height = H, pad: Pad = PAD): number { const inner = height - pad.t - pad.b; return pad.t + inner * (1 - Math.max(0, Math.min(top, v)) / top); } /** The span a series is drawn across: the one it is handed, or its own first * and last point. */ export type Domain = [t0: number, t1: number]; function domainOf(points: Point[], domain?: Domain): Domain { return domain ?? [points[0].t, points[points.length - 1].t]; } /** * Where a moment sits, left to right, inside the plot box. * * Against `[t0, t1]`, which in the dialog is the span EVERY chart in it covers * rather than each series' own: one minute is one x down the whole stack, and a * series that started late or stopped early leaves its part of the width empty. * Stretched to its own points, forty minutes of latency under three hours of * download drew the same minute in two places. */ export function xFor(t: number, [t0, t1]: Domain, width: number, pad: Pad = PAD): number { const inner = width - pad.l - pad.r; const span = t1 - t0; return pad.l + (span > 0 ? (inner * (t - t0)) / span : inner / 2); } /** * The line, in path commands, with gaps left as gaps. * * A bucket exists only for a minute that was sampled, so a machine that slept, * or a deck that was paused, leaves a hole. Drawing straight through it would * invent a reading for every minute in between — the one thing this whole * feature refuses to do. Anything more than two steps apart starts a new * subpath instead. * * `domain` is the span to draw across (xFor); without one, the series' own. */ export function linePath(points: Point[], width: number, stepMs: number, top = 100, height = H, pad: Pad = PAD, domain?: Domain): string { if (!points.length) return ""; const span = domainOf(points, domain); const x = (t: number) => xFor(t, span, width, pad); let d = ""; let prev: Point | null = null; for (const p of points) { const cmd = prev && p.t - prev.t <= stepMs * 2 ? "L" : "M"; d += `${cmd}${x(p.t).toFixed(1)} ${yFor(p.v, top, height, pad).toFixed(1)}`; prev = p; } return d; } /** * The same shape closed to the floor, so the line reads as a level rather than * as a squiggle. * * One closed shape PER CONTIGUOUS RUN, not one for the series. Filling across a * hole would claim the machine read zero through it, which is the invention * this whole feature refuses; but abandoning the fill because the series has * one hole anywhere — which is what this did first — throws away the reading * for the other two hours to avoid inventing twelve minutes. Each run is * dropped to the floor on its own and the gap stays empty. */ export function areaPath(points: Point[], width: number, stepMs: number, top = 100, height = H, pad: Pad = PAD, domain?: Domain): string { if (points.length < 2) return ""; const floor = height - pad.b; const span = domainOf(points, domain); const x = (t: number) => xFor(t, span, width, pad); let out = ""; let run: Point[] = []; const flush = () => { if (run.length >= 2) { let d = `M${x(run[0].t).toFixed(1)} ${floor}`; for (const p of run) d += `L${x(p.t).toFixed(1)} ${yFor(p.v, top, height, pad).toFixed(1)}`; out += `${d}L${x(run[run.length - 1].t).toFixed(1)} ${floor}Z`; } run = []; }; for (const p of points) { if (run.length && p.t - run[run.length - 1].t > stepMs * 2) flush(); run.push(p); } flush(); return out; } /** now, peak — the two numbers worth the space. A minimum is not a question * anybody asks of a temperature. */ export function summary(points: Point[]): { now: number | null; peak: number | null } { if (!points.length) return { now: null, peak: null }; return { now: points[points.length - 1].v, peak: points.reduce((a, p) => Math.max(a, p.v), points[0].v), }; } /** Which band a value is in, for the peak readout's colour. Mirrors the row's * own rule so the chart and the panel cannot disagree. */ export function band(v: number, warnAt: number | null, critAt: number | null): "" | "warn" | "hot" { if (critAt != null && v >= critAt) return "hot"; if (warnAt != null && v >= warnAt) return "warn"; return ""; } /** * What the throttle series is for: the sentence under it. * * A chart of a line that is flat at zero says "nothing happened" perfectly well * and says nothing about WHEN it did not happen. When it did happen, the two * facts worth having are how long and how recently — a machine held back for * one minute an hour ago is a different machine from one held back for forty of * the last sixty. */ export function throttleNote(points: Point[], stepMs: number, at = (t: number) => clock(t), tr: TFunction = translate): string | null { const held = points.filter(p => p.v > 0); if (!points.length) return null; if (!held.length) return tr("board.hist.neverHeld"); const minutes = held.length * (stepMs / 60_000); const last = held[held.length - 1]; return tr("board.hist.heldBack", { span: tr("board.time.minutes", { count: minutes }), at: at(last.t) }); } /** * How hard the machine was working at one point of the load chart, as a * multiple of its cores. * * The panel's own note says it only for the load right now, and only once the * queue is longer than the cores — a spike at 03:00 had no number of its own * unless somebody was looking at 03:00. Read after the fact, every point gets * one, under the cores too: 0.4× is as much an answer to "how busy was it" as * 40× is. */ export function coreMultiple(load: number, cores: number | undefined, tr: TFunction = translate): string | null { if (cores == null || !Number.isFinite(cores) || cores <= 0 || !Number.isFinite(load) || load < 0) return null; return tr("board.hist.coreMultiple", { n: oneDecimal(load / cores) }); } /** 24-hour, always, like every other clock in this panel. A locale that prints * 01:28 PM beside a 13:28 elsewhere is two clocks in one card. */ export function clock(ms: number): string { const d = new Date(ms); return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`; } /** * How long the chart covers, said the way a person would. * * Truncated, never rounded. Rounding read thirty seconds as "1 minute", which * is the deck claiming a minute it does not have — on the surface whose whole * argument is that it never reports what it did not measure. Truncating can * only ever understate, and understating an elapsed time costs nothing. */ /** One decimal with the language's separator, "4.0" kept as written. */ function oneDecimal(v: number): string { try { return new Intl.NumberFormat(currentLanguage(), { minimumFractionDigits: 1, maximumFractionDigits: 1 }).format(v); } catch { return v.toFixed(1); } } export function spanLabel(fromMs: number, toMs: number, tr: TFunction = translate): string { const mins = Math.max(0, Math.floor((toMs - fromMs) / 60_000)); if (mins < 1) return tr("board.time.lessThanMinute"); if (mins < 60) return tr("board.time.minutes", { count: mins }); const h = Math.floor(mins / 60); const m = mins % 60; return m ? tr("board.time.hm", { h, m }) : tr("board.time.h", { h }); } export default function SectionHistoryModal({ group, title, liveNote, onClose }: { /** Which section of the panel was pressed. The server keeps one ring of * minute buckets for all of them and answers one section per request. */ group: "thermal" | "cores" | "memory" | "load" | "network"; title: string; /** Live snapshot context, distinct from the minute-bucket chart summaries. */ liveNote?: string | null; onClose: () => void; }) { const t = useT(); const dialogRef = useModalDismiss(onClose); const scrimPress = useScrimDismiss(onClose); const [hist, setHist] = useState(null); useEffect(() => { let alive = true; const load = async () => { try { const res = await fetch(`/api/system/history?group=${group}`); if (!res.ok) return; const data = await res.json(); if (alive && data?.ok) setHist(data); } catch { /* the deck is down; the connection pill already says so */ } }; load(); // The buckets are a minute wide, so a faster poll would redraw the same // picture; a slower one would let the newest minute sit stale on screen // while the row beside it moved. const iv = window.setInterval(load, 20_000); return () => { alive = false; window.clearInterval(iv); }; }, [group]); const series = hist?.series ?? []; /** * What the chart actually covers, which is NOT how long the deck has been * running. * * The header read `since ·