Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
import { describe, expect, it } from 'vitest';
import type { AnomalyReport } from '@/types/aiIntelligence';
import type { Disk } from '@/types/api';
import stackedDiskBarSource from '../StackedDiskBar.tsx?raw';
import { buildStackedDiskBarPresentation } from '../stackedDiskBarModel';
// The four small helpers under test (getDiskUsagePercent, getShortDiskLabel,
// getInlineDiskText, getStackedDiskColor) are module-private, so every branch
// is exercised through the exported buildStackedDiskBarPresentation and
// asserted on concrete fields (miniDisks[].percent / shortLabel / inlineText,
// segments[].color, verticalBars[].fillPercent, ...).
// Palette mirrored from the module under test (not exported).
const SEGMENT_COLORS = [
'rgba(34, 197, 94, 0.6)',
'rgba(59, 130, 246, 0.6)',
'rgba(168, 85, 247, 0.6)',
'rgba(249, 115, 22, 0.6)',
'rgba(236, 72, 153, 0.6)',
'rgba(20, 184, 166, 0.6)',
];
const NORMAL = 'rgba(34, 197, 94, 0.6)';
const WARNING = 'rgba(234, 179, 8, 0.6)';
const CRITICAL = 'rgba(239, 68, 68, 0.6)';
const makeDisk = (overrides: Partial<Disk> = {}): Disk => ({
total: 100,
used: 0,
free: 100,
usage: 0,
mountpoint: '/',
...overrides,
});
const makeAnomaly = (overrides: Partial<AnomalyReport> = {}): AnomalyReport => ({
resource_id: 'r1',
resource_name: 'resource-1',
resource_type: 'guest',
metric: 'disk',
current_value: 25,
baseline_mean: 10,
baseline_std_dev: 1,
z_score: 15,
severity: 'high',
description: 'Disk usage spike',
...overrides,
});
describe('stackedDiskBarModel (branch coverage 2)', () => {
it('does not invent aggregate usage from capacity, or bytes from a percentage', () => {
const capacity = buildStackedDiskBarPresentation({ aggregateDisk: { total: 100 } }, 400);
expect(capacity.unavailable).toBe(true);
expect(capacity.displayLabel).toBe('N/A');
expect(capacity.tooltipContent[0]).toMatchObject({ percent: '—', used: '?', total: '100 B' });
const percentage = buildStackedDiskBarPresentation({ aggregateDisk: { usage: 0.5 } }, 400);
expect(percentage.unavailable).toBe(false);
expect(percentage.barPercent).toBe(0.5);
expect(percentage.displaySublabel).toBe('');
expect(percentage.tooltipContent[0]).toMatchObject({ used: '?', total: '—' });
// DiskInfo is not an aggregate metric: its genuine zero bytes may be omitted.
const filesystem = buildStackedDiskBarPresentation({ disks: [{ total: 100, free: 100 }] }, 400);
expect(filesystem.unavailable).toBe(false);
expect(filesystem.displayPercentValue).toBe(0);
});
describe('getDiskUsagePercent (via miniDisks[].percent)', () => {
it('uses the used/total ratio when total > 0', () => {
// Branch: disk.total > 0 -> (used / total) * 100.
const p = buildStackedDiskBarPresentation(
{ disks: [makeDisk({ total: 200, used: 50, free: 150, usage: 25 })] },
400,
);
expect(p.miniDisks[0].percent).toBe(25);
});
it.each([0.5, 75, Number.NaN])(
'withholds per-filesystem utilization without byte capacity (%s)',
(usage) => {
// Normalized filesystem rows do not carry independently observed
// aggregate percentages. No capacity means no usable byte reading.
const p = buildStackedDiskBarPresentation(
{ disks: [makeDisk({ total: 0, used: 0, free: 0, usage })] },
400,
);
expect(p.miniDisks).toEqual([]);
expect(p.unavailable).toBe(true);
expect(p.displayLabel).toBe('N/A');
expect(p.tooltipContent[0]).toMatchObject({ percent: '—', total: '—', used: '?' });
},
);
it.each([
{ usage: 0.5, expected: 0.5 },
{ usage: 75, expected: 75 },
{ usage: 0, expected: 0 },
])('preserves independently supplied aggregate-only percentages: %j', ({ usage, expected }) => {
const p = buildStackedDiskBarPresentation(
{ disks: [makeDisk({ total: 0 })], aggregateDisk: { usage } },
400,
);
expect(p.unavailable).toBe(false);
expect(p.displayPercentValue).toBe(expected);
expect(p.miniDisks).toEqual([]);
});
});
describe('independent aggregate percentage with invalid bytes', () => {
it.each([
{ total: Infinity, used: 50 },
{ total: -Infinity, used: 50 },
{ total: Number.NaN, used: 50 },
{ total: -100, used: 50 },
{ total: 0, used: 50 },
{ total: undefined, used: 50 },
{ total: 100, used: Infinity },
{ total: 100, used: Number.NaN },
{ total: 100, used: -1 },
{ total: 100, used: undefined },
])('keeps 50%% but withholds the invalid byte summary: %j', (bytes) => {
const p = buildStackedDiskBarPresentation(
{ aggregateDisk: { ...bytes, usage: 50 }, mode: 'aggregate' },
400,
);
expect(p.unavailable).toBe(false);
expect(p.displayLabel).toBe('50%');
expect(p.barPercent).toBe(50);
expect(p.displaySublabel).toBe('');
expect(p.showSublabel).toBe(false);
expect(JSON.stringify(p)).not.toMatch(/NaN|undefined/);
});
it('still shows finite positive capacity and measured zero bytes', () => {
const p = buildStackedDiskBarPresentation(
{ aggregateDisk: { total: 100, used: 0, usage: 0 }, mode: 'aggregate' },
400,
);
expect(p.displayLabel).toBe('0%');
expect(p.displaySublabel).toBe('0 B/100 B');
expect(p.showSublabel).toBe(true);
});
});
describe('getShortDiskLabel (via miniDisks[].shortLabel)', () => {
it('strips /dev/, returns root, takes the last path segment, and returns short/long labels unchanged', () => {
// Drives all five return arms in array order:
// '/dev/sda1' -> slice '/dev/' -> 'sda1'
// '/' -> trimmed === '/' -> '/'
// '/var/log' -> absolute path -> last segment 'log'
// 'data' -> length <= 12 -> 'data'
// 'verylongmount' -> fall-through -> 'verylongmount'
const p = buildStackedDiskBarPresentation(
{
disks: [
makeDisk({ mountpoint: '/dev/sda1' }),
makeDisk({ mountpoint: '/' }),
makeDisk({ mountpoint: '/var/log' }),
makeDisk({ mountpoint: 'data' }),
makeDisk({ mountpoint: 'verylongmount' }),
],
},
400,
);
expect(p.miniDisks.map((d) => d.shortLabel)).toEqual([
'sda1',
'/',
'log',
'data',
'verylongmount',
]);
});
});
describe('getInlineDiskText (via miniDisks[].inlineText)', () => {
// estimateInlineTextWidth(text) is the label's width at text-[9px]
// semibold, rounded up, plus the slot's 2px of padding (module-internal).
it('returns the full text when slotWidth <= 0 (short-circuit)', () => {
// slotWidth = containerWidth(0) / 1 = 0 -> first operand of the || .
const p = buildStackedDiskBarPresentation(
{
disks: [makeDisk({ mountpoint: '/dev/sda1', total: 100, used: 50, free: 50, usage: 50 })],
},
0,
);
expect(p.miniDisks[0].inlineText).toBe('sda1 50%');
});
it('returns the full text when it fits within the slot', () => {
// 'sda1 50%' width = 46 + 2 = 48 <= slotWidth(60).
const p = buildStackedDiskBarPresentation(
{
disks: [makeDisk({ mountpoint: '/dev/sda1', total: 100, used: 50, free: 50, usage: 50 })],
},
60,
);
expect(p.miniDisks[0].inlineText).toBe('sda1 50%');
});
it('falls back to the percent label when only it fits', () => {
// shortLabel 'a', percentLabel '100%'. full 'a 100%' width 38 > 30;
// '100%' width 30 <= 30 -> returns '100%'.
const p = buildStackedDiskBarPresentation(
{ disks: [makeDisk({ mountpoint: '/dev/a', total: 100, used: 100, free: 0, usage: 100 })] },
30,
);
expect(p.miniDisks[0].inlineText).toBe('100%');
});
it('falls back to the short label when the percent label does not fit but the short label does', () => {
// slotWidth 20: full 38 > 20; percent '100%' 30 > 20; short 'a' 8 <= 20 -> 'a'.
const p = buildStackedDiskBarPresentation(
{ disks: [makeDisk({ mountpoint: '/dev/a', total: 100, used: 100, free: 0, usage: 100 })] },
20,
);
expect(p.miniDisks[0].inlineText).toBe('a');
});
it('returns an empty string when neither label fits', () => {
// slotWidth 5: every estimateInlineTextWidth > 5 -> ''.
const p = buildStackedDiskBarPresentation(
{ disks: [makeDisk({ mountpoint: '/dev/a', total: 100, used: 100, free: 0, usage: 100 })] },
5,
);
expect(p.miniDisks[0].inlineText).toBe('');
});
it('sizes each slot after the gap between slots', () => {
// Two disks in a 117.58px bar (Proxmox nodes at a 900px viewport) get
// 57.79px each once the 2px gap is out. 'backup 80%' needs 58 + 2, so
// the slot keeps the percentage; splitting the bar in half had let the
// full text in and clipped it.
const disks = [
makeDisk({ mountpoint: '/backup', total: 100, used: 80, free: 20, usage: 80 }),
makeDisk({ mountpoint: '/', total: 100, used: 50, free: 50, usage: 50 }),
];
const narrow = buildStackedDiskBarPresentation({ disks }, 117.58);
expect(narrow.miniDisks.map((disk) => disk.inlineText)).toEqual(['80%', '/ 50%']);
const wide = buildStackedDiskBarPresentation({ disks }, 122);
expect(wide.miniDisks[0].inlineText).toBe('backup 80%');
});
it('counts the padding and gap the inline slots carry in StackedDiskBar', () => {
expect(stackedDiskBarSource).toContain('flex h-full items-stretch gap-0.5');
expect(stackedDiskBarSource).toContain('overflow-hidden px-px text-center text-[9px]');
});
});
describe('getStackedDiskColor (via segments[].color, mode=stacked)', () => {
it('maps to warning/critical severity colors and the palette by percent with default thresholds', () => {
// Default thresholds (undefined -> ?? 90 / ?? 80).
// 85 -> warning arm; 10 -> palette arm (index 1); 95 -> critical arm.
const p = buildStackedDiskBarPresentation(
{
mode: 'stacked',
disks: [
makeDisk({ mountpoint: '/a', total: 100, used: 85, free: 15, usage: 85 }),
makeDisk({ mountpoint: '/b', total: 100, used: 10, free: 90, usage: 10 }),
makeDisk({ mountpoint: '/c', total: 100, used: 95, free: 5, usage: 95 }),
],
},
400,
);
expect(p.segments.map((s) => s.color)).toEqual([WARNING, SEGMENT_COLORS[1], CRITICAL]);
expect(p.segments.map((s) => s.diskUsagePercent)).toEqual([85, 10, 95]);
expect(p.segments.map((s) => s.index)).toEqual([0, 1, 2]);
// widthPercent = used / totalCapacity(300) * 100.
expect(p.segments[0].widthPercent).toBeCloseTo(28.33, 1);
expect(p.segments[2].widthPercent).toBeCloseTo(31.67, 1);
});
it('honors custom warning/critical thresholds', () => {
// thresholds { warning: 60, critical: 70 } (no ?? defaults).
// 65 -> warning (>=60, <70); 75 -> critical (>=70); 50 -> palette[2].
const p = buildStackedDiskBarPresentation(
{
mode: 'stacked',
thresholds: { warning: 60, critical: 70 },
disks: [
makeDisk({ mountpoint: '/a', total: 100, used: 65, free: 35, usage: 65 }),
makeDisk({ mountpoint: '/b', total: 100, used: 75, free: 25, usage: 75 }),
makeDisk({ mountpoint: '/c', total: 100, used: 50, free: 50, usage: 50 }),
],
},
400,
);
expect(p.segments.map((s) => s.color)).toEqual([WARNING, CRITICAL, SEGMENT_COLORS[2]]);
});
it('falls back to default thresholds when thresholds is null and wraps the palette index past the end', () => {
// thresholds null -> thresholds?.critical ?? 90 (nullish arm). All 5% (<80)
// -> palette arm; index 6 wraps to SEGMENT_COLORS[0].
const p = buildStackedDiskBarPresentation(
{
mode: 'stacked',
thresholds: null,
disks: Array.from({ length: 7 }, () =>
makeDisk({ total: 100, used: 5, free: 95, usage: 5 }),
),
},
400,
);
expect(p.segments.length).toBe(7);
expect(p.segments[5].color).toBe(SEGMENT_COLORS[5]);
expect(p.segments[6].color).toBe(SEGMENT_COLORS[0]);
});
});
describe('buildStackedDiskBarPresentation', () => {
it('renders an empty state when no disks and no aggregate disk are given', () => {
// disks ?? [] arm (undefined); aggregateDisk absent; overallPercent final 0 arm.
const p = buildStackedDiskBarPresentation({}, 400);
expect(p.hasDisks).toBe(false);
expect(p.hasMultipleDisks).toBe(false);
expect(p.displayPercentValue).toBe(0);
expect(p.barPercent).toBe(0);
expect(p.displayLabel).toBe('0%');
expect(p.segments).toEqual([]);
expect(p.miniDisks).toEqual([]);
expect(p.verticalBars).toEqual([]);
expect(p.tooltipContent).toEqual([]);
expect(p.tooltipTitle).toBe('Disk Usage');
// No mode + no inline disk mode -> centered container class.
expect(p.containerClass).toBe('metric-text w-full h-4 flex items-center justify-center');
expect(p.anomalyClass).toBe('text-yellow-400');
expect(p.anomalyRatio).toBe('');
});
it('renders a single disk without stacked segments', () => {
// hasDisks true, hasMultipleDisks false; maxInfo from a single disk;
// tooltip uses getStackedDiskColor palette (useUsageColors false).
const p = buildStackedDiskBarPresentation(
{ disks: [makeDisk({ mountpoint: '/', total: 100, used: 25, free: 75, usage: 25 })] },
400,
);
expect(p.hasDisks).toBe(true);
expect(p.hasMultipleDisks).toBe(false);
expect(p.displayPercentValue).toBe(25);
expect(p.barPercent).toBe(25);
expect(p.displayLabel).toBe('25%');
expect(p.displaySublabel).toBe('25.0 B/100 B');
expect(p.maxLabelShort).toBe('max 25%');
expect(p.maxLabelFull).toBe('Highest usage: / 25%');
expect(p.useStackedSegments).toBe(false);
expect(p.segments).toEqual([]);
expect(p.miniDisks[0].shortLabel).toBe('/');
expect(p.miniDisks[0].percent).toBe(25);
expect(p.miniDisks[0].title).toBe('/: 25% (25.0 B/100 B)');
expect(p.tooltipTitle).toBe('Disk Usage');
expect(p.tooltipContent[0]).toStrictEqual({
color: SEGMENT_COLORS[0],
label: '/',
percent: '25%',
total: '100 B',
used: '25.0 B',
});
});
it('enables stacked segments and the disk-count flag in stacked mode with multiple disks', () => {
// useStackedSegments = hasMultipleDisks && explicitStackedMode; totalCapacity > 0
// -> segments built; showDiskCount = useStackedSegments || showDiskCount.
const p = buildStackedDiskBarPresentation(
{
mode: 'stacked',
disks: [
makeDisk({ mountpoint: '/a', total: 100, used: 10, free: 90, usage: 10 }),
makeDisk({ mountpoint: '/b', total: 100, used: 20, free: 80, usage: 20 }),
],
},
400,
);
expect(p.useStackedSegments).toBe(true);
expect(p.segments.length).toBe(2);
expect(p.showDiskCount).toBe(true);
expect(p.tooltipTitle).toBe('Disk Breakdown');
// explicitStackedMode suppresses inlineDiskMode.
expect(p.inlineDiskMode).toBe(false);
});
it('uses the total summary strategy in aggregate mode (overall percent, max label shown, usage-colored tooltip)', () => {
// aggregateMode true; summaryStrategy defaults to 'total' -> useMaxSummary false;
// displayPercentValue = overallPercent; barColor uses maxInfo.percent;
// showMaxLabel true via the aggregate width check; tooltip useUsageColors true.
const p = buildStackedDiskBarPresentation(
{
mode: 'aggregate',
disks: [
makeDisk({ mountpoint: '/a', total: 100, used: 80, free: 20, usage: 80 }),
makeDisk({ mountpoint: '/b', total: 100, used: 20, free: 80, usage: 20 }),
],
},
400,
);
expect(p.aggregateMode).toBe(true);
expect(p.displayPercentValue).toBe(50); // 100 / 200 * 100
expect(p.barPercent).toBe(50);
expect(p.maxLabelShort).toBe('max 80%');
expect(p.barColor).toBe(WARNING); // getMetricColorRgba(maxInfo.percent = 80)
expect(p.showMaxLabel).toBe(true);
expect(p.showSublabel).toBe(true);
expect(p.tooltipContent.map((t) => t.color)).toEqual([WARNING, NORMAL]);
});
it('uses the max summary strategy in aggregate mode (display = max percent, sublabel suppressed)', () => {
// useMaxSummary = aggregateMode && hasMultipleDisks && 'max' && maxInfo -> true;
// displayPercentValue = maxInfo.percent; maxLabelShort = 'max'; displaySublabel = ''.
const p = buildStackedDiskBarPresentation(
{
mode: 'aggregate',
summaryStrategy: 'max',
disks: [
makeDisk({ mountpoint: '/a', total: 100, used: 30, free: 70, usage: 30 }),
makeDisk({ mountpoint: '/b', total: 100, used: 90, free: 10, usage: 90 }),
],
},
400,
);
expect(p.displayPercentValue).toBe(90);
expect(p.barPercent).toBe(90);
expect(p.maxLabelShort).toBe('max');
expect(p.displaySublabel).toBe('');
expect(p.showSublabel).toBe(false);
expect(p.showMaxLabel).toBe(true);
expect(p.barColor).toBe(CRITICAL); // getMetricColorRgba(90)
});
it('keeps the max summary when only one of several reported disks is measured', () => {
// An unmeasured sibling must not drop the host to a low aggregate and
// hide the full disk it can still read.
const p = buildStackedDiskBarPresentation(
{
mode: 'aggregate',
summaryStrategy: 'max',
aggregateDisk: makeDisk({ total: 1000, used: 200, free: 800, usage: 20 }),
disks: [
makeDisk({ mountpoint: '/data', total: 100, used: 95, free: 5, usage: 95 }),
makeDisk({ mountpoint: '/scratch', total: 100, used: 0, usage: -1 }),
],
},
400,
);
expect(p.displayPercentValue).toBe(95);
expect(p.maxLabelShort).toBe('max');
expect(p.showMaxLabel).toBe(true);
expect(p.barColor).toBe(CRITICAL);
});
it('drops the max marker rather than clip the percentage in a narrow cell', () => {
const p = buildStackedDiskBarPresentation(
{
mode: 'aggregate',
summaryStrategy: 'max',
disks: [
makeDisk({ mountpoint: '/a', total: 100, used: 30, free: 70, usage: 30 }),
makeDisk({ mountpoint: '/b', total: 100, used: 61, free: 39, usage: 61 }),
],
},
30,
);
expect(p.displayPercentValue).toBe(61);
expect(p.showMaxLabel).toBe(false);
expect(p.maxLabelFull).toBe('Highest usage: /b 61%');
});
it('builds vertical bars clamped to 0..100 and the vertical-bars container class', () => {
// verticalBarsMode = mode === 'vertical-bars' && hasDisks; fillPercent uses
// Math.max(0, Math.min(percent, 100)) -> exercises the upper clamp. A
// negative usage is the unknown-usage sentinel: excluded from the bars,
// still listed in the tooltip.
const p = buildStackedDiskBarPresentation(
{
mode: 'vertical-bars',
disks: [
makeDisk({ mountpoint: '/x', total: 100, used: 40, free: 60, usage: 40 }),
makeDisk({ mountpoint: '/y', total: 100, used: 120, free: 0, usage: 120 }),
makeDisk({ mountpoint: '/z', total: 100, used: 0, free: 0, usage: -5 }),
],
},
400,
);
expect(p.verticalBarsMode).toBe(true);
expect(p.containerClass).toBe('metric-text w-full h-4 min-w-0');
expect(p.verticalBars.map((b) => b.fillPercent)).toEqual([40, 100]);
expect(p.verticalBars[0]).toStrictEqual({
color: NORMAL,
fillPercent: 40,
title: '/x: 40% (40.0 B/100 B)',
});
expect(p.verticalBars[1].color).toBe(CRITICAL); // 120% -> critical
// The fullest disk's usage labels the cell so a multi-disk host still
// reads as a number without a hover.
expect(p.verticalBarsLabel).toBe('120%');
expect(p.verticalBarsLabelTitle).toBe('Highest usage: /y 120%');
expect(p.tooltipContent).toHaveLength(3);
expect(p.tooltipContent[2]).toMatchObject({ label: '/z', percent: '—', used: '?' });
});
it('enables inline disk mode and its container class in mini mode', () => {
// miniMode true -> inlineDiskMode true (miniMode && !aggregate && !stacked
// && !verticalBars); containerClass = inline-disk arm.
const p = buildStackedDiskBarPresentation(
{
mode: 'mini',
disks: [
makeDisk({ mountpoint: '/dev/nvme0', total: 100, used: 75, free: 25, usage: 75 }),
],
},
400,
);
expect(p.miniMode).toBe(true);
expect(p.inlineDiskMode).toBe(true);
expect(p.containerClass).toBe('metric-text w-full h-4 min-w-0');
expect(p.miniDisks[0].shortLabel).toBe('nvme0');
});
it('derives capacity and a Total tooltip from aggregateDisk when no disks array is given', () => {
// hasDisks false -> totalCapacity/totalUsed from aggregateDisk;
// tooltip aggregateDisk arm (total > 0) -> single Total item.
const p = buildStackedDiskBarPresentation(
{ aggregateDisk: makeDisk({ total: 200, used: 50, free: 150, usage: 25 }) },
400,
);
expect(p.hasDisks).toBe(false);
expect(p.displayPercentValue).toBe(25);
expect(p.displaySublabel).toBe('50.0 B/200 B');
expect(p.tooltipContent).toStrictEqual([
{
color: NORMAL,
label: 'Total',
percent: '25%',
total: '200 B',
used: '50.0 B',
},
]);
});
it('shows an independently observed aggregate percentage without inventing byte totals', () => {
const p = buildStackedDiskBarPresentation({ aggregateDisk: { usage: 75 } }, 400);
expect(p.displayPercentValue).toBe(75);
expect(p.barPercent).toBe(75);
expect(p.displaySublabel).toBe('');
expect(p.tooltipContent[0]).toMatchObject({ percent: '75%', used: '?', total: '—' });
});
it('maps anomaly severity to a class and formats each anomaly-ratio tier', () => {
// ratio >= 2 -> `${ratio}x`; 1.5..2 -> '↑↑'; 1..1.5 -> '↑'; baseline 0 -> ''.
const high = buildStackedDiskBarPresentation(
{ anomaly: makeAnomaly({ severity: 'high', baseline_mean: 10, current_value: 25 }) },
400,
);
expect(high.anomalyClass).toBe('text-orange-400');
expect(high.anomalyRatio).toBe('2.5x');
expect(high.anomalyDescription).toBe('Disk usage spike');
const critical = buildStackedDiskBarPresentation(
{ anomaly: makeAnomaly({ severity: 'critical', baseline_mean: 10, current_value: 17 }) },
400,
);
expect(critical.anomalyClass).toBe('text-red-400');
expect(critical.anomalyRatio).toBe('↑↑');
const lowTier = buildStackedDiskBarPresentation(
{ anomaly: makeAnomaly({ severity: 'low', baseline_mean: 10, current_value: 13 }) },
400,
);
expect(lowTier.anomalyClass).toBe('text-blue-400');
expect(lowTier.anomalyRatio).toBe('↑');
// Unknown severity -> ANOMALY_SEVERITY_CLASS[sev] ?? 'text-yellow-400';
// baseline_mean 0 -> formatAnomalyRatio null -> ?? ''.
const unknown = buildStackedDiskBarPresentation(
{ anomaly: makeAnomaly({ severity: 'weird', baseline_mean: 0, current_value: 0 }) },
400,
);
expect(unknown.anomalyClass).toBe('text-yellow-400');
expect(unknown.anomalyRatio).toBe('');
});
it('shows the sublabel only where the whole label fits', () => {
// '60% (265 GB/440 GB)' is 110.1px of text in the browser and sits in
// 4px of padding: a 113px bar keeps the percentage, a 115px bar fits it.
const GiB = 1024 ** 3;
const disks = [
makeDisk({
mountpoint: '/',
total: 440 * GiB,
used: 265 * GiB,
free: 175 * GiB,
usage: 60,
}),
];
const narrow = buildStackedDiskBarPresentation({ disks }, 113);
expect(narrow.displayLabel).toBe('60%');
expect(narrow.displaySublabel).toBe('265 GB/440 GB');
expect(narrow.showSublabel).toBe(false);
expect(buildStackedDiskBarPresentation({ disks }, 114).showSublabel).toBe(false);
expect(buildStackedDiskBarPresentation({ disks }, 115).showSublabel).toBe(true);
expect(stackedDiskBarSource).toContain('text-ellipsis px-0.5 text-center');
});
it('leaves room for the anomaly marker that shares the line', () => {
// ' 2.5x' adds 25.35px, taking the threshold from 115 to 140.
const GiB = 1024 ** 3;
const props = {
disks: [
makeDisk({
mountpoint: '/',
total: 440 * GiB,
used: 265 * GiB,
free: 175 * GiB,
usage: 60,
}),
],
anomaly: makeAnomaly({ baseline_mean: 10, current_value: 25 }),
};
expect(buildStackedDiskBarPresentation(props, 139).showSublabel).toBe(false);
expect(buildStackedDiskBarPresentation(props, 140).showSublabel).toBe(true);
});
it('suppresses the sublabel when containerWidth is too narrow to fit it', () => {
// displaySublabel non-empty but containerWidth < estimateTextWidth(...) ->
// showSublabel false (the width-failing arm of the && ).
const p = buildStackedDiskBarPresentation(
{ disks: [makeDisk({ mountpoint: '/', total: 100, used: 25, free: 75, usage: 25 })] },
5,
);
expect(p.showSublabel).toBe(false);
expect(p.displaySublabel).toBe('25.0 B/100 B');
});
it('excludes config-only mounts (usage -1) from usage visuals but lists them in the tooltip', () => {
// A container with a measured rootfs plus a mount known only from the
// guest config (usage -1, capacity from size=). The unknown mount must
// not get a bar slot or skew the summary math, but stays discoverable
// in the tooltip with capacity and no fabricated 0%.
const p = buildStackedDiskBarPresentation(
{
disks: [
makeDisk({ mountpoint: '/', total: 100, used: 50, free: 50, usage: 50 }),
makeDisk({ mountpoint: '/srv/archive', total: 200, used: 0, free: 0, usage: -1 }),
],
},
400,
);
expect(p.hasMultipleDisks).toBe(false); // only the measured disk counts
expect(p.inlineDiskMode).toBe(false); // no "archive 0%" mini slot
expect(p.miniDisks.map((d) => d.label)).toEqual(['/']);
expect(p.displayPercentValue).toBe(50); // unknown capacity not in the denominator
expect(p.tooltipContent).toHaveLength(2);
expect(p.tooltipContent[1]).toMatchObject({
label: '/srv/archive',
percent: '—',
used: '?',
total: '200 B',
});
});
it('falls back to the aggregate disk when every listed disk has unknown usage', () => {
const p = buildStackedDiskBarPresentation(
{
disks: [
makeDisk({ mountpoint: '/srv/archive', total: 200, used: 0, free: 0, usage: -1 }),
],
aggregateDisk: makeDisk({ total: 100, used: 25, free: 75, usage: 25 }),
},
400,
);
expect(p.hasDisks).toBe(false);
expect(p.displayPercentValue).toBe(25);
expect(p.tooltipContent).toHaveLength(1);
expect(p.tooltipContent[0]).toMatchObject({ label: '/srv/archive', percent: '—' });
});
});
});
describe('disk observation decorations', () => {
const neutral = 'rgba(148, 163, 184, 0.5)';
const message = 'Using last known disk stats. Guest reads paused during a backup.';
const disks = [
makeDisk({ used: 95, free: 5, usage: 95 }),
makeDisk({ mountpoint: '/data', total: 200, used: 180, free: 20, usage: 90 }),
];
it.each([undefined, 'aggregate', 'stacked', 'mini', 'vertical-bars'] as const)(
'keeps last-known %s values inspectable without live health colours or anomaly',
(mode) => {
const props = { disks, mode, anomaly: makeAnomaly(), summaryStrategy: 'max' as const };
const current = buildStackedDiskBarPresentation(props, 400);
const retained = buildStackedDiskBarPresentation(
{ ...props, reading: { state: 'last-known', message } },
400,
);
expect(retained.displayPercentValue).toBe(current.displayPercentValue);
expect(retained.barPercent).toBe(current.barPercent);
expect(retained.displaySublabel).toBe(current.displaySublabel);
expect(retained.segments.map((item) => item.widthPercent)).toEqual(
current.segments.map((item) => item.widthPercent),
);
expect(retained.miniDisks.map((item) => item.percent)).toEqual(
current.miniDisks.map((item) => item.percent),
);
expect(retained.verticalBars.map((item) => item.fillPercent)).toEqual(
current.verticalBars.map((item) => item.fillPercent),
);
expect(retained.barColor).toBe(neutral);
for (const item of [
...retained.segments,
...retained.miniDisks,
...retained.verticalBars,
...retained.tooltipContent,
])
expect(item.color).toBe(neutral);
expect(retained.anomalyDescription).toBeUndefined();
expect(retained.anomalyRatio).toBe('');
expect(retained.tooltipMessage).toBe(message);
expect(retained.tooltipTitle).toMatch(/Last known/i);
expect(retained.miniDisks.every((item) => item.title.startsWith('Last known'))).toBe(true);
expect(retained.verticalBars.every((item) => item.title.startsWith('Last known'))).toBe(true);
},
);
it('keeps a retained aggregate-only value neutral, and config-only capacity unknown', () => {
const aggregate = buildStackedDiskBarPresentation(
{ aggregateDisk: disks[0], reading: { state: 'last-known', message } },
400,
);
expect(aggregate.displayPercentValue).toBe(95);
expect(aggregate.barColor).toBe(neutral);
expect(aggregate.tooltipContent[0]).toMatchObject({ percent: '95%', color: neutral });
const mixed = buildStackedDiskBarPresentation(
{
disks: [...disks, makeDisk({ mountpoint: '/config', total: 300, usage: -1 })],
reading: { state: 'last-known', message },
},
400,
);
expect(mixed.miniDisks).toHaveLength(2);
expect(mixed.tooltipContent[2]).toMatchObject({
label: '/config',
percent: '—',
used: '?',
total: '300 B',
color: neutral,
});
});
it.each([undefined, 'aggregate', 'stacked', 'mini', 'vertical-bars'] as const)(
'withholds unavailable %s usage and anomaly despite numeric carriers',
(mode) => {
const p = buildStackedDiskBarPresentation(
{
disks,
aggregateDisk: disks[0],
mode,
anomaly: makeAnomaly(),
reading: { state: 'unavailable', message: 'Filesystem usage is unavailable.' },
},
400,
);
expect(p.unavailable).toBe(true);
expect(p.displayLabel).toBe('N/A');
expect(p.displayPercentValue).toBe(0);
expect(p.barPercent).toBe(0);
expect(p.segments).toEqual([]);
expect(p.miniDisks).toEqual([]);
expect(p.verticalBars).toEqual([]);
expect(p.displaySublabel).toBe('');
expect(p.anomalyDescription).toBeUndefined();
expect(p.anomalyRatio).toBe('');
expect(
p.tooltipContent.every(
(item) => item.percent === '—' && item.used === '?' && item.color === neutral,
),
).toBe(true);
expect(p.tooltipContent.map((item) => item.total)).toEqual(['100 B', '200 B']);
},
);
it('does not fabricate zero usage for unavailable aggregate-only capacity', () => {
const p = buildStackedDiskBarPresentation(
{ aggregateDisk: disks[0], reading: { state: 'unavailable', message: 'No reading.' } },
400,
);
expect(p.tooltipContent).toEqual([
{ label: 'Total', percent: '—', used: '?', total: '100 B', color: neutral },
]);
expect(p.displayLabel).toBe('N/A');
});
it('preserves measured current zero and unannotated callers; advisory text alone is not freshness', () => {
const base = { disks, anomaly: makeAnomaly(), statusMessage: 'Advisory text' };
const legacy = buildStackedDiskBarPresentation(base, 400);
const current = buildStackedDiskBarPresentation(
{ ...base, reading: { state: 'current', message: null } },
400,
);
expect(current).toEqual(legacy);
expect(current.barColor).toBe(CRITICAL);
expect(current.anomalyDescription).toBe('Disk usage spike');
const zero = buildStackedDiskBarPresentation(
{ disks: [makeDisk()], reading: { state: 'current', message: null } },
400,
);
expect(zero.displayLabel).toBe('0%');
expect(zero.barColor).toBe(NORMAL);
expect(zero.tooltipContent[0].percent).toBe('0%');
expect(zero.unavailable).toBe(false);
});
});
describe('partial filesystem byte admission shared with host drawers', () => {
it('excludes unavailable capacity and invalid used bytes from combined utilization and bars', () => {
const known = makeDisk({ mountpoint: '/known', total: 100, used: 50, usage: 50 });
const partials = [
makeDisk({ mountpoint: '/no-capacity', total: 0, used: 30, usage: 0 }),
makeDisk({ mountpoint: '/negative', total: 200, used: -1, usage: 0 }),
makeDisk({ mountpoint: '/non-finite', total: Infinity, used: 20, usage: 0 }),
makeDisk({ mountpoint: '/sentinel', total: 200, used: 70, usage: -1 }),
];
const presentation = buildStackedDiskBarPresentation(
{ disks: [known, ...partials], mode: 'aggregate' },
200,
);
expect(presentation.displayPercentValue).toBe(50);
expect(presentation.tooltipContent.map((item) => item.percent)).toEqual([
'50%',
'—',
'—',
'—',
'—',
]);
expect(presentation.tooltipContent[1].total).toBe('—');
expect(presentation.tooltipContent[2].total).toBe('200 B');
expect(presentation.tooltipContent[3].total).toBe('—');
const vertical = buildStackedDiskBarPresentation(
{ disks: [known, ...partials], mode: 'vertical-bars' },
200,
);
expect(vertical.verticalBars).toHaveLength(1);
expect(vertical.verticalBars[0].fillPercent).toBe(50);
});
});