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, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { createSignal } from 'solid-js';
import { waitFor, cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
import { ALERT_BULK_EDIT_CLEAR_LABEL } from '@/utils/alertBulkEditPresentation';
import alertResourceMetricEditorSource from '@/components/Alerts/AlertResourceMetricEditor.tsx?raw';
import {
alertResourceSupportsMetric,
buildAlertResourceEditPayload,
getAlertResourceMetricDisplayValue,
isAlertResourceMetricOff,
normalizeAlertResourceMetricKey,
resolveAlertResourceMetricEnableValue,
} from '@/components/Alerts/alertResourceTableModel';
// --- Mocks (must be before component import) ---
const mockIsMobile = vi.fn(() => false);
vi.mock('@/hooks/useBreakpoint', () => ({
useBreakpoint: () => ({ isMobile: mockIsMobile }),
}));
vi.mock('@/utils/logger', () => ({
logger: {
debug: vi.fn(),
error: vi.fn(),
warn: vi.fn(),
info: vi.fn(),
},
}));
vi.mock('@/components/shared/StatusBadge', () => ({
StatusBadge: (props: any) => (
<button
data-testid="status-badge"
aria-label={
props.ariaLabel
? `${props.ariaLabel}: ${props.isEnabled ? (props.labelEnabled ?? 'On') : (props.labelDisabled ?? 'Off')}`
: undefined
}
aria-pressed={props.isEnabled}
onClick={() => props.onToggle?.()}
title={props.isEnabled ? props.titleEnabled : props.titleDisabled}
>
{props.isEnabled ? (props.labelEnabled ?? 'On') : (props.labelDisabled ?? 'Off')}
</button>
),
}));
vi.mock('@/components/shared/Toggle', () => ({
TogglePrimitive: (props: any) => (
<button
data-testid="toggle"
role="switch"
aria-checked={props.checked}
aria-label={props.ariaLabel}
disabled={props.disabled}
title={props.title}
onClick={() => !props.disabled && props.onToggle?.()}
>
{props.checked ? 'ON' : 'OFF'}
</button>
),
}));
vi.mock('@/components/shared/Card', () => ({
Card: (props: any) => (
<div data-testid="card" class={props.class}>
{props.children}
</div>
),
}));
vi.mock('@/components/shared/Table', () => ({
Table: (props: any) => (
<table data-testid="table" class={props.class}>
{props.children}
</table>
),
TableHeader: (props: any) => <thead>{props.children}</thead>,
TableBody: (props: any) => <tbody class={props.class}>{props.children}</tbody>,
TableRow: (props: any) => (
<tr class={props.class} onFocusOut={props.onFocusOut} onFocusIn={props.onFocusIn}>
{props.children}
</tr>
),
TableHead: (props: any) => (
<th class={props.class} title={props.title}>
{props.children}
</th>
),
TableCell: (props: any) => (
<td class={props.class} colspan={props.colspan}>
{props.children}
</td>
),
}));
vi.mock('@/components/shared/SectionHeader', () => ({
SectionHeader: (props: any) => <h3 data-testid="section-header">{props.title}</h3>,
}));
vi.mock('@/components/Workloads/ThresholdSlider', () => ({
ThresholdSlider: (props: any) => (
<input
data-testid="threshold-slider"
type="range"
value={props.value}
min={props.min}
max={props.max}
disabled={props.disabled}
onChange={(e) => props.onChange?.(Number(e.currentTarget.value))}
/>
),
}));
vi.mock('@/components/shared/HelpIcon', () => ({
HelpIcon: () => <span data-testid="help-icon" />,
}));
vi.mock('lucide-solid/icons/rotate-ccw', () => ({
default: (props: any) => <svg data-testid="rotate-ccw-icon" class={props.class} />,
}));
vi.mock('lucide-solid/icons/check', () => ({
default: (props: any) => <svg data-testid="check-icon" class={props.class} />,
}));
vi.mock('lucide-solid/icons/chevron-down', () => ({
default: (props: any) => <svg data-testid="chevron-down-icon" class={props.class} />,
}));
vi.mock('lucide-solid/icons/pencil', () => ({
default: (props: any) => <svg data-testid="pencil-icon" class={props.class} />,
}));
vi.mock('lucide-solid/icons/trash-2', () => ({
default: (props: any) => <svg data-testid="trash-2-icon" class={props.class} />,
}));
vi.mock('lucide-solid/icons/x', () => ({
default: (props: any) => <svg data-testid="x-icon" class={props.class} />,
}));
import {
ResourceTable,
getAlertResourceTableDesktopMinWidth,
type Resource,
} from './ResourceTable';
// --- Helpers ---
function makeResource(overrides: Partial<Resource> = {}): Resource {
return {
id: 'res-1',
name: 'Test VM',
thresholds: { cpu: 80, memory: 85 },
defaults: { cpu: 80, memory: 85 },
...overrides,
};
}
describe('getAlertResourceTableDesktopMinWidth', () => {
it('keeps progressively denser editors in the card layout until their container can support them', () => {
expect(getAlertResourceTableDesktopMinWidth(4)).toBe(544);
expect(getAlertResourceTableDesktopMinWidth(6)).toBe(768);
expect(getAlertResourceTableDesktopMinWidth(8)).toBe(1024);
expect(getAlertResourceTableDesktopMinWidth(10)).toBe(1216);
expect(getAlertResourceTableDesktopMinWidth(13)).toBe(1728);
expect(getAlertResourceTableDesktopMinWidth(20)).toBe(Number.POSITIVE_INFINITY);
});
});
interface DefaultProps {
title: string;
resources: Resource[];
columns: string[];
onEdit: ReturnType<typeof vi.fn<(...args: any[]) => any>>;
onSaveEdit: ReturnType<typeof vi.fn<(...args: any[]) => any>>;
onCancelEdit: ReturnType<typeof vi.fn<(...args: any[]) => any>>;
onRemoveOverride: ReturnType<typeof vi.fn<(...args: any[]) => any>>;
editingId: () => string | null;
editingThresholds: () => Record<string, number | undefined>;
setEditingThresholds: ReturnType<typeof vi.fn<(...args: any[]) => any>>;
formatMetricValue: ReturnType<typeof vi.fn<(...args: any[]) => any>>;
hasActiveAlert: ReturnType<typeof vi.fn<(...args: any[]) => any>>;
editingNote: () => string;
setEditingNote: ReturnType<typeof vi.fn<(...args: any[]) => any>>;
}
function makeProps(
overrides: Partial<DefaultProps> & Record<string, any> = {},
): DefaultProps & Record<string, any> {
return {
title: 'Virtual Machines',
resources: [makeResource()],
columns: ['CPU %', 'Memory %'],
onEdit: vi.fn(),
onSaveEdit: vi.fn(),
onCancelEdit: vi.fn(),
onRemoveOverride: vi.fn(),
editingId: () => null,
editingThresholds: () => ({}),
setEditingThresholds: vi.fn(),
formatMetricValue: vi.fn((_metric: string, value: number | undefined) =>
value !== undefined ? String(value) : '-',
),
hasActiveAlert: vi.fn(() => false),
editingNote: () => '',
setEditingNote: vi.fn(),
...overrides,
};
}
// --- Tests ---
describe('ResourceTable', () => {
beforeEach(() => {
mockIsMobile.mockReturnValue(false);
});
afterEach(() => {
cleanup();
vi.clearAllMocks();
});
it.each([false, true])(
'omits unavailable all-alert controls but retains connectivity (mobile=%s)',
(mobile) => {
mockIsMobile.mockReturnValue(mobile);
const onToggleDisabled = vi.fn();
const onToggleNodeConnectivity = vi.fn();
render(() => (
<ResourceTable
{...makeProps({
resources: [
makeResource({
id: 'runtime-a',
name: 'Runtime A',
type: 'dockerHost',
editable: false,
}),
],
columns: [],
showAlertsColumn: false,
showOfflineAlertsColumn: true,
onToggleDisabled,
onToggleNodeConnectivity,
})}
/>
));
expect(
screen.queryByRole('switch', { name: 'Alerts for Runtime A' }),
).not.toBeInTheDocument();
expect(screen.queryByRole('columnheader', { name: 'Alerts' })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Offline alerts for Runtime A: On' }));
expect(onToggleNodeConnectivity).toHaveBeenCalledWith('runtime-a');
expect(onToggleDisabled).not.toHaveBeenCalled();
if (!mobile) {
expect(screen.getAllByRole('columnheader')).toHaveLength(3);
expect(screen.getAllByRole('cell')).toHaveLength(3);
}
},
);
it('keeps grouped, default, delay and empty rows aligned without an Alerts column', () => {
const { unmount } = render(() => (
<ResourceTable
{...makeProps({
resources: undefined,
groupedResources: { runtimes: [makeResource()] },
columns: ['CPU %'],
showAlertsColumn: false,
showOfflineAlertsColumn: true,
globalDefaults: { cpu: 80 },
setGlobalDefaults: vi.fn(),
setHasUnsavedChanges: vi.fn(),
onToggleGlobalDisable: vi.fn(),
showDelayColumn: true,
onMetricDelayChange: vi.fn(),
})}
/>
));
expect(screen.queryByRole('switch', { name: 'Global alerts toggle' })).not.toBeInTheDocument();
expect(screen.getAllByRole('columnheader')).toHaveLength(4);
fireEvent.click(screen.getByLabelText('Show alert delay settings'));
expect(screen.getByText('Alert Delay (s)')).toBeInTheDocument();
const group = screen.getByText('runtimes').closest('td');
expect(group).toHaveAttribute('colspan', '4');
for (const row of screen.getAllByRole('row').slice(1)) {
if (row.contains(group)) continue;
expect(row.querySelectorAll('td')).toHaveLength(4);
}
unmount();
render(() => (
<ResourceTable
{...makeProps({
resources: [],
columns: [],
showAlertsColumn: false,
showOfflineAlertsColumn: true,
})}
/>
));
for (const cell of screen.getAllByRole('cell')) expect(cell).toHaveAttribute('colspan', '3');
});
describe('rendering basics', () => {
it.each([false, true])(
'keeps filesystem reading explanations visible and reactive (mobile=%s)',
(mobile) => {
mockIsMobile.mockReturnValue(mobile);
const [resources, setResources] = createSignal([
makeResource({
id: 'disk-1',
name: '/data',
type: 'guestDisk',
subtitle: 'Last known 9.0 / 10.0 GB · 90.0%',
readingMessage: 'Guest reads paused while the backup lock is reported.',
}),
]);
const props = makeProps({ columns: ['Disk %'] });
render(() => <ResourceTable {...props} resources={resources()} />);
const explanation = screen.getByText(
'Guest reads paused while the backup lock is reported.',
);
if (mobile) {
expect(explanation).not.toHaveClass('truncate');
} else {
// A desktop row stays one line: the note joins the name and ends in
// an ellipsis, with the whole note in its title.
expect(explanation).toHaveClass('truncate');
expect(explanation).toHaveAttribute(
'title',
'Guest reads paused while the backup lock is reported.',
);
expect(explanation.parentElement).toHaveClass('flex', 'items-center');
expect(explanation.parentElement).not.toHaveClass('flex-wrap');
}
if (mobile)
expect(screen.getByText('Last known 9.0 / 10.0 GB · 90.0%')).not.toHaveClass('truncate');
setResources([
makeResource({
id: 'disk-1',
name: '/data',
type: 'guestDisk',
subtitle: '3.0 / 10.0 GB · 30.0%',
}),
]);
expect(screen.queryByText(/Guest reads paused/)).not.toBeInTheDocument();
expect(screen.getByText('3.0 / 10.0 GB · 30.0%')).toBeInTheDocument();
},
);
it('renders the section header with the provided title', () => {
const props = makeProps({ title: 'Nodes' });
render(() => <ResourceTable {...props} />);
expect(screen.getByTestId('section-header')).toHaveTextContent('Nodes');
});
it('renders column headers', () => {
const props = makeProps({ columns: ['CPU %', 'Memory %', 'Disk %'] });
render(() => <ResourceTable {...props} />);
expect(screen.getByText('CPU %')).toBeInTheDocument();
expect(screen.getByText('Memory %')).toBeInTheDocument();
expect(screen.getByText('Disk %')).toBeInTheDocument();
});
it('renders resource name', () => {
const props = makeProps({
resources: [makeResource({ name: 'my-vm-100' })],
});
render(() => <ResourceTable {...props} />);
expect(screen.getByText('my-vm-100')).toBeInTheDocument();
});
it('renders policy-redacted resources with their raw display name in operator-local UI', () => {
// The alert resource table is local UI for the operator. Per docs/PRIVACY.md
// resource-policy redaction is a transmission-boundary policy, not a
// local-rendering policy.
const props = makeProps({
resources: [
makeResource({
id: 'vm-1',
name: 'secret-vm-1',
rawName: 'secret-vm-1',
policy: {
sensitivity: 'restricted',
routing: { scope: 'local-only', redact: ['hostname'] },
},
aiSafeSummary: 'Production VM',
}),
],
});
render(() => <ResourceTable {...props} />);
expect(screen.getByText('secret-vm-1')).toBeInTheDocument();
expect(screen.getByLabelText('Edit thresholds for secret-vm-1')).toBeInTheDocument();
expect(screen.queryByText('Production VM')).not.toBeInTheDocument();
});
it('renders multiple resources', () => {
const props = makeProps({
resources: [
makeResource({ id: 'vm-1', name: 'VM Alpha' }),
makeResource({ id: 'vm-2', name: 'VM Beta' }),
makeResource({ id: 'vm-3', name: 'VM Gamma' }),
],
});
render(() => <ResourceTable {...props} />);
expect(screen.getByText('VM Alpha')).toBeInTheDocument();
expect(screen.getByText('VM Beta')).toBeInTheDocument();
expect(screen.getByText('VM Gamma')).toBeInTheDocument();
});
it('renders Alerts, Resource, and Actions column headers', () => {
const props = makeProps();
render(() => <ResourceTable {...props} />);
expect(screen.getByText('Alerts')).toBeInTheDocument();
expect(screen.getByText('Resource')).toBeInTheDocument();
expect(screen.getByText('Actions')).toBeInTheDocument();
});
});
describe('column header tooltips', () => {
it('renders tooltips for known columns', () => {
const props = makeProps({ columns: ['CPU %', 'Memory %'] });
render(() => <ResourceTable {...props} />);
const cpuHeader = screen.getByText('CPU %');
expect(cpuHeader.closest('th')).toHaveAttribute(
'title',
'Percent CPU utilization allowed before an alert fires.',
);
const memHeader = screen.getByText('Memory %');
expect(memHeader.closest('th')).toHaveAttribute(
'title',
'Percent memory usage threshold for triggering alerts.',
);
});
});
describe('table ownership model', () => {
it('keeps the metric editor input touch-sized on phones', () => {
expect(alertResourceMetricEditorSource).toContain(
'min-h-11 w-full rounded-sm border p-1 text-center text-sm sm:min-h-0',
);
});
it('resolves metric values and edit payloads through the shared model', () => {
expect(normalizeAlertResourceMetricKey('CPU %')).toBe('cpu');
expect(alertResourceSupportsMetric('agent', 'networkIn')).toBe(false);
expect(alertResourceSupportsMetric('pbs', 'disk')).toBe(false);
expect(alertResourceSupportsMetric('vmwareHost', 'networkIn')).toBe(true);
expect(alertResourceSupportsMetric('vmwareHost', 'disk')).toBe(false);
expect(alertResourceSupportsMetric('vmwareDatastore', 'usage')).toBe(true);
expect(alertResourceSupportsMetric('vmwareNetwork', 'cpu')).toBe(false);
expect(
getAlertResourceMetricDisplayValue(
makeResource({
thresholds: { cpu: 80 },
defaults: { cpu: 75 },
}),
'cpu',
),
).toBe(80);
expect(
getAlertResourceMetricDisplayValue(
makeResource({
thresholds: { cpu: 80 },
defaults: { cpu: 75 },
}),
'cpu',
{ cpu: undefined },
true,
),
).toBe(75);
expect(
buildAlertResourceEditPayload(
makeResource({
thresholds: { cpu: 85 },
defaults: { cpu: 80 },
note: 'Investigating bursty load',
}),
),
).toEqual({
thresholds: { cpu: 85 },
defaults: { cpu: 80 },
note: 'Investigating bursty load',
});
});
it('reads the engine off sentinel and resolves re-enable values in the shared model', () => {
// internal/alerts/canonical_metric.go disables any metric whose trigger is
// <= 0, so a legacy 0 override is off even though the UI now writes -1.
expect(isAlertResourceMetricOff(-1)).toBe(true);
expect(isAlertResourceMetricOff(0)).toBe(true);
expect(isAlertResourceMetricOff(-5)).toBe(true);
expect(isAlertResourceMetricOff(80)).toBe(false);
expect(isAlertResourceMetricOff(undefined)).toBe(false);
// Re-enabling can only clear the override when the inherited default is
// itself enabled; otherwise the resource stays disabled.
expect(resolveAlertResourceMetricEnableValue(80, 'cpu')).toBeUndefined();
expect(resolveAlertResourceMetricEnableValue(-1, 'cpu')).toBe(80);
expect(resolveAlertResourceMetricEnableValue(0, 'cpu')).toBe(80);
expect(resolveAlertResourceMetricEnableValue(undefined, 'restartCount')).toBe(3);
});
});
describe('resource display and editing', () => {
it('calls onEdit with correct args when edit button is clicked', () => {
const onEdit = vi.fn();
const resource = makeResource({
id: 'vm-1',
name: 'Test VM',
thresholds: { cpu: 90 },
defaults: { cpu: 80 },
note: 'test note',
});
const props = makeProps({ resources: [resource], onEdit });
render(() => <ResourceTable {...props} />);
const editButton = screen.getByLabelText('Edit thresholds for Test VM');
fireEvent.click(editButton);
expect(onEdit).toHaveBeenCalledWith('vm-1', { cpu: 90 }, { cpu: 80 }, 'test note');
});
it('shows cancel button when editing a resource', () => {
const props = makeProps({
resources: [makeResource({ id: 'vm-1', name: 'Editing VM' })],
editingId: () => 'vm-1',
editingThresholds: () => ({ cpu: 90 }),
});
render(() => <ResourceTable {...props} />);
expect(screen.getByLabelText('Cancel editing')).toBeInTheDocument();
});
it('calls onCancelEdit when cancel button is clicked', () => {
const onCancelEdit = vi.fn();
const props = makeProps({
resources: [makeResource({ id: 'vm-1' })],
editingId: () => 'vm-1',
editingThresholds: () => ({ cpu: 90 }),
onCancelEdit,
});
render(() => <ResourceTable {...props} />);
fireEvent.click(screen.getByLabelText('Cancel editing'));
expect(onCancelEdit).toHaveBeenCalled();
});
it('shows Custom badge for resources with overrides', () => {
const props = makeProps({
resources: [makeResource({ id: 'vm-1', name: 'Custom VM', hasOverride: true })],
});
render(() => <ResourceTable {...props} />);
expect(screen.getByText('Custom')).toBeInTheDocument();
});
it('calls onRemoveOverride with resource id when revert button is clicked', () => {
const onRemoveOverride = vi.fn();
const props = makeProps({
resources: [makeResource({ id: 'vm-1', name: 'Overridden VM', hasOverride: true })],
onRemoveOverride,
});
render(() => <ResourceTable {...props} />);
const revertBtn = screen.getByLabelText('Revert to defaults for Overridden VM');
fireEvent.click(revertBtn);
expect(onRemoveOverride).toHaveBeenCalledWith('vm-1');
});
it('does not show edit button for dockerHost resources (grouped)', () => {
const props = makeProps({
resources: undefined,
groupedResources: {
host1: [makeResource({ id: 'dh-1', name: 'Docker Host', type: 'dockerHost' })],
},
});
render(() => <ResourceTable {...props} />);
expect(screen.queryByLabelText('Edit thresholds for Docker Host')).not.toBeInTheDocument();
});
it('does not show edit button for non-editable flat resources', () => {
const props = makeProps({
resources: [makeResource({ id: 'dh-1', name: 'Docker Host', editable: false })],
});
render(() => <ResourceTable {...props} />);
expect(screen.queryByLabelText('Edit thresholds for Docker Host')).not.toBeInTheDocument();
// Non-editable resources show an em-dash placeholder
expect(screen.getByText('—')).toBeInTheDocument();
});
it('renders a note for grouped resources when not editing', () => {
const props = makeProps({
resources: undefined,
groupedResources: {
node1: [
makeResource({
id: 'vm-1',
name: 'Noted VM',
note: 'Threshold lowered for maintenance',
}),
],
},
});
render(() => <ResourceTable {...props} />);
expect(screen.getByText('Threshold lowered for maintenance')).toBeInTheDocument();
});
it('renders note editor textarea when editing grouped resource', () => {
const props = makeProps({
resources: undefined,
groupedResources: {
node1: [makeResource({ id: 'vm-1' })],
},
editingId: () => 'vm-1',
editingThresholds: () => ({ cpu: 90 }),
editingNote: () => 'My editing note',
});
render(() => <ResourceTable {...props} />);
const textarea = screen.getByPlaceholderText('Add a note about this override (optional)');
expect(textarea).toBeInTheDocument();
expect(textarea).toHaveValue('My editing note');
});
it('calls setEditingNote when note textarea input changes', () => {
const setEditingNote = vi.fn();
const props = makeProps({
resources: undefined,
groupedResources: {
node1: [makeResource({ id: 'vm-1' })],
},
editingId: () => 'vm-1',
editingThresholds: () => ({ cpu: 90 }),
editingNote: () => '',
setEditingNote,
});
render(() => <ResourceTable {...props} />);
const textarea = screen.getByPlaceholderText('Add a note about this override (optional)');
fireEvent.input(textarea, { target: { value: 'Updated note' } });
expect(setEditingNote).toHaveBeenCalledWith('Updated note');
});
});
describe('pulse-relaxed guests', () => {
const relaxedGuest = (overrides: Partial<Resource> = {}) =>
makeResource({
id: 'vm-1',
name: 'batch-vm',
type: 'guest',
pulseRelaxed: true,
thresholds: {},
defaults: { cpu: 80, memory: 85, disk: 90 },
...overrides,
});
const renderGrouped = (resource: Resource, overrides: Record<string, any> = {}) =>
render(() => (
<ResourceTable
{...makeProps({
resources: undefined,
groupedResources: { node1: [resource] },
columns: ['CPU %', 'Memory %', 'Disk %'],
...overrides,
})}
/>
));
it.each([
['desktop', false],
['mobile', true],
])('states the thresholds the tag raises on the %s row', (_layout, mobile) => {
mockIsMobile.mockReturnValue(mobile);
renderGrouped(relaxedGuest());
const line = screen.getByTestId('alert-resource-relaxed-triggers');
expect(line).toHaveTextContent(
'Proxmox tag pulse-relaxed: alerts at CPU 95% · Memory 92% · Disk 95%',
);
expect(line.getAttribute('title')).toContain('Remove the tag in Proxmox');
// The row keeps showing the configured values the editor changes.
expect(screen.getByText('80')).toBeInTheDocument();
});
it('omits metrics the tag leaves alone', () => {
renderGrouped(relaxedGuest({ thresholds: { cpu: -1, memory: 96 } }));
expect(screen.getByTestId('alert-resource-relaxed-triggers')).toHaveTextContent(
'Proxmox tag pulse-relaxed: alerts at Disk 95%',
);
});
it('follows unsaved edits', () => {
renderGrouped(relaxedGuest(), {
editingId: () => 'vm-1',
editingThresholds: () => ({ cpu: 97, memory: 93, disk: 70 }),
});
expect(screen.getByTestId('alert-resource-relaxed-triggers')).toHaveTextContent(
'Proxmox tag pulse-relaxed: alerts at Disk 95%',
);
});
it('stays hidden when the tag raises nothing or alerts are off', () => {
renderGrouped(relaxedGuest({ thresholds: { cpu: 99, memory: 99, disk: 99 } }));
expect(screen.queryByTestId('alert-resource-relaxed-triggers')).toBeNull();
cleanup();
renderGrouped(relaxedGuest({ disabled: true }));
expect(screen.queryByTestId('alert-resource-relaxed-triggers')).toBeNull();
cleanup();
renderGrouped(relaxedGuest(), { globalDisableFlag: () => true });
expect(screen.queryByTestId('alert-resource-relaxed-triggers')).toBeNull();
cleanup();
renderGrouped(relaxedGuest({ pulseRelaxed: false }));
expect(screen.queryByTestId('alert-resource-relaxed-triggers')).toBeNull();
});
});
describe('metric display values', () => {
it('shows formatted metric values using formatMetricValue', () => {
const formatMetricValue = vi.fn((metric: string, value: number | undefined) => {
if (metric === 'cpu') return '90%';
if (metric === 'memory') return '85%';
return String(value);
});
const props = makeProps({
resources: [makeResource({ id: 'vm-1', thresholds: { cpu: 90, memory: 85 } })],
formatMetricValue,
});
render(() => <ResourceTable {...props} />);
expect(screen.getByText('90%')).toBeInTheDocument();
expect(screen.getByText('85%')).toBeInTheDocument();
});
it('shows "Off" text for disabled metrics (value -1) with disabled styling', () => {
const formatMetricValue = vi.fn((_metric: string, value: number | undefined) =>
value !== undefined ? String(value) : '-',
);
const props = makeProps({
resources: [makeResource({ id: 'vm-1', thresholds: { cpu: -1, memory: 85 } })],
columns: ['CPU %', 'Memory %'],
formatMetricValue,
});
render(() => <ResourceTable {...props} />);
// The disabled metric (cpu = -1) renders "Off" with italic styling
const offElements = screen.getAllByText('Off');
const disabledOff = offElements.find((el) => el.className.includes('italic'));
expect(disabledOff).toBeTruthy();
// formatMetricValue should NOT be called for disabled metrics (they show "Off" directly)
const cpuCalls = formatMetricValue.mock.calls.filter(([metric]) => metric === 'cpu');
expect(cpuCalls.length).toBe(0);
// Memory (85) should still be formatted normally
const memoryCalls = formatMetricValue.mock.calls.filter(([metric]) => metric === 'memory');
expect(memoryCalls.length).toBeGreaterThanOrEqual(1);
});
it.each([false, true])(
'reads a legacy 0 override as Off, like -1, without formatting it (mobile=%s)',
(mobile) => {
mockIsMobile.mockReturnValue(mobile);
const formatMetricValue = vi.fn((_metric: string, value: number | undefined) =>
value !== undefined ? String(value) : '-',
);
const props = makeProps({
resources: [makeResource({ id: 'vm-1', thresholds: { cpu: 0, memory: 85 } })],
columns: ['CPU %', 'Memory %'],
formatMetricValue,
});
render(() => <ResourceTable {...props} />);
expect(screen.getAllByText('Off').length).toBeGreaterThan(0);
if (!mobile) {
expect(screen.getAllByText('Off').some((el) => el.className.includes('italic'))).toBe(
true,
);
}
expect(formatMetricValue.mock.calls.filter(([metric]) => metric === 'cpu')).toHaveLength(0);
expect(
formatMetricValue.mock.calls.filter(([metric]) => metric === 'memory').length,
).toBeGreaterThanOrEqual(1);
},
);
it('shows active alert indicator dot when hasActiveAlert returns true', () => {
const hasActiveAlert = vi.fn((_resource: unknown, metric: string) => metric === 'cpu');
const resource = makeResource({
id: 'vm-1',
alertResourceIds: ['vm-1', 'pve1-101'],
thresholds: { cpu: 90, memory: 85 },
});
const props = makeProps({ resources: [resource], hasActiveAlert });
render(() => <ResourceTable {...props} />);
// The active alert indicator is a pulsing red dot
const alertDots = document.querySelectorAll('[title="Active alert"]');
expect(alertDots).toHaveLength(1);
expect(alertDots[0].className).toContain('animate-pulse');
// The row hands over the whole resource so its alert resource IDs reach the lookup.
expect(hasActiveAlert).toHaveBeenCalledWith(
expect.objectContaining({ id: 'vm-1', alertResourceIds: ['vm-1', 'pve1-101'] }),
'cpu',
);
});
});
describe('alert toggle', () => {
it('renders alert toggle when onToggleDisabled is provided', () => {
const onToggleDisabled = vi.fn();
const props = makeProps({
resources: [makeResource({ id: 'vm-1', disabled: false })],
onToggleDisabled,
});
render(() => <ResourceTable {...props} />);
const toggle = screen.getByRole('switch', { name: 'Alerts for Test VM' });
expect(toggle).toHaveAttribute('aria-checked', 'true');
});
it('calls onToggleDisabled with resource id when toggle is clicked', () => {
const onToggleDisabled = vi.fn();
const props = makeProps({
resources: [makeResource({ id: 'vm-1', disabled: false })],
onToggleDisabled,
});
render(() => <ResourceTable {...props} />);
const toggle = screen.getByRole('switch', { name: 'Alerts for Test VM' });
fireEvent.click(toggle);
expect(onToggleDisabled).toHaveBeenCalledWith('vm-1');
});
it('disables resource toggles when global disable is active', () => {
const onToggleDisabled = vi.fn();
const props = makeProps({
resources: [makeResource({ id: 'vm-1', disabled: false })],
onToggleDisabled,
globalDisableFlag: () => true,
});
render(() => <ResourceTable {...props} />);
const toggle = screen.getByRole('switch', { name: 'Alerts for Test VM' });
expect(toggle).toHaveAttribute('aria-checked', 'false');
expect(toggle).toBeDisabled();
});
it('applies opacity to disabled resources', () => {
const props = makeProps({
resources: [makeResource({ id: 'vm-1', disabled: true })],
onToggleDisabled: vi.fn(),
});
render(() => <ResourceTable {...props} />);
const row = screen.getByText('Test VM').closest('tr');
expect(row?.className).toContain('opacity-40');
});
});
describe('global defaults row', () => {
it('renders global defaults row when all three required props are provided', () => {
const props = makeProps({
globalDefaults: { cpu: 80, memory: 85 },
setGlobalDefaults: vi.fn(),
setHasUnsavedChanges: vi.fn(),
});
render(() => <ResourceTable {...props} />);
expect(screen.getByText('Global Defaults')).toBeInTheDocument();
});
it('shows Custom badge when global defaults differ from factory defaults', () => {
const props = makeProps({
resources: [],
globalDefaults: { cpu: 90, memory: 85 },
factoryDefaults: { cpu: 80, memory: 85 },
setGlobalDefaults: vi.fn(),
setHasUnsavedChanges: vi.fn(),
});
render(() => <ResourceTable {...props} />);
expect(screen.getByText('Custom')).toBeInTheDocument();
});
it('does not show Custom badge when defaults match factory', () => {
const props = makeProps({
resources: [],
globalDefaults: { cpu: 80, memory: 85 },
factoryDefaults: { cpu: 80, memory: 85 },
setGlobalDefaults: vi.fn(),
setHasUnsavedChanges: vi.fn(),
});
render(() => <ResourceTable {...props} />);
expect(screen.getByText('Global Defaults')).toBeInTheDocument();
expect(screen.queryByText('Custom')).not.toBeInTheDocument();
});
it('renders global toggle when onToggleGlobalDisable is provided', () => {
const onToggleGlobalDisable = vi.fn();
const props = makeProps({
resources: [],
globalDefaults: { cpu: 80 },
setGlobalDefaults: vi.fn(),
setHasUnsavedChanges: vi.fn(),
onToggleGlobalDisable,
globalDisableFlag: () => false,
});
render(() => <ResourceTable {...props} />);
const globalToggle = screen.getByRole('switch', { name: 'Global alerts toggle' });
expect(globalToggle).toBeInTheDocument();
});
it('calls onToggleGlobalDisable and setHasUnsavedChanges when global toggle is clicked', () => {
const onToggleGlobalDisable = vi.fn();
const setHasUnsavedChanges = vi.fn();
const props = makeProps({
resources: [],
globalDefaults: { cpu: 80 },
setGlobalDefaults: vi.fn(),
setHasUnsavedChanges,
onToggleGlobalDisable,
globalDisableFlag: () => false,
});
render(() => <ResourceTable {...props} />);
const globalToggle = screen.getByRole('switch', { name: 'Global alerts toggle' });
fireEvent.click(globalToggle);
expect(onToggleGlobalDisable).toHaveBeenCalled();
expect(setHasUnsavedChanges).toHaveBeenCalledWith(true);
});
it('calls setGlobalDefaults and setHasUnsavedChanges on input change', () => {
const setGlobalDefaults = vi.fn();
const setHasUnsavedChanges = vi.fn();
const props = makeProps({
resources: [],
globalDefaults: { cpu: 80 },
setGlobalDefaults,
setHasUnsavedChanges,
columns: ['CPU %'],
});
render(() => <ResourceTable {...props} />);
// Find the global defaults input (only one when no resources and one column)
const input = screen.getByDisplayValue('80');
fireEvent.input(input, { target: { value: '95' } });
expect(setGlobalDefaults).toHaveBeenCalled();
expect(setHasUnsavedChanges).toHaveBeenCalledWith(true);
});
it('shows reset to factory defaults button when custom and onResetDefaults provided', () => {
const onResetDefaults = vi.fn();
const props = makeProps({
resources: [],
globalDefaults: { cpu: 95 },
factoryDefaults: { cpu: 80 },
setGlobalDefaults: vi.fn(),
setHasUnsavedChanges: vi.fn(),
onResetDefaults,
});
render(() => <ResourceTable {...props} />);
const resetBtn = screen.getByLabelText('Reset to factory defaults');
fireEvent.click(resetBtn);
expect(onResetDefaults).toHaveBeenCalled();
});
});
it.each([false, true])(
'preserves host cluster context in threshold layouts (mobile=%s)',
(mobile) => {
mockIsMobile.mockReturnValue(mobile);
render(() => (
<ResourceTable
{...makeProps({
resources: [makeResource({ type: 'agent', name: 'A', clusterName: 'Analytics' })],
})}
/>
));
expect(screen.getByText('Analytics')).toBeInTheDocument();
},
);
it.each([false, true])(
'keeps backup and snapshot configs out of numeric defaults (mobile=%s)',
(mobile) => {
mockIsMobile.mockReturnValue(mobile);
render(() => (
<ResourceTable
{...makeProps({
resources: [],
columns: ['CPU %', 'Backup', 'Snapshot'],
globalDefaults: { cpu: 80 },
setGlobalDefaults: vi.fn(),
setHasUnsavedChanges: vi.fn(),
})}
/>
));
expect(screen.getAllByRole('spinbutton')).toHaveLength(1);
expect(screen.getAllByTestId('status-badge')).toHaveLength(1);
},
);
// Moving between form controls, assistive tech reads a control's own name,
// not its column header: every threshold input and On/Off toggle on the
// page used to sound alike ("Click to enable this metric", "On").
describe('threshold control names', () => {
it.each([false, true])(
'names each global default input and toggle by its metric (mobile=%s)',
(mobile) => {
mockIsMobile.mockReturnValue(mobile);
const props = makeProps({
columns: ['CPU %', 'Memory %'],
resources: [],
globalDefaults: { cpu: 80, memory: 85 },
setGlobalDefaults: vi.fn(),
setHasUnsavedChanges: vi.fn(),
});
render(() => <ResourceTable {...props} />);
expect(screen.getByRole('spinbutton', { name: 'CPU % default' })).toHaveValue(80);
expect(screen.getByRole('spinbutton', { name: 'Memory % default' })).toHaveValue(85);
expect(screen.getByRole('button', { name: 'CPU % default alerts: On' })).toHaveAttribute(
'aria-pressed',
'true',
);
},
);
it.each([false, true])(
'names an override input and toggle by metric and resource (mobile=%s)',
(mobile) => {
mockIsMobile.mockReturnValue(mobile);
const props = makeProps({
columns: ['CPU %'],
editingId: () => 'vm-1',
editingThresholds: () => ({ cpu: 90 }),
resources: [
makeResource({
id: 'vm-1',
name: 'web-01',
thresholds: { cpu: 90 },
defaults: { cpu: 80 },
}),
],
});
render(() => <ResourceTable {...props} />);
expect(screen.getByRole('spinbutton', { name: 'CPU % for web-01' })).toHaveValue(90);
expect(
screen.getByRole('button', { name: 'CPU % for web-01 alerts: On' }),
).toBeInTheDocument();
},
);
it.each([false, true])(
'names the offline alert toggles for the default and each resource (mobile=%s)',
(mobile) => {
mockIsMobile.mockReturnValue(mobile);
const props = makeProps({
columns: ['CPU %'],
resources: [makeResource({ id: 'node-a', name: 'pve-a', type: 'node' })],
globalDefaults: { cpu: 80 },
setGlobalDefaults: vi.fn(),
setHasUnsavedChanges: vi.fn(),
showOfflineAlertsColumn: true,
onToggleGlobalDisableOffline: vi.fn(),
globalDisableOfflineFlag: () => false,
onToggleNodeConnectivity: vi.fn(),
});
render(() => <ResourceTable {...props} />);
expect(
screen.getByRole('button', { name: /^Offline alerts default: On$/ }),
).toBeInTheDocument();
expect(
screen.getByRole('button', { name: /^Offline alerts for pve-a: / }),
).toBeInTheDocument();
},
);
it.each([false, true])(
'names each resource backup and snapshot toggle (mobile=%s)',
(mobile) => {
mockIsMobile.mockReturnValue(mobile);
const props = makeProps({
columns: ['Backup', 'Snapshot'],
resources: [
makeResource({
id: 'vm-1',
name: 'web-01',
backup: { enabled: true },
snapshot: { enabled: false },
}),
],
onToggleBackup: vi.fn(),
onToggleSnapshot: vi.fn(),
});
render(() => <ResourceTable {...props} />);
expect(screen.getByRole('button', { name: /^Backup alerts for web-01: / })).toHaveAttribute(
'aria-pressed',
'true',
);
expect(
screen.getByRole('button', { name: /^Snapshot alerts for web-01: / }),
).toHaveAttribute('aria-pressed', 'false');
},
);
// Proxmox guests and Docker containers cycle Warn / Crit / Off instead
// of a binary badge; their names carry the context and the visible word.
it.each([false, true])(
'names the three-state offline controls for the default and each guest (mobile=%s)',
(mobile) => {
mockIsMobile.mockReturnValue(mobile);
const props = makeProps({
columns: ['CPU %'],
resources: undefined,
groupedResources: {
node1: [makeResource({ id: 'vm-1', name: 'VM1', type: 'guest' })],
},
globalDefaults: { cpu: 80 },
setGlobalDefaults: vi.fn(),
setHasUnsavedChanges: vi.fn(),
showOfflineAlertsColumn: true,
onSetGlobalOfflineState: vi.fn(),
onSetOfflineState: vi.fn(),
});
render(() => <ResourceTable {...props} />);
expect(
screen.getByRole('button', { name: 'Offline alerts default: Warn' }),
).toBeInTheDocument();
expect(
screen.getByRole('button', { name: 'Offline alerts for VM1: Warn' }),
).toBeInTheDocument();
},
);
// A metric cell outside edit mode is a button showing the current value;
// its name says which threshold it edits and repeats that value.
it.each([false, true])(
'names each metric value button with its resource and shown value (mobile=%s)',
(mobile) => {
mockIsMobile.mockReturnValue(mobile);
const props = makeProps({
columns: ['CPU %', 'Memory %'],
resources: [
makeResource({
id: 'vm-1',
name: 'web-01',
thresholds: { cpu: 90, memory: -1 },
defaults: { cpu: 80, memory: 85 },
}),
],
});
render(() => <ResourceTable {...props} />);
expect(
screen.getByRole('button', { name: 'Edit CPU % threshold for web-01: 90' }),
).toBeInTheDocument();
expect(
screen.getByRole('button', { name: 'Edit Memory % threshold for web-01: Off' }),
).toBeInTheDocument();
},
);
it.each([false, true])(
'names the global and per-resource alert switches (mobile=%s)',
(mobile) => {
mockIsMobile.mockReturnValue(mobile);
const props = makeProps({
columns: ['CPU %'],
resources: [makeResource({ id: 'vm-1', name: 'web-01' })],
globalDefaults: { cpu: 80 },
setGlobalDefaults: vi.fn(),
setHasUnsavedChanges: vi.fn(),
onToggleGlobalDisable: vi.fn(),
globalDisableFlag: () => false,
onToggleDisabled: vi.fn(),
});
render(() => <ResourceTable {...props} />);
expect(screen.getByRole('switch', { name: 'Global alerts toggle' })).toHaveAttribute(
'aria-checked',
'true',
);
expect(screen.getByRole('switch', { name: 'Alerts for web-01' })).toBeInTheDocument();
},
);
});
describe('metric off toggles', () => {
// The alert engine disables a metric whenever its trigger is <= 0, so every
// editor here has to agree on that reading and has to write a value the
// engine will actually honour.
function editorProps(overrides: Record<string, any> = {}) {
return makeProps({
columns: ['CPU %'],
editingId: () => 'vm-1',
...overrides,
});
}
it.each([false, true])(
'reads a stored 0 override as Off in the row editor (mobile=%s)',
(mobile) => {
mockIsMobile.mockReturnValue(mobile);
const props = editorProps({
resources: [makeResource({ id: 'vm-1', thresholds: { cpu: 0 }, defaults: { cpu: 80 } })],
editingThresholds: () => ({ cpu: 0 }),
});
render(() => <ResourceTable {...props} />);
expect(screen.getByTestId('status-badge')).toHaveTextContent('Off');
},
);
it.each([false, true])(
'does not stage 0 through the row numeric input (mobile=%s)',
(mobile) => {
mockIsMobile.mockReturnValue(mobile);
const setEditingThresholds = vi.fn();
const props = editorProps({
resources: [makeResource({ id: 'vm-1', thresholds: { cpu: 80 }, defaults: { cpu: 80 } })],
editingThresholds: () => ({ cpu: 80 }),
setEditingThresholds,
});
render(() => <ResourceTable {...props} />);
fireEvent.input(screen.getByRole('spinbutton'), { target: { value: '0' } });
expect(setEditingThresholds).not.toHaveBeenCalled();
},
);
it.each([false, true])(
'stages an explicit threshold when the inherited default is itself off (mobile=%s)',
(mobile) => {
mockIsMobile.mockReturnValue(mobile);
// Clearing the override would only re-inherit the disabled default, so
// the save path would drop the change and the metric would stay off.
const setEditingThresholds = vi.fn();
const props = editorProps({
resources: [makeResource({ id: 'vm-1', thresholds: {}, defaults: { cpu: -1 } })],
editingThresholds: () => ({ cpu: -1 }),
setEditingThresholds,
});
render(() => <ResourceTable {...props} />);
fireEvent.click(screen.getByTestId('status-badge'));
expect(setEditingThresholds).toHaveBeenCalledWith({ cpu: 80 });
},
);
it.each([false, true])(
'clears the override when the inherited default is already enabled (mobile=%s)',
(mobile) => {
mockIsMobile.mockReturnValue(mobile);
const setEditingThresholds = vi.fn();
const props = editorProps({
resources: [makeResource({ id: 'vm-1', thresholds: { cpu: -1 }, defaults: { cpu: 80 } })],
editingThresholds: () => ({ cpu: -1 }),
setEditingThresholds,
});
render(() => <ResourceTable {...props} />);
fireEvent.click(screen.getByTestId('status-badge'));
expect(setEditingThresholds).toHaveBeenCalledWith({ cpu: undefined });
},
);
it.each([false, true])(
'turns a metric off with the canonical -1 sentinel (mobile=%s)',
(mobile) => {
mockIsMobile.mockReturnValue(mobile);
const setEditingThresholds = vi.fn();
const props = editorProps({
resources: [makeResource({ id: 'vm-1', thresholds: { cpu: 80 }, defaults: { cpu: 80 } })],
editingThresholds: () => ({ cpu: 80 }),
setEditingThresholds,
});
render(() => <ResourceTable {...props} />);
fireEvent.click(screen.getByTestId('status-badge'));
expect(setEditingThresholds).toHaveBeenCalledWith({ cpu: -1 });
},
);
it.each([false, true])(
'clears an override to inherit without disabling (mobile=%s)',
(mobile) => {
mockIsMobile.mockReturnValue(mobile);
const setEditingThresholds = vi.fn();
const props = editorProps({
resources: [makeResource({ id: 'vm-1', thresholds: { cpu: 90 }, defaults: { cpu: 80 } })],
editingThresholds: () => ({ cpu: 90 }),
setEditingThresholds,
});
render(() => <ResourceTable {...props} />);
fireEvent.input(screen.getByRole('spinbutton'), { target: { value: '' } });
expect(setEditingThresholds).toHaveBeenCalledWith({ cpu: undefined });
},
);
it.each([false, true])(
'clearing an override inherits Off and enables in one toggle (mobile=%s)',
(mobile) => {
mockIsMobile.mockReturnValue(mobile);
const [editingThresholds, setEditingThresholds] = createSignal<
Record<string, number | undefined>
>({ cpu: 81 });
render(() => (
<ResourceTable
{...editorProps({
editingThresholds,
setEditingThresholds,
resources: [
makeResource({ id: 'vm-1', thresholds: { cpu: 81 }, defaults: { cpu: 0 } }),
],
})}
/>
));
fireEvent.input(screen.getByRole('spinbutton'), { target: { value: '' } });
expect(editingThresholds().cpu).toBeUndefined();
expect(screen.getByTestId('status-badge')).toHaveTextContent('Off');
if (!mobile) expect(screen.getByRole('slider')).toBeDisabled();
fireEvent.click(screen.getByTestId('status-badge'));
expect(editingThresholds().cpu).toBe(80);
expect(screen.getByRole('spinbutton')).toHaveValue(80);
expect(screen.getByTestId('status-badge')).toHaveTextContent('On');
},
);
it('keeps the editor open when focus moves from the input to the off toggle', () => {
// Tabbing to the toggle must not save and close the row before the toggle
// can be operated.
const onSaveEdit = vi.fn();
const props = editorProps({
resources: [makeResource({ id: 'vm-1', thresholds: { cpu: 80 }, defaults: { cpu: 80 } })],
editingThresholds: () => ({ cpu: 80 }),
onSaveEdit,
});
render(() => <ResourceTable {...props} />);
const input = screen.getByRole('spinbutton');
fireEvent.focusOut(input, { relatedTarget: screen.getByTestId('status-badge') });
expect(onSaveEdit).not.toHaveBeenCalled();
});
it.each([false, true])(
'opens from the focused edit button and focuses the first input (mobile=%s)',
async (mobile) => {
mockIsMobile.mockReturnValue(mobile);
const [editingId, setEditingId] = createSignal<string | null>(null);
const onSaveEdit = vi.fn();
render(() => (
<>
<button data-testid="outside-entry">Other action</button>
<ResourceTable
{...editorProps({
editingId,
onSaveEdit,
onEdit: () => setEditingId('vm-1'),
resources: [makeResource({ id: 'vm-1' })],
})}
/>
</>
));
const edit = screen.getByLabelText('Edit thresholds for Test VM');
edit.focus();
fireEvent.click(edit);
await waitFor(() => expect(document.activeElement).toBe(screen.getByRole('spinbutton')));
expect(onSaveEdit).not.toHaveBeenCalled();
screen.getByTestId('outside-entry').focus();
if (mobile) {
expect(onSaveEdit).not.toHaveBeenCalled();
fireEvent.click(screen.getByLabelText('Save threshold edits for Test VM'));
}
expect(onSaveEdit).toHaveBeenCalledWith('vm-1');
},
);
it.each([false, true])(
'transfers the current metric focus and draft between layouts (mobile=%s)',
async (initialMobile) => {
const [mobile, setMobile] = createSignal(initialMobile);
mockIsMobile.mockImplementation(mobile);
const onSaveEdit = vi.fn();
const [editingThresholds, setEditingThresholds] = createSignal({ cpu: 80, memory: 85 });
render(() => (
<ResourceTable
{...editorProps({
columns: ['CPU %', 'Memory %'],
editingThresholds,
setEditingThresholds,
onSaveEdit,
resources: [makeResource({ id: 'vm-1', defaults: { cpu: 80, memory: 85 } })],
})}
/>
));
const memory = screen.getAllByRole('spinbutton')[1];
memory.focus();
fireEvent.input(memory, { target: { value: '93' } });
setMobile(!initialMobile);
await waitFor(() =>
expect(document.activeElement).toBe(screen.getAllByRole('spinbutton')[1]),
);
expect(screen.getAllByRole('spinbutton')[1]).toHaveValue(93);
expect(onSaveEdit).not.toHaveBeenCalled();
setMobile(initialMobile);
await waitFor(() =>
expect(document.activeElement).toBe(screen.getAllByRole('spinbutton')[1]),
);
expect(screen.getAllByRole('spinbutton')[1]).toHaveValue(93);
expect(onSaveEdit).not.toHaveBeenCalled();
},
);
it('keeps the editor open when focus moves from the number to its slider', () => {
const onSaveEdit = vi.fn();
render(() => (
<ResourceTable
{...editorProps({ onSaveEdit, resources: [makeResource({ id: 'vm-1' })] })}
/>
));
screen.getByRole('spinbutton').focus();
screen.getByRole('slider').focus();
expect(onSaveEdit).not.toHaveBeenCalled();
});
it('saves when focus leaves the edited row after the Off toggle', () => {
const onSaveEdit = vi.fn();
render(() => (
<>
<button data-testid="outside-row">Other action</button>
<ResourceTable
{...editorProps({ onSaveEdit, resources: [makeResource({ id: 'vm-1' })] })}
/>
</>
));
screen.getByRole('spinbutton').focus();
screen.getByTestId('status-badge').focus();
screen.getByTestId('outside-row').focus();
expect(onSaveEdit).toHaveBeenCalledWith('vm-1');
});
it('lets Cancel discard a focused threshold without saving', () => {
const onSaveEdit = vi.fn();
const onCancelEdit = vi.fn();
render(() => (
<ResourceTable
{...editorProps({
onSaveEdit,
onCancelEdit,
resources: [makeResource({ id: 'vm-1' })],
})}
/>
));
screen.getByRole('spinbutton').focus();
const cancel = screen.getByLabelText('Cancel editing');
cancel.focus();
fireEvent.click(cancel);
expect(onCancelEdit).toHaveBeenCalledOnce();
expect(onSaveEdit).not.toHaveBeenCalled();
});
it('keeps editing when keyboard focus moves to another metric in the row', () => {
const onSaveEdit = vi.fn();
render(() => (
<ResourceTable
{...editorProps({
onSaveEdit,
columns: ['CPU %', 'Memory %'],
resources: [makeResource({ id: 'vm-1' })],
})}
/>
));
const inputs = screen.getAllByRole('spinbutton');
inputs[0].focus();
inputs[1].focus();
expect(onSaveEdit).not.toHaveBeenCalled();
});
it('still saves when focus leaves the metric editor entirely', () => {
const onSaveEdit = vi.fn();
const props = editorProps({
resources: [makeResource({ id: 'vm-1', thresholds: { cpu: 80 }, defaults: { cpu: 80 } })],
editingThresholds: () => ({ cpu: 80 }),
onSaveEdit,
});
render(() => <ResourceTable {...props} />);
screen.getByRole('spinbutton').focus();
fireEvent.focusOut(screen.getByRole('spinbutton'), { relatedTarget: null });
expect(onSaveEdit).toHaveBeenCalledWith('vm-1');
});
it('shows an unset global default as Off and re-enables it explicitly', () => {
const setGlobalDefaults = vi.fn();
const props = makeProps({
resources: [],
columns: ['CPU %'],
globalDefaults: {},
setGlobalDefaults,
setHasUnsavedChanges: vi.fn(),
});
render(() => <ResourceTable {...props} />);
expect(screen.getByTestId('status-badge')).toHaveTextContent('Off');
fireEvent.click(screen.getByTestId('status-badge'));
const updater = setGlobalDefaults.mock.calls[0][0] as (
prev: Record<string, number | undefined>,
) => Record<string, number | undefined>;
expect(updater({})).toEqual({ cpu: 80 });
});
it('shows a stored 0 global default as Off', () => {
const props = makeProps({
resources: [],
columns: ['CPU %'],
globalDefaults: { cpu: 0 },
setGlobalDefaults: vi.fn(),
setHasUnsavedChanges: vi.fn(),
});
render(() => <ResourceTable {...props} />);
expect(screen.getByTestId('status-badge')).toHaveTextContent('Off');
});
it('does not write a disabling 0 when the global default input is cleared', () => {
const setGlobalDefaults = vi.fn();
const setHasUnsavedChanges = vi.fn();
const props = makeProps({
resources: [],
columns: ['CPU %'],
globalDefaults: { cpu: 80 },
setGlobalDefaults,
setHasUnsavedChanges,
});
render(() => <ResourceTable {...props} />);
fireEvent.input(screen.getByDisplayValue('80'), { target: { value: '' } });
expect(setGlobalDefaults).not.toHaveBeenCalled();
expect(setHasUnsavedChanges).not.toHaveBeenCalled();
});
it('turns a global default off with the canonical -1 sentinel', () => {
const setGlobalDefaults = vi.fn();
const props = makeProps({
resources: [],
columns: ['CPU %'],
globalDefaults: { cpu: 80 },
setGlobalDefaults,
setHasUnsavedChanges: vi.fn(),
});
render(() => <ResourceTable {...props} />);
fireEvent.click(screen.getByTestId('status-badge'));
const updater = setGlobalDefaults.mock.calls[0][0] as (
prev: Record<string, number | undefined>,
) => Record<string, number | undefined>;
expect(updater({ cpu: 80 })).toEqual({ cpu: -1 });
});
it('applies the same off reading to the mobile global defaults card', () => {
mockIsMobile.mockReturnValue(true);
const setGlobalDefaults = vi.fn();
const props = makeProps({
resources: [],
columns: ['CPU %'],
globalDefaults: { cpu: 0 },
setGlobalDefaults,
setHasUnsavedChanges: vi.fn(),
});
render(() => <ResourceTable {...props} />);
expect(screen.getByTestId('status-badge')).toHaveTextContent('Off');
fireEvent.click(screen.getByTestId('status-badge'));
const updater = setGlobalDefaults.mock.calls[0][0] as (
prev: Record<string, number | undefined>,
) => Record<string, number | undefined>;
expect(updater({ cpu: 0 })).toEqual({ cpu: 80 });
});
it.each([
['desktop', false],
['mobile', true],
])('lets an unset %s global default follow its fallback', (_layout, mobile) => {
mockIsMobile.mockReturnValue(mobile);
const setGlobalDefaults = vi.fn();
const props = makeProps({
resources: [],
columns: ['Temp °C'],
globalDefaults: { temperature: undefined },
globalDefaultFallbacks: {
temperature: { label: 'By type', title: 'Follows Disk temperature by type' },
},
setGlobalDefaults,
setHasUnsavedChanges: vi.fn(),
});
render(() => <ResourceTable {...props} />);
// Unset reads On and names where the value comes from.
expect(screen.getByTestId('status-badge')).toHaveTextContent('On');
const input = screen.getByPlaceholderText('By type') as HTMLInputElement;
expect(input.value).toBe('');
expect(input.disabled).toBe(false);
expect(input.title).toBe('Follows Disk temperature by type');
fireEvent.click(screen.getByTestId('status-badge'));
const updater = setGlobalDefaults.mock.calls[0][0] as (
prev: Record<string, number | undefined>,
) => Record<string, number | undefined>;
expect(updater({ temperature: undefined })).toEqual({ temperature: -1 });
});
it.each([
['desktop', false],
['mobile', true],
])('switches an Off %s fallback default back to following', (_layout, mobile) => {
mockIsMobile.mockReturnValue(mobile);
const setGlobalDefaults = vi.fn();
const props = makeProps({
resources: [],
columns: ['Temp °C'],
globalDefaults: { temperature: -1 },
globalDefaultFallbacks: {
temperature: { label: 'By type', title: 'Follows Disk temperature by type' },
},
setGlobalDefaults,
setHasUnsavedChanges: vi.fn(),
});
render(() => <ResourceTable {...props} />);
expect(screen.getByTestId('status-badge')).toHaveTextContent('Off');
fireEvent.click(screen.getByTestId('status-badge'));
const updater = setGlobalDefaults.mock.calls[0][0] as (
prev: Record<string, number | undefined>,
) => Record<string, number | undefined>;
expect(updater({ temperature: -1 })).toEqual({ temperature: undefined });
});
it.each([
['desktop', false],
['mobile', true],
])('reads an unset %s default Off when its fallback is off', (_layout, mobile) => {
mockIsMobile.mockReturnValue(mobile);
const setGlobalDefaults = vi.fn();
const props = makeProps({
resources: [],
columns: ['Temp °C'],
globalDefaults: { temperature: undefined },
globalDefaultFallbacks: {
temperature: { label: 'By type', title: 'Off by type', off: true, enableValue: 55 },
},
setGlobalDefaults,
setHasUnsavedChanges: vi.fn(),
});
render(() => <ResourceTable {...props} />);
expect(screen.getByTestId('status-badge')).toHaveTextContent('Off');
expect(screen.queryByPlaceholderText('By type')).toBeNull();
// Unset would still be off, so switching on stages an explicit value.
fireEvent.click(screen.getByTestId('status-badge'));
const updater = setGlobalDefaults.mock.calls[0][0] as (
prev: Record<string, number | undefined>,
) => Record<string, number | undefined>;
expect(updater({ temperature: undefined })).toEqual({ temperature: 55 });
});
it('shows a set fallback global default as its number', () => {
const props = makeProps({
resources: [],
columns: ['Temp °C'],
globalDefaults: { temperature: 62 },
globalDefaultFallbacks: {
temperature: { label: 'By type', title: 'Follows Disk temperature by type' },
},
setGlobalDefaults: vi.fn(),
setHasUnsavedChanges: vi.fn(),
});
render(() => <ResourceTable {...props} />);
expect(screen.getByDisplayValue('62')).toBeInTheDocument();
expect(screen.queryByPlaceholderText('By type')).toBeNull();
});
it('follows global defaults that arrive after the table mounts', () => {
const [globalDefaults, setGlobalDefaults] = createSignal<Record<string, number | undefined>>({
temperature: undefined,
});
const props = makeProps({
resources: [],
columns: ['Temp °C'],
factoryDefaults: { temperature: undefined },
onResetDefaults: vi.fn(),
setGlobalDefaults: vi.fn(),
setHasUnsavedChanges: vi.fn(),
});
render(() => <ResourceTable {...props} globalDefaults={globalDefaults()} />);
expect(screen.queryByText('Custom')).toBeNull();
// The saved config loads after mount.
setGlobalDefaults({ temperature: 62 });
expect(screen.getByText('Custom')).toBeInTheDocument();
});
it('uses a table column tooltip over the generic one', () => {
const props = makeProps({
resources: [],
columns: ['Temp °C'],
columnTooltips: { 'Temp °C': 'Disk temperature that raises an alert.' },
});
render(() => <ResourceTable {...props} />);
expect(screen.getByText('Temp °C', { selector: 'th' })).toHaveAttribute(
'title',
'Disk temperature that raises an alert.',
);
});
it('stages an explicit threshold from the mobile row editor', () => {
mockIsMobile.mockReturnValue(true);
const setEditingThresholds = vi.fn();
const props = makeProps({
columns: ['CPU %'],
resources: [makeResource({ id: 'vm-1', thresholds: {}, defaults: { cpu: -1 } })],
editingId: () => 'vm-1',
editingThresholds: () => ({ cpu: -1 }),
setEditingThresholds,
globalDefaults: undefined,
});
render(() => <ResourceTable {...props} />);
fireEvent.click(screen.getByTestId('status-badge'));
expect(setEditingThresholds).toHaveBeenCalledWith({ cpu: 80 });
});
});
describe('grouped resources', () => {
it('renders group headers for grouped resources', () => {
const props = makeProps({
resources: undefined,
groupedResources: {
'node-a': [makeResource({ id: 'vm-1', name: 'VM 1' })],
'node-b': [makeResource({ id: 'vm-2', name: 'VM 2' })],
},
});
render(() => <ResourceTable {...props} />);
expect(screen.getByText('node-a')).toBeInTheDocument();
expect(screen.getByText('node-b')).toBeInTheDocument();
expect(screen.getByText('VM 1')).toBeInTheDocument();
expect(screen.getByText('VM 2')).toBeInTheDocument();
});
it('renders node group headers with display name and cluster name', () => {
const props = makeProps({
resources: undefined,
groupedResources: {
pve1: [makeResource({ id: 'vm-1', name: 'VM 1' })],
},
groupHeaderMeta: {
pve1: {
type: 'agent',
displayName: 'PVE Node 1',
clusterName: 'production',
},
},
});
render(() => <ResourceTable {...props} />);
expect(screen.getByText('PVE Node 1')).toBeInTheDocument();
expect(screen.getByText('production')).toBeInTheDocument();
});
it('renders group header with link when host is provided', () => {
const props = makeProps({
resources: undefined,
groupedResources: {
pve1: [makeResource({ id: 'vm-1', name: 'VM 1' })],
},
groupHeaderMeta: {
pve1: {
type: 'agent',
displayName: 'PVE Node 1',
host: 'https://pve1.example.com:8006',
},
},
});
render(() => <ResourceTable {...props} />);
expect(screen.getByText('PVE Node 1').tagName).toBe('SPAN');
const link = screen.getByRole('link', {
name: 'Open web interface for PVE Node 1',
});
expect(link).toHaveAttribute('href', 'https://pve1.example.com:8006');
expect(link).toHaveAttribute('target', '_blank');
});
});
describe('offline alerts column', () => {
it('renders Offline Alerts column header when showOfflineAlertsColumn is true', () => {
const props = makeProps({ showOfflineAlertsColumn: true });
render(() => <ResourceTable {...props} />);
expect(screen.getByText('Offline Alerts')).toBeInTheDocument();
});
it('does not render Offline Alerts column header when showOfflineAlertsColumn is false', () => {
const props = makeProps({ showOfflineAlertsColumn: false });
render(() => <ResourceTable {...props} />);
expect(screen.queryByText('Offline Alerts')).not.toBeInTheDocument();
});
});
describe('bulk edit', () => {
it('renders select-all checkbox when onBulkEdit is provided', () => {
const onBulkEdit = vi.fn();
const props = makeProps({
resources: [
makeResource({ id: 'vm-1', name: 'VM 1' }),
makeResource({ id: 'vm-2', name: 'VM 2' }),
],
onBulkEdit,
});
render(() => <ResourceTable {...props} />);
expect(screen.getByLabelText('Select all resources')).toBeInTheDocument();
});
it('renders per-resource checkboxes when onBulkEdit is provided', () => {
const onBulkEdit = vi.fn();
const props = makeProps({
resources: [
makeResource({ id: 'vm-1', name: 'VM Alpha' }),
makeResource({ id: 'vm-2', name: 'VM Beta' }),
],
onBulkEdit,
});
render(() => <ResourceTable {...props} />);
expect(screen.getByLabelText('Select VM Alpha')).toBeInTheDocument();
expect(screen.getByLabelText('Select VM Beta')).toBeInTheDocument();
});
it('does not render checkboxes when onBulkEdit is not provided', () => {
const props = makeProps({
resources: [makeResource({ id: 'vm-1', name: 'VM Alpha' })],
});
render(() => <ResourceTable {...props} />);
expect(screen.queryByLabelText('Select all resources')).not.toBeInTheDocument();
expect(screen.queryByLabelText('Select VM Alpha')).not.toBeInTheDocument();
});
it('toggles individual resource selection', () => {
const onBulkEdit = vi.fn();
const props = makeProps({
resources: [
makeResource({ id: 'vm-1', name: 'VM Alpha' }),
makeResource({ id: 'vm-2', name: 'VM Beta' }),
],
onBulkEdit,
});
render(() => <ResourceTable {...props} />);
const checkbox = screen.getByLabelText('Select VM Alpha') as HTMLInputElement;
expect(checkbox.checked).toBe(false);
fireEvent.change(checkbox, { target: { checked: true } });
expect(checkbox.checked).toBe(true);
});
it('select-all checks all resource checkboxes', () => {
const onBulkEdit = vi.fn();
const props = makeProps({
resources: [
makeResource({ id: 'vm-1', name: 'VM Alpha' }),
makeResource({ id: 'vm-2', name: 'VM Beta' }),
],
onBulkEdit,
});
render(() => <ResourceTable {...props} />);
const selectAll = screen.getByLabelText('Select all resources') as HTMLInputElement;
fireEvent.change(selectAll, { target: { checked: true } });
const checkboxAlpha = screen.getByLabelText('Select VM Alpha') as HTMLInputElement;
const checkboxBeta = screen.getByLabelText('Select VM Beta') as HTMLInputElement;
expect(checkboxAlpha.checked).toBe(true);
expect(checkboxBeta.checked).toBe(true);
});
it('calls onBulkEdit with selected resource ids when Bulk Edit Settings is clicked', () => {
const onBulkEdit = vi.fn();
const props = makeProps({
resources: [
makeResource({ id: 'vm-1', name: 'VM Alpha' }),
makeResource({ id: 'vm-2', name: 'VM Beta' }),
makeResource({ id: 'vm-3', name: 'VM Gamma' }),
],
onBulkEdit,
});
render(() => <ResourceTable {...props} />);
// Select two resources
fireEvent.change(screen.getByLabelText('Select VM Alpha'), { target: { checked: true } });
fireEvent.change(screen.getByLabelText('Select VM Gamma'), { target: { checked: true } });
// The floating action bar with "Bulk Edit Settings" should appear
const bulkEditBtn = screen.getByText('Bulk Edit Settings');
fireEvent.click(bulkEditBtn);
expect(onBulkEdit).toHaveBeenCalledTimes(1);
const calledWith = onBulkEdit.mock.calls[0][0] as string[];
expect(calledWith).toHaveLength(2);
expect(calledWith).toContain('vm-1');
expect(calledWith).toContain('vm-3');
});
it('clears selection after bulk edit is triggered', () => {
const onBulkEdit = vi.fn();
const props = makeProps({
resources: [
makeResource({ id: 'vm-1', name: 'VM Alpha' }),
makeResource({ id: 'vm-2', name: 'VM Beta' }),
],
onBulkEdit,
});
render(() => <ResourceTable {...props} />);
// Select a resource
fireEvent.change(screen.getByLabelText('Select VM Alpha'), { target: { checked: true } });
// Click bulk edit
fireEvent.click(screen.getByText('Bulk Edit Settings'));
// After bulk edit, selection should be cleared and the floating bar should disappear
expect(screen.queryByText('Bulk Edit Settings')).not.toBeInTheDocument();
});
it('clears selection when clear button is clicked', () => {
const onBulkEdit = vi.fn();
const props = makeProps({
resources: [makeResource({ id: 'vm-1', name: 'VM Alpha' })],
onBulkEdit,
});
render(() => <ResourceTable {...props} />);
// Select a resource
fireEvent.change(screen.getByLabelText('Select VM Alpha'), { target: { checked: true } });
expect(screen.getByText('Bulk Edit Settings')).toBeInTheDocument();
// Click clear selection
fireEvent.click(screen.getByLabelText(ALERT_BULK_EDIT_CLEAR_LABEL));
expect(screen.queryByText('Bulk Edit Settings')).not.toBeInTheDocument();
});
});
describe('resource type-specific metric support', () => {
it('only formats supported metrics for storage type (usage only)', () => {
const formatMetricValue = vi.fn((_metric: string, _value: number | undefined) => '80');
const props = makeProps({
resources: [
makeResource({ id: 'st-1', name: 'Storage', type: 'storage', thresholds: { usage: 80 } }),
],
columns: ['CPU %', 'Memory %', 'Usage %'],
formatMetricValue,
});
render(() => <ResourceTable {...props} />);
// Storage only supports 'usage' — cpu and memory should NOT be formatted
const usageCalls = formatMetricValue.mock.calls.filter((args) => args[0] === 'usage');
expect(usageCalls.length).toBeGreaterThanOrEqual(1);
const cpuCalls = formatMetricValue.mock.calls.filter((args) => args[0] === 'cpu');
const memoryCalls = formatMetricValue.mock.calls.filter((args) => args[0] === 'memory');
expect(cpuCalls.length).toBe(0);
expect(memoryCalls.length).toBe(0);
});
it('hides disk/network metrics for node type', () => {
const formatMetricValue = vi.fn((_metric: string, _value: number | undefined) => '80');
const props = makeProps({
resources: [
makeResource({
id: 'node-1',
name: 'Node 1',
type: 'agent',
thresholds: { cpu: 80 },
}),
],
columns: ['CPU %', 'Disk R MB/s', 'Disk W MB/s', 'Net In MB/s', 'Net Out MB/s'],
formatMetricValue,
});
render(() => <ResourceTable {...props} />);
// formatMetricValue should only be called for 'cpu', not for unsupported network/disk metrics
const cpuCalls = formatMetricValue.mock.calls.filter((args) => args[0] === 'cpu');
expect(cpuCalls.length).toBeGreaterThanOrEqual(1);
// Unsupported metrics should not call formatMetricValue
const unsupportedCalls = formatMetricValue.mock.calls.filter((args) =>
['diskRead', 'diskWrite', 'networkIn', 'networkOut'].includes(args[0] ?? ''),
);
expect(unsupportedCalls.length).toBe(0);
});
it('shows only cpu and memory for pbs type', () => {
const formatMetricValue = vi.fn((_metric: string, _value: number | undefined) => '80');
const props = makeProps({
resources: [
makeResource({
id: 'pbs-1',
name: 'PBS Node',
type: 'pbs',
thresholds: { cpu: 80, memory: 85, disk: 90 },
}),
],
columns: ['CPU %', 'Memory %', 'Disk %'],
formatMetricValue,
});
render(() => <ResourceTable {...props} />);
// Disk should not call formatMetricValue since PBS doesn't support it
const diskCalls = formatMetricValue.mock.calls.filter((args) => args[0] === 'disk');
expect(diskCalls.length).toBe(0);
});
});
describe('node type rendering', () => {
it('prefers displayName for agent resources and action labels', () => {
const props = makeProps({
resources: [
makeResource({
id: 'node-1',
name: 'pve-node-1',
displayName: 'PVE Node 1',
type: 'agent',
host: 'https://192.168.0.10:8006',
}),
],
});
render(() => <ResourceTable {...props} />);
expect(screen.getByText('PVE Node 1').tagName).toBe('SPAN');
const link = screen.getByRole('link', {
name: 'Open web interface for PVE Node 1',
});
expect(link).toHaveAttribute('href', 'https://192.168.0.10:8006');
expect(screen.getByLabelText('Edit thresholds for PVE Node 1')).toBeInTheDocument();
});
it('renders node name as a link when host URL is provided', () => {
const props = makeProps({
resources: [
makeResource({
id: 'node-1',
name: 'pve-node-1',
type: 'agent',
host: 'https://192.168.0.10:8006',
}),
],
});
render(() => <ResourceTable {...props} />);
expect(screen.getByText('pve-node-1').tagName).toBe('SPAN');
const link = screen.getByRole('link', {
name: 'Open web interface for pve-node-1',
});
expect(link).toHaveAttribute('href', 'https://192.168.0.10:8006');
});
it('renders cluster name badge for node resources', () => {
const props = makeProps({
resources: [
makeResource({
id: 'node-1',
name: 'pve-node-1',
type: 'agent',
clusterName: 'home-lab',
}),
],
});
render(() => <ResourceTable {...props} />);
expect(screen.getByText('home-lab')).toBeInTheDocument();
});
it('renders node name as plain text when no host URL', () => {
const props = makeProps({
resources: [
makeResource({
id: 'node-1',
name: 'pve-node-1',
type: 'agent',
}),
],
columns: ['CPU %'],
});
render(() => <ResourceTable {...props} />);
const nameEl = screen.getByText('pve-node-1');
expect(nameEl).toBeInTheDocument();
// Without host, name renders as SPAN, not a link
expect(nameEl.tagName).toBe('SPAN');
});
});
describe('mobile view', () => {
beforeEach(() => {
mockIsMobile.mockReturnValue(true);
});
it('renders mobile card layout instead of table', () => {
const props = makeProps({
resources: [makeResource({ id: 'vm-1', name: 'Mobile VM' })],
});
render(() => <ResourceTable {...props} />);
expect(screen.queryByTestId('table')).not.toBeInTheDocument();
expect(screen.getByText('Mobile VM')).toBeInTheDocument();
});
it('shows custom empty message when no resources', () => {
const props = makeProps({
resources: [],
emptyMessage: 'Nothing here',
globalDefaults: undefined,
});
render(() => <ResourceTable {...props} />);
expect(screen.getByText('Nothing here')).toBeInTheDocument();
});
it('shows default empty message when none specified', () => {
const props = makeProps({
resources: [],
globalDefaults: undefined,
});
render(() => <ResourceTable {...props} />);
expect(screen.getByText('No resources available.')).toBeInTheDocument();
});
it('shows canonical no-results message in table view', () => {
mockIsMobile.mockReturnValue(false);
const props = makeProps({
resources: [],
globalDefaults: { cpu: 80 },
});
render(() => <ResourceTable {...props} title="Guests" />);
expect(screen.getByText('No guests found')).toBeInTheDocument();
});
it('renders global defaults card when provided', () => {
const props = makeProps({
resources: [makeResource()],
globalDefaults: { cpu: 80, memory: 85 },
setGlobalDefaults: vi.fn(),
setHasUnsavedChanges: vi.fn(),
});
render(() => <ResourceTable {...props} />);
expect(screen.getByText('Global Defaults')).toBeInTheDocument();
});
it('calls onEdit when edit button is clicked', () => {
const onEdit = vi.fn();
const props = makeProps({
resources: [makeResource({ id: 'vm-1', name: 'Mobile VM' })],
onEdit,
});
render(() => <ResourceTable {...props} />);
const editBtn = screen.getByLabelText('Edit thresholds for Mobile VM');
fireEvent.click(editBtn);
expect(onEdit).toHaveBeenCalled();
});
it('keeps mobile threshold actions touch-sized', () => {
const props = makeProps({
resources: [makeResource({ id: 'vm-1', name: 'Mobile VM' })],
onConfigureResourceIntent: vi.fn(),
});
render(() => <ResourceTable {...props} />);
expect(screen.getByLabelText('Edit thresholds for Mobile VM')).toHaveClass(
'min-h-11',
'min-w-11',
);
expect(screen.getByLabelText('Configure alert delay for Mobile VM')).toHaveClass(
'min-h-11',
'min-w-11',
);
expect(screen.getByLabelText(/^Edit CPU % threshold for Mobile VM: /)).toHaveClass(
'min-h-11',
'min-w-11',
);
});
it('uses a single metric column while editing on mobile', () => {
const props = makeProps({
resources: [makeResource({ id: 'vm-1', name: 'Mobile VM' })],
editingId: () => 'vm-1',
editingThresholds: () => ({ cpu: 80, memory: 85 }),
});
render(() => <ResourceTable {...props} />);
const metricGrid = screen.getAllByRole('spinbutton')[0]?.closest('.grid');
expect(metricGrid).toHaveClass('grid-cols-1');
expect(metricGrid).not.toHaveClass('grid-cols-2');
expect(screen.getByLabelText('Cancel threshold edits')).toHaveClass('min-h-11', 'min-w-11');
});
it('renders subtitle when present', () => {
const props = makeProps({
resources: [makeResource({ id: 'vm-1', name: 'VM', subtitle: 'Running on pve1' })],
});
render(() => <ResourceTable {...props} />);
expect(screen.getByText('Running on pve1')).toBeInTheDocument();
});
it('renders note textarea in editing mode', () => {
const props = makeProps({
resources: [makeResource({ id: 'vm-1', name: 'Mobile VM' })],
editingId: () => 'vm-1',
editingThresholds: () => ({ cpu: 80 }),
editingNote: () => 'mobile note',
});
render(() => <ResourceTable {...props} />);
const textarea = screen.getByPlaceholderText('Add a note...');
expect(textarea).toBeInTheDocument();
expect(textarea).toHaveValue('mobile note');
});
it('prefers displayName over name', () => {
const props = makeProps({
resources: [
makeResource({ id: 'vm-1', name: 'vm-100', displayName: 'Production Web Server' }),
],
});
render(() => <ResourceTable {...props} />);
expect(screen.getByText('Production Web Server')).toBeInTheDocument();
});
it('renders backup as a toggle badge in the card layout, not a number input', () => {
// Routing backup through the numeric editor persisted {trigger, clear}
// into the backup block, which the backend reads as an all-zero
// disabled config (#1126).
const onToggleBackup = vi.fn();
const props = makeProps({
resources: [makeResource({ id: 'vm-1', name: 'Mobile VM', backup: { enabled: true } })],
columns: ['CPU %', 'Backup'],
onToggleBackup,
});
render(() => <ResourceTable {...props} />);
const badge = screen.getByTestId('status-badge');
expect(badge.title).toContain('Backup alerts enabled');
fireEvent.click(badge);
expect(onToggleBackup).toHaveBeenCalledWith('vm-1');
});
it('keeps backup and snapshot out of the numeric editor while editing in the card layout', () => {
const onToggleSnapshot = vi.fn();
const props = makeProps({
resources: [makeResource({ id: 'vm-1', name: 'Mobile VM', snapshot: { enabled: false } })],
columns: ['CPU %', 'Snapshot'],
editingId: () => 'vm-1',
editingThresholds: () => ({ cpu: 80 }),
onToggleSnapshot,
});
render(() => <ResourceTable {...props} />);
// Only the CPU metric may offer a number input; snapshot stays a badge.
expect(screen.getAllByRole('spinbutton')).toHaveLength(1);
const badge = screen.getByTitle(
'Snapshot alerts disabled. Click to enable for this resource.',
);
fireEvent.click(badge);
expect(onToggleSnapshot).toHaveBeenCalledWith('vm-1');
});
});
describe('delay settings', () => {
it('opens the canonical per-resource delay editor from the resource row', () => {
const onConfigureResourceIntent = vi.fn();
const props = makeProps({
resources: [makeResource({ id: 'vm-1', name: 'Database VM' })],
columns: ['CPU %', 'Memory %'],
onConfigureResourceIntent,
});
render(() => <ResourceTable {...props} />);
fireEvent.click(screen.getByLabelText('Configure alert delay for Database VM'));
expect(onConfigureResourceIntent).toHaveBeenCalledWith('vm-1', 'metric.cpu', 'Database VM');
});
it('falls back to the offline signal when the row has no supported metric', () => {
const onConfigureResourceIntent = vi.fn();
const props = makeProps({
resources: [makeResource({ id: 'docker-host-1', name: 'Docker Host', type: 'dockerHost' })],
columns: [],
onConfigureResourceIntent,
});
render(() => <ResourceTable {...props} />);
fireEvent.click(screen.getByLabelText('Configure alert delay for Docker Host'));
expect(onConfigureResourceIntent).toHaveBeenCalledWith(
'docker-host-1',
'state.offline',
'Docker Host',
);
});
it('opens a machine sensor on its temperature signal, named with its machine', () => {
const onConfigureResourceIntent = vi.fn();
const props = makeProps({
resources: [
makeResource({
id: 'agent:host-1/sensor:6162',
name: 'TB0T',
type: 'agentSensor',
node: 'macbook-pve',
thresholds: {},
defaults: { temperature: 0 },
}),
],
columns: ['Temp °C'],
onConfigureResourceIntent,
});
render(() => <ResourceTable {...props} />);
fireEvent.click(screen.getByLabelText('Configure alert delay for TB0T'));
expect(onConfigureResourceIntent).toHaveBeenCalledWith(
'agent:host-1/sensor:6162',
'metric.temperature',
'TB0T · macbook-pve',
);
});
it('shows delay toggle button when showDelayColumn and onMetricDelayChange are provided', () => {
const props = makeProps({
showDelayColumn: true,
onMetricDelayChange: vi.fn(),
globalDefaults: { cpu: 80 },
setGlobalDefaults: vi.fn(),
setHasUnsavedChanges: vi.fn(),
});
render(() => <ResourceTable {...props} />);
const delayToggle = screen.getByLabelText('Show alert delay settings');
expect(delayToggle).toBeInTheDocument();
});
it('toggles delay row visibility when clicked', () => {
const props = makeProps({
showDelayColumn: true,
onMetricDelayChange: vi.fn(),
globalDefaults: { cpu: 80 },
setGlobalDefaults: vi.fn(),
setHasUnsavedChanges: vi.fn(),
globalDelaySeconds: 5,
});
render(() => <ResourceTable {...props} />);
// Initially delay row is hidden
expect(screen.queryByText('Alert Delay (s)')).not.toBeInTheDocument();
// Click to show
fireEvent.click(screen.getByLabelText('Show alert delay settings'));
expect(screen.getByText('Alert Delay (s)')).toBeInTheDocument();
// Click to hide
fireEvent.click(screen.getByLabelText('Hide alert delay settings'));
expect(screen.queryByText('Alert Delay (s)')).not.toBeInTheDocument();
});
});
describe('editing thresholds in desktop view', () => {
it('shows number inputs when editing a grouped resource', () => {
const props = makeProps({
resources: undefined,
groupedResources: {
node1: [makeResource({ id: 'vm-1', name: 'VM1' })],
},
editingId: () => 'vm-1',
editingThresholds: () => ({ cpu: 85, memory: 90 }),
columns: ['CPU %', 'Memory %'],
});
render(() => <ResourceTable {...props} />);
// When editing, number inputs should appear for each metric
const inputs = document.querySelectorAll('input[type="number"]');
expect(inputs.length).toBeGreaterThanOrEqual(2);
});
it('calls setEditingThresholds when a threshold input changes', () => {
const setEditingThresholds = vi.fn();
const props = makeProps({
resources: undefined,
groupedResources: {
node1: [makeResource({ id: 'vm-1', name: 'VM1', defaults: { cpu: 80 } })],
},
editingId: () => 'vm-1',
editingThresholds: () => ({ cpu: 85 }),
setEditingThresholds,
columns: ['CPU %'],
});
render(() => <ResourceTable {...props} />);
// Find the resource editing input by its explicit Off-control guidance.
const editInputs = document.querySelectorAll(
'input[type="number"][title="Use the Off control to disable alerts for this metric"]',
);
expect(editInputs.length).toBeGreaterThanOrEqual(1);
fireEvent.input(editInputs[0], { target: { value: '95' } });
expect(setEditingThresholds).toHaveBeenCalledWith(expect.objectContaining({ cpu: 95 }));
});
it('calls onSaveEdit when focus leaves the edited row', () => {
const onSaveEdit = vi.fn();
const props = makeProps({
resources: undefined,
groupedResources: {
node1: [makeResource({ id: 'vm-1', name: 'VM1', defaults: { cpu: 80 } })],
},
editingId: () => 'vm-1',
editingThresholds: () => ({ cpu: 85 }),
onSaveEdit,
columns: ['CPU %'],
});
render(() => <ResourceTable {...props} />);
const editInputs = document.querySelectorAll(
'input[type="number"][title="Use the Off control to disable alerts for this metric"]',
);
expect(editInputs.length).toBeGreaterThanOrEqual(1);
(editInputs[0] as HTMLInputElement).focus();
fireEvent.focusOut(editInputs[0]);
expect(onSaveEdit).toHaveBeenCalledWith('vm-1');
});
});
describe('offline state button', () => {
it('renders "Warn" for guest resources with default state', () => {
const onSetOfflineState = vi.fn();
const props = makeProps({
resources: undefined,
groupedResources: {
node1: [
makeResource({
id: 'vm-1',
name: 'VM1',
type: 'guest',
disableConnectivity: false,
}),
],
},
showOfflineAlertsColumn: true,
onSetOfflineState,
});
render(() => <ResourceTable {...props} />);
const warnButton = screen.getByText('Warn');
expect(warnButton).toBeInTheDocument();
expect(warnButton.title).toContain('warning-level');
});
it('renders "Off" for resources with disableConnectivity', () => {
const onSetOfflineState = vi.fn();
const props = makeProps({
resources: undefined,
groupedResources: {
node1: [
makeResource({
id: 'vm-1',
name: 'VM1',
type: 'guest',
disableConnectivity: true,
}),
],
},
showOfflineAlertsColumn: true,
onSetOfflineState,
});
render(() => <ResourceTable {...props} />);
const offButton = screen.getByText('Off', { selector: 'button' });
expect(offButton.title).toContain('Offline alerts disabled');
});
it('cycles from warning to critical on click', () => {
const onSetOfflineState = vi.fn();
const props = makeProps({
resources: undefined,
groupedResources: {
node1: [
makeResource({
id: 'vm-1',
name: 'VM1',
type: 'guest',
disableConnectivity: false,
}),
],
},
showOfflineAlertsColumn: true,
onSetOfflineState,
});
render(() => <ResourceTable {...props} />);
const warnButton = screen.getByText('Warn');
fireEvent.click(warnButton);
expect(onSetOfflineState).toHaveBeenCalledWith('vm-1', 'critical');
});
it('does not fire callback when globally disabled', () => {
const onSetOfflineState = vi.fn();
const props = makeProps({
resources: undefined,
groupedResources: {
node1: [
makeResource({
id: 'vm-1',
name: 'VM1',
type: 'guest',
disableConnectivity: false,
}),
],
},
showOfflineAlertsColumn: true,
onSetOfflineState,
globalDisableFlag: () => true,
});
render(() => <ResourceTable {...props} />);
const warnButton = screen.getByText('Warn');
fireEvent.click(warnButton);
expect(onSetOfflineState).not.toHaveBeenCalled();
});
});
describe('backup/snapshot toggles', () => {
it('calls onToggleBackup with resource id when backup badge is clicked', () => {
const onToggleBackup = vi.fn();
const props = makeProps({
resources: undefined,
groupedResources: {
node1: [
makeResource({
id: 'vm-1',
name: 'VM1',
backup: { enabled: true },
}),
],
},
columns: ['Backup'],
onToggleBackup,
});
render(() => <ResourceTable {...props} />);
const badge = screen.getByTestId('status-badge');
fireEvent.click(badge);
expect(onToggleBackup).toHaveBeenCalledWith('vm-1');
});
it('calls onToggleSnapshot with resource id when snapshot badge is clicked', () => {
const onToggleSnapshot = vi.fn();
const props = makeProps({
resources: undefined,
groupedResources: {
node1: [
makeResource({
id: 'vm-2',
name: 'VM2',
snapshot: { enabled: false },
}),
],
},
columns: ['Snapshot'],
onToggleSnapshot,
});
render(() => <ResourceTable {...props} />);
const badge = screen.getByTestId('status-badge');
fireEvent.click(badge);
expect(onToggleSnapshot).toHaveBeenCalledWith('vm-2');
});
it('shows enabled title for backup when enabled', () => {
const onToggleBackup = vi.fn();
const props = makeProps({
resources: undefined,
groupedResources: {
node1: [
makeResource({
id: 'vm-1',
name: 'VM1',
backup: { enabled: true },
}),
],
},
columns: ['Backup'],
onToggleBackup,
});
render(() => <ResourceTable {...props} />);
const badge = screen.getByTestId('status-badge');
expect(badge.title).toContain('Backup alerts enabled');
});
});
describe('slider for SLIDER_METRICS', () => {
it('renders ThresholdSlider for cpu metric when editing', () => {
const props = makeProps({
resources: undefined,
groupedResources: {
node1: [makeResource({ id: 'vm-1', name: 'VM1' })],
},
editingId: () => 'vm-1',
editingThresholds: () => ({ cpu: 80 }),
columns: ['CPU %'],
});
render(() => <ResourceTable {...props} />);
expect(screen.getByTestId('threshold-slider')).toBeInTheDocument();
});
it('does not render ThresholdSlider for non-slider metrics when editing', () => {
const props = makeProps({
resources: undefined,
groupedResources: {
node1: [makeResource({ id: 'vm-1', name: 'VM1', thresholds: { diskRead: 100 } })],
},
editingId: () => 'vm-1',
editingThresholds: () => ({ diskRead: 100 }),
columns: ['Disk R MB/s'],
});
render(() => <ResourceTable {...props} />);
expect(screen.queryByTestId('threshold-slider')).not.toBeInTheDocument();
});
});
});