diff --git a/CLAUDE.md b/CLAUDE.md
index 935c77c..a0009b6 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -181,6 +181,8 @@ Everything else here is convention, and the import-alias rule in particular has
- Prefer short-circuit (`&&`) over a ternary when the else branch is `null` or `undefined`, especially in React rendering. Do: `{isActive && }`. Don't: `{isActive ? : null}`. Guard the condition so it is a real boolean (`!!count && ...`), never a bare number that could render `0`.
- Prefer optional chaining (`?.`). When optional chaining is used, ALWAYS pair it with nullish coalescing (`??`) to supply a fallback.
- Prefer a single configurable object parameter over multiple positional parameters so argument order doesn't matter. Don't: `doSomething(foo, bar, hello)`. Do: `doSomething({ foo, bar, hello })`.
+- A comment that fits on one line uses `//`. A comment that spans more than one line uses one block, `/* ... */`, or `/** ... */` when it documents an export, a type or one of its fields. Never stack `//` lines into a paragraph, and never wrap a one-line comment in `/* */`.
+- Exceptions: comments inside JSX stay `{/* ... */}`, since JSX has no `//`; a trailing comment after code on the same line is always `//`; and a `/** ... */` doc comment that fits on one line stays as it is, because editors only show `/** */` comments on hover.
## Accessibility
diff --git a/apps/admin-portal/src/components/Chart/ChartLegend.tsx b/apps/admin-portal/src/components/Chart/ChartLegend.tsx
index 211477c..f5fc3de 100644
--- a/apps/admin-portal/src/components/Chart/ChartLegend.tsx
+++ b/apps/admin-portal/src/components/Chart/ChartLegend.tsx
@@ -1,3 +1,4 @@
+import { classNames } from '@/components/Chart/classNames'
import { swatchClass, type ChartMark } from '@/components/Chart/ChartTooltip'
import styles from '@/components/Chart/chart.module.scss'
@@ -12,20 +13,79 @@ export type ChartLegendItem = {
readonly note?: string
}
+/** Which series the reader left off the plot, and how to flip one. A chart
+ takes this whole or not at all, so a hidden series always comes with the
+ checkbox that brings it back. */
+export type SeriesToggle = {
+ /** Keys of the series currently left off the plot. */
+ readonly hidden: readonly string[]
+ readonly onToggle: (key: string) => void
+}
+
+/** Lets the reader choose which series are drawn. Without it the legend is a
+ plain key. */
+export type ChartLegendToggle = SeriesToggle & {
+ /** Names the group of checkboxes for a screen reader, such as "Hosts shown
+ on the CPU chart". */
+ readonly label: string
+}
+
type ChartLegendProps = {
readonly items: readonly ChartLegendItem[]
readonly mark?: ChartMark
+ readonly toggle?: ChartLegendToggle
}
-/** What each mark on the plot stands for, named in words beside its colour. */
-export const ChartLegend = ({ items, mark = 'square' }: ChartLegendProps) => (
-
- {items.map((item) => (
- -
-
- {item.name}
- {item.note !== undefined && {item.note}}
-
- ))}
+/** The swatch, name and note one entry shows, shared by both forms. */
+const EntryBody = ({
+ item,
+ mark,
+}: {
+ readonly item: ChartLegendItem
+ readonly mark: ChartMark
+}) => (
+ <>
+
+ {item.name}
+ {item.note !== undefined && {item.note}}
+ >
+)
+
+/** What each mark on the plot stands for, named in words beside its colour.
+ *
+ * Given a toggle, every entry is also a checkbox that shows or hides its
+ * series. A native checkbox inside its label, so the whole entry is the click
+ * target, the space bar works, and the checked state is announced without any
+ * ARIA of our own. The box is tinted the series colour, and an unchecked entry
+ * also dims and strikes its name, so hidden is never told by colour alone.
+ */
+export const ChartLegend = ({ items, mark = 'square', toggle }: ChartLegendProps) => (
+
)
diff --git a/apps/admin-portal/src/components/Chart/ChartTooltip.tsx b/apps/admin-portal/src/components/Chart/ChartTooltip.tsx
index 727601f..1c415fb 100644
--- a/apps/admin-portal/src/components/Chart/ChartTooltip.tsx
+++ b/apps/admin-portal/src/components/Chart/ChartTooltip.tsx
@@ -1,3 +1,4 @@
+import { classNames } from '@/components/Chart/classNames'
import styles from '@/components/Chart/chart.module.scss'
/** Which mark a series is drawn with, so its key in the tooltip and the legend
@@ -28,9 +29,7 @@ type ChartTooltipProps = {
/** One series' key: the colour it is drawn in, in the shape it is drawn as. */
export const swatchClass = ({ mark, tint }: { mark: ChartMark; tint?: string }): string =>
- [styles.swatch, mark === 'line' ? styles.swatchLine : '', tint ?? '']
- .filter((part) => part.length > 0)
- .join(' ')
+ classNames([styles.swatch, mark === 'line' && styles.swatchLine, tint])
/** Every series' reading at the inspected point on a chart.
*
@@ -39,8 +38,8 @@ export const swatchClass = ({ mark, tint }: { mark: ChartMark; tint?: string }):
* chart's own formatter instead of raw.
*/
export const ChartTooltip = ({ title, rows, total, mark = 'square' }: ChartTooltipProps) => {
- // A chart whose series carry no mark of their own gets no swatch column at
- // all, rather than one blank indenting every value it holds.
+ /* A chart whose series carry no mark of their own gets no swatch column at
+ all, rather than one blank indenting every value it holds. */
const keyed = rows.some((row) => row.swatchClass !== undefined)
const rowClass = keyed ? styles.tooltipRow : `${styles.tooltipRow} ${styles.tooltipRowPlain}`
diff --git a/apps/admin-portal/src/components/Chart/chart.module.scss b/apps/admin-portal/src/components/Chart/chart.module.scss
index 7fc92f7..e23fe6d 100644
--- a/apps/admin-portal/src/components/Chart/chart.module.scss
+++ b/apps/admin-portal/src/components/Chart/chart.module.scss
@@ -1,6 +1,6 @@
-// The chrome every chart in the admin portal wears: a recessive grid, one
-// tooltip box, one legend row. Written once here because three copies of it
-// is how two charts a page apart end up a token different from each other.
+/* The chrome every chart in the admin portal wears: a recessive grid, one
+ tooltip box, one legend row. Written once here because three copies of it
+ is how two charts a page apart end up a token different from each other. */
.chart {
display: grid;
grid-template-columns: minmax(0, 1fr);
@@ -22,9 +22,9 @@
display: grid;
grid-template-columns: minmax(0, 1fr);
- // The SVG is drawn at a measured pixel width, so between mount and the
- // first measurement it may be wider than this box. Scrolling inside is the
- // house rule for wide content: the mismatch must never widen the page.
+ /* The SVG is drawn at a measured pixel width, so between mount and the
+ first measurement it may be wider than this box. Scrolling inside is the
+ house rule for wide content: the mismatch must never widen the page. */
overflow-x: auto;
padding: var(--space-1) 0;
border: 1px solid var(--color-border);
@@ -32,33 +32,33 @@
background: var(--color-surface);
}
-// Bars run to the edge of their own category, so a bar chart's box keeps its
-// horizontal padding at zero. A line chart has a stroke that can sit right on
-// the axis ceiling, and wants the same air all round.
+/* Bars run to the edge of their own category, so a bar chart's box keeps its
+ horizontal padding at zero. A line chart has a stroke that can sit right on
+ the axis ceiling, and wants the same air all round. */
.plotWrapPadded {
padding: var(--space-2);
}
-// Horizontal guides only, kept recessive: border-coloured hairlines sit
-// behind the data ink instead of competing with it. Recharts stamps the
-// class on every gridline element itself, so the stroke sits on the class
-// directly, not on a descendant.
+/* Horizontal guides only, kept recessive: border-coloured hairlines sit
+ behind the data ink instead of competing with it. Recharts stamps the
+ class on every gridline element itself, so the stroke sits on the class
+ directly, not on a descendant. */
.grid {
stroke: var(--color-border);
}
-// Only the baseline lives inside the classed axis group; the tick text is
-// hoisted into its own layer and classed per element via the tick prop.
+/* Only the baseline lives inside the classed axis group; the tick text is
+ hoisted into its own layer and classed per element via the tick prop. */
.axis {
line {
stroke: var(--color-border);
}
}
-// Each tick's text element, reached through the axes' tick prop. Sized to
-// what the scale's axisWidth budgets for: at the page's body size a
-// "200.0 MB/s" label overruns the axis margin and clips. Tabular figures
-// keep times and rates the same width from tick to tick.
+/* Each tick's text element, reached through the axes' tick prop. Sized to
+ what the scale's axisWidth budgets for: at the page's body size a
+ "200.0 MB/s" label overruns the axis margin and clips. Tabular figures
+ keep times and rates the same width from tick to tick. */
.tickLabel {
fill: var(--color-muted);
font-size: var(--font-size-xs);
@@ -71,17 +71,17 @@
stroke-width: 1;
}
-// A bar chart's cursor: the hovered column lifts against a wash, so the
-// reader sees which bar the tooltip belongs to.
+/* A bar chart's cursor: the hovered column lifts against a wash, so the
+ reader sees which bar the tooltip belongs to. */
.hoverBand {
fill: var(--color-text);
fill-opacity: 0.06;
}
-// Recharts measures this box and pins it beside the cursor, clamped to the
-// plot, so it must stay in normal flow: positioned absolutely it collapses
-// the measuring wrapper to zero size, the background never paints, and every
-// word wraps onto its own line down the y axis.
+/* Recharts measures this box and pins it beside the cursor, clamped to the
+ plot, so it must stay in normal flow: positioned absolutely it collapses
+ the measuring wrapper to zero size, the background never paints, and every
+ word wraps onto its own line down the y axis. */
.tooltip {
display: grid;
grid-template-columns: minmax(0, 1fr);
@@ -107,8 +107,8 @@
list-style: none;
}
-// The value leads and the name follows: at the tooltip the reader has already
-// chosen the moment and wants the number.
+/* The value leads and the name follows: at the tooltip the reader has already
+ chosen the moment and wants the number. */
.tooltipRow {
display: grid;
grid-template-columns: auto auto minmax(0, 1fr);
@@ -116,8 +116,8 @@
gap: var(--space-1);
}
-// A row on a chart whose series carry no mark of their own, where the swatch
-// column would only indent every value by a blank.
+/* A row on a chart whose series carry no mark of their own, where the swatch
+ column would only indent every value by a blank. */
.tooltipRowPlain {
grid-template-columns: auto minmax(0, 1fr);
}
@@ -147,15 +147,64 @@
gap: var(--space-1);
}
+/* A legend whose entries are checkboxes: a little more room between them, so
+ each entry is a comfortable target rather than a run of words. */
+.legendToggles {
+ gap: var(--space-1) var(--space-2);
+}
+
+/* The whole entry is the click target. Padding instead of a bare word gives it
+ a hit area worth aiming at, and the focus ring wraps the entry rather than
+ the 1rem box, so a keyboard reader sees which series they are on. */
+.legendToggle {
+ display: grid;
+ align-items: center;
+ grid-auto-flow: column;
+ gap: var(--space-1);
+ padding: var(--space-0) var(--space-1);
+ border-radius: var(--radius-sm);
+ cursor: pointer;
+
+ &:hover {
+ background: color-mix(in oklab, var(--color-text) 6%, transparent);
+ }
+
+ &:has(:focus-visible) {
+ outline: 2px solid var(--color-accent);
+ outline-offset: 2px;
+ }
+
+ /* Hidden is told three ways: the box is empty, the name dims, and the name
+ is struck through, so it never rests on colour alone. */
+ &[data-hidden='true'] {
+ color: var(--color-muted);
+ text-decoration: line-through;
+ }
+}
+
+/* Native, so it keeps its own semantics and keyboard handling; tinted the
+ series colour so the box doubles as the key. */
+.legendCheck {
+ width: var(--space-2);
+ height: var(--space-2);
+ accent-color: var(--series-color, var(--color-accent));
+ cursor: pointer;
+
+ // the entry draws the ring, so the box does not draw a second one
+ &:focus-visible {
+ outline: none;
+ }
+}
+
.legendNote {
color: var(--color-muted);
font-size: var(--font-size-xs);
}
-// A filled square for a bar series, mirroring the mark it stands for. The
-// series colour comes from whichever palette class rides alongside this one;
-// identity is always also stated in words beside the swatch, never by colour
-// alone.
+/* A filled square for a bar series, mirroring the mark it stands for. The
+ series colour comes from whichever palette class rides alongside this one;
+ identity is always also stated in words beside the swatch, never by colour
+ alone. */
.swatch {
width: var(--space-2);
height: var(--space-2);
@@ -163,15 +212,15 @@
background: var(--series-color, var(--mark-color, var(--color-muted)));
}
-// The same key for a line series: a short stroke rather than a block, so the
-// mark in the legend is the mark on the plot.
+/* The same key for a line series: a short stroke rather than a block, so the
+ mark in the legend is the mark on the plot. */
.swatchLine {
height: 2px;
border-radius: 1px;
}
-// Holds the swatch column open on a row that stands for no series, such as a
-// total.
+/* Holds the swatch column open on a row that stands for no series, such as a
+ total. */
.swatchGap {
width: var(--space-2);
}
diff --git a/apps/admin-portal/src/components/Chart/classNames.ts b/apps/admin-portal/src/components/Chart/classNames.ts
new file mode 100644
index 0000000..71c1d3f
--- /dev/null
+++ b/apps/admin-portal/src/components/Chart/classNames.ts
@@ -0,0 +1,4 @@
+/** The class attribute for a set of parts, dropping the absent ones so no
+ stray space or "undefined" reaches the DOM. */
+export const classNames = (parts: readonly (string | false | undefined)[]): string =>
+ parts.filter((part): part is string => !!part).join(' ')
diff --git a/apps/admin-portal/src/components/Icon/Icon.tsx b/apps/admin-portal/src/components/Icon/Icon.tsx
index 9a39943..577c288 100644
--- a/apps/admin-portal/src/components/Icon/Icon.tsx
+++ b/apps/admin-portal/src/components/Icon/Icon.tsx
@@ -10,6 +10,7 @@ export type IconName =
| 'cpu'
| 'disk'
| 'expand'
+ | 'external'
| 'gauge'
| 'gpu'
| 'help'
@@ -23,9 +24,9 @@ export type IconName =
| 'users'
| 'warn'
-// One 16-unit grid, strokes only, round caps and joins: the geometry every
-// glyph shares, so the set reads as one hand whatever size it is shown at. The
-// single filled mark (the disk's indicator dot) says so inline.
+/* One 16-unit grid, strokes only, round caps and joins: the geometry every
+ glyph shares, so the set reads as one hand whatever size it is shown at. The
+ single filled mark (the disk's indicator dot) says so inline. */
const GLYPHS: Record = {
box: (
<>
@@ -57,6 +58,9 @@ const GLYPHS: Record = {
>
),
expand: ,
+ external: (
+
+ ),
gauge: (
<>
diff --git a/apps/admin-portal/src/lib/fleetApi.ts b/apps/admin-portal/src/lib/fleetApi.ts
index 7866433..df1ba50 100644
--- a/apps/admin-portal/src/lib/fleetApi.ts
+++ b/apps/admin-portal/src/lib/fleetApi.ts
@@ -17,9 +17,9 @@ import {
} from '@wizteros/wire'
import { createClient } from '@/lib/http'
-// The response types are the wire contract's, in libs/wire, where the monitor's
-// own route tests check every body against the same schemas this module reads
-// them with.
+/* The response types are the wire contract's, in libs/wire, where the monitor's
+ own route tests check every body against the same schemas this module reads
+ them with. */
export type {
FleetContainer,
FleetHost,
@@ -48,8 +48,8 @@ const AGE_UNITS = [
export const formatBytes = (value: number | null): string => {
if (value === null || !Number.isFinite(value)) return '--'
- // log2/10, not log(v)/log(1024): the latter comes back 2.9999999999999996 for
- // exactly 1024 ** 3, which floors to the wrong unit and renders "1024.0 MB"
+ /* log2/10, not log(v)/log(1024): the latter comes back 2.9999999999999996 for
+ exactly 1024 ** 3, which floors to the wrong unit and renders "1024.0 MB" */
const index = Math.min(
UNITS.length - 1,
Math.max(0, Math.floor(Math.log2(Math.max(value, 1)) / 10)),
@@ -62,6 +62,15 @@ export const plural = ({ count, unit }: { count: number; unit: string }): string
/** A metric age in words. "unknown" for an absent age, because a host that was
never measured has no age at all, and rendering it as 0 would read as fresh. */
+/* DiskStation Manager's own port. Every box answers on both 5000 (http) and
+ 5001 (https, self-signed), checked 2026-11-07; the plain port opens straight
+ to the login page instead of behind a certificate warning, and DSM encrypts
+ the password itself before it leaves the browser. */
+const DSM_PORT = 5000
+
+/** A host's DSM login page, which its card on the Fleet page links to. */
+export const dsmUrl = ({ ip }: { ip: string }): string => `http://${ip}:${DSM_PORT}/`
+
export const formatAge = (seconds: number | null): string => {
if (seconds === null || !Number.isFinite(seconds) || seconds < 0) return 'unknown'
const unit = AGE_UNITS.find((candidate) => seconds >= candidate.seconds)
@@ -129,8 +138,8 @@ export const fetchMetricHistory = async ({
is: isMetricHistory,
what: `${kind} history response`,
})
- // A response that answered for a different family would paint one chart with
- // another's numbers, silently and plausibly.
+ /* A response that answered for a different family would paint one chart with
+ another's numbers, silently and plausibly. */
if (data.kind !== kind) {
throw new Error(`Asked the fleet monitor for ${kind} history and got ${data.kind}`)
}
diff --git a/apps/admin-portal/src/pages/Fleet/Fleet.test.tsx b/apps/admin-portal/src/pages/Fleet/Fleet.test.tsx
index 56e1ef8..5caa68f 100644
--- a/apps/admin-portal/src/pages/Fleet/Fleet.test.tsx
+++ b/apps/admin-portal/src/pages/Fleet/Fleet.test.tsx
@@ -58,9 +58,9 @@ const host: FleetHost = {
uptime_percent_24h: 100,
}
-// AdminLayout brings the header, sidebar and footer, so the page needs a
-// router; the gate is dormant while Supabase is unconfigured, as in every
-// other page suite.
+/* AdminLayout brings the header, sidebar and footer, so the page needs a
+ router; the gate is dormant while Supabase is unconfigured, as in every
+ other page suite. */
const renderFleet = () => {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
useAuthStore.setState({ enabled: false })
@@ -73,8 +73,8 @@ const renderFleet = () => {
)
}
-// One chart per kind, so an empty history has to be answerable for each of
-// them; the kind has to match the route or the fetcher refuses the payload.
+/* One chart per kind, so an empty history has to be answerable for each of
+ them; the kind has to match the route or the fetcher refuses the payload. */
const CHART_KINDS = ['cpu', 'memory', 'gpu', 'network', 'disk'] as const
const emptyHistory = (kind: string) => ({
@@ -84,10 +84,10 @@ const emptyHistory = (kind: string) => ({
hosts: [],
})
-// Every query goes through the same window.fetch, so route the stub by path
-// rather than by call order; the chart routes must be tested before their
-// /fleet prefix. `cpu` overrides only the CPU history: the other three stay
-// empty, which keeps a test about one chart from having to describe four.
+/* Every query goes through the same window.fetch, so route the stub by path
+ rather than by call order; the chart routes must be tested before their
+ /fleet prefix. `cpu` overrides only the CPU history: the other three stay
+ empty, which keeps a test about one chart from having to describe four. */
const stubFleetFetch = ({
fleet,
incidents,
@@ -118,8 +118,8 @@ afterEach(() => {
useFleetPrefsStore.setState({
rangeMinutes: DEFAULT_RANGE_MINUTES,
updateIntervalMs: DEFAULT_UPDATE_INTERVAL_MS,
- // the selected tab is persisted too, so a test that switched charts would
- // otherwise hand the next one a GPU panel
+ /* the selected tab is persisted too, so a test that switched charts would
+ otherwise hand the next one a GPU panel */
chartKind: DEFAULT_CHART_KIND,
})
localStorage.removeItem('wz-fleet-prefs')
@@ -159,8 +159,8 @@ test('Fleet opens the chart full screen, and gives focus back to the button on c
// a native modal, which is what makes the page behind it inert
expect(dialog.tagName).toBe('DIALOG')
expect(dialog).toHaveAttribute('open')
- // the same chart, drawn to the box the screen leaves it; the test DOM
- // measures nothing, so here that is the unmeasured fallback
+ /* the same chart, drawn to the box the screen leaves it; the test DOM
+ measures nothing, so here that is the unmeasured fallback */
expect(dialog.querySelector('.recharts-surface')).toHaveAttribute('height', '240')
// focus moves in on open
const close = screen.getByRole('button', { name: 'Close full screen' })
@@ -249,8 +249,17 @@ test('HostCard names the host and its status in text, not by color alone', () =>
expect(screen.getByText('Healthy')).toBeInTheDocument()
})
-// A warn host prints no status word at all: the finding is the disk and load
-// figures the monitor judged, not a phrase summarising them over the name.
+test('HostCard opens its DSM login page in a new tab', () => {
+ render()
+
+ const link = screen.getByRole('link', { name: 'vermithor' })
+ expect(link).toHaveAttribute('href', `http://${card.ip}:5000/`)
+ expect(link).toHaveAttribute('target', '_blank')
+ expect(link).toHaveAccessibleDescription('Opens DiskStation Manager in a new tab')
+})
+
+/* A warn host prints no status word at all: the finding is the disk and load
+ figures the monitor judged, not a phrase summarising them over the name. */
test('HostCard prints no status line on a warn host', () => {
render()
@@ -295,9 +304,9 @@ test('HostCard reports an unmeasured 24h uptime as unknown rather than a score',
})
test('HostCard names the family that fell silent rather than blaming the slow tier', () => {
- // it used to print "Disk and temperature refresh every 15 minutes" whatever
- // had actually stopped, which read as a lie on meleys: both were seven
- // minutes old and a dead VPN counter was the stale reading
+ /* it used to print "Disk and temperature refresh every 15 minutes" whatever
+ had actually stopped, which read as a lie on meleys: both were seven
+ minutes old and a dead VPN counter was the stale reading */
render(
{
render(
{
- // the monitor sends a null age when nothing reported inside its age window,
- // and when a clock step left a reading stamped ahead of now
+ /* the monitor sends a null age when nothing reported inside its age window,
+ and when a clock step left a reading stamped ahead of now */
render(
{
render(
{
})
test('HostCard claims no health for a container that declares no healthcheck', () => {
- // "no healthcheck configured" is neither a pass nor a failure: "Up, healthy"
- // asserts a check that never ran, "Up, unhealthy" asserts one that failed
+ /* "no healthcheck configured" is neither a pass nor a failure: "Up, healthy"
+ asserts a check that never ran, "Up, unhealthy" asserts one that failed */
render(
{
vi.stubGlobal(
'fetch',
@@ -560,8 +569,8 @@ test('Fleet binds each card to the chart colour of the same host position', asyn
const first = await screen.findByRole('heading', { name: 'vermithor' })
const second = screen.getByRole('heading', { name: 'caraxes' })
- // both surfaces derive the class from array position, and the monitor
- // guarantees /fleet and /fleet/cpu agree on order
+ /* both surfaces derive the class from array position, and the monitor
+ guarantees /fleet and /fleet/cpu agree on order */
expect(first.closest('article')).toHaveClass('series1')
expect(second.closest('article')).toHaveClass('series2')
})
@@ -577,8 +586,8 @@ test('Fleet renders the selected chart in its tab panel once the payload lands',
hosts: [
{
name: 'vermithor',
- // recent stamps: the chart's frame is the last hour ending now, and
- // readings outside it are not drawn
+ /* recent stamps: the chart's frame is the last hour ending now, and
+ readings outside it are not drawn */
points: [
{ at: new Date(Date.now() - 60_000).toISOString(), value: 12.5 },
{ at: new Date(Date.now() - 30_000).toISOString(), value: 37.5 },
@@ -595,8 +604,8 @@ test('Fleet renders the selected chart in its tab panel once the payload lands',
})
test('Fleet keeps the update-rate control reachable while the CPU query fails', async () => {
- // the slider tunes the polling the failing query does, so it must never
- // disappear behind the error it could help recover from
+ /* the slider tunes the polling the failing query does, so it must never
+ disappear behind the error it could help recover from */
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('network down')))
renderFleet()
@@ -655,9 +664,9 @@ test('Fleet lists open incidents by target and reason', async () => {
expect(screen.getByText('timeout')).toBeInTheDocument()
})
-// The card carries a meter per capacity reading, so this one is found through
-// its own label rather than by position: picking the first .meterFill on the
-// card would silently start asserting against memory.
+/* The card carries a meter per capacity reading, so this one is found through
+ its own label rather than by position: picking the first .meterFill on the
+ card would silently start asserting against memory. */
const meterUnder = (label: string): Element | null => {
const cell = screen.getByText(label).parentElement
return cell === null ? null : cell.querySelector('.meterFill')
@@ -666,12 +675,12 @@ const meterUnder = (label: string): Element | null => {
test('HostCard draws the disk reading as a bar the number beside it already states', () => {
const { container } = render()
- // the figure and its denominator are separate nodes so the number can carry
- // the weight and the qualifier can step back
+ /* the figure and its denominator are separate nodes so the number can carry
+ the weight and the qualifier can step back */
expect(screen.getByText('96%')).toBeInTheDocument()
expect(screen.getByText(/of 94\.8 TB/)).toBeInTheDocument()
- // the bar is a second reading of that one fact, so it stays out of the
- // accessibility tree rather than repeating the number there
+ /* the bar is a second reading of that one fact, so it stays out of the
+ accessibility tree rather than repeating the number there */
expect(meterUnder('Disk')).toHaveStyle({ width: '96%' })
expect(container.querySelector('.meter')).toHaveAttribute('aria-hidden', 'true')
})
@@ -679,16 +688,16 @@ test('HostCard draws the disk reading as a bar the number beside it already stat
test('HostCard prints the free space beside the volume it describes', () => {
render()
- // "how much room is left" is what an operator does arithmetic for, so the
- // card does it: the monitor's own byte reading, never the rounded percentage
+ /* "how much room is left" is what an operator does arithmetic for, so the
+ card does it: the monitor's own byte reading, never the rounded percentage */
expect(screen.getByText('1.0 TB free')).toBeInTheDocument()
// the mount names which volume the figures describe
expect(screen.getByText('/volume1')).toBeInTheDocument()
})
test('HostCard claims no free space where the monitor reported none', () => {
- // absent is absent: a figure derived from the rounded percentage would
- // claim a precision the monitor never reported
+ /* absent is absent: a figure derived from the rounded percentage would
+ claim a precision the monitor never reported */
render()
expect(screen.queryByText(/free/)).toBeNull()
@@ -697,8 +706,8 @@ test('HostCard claims no free space where the monitor reported none', () => {
expect(screen.getByText(/of 94\.8 TB/)).toBeInTheDocument()
})
-// The same treatment for both capacity readings: a percentage with a bar under
-// it on one row and a bare percentage on the next reads as an accident.
+/* The same treatment for both capacity readings: a percentage with a bar under
+ it on one row and a bare percentage on the next reads as an accident. */
test('HostCard draws the memory reading as a bar as well', () => {
render()
@@ -712,8 +721,8 @@ test('HostCard draws no disk bar where there is no disk reading', () => {
expect(meterUnder('Disk')).toBeNull()
})
-// Load has no ceiling this card could honestly draw a bar against, and a full
-// bar under every host's 100% uptime would carry no information at all.
+/* Load has no ceiling this card could honestly draw a bar against, and a full
+ bar under every host's 100% uptime would carry no information at all. */
test('HostCard draws no bar under the readings that have no scale', () => {
render()
@@ -721,9 +730,9 @@ test('HostCard draws no bar under the readings that have no scale', () => {
expect(meterUnder('Uptime')).toBeNull()
})
-// The tile beside a reading wears the host's chart colour, which the card
-// border already states, and stands for the label beside it, which the label
-// already states: it is a second reading of two facts, so it is hidden whole.
+/* The tile beside a reading wears the host's chart colour, which the card
+ border already states, and stands for the label beside it, which the label
+ already states: it is a second reading of two facts, so it is hidden whole. */
const tileBeside = (label: string): Element | null =>
screen.getByText(label).parentElement?.querySelector('.tile') ?? null
@@ -748,8 +757,8 @@ test('HostCard marks a healthy status with a tile the word beside it already sta
expect(tile).toHaveClass('ok')
})
-// Never collected is an absence, not a health: its tile must not borrow the
-// healthy tone and let a reader's eye file the card as fine.
+/* Never collected is an absence, not a health: its tile must not borrow the
+ healthy tone and let a reader's eye file the card as fine. */
test('HostCard marks an uncollected status in the muted tone, not the healthy one', () => {
render()
@@ -768,11 +777,11 @@ test('HostCard leads each inventory row with a hidden tile and keeps the label i
})
test('Fleet asks the monitor for the chosen range, and marks it on the picker', async () => {
- // the picker's own suite covers the click reaching onChange; what this one
- // pins is the other half - a chosen range reaching the query, not the
- // hardcoded hour the page used to ask for
- // the slowest poll stop too, so the page's own refetch clock cannot fire
- // mid-test and make this about timing rather than about the range
+ /* the picker's own suite covers the click reaching onChange; what this one
+ pins is the other half - a chosen range reaching the query, not the
+ hardcoded hour the page used to ask for
+ the slowest poll stop too, so the page's own refetch clock cannot fire
+ mid-test and make this about timing rather than about the range */
useFleetPrefsStore.setState({ rangeMinutes: 10_080, updateIntervalMs: 10_000 })
stubFleetFetch({
fleet: { collected_at: '2026-08-15T00:00:00+00:00', stale: false, hosts: [host] },
@@ -780,12 +789,12 @@ test('Fleet asks the monitor for the chosen range, and marks it on the picker',
})
renderFleet()
- // the CPU query's own result, not the section heading: that heading renders
- // while all three queries are still in flight, so waiting on it waits for
- // nothing
+ /* the CPU query's own result, not the section heading: that heading renders
+ while all three queries are still in flight, so waiting on it waits for
+ nothing */
await screen.findByText(/No CPU readings in the last week/)
- // a week is the monitor's ceiling, so the lead-in minute every other range
- // asks for is clamped away here rather than refused
+ /* a week is the monitor's ceiling, so the lead-in minute every other range
+ asks for is clamped away here rather than refused */
expect(globalThis.fetch).toHaveBeenCalledWith('/fleet/cpu?minutes=10080', expect.anything())
expect(screen.getByRole('button', { name: '1 week' })).toHaveAttribute('aria-pressed', 'true')
})
@@ -810,8 +819,8 @@ test('Fleet offers one tab per chart and shows only the selected one', async ()
const tabs = await screen.findAllByRole('tab')
expect(tabs.map((tab) => tab.textContent)).toEqual(['CPU', 'Memory', 'Network', 'Disk', 'GPU'])
- // exactly one selected, and exactly one panel: the chart nobody is looking at
- // is the chart whose query never runs
+ /* exactly one selected, and exactly one panel: the chart nobody is looking at
+ is the chart whose query never runs */
expect(tabs.filter((tab) => tab.getAttribute('aria-selected') === 'true')).toHaveLength(1)
expect(screen.getAllByRole('tabpanel')).toHaveLength(1)
expect(screen.getByText(/No CPU readings/)).toBeInTheDocument()
@@ -847,8 +856,8 @@ test('Fleet moves between chart tabs with the arrow keys, wrapping at the ends',
renderFleet()
await screen.findAllByRole('tab')
- // keys land on the focused tab, the way they do in a browser: the strip
- // itself is not focusable in this pattern
+ /* keys land on the focused tab, the way they do in a browser: the strip
+ itself is not focusable in this pattern */
const selected = (): HTMLElement => {
const tabs = screen.getAllByRole('tab')
const tab = tabs.find((entry) => entry.getAttribute('aria-selected') === 'true') ?? tabs[0]
@@ -870,9 +879,9 @@ test('Fleet moves between chart tabs with the arrow keys, wrapping at the ends',
expect(screen.getByRole('tab', { name: 'CPU' })).toHaveAttribute('aria-selected', 'true')
})
-// Every kind and every range is its own query key, so most presses land on a
-// payload that is not in cache. The panel used to empty for that moment, which
-// dropped the chart's ~300px and jumped everything below it up the page.
+/* Every kind and every range is its own query key, so most presses land on a
+ payload that is not in cache. The panel used to empty for that moment, which
+ dropped the chart's ~300px and jumped everything below it up the page. */
const stubStalledChart = ({ stalled }: { stalled: string }) =>
vi.stubGlobal(
'fetch',
@@ -893,8 +902,8 @@ test('Fleet holds the chart shape while its first payload is in flight', async (
stubStalledChart({ stalled: 'cpu' })
renderFleet()
- // the caption is knowable before any reading is, so it stands in the same
- // words and the same space rather than being replaced by a one-line notice
+ /* the caption is knowable before any reading is, so it stands in the same
+ words and the same space rather than being replaced by a one-line notice */
expect(
await screen.findByText(/Aggregate CPU busy percent per host over the last hour/),
).toBeInTheDocument()
@@ -916,8 +925,8 @@ test('Fleet keeps the chart shape while an uncached tab loads', async () => {
).toBeInTheDocument()
})
-// A spinner over a chart that already failed reads as a request still running,
-// and the error beneath it as history. Only one of the two can be true.
+/* A spinner over a chart that already failed reads as a request still running,
+ and the error beneath it as history. Only one of the two can be true. */
test('Fleet drops the chart placeholder once the history request fails', async () => {
vi.stubGlobal(
'fetch',
diff --git a/apps/admin-portal/src/pages/Fleet/Fleet.tsx b/apps/admin-portal/src/pages/Fleet/Fleet.tsx
index 3d71083..512c0a4 100644
--- a/apps/admin-portal/src/pages/Fleet/Fleet.tsx
+++ b/apps/admin-portal/src/pages/Fleet/Fleet.tsx
@@ -17,12 +17,12 @@ import { UpdateRateSlider } from '@/pages/Fleet/UpdateRateSlider'
import { CHART_KINDS, useFleetPrefsStore } from '@/stores/fleetPrefsStore'
import styles from '@/pages/Fleet/Fleet.module.scss'
-// One vitals tick. Anything slower and the page lags the collector it reports.
-// The chart queries' cadence is user-set through the slider instead: polling
-// faster than a tick buys display latency (a fresh tick shows within the
-// chosen interval), never extra data. It does not set a chart's own rate -
-// the frame advances once a second whatever the slider says, carrying each
-// host's newest reading onto the present in between.
+/* One vitals tick. Anything slower and the page lags the collector it reports.
+ The chart queries' cadence is user-set through the slider instead: polling
+ faster than a tick buys display latency (a fresh tick shows within the
+ chosen interval), never extra data. It does not set a chart's own rate -
+ the frame advances once a second whatever the slider says, carrying each
+ host's newest reading onto the present in between. */
const REFETCH_MS = 30_000
const INCIDENT_HOURS = 24
@@ -56,20 +56,22 @@ const FleetInner = () => {
const setRangeMinutes = useFleetPrefsStore((state) => state.setRangeMinutes)
const chartKind = useFleetPrefsStore((state) => state.chartKind)
const setChartKind = useFleetPrefsStore((state) => state.setChartKind)
- // Not persisted, unlike the knobs above: a full-screen view that reopened by
- // itself on the next visit would cover the page before anyone asked for it.
+ const hiddenHosts = useFleetPrefsStore((state) => state.hiddenHosts[chartKind])
+ const toggleHost = useFleetPrefsStore((state) => state.toggleHost)
+ /* Not persisted, unlike the knobs above: a full-screen view that reopened by
+ itself on the next visit would cover the page before anyone asked for it. */
const [fullscreen, setFullscreen] = useState(false)
- // One query, for the chart on screen. Four charts polling at once cost four
- // requests an interval for three answers nobody was looking at, and at the
- // fastest stop that is forty a second against a NAS behind a Funnel.
- //
- // Kind and range are both in the key, so switching tabs or ranges back to
- // something already fetched paints from cache instead of emptying the chart
- // while a week reloads.
+ /* One query, for the chart on screen. Four charts polling at once cost four
+ requests an interval for three answers nobody was looking at, and at the
+ fastest stop that is forty a second against a NAS behind a Funnel.
+
+ Kind and range are both in the key, so switching tabs or ranges back to
+ something already fetched paints from cache instead of emptying the chart
+ while a week reloads. */
const chart = useQuery({
queryKey: ['fleet-metric', chartKind, rangeMinutes],
- // a lead-in past the frame, so the reading just before its left edge comes
- // along and the line can be drawn in from the edge
+ /* a lead-in past the frame, so the reading just before its left edge comes
+ along and the line can be drawn in from the edge */
queryFn: () =>
fetchMetricHistory({
kind: chartKind,
@@ -78,15 +80,15 @@ const FleetInner = () => {
refetchInterval: chartIntervalMs,
})
const chartCopy = METRIC_COPY[chartKind]
- // Known from the fleet query, which is not the one being switched: the
- // placeholder can name the hosts its legend row will list, so that row takes
- // the height it will still take once the readings land.
+ /* Known from the fleet query, which is not the one being switched: the
+ placeholder can name the hosts its legend row will list, so that row takes
+ the height it will still take once the readings land. */
const hostNames = fleet.data?.hosts.map((host) => host.name) ?? []
- // One panel, drawn twice: in the tab, and full screen. Nothing about it
- // changes between the two; the container is what decides how tall the chart
- // stands. Both read the one query, so opening the full-screen view costs no
- // request of its own.
+ /* One panel, drawn twice: in the tab, and full screen. Nothing about it
+ changes between the two; the container is what decides how tall the chart
+ stands. Both read the one query, so opening the full-screen view costs no
+ request of its own. */
const chartPanel = (
{/* Inside the panel rather than above the strip: the failure
@@ -99,17 +101,21 @@ const FleetInner = () => {
)}
{!!chart.data && (
toggleHost({ kind: chartKind, name }),
+ }}
/>
)}
{/* No data for this tab and range yet, and no error to explain
@@ -179,8 +185,8 @@ const FleetInner = () => {
setFullscreen(false)}
- // the range is the one knob worth having full screen: the view is
- // for reading a longer stretch in detail
+ /* the range is the one knob worth having full screen: the view is
+ for reading a longer stretch in detail */
tools={}
>
{chartPanel}
diff --git a/apps/admin-portal/src/pages/Fleet/HostCard.module.scss b/apps/admin-portal/src/pages/Fleet/HostCard.module.scss
index 3d79c58..a177179 100644
--- a/apps/admin-portal/src/pages/Fleet/HostCard.module.scss
+++ b/apps/admin-portal/src/pages/Fleet/HostCard.module.scss
@@ -1,36 +1,113 @@
-// Three bands, each owning its own padding so the rules between them run the
-// full width of the card. An inset rule reads as decoration; a full-bleed one
-// reads as a division, which is what these are: identity, readings, inventory.
+/* Three bands, each owning its own padding so the rules between them run the
+ full width of the card. An inset rule reads as decoration; a full-bleed one
+ reads as a division, which is what these are: identity, readings, inventory. */
.card {
+ /* the positioning context for the name link's overlay, which is what makes
+ the whole card clickable */
+ position: relative;
display: grid;
overflow: hidden;
grid-template-columns: minmax(0, 1fr);
- // The readings band takes the slack, so the inventory band sits on the same
- // baseline across a row of cards whatever each host reports. A third
- // implicit row is created only when a footer is actually rendered, so a
- // host with neither GPU nor Docker leaves no empty track behind.
+ /* The readings band takes the slack, so the inventory band sits on the same
+ baseline across a row of cards whatever each host reports. A third
+ implicit row is created only when a footer is actually rendered, so a
+ host with neither GPU nor Docker leaves no empty track behind. */
grid-template-rows: auto 1fr;
height: 100%;
- // The border carries the host's identity, matching its line on the CPU
- // chart; identity is still stated by the name, never by colour alone.
+ /* The border carries the host's identity, matching its line on the CPU
+ chart; identity is still stated by the name, never by colour alone. */
border: 2px solid var(--series-color, var(--color-border));
border-radius: var(--radius-md);
background: var(--color-surface);
- // Status keeps a non-colour cue now that the border colour means identity:
- // dashed for never-collected, and the status word plus note text elsewhere.
+ /* Status keeps a non-colour cue now that the border colour means identity:
+ dashed for never-collected, and the status word plus note text elsewhere. */
&[data-status='unknown'] {
border-style: dashed;
}
+
+ /* The card answers the pointer, or keyboard focus on its link, as one
+ target: the border brightens toward the host's colour, a soft glow in that
+ colour rises under it, and focus adds the accent ring. The lift is motion,
+ so it alone waits for the reduced-motion check; a transition listed for a
+ property that never changes costs nothing. */
+ transition:
+ box-shadow 180ms ease-out,
+ border-color 180ms ease-out,
+ translate 180ms ease-out;
+
+ &:hover,
+ &:has(.dsmLink:focus-visible) {
+ border-color: color-mix(
+ in oklab,
+ var(--series-color, var(--color-border)) 70%,
+ var(--color-text)
+ );
+ box-shadow: 0 var(--space-1) var(--space-3)
+ color-mix(in oklab, var(--series-color, transparent) 35%, transparent);
+
+ @media (prefers-reduced-motion: no-preference) {
+ translate: 0 calc(var(--space-0) * -1);
+ }
+ }
+
+ &:has(.dsmLink:focus-visible) {
+ outline: 2px solid var(--color-accent);
+ outline-offset: 2px;
+ }
+}
+
+/* The host name, and through its overlay the whole card. Inherits the name's
+ colour rather than link blue: the card's lift and the mark beside the name
+ are what say it opens something. */
+.dsmLink {
+ display: inline-grid;
+ align-items: center;
+ grid-auto-flow: column;
+ gap: var(--space-1);
+ justify-content: start;
+ color: inherit;
+ text-decoration: none;
+
+ &::after {
+ content: '';
+ position: absolute;
+ inset: 0;
+ }
+
+ /* the card draws the focus state, so the ring goes on the card's edge where
+ the overlay is, not around the name alone */
+ &:focus-visible {
+ outline: none;
+ }
+}
+
+// Says "opens elsewhere" without words; the words are in the hidden span.
+.dsmMark {
+ color: var(--color-muted);
+ transition: color 180ms ease-out;
+
+ .card:hover & {
+ color: var(--color-text);
+ }
+}
+
+.srOnly {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ overflow: hidden;
+ clip-path: inset(50%);
+ white-space: nowrap;
}
-// The name band wears the host's colour at a tenth strength: enough to bind
-// the card to its chart line at a glance, faint enough that muted text still
-// clears 4.5:1 over every slot in the palette. Where color-mix is
-// unsupported the declaration drops and the band is plain surface, which is
-// the border-only card this replaced.
+/* The name band wears the host's colour at a tenth strength: enough to bind
+ the card to its chart line at a glance, faint enough that muted text still
+ clears 4.5:1 over every slot in the palette. Where color-mix is
+ unsupported the declaration drops and the band is plain surface, which is
+ the border-only card this replaced. */
.header {
display: grid;
grid-template-columns: minmax(0, 1fr);
@@ -40,11 +117,11 @@
background: color-mix(in oklab, var(--series-color, transparent) 10%, var(--color-surface));
}
-// The name owns a full row at every width, and everything else sits under it.
-// It used to share a row with the status, where the status column sized to its
-// own content first: a qualified phrase took the whole card and left the name
-// a few characters wide, which `overflow-wrap: anywhere` then broke down the
-// middle of the hostname, one letter per line.
+/* The name owns a full row at every width, and everything else sits under it.
+ It used to share a row with the status, where the status column sized to its
+ own content first: a qualified phrase took the whole card and left the name
+ a few characters wide, which `overflow-wrap: anywhere` then broke down the
+ middle of the hostname, one letter per line. */
.name {
font-family: var(--font-display);
font-size: var(--font-size-lg);
@@ -61,9 +138,9 @@
overflow-wrap: anywhere;
}
-// Hugs its own text rather than spanning the band, so a one-word status reads
-// as a token and a phrase can still wrap to a second line. The tile leads,
-// inset by the same hairline the text is, so pill and tile share one corner.
+/* Hugs its own text rather than spanning the band, so a one-word status reads
+ as a token and a phrase can still wrap to a second line. The tile leads,
+ inset by the same hairline the text is, so pill and tile share one corner. */
.status {
display: grid;
align-items: center;
@@ -80,8 +157,8 @@
text-transform: uppercase;
}
-// The qualified form is a phrase, not a micro-label: uppercase tracking at
-// that length is unreadable, so drop it while keeping the same position.
+/* The qualified form is a phrase, not a micro-label: uppercase tracking at
+ that length is unreadable, so drop it while keeping the same position. */
.statusStale {
font-weight: 400;
font-size: var(--font-size-sm);
@@ -97,9 +174,9 @@
padding: var(--space-3);
}
-// A rail rather than a filled box: these notes qualify the readings beside
-// them and should not outweigh them. The mark sits on the first line and the
-// sentence takes the rest of the width.
+/* A rail rather than a filled box: these notes qualify the readings beside
+ them and should not outweigh them. The mark sits on the first line and the
+ sentence takes the rest of the width. */
.note {
display: grid;
align-items: start;
@@ -116,10 +193,10 @@
color: var(--color-accent);
}
-// One reading per row. Two to a line halved the card's height, but every
-// figure competed with the one beside it and the disk row had no room to
-// state its free space; a single column gives each reading the full width and
-// the figures a common right edge to line up on.
+/* One reading per row. Two to a line halved the card's height, but every
+ figure competed with the one beside it and the disk row had no room to
+ state its free space; a single column gives each reading the full width and
+ the figures a common right edge to line up on. */
.stats {
display: grid;
grid-template-columns: minmax(0, 1fr);
@@ -127,10 +204,10 @@
margin: 0;
}
-// The tile leads and spans the first two rows, so it sits beside the reading
-// as a whole rather than beside its first line. The label and figure share
-// the top row; the meter and context line hang under them, spanning both of
-// their columns, so the bar underlines the reading edge to edge.
+/* The tile leads and spans the first two rows, so it sits beside the reading
+ as a whole rather than beside its first line. The label and figure share
+ the top row; the meter and context line hang under them, spanning both of
+ their columns, so the bar underlines the reading edge to edge. */
.stat {
display: grid;
align-items: center;
@@ -151,15 +228,15 @@
text-transform: uppercase;
}
-// The dd has to be an element for the definition-list semantics, but its
-// children are grid items of the row: the figure shares the label's line and
-// the meter and context span the columns beneath it.
+/* The dd has to be an element for the definition-list semantics, but its
+ children are grid items of the row: the figure shares the label's line and
+ the meter and context span the columns beneath it. */
.statValue {
display: contents;
}
-// The figure is the thing the eye lands on, so it takes the weight, the size,
-// and the mono face every machine-reported number on this page is set in.
+/* The figure is the thing the eye lands on, so it takes the weight, the size,
+ and the mono face every machine-reported number on this page is set in. */
.figure {
font-family: var(--font-mono);
font-size: var(--font-size-lg);
@@ -170,8 +247,8 @@
text-align: right;
}
-// The finding and the qualifier share one line, finding left and scope right,
-// wrapping into a stack when a narrow card cannot hold both.
+/* The finding and the qualifier share one line, finding left and scope right,
+ wrapping into a stack when a narrow card cannot hold both. */
.contextRow {
display: flex;
flex-wrap: wrap;
@@ -183,8 +260,8 @@
font-variant-numeric: tabular-nums;
}
-// Body colour and label weight where the qualifier beside it is muted: "2.5 TB
-// free" is a finding, not a scoping.
+/* Body colour and label weight where the qualifier beside it is muted: "2.5 TB
+ free" is a finding, not a scoping. */
.finding {
font-weight: 600;
overflow-wrap: anywhere;
@@ -210,9 +287,9 @@
box-shadow: inset 0 0 0 1px var(--color-border);
}
-// The host's own colour, the one its card border and chart line already wear:
-// the bar says how much, never what it means, so it needs no scale of its own.
-// Every series colour clears 3:1 against the track it sits in.
+/* The host's own colour, the one its card border and chart line already wear:
+ the bar says how much, never what it means, so it needs no scale of its own.
+ Every series colour clears 3:1 against the track it sits in. */
.meterFill {
display: block;
height: 100%;
@@ -228,9 +305,9 @@
border-block-start: 1px solid var(--color-border);
}
-// The GPU line and the containers line are the same kind of statement - what
-// this host has - so they open on the same tile column and read as a pair,
-// with both labels starting at the same x.
+/* The GPU line and the containers line are the same kind of statement - what
+ this host has - so they open on the same tile column and read as a pair,
+ with both labels starting at the same x. */
.meta {
display: grid;
align-items: center;
@@ -246,8 +323,8 @@
text-transform: uppercase;
}
-// Never colour alone: on the collapsed roster this is the whole finding, so it
-// is stated in words ("2 down", "not collected") and merely set quietly.
+/* Never colour alone: on the collapsed roster this is the whole finding, so it
+ is stated in words ("2 down", "not collected") and merely set quietly. */
.metaValue {
color: var(--color-muted);
font-size: var(--font-size-xs);
@@ -256,15 +333,18 @@
}
.containers {
+ // above the card's link overlay, so opening the roster does not open DSM
+ position: relative;
+ z-index: 1;
display: grid;
grid-template-columns: minmax(0, 1fr);
gap: var(--space-1);
}
-// Four columns - tile, label, tally, chevron - so the tally sits hard right
-// whatever the label wraps to, and the chevron past it is what tells this row
-// apart from the GPU line above: `display: grid` takes a summary's own marker
-// away, so the row that reads as expandable used to look just like that one.
+/* Four columns - tile, label, tally, chevron - so the tally sits hard right
+ whatever the label wraps to, and the chevron past it is what tells this row
+ apart from the GPU line above: `display: grid` takes a summary's own marker
+ away, so the row that reads as expandable used to look just like that one. */
.containersSummary {
display: grid;
align-items: center;
@@ -283,8 +363,8 @@
}
}
-// Pointing down while shut, up while open. Snapped rather than tweened: a
-// 12px mark is too small for the motion to read as anything but flicker.
+/* Pointing down while shut, up while open. Snapped rather than tweened: a
+ 12px mark is too small for the motion to read as anything but flicker. */
.chevron {
color: var(--color-muted);
}
diff --git a/apps/admin-portal/src/pages/Fleet/HostCard.tsx b/apps/admin-portal/src/pages/Fleet/HostCard.tsx
index f59a4bb..fce6e17 100644
--- a/apps/admin-portal/src/pages/Fleet/HostCard.tsx
+++ b/apps/admin-portal/src/pages/Fleet/HostCard.tsx
@@ -1,8 +1,9 @@
-import type { ReactNode } from 'react'
+import { useId, type ReactNode } from 'react'
import { Icon, type IconName } from '@/components/Icon/Icon'
import { IconTile, type IconTileTone } from '@/components/IconTile/IconTile'
import {
formatAge,
+ dsmUrl,
formatBytes,
type FleetContainer,
type FleetHost,
@@ -18,34 +19,34 @@ type HostCardProps = {
readonly className?: string
}
-// null is "print no status line", not "no status": a warn host states its case
-// through the disk and load figures below and the stale note beside them,
-// which are the readings the monitor judged, rather than through a summary
-// word sitting over them.
+/* null is "print no status line", not "no status": a warn host states its case
+ through the disk and load figures below and the stale note beside them,
+ which are the readings the monitor judged, rather than through a summary
+ word sitting over them. */
const STATUS_LABEL: Record = {
ok: 'Healthy',
warn: null,
unknown: 'Not collected',
}
-// The tile beside the status word. Never collected is an absence, not a
-// health, so it wears the muted tone: a green tile on it would let a reader's
-// eye file the card as fine before the word beside it said otherwise.
+/* The tile beside the status word. Never collected is an absence, not a
+ health, so it wears the muted tone: a green tile on it would let a reader's
+ eye file the card as fine before the word beside it said otherwise. */
const STATUS_MARK: Record = {
ok: { name: 'check', tone: 'ok' },
warn: null,
unknown: { name: 'help', tone: 'muted' },
}
-// The status word is computed from disk and load, and disk is a slow-tier
-// metric: on a host whose slow probe died it is as frozen as the numbers under
-// it. Say so in the word itself, so the most prominent text on the card cannot
-// assert the present tense while the note below scopes only the readings.
+/* The status word is computed from disk and load, and disk is a slow-tier
+ metric: on a host whose slow probe died it is as frozen as the numbers under
+ it. Say so in the word itself, so the most prominent text on the card cannot
+ assert the present tense while the note below scopes only the readings. */
const STALE_STATUS_SUFFIX = ' as of the last reading'
-// The monitor names the family that fell silent in its own metric namespace.
-// These are the same words a reader already sees on the card, so the note
-// reads as English rather than as a key out of the database.
+/* The monitor names the family that fell silent in its own metric namespace.
+ These are the same words a reader already sees on the card, so the note
+ reads as English rather than as a key out of the database. */
const FAMILY_LABEL: Record = {
container: 'container state',
cpu: 'CPU',
@@ -145,8 +146,8 @@ const diskReading = ({
const base = usageReading({ percent, total })
return {
...base,
- // the mount names which volume the total describes, so it goes wherever
- // the total does
+ /* the mount names which volume the total describes, so it goes wherever
+ the total does */
...(base.context.length > 0 && { scopeName: mount }),
...(percent !== null && available !== null && { finding: `${formatBytes(available)} free` }),
}
@@ -225,19 +226,20 @@ const Stat = ({ label, icon, reading, meterPercent }: StatProps) => (
)
export const HostCard = ({ host, className }: HostCardProps) => {
- // A never-collected host is already unqualified-proof: its label is the
- // absence itself. Only a collected host can carry a stale present tense.
+ /* A never-collected host is already unqualified-proof: its label is the
+ absence itself. Only a collected host can carry a stale present tense. */
const staleStatus = host.status !== 'unknown' && host.metrics_stale
const label = STATUS_LABEL[host.status]
const mark = STATUS_MARK[host.status]
- // One text node, not a word plus a decorative span: the qualification has to
- // be part of the status itself, not something a reader can visually skip.
+ /* One text node, not a word plus a decorative span: the qualification has to
+ be part of the status itself, not something a reader can visually skip. */
const statusText = label === null ? null : `${label}${staleStatus ? STALE_STATUS_SUFFIX : ''}`
- // The core count is observed, not assumed, so it is worth showing: it is
- // what the load figure above it was divided by.
+ /* The core count is observed, not assumed, so it is worth showing: it is
+ what the load figure above it was divided by. */
const coreContext =
host.cores === null ? '' : `${host.cores} ${host.cores === 1 ? 'core' : 'cores'}`
const hasFooter = host.has_gpu || host.has_docker
+ const dsmHintId = useId()
return (
{
data-status={host.status}
>
- {host.name}
+
+ {/* The whole card is the link: the anchor's overlay stretches over the
+ card, so a click anywhere opens DSM, while the name stays the one
+ focusable, announced element. The containers disclosure sits above
+ the overlay and keeps its own click. */}
+
+ {host.name}
+
+
+
+
+ Opens DiskStation Manager in a new tab
+
{host.ip}
{/* status is stated in text, never by color alone: the tile restates
the word beside it and is hidden from the accessibility tree */}
diff --git a/apps/admin-portal/src/pages/Fleet/MetricChart.test.tsx b/apps/admin-portal/src/pages/Fleet/MetricChart.test.tsx
index e62b98a..9dbf9d4 100644
--- a/apps/admin-portal/src/pages/Fleet/MetricChart.test.tsx
+++ b/apps/admin-portal/src/pages/Fleet/MetricChart.test.tsx
@@ -36,8 +36,8 @@ const vermithor = series({
],
})
-// A fixed present, injected so the sliding window is deterministic: the frame
-// is [NOW - 60min, NOW] and every fixture point sits inside it.
+/* A fixed present, injected so the sliding window is deterministic: the frame
+ is [NOW - 60min, NOW] and every fixture point sits inside it. */
const NOW = T0 + 390_000
// One sampling tick plus slack, for the cases that assert nothing was added.
@@ -78,8 +78,8 @@ test('MetricChart legend names every host, including one with nothing to draw',
const legend = screen.getByRole('list')
expect(within(legend).getByText('meleys')).toBeInTheDocument()
expect(within(legend).getByText('caraxes')).toBeInTheDocument()
- // absent is absent: a host that reported nothing says so instead of drawing
- // a flat line at zero
+ /* absent is absent: a host that reported nothing says so instead of drawing
+ a flat line at zero */
expect(within(legend).getByText('no readings')).toBeInTheDocument()
})
@@ -118,8 +118,8 @@ test('MetricChart curves between readings rather than joining them straight', ()
})
test('MetricChart breaks a line across a gap instead of bridging it', () => {
- // readings every 30s, then a five-minute hole: drawing through it would
- // claim the host was observed while it was not
+ /* readings every 30s, then a five-minute hole: drawing through it would
+ claim the host was observed while it was not */
const gappy = series({
name: 'meleys',
points: [
@@ -146,15 +146,15 @@ test('MetricChart says nothing about freshness while the readings keep coming',
/>,
)
- // the newest reading sits at T0+60s against a 30s cadence, so 30.5s of age is
- // the ordinary lag between a reading and the frame that drew it, not news
+ /* the newest reading sits at T0+60s against a 30s cadence, so 30.5s of age is
+ the ordinary lag between a reading and the frame that drew it, not news */
expect(screen.queryByText(/Newest reading/)).toBeNull()
})
test('MetricChart carries the newest reading up to the present', async () => {
- // A present 10s past the newest reading, well inside the 30s cadence: the
- // line has to reach the right edge, or every host reads as one that fell
- // silent whenever the collector is mid-cycle.
+ /* A present 10s past the newest reading, well inside the 30s cadence: the
+ line has to reach the right edge, or every host reads as one that fell
+ silent whenever the collector is mid-cycle. */
const held = render(
{
now={() => T0 + 70_000}
/>,
)
- // the same frame with that present actually observed, which is the geometry
- // the carried point has to land on: asserted against Recharts' own scale
- // rather than against a pixel written out here
+ /* the same frame with that present actually observed, which is the geometry
+ the carried point has to land on: asserted against Recharts' own scale
+ rather than against a pixel written out here */
const observed = render(
{
const drawn = (): string => curves(container)[0] ?? ''
const before = drawn()
- // nothing about this render changes except the clock, and the frame slides
- // under the line anyway
+ /* nothing about this render changes except the clock, and the frame slides
+ under the line anyway */
offset = 1000
await waitFor(() => expect(drawn()).not.toBe(before), { timeout: 4000 })
})
test('MetricChart keeps its line whole as the held seconds pile up', async () => {
- // The seconds carried between readings are a drawing device, not readings.
- // Reading the collector's cadence back off a series that already holds them
- // measures the drawing device: the cadence collapses to a second, every real
- // 30s interval is reclassified as a gap, and the line shatters into points
- // too sparse to draw. The chart went blank a few seconds after it painted.
+ /* The seconds carried between readings are a drawing device, not readings.
+ Reading the collector's cadence back off a series that already holds them
+ measures the drawing device: the cadence collapses to a second, every real
+ 30s interval is reclassified as a gap, and the line shatters into points
+ too sparse to draw. The chart went blank a few seconds after it painted. */
const started = Date.now()
const { container } = render(
windowMinutes={60}
unit="percent"
copy={METRIC_COPY.cpu}
- // 10s past the newest reading against a 30s cadence, advancing with the
- // real clock so each sampling tick stamps a distinct second, as in a browser
+ /* 10s past the newest reading against a 30s cadence, advancing with the
+ real clock so each sampling tick stamps a distinct second, as in a browser */
now={() => T0 + 70_000 + (Date.now() - started)}
/>,
)
@@ -239,14 +239,14 @@ test('MetricChart keeps its line whole as the held seconds pile up', async () =>
})
test('MetricChart holds nothing once the newest reading has outlived the cadence', async () => {
- // NOW is 330s past the last reading against a 30s cadence, so there is
- // nothing fresh enough to carry: the line must end where the readings did
+ /* NOW is 330s past the last reading against a 30s cadence, so there is
+ nothing fresh enough to carry: the line must end where the readings did */
const { container } = renderChart([meleys])
const drawn = (): string => curves(container)[0] ?? ''
const before = drawn()
- // act, so the sampling tick that fires during the wait is flushed as React
- // would flush it in the browser rather than warned about
+ /* act, so the sampling tick that fires during the wait is flushed as React
+ would flush it in the browser rather than warned about */
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, SAMPLE_WAIT_MS))
})
@@ -255,9 +255,9 @@ test('MetricChart holds nothing once the newest reading has outlived the cadence
})
test('MetricChart reports the age of the newest reading once the collector is late', () => {
- // 330s past the last reading against a 30s cadence, well past the point the
- // lines stop advancing, which is the case the readout exists for. Counted in
- // whole seconds, the rate the frame itself advances at.
+ /* 330s past the last reading against a 30s cadence, well past the point the
+ lines stop advancing, which is the case the readout exists for. Counted in
+ whole seconds, the rate the frame itself advances at. */
renderChart([meleys, vermithor])
expect(screen.getByText('Newest reading 330 s ago.')).toBeInTheDocument()
@@ -313,11 +313,11 @@ const renderChartWindow = ({
return container
}
-// Recharts divides the domain for its own ticks, which labels the present's
-// offset and reshuffles every second as the frame slides.
+/* Recharts divides the domain for its own ticks, which labels the present's
+ offset and reshuffles every second as the frame slides. */
test('MetricChart labels the time axis on round minutes only', () => {
- // an hour on a wide box takes the five-minute spacing; the frame itself
- // starts at :06:30, which is where a domain-divided axis would label from
+ /* an hour on a wide box takes the five-minute spacing; the frame itself
+ starts at :06:30, which is where a domain-divided axis would label from */
const container = renderChartWindow({ windowMinutes: 60, width: 1600 })
const labels = axisLabels(container)
@@ -326,9 +326,9 @@ test('MetricChart labels the time axis on round minutes only', () => {
expect(minutes.filter((minute) => minute % 5 !== 0)).toEqual([])
})
-// The preset ranges span four orders of magnitude; the axis must carry a
-// readable number of labels at every one of them, not one label at fifteen
-// minutes and twenty-five at a day.
+/* The preset ranges span four orders of magnitude; the axis must carry a
+ readable number of labels at every one of them, not one label at fifteen
+ minutes and twenty-five at a day. */
test.each([60, 6 * 60, 24 * 60, 3 * 24 * 60, 7 * 24 * 60])(
'MetricChart draws between six and twelve labels over a %i minute window',
(windowMinutes) => {
@@ -340,9 +340,9 @@ test.each([60, 6 * 60, 24 * 60, 3 * 24 * 60, 7 * 24 * 60])(
},
)
-// Readings land a collector tick apart, so the first one inside the frame can
-// sit a whole tick past the left edge. The line is drawn in from the reading
-// before the edge instead, and Recharts clips it at the plot's side.
+/* Readings land a collector tick apart, so the first one inside the frame can
+ sit a whole tick past the left edge. The line is drawn in from the reading
+ before the edge instead, and Recharts clips it at the plot's side. */
test('MetricChart draws the line in from the reading before the frame edge', () => {
// the frame is [NOW - 60 min, NOW]; -3300 s is 90 s before its left edge
const insideOnly = series({
@@ -377,8 +377,8 @@ test('MetricChart sizes the axis from the readings on screen, not the lead-in',
series({
name: 'meleys',
points: [
- // a 100 MB/s reading 90 s before the frame's left edge is drawn
- // in from, not shown, so it must not lift the ceiling to 100
+ /* a 100 MB/s reading 90 s before the frame's left edge is drawn
+ in from, not shown, so it must not lift the ceiling to 100 */
[-3300, 100 * MB],
[0, 1 * MB],
[30, 1.5 * MB],
@@ -401,8 +401,8 @@ test('MetricChart sizes the axis from the readings on screen, not the lead-in',
expect(labels).not.toContain('100.0 MB/s')
})
-// A quarter hour is short enough to label every minute, so it does: fifteen
-// marks, one a minute, on any box that holds them.
+/* A quarter hour is short enough to label every minute, so it does: fifteen
+ marks, one a minute, on any box that holds them. */
test('MetricChart labels every minute of a fifteen minute window', () => {
const container = renderChartWindow({ windowMinutes: 15, width: 1600 })
@@ -415,8 +415,8 @@ test('MetricChart keeps the axis under twelve labels on a narrow box', () => {
expect(axisLabels(container).length).toBeLessThanOrEqual(12)
})
-// A week holds seven midnights; "12:00 AM" seven times over names none of
-// them. Every label past a day carries its date, so no two can read the same.
+/* A week holds seven midnights; "12:00 AM" seven times over names none of
+ them. Every label past a day carries its date, so no two can read the same. */
test('MetricChart dates the axis labels once the window passes a day', () => {
const container = renderChartWindow({ windowMinutes: 3 * 24 * 60, width: 1600 })
@@ -443,14 +443,14 @@ test('MetricChart dates the inspected moment, not just its time', () => {
fireEvent.focus(plot)
fireEvent.keyDown(plot, { key: 'ArrowRight' })
- // derived rather than written out: the suite runs in whatever zone and locale
- // the machine is set to, and the assertion is that a date is there at all
+ /* derived rather than written out: the suite runs in whatever zone and locale
+ the machine is set to, and the assertion is that a date is there at all */
const day = new Date(T0 + 30_000).toLocaleDateString([], { month: 'short', day: 'numeric' })
expect(container.querySelector('.recharts-tooltip-wrapper')).toHaveTextContent(day)
})
-// Recharts' accessibility layer puts the plot on the tab order and walks it
-// with the arrow keys; the tooltip is what it announces at each stop.
+/* Recharts' accessibility layer puts the plot on the tab order and walks it
+ with the arrow keys; the tooltip is what it announces at each stop. */
test('MetricChart reads out every host at the focused moment, stepped by arrow keys', () => {
const { container } = renderChart([meleys, vermithor])
@@ -474,8 +474,8 @@ test('MetricChart names the plot for a screen reader', () => {
expect(screen.getByRole('img', { name: 'CPU by host over the last hour' })).toBeInTheDocument()
})
-// The four charts share this component, so what makes them different has to be
-// the unit and the copy rather than four near-copies of the drawing code.
+/* The four charts share this component, so what makes them different has to be
+ the unit and the copy rather than four near-copies of the drawing code. */
test('MetricChart prints a throughput in bytes per second, not as a percentage', () => {
const traffic = series({
name: 'meleys',
@@ -504,9 +504,9 @@ test('MetricChart prints a throughput in bytes per second, not as a percentage',
})
test('MetricChart scales a throughput axis to the readings in view', () => {
- // a rate has no natural ceiling, so the axis takes one from the data; a
- // 2 MB/s peak makes a 2 MB/s ceiling whose quarters print round, because the
- // ceiling was rounded inside the unit the label prints in
+ /* a rate has no natural ceiling, so the axis takes one from the data; a
+ 2 MB/s peak makes a 2 MB/s ceiling whose quarters print round, because the
+ ceiling was rounded inside the unit the label prints in */
const traffic = series({ name: 'meleys', points: [[0, 2_097_152]] })
const { container } = render(
{
// the origin carries no unit
expect(axis).toContain('0')
})
+
+/** The y axis labels as drawn, bottom first. */
+const yLabels = (container: HTMLElement): readonly string[] =>
+ [
+ ...container.querySelectorAll(
+ '.recharts-yAxis-tick-labels .recharts-cartesian-axis-tick-value',
+ ),
+ ].map((tick) => tick.textContent ?? '')
+
+test('MetricChart draws a percent axis from 0% to 100%, whatever band the lines sit in', () => {
+ const { container } = render(
+ NOW}
+ />,
+ )
+
+ expect(yLabels(container)).toEqual(['0%', '25%', '50%', '75%', '100%'])
+})
+
+test('MetricChart legend checkboxes hide a line and keep the 0-100 axis', () => {
+ const toggled: string[] = []
+ const hosts = [
+ series({
+ name: 'meleys',
+ points: [
+ [0, 89.2],
+ [30, 89.6],
+ ],
+ }),
+ series({
+ name: 'vhagar',
+ points: [
+ [0, 93.1],
+ [30, 93.4],
+ ],
+ }),
+ ]
+ const { container, rerender } = render(
+ toggled.push(name) }}
+ now={() => NOW}
+ />,
+ )
+
+ const vhagar = screen.getByRole('checkbox', { name: 'vhagar' })
+ expect(vhagar).toBeChecked()
+ fireEvent.click(vhagar)
+ expect(toggled).toEqual(['vhagar'])
+
+ rerender(
+ toggled.push(name) }}
+ now={() => NOW}
+ />,
+ )
+
+ expect(screen.getByRole('checkbox', { name: 'vhagar' })).not.toBeChecked()
+ expect(curves(container)).toHaveLength(1)
+ // hiding a line never moves a percent axis off 0-100
+ expect(yLabels(container)).toEqual(['0%', '25%', '50%', '75%', '100%'])
+})
diff --git a/apps/admin-portal/src/pages/Fleet/MetricChart.tsx b/apps/admin-portal/src/pages/Fleet/MetricChart.tsx
index 0006e30..55ea60f 100644
--- a/apps/admin-portal/src/pages/Fleet/MetricChart.tsx
+++ b/apps/admin-portal/src/pages/Fleet/MetricChart.tsx
@@ -1,6 +1,6 @@
import { useEffect, useMemo, useState } from 'react'
import { CartesianGrid, Line, LineChart, Tooltip, XAxis, YAxis } from 'recharts'
-import { ChartLegend } from '@/components/Chart/ChartLegend'
+import { ChartLegend, type SeriesToggle } from '@/components/Chart/ChartLegend'
import { CHART_MARGIN } from '@/components/Chart/chartFrame'
import { ChartTooltip, type ChartKeyRow } from '@/components/Chart/ChartTooltip'
import { useMeasuredBox } from '@/components/Chart/useMeasuredBox'
@@ -29,6 +29,10 @@ import { rangeProse } from '@/stores/fleetPrefsStore'
import chrome from '@/components/Chart/chart.module.scss'
import styles from '@/pages/Fleet/MetricChart.module.scss'
+/** Shared rather than a fresh `[]` per render, so the frame below is not
+ rebuilt when no toggle is given. */
+const NONE_HIDDEN: readonly string[] = []
+
type MetricChartProps = {
readonly hosts: readonly MetricHostSeries[]
readonly windowMinutes: number
@@ -36,15 +40,18 @@ type MetricChartProps = {
formatting. Comes from the same response as the numbers. */
readonly unit: MetricUnit
readonly copy: MetricCopy
+ /** Which host lines the reader unchecked, and how to flip one. Without it
+ every line is drawn and the legend is a plain key. */
+ readonly toggle?: SeriesToggle
/** The clock, injectable so tests can pin the frame. */
readonly now?: () => number
}
-// The frame advances once a second, whatever cadence the page polls the monitor
-// at, and each host's newest reading is carried onto the new right edge with
-// it. The collector reads each host far more slowly than that, so the tip of
-// every line keeps moving between readings instead of freezing until the next
-// one lands.
+/* The frame advances once a second, whatever cadence the page polls the monitor
+ at, and each host's newest reading is carried onto the new right edge with
+ it. The collector reads each host far more slowly than that, so the tip of
+ every line keeps moving between readings instead of freezing until the next
+ one lands. */
const FRAME_EVERY_MS = 1000
/** The moving present: the frame's right edge, and the moment every line's tip
@@ -69,9 +76,9 @@ const useNow = (now: () => number): number => {
return nowMs
}
-// Module-level so the default is one stable reference: an inline default would
-// be a new function every render and reset the interval effect keyed on it each
-// time.
+/* Module-level so the default is one stable reference: an inline default would
+ be a new function every render and reset the interval effect keyed on it each
+ time. */
const readClock = (): number => Date.now()
type ReadingTooltipProps = {
@@ -118,28 +125,33 @@ export const MetricChart = ({
windowMinutes,
unit,
copy,
+ toggle,
now = readClock,
}: MetricChartProps) => {
- // The stylesheet sizes the plot box, never the chart inside it: a floor on
- // the page, and whatever height is left in a container that has some to
- // give, such as the full-screen view. The chart is drawn to what is measured.
+ /* The stylesheet sizes the plot box, never the chart inside it: a floor on
+ the page, and whatever height is left in a container that has some to
+ give, such as the full-screen view. The chart is drawn to what is measured. */
const { ref, width, height } = useMeasuredBox()
const plots = useMemo(() => toPlots(hosts), [hosts])
+ const hidden = toggle?.hidden ?? NONE_HIDDEN
const span = windowMinutes * 60_000
const nowMs = useNow(now)
const {
rows,
lines: visiblePlots,
- readings: visibleReadings,
+ readings,
ticks,
scale,
- } = useMemo(() => drawFrame({ plots, nowMs, span, unit }), [plots, nowMs, span, unit])
+ } = useMemo(
+ () => drawFrame({ plots, nowMs, span, unit, hidden }),
+ [plots, nowMs, span, unit, hidden],
+ )
const first = nowMs - span
- // Labelled at round minutes rather than wherever the domain divides, so the
- // ticks name round times and stay put while the frame slides under them. The
- // spacing widens with the range and narrows with the box.
+ /* Labelled at round minutes rather than wherever the domain divides, so the
+ ticks name round times and stay put while the frame slides under them. The
+ spacing widens with the range and narrows with the box. */
const dated = span > DAY_MS
const axisMoments = labelledTicks({
first,
@@ -149,17 +161,17 @@ export const MetricChart = ({
cap: tickCap(span),
})
- // Only worth saying once the collector is late. Readings land every few
- // seconds, so an always-on readout spends its life reporting the ordinary lag
- // between a reading and the frame that drew it - a number that reads as a
- // fault and is not one. Past the stall limit it is the opposite: the lines
- // have stopped, and this is the only thing on the page that says so.
- //
- // Whole seconds, because the frame advances in whole seconds: a readout with
- // more precision than the thing it measures reads as false precision.
+ /* Only worth saying once the collector is late. Readings land every few
+ seconds, so an always-on readout spends its life reporting the ordinary lag
+ between a reading and the frame that drew it - a number that reads as a
+ fault and is not one. Past the stall limit it is the opposite: the lines
+ have stopped, and this is the only thing on the page that says so.
+
+ Whole seconds, because the frame advances in whole seconds: a readout with
+ more precision than the thing it measures reads as false precision. */
const newestTick = ticks[ticks.length - 1] ?? null
const ageMs = newestTick === null ? null : Math.max(0, nowMs - newestTick)
- const stallAfterMs = stallLimit(visibleReadings)
+ const stallAfterMs = stallLimit(readings)
const ageLabel =
ageMs !== null && stallAfterMs !== null && ageMs > stallAfterMs
? `${Math.round(ageMs / 1000)} s`
@@ -186,8 +198,8 @@ export const MetricChart = ({
height={height}
data={rows}
margin={CHART_MARGIN}
- // Recharts' own keyboard layer: the chart takes a tab stop and the
- // arrow keys walk it, announcing each moment through the tooltip.
+ /* Recharts' own keyboard layer: the chart takes a tab stop and the
+ arrow keys walk it, announcing each moment through the tooltip. */
accessibilityLayer
role="img"
aria-label={`${copy.title} by host over the last ${rangeProse(windowMinutes)}`}
@@ -197,21 +209,21 @@ export const MetricChart = ({
dataKey={AT_KEY}
type="number"
scale="time"
- // the frame is the window, not the extent of the data: a host that
- // stopped reporting an hour ago leaves empty space to the right
- // rather than stretching to fill it
+ /* the frame is the window, not the extent of the data: a host that
+ stopped reporting an hour ago leaves empty space to the right
+ rather than stretching to fill it */
domain={[first, nowMs]}
allowDataOverflow
ticks={[...axisMoments]}
tickFormatter={(at: number) => axisLabel({ at, dated })}
- // the label class rides the tick itself: Recharts hoists tick
- // text out of the axis group, where the axis class cannot
- // reach it
+ /* the label class rides the tick itself: Recharts hoists tick
+ text out of the axis group, where the axis class cannot
+ reach it */
tick={{ className: chrome.tickLabel }}
tickLine={false}
- // every tick handed over is drawn: the axis already picked as
- // many as the box holds, and Recharts culling them again by its
- // own measure thinned a scale that was sized to fit
+ /* every tick handed over is drawn: the axis already picked as
+ many as the box holds, and Recharts culling them again by its
+ own measure thinned a scale that was sized to fit */
interval={0}
className={chrome.axis}
/>
@@ -229,31 +241,33 @@ export const MetricChart = ({
}
+ /* the drawn lines, so a host the reader hid is not read out; their
+ byTick is the observations alone, never the carried tip */
+ content={}
/>
{visiblePlots.map((plot) => (
))}
@@ -273,12 +287,18 @@ export const MetricChart = ({
({
+ items={readings.map((plot) => ({
key: plot.name,
name: plot.name,
swatchClass: seriesClass(plot.seriesIndex),
note: plot.points.length === 0 ? 'no readings' : undefined,
}))}
+ toggle={
+ toggle && {
+ ...toggle,
+ label: `Hosts shown on the ${copy.title} chart`,
+ }
+ }
/>
)
diff --git a/apps/admin-portal/src/pages/Fleet/metricCopy.ts b/apps/admin-portal/src/pages/Fleet/metricCopy.ts
index 2941152..69e8ea5 100644
--- a/apps/admin-portal/src/pages/Fleet/metricCopy.ts
+++ b/apps/admin-portal/src/pages/Fleet/metricCopy.ts
@@ -40,7 +40,8 @@ export const METRIC_COPY: Record = {
disk: {
title: 'Disk',
icon: 'disk',
- measure: "Free space on each host's watched volume as a percent of its size",
+ measure:
+ "Used space on each host's watched volume as a percent of its size, read every fifteen minutes",
reading: 'disk',
},
network: {
@@ -64,4 +65,4 @@ export const chartCaption = ({
copy: MetricCopy
windowMinutes: number
}): string =>
- `${copy.measure} over the last ${rangeProse(windowMinutes)}. The line advances a point every second and holds the last reading between collector ticks, so a flat run means no new reading rather than steady load. A gap in a line is a span nothing was observed. Wide ranges arrive averaged into buckets, so a hole shorter than one bucket is averaged over rather than drawn as a gap.`
+ `${copy.measure} over the last ${rangeProse(windowMinutes)}. The line advances a point every second and holds the last reading between collector ticks, so a flat run means no new reading rather than steady load. A gap in a line is a span nothing was observed. Wide ranges arrive averaged into buckets, so a hole shorter than one bucket is averaged over rather than drawn as a gap. Percent charts run from 0% to 100%; uncheck a host below to hide its line.`
diff --git a/apps/admin-portal/src/pages/Fleet/metricFrame.ts b/apps/admin-portal/src/pages/Fleet/metricFrame.ts
index 23e77d3..9512d9a 100644
--- a/apps/admin-portal/src/pages/Fleet/metricFrame.ts
+++ b/apps/admin-portal/src/pages/Fleet/metricFrame.ts
@@ -33,10 +33,10 @@ export const AT_KEY = 'at'
export const hostKey = (name: string): string => `host:${name}`
-// A missed reading must render as a gap in the line, not a straight bridge
-// pretending the host was observed. The collector's cadence is not hardcoded
-// here; it is inferred from the readings themselves, so a config change on the
-// monitor cannot silently turn real gaps into bridges.
+/* A missed reading must render as a gap in the line, not a straight bridge
+ pretending the host was observed. The collector's cadence is not hardcoded
+ here; it is inferred from the readings themselves, so a config change on the
+ monitor cannot silently turn real gaps into bridges. */
const GAP_FACTOR = 2.5
/** The typical spacing between readings, or null below two readings. */
@@ -101,8 +101,8 @@ export const stallLimit = (plots: readonly HostPlot[]): number | null => {
const heldPoint = ({ plot, at }: { plot: HostPlot; at: number }): PlotPoint | null => {
const newest = plot.points[plot.points.length - 1]
if (newest === undefined || plot.holdLimitMs === null) return null
- // strictly past the newest reading: a hold stands in for a reading that has
- // not arrived and must never displace one that has
+ /* strictly past the newest reading: a hold stands in for a reading that has
+ not arrived and must never displace one that has */
return at > newest.at && at - newest.at <= plot.holdLimitMs ? { at, value: newest.value } : null
}
@@ -139,16 +139,16 @@ const carryForward = ({
const byMoment = new Map(points.map((point) => [point.at, point]))
/** What the host stands at for one moment of the run one reading opens. */
const held = ({ point, at }: { point: PlotPoint; at: number }): number | null =>
- // A reading always stands at its own moment, hold limit or not: a host with
- // a single reading has no observed cadence to hold against, and returning
- // null there dropped it off the chart entirely.
+ /* A reading always stands at its own moment, hold limit or not: a host with
+ a single reading has no observed cadence to hold against, and returning
+ null there dropped it off the chart entirely. */
point.at === at || (limit !== null && at - point.at <= limit) ? point.value : null
const runs = times.flatMap((at, index) => {
const point = byMoment.get(at)
return point === undefined ? [] : [{ index, point }]
})
- // Before the first reading the host has no value at all, which is not the
- // same as a value of zero.
+ /* Before the first reading the host has no value at all, which is not the
+ same as a value of zero. */
const unobserved = times.slice(0, runs[0]?.index ?? times.length).map(() => null)
return [
...unobserved,
@@ -173,8 +173,8 @@ const gapBreaks = (plots: readonly HostPlot[]): readonly number[] =>
? []
: plot.points.flatMap((point, index) => {
const next = plot.points[index + 1]
- // one past the limit, because the hold covers the limit itself: a
- // break placed exactly on it still carries a value and joins the line
+ /* one past the limit, because the hold covers the limit itself: a
+ break placed exactly on it still carries a value and joins the line */
const breakAt = point.at + limit + 1
return next && next.at > breakAt ? [breakAt] : []
})
@@ -212,10 +212,12 @@ export type DrawnFrame = {
/** Mutable, because Recharts takes its data that way, and built here so the
render does not have to copy it back out of a readonly one every pass. */
readonly rows: ChartRow[]
- /** The lines as drawn: readings plus each host's carried present. */
+ /** The lines as drawn: readings plus each host's carried present, for the
+ hosts the reader has left checked. */
readonly lines: readonly HostPlot[]
- /** The same hosts with observations only, which is what the legend names and
- the freshness readout counts. A carried point is not a reading. */
+ /** Every host, hidden ones included, with observations only: what the
+ legend names and the freshness readout counts. A carried point is not a
+ reading. */
readonly readings: readonly HostPlot[]
readonly ticks: readonly number[]
readonly scale: ChartScale
@@ -234,27 +236,31 @@ export const drawFrame = ({
nowMs,
span,
unit,
+ hidden,
}: {
plots: readonly HostPlot[]
nowMs: number
span: number
unit: MetricUnit
+ /** Hosts the reader unchecked: left off the plot and out of the axis
+ ceiling, but still named in the legend so they can be checked back on. */
+ hidden: readonly string[]
}): DrawnFrame => {
- // The drawn frame is [now - window, now]: a reading that ages past the window
- // slides off the left edge, and the space between the newest reading and the
- // right edge is the honest rendering of "nothing this recent yet".
+ /* The drawn frame is [now - window, now]: a reading that ages past the window
+ slides off the left edge, and the space between the newest reading and the
+ right edge is the honest rendering of "nothing this recent yet". */
const first = nowMs - span
const inFrame = (point: PlotPoint): boolean => point.at >= first && point.at <= nowMs
const clipToFrame = (plot: HostPlot): HostPlot => ({
...plot,
points: plot.points.filter(inFrame),
})
- // The newest reading before the left edge stays on the drawn line, so the
- // stroke enters from the edge instead of starting at the first reading
- // inside it: readings land a collector tick apart, and a line that began at
- // the first one left up to a tick of empty plot on the left. The x axis
- // allows overflow, so Recharts clips the stroke at the plot's edge and the
- // reading itself is never shown.
+ /* The newest reading before the left edge stays on the drawn line, so the
+ stroke enters from the edge instead of starting at the first reading
+ inside it: readings land a collector tick apart, and a line that began at
+ the first one left up to a tick of empty plot on the left. The x axis
+ allows overflow, so Recharts clips the stroke at the plot's edge and the
+ reading itself is never shown. */
const withLeadIn = (plot: HostPlot): HostPlot => {
const before = plot.points.filter((point) => point.at < first)
const lead = before[before.length - 1]
@@ -263,13 +269,20 @@ export const drawFrame = ({
points: [...(lead === undefined ? [] : [lead]), ...plot.points.filter(inFrame)],
}
}
- const lines = withHeld({ plots, at: nowMs }).map(withLeadIn)
+ const shown = plots.filter((plot) => !hidden.includes(plot.name))
+ const lines = withHeld({ plots: shown, at: nowMs }).map(withLeadIn)
+ /* every host, hidden or not: the legend names them all so a hidden one can
+ be checked back on */
const readings = plots.map(clipToFrame)
- // The axis is sized from what is on screen, not from the whole payload: a
- // spike that has already slid off the left edge must not keep the ceiling
- // high over a chart that no longer shows it, and the lead-in reading is off
- // screen by definition. A fixed-scale unit ignores the peak entirely.
- const peak = Math.max(0, ...readings.flatMap((plot) => plot.points.map((point) => point.value)))
+ /* The axis is sized from what is on screen, not from the whole payload: a
+ spike that has already slid off the left edge must not keep the ceiling
+ high over a chart that no longer shows it, the lead-in reading is off
+ screen by definition, and an unchecked line is not on screen at all. A
+ fixed-scale unit ignores the peak entirely. */
+ const peak = Math.max(
+ 0,
+ ...shown.map(clipToFrame).flatMap((plot) => plot.points.map((point) => point.value)),
+ )
return {
rows: [...toRows(lines)],
lines,
diff --git a/apps/admin-portal/src/pages/Fleet/metricScale.test.ts b/apps/admin-portal/src/pages/Fleet/metricScale.test.ts
index a816313..f22cc08 100644
--- a/apps/admin-portal/src/pages/Fleet/metricScale.test.ts
+++ b/apps/admin-portal/src/pages/Fleet/metricScale.test.ts
@@ -1,16 +1,20 @@
import { expect, test } from '@/test/vi'
import { formatRate, metricScale, niceCeiling } from '@/pages/Fleet/metricScale'
-test('a percent scale ignores the readings and stands at a fixed 0-100', () => {
- // a CPU chart whose ceiling moved with the busiest second would make a 4%
- // hour and a 90% hour draw identically
- const quiet = metricScale({ unit: 'percent', peak: 3 })
- const busy = metricScale({ unit: 'percent', peak: 97 })
+test('a percent scale is always the whole 0-100, so a full disk looks full', () => {
+ const disks = metricScale({ unit: 'percent', peak: 93.4 })
- expect(quiet.max).toBe(100)
- expect(busy.max).toBe(100)
- expect(quiet.ticks).toEqual([0, 25, 50, 75, 100])
- expect(quiet.format(42)).toBe('42%')
+ expect(disks.ticks).toEqual([0, 25, 50, 75, 100])
+ expect(disks.min).toBe(0)
+ expect(disks.max).toBe(100)
+ expect(disks.format(75)).toBe('75%')
+ // the tooltip prints through the same formatter and keeps the reading whole
+ expect(disks.format(89.21)).toBe('89.21%')
+})
+
+test('a quiet line and an empty chart get the same 0-100', () => {
+ expect(metricScale({ unit: 'percent', peak: 3 }).ticks).toEqual([0, 25, 50, 75, 100])
+ expect(metricScale({ unit: 'percent', peak: 0 }).ticks).toEqual([0, 25, 50, 75, 100])
})
test('a rate scale takes its ceiling from the readings, since bytes have none', () => {
@@ -30,8 +34,8 @@ test('a rate scale takes its ceiling from the readings, since bytes have none',
})
test('a rate axis leaves room its labels need and a percent axis does not', () => {
- // "125.0 MB/s" does not fit where "100%" does, and a label wider than its
- // margin is drawn over the plot
+ /* "125.0 MB/s" does not fit where "100%" does, and a label wider than its
+ margin is drawn over the plot */
expect(metricScale({ unit: 'bytes_per_second', peak: 1 }).axisWidth).toBeGreaterThan(
metricScale({ unit: 'percent', peak: 1 }).axisWidth,
)
@@ -39,8 +43,8 @@ test('a rate axis leaves room its labels need and a percent axis does not', () =
test('the axis widens with its widest label, so none is wrapped onto two lines', () => {
const MB = 1024 ** 2
- // "100.0 MB/s" is one character wider than "75.0 MB/s", and that character
- // is what Recharts broke the label at
+ /* "100.0 MB/s" is one character wider than "75.0 MB/s", and that character
+ is what Recharts broke the label at */
const wide = metricScale({ unit: 'bytes_per_second', peak: 100 * MB })
const narrow = metricScale({ unit: 'bytes_per_second', peak: 8 * MB })
@@ -52,17 +56,17 @@ test('the axis widens with its widest label, so none is wrapped onto two lines',
})
test('niceCeiling rounds up to a readable number rather than to the peak itself', () => {
- // under a kilobyte there is no binary unit to round inside, so this is plain
- // decimal rounding
+ /* under a kilobyte there is no binary unit to round inside, so this is plain
+ decimal rounding */
expect(niceCeiling(0.4)).toBe(0.5)
expect(niceCeiling(7)).toBe(10)
- // 2.5 earns its place: without it a 2.4 peak rounds to 5 and the chart
- // spends its whole top half empty
+ /* 2.5 earns its place: without it a 2.4 peak rounds to 5 and the chart
+ spends its whole top half empty */
expect(niceCeiling(2.4)).toBe(2.5)
})
-// A decimal ceiling over a 1024-based formatter is what produced axes reading
-// "610.4 KB/s": round before formatBytes divides by 1024, not after.
+/* A decimal ceiling over a 1024-based formatter is what produced axes reading
+ "610.4 KB/s": round before formatBytes divides by 1024, not after. */
test('niceCeiling rounds inside the unit the label will be printed in', () => {
expect(niceCeiling(1200)).toBe(2 * 1024)
expect(niceCeiling(1024 ** 2 * 2)).toBe(1024 ** 2 * 2)
@@ -71,8 +75,8 @@ test('niceCeiling rounds inside the unit the label will be printed in', () => {
})
test('niceCeiling refuses to return a zero-height axis', () => {
- // an axis from 0 to 0 has nothing to divide by, and every point on it would
- // be drawn at a coordinate of NaN
+ /* an axis from 0 to 0 has nothing to divide by, and every point on it would
+ be drawn at a coordinate of NaN */
expect(niceCeiling(0)).toBe(1)
expect(niceCeiling(-5)).toBe(1)
expect(niceCeiling(Number.NaN)).toBe(1)
diff --git a/apps/admin-portal/src/pages/Fleet/metricScale.ts b/apps/admin-portal/src/pages/Fleet/metricScale.ts
index f5d2629..3e22d6f 100644
--- a/apps/admin-portal/src/pages/Fleet/metricScale.ts
+++ b/apps/admin-portal/src/pages/Fleet/metricScale.ts
@@ -1,12 +1,15 @@
import { axisWidthFor, quarterTicks, type ChartScale } from '@/components/Chart/chartScale'
import { formatBytes, type MetricUnit } from '@/lib/fleetApi'
-// Ceilings worth landing on. 2.5 earns its place between 2 and 5: without it a
-// 2.4 MB/s peak rounds all the way up to 5 and spends the chart's whole top
-// half empty.
+/* Ceilings worth landing on. 2.5 earns its place between 2 and 5: without it a
+ 2.4 MB/s peak rounds all the way up to 5 and spends the chart's whole top
+ half empty. */
const NICE_STEPS = [1, 2, 2.5, 5, 10] as const
-const formatPercent = (value: number): string => `${value}%`
+/** A percentage to at most two decimals, trailing zeros dropped: the axis lands
+ on round steps and prints "90%", while a tooltip over a disk reading still
+ shows the "89.21%" it was given. */
+const formatPercent = (value: number): string => `${Number(value.toFixed(2))}%`
/** Bytes per second in words. Zero is "0", not "0.0 B/s": an axis origin needs
no unit, and the long form crowds the label off the plot. */
@@ -44,8 +47,9 @@ export const niceCeiling = (peak: number): number => {
}
/** A metric family's y axis. A percent runs against a fixed 0-100 whatever the
- readings do; a throughput has no natural ceiling at all and takes one from
- the readings in view. */
+ readings do, so a line's height is the share itself and a full disk looks
+ full; a throughput has no natural ceiling at all and takes one from the
+ busiest reading in view. */
export const metricScale = ({ unit, peak }: { unit: MetricUnit; peak: number }): ChartScale => {
const percent = unit === 'percent'
const max = percent ? 100 : niceCeiling(peak)
diff --git a/apps/admin-portal/src/stores/fleetPrefsStore.test.ts b/apps/admin-portal/src/stores/fleetPrefsStore.test.ts
index ce8f762..7f27881 100644
--- a/apps/admin-portal/src/stores/fleetPrefsStore.test.ts
+++ b/apps/admin-portal/src/stores/fleetPrefsStore.test.ts
@@ -3,17 +3,19 @@ import {
CPU_RANGES,
DEFAULT_RANGE_MINUTES,
DEFAULT_UPDATE_INTERVAL_MS,
+ NO_HIDDEN_HOSTS,
rangeProse,
UPDATE_INTERVAL_STOPS_MS,
useFleetPrefsStore,
} from '@/stores/fleetPrefsStore'
-// The store is a module singleton and the suite shares one localStorage, so
-// every test hands back the defaults it started from.
+/* The store is a module singleton and the suite shares one localStorage, so
+ every test hands back the defaults it started from. */
afterEach(() => {
useFleetPrefsStore.setState({
updateIntervalMs: DEFAULT_UPDATE_INTERVAL_MS,
rangeMinutes: DEFAULT_RANGE_MINUTES,
+ hiddenHosts: NO_HIDDEN_HOSTS,
})
localStorage.removeItem('wz-fleet-prefs')
})
@@ -60,8 +62,8 @@ test('a stale persisted value rehydrates as the default, never an arbitrary rate
})
test('the ranges run from a week down to a quarter hour, widest first', () => {
- // a week is the monitor's own ceiling: raw samples are pruned at seven days,
- // so anything wider could only answer with less
+ /* a week is the monitor's own ceiling: raw samples are pruned at seven days,
+ so anything wider could only answer with less */
expect(CPU_RANGES.map((range) => range.minutes)).toEqual([10_080, 4320, 1440, 720, 360, 60, 15])
expect(DEFAULT_RANGE_MINUTES).toBe(60)
})
@@ -95,3 +97,30 @@ test('a persisted range survives rehydration alongside the interval', async () =
expect(useFleetPrefsStore.getState().rangeMinutes).toBe(720)
expect(useFleetPrefsStore.getState().updateIntervalMs).toBe(2000)
})
+
+test('a host is hidden on one chart only, and toggling again shows it', () => {
+ const { toggleHost } = useFleetPrefsStore.getState()
+
+ toggleHost({ kind: 'disk', name: 'vhagar' })
+ expect(useFleetPrefsStore.getState().hiddenHosts).toEqual({
+ ...NO_HIDDEN_HOSTS,
+ disk: ['vhagar'],
+ })
+
+ toggleHost({ kind: 'disk', name: 'vhagar' })
+ expect(useFleetPrefsStore.getState().hiddenHosts).toEqual(NO_HIDDEN_HOSTS)
+})
+
+test('hidden hosts survive rehydration, and a malformed entry is dropped', async () => {
+ localStorage.setItem(
+ 'wz-fleet-prefs',
+ JSON.stringify({
+ state: { hiddenHosts: { cpu: ['meleys'], disk: 'vhagar', nonsense: ['syrax'] } },
+ version: 0,
+ }),
+ )
+
+ await useFleetPrefsStore.persist.rehydrate()
+
+ expect(useFleetPrefsStore.getState().hiddenHosts).toEqual({ ...NO_HIDDEN_HOSTS, cpu: ['meleys'] })
+})
diff --git a/apps/admin-portal/src/stores/fleetPrefsStore.ts b/apps/admin-portal/src/stores/fleetPrefsStore.ts
index 278951c..6ca0791 100644
--- a/apps/admin-portal/src/stores/fleetPrefsStore.ts
+++ b/apps/admin-portal/src/stores/fleetPrefsStore.ts
@@ -53,6 +53,46 @@ const isRange = (value: unknown): value is number =>
const isChartKind = (value: unknown): value is MetricKind =>
CHART_KINDS.some((kind) => kind === value)
+/** The hosts each chart has been told to leave out, by host name. */
+export type HiddenHosts = Readonly>
+
+/** Every chart showing every host. A list per chart from the start, so a
+ reader never has to tell "nothing hidden" from "never asked". */
+export const NO_HIDDEN_HOSTS: HiddenHosts = { cpu: [], memory: [], network: [], disk: [], gpu: [] }
+
+const isNameList = (value: unknown): value is readonly string[] =>
+ Array.isArray(value) && value.every((name) => typeof name === 'string')
+
+/** What came back from storage, kept only where it is a chart this build has
+ and a list of names. A host name that no longer exists is harmless: it
+ matches no line and is never drawn as hidden. */
+const storedHiddenHosts = (value: unknown): HiddenHosts =>
+ isRecord(value)
+ ? CHART_KINDS.reduce((kept, kind) => {
+ const names = value[kind]
+ return isNameList(names) ? { ...kept, [kind]: names } : kept
+ }, NO_HIDDEN_HOSTS)
+ : NO_HIDDEN_HOSTS
+
+/** One host's line shown or hidden on one chart. */
+const toggled = ({
+ hidden,
+ kind,
+ name,
+}: {
+ hidden: HiddenHosts
+ kind: MetricKind
+ name: string
+}): HiddenHosts => {
+ const current = hidden[kind]
+ return {
+ ...hidden,
+ [kind]: current.includes(name)
+ ? current.filter((hiddenName) => hiddenName !== name)
+ : [...current, name],
+ }
+}
+
type FleetPrefsState = {
readonly updateIntervalMs: number
readonly setUpdateIntervalMs: (intervalMs: number) => void
@@ -62,6 +102,11 @@ type FleetPrefsState = {
one request per interval however many charts exist. */
readonly chartKind: MetricKind
readonly setChartKind: (kind: MetricKind) => void
+ /** Lines the reader unchecked, per chart. Per chart rather than one list for
+ all of them, because a host worth hiding on one (a GPU line pinned at its
+ floor) is often the one worth watching on another. */
+ readonly hiddenHosts: HiddenHosts
+ readonly toggleHost: (toggle: { kind: MetricKind; name: string }) => void
}
/** The fleet page's own knobs, persisted so a refresh keeps them.
@@ -82,6 +127,9 @@ export const useFleetPrefsStore = create()(
set({ rangeMinutes: isRange(minutes) ? minutes : DEFAULT_RANGE_MINUTES }),
chartKind: DEFAULT_CHART_KIND,
setChartKind: (kind) => set({ chartKind: isChartKind(kind) ? kind : DEFAULT_CHART_KIND }),
+ hiddenHosts: NO_HIDDEN_HOSTS,
+ toggleHost: ({ kind, name }) =>
+ set((state) => ({ hiddenHosts: toggled({ hidden: state.hiddenHosts, kind, name }) })),
}),
{
name: 'wz-fleet-prefs',
@@ -94,6 +142,7 @@ export const useFleetPrefsStore = create()(
: current.updateIntervalMs,
rangeMinutes: isRange(stored.rangeMinutes) ? stored.rangeMinutes : current.rangeMinutes,
chartKind: isChartKind(stored.chartKind) ? stored.chartKind : current.chartKind,
+ hiddenHosts: storedHiddenHosts(stored.hiddenHosts),
}
},
},
diff --git a/apps/fleet-monitor/src/api/api.test.ts b/apps/fleet-monitor/src/api/api.test.ts
index 6648433..31cc33d 100644
--- a/apps/fleet-monitor/src/api/api.test.ts
+++ b/apps/fleet-monitor/src/api/api.test.ts
@@ -1,11 +1,11 @@
-// The fleet routes over HTTP: /health, /fleet, the four histories and
-// /incidents, driven through `inject` against the app main.ts serves.
-//
-// What the /fleet body means is pinned case by case in src/fleet.test.ts,
-// directly on fleetView; the cases here are the same ones through the route,
-// which is what the Python suite tested. The eight Python tests on the pure
-// helpers (core_count, host_state, memory_used_percent) never touched a route
-// and live in src/fleet.test.ts alone.
+/* The fleet routes over HTTP: /health, /fleet, the four histories and
+ /incidents, driven through `inject` against the app main.ts serves.
+
+ What the /fleet body means is pinned case by case in src/fleet.test.ts,
+ directly on fleetView; the cases here are the same ones through the route,
+ which is what the Python suite tested. The eight Python tests on the pure
+ helpers (core_count, host_state, memory_used_percent) never touched a route
+ and live in src/fleet.test.ts alone. */
import { existsSync } from 'node:fs'
import type { NestFastifyApplication } from '@nestjs/platform-fastify'
@@ -32,9 +32,9 @@ import {
} from '@wizteros/wire'
import { z } from 'zod'
-// A host also carries the raw `metrics` map, which the portal does not read
-// and the Python tests asserted on, so these tests check it on top of the
-// shared schema rather than the schema growing a field no reader has.
+/* A host also carries the raw `metrics` map, which the portal does not read
+ and the Python tests asserted on, so these tests check it on top of the
+ shared schema rather than the schema growing a field no reader has. */
const fleetHostWithMetricsSchema = fleetHostSchema.extend({
metrics: z.record(z.string(), z.number()),
})
@@ -62,9 +62,9 @@ const gauge = (metric: string, value: number): Sample => ({ metric, value })
const counter = (metric: string, value: number): Sample => ({ metric, value })
-// One session per write, the same way a collector round opens one. store and
-// incidents take a connection, and the API under test opens its own, so a
-// test seeding state has to commit through a session of its own.
+/* One session per write, the same way a collector round opens one. store and
+ incidents take a connection, and the API under test opens its own, so a
+ test seeding state has to commit through a session of its own. */
const writeSamplesTo = ({
path,
target,
@@ -187,11 +187,11 @@ describe('the fleet API', () => {
bodyOf({ answer: await get(url), schema: metricHistorySchema })
it('answers cross-origin requests', async () => {
- // The portal is served from a different origin than this API everywhere
- // it runs: the Vite dev server in development, the deployed portal
- // against vermithor:8010 in production. Without CORS headers the browser
- // discards the response and the /fleet page reports "Failed to fetch"
- // against a perfectly healthy API.
+ /* The portal is served from a different origin than this API everywhere
+ it runs: the Vite dev server in development, the deployed portal
+ against vermithor:8010 in production. Without CORS headers the browser
+ discards the response and the /fleet page reports "Failed to fetch"
+ against a perfectly healthy API. */
const response = await get('/fleet', { origin: 'http://localhost:5173' })
expect(response.statusCode).toBe(200)
expect(response.headers['access-control-allow-origin']).toBe('*')
@@ -278,9 +278,9 @@ describe('the fleet API', () => {
const body = await fleet()
const caraxes = hostNamed(body, 'caraxes')
- // the collector is alive and the fast tier is current, so the fleet-wide
- // heartbeat flag reads fresh; only the per-host metric age catches the
- // slow tier that died six hours ago behind it
+ /* the collector is alive and the fast tier is current, so the fleet-wide
+ heartbeat flag reads fresh; only the per-host metric age catches the
+ slow tier that died six hours ago behind it */
expect(body.stale).toBe(false)
expect(caraxes.collected).toBe(true)
expect(caraxes.metrics_stale).toBe(true)
@@ -288,12 +288,12 @@ describe('the fleet API', () => {
})
it('never reports a reading it cannot date', async () => {
- // the slow tier (disk, temperatures) died a week ago while the fast tier
- // kept reporting. Samples live seven days and the age window is a day, so
- // the disk reading outlived the only thing that could date it: it dropped
- // out of metric_ages, `metrics_stale` went false on the strength of the
- // fresh load reading, and the card printed a bare "Healthy" over a
- // seven-day-old disk number with no stale note anywhere.
+ /* the slow tier (disk, temperatures) died a week ago while the fast tier
+ kept reporting. Samples live seven days and the age window is a day, so
+ the disk reading outlived the only thing that could date it: it dropped
+ out of metric_ages, `metrics_stale` went false on the strength of the
+ fresh load reading, and the card printed a bare "Healthy" over a
+ seven-day-old disk number with no stale note anywhere. */
const now = new Date()
writeHeartbeatTo({ path: db, at: now })
writeSamplesTo({ path: db, target: 'host:caraxes', at: now, samples: [gauge('load.1m', 0.1)] })
@@ -314,10 +314,10 @@ describe('the fleet API', () => {
})
it('dates every reading it reports', async () => {
- // the invariant behind the case above, stated directly: `metrics` and the
- // age computation must always describe the same set. A metric visible to
- // one and invisible to the other is a value on the page with no age
- // accounted for anywhere.
+ /* the invariant behind the case above, stated directly: `metrics` and the
+ age computation must always describe the same set. A metric visible to
+ one and invisible to the other is a value on the page with no age
+ accounted for anywhere. */
const now = new Date()
writeHeartbeatTo({ path: db, at: now })
const offsets: readonly (readonly [number, string])[] = [
@@ -346,9 +346,9 @@ describe('the fleet API', () => {
})
it('stops reporting a container removed days ago as up', async () => {
- // same mechanism, different surface: container..up is a sample like
- // any other, so a container removed more than a day ago kept its last "1"
- // and the card kept rendering it "Up" indefinitely
+ /* same mechanism, different surface: container..up is a sample like
+ any other, so a container removed more than a day ago kept its last "1"
+ and the card kept rendering it "Up" indefinitely */
const now = new Date()
writeHeartbeatTo({ path: db, at: now })
writeSamplesTo({ path: db, target: 'host:meleys', at: now, samples: [gauge('load.1m', 0.2)] })
@@ -364,9 +364,9 @@ describe('the fleet API', () => {
})
it('marks a host whose every reading aged out as not collected', async () => {
- // rows exist for this host, all of them older than the age window. That
- // is neither fresh nor never-collected, and the card's "no current
- // readings" copy is written for exactly this: not collected *now*.
+ /* rows exist for this host, all of them older than the age window. That
+ is neither fresh nor never-collected, and the card's "no current
+ readings" copy is written for exactly this: not collected *now*. */
const now = new Date()
writeHeartbeatTo({ path: db, at: now })
writeSamplesTo({
@@ -392,9 +392,9 @@ describe('the fleet API', () => {
})
it('drops a metric source that stopped producing', async () => {
- // a veth renamed by a container restart is written once and never again.
- // Counted forever it pins metrics_stale true on a healthy docker host and
- // walks stalest_family_age_seconds up to seven days.
+ /* a veth renamed by a container restart is written once and never again.
+ Counted forever it pins metrics_stale true on a healthy docker host and
+ walks stalest_family_age_seconds up to seven days. */
const now = new Date()
writeHeartbeatTo({ path: db, at: now })
writeSamplesTo({
@@ -416,11 +416,11 @@ describe('the fleet API', () => {
})
it('ignores a vanished source beside a live sibling', async () => {
- // meleys, 2026-08-26: DSM brought up a VPN tun1000 for one hour, and its
- // two counters froze when it went away. The age window is a day and the
- // stale band is 45 minutes, so under a plain `min` over every metric those
- // two dead readings reported the host stale for the next 23 hours while
- // net.eth0.* beside them updated every 30 seconds.
+ /* meleys, 2026-08-26: DSM brought up a VPN tun1000 for one hour, and its
+ two counters froze when it went away. The age window is a day and the
+ stale band is 45 minutes, so under a plain `min` over every metric those
+ two dead readings reported the host stale for the next 23 hours while
+ net.eth0.* beside them updated every 30 seconds. */
const now = new Date()
writeHeartbeatTo({ path: db, at: now })
writeSamplesTo({
@@ -437,19 +437,19 @@ describe('the fleet API', () => {
})
const meleys = hostNamed(await fleet(), 'meleys')
- // the family is reporting, so the host is not stale on the strength of
- // one source that went away inside it
+ /* the family is reporting, so the host is not stale on the strength of
+ one source that went away inside it */
expect(meleys.metrics_stale).toBe(false)
expect(meleys.stalest_family_age_seconds).toBeLessThan(60)
- // and the dead counter is still a reading the monitor will hand back: it
- // is excluded from the staleness judgment, not hidden
+ /* and the dead counter is still a reading the monitor will hand back: it
+ is excluded from the staleness judgment, not hidden */
expect(meleys.metrics['net.tun1000.rx_bytes']).toBe(900.0)
})
it('still flags a family that went silent whole', async () => {
- // the other half of the same rule. Ignoring a vanished source must not
- // ignore a probe that stopped: when every metric under `disk` is old, no
- // sibling is left to vouch for it and the host is stale.
+ /* the other half of the same rule. Ignoring a vanished source must not
+ ignore a probe that stopped: when every metric under `disk` is old, no
+ sibling is left to vouch for it and the host is stale. */
const now = new Date()
writeHeartbeatTo({ path: db, at: now })
writeSamplesTo({
@@ -466,8 +466,8 @@ describe('the fleet API', () => {
})
it('names the family that fell silent', async () => {
- // the page prints this word. Without it the card blamed disk and
- // temperature whatever had actually stopped.
+ /* the page prints this word. Without it the card blamed disk and
+ temperature whatever had actually stopped. */
const now = new Date()
writeHeartbeatTo({ path: db, at: now })
writeSamplesTo({
@@ -483,10 +483,10 @@ describe('the fleet API', () => {
})
it('reports no uptime for a window the collector did not watch', async () => {
- // the collector has been up for one round. Nothing observed the other 24
- // hours, and an empty incident history over unwatched hours is not proof
- // of uptime, so the honest answer is null, which the card reads as
- // "Unknown" rather than a perfect score.
+ /* the collector has been up for one round. Nothing observed the other 24
+ hours, and an empty incident history over unwatched hours is not proof
+ of uptime, so the honest answer is null, which the card reads as
+ "Unknown" rather than a perfect score. */
const now = new Date()
writeHeartbeatTo({ path: db, at: now })
writeSamplesTo({ path: db, target: 'host:caraxes', at: now, samples: [gauge('load.1m', 0.1)] })
@@ -502,9 +502,9 @@ describe('the fleet API', () => {
// the collector ticking across the window, which on its own is not enough
writeHeartbeatTo({ path: db, at: dayAndAnHourAgo })
writeHeartbeatTo({ path: db, at: now })
- // and the host itself checked across that run, not merely the collector
- // ticking beside it. A round that recorded no check for this host
- // observed the fleet, not the host.
+ /* and the host itself checked across that run, not merely the collector
+ ticking beside it. A round that recorded no check for this host
+ observed the fleet, not the host. */
watched({ db, target: 'host:caraxes', since: dayAndAnHourAgo, until: now, gap: 2 * DAY })
writeSamplesTo({ path: db, target: 'host:caraxes', at: now, samples: [gauge('load.1m', 0.1)] })
const caraxes = hostNamed(await fleet(), 'caraxes')
@@ -513,17 +513,17 @@ describe('the fleet API', () => {
})
it('reports no uptime for a host the collector stopped checking', async () => {
- // a persistent spawn_error: ssh cannot be started, so no host check is
- // recorded, while the collector keeps ticking and the docker endpoints
- // beside it keep recording failures. The collector-wide coverage mark ran
- // on unbroken through hours in which not one host was observed, and
- // scored them a flawless 100%.
+ /* a persistent spawn_error: ssh cannot be started, so no host check is
+ recorded, while the collector keeps ticking and the docker endpoints
+ beside it keep recording failures. The collector-wide coverage mark ran
+ on unbroken through hours in which not one host was observed, and
+ scored them a flawless 100%. */
const now = new Date()
const sixHoursAgo = addSeconds({ at: now, seconds: -6 * HOUR })
writeHeartbeatTo({ path: db, at: addSeconds({ at: now, seconds: -25 * HOUR }) })
writeHeartbeatTo({ path: db, at: now })
- // checks for this host stop six hours ago; its readings are still inside
- // the age window, so the card is still showing numbers
+ /* checks for this host stop six hours ago; its readings are still inside
+ the age window, so the card is still showing numbers */
watched({
db,
target: 'host:caraxes',
@@ -544,9 +544,9 @@ describe('the fleet API', () => {
})
it('never reads a future timestamp as fresh', async () => {
- // a clock that stepped backwards leaves rows stamped ahead of now. A
- // negative age clears every staleness threshold, so the page would show
- // frozen values and affirmatively call them current.
+ /* a clock that stepped backwards leaves rows stamped ahead of now. A
+ negative age clears every staleness threshold, so the page would show
+ frozen values and affirmatively call them current. */
const ahead = addSeconds({ at: new Date(), seconds: 6 * HOUR })
writeHeartbeatTo({ path: db, at: ahead })
writeSamplesTo({
@@ -572,8 +572,8 @@ describe('the fleet API', () => {
})
it('rejects a negative incident window', async () => {
- // bounded above but not below: an extreme negative still overflowed the
- // timedelta into an unhandled 500 instead of a client error
+ /* bounded above but not below: an extreme negative still overflowed the
+ timedelta into an unhandled 500 instead of a client error */
expect((await get('/incidents?hours=-999999999999999999')).statusCode).toBe(422)
expect((await get('/incidents?hours=0')).statusCode).toBe(422)
})
@@ -642,9 +642,9 @@ describe('the fleet API', () => {
})
it('reports the volume free space and its mount', async () => {
- // the card prints "{free} free" beside "/volume1 · of {total}", and both
- // facts belong to the monitor: the SPA must not hardcode which volume the
- // collector watches, nor derive free space from a rounded percentage
+ /* the card prints "{free} free" beside "/volume1 · of {total}", and both
+ facts belong to the monitor: the SPA must not hardcode which volume the
+ collector watches, nor derive free space from a rounded percentage */
const now = new Date()
writeHeartbeatTo({ path: db, at: now })
writeSamplesTo({
@@ -665,8 +665,8 @@ describe('the fleet API', () => {
})
it('reports absent free space as absent', async () => {
- // a host that has not reported the reading, or was never collected at
- // all, carries null rather than a number invented from the percentage
+ /* a host that has not reported the reading, or was never collected at
+ all, carries null rather than a number invented from the percentage */
const now = new Date()
writeHeartbeatTo({ path: db, at: now })
writeSamplesTo({
@@ -734,8 +734,8 @@ describe('the fleet API', () => {
})
it('lists cpu hosts in the same order as /fleet', async () => {
- // the portal binds one color per host by array position, on the cards
- // from /fleet and on the chart from here; the two must never disagree
+ /* the portal binds one color per host by array position, on the cards
+ from /fleet and on the chart from here; the two must never disagree */
const fleetNames = (await fleet()).hosts.map((host) => host.name)
const cpuNames = (await history('/fleet/cpu')).hosts.map((host) => host.name)
@@ -771,8 +771,8 @@ describe('the fleet API', () => {
})
it('accepts a week of cpu and refuses more', async () => {
- // raw samples live seven days, so a week is the widest window that can be
- // answered with readings rather than with silence
+ /* raw samples live seven days, so a week is the widest window that can be
+ answered with readings rather than with silence */
expect((await get('/fleet/cpu?minutes=10080')).statusCode).toBe(200)
expect((await get('/fleet/cpu?minutes=10081')).statusCode).toBe(422)
})
@@ -813,7 +813,7 @@ describe('the fleet API', () => {
expect(byName.meleys).toEqual([])
})
- it('reports free disk percent on the disk route', async () => {
+ it('reports used disk percent on the disk route', async () => {
writeSamplesTo({
path: db,
target: 'host:meleys',
@@ -829,7 +829,7 @@ describe('the fleet API', () => {
expect(payload.kind).toBe('disk')
expect(payload.unit).toBe('percent')
const byName = pointsByName(payload)
- expect(values(byName.meleys)).toEqual([25.0])
+ expect(values(byName.meleys)).toEqual([75.0])
// a host that reported no disk gauges has no points, not zeros
expect(byName.vermithor).toEqual([])
})
@@ -857,8 +857,8 @@ describe('the fleet API', () => {
})
it('reads only this target and only net metrics on the network route', async () => {
- // the prefix read is a range scan over the metric column, so a
- // neighbouring family (or another host's counters) must not fall inside it
+ /* the prefix read is a range scan over the metric column, so a
+ neighbouring family (or another host's counters) must not fall inside it */
const now = new Date()
const ticks: readonly (readonly [number, number])[] = [
[40, 0.0],
@@ -891,8 +891,8 @@ describe('the fleet API', () => {
})
it('lists hosts in the same order as /fleet on every history route', async () => {
- // one colour per host position, bound on the cards from /fleet and on
- // every chart from these; a route disagreeing would recolour a whole chart
+ /* one colour per host position, bound on the cards from /fleet and on
+ every chart from these; a route disagreeing would recolour a whole chart */
const fleetNames = (await fleet()).hosts.map((host) => host.name)
const routes = await Promise.all(
@@ -905,8 +905,8 @@ describe('the fleet API', () => {
})
it('shares one window contract on every history route', async () => {
- // the page drives all four from one range picker, so a route with its own
- // floor or ceiling would fail only at the extremes of that control
+ /* the page drives all four from one range picker, so a route with its own
+ floor or ceiling would fail only at the extremes of that control */
const routes = await Promise.all(
HISTORY_ROUTES.map(async (path) => ({
path,
@@ -932,11 +932,11 @@ describe('the fleet API on a fresh volume', () => {
})
it('creates its own schema on startup', async () => {
- // every other test in this file creates the schema itself, which masks
- // whether anything in the API ever did. Opening a SQLite file happily
- // creates an empty one, so against a fresh FM_DB_PATH the first query
- // raised "no such table: heartbeat" and answered 500. Starting the app is
- // exactly what is under test.
+ /* every other test in this file creates the schema itself, which masks
+ whether anything in the API ever did. Opening a SQLite file happily
+ creates an empty one, so against a fresh FM_DB_PATH the first query
+ raised "no such table: heartbeat" and answered 500. Starting the app is
+ exactly what is under test. */
const db = tempDbPath()
expect(existsSync(db)).toBe(false)
vi.stubEnv('FM_DB_PATH', db)
diff --git a/apps/fleet-monitor/src/api/fleetController.ts b/apps/fleet-monitor/src/api/fleetController.ts
index a31a127..d0f34e7 100644
--- a/apps/fleet-monitor/src/api/fleetController.ts
+++ b/apps/fleet-monitor/src/api/fleetController.ts
@@ -9,23 +9,23 @@ import { history, type Incident, openIncidents } from '@/incidents.js'
import { fleetHistory, type Kind, type MetricHistoryView } from '@/series.js'
import { lastHeartbeat } from '@/store.js'
-// Liveness, the fleet, its charts and its incidents. Every route opens one
-// session for its whole response, and in `read` mode: the API never writes the
-// main database, so a request must never make the collector wait for the
-// write lock.
-
-// Generous but bounded, well under what a Date can represent. Without a cap
-// an absurd `hours` value overflowed the C int Python's `timedelta` builds
-// from and turned into an unhandled 500 instead of a client error.
+/* Liveness, the fleet, its charts and its incidents. Every route opens one
+ session for its whole response, and in `read` mode: the API never writes the
+ main database, so a request must never make the collector wait for the
+ write lock. */
+
+/* Generous but bounded, well under what a Date can represent. Without a cap
+ an absurd `hours` value overflowed the C int Python's `timedelta` builds
+ from and turned into an unhandled 500 instead of a client error. */
export const MAX_INCIDENT_HOURS = 24 * 365 * 5
-// The history window every chart shares. The floor is one vitals tick past
-// nothing (a counter-derived series yields no delta from a single reading, so
-// anything shorter cannot answer); the ceiling is seven days, which is how
-// long raw samples live before store.prune takes them, so asking for more
-// could only ever answer with less. Windows past a few hours carry more ticks
-// than a chart can draw, so the series is bucketed on the way out rather than
-// the window being refused.
+/* The history window every chart shares. The floor is one vitals tick past
+ nothing (a counter-derived series yields no delta from a single reading, so
+ anything shorter cannot answer); the ceiling is seven days, which is how
+ long raw samples live before store.prune takes them, so asking for more
+ could only ever answer with less. Windows past a few hours carry more ticks
+ than a chart can draw, so the series is bucketed on the way out rather than
+ the window being refused. */
export const DEFAULT_HISTORY_MINUTES = 60
export const MAX_HISTORY_MINUTES = 7 * 24 * 60
@@ -142,7 +142,7 @@ export class FleetController {
return metricHistory({ kind: 'network', minutes: query.minutes })
}
- /** Free space on the watched volume per host, as a percent of its size. */
+ /** Used space on the watched volume per host, as a percent of its size. */
@Get('fleet/disk')
disk(@Query({ schema: HistoryQuery }) query: z.infer): MetricHistoryView {
return metricHistory({ kind: 'disk', minutes: query.minutes })
diff --git a/apps/fleet-monitor/src/series.test.ts b/apps/fleet-monitor/src/series.test.ts
index 4507b35..db8d1fa 100644
--- a/apps/fleet-monitor/src/series.test.ts
+++ b/apps/fleet-monitor/src/series.test.ts
@@ -5,7 +5,7 @@ import type { Sample } from '@/probes/types.js'
import {
FAMILIES,
MAX_POINTS,
- diskAvailableSeries,
+ diskUsedSeries,
downsample,
fleetHistory,
gpuLoadSeries,
@@ -25,16 +25,16 @@ const at = (seconds: number): Date => addSeconds({ at: T0, seconds })
describe('FAMILIES', () => {
it('declares either names or a prefix for every family', () => {
- // a family with neither would read nothing and draw an empty chart with no
- // error anywhere; with both, the prefix silently wins in history
+ /* a family with neither would read nothing and draw an empty chart with no
+ error anywhere; with both, the prefix silently wins in history */
Object.values(FAMILIES).forEach((family) => {
expect(family.metrics.length > 0, family.kind).not.toBe(!!family.prefix)
})
})
it('keys each family by the kind it carries', () => {
- // the kind travels to the browser on every response, so a key that
- // disagreed with it would label one chart with another's name
+ /* the kind travels to the browser on every response, so a key that
+ disagreed with it would label one chart with another's name */
Object.entries(FAMILIES).forEach(([key, family]) => {
expect(key).toBe(family.kind)
})
@@ -43,9 +43,9 @@ describe('FAMILIES', () => {
// --- disk --------------------------------------------------------------
-describe('diskAvailableSeries', () => {
- it('reports available over total as a percentage', () => {
- const points = diskAvailableSeries({
+describe('diskUsedSeries', () => {
+ it('reports size less available over size as a percentage', () => {
+ const points = diskUsedSeries({
'disk.volume1.total_bytes': [
[at(0), 40 * GB],
[at(300), 40 * GB],
@@ -57,13 +57,22 @@ describe('diskAvailableSeries', () => {
})
expect(points).toEqual([
- [at(0), 25],
- [at(300), 10],
+ [at(0), 75],
+ [at(300), 90],
])
})
+ it('keeps two decimals, so a few gigabytes on a large volume still move the line', () => {
+ const points = diskUsedSeries({
+ 'disk.volume1.total_bytes': [[at(0), 1000 * GB]],
+ 'disk.volume1.available_bytes': [[at(0), 123.4 * GB]],
+ })
+
+ expect(points).toEqual([[at(0), 87.66]])
+ })
+
it('drops a moment it cannot judge', () => {
- const points = diskAvailableSeries({
+ const points = diskUsedSeries({
'disk.volume1.total_bytes': [
[at(0), 0],
[at(300), 40 * GB],
@@ -73,12 +82,12 @@ describe('diskAvailableSeries', () => {
'disk.volume1.available_bytes': [
[at(0), 0],
[at(300), 41 * GB],
- [at(900), 20 * GB],
+ [at(900), 30 * GB],
],
})
// a zero total, free space past the volume, and a total read alone
- expect(points).toEqual([[at(900), 50]])
+ expect(points).toEqual([[at(900), 25]])
})
})
@@ -104,8 +113,8 @@ describe('memoryUsedSeries', () => {
})
it('drops a moment missing either gauge', () => {
- // both come from one /proc/meminfo read, so a moment carrying only one of
- // them is a bad read; pairing it with a neighbour would invent a reading
+ /* both come from one /proc/meminfo read, so a moment carrying only one of
+ them is a bad read; pairing it with a neighbour would invent a reading */
const points = memoryUsedSeries({
'mem.total_bytes': [
[at(0), 8 * GB],
@@ -159,8 +168,8 @@ describe('gpuLoadSeries', () => {
})
it('clamps a card reporting past its own ceiling', () => {
- // pegged is a real state worth seeing; dropping it would hide the one
- // moment on the chart that mattered
+ /* pegged is a real state worth seeing; dropping it would hide the one
+ moment on the chart that mattered */
const points = gpuLoadSeries({ 'gpu.freq_ratio': [[at(0), 1.4]] })
expect(points).toEqual([[at(0), 100]] satisfies Series)
@@ -171,8 +180,8 @@ describe('gpuLoadSeries', () => {
})
it('is empty on a host with no render node', () => {
- // three of the five boxes have no /dev/dri at all; an empty series draws a
- // legend entry with no line rather than a flat line along the axis
+ /* three of the five boxes have no /dev/dri at all; an empty series draws a
+ legend entry with no line rather than a flat line along the axis */
expect(gpuLoadSeries({})).toEqual([])
})
})
@@ -197,8 +206,8 @@ describe('networkThroughputSeries', () => {
})
it('drops the pair a reboot zeroed', () => {
- // a counter that went backwards is a reset, and rendering the delta would
- // be a spike that never happened
+ /* a counter that went backwards is a reset, and rendering the delta would
+ be a spike that never happened */
const points = networkThroughputSeries({
'net.eth0.rx_bytes': [
[at(0), 5000],
@@ -232,8 +241,8 @@ describe('downsample', () => {
})
it('averages each bucket and dates it by its last reading', () => {
- // 4 readings over 4 seconds into 2 buckets: each point keeps a real
- // reading's timestamp, and its value is the mean of that bucket
+ /* 4 readings over 4 seconds into 2 buckets: each point keeps a real
+ reading's timestamp, and its value is the mean of that bucket */
const points: Series = [
[at(0), 10],
[at(1), 20],
@@ -248,8 +257,8 @@ describe('downsample', () => {
})
it('drops empty buckets instead of filling them', () => {
- // a hole wider than a bucket stays a hole: nothing is emitted for the
- // seconds nothing was read, so the chart still breaks the line there
+ /* a hole wider than a bucket stays a hole: nothing is emitted for the
+ seconds nothing was read, so the chart still breaks the line there */
const points: Series = [
[at(0), 10],
[at(1), 20],
@@ -264,8 +273,8 @@ describe('downsample', () => {
})
it("bounds a week's worth of ticks", () => {
- // a week of 30s ticks is 20k points; whatever the window, the answer stays
- // small enough for a browser to parse and an svg to draw
+ /* a week of 30s ticks is 20k points; whatever the window, the answer stays
+ small enough for a browser to parse and an svg to draw */
const week = 7 * 24 * 3600
const points: Series = Array.from(
{ length: week / 30 },
@@ -277,14 +286,14 @@ describe('downsample', () => {
)
})
- // The two below have no Python counterpart. They pin the port to what the
- // Python served where JS arithmetic alone would part from it; both expected
- // answers were computed by running series.downsample itself.
+ /* The two below have no Python counterpart. They pin the port to what the
+ Python served where JS arithmetic alone would part from it; both expected
+ answers were computed by running series.downsample itself. */
it('buckets a reading the way Python floor division does', () => {
- // a 10 second window in 6 buckets is 1.6666666666666667 wide, and the
- // reading at 5s is bucket 2 to Python's `//` but bucket 3 to Math.floor
- // of the quotient, which would have averaged it with the one at 6s instead
+ /* a 10 second window in 6 buckets is 1.6666666666666667 wide, and the
+ reading at 5s is bucket 2 to Python's `//` but bucket 3 to Math.floor
+ of the quotient, which would have averaged it with the one at 6s instead */
const points: Series = [
[at(0), 10],
[at(1), 20],
@@ -305,9 +314,9 @@ describe('downsample', () => {
})
it("averages a bucket with Python's compensated sum", () => {
- // summed left to right these four come to 54.150000000000006 over four,
- // which rounds to 54.2; Python's sum() carries the lost bits and lands on
- // the side of the tie that rounds to 54.1
+ /* summed left to right these four come to 54.150000000000006 over four,
+ which rounds to 54.2; Python's sum() carries the lost bits and lands on
+ the side of the tie that rounds to 54.1 */
const points: Series = [
[at(0), 94.9],
[at(1), 14.9],
@@ -321,10 +330,10 @@ describe('downsample', () => {
})
})
-// --- fleetHistory ------------------------------------------------------
-//
-// Python tested fleet_history only through its routes in test_api.py. These
-// exercise it directly on a seeded database, from those same cases.
+/* --- fleetHistory ------------------------------------------------------
+
+ Python tested fleet_history only through its routes in test_api.py. These
+ exercise it directly on a seeded database, from those same cases. */
describe('fleetHistory', () => {
let db: Connection
@@ -380,8 +389,8 @@ describe('fleetHistory', () => {
})
it('lists hosts in the same order as /fleet, for every kind', () => {
- // one colour per host position, bound on the cards from /fleet and on every
- // chart from these; a kind disagreeing would recolour a whole chart
+ /* one colour per host position, bound on the cards from /fleet and on every
+ chart from these; a kind disagreeing would recolour a whole chart */
const names = fleetHosts().map((host) => host.name)
const kinds = ['cpu', 'memory', 'gpu', 'network', 'disk'] as const
@@ -468,8 +477,8 @@ describe('fleetHistory', () => {
})
it('reads only this target and only net metrics for network', () => {
- // the prefix read is a range scan over the metric column, so a neighbouring
- // family (or another host's counters) must not fall inside it
+ /* the prefix read is a range scan over the metric column, so a neighbouring
+ family (or another host's counters) must not fall inside it */
const ticks = [
[40, 0],
[30, 1000],
diff --git a/apps/fleet-monitor/src/series.ts b/apps/fleet-monitor/src/series.ts
index 737f0b9..80c29c0 100644
--- a/apps/fleet-monitor/src/series.ts
+++ b/apps/fleet-monitor/src/series.ts
@@ -1,16 +1,16 @@
-// Every chartable history the dashboard draws, as one shape.
-//
-// Four questions, four different pieces of arithmetic: CPU busy comes out of
-// jiffy counters, memory out of two gauges read against each other, GPU out of a
-// frequency ratio, network out of byte counters. The page draws all four the same
-// way, so they leave here as the same thing: a per-host series of (moment,
-// value), plus a unit naming what the numbers mean.
-//
-// The derivations live here rather than in the browser for the same reason the
-// host judgments do: they need to know what the collector collects. Which volume
-// is watched, which meminfo keys carry the truth about used memory, that a GPU
-// frequency is a load proxy and not a utilization percent: none of that is
-// knowable a wire away.
+/* Every chartable history the dashboard draws, as one shape.
+
+ Four questions, four different pieces of arithmetic: CPU busy comes out of
+ jiffy counters, memory out of two gauges read against each other, GPU out of a
+ frequency ratio, network out of byte counters. The page draws all four the same
+ way, so they leave here as the same thing: a per-host series of (moment,
+ value), plus a unit naming what the numbers mean.
+
+ The derivations live here rather than in the browser for the same reason the
+ host judgments do: they need to know what the collector collects. Which volume
+ is watched, which meminfo keys carry the truth about used memory, that a GPU
+ frequency is a load proxy and not a utilization percent: none of that is
+ knowable a wire away. */
import { fleetHosts } from '@/config.js'
import { METRICS as CPU_METRICS, busySeries } from '@/cpu.js'
@@ -19,35 +19,35 @@ import { metricSeries, metricSeriesPrefix, rateSeries, type Series } from '@/sto
import { addSeconds, secondsBetween } from '@wizteros/server-common'
import { floorDivide, pythonRound, pythonSum } from '@/pythonMath.js'
-// A series carries one point per collector tick, so a long window is thousands
-// of them per host: a week at the vitals cadence is 20k points no chart can draw
-// and no browser wants to parse. Anything longer than this is bucketed down.
+/* A series carries one point per collector tick, so a long window is thousands
+ of them per host: a week at the vitals cadence is 20k points no chart can draw
+ and no browser wants to parse. Anything longer than this is bucketed down. */
export const MAX_POINTS = 720
-// Memory is judged against MemAvailable rather than MemFree: free excludes
-// reclaimable page cache, and on these boxes that reads as 95% used on an idle
-// machine. Both keys are what probes.proc writes, named from there.
+/* Memory is judged against MemAvailable rather than MemFree: free excludes
+ reclaimable page cache, and on these boxes that reads as 95% used on an idle
+ machine. Both keys are what probes.proc writes, named from there. */
export const MEMORY_TOTAL_METRIC = 'mem.total_bytes'
export const MEMORY_AVAILABLE_METRIC = 'mem.available_bytes'
-// The i915 actual-frequency share of the card's ceiling. DSM ships no
-// intel_gpu_top and does not expose the i915 perf interface, so a true busy
-// percentage is not obtainable on this fleet; this is a load proxy and the page
-// has to say so rather than print it as utilization.
+/* The i915 actual-frequency share of the card's ceiling. DSM ships no
+ intel_gpu_top and does not expose the i915 perf interface, so a true busy
+ percentage is not obtainable on this fleet; this is a load proxy and the page
+ has to say so rather than print it as utilization. */
export const GPU_RATIO_METRIC = 'gpu.freq_ratio'
-// The watched volume's size and free space, from the collector's one
-// `df -Pk /volume1`. Slow tier, so a few readings an hour rather than one a
-// tick. fleet.ts reads the same two keys for the host card, which is why they
-// live here and are imported there.
+/* The watched volume's size and free space, from the collector's one
+ `df -Pk /volume1`. Slow tier, so a few readings an hour rather than one a
+ tick. fleet.ts reads the same two keys for the host card, which is why they
+ live here and are imported there. */
export const DISK_TOTAL_METRIC = 'disk.volume1.total_bytes'
export const DISK_AVAILABLE_METRIC = 'disk.volume1.available_bytes'
-// Every per-interface byte counter probes.proc kept: loopback, tunnels, the
-// docker bridges and the veth pairs are already dropped there, so what remains
-// is the physical NICs. Measured 2026-08-26: meleys has eth0/eth1/eth2,
-// vermithor and vhagar eth0/eth1, and none of the five runs a bond, so summing
-// every interface cannot double-count a bond against its own members.
+/* Every per-interface byte counter probes.proc kept: loopback, tunnels, the
+ docker bridges and the veth pairs are already dropped there, so what remains
+ is the physical NICs. Measured 2026-08-26: meleys has eth0/eth1/eth2,
+ vermithor and vhagar eth0/eth1, and none of the five runs a bond, so summing
+ every interface cannot double-count a bond against its own members. */
export const NETWORK_PREFIX = 'net.'
export type Unit = 'percent' | 'bytes_per_second'
@@ -69,9 +69,9 @@ export type Family = Readonly<{
derive: (seriesByMetric: Readonly>) => Series
}>
-// A series keyed by its instants rather than its Dates, since two Dates for the
-// same moment are different Map keys. A repeated instant keeps its last
-// reading, as dict() does.
+/* A series keyed by its instants rather than its Dates, since two Dates for the
+ same moment are different Map keys. A repeated instant keeps its last
+ reading, as dict() does. */
const byInstant = (points: Series): ReadonlyMap =>
new Map(points.map((point) => [point[0].getTime(), point] as const))
@@ -90,12 +90,15 @@ const shareSeries = ({
totalMetric,
freeMetric,
share,
+ digits = 1,
}: {
seriesByMetric: Readonly>
totalMetric: string
freeMetric: string
/** The share to report, as a fraction of the total. */
share: (reading: { total: number; free: number }) => number
+ /** Decimal places the percentage keeps. */
+ digits?: number
}): Series => {
const totals = byInstant(seriesByMetric[totalMetric] ?? [])
const frees = byInstant(seriesByMetric[freeMetric] ?? [])
@@ -106,7 +109,7 @@ const shareSeries = ({
if (!(total > 0) || free === null || !(free >= 0 && free <= total)) {
return []
}
- return [[at, pythonRound({ value: share({ total, free }) * 100, digits: 1 })]]
+ return [[at, pythonRound({ value: share({ total, free }) * 100, digits })]]
})
}
@@ -151,9 +154,9 @@ export const gpuLoadSeries = (seriesByMetric: Readonly>):
export const networkThroughputSeries = (
seriesByMetric: Readonly>,
): Series => {
- // keyed by the instant, as in memoryUsedSeries, and summed interface by
- // interface in the order the store handed them over, so the float additions
- // happen in the order Python made them
+ /* keyed by the instant, as in memoryUsedSeries, and summed interface by
+ interface in the order the store handed them over, so the float additions
+ happen in the order Python made them */
const totals = Object.values(seriesByMetric).reduce(
(summed, points) =>
rateSeries(points).reduce((running, [at, value]) => {
@@ -168,18 +171,24 @@ export const networkThroughputSeries = (
}
/**
- * Free space on the watched volume as a percentage of its size, per reading.
+ * Used space on the watched volume as a percentage of its size, per reading.
*
- * Available over total, which is what a reader can still write: df's own
- * capacity figure is used over used-plus-available, and the blocks the
- * filesystem reserves for root fall out of it, so the two do not sum to 100.
+ * Size less available over size, which counts the blocks the filesystem
+ * reserves for root as used: they are space nobody else can write to. df's own
+ * capacity figure divides by used-plus-available instead and rounds up to a
+ * whole percent, which is why the host card can read a point higher.
+ *
+ * Two decimals rather than memory's one. A tenth of a percent of an 80 TB
+ * volume is 80 GB, so at one decimal a day of downloads barely moved the line;
+ * at two it moves in steps of about 8 GB.
*/
-export const diskAvailableSeries = (seriesByMetric: Readonly>): Series =>
+export const diskUsedSeries = (seriesByMetric: Readonly>): Series =>
shareSeries({
seriesByMetric,
totalMetric: DISK_TOTAL_METRIC,
freeMetric: DISK_AVAILABLE_METRIC,
- share: ({ total, free }) => free / total,
+ share: ({ total, free }) => (total - free) / total,
+ digits: 2,
})
export const FAMILIES: Readonly> = {
@@ -216,7 +225,7 @@ export const FAMILIES: Readonly> = {
unit: 'percent',
metrics: [DISK_TOTAL_METRIC, DISK_AVAILABLE_METRIC],
prefix: '',
- derive: diskAvailableSeries,
+ derive: diskUsedSeries,
},
}