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
Add branch-coverage tests for eight more frontend models
rcourtman3c252918b3b8
diff --git a/frontend-modern/src/components/Infrastructure/__tests__/resourceDetailDrawerTrueNASModel.coverage.test.ts b/frontend-modern/src/components/Infrastructure/__tests__/resourceDetailDrawerTrueNASModel.coverage.test.tsnew file mode 100644index 0000000000..ae7708df6f--- /dev/null+++ b/frontend-modern/src/components/Infrastructure/__tests__/resourceDetailDrawerTrueNASModel.coverage.test.ts@@ -0,0 +1,329 @@+import { describe, expect, it } from 'vitest';+import {+ buildTrueNASDetailSections,+ type ResourceDetailDrawerTrueNASRow,+ type ResourceDetailDrawerTrueNASRowTone,+} from '@/components/Infrastructure/resourceDetailDrawerTrueNASModel';+import type {+ Resource,+ ResourcePhysicalDiskMeta,+ ResourceStorageMeta,+ ResourceTrueNASServiceMeta,+} from '@/types/resource';++// All target helpers are module-private, so every case drives them through the+// public `buildTrueNASDetailSections` entry point and asserts on the rendered+// sections/rows. `baseResource` mirrors the sibling test's factory.++const baseResource = (overrides: Partial<Resource>): Resource =>+ ({+ id: 'truenas-resource',+ type: 'vm',+ name: 'truenas-resource',+ displayName: 'TrueNAS resource',+ platformId: 'truenas-main',+ platformType: 'truenas',+ sourceType: 'api',+ status: 'online',+ ...overrides,+ }) as Resource;++const sectionLabels = (resource: Resource): string[] =>+ buildTrueNASDetailSections(resource).map((section) => section.label);++const allRows = (resource: Resource): ResourceDetailDrawerTrueNASRow[] =>+ buildTrueNASDetailSections(resource).flatMap((section) => section.rows);++const findRow = (+ resource: Resource,+ label: string,+): ResourceDetailDrawerTrueNASRow | undefined =>+ allRows(resource).find((row) => row.label === label);++const systemWithService = (service: ResourceTrueNASServiceMeta): Resource =>+ baseResource({ type: 'agent', truenas: { services: [service] } });++const diskResource = (disk: ResourcePhysicalDiskMeta): Resource =>+ baseResource({ physicalDisk: disk });++const storageResource = (storage: ResourceStorageMeta): Resource =>+ baseResource({ storage });++describe('truenasServiceStatus / serviceStatusLabel / serviceStatusTone', () => {+ // A single service must resolve to exactly one status row; its label and tone+ // come straight from serviceStatusLabel / serviceStatusTone, and its presence+ // is driven by truenasServiceStatus.+ const STATUS_LABELS = ['Running', 'Attention', 'Stopped', 'Disabled'] as const;++ type Case = {+ name: string;+ state?: string;+ enabled?: boolean;+ status: (typeof STATUS_LABELS)[number];+ tone: ResourceDetailDrawerTrueNASRowTone;+ };++ const cases: Case[] = [+ {+ name: 'running token wins over enabled:false (precedence)',+ state: 'running',+ enabled: false,+ status: 'Running',+ tone: 'success',+ },+ { name: 'started -> running', state: 'started', status: 'Running', tone: 'success' },+ { name: 'active -> running', state: 'active', status: 'Running', tone: 'success' },+ { name: 'failed -> attention', state: 'failed', status: 'Attention', tone: 'warning' },+ { name: 'error -> attention', state: 'error', status: 'Attention', tone: 'warning' },+ { name: 'crashed -> attention', state: 'crashed', status: 'Attention', tone: 'warning' },+ { name: 'degraded -> attention', state: 'degraded', status: 'Attention', tone: 'warning' },+ { name: 'unknown -> attention', state: 'unknown', status: 'Attention', tone: 'warning' },+ {+ name: 'stop + enabled -> stopped',+ state: 'stop',+ enabled: true,+ status: 'Stopped',+ tone: 'warning',+ },+ {+ name: 'inactive + enabled -> stopped',+ state: 'inactive',+ enabled: true,+ status: 'Stopped',+ tone: 'warning',+ },+ {+ name: 'stop + disabled -> disabled',+ state: 'stop',+ enabled: false,+ status: 'Disabled',+ tone: 'default',+ },+ {+ name: 'inactive + disabled -> disabled',+ state: 'inactive',+ enabled: false,+ status: 'Disabled',+ tone: 'default',+ },+ {+ name: 'unknown state + enabled -> attention (fallback)',+ state: 'restarting',+ enabled: true,+ status: 'Attention',+ tone: 'warning',+ },+ {+ name: 'unknown state + enabled undefined -> attention (fallback)',+ state: 'restarting',+ status: 'Attention',+ tone: 'warning',+ },+ {+ name: 'unknown state + disabled -> disabled (fallback)',+ state: 'restarting',+ enabled: false,+ status: 'Disabled',+ tone: 'default',+ },+ {+ name: 'empty state + disabled -> disabled (fallback)',+ state: '',+ enabled: false,+ status: 'Disabled',+ tone: 'default',+ },+ {+ name: 'whitespace-only state + disabled -> disabled (fallback)',+ state: ' ',+ enabled: false,+ status: 'Disabled',+ tone: 'default',+ },+ {+ name: 'missing state + enabled -> attention (fallback)',+ enabled: true,+ status: 'Attention',+ tone: 'warning',+ },+ ];++ for (const testCase of cases) {+ it(testCase.name, () => {+ const resource = systemWithService({+ id: '1',+ service: 'svc',+ enabled: testCase.enabled,+ state: testCase.state,+ });++ const presentStatusRows = STATUS_LABELS.filter((label) => Boolean(findRow(resource, label)));+ expect(presentStatusRows).toEqual([testCase.status]);++ const row = findRow(resource, testCase.status);+ expect(row?.value).toBe('1');+ expect(row?.tone).toBe(testCase.tone);+ });+ }+});++describe('storageKindLabel', () => {+ it('prefers topology over type', () => {+ expect(+ findRow(storageResource({ topology: 'dataset', type: 'zfs_pool' }), 'Kind')?.value,+ ).toBe('Dataset');+ });++ it('falls back to type when topology is absent', () => {+ expect(findRow(storageResource({ type: 'zfs_pool' }), 'Kind')?.value).toBe('Zfs Pool');+ });++ it('returns null when both topology and type are absent', () => {+ expect(findRow(storageResource({}), 'Kind')).toBeUndefined();+ });+});++describe('diskStateTone', () => {+ it('maps passed/healthy/ok to success', () => {+ expect(findRow(diskResource({ health: 'PASSED' }), 'Health')?.tone).toBe('success');+ expect(findRow(diskResource({ health: 'OK' }), 'Health')?.tone).toBe('success');+ });++ it('maps failed to warning', () => {+ expect(findRow(diskResource({ health: 'FAILED' }), 'Health')?.tone).toBe('warning');+ });++ it('maps unrecognized health to default', () => {+ expect(findRow(diskResource({ health: 'SCRUBBED' }), 'Health')?.tone).toBe('default');+ });++ it('omits the Health row when health is missing (default tone still computed)', () => {+ expect(findRow(diskResource({}), 'Health')).toBeUndefined();+ });+});++describe('formatDiskHours', () => {+ it('formats positive hours with thousands separators and the h suffix', () => {+ expect(findRow(diskResource({ smart: { powerOnHours: 1_234_567 } }), 'Power on')?.value).toBe(+ '1,234,567h',+ );+ });++ it('formats a single-digit hour value', () => {+ expect(findRow(diskResource({ smart: { powerOnHours: 1 } }), 'Power on')?.value).toBe('1h');+ });++ const nullCases: Array<[string, number | undefined]> = [+ ['undefined', undefined],+ ['zero', 0],+ ['negative', -5],+ ['NaN', Number.NaN],+ ];+ for (const [label, powerOnHours] of nullCases) {+ it(`omits the Power on row for a non-positive hour value (${label})`, () => {+ expect(findRow(diskResource({ smart: { powerOnHours } }), 'Power on')).toBeUndefined();+ });+ }++ it('omits the Power on row for a non-number value', () => {+ const resource = diskResource({+ smart: { powerOnHours: 'lots' as unknown as number },+ });+ expect(findRow(resource, 'Power on')).toBeUndefined();+ });+});++describe('buildTrueNAS sections empty-input guards', () => {+ it('buildTrueNASSystemSections: minimal truenas yields only the System section', () => {+ const resource = baseResource({ type: 'agent', truenas: {} });++ expect(sectionLabels(resource)).toEqual(['System']);+ // Hostname falls back to resource.name; Status falls back to resource.status.+ expect(findRow(resource, 'Hostname')?.value).toBe('truenas-resource');+ expect(findRow(resource, 'Status')?.value).toBe('Online');+ // Empty services/pids/names guards drop every Services-section row.+ expect(findRow(resource, 'Services')).toBeUndefined();+ expect(findRow(resource, 'Running')).toBeUndefined();+ expect(findRow(resource, 'Attention')).toBeUndefined();+ expect(findRow(resource, 'Stopped')).toBeUndefined();+ expect(findRow(resource, 'Disabled')).toBeUndefined();+ expect(findRow(resource, 'PIDs')).toBeUndefined();+ expect(findRow(resource, 'Names')).toBeUndefined();+ });++ it('buildTrueNASStorageSections: minimal storage yields only the Storage section', () => {+ const resource = baseResource({ storage: {} });++ expect(sectionLabels(resource)).toEqual(['Storage']);+ // State derives from resource.status when no zfs/array state is set.+ expect(findRow(resource, 'State')).toEqual({+ label: 'State',+ value: 'Online',+ tone: 'success',+ });+ expect(findRow(resource, 'Kind')).toBeUndefined();+ expect(findRow(resource, 'Shared')).toBeUndefined();+ });++ it('buildTrueNASDiskSections: minimal disk yields only the Disk section', () => {+ const resource = baseResource({ physicalDisk: {} });++ expect(sectionLabels(resource)).toEqual(['Disk']);+ // Device falls back to resource.name.+ expect(findRow(resource, 'Device')?.value).toBe('truenas-resource');+ expect(findRow(resource, 'Health')).toBeUndefined();+ expect(findRow(resource, 'Power on')).toBeUndefined();+ });++ it('buildTrueNASAppSections: a bare app yields no sections', () => {+ expect(sectionLabels(baseResource({ truenas: { app: {} } }))).toEqual([]);+ });++ it('buildTrueNASVMSections: a bare vm yields no sections', () => {+ expect(sectionLabels(baseResource({ truenas: { vm: {} } }))).toEqual([]);+ });++ it('buildTrueNASShareSections: a bare share yields only the Share section with a default Enabled state', () => {+ const resource = baseResource({ truenas: { share: {} } });++ expect(sectionLabels(resource)).toEqual(['Share']);+ expect(findRow(resource, 'State')).toEqual({+ label: 'State',+ value: 'Enabled',+ tone: 'success',+ });+ });+});++describe('yesNoValue (via the Shared row)', () => {+ it('returns "Yes" for true', () => {+ expect(findRow(storageResource({ shared: true }), 'Shared')?.value).toBe('Yes');+ });++ it('returns "No" for false', () => {+ expect(findRow(storageResource({ shared: false }), 'Shared')?.value).toBe('No');+ });++ it('returns null (row omitted) for undefined', () => {+ expect(findRow(storageResource({}), 'Shared')).toBeUndefined();+ });+});++describe('booleanValue (via the VM Autostart flag)', () => {+ it('returns "Enabled" for true', () => {+ const resource = baseResource({ truenas: { vm: { autostart: true } } });+ expect(sectionLabels(resource)).toEqual(['Flags']);+ expect(findRow(resource, 'Autostart')?.value).toBe('Enabled');+ });++ it('returns "Disabled" for false', () => {+ expect(findRow(baseResource({ truenas: { vm: { autostart: false } } }), 'Autostart')?.value).toBe(+ 'Disabled',+ );+ });++ it('returns null (row omitted) for undefined', () => {+ const resource = baseResource({ truenas: { vm: { state: 'running' } } });+ expect(findRow(resource, 'Autostart')).toBeUndefined();+ });+});diff --git a/frontend-modern/src/components/Settings/__tests__/connectionsTableModel.coverage.test.ts b/frontend-modern/src/components/Settings/__tests__/connectionsTableModel.coverage.test.tsnew file mode 100644index 0000000000..7ff4ced962--- /dev/null+++ b/frontend-modern/src/components/Settings/__tests__/connectionsTableModel.coverage.test.ts@@ -0,0 +1,680 @@+import { describe, expect, it } from 'vitest';+import type {+ Connection,+ ConnectionFleetGovernance,+ ConnectionFleetAdapterHealth,+ ConnectionFleetConfigRollout,+ ConnectionFleetCredentialStatus,+ ConnectionFleetEnrollmentState,+ ConnectionFleetLivenessState,+ ConnectionFleetRemoteControl,+ ConnectionFleetUpdateStatus,+ ConnectionFleetVersionDrift,+} from '@/api/connections';+import {+ connectionAgentEndpointDisplay,+ fleetGovernanceSignalsForConnection,+ fleetSignalClassName,+ type FleetGovernanceSignal,+ type FleetGovernanceSignalKey,+ type FleetGovernanceSignalTone,+} from '../connectionsTableModel';++// ---- Fixtures ---------------------------------------------------------------++const connectionFixture = (overrides: Partial<Connection> = {}): Connection => ({+ id: 'agent:host-1',+ type: 'agent',+ name: 'host-1',+ address: 'host-1',+ state: 'active',+ stateReason: '',+ enabled: true,+ surfaces: ['host'],+ scope: { host: true },+ lastSeen: '2026-04-23T12:00:00Z',+ lastError: null,+ source: 'agent',+ capabilities: { supportsPause: false, supportsScope: false, supportsTest: false },+ ...overrides,+});++// Defaults to a fully "healthy/current" agent fleet. The optional derived+// fields (configDrift/rollout/credentialHealth/commandPolicy) are left+// undefined so the *FromFleet derivation paths are exercised unless a test+// overrides them explicitly.+const fleetFixture = (overrides: Partial<ConnectionFleetGovernance> = {}): ConnectionFleetGovernance => ({+ enrollmentState: 'enrolled',+ livenessState: 'active',+ versionDrift: 'current',+ adapterHealth: 'healthy',+ configRollout: 'reported',+ credentialStatus: 'verified',+ updateStatus: 'current',+ remoteControl: 'disabled',+ ...overrides,+});++const signalByKey = (+ connection: Connection,+ key: FleetGovernanceSignalKey,+): FleetGovernanceSignal | undefined =>+ fleetGovernanceSignalsForConnection(connection).find((signal) => signal.key === key);++// ---- isIPv4Literal (private) via connectionAgentEndpointDisplay -------------+//+// isIPv4Literal is module-private and only reachable through+// firstDistinctAgentIPv4Alias -> connectionAgentEndpointDisplay. To exercise+// its branches we drive endpoint display with reportIp unset so the alias+// scan runs, and assert which alias (if any) is returned.++describe('isIPv4Literal (via connectionAgentEndpointDisplay)', () => {+ // A connection whose name/address are distinct from any alias, with no+ // reportIp/hostname, so the alias IPv4 scan is the decisive path.+ const aliasConnection = (hostAliases: string[]): Connection =>+ connectionFixture({+ name: 'host-1',+ address: 'host-1',+ agentIdentity: undefined,+ hostAliases,+ });++ it('recognizes canonical IPv4 literals', () => {+ expect(connectionAgentEndpointDisplay(aliasConnection(['1.2.3.4']))).toBe('1.2.3.4');+ expect(connectionAgentEndpointDisplay(aliasConnection(['12.34.56.78']))).toBe('12.34.56.78');+ });++ it('recognizes single-digit and triple-digit octet boundaries', () => {+ expect(connectionAgentEndpointDisplay(aliasConnection(['1.1.1.1']))).toBe('1.1.1.1');+ expect(connectionAgentEndpointDisplay(aliasConnection(['255.255.255.255']))).toBe(+ '255.255.255.255',+ );+ expect(connectionAgentEndpointDisplay(aliasConnection(['0.0.0.0']))).toBe('0.0.0.0');+ });++ it('treats out-of-range octets as literals (regex checks digit count, not range)', () => {+ // 256/999 exceed the valid IPv4 octet range but match \d{1,3}; current+ // behaviour accepts them. Noted as a caveat in GLM_REPORT.md.+ expect(connectionAgentEndpointDisplay(aliasConnection(['256.1.1.1']))).toBe('256.1.1.1');+ expect(connectionAgentEndpointDisplay(aliasConnection(['999.999.999.999']))).toBe(+ '999.999.999.999',+ );+ });++ it('rejects too few octets', () => {+ // '1.2.3' is not an IPv4 literal -> no alias -> name == address -> null.+ expect(connectionAgentEndpointDisplay(aliasConnection(['1.2.3']))).toBeNull();+ });++ it('rejects too many octets', () => {+ expect(connectionAgentEndpointDisplay(aliasConnection(['1.2.3.4.5']))).toBeNull();+ });++ it('rejects non-numeric octets and adjacent characters', () => {+ expect(connectionAgentEndpointDisplay(aliasConnection(['a.b.c.d']))).toBeNull();+ expect(connectionAgentEndpointDisplay(aliasConnection(['1.2.3.4a']))).toBeNull();+ expect(connectionAgentEndpointDisplay(aliasConnection(['a1.2.3.4']))).toBeNull();+ });++ it('skips whitespace-only aliases before the first valid literal', () => {+ // Empty/whitespace aliases are skipped by trim(), then the first valid+ // literal wins.+ expect(+ connectionAgentEndpointDisplay(aliasConnection([' ', '', '10.0.0.5'])),+ ).toBe('10.0.0.5');+ });++ it('trims surrounding whitespace from a candidate before matching', () => {+ // The candidate is trimmed first, so ' 10.0.0.5 ' is a valid literal.+ expect(connectionAgentEndpointDisplay(aliasConnection([' 10.0.0.5 ']))).toBe('10.0.0.5');+ });++ it('returns the first valid literal after skipping invalid and excluded aliases', () => {+ const connection = aliasConnection([+ 'hostname.example', // not an IPv4 literal+ '1.2.3', // too few octets+ 'not-an-ip', // not an IPv4 literal+ '10.0.0.5', // first valid -> wins+ '10.0.0.6', // would also be valid but later+ ]);+ expect(connectionAgentEndpointDisplay(connection)).toBe('10.0.0.5');+ });++ it('excludes aliases equal to name, address, or hostname (case-insensitive)', () => {+ // 'node-1' matches name 'Node-1' (lowercased), '10.0.0.1' == address,+ // '10.0.0.2' == hostname. reportIp is intentionally unset so the alias+ // scan runs; only '10.0.0.9' survives.+ const connection = connectionFixture({+ name: 'Node-1',+ address: '10.0.0.1',+ agentIdentity: { hostname: '10.0.0.2' },+ hostAliases: ['node-1', '10.0.0.1', '10.0.0.2', '10.0.0.9'],+ });+ expect(connectionAgentEndpointDisplay(connection)).toBe('10.0.0.9');+ });++ it('prefers reportIp over any host alias', () => {+ // Precedence: reportIp short-circuits before the alias scan.+ expect(+ connectionAgentEndpointDisplay(+ connectionFixture({+ agentIdentity: { reportIp: '192.168.1.50' },+ hostAliases: ['10.0.0.5'],+ }),+ ),+ ).toBe('192.168.1.50');+ });++ it('falls back to hostname when distinct from name and no alias is available', () => {+ expect(+ connectionAgentEndpointDisplay(+ connectionFixture({ name: 'host-1', agentIdentity: { hostname: 'real-host' } }),+ ),+ ).toBe('real-host');+ });++ it('falls back to address when distinct from name and no hostname/alias is available', () => {+ expect(+ connectionAgentEndpointDisplay(connectionFixture({ name: 'host-1', address: '10.0.0.99' })),+ ).toBe('10.0.0.99');+ });++ it('returns null when name equals address and nothing else is available', () => {+ expect(+ connectionAgentEndpointDisplay(connectionFixture({ name: 'host-1', address: 'host-1' })),+ ).toBeNull();+ });+});++// ---- fleetSignalClassName ---------------------------------------------------++describe('fleetSignalClassName', () => {+ const PREFIX =+ 'inline-flex items-center rounded-full border px-2 py-0.5 text-[11px] font-medium whitespace-nowrap ';++ const expectedByTone: Record<FleetGovernanceSignalTone, string> = {+ ok: `${PREFIX}border-emerald-200 bg-emerald-50 text-emerald-800 dark:border-emerald-900 dark:bg-emerald-950/30 dark:text-emerald-200`,+ info: `${PREFIX}border-blue-200 bg-blue-50 text-blue-800 dark:border-blue-900 dark:bg-blue-950/30 dark:text-blue-200`,+ warning: `${PREFIX}border-amber-200 bg-amber-50 text-amber-800 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-200`,+ critical: `${PREFIX}border-rose-200 bg-rose-50 text-rose-800 dark:border-rose-900 dark:bg-rose-950/30 dark:text-rose-200`,+ muted: `${PREFIX}border-border bg-surface-alt text-muted`,+ };++ it.each(['ok', 'info', 'warning', 'critical', 'muted'] as FleetGovernanceSignalTone[])(+ 'renders the exact className for the %s tone',+ (tone) => {+ expect(fleetSignalClassName(tone)).toBe(expectedByTone[tone]);+ },+ );++ it('always embeds the shared layout prefix', () => {+ for (const tone of ['ok', 'info', 'warning', 'critical', 'muted'] as FleetGovernanceSignalTone[]) {+ expect(fleetSignalClassName(tone).startsWith(PREFIX)).toBe(true);+ }+ });++ it('produces a distinct class string per tone', () => {+ const tones = ['ok', 'info', 'warning', 'critical', 'muted'] as FleetGovernanceSignalTone[];+ const classNames = new Set(tones.map((tone) => fleetSignalClassName(tone)));+ expect(classNames.size).toBe(tones.length);+ });+});++// ---- configDriftFromFleet (private) via fleetGovernanceSignalsForConnection -++describe('configDriftFromFleet (via fleetGovernanceSignalsForConnection)', () => {+ it('returns an explicit configDrift verbatim, ignoring configRollout', () => {+ // configRollout 'configured' would derive status 'current' (label+ // 'Config current'); the explicit 'drifted' status must win.+ const signal = signalByKey(+ connectionFixture({+ fleet: fleetFixture({+ configRollout: 'configured',+ configDrift: { status: 'drifted', reason: 'override mismatch' },+ }),+ }),+ 'config-drift',+ );+ expect(signal).toMatchObject({+ label: 'Config drift',+ detail: 'override mismatch',+ tone: 'warning',+ });+ });++ it.each(['configured', 'reported'] as ConnectionFleetConfigRollout[])(+ 'derives status "current" from configRollout %s when no explicit configDrift is set',+ (configRollout) => {+ const signal = signalByKey(+ connectionFixture({ fleet: fleetFixture({ configRollout }) }),+ 'config-drift',+ );+ expect(signal).toMatchObject({ label: 'Config current', tone: 'ok' });+ expect(signal?.detail).toBe('Configuration is current.');+ },+ );++ it('derives status "paused" from configRollout paused', () => {+ const signal = signalByKey(+ connectionFixture({ fleet: fleetFixture({ configRollout: 'paused' }) }),+ 'config-drift',+ );+ expect(signal).toMatchObject({ label: 'Config paused', tone: 'muted' });+ expect(signal?.detail).toBe('Configuration rollout is paused.');+ });++ it('derives status "unknown" from configRollout unknown', () => {+ const signal = signalByKey(+ connectionFixture({ fleet: fleetFixture({ configRollout: 'unknown' }) }),+ 'config-drift',+ );+ expect(signal).toMatchObject({ label: 'Config unknown', tone: 'warning' });+ expect(signal?.detail).toBe('Configuration drift state is unknown.');+ });+});++// ---- rolloutFromFleet (private) --------------------------------------------++describe('rolloutFromFleet (via fleetGovernanceSignalsForConnection)', () => {+ it('returns an explicit rollout verbatim, ignoring configRollout', () => {+ // configRollout 'configured' would derive 'current'; explicit 'blocked'+ // must win.+ const signal = signalByKey(+ connectionFixture({+ fleet: fleetFixture({+ configRollout: 'configured',+ rollout: { status: 'blocked', reason: 'halted by operator' },+ }),+ }),+ 'rollout',+ );+ expect(signal).toMatchObject({ label: 'Rollout blocked', detail: 'halted by operator', tone: 'critical' });+ });++ it.each(['configured', 'reported'] as ConnectionFleetConfigRollout[])(+ 'derives status "current" / stage "applied" from configRollout %s',+ (configRollout) => {+ const signal = signalByKey(+ connectionFixture({ fleet: fleetFixture({ configRollout }) }),+ 'rollout',+ );+ expect(signal).toMatchObject({ label: 'Rollout current', tone: 'ok' });+ expect(signal?.detail).toBe('The rollout state is current.');+ },+ );++ it('derives status "paused" / stage "paused" from configRollout paused', () => {+ const signal = signalByKey(+ connectionFixture({ fleet: fleetFixture({ configRollout: 'paused' }) }),+ 'rollout',+ );+ expect(signal).toMatchObject({ label: 'Rollout paused', tone: 'warning' });+ expect(signal?.detail).toBe('The staged rollout is paused.');+ });++ it('derives status "unknown" from configRollout unknown', () => {+ const signal = signalByKey(+ connectionFixture({ fleet: fleetFixture({ configRollout: 'unknown' }) }),+ 'rollout',+ );+ expect(signal).toMatchObject({ label: 'Rollout unknown', tone: 'warning' });+ expect(signal?.detail).toBe('Pulse has not classified staged rollout state yet.');+ });+});++// ---- credentialHealthFromFleet (private) -----------------------------------++describe('credentialHealthFromFleet (via fleetGovernanceSignalsForConnection)', () => {+ it('returns an explicit credentialHealth verbatim, ignoring credentialStatus', () => {+ // credentialStatus 'verified' would derive 'verified'; explicit 'expired'+ // must win.+ const signal = signalByKey(+ connectionFixture({+ fleet: fleetFixture({+ credentialStatus: 'verified',+ credentialHealth: { status: 'expired' },+ }),+ }),+ 'credential-health',+ );+ expect(signal).toMatchObject({ label: 'Credentials expired', tone: 'critical' });+ });++ it.each([+ ['verified', 'Credentials verified', 'ok'],+ ['invalid', 'Credentials invalid', 'critical'],+ ['paused', 'Credentials paused', 'muted'],+ ['unknown', 'Credentials unknown', 'warning'],+ ] as const satisfies ReadonlyArray<[ConnectionFleetCredentialStatus, string, FleetGovernanceSignalTone]>)(+ 'derives the credential-health signal from credentialStatus %s',+ (status, label, tone) => {+ const signal = signalByKey(+ connectionFixture({ fleet: fleetFixture({ credentialStatus: status }) }),+ 'credential-health',+ );+ expect(signal).toMatchObject({ label, tone });+ },+ );++ it('surfaces credential-health for non-agent API sources too', () => {+ // credentialHealth is source-agnostic: it appears even when agent-fleet+ // signals are gated off for a pull-based source.+ const signal = signalByKey(+ connectionFixture({+ type: 'pbs',+ fleet: fleetFixture({ credentialStatus: 'invalid' }),+ }),+ 'credential-health',+ );+ expect(signal).toMatchObject({ label: 'Credentials invalid', tone: 'critical' });+ });+});++// ---- commandPolicyFromFleet (private) --------------------------------------++describe('commandPolicyFromFleet (via fleetGovernanceSignalsForConnection)', () => {+ it('returns an explicit commandPolicy verbatim, ignoring remoteControl', () => {+ // remoteControl 'disabled' would derive an info 'Remote control disabled';+ // the explicit blocked status must win.+ const signal = signalByKey(+ connectionFixture({+ fleet: fleetFixture({+ remoteControl: 'disabled',+ commandPolicy: { status: 'blocked', enforcement: 'blocked' },+ }),+ }),+ 'command-policy',+ );+ expect(signal).toMatchObject({ label: 'Remote control blocked', tone: 'critical' });+ });++ it('flags an explicit drifted policy with desired=disabled/applied=enabled as critical', () => {+ // commandPolicySignal: enforcement 'drifted' + desired disabled & applied+ // enabled -> critical (the dangerous direction).+ const signal = signalByKey(+ connectionFixture({+ fleet: fleetFixture({+ remoteControl: 'enabled',+ commandPolicy: {+ status: 'enabled',+ desired: 'disabled',+ applied: 'enabled',+ enforcement: 'drifted',+ reason: 'policy reverted by agent',+ },+ }),+ }),+ 'command-policy',+ );+ expect(signal).toMatchObject({+ label: 'Command policy mismatch',+ detail: 'policy reverted by agent',+ tone: 'critical',+ });+ });++ it('flags an explicit drifted policy in the safe direction as warning', () => {+ // desired enabled / applied disabled is the less dangerous drift -> warning.+ const signal = signalByKey(+ connectionFixture({+ fleet: fleetFixture({+ commandPolicy: {+ status: 'disabled',+ desired: 'enabled',+ applied: 'disabled',+ enforcement: 'drifted',+ },+ }),+ }),+ 'command-policy',+ );+ expect(signal).toMatchObject({ label: 'Command policy mismatch', tone: 'warning' });+ });++ it.each([+ ['enabled', 'Remote control enabled', 'info'],+ ['disabled', 'Remote control disabled', 'info'],+ ['not-applicable', 'No remote control', 'muted'],+ ] as const satisfies ReadonlyArray<[ConnectionFleetRemoteControl, string, FleetGovernanceSignalTone]>)(+ 'derives the command-policy signal from remoteControl %s (enforcement not-applicable)',+ (remoteControl, label, tone) => {+ const signal = signalByKey(+ connectionFixture({ fleet: fleetFixture({ remoteControl }) }),+ 'command-policy',+ );+ expect(signal).toMatchObject({ label, tone });+ },+ );++ it('derives a pending signal from remoteControl unknown (enforcement pending short-circuits the status)', () => {+ // commandPolicyFromFleet maps remoteControl 'unknown' to enforcement+ // 'pending'; commandPolicySignal treats enforcement 'pending' as the+ // decisive branch, so the label is 'Command policy pending' rather than+ // 'Remote control unknown'.+ const signal = signalByKey(+ connectionFixture({ fleet: fleetFixture({ remoteControl: 'unknown' }) }),+ 'command-policy',+ );+ expect(signal).toMatchObject({ label: 'Command policy pending', tone: 'warning' });+ });+});++// ---- enrollmentSignal (private) --------------------------------------------++describe('enrollmentSignal (via fleetGovernanceSignalsForConnection)', () => {+ it.each([+ ['configured', 'Configured', 'ok'],+ ['enrolled', 'Enrolled', 'ok'],+ ['paused', 'Paused', 'muted'],+ ] as const satisfies ReadonlyArray<+ [ConnectionFleetEnrollmentState, string, FleetGovernanceSignalTone]+ >)('maps enrollment state %s to its signal', (state, label, tone) => {+ const signal = signalByKey(+ connectionFixture({ fleet: fleetFixture({ enrollmentState: state }) }),+ 'enrollment',+ );+ expect(signal).toMatchObject({ key: 'enrollment', label, tone });+ });++ it('uses the agent-specific detail for pending agent connections', () => {+ const signal = signalByKey(+ connectionFixture({ type: 'agent', fleet: fleetFixture({ enrollmentState: 'pending' }) }),+ 'enrollment',+ );+ expect(signal).toMatchObject({ label: 'Enrollment pending', tone: 'warning' });+ expect(signal?.detail).toBe('Pulse has not received the first agent report yet.');+ });++ it('uses the generic detail for pending non-agent sources', () => {+ const signal = signalByKey(+ connectionFixture({ type: 'pbs', fleet: fleetFixture({ enrollmentState: 'pending' }) }),+ 'enrollment',+ );+ expect(signal).toMatchObject({ label: 'Enrollment pending', tone: 'warning' });+ expect(signal?.detail).toBe('Pulse has not confirmed this source yet.');+ });+});++// ---- livenessSignal (private) ----------------------------------------------++describe('livenessSignal (via fleetGovernanceSignalsForConnection)', () => {+ it.each([+ ['active', 'Live', 'ok'],+ ['paused', 'Paused', 'muted'],+ ['stale', 'Stale', 'warning'],+ ['pending', 'Pending', 'warning'],+ ['unauthorized', 'Unauthorized', 'critical'],+ ['unreachable', 'Unreachable', 'critical'],+ ] as const satisfies ReadonlyArray<+ [ConnectionFleetLivenessState, string, FleetGovernanceSignalTone]+ >)('maps liveness state %s to its signal', (state, label, tone) => {+ const signal = signalByKey(+ connectionFixture({ fleet: fleetFixture({ livenessState: state }) }),+ 'liveness',+ );+ expect(signal).toMatchObject({ key: 'liveness', label, tone });+ });+});++// ---- versionSignal (private) -----------------------------------------------++describe('versionSignal (via fleetGovernanceSignalsForConnection)', () => {+ // versionSignal is only emitted for agent-fleet connection types.+ it.each([+ ['behind', 'Version behind', 'warning'],+ ['current', 'Version current', 'ok'],+ ['unknown', 'Version unknown', 'muted'],+ ['not-applicable', 'No agent version', 'muted'],+ ] as const satisfies ReadonlyArray<[ConnectionFleetVersionDrift, string, FleetGovernanceSignalTone]>)(+ 'maps version drift %s to its signal',+ (state, label, tone) => {+ const signal = signalByKey(+ connectionFixture({ fleet: fleetFixture({ versionDrift: state }) }),+ 'version',+ );+ expect(signal).toMatchObject({ key: 'version', label, tone });+ },+ );+});++// ---- fleetGovernanceSignalsForConnection (orchestrator) --------------------++describe('fleetGovernanceSignalsForConnection', () => {+ it('falls back to the default fleet governance when connection.fleet is undefined', () => {+ // DEFAULT_FLEET_GOVERNANCE maps every field to its unknown/pending+ // baseline; for an agent that yields a consistent set of derived signals.+ const connection = connectionFixture({ fleet: undefined });+ const signals = fleetGovernanceSignalsForConnection(connection);+ const labels = signals.map((signal) => signal.label);+ expect(labels).toEqual(+ expect.arrayContaining([+ 'Enrollment pending',+ 'Pending',+ 'Credentials unknown',+ 'Config unknown',+ 'Rollout unknown',+ 'Version unknown',+ 'Update unknown',+ 'Adapter unknown',+ 'No remote control',+ ]),+ );+ });++ it('gates agent-fleet signals on for docker connections', () => {+ const keys = fleetGovernanceSignalsForConnection(+ connectionFixture({+ type: 'docker',+ fleet: fleetFixture({ versionDrift: 'behind', updateStatus: 'update-available' }),+ }),+ ).map((signal) => signal.key);+ expect(keys).toContain('version');+ expect(keys).toContain('config-drift');+ expect(keys).toContain('rollout');+ expect(keys).toContain('command-policy');+ });++ it('gates agent-fleet signals on for kubernetes connections', () => {+ const keys = fleetGovernanceSignalsForConnection(+ connectionFixture({ type: 'kubernetes', fleet: fleetFixture() }),+ ).map((signal) => signal.key);+ expect(keys).toContain('version');+ expect(keys).toContain('command-policy');+ });++ it('gates agent-fleet signals off for pull-based API sources', () => {+ const keys = fleetGovernanceSignalsForConnection(+ connectionFixture({ type: 'pve', fleet: fleetFixture() }),+ ).map((signal) => signal.key);+ expect(keys).toEqual(['enrollment', 'liveness', 'credential-health', 'adapter']);+ });++ it('emits signals in the documented order for an agent with a failing module', () => {+ const keys = fleetGovernanceSignalsForConnection(+ connectionFixture({+ agentModules: [+ {+ name: 'kubernetes',+ enabled: true,+ state: 'starting',+ updatedAt: '2026-07-09T12:00:00Z',+ },+ ],+ fleet: fleetFixture(),+ }),+ ).map((signal) => signal.key);+ expect(keys).toEqual([+ 'enrollment',+ 'liveness',+ 'credential-health',+ 'module-health',+ 'config-drift',+ 'rollout',+ 'version',+ 'updates',+ 'adapter',+ 'command-policy',+ ]);+ });++ it('omits the module-health signal when no enabled module is failing', () => {+ const keys = fleetGovernanceSignalsForConnection(+ connectionFixture({+ agentModules: [+ {+ name: 'host',+ enabled: true,+ state: 'running',+ updatedAt: '2026-07-09T12:00:00Z',+ },+ ],+ fleet: fleetFixture(),+ }),+ ).map((signal) => signal.key);+ expect(keys).not.toContain('module-health');+ });++ it('always emits the adapter signal with the declared health regardless of type', () => {+ const adapterStates: ReadonlyArray<ConnectionFleetAdapterHealth> = [+ 'healthy',+ 'degraded',+ 'blocked',+ 'paused',+ 'unknown',+ ];+ for (const adapterHealth of adapterStates) {+ const signal = signalByKey(+ connectionFixture({ type: 'pbs', fleet: fleetFixture({ adapterHealth }) }),+ 'adapter',+ );+ expect(signal).toBeDefined();+ }+ });++ it('maps each update status to its updates signal for agent sources', () => {+ const updateStates: ReadonlyArray<ConnectionFleetUpdateStatus> = [+ 'update-available',+ 'checking',+ 'updating',+ 'failed',+ 'disabled',+ 'current',+ 'unknown',+ 'not-applicable',+ ];+ for (const updateStatus of updateStates) {+ const signal = signalByKey(+ connectionFixture({+ fleet: fleetFixture({ updateStatus }),+ agentUpdate:+ updateStatus === 'failed'+ ? { state: 'error', autoUpdate: true, lastError: 'boom' }+ : undefined,+ }),+ 'updates',+ );+ expect(signal).toBeDefined();+ expect(signal?.key).toBe('updates');+ }+ });+});diff --git a/frontend-modern/src/features/alerts/__tests__/alertsConfigurationModel.coverage.test.ts b/frontend-modern/src/features/alerts/__tests__/alertsConfigurationModel.coverage.test.tsnew file mode 100644index 0000000000..2831b50f0b--- /dev/null+++ b/frontend-modern/src/features/alerts/__tests__/alertsConfigurationModel.coverage.test.ts@@ -0,0 +1,282 @@+import { describe, expect, it } from 'vitest';++import type { AlertConfig } from '@/types/alerts';++import {+ buildAlertsConfigurationPayload,+ createDefaultAlertsConfigurationSnapshot,+ FACTORY_BACKUP_DEFAULTS,+ FACTORY_DOCKER_DEFAULTS,+ readAlertsConfigurationSnapshot,+} from '../alertsConfigurationModel';++// The functions under test (createHysteresisThreshold, normalizeGap,+// normalizeWarningCriticalPair, normalizeStringList, cloneDays, cloneBackupDefaults)+// are all module-private. Each is exercised below through its public entry point:+// createDefaultAlertsConfigurationSnapshot / readAlertsConfigurationSnapshot /+// buildAlertsConfigurationPayload.+const buildFromSnapshot = (snapshot: ReturnType<typeof createDefaultAlertsConfigurationSnapshot>) =>+ buildAlertsConfigurationPayload({+ snapshot,+ rawOverridesConfig: {},+ alertsActivationState: null,+ alertsActivationConfig: null,+ });++describe('createHysteresisThreshold (via buildAlertsConfigurationPayload)', () => {+ it('coerces a non-number trigger to 0 and clamps the clear floor at 0', () => {+ const snapshot = createDefaultAlertsConfigurationSnapshot();+ snapshot.guestDefaults.cpu = undefined; // non-number branch -> normalized 0; clear 0-5 -> clamped 0+ snapshot.guestDefaults.memory = 3; // number below default margin -> clear clamps to 0+ snapshot.guestDefaults.disk = 5; // exactly at margin -> clear is exactly 0+ snapshot.guestDefaults.diskRead = 6; // just above margin -> clear is 1++ const { alertConfig } = buildFromSnapshot(snapshot);++ expect(alertConfig?.guestDefaults?.cpu).toEqual({ trigger: 0, clear: 0 });+ expect(alertConfig?.guestDefaults?.memory).toEqual({ trigger: 3, clear: 0 });+ expect(alertConfig?.guestDefaults?.disk).toEqual({ trigger: 5, clear: 0 });+ expect(alertConfig?.guestDefaults?.diskRead).toEqual({ trigger: 6, clear: 1 });+ });++ it('applies the threshold factory to each diskTempByType entry', () => {+ const snapshot = createDefaultAlertsConfigurationSnapshot();+ snapshot.diskTempByType = { hot: 7, sub: 2 };++ const { alertConfig } = buildFromSnapshot(snapshot);++ expect(alertConfig?.diskTempByType?.hot).toEqual({ trigger: 7, clear: 2 });+ expect(alertConfig?.diskTempByType?.sub).toEqual({ trigger: 2, clear: 0 });+ });+});++describe('normalizeGap (via readAlertsConfigurationSnapshot dockerDefaults)', () => {+ // serviceWarnGapPercent flows 1:1 into snapshot.dockerDefaults.serviceWarnGapPercent, so it+ // exposes normalizeGap's output directly (independent of the warn>critical clamp downstream).++ it('falls back to the factory default for non-finite-coercing inputs', () => {+ const fallback = FACTORY_DOCKER_DEFAULTS.serviceWarnGapPercent;+ const badValues: unknown[] = ['abc', Infinity, -Infinity, undefined, {}, NaN];++ badValues.forEach((bad) => {+ const config = {+ overrides: {},+ dockerDefaults: { serviceWarnGapPercent: bad },+ } as unknown as AlertConfig;+ const snapshot = readAlertsConfigurationSnapshot(config);+ expect(snapshot.dockerDefaults.serviceWarnGapPercent).toBe(fallback);+ });+ });++ it('clamps values below 0 up to 0 and above 100 down to 100', () => {+ const low = {+ overrides: {},+ dockerDefaults: { serviceWarnGapPercent: -5 },+ } as AlertConfig;+ expect(readAlertsConfigurationSnapshot(low).dockerDefaults.serviceWarnGapPercent).toBe(0);++ const high = {+ overrides: {},+ dockerDefaults: { serviceWarnGapPercent: 150 },+ } as AlertConfig;+ expect(readAlertsConfigurationSnapshot(high).dockerDefaults.serviceWarnGapPercent).toBe(100);+ });++ it('keeps in-range numeric values (including numeric strings) and boundaries', () => {+ expect(+ readAlertsConfigurationSnapshot({+ overrides: {},+ dockerDefaults: { serviceWarnGapPercent: 0 },+ } as AlertConfig).dockerDefaults.serviceWarnGapPercent,+ ).toBe(0);++ expect(+ readAlertsConfigurationSnapshot({+ overrides: {},+ dockerDefaults: { serviceWarnGapPercent: 100 },+ } as AlertConfig).dockerDefaults.serviceWarnGapPercent,+ ).toBe(100);++ expect(+ readAlertsConfigurationSnapshot({+ overrides: {},+ dockerDefaults: { serviceWarnGapPercent: 42 },+ } as AlertConfig).dockerDefaults.serviceWarnGapPercent,+ ).toBe(42);++ // Number('24') === 24 -> finite, in range, so the string is coerced (not fallback).+ expect(+ readAlertsConfigurationSnapshot({+ overrides: {},+ dockerDefaults: { serviceWarnGapPercent: '24' },+ } as unknown as AlertConfig).dockerDefaults.serviceWarnGapPercent,+ ).toBe(24);+ });+});++describe('normalizeWarningCriticalPair', () => {+ it('keeps warning unchanged when warning is strictly less than critical', () => {+ const snapshot = readAlertsConfigurationSnapshot({+ overrides: {},+ backupDefaults: { enabled: true, warningDays: 5, criticalDays: 10 },+ } as AlertConfig);++ expect(snapshot.backupDefaults.warningDays).toBe(5);+ expect(snapshot.backupDefaults.criticalDays).toBe(10);+ });++ it('treats equal warning/critical as not strictly greater (no clamp)', () => {+ const snapshot = readAlertsConfigurationSnapshot({+ overrides: {},+ backupDefaults: { enabled: true, warningDays: 7, criticalDays: 7 },+ } as AlertConfig);++ expect(snapshot.backupDefaults.warningDays).toBe(7);+ expect(snapshot.backupDefaults.criticalDays).toBe(7);+ });++ it('clamps negative warning and critical inputs to 0 and collapses critical to warning', () => {+ const snapshot = readAlertsConfigurationSnapshot({+ overrides: {},+ backupDefaults: { enabled: true, warningDays: -3, criticalDays: -9 },+ } as AlertConfig);++ expect(snapshot.backupDefaults.warningDays).toBe(0);+ expect(snapshot.backupDefaults.criticalDays).toBe(0);+ });++ it('defaults an undefined warning to 0 while preserving a positive critical', () => {+ const snapshot = readAlertsConfigurationSnapshot({+ overrides: {},+ backupDefaults: { enabled: true, warningDays: undefined, criticalDays: 14 },+ } as unknown as AlertConfig);++ expect(snapshot.backupDefaults.warningDays).toBe(0);+ expect(snapshot.backupDefaults.criticalDays).toBe(14);+ });++ it('inherits critical from warning when critical is 0 (build snapshotDefaults path)', () => {+ const snapshot = createDefaultAlertsConfigurationSnapshot();+ snapshot.snapshotDefaults = { enabled: true, warningDays: 15, criticalDays: 0 };++ const { alertConfig } = buildFromSnapshot(snapshot);++ expect(alertConfig?.snapshotDefaults?.warningDays).toBe(15);+ expect(alertConfig?.snapshotDefaults?.criticalDays).toBe(15);+ });++ it('defaults an undefined critical to 0 and inherits the warning value', () => {+ const snapshot = readAlertsConfigurationSnapshot({+ overrides: {},+ backupDefaults: { enabled: true, warningDays: 4, criticalDays: undefined },+ } as unknown as AlertConfig);++ expect(snapshot.backupDefaults.warningDays).toBe(4);+ expect(snapshot.backupDefaults.criticalDays).toBe(4);+ });+});++describe('normalizeStringList', () => {+ it('returns an empty array for undefined input on the build path', () => {+ const snapshot = createDefaultAlertsConfigurationSnapshot();+ snapshot.dockerIgnoredPrefixes = undefined as unknown as string[];++ const { alertConfig } = buildFromSnapshot(snapshot);++ expect(alertConfig?.dockerIgnoredContainerPrefixes).toEqual([]);+ });++ it('trims entries, drops empty/whitespace-only items, and preserves internal spacing', () => {+ const snapshot = createDefaultAlertsConfigurationSnapshot();+ snapshot.guestTagWhitelist = [' prod ', '\t', '', ' ', 'web app', 'db'];++ const { alertConfig } = buildFromSnapshot(snapshot);++ expect(alertConfig?.guestTagWhitelist).toEqual(['prod', 'web app', 'db']);+ });++ it('does NOT dedupe on the build path (duplicates survive, only trimmed/filtered)', () => {+ const snapshot = createDefaultAlertsConfigurationSnapshot();+ snapshot.backupDefaults = {+ ...snapshot.backupDefaults,+ ignoreVMIDs: ['1', ' 1 ', '2', '1'],+ };++ const { alertConfig } = buildFromSnapshot(snapshot);++ expect(alertConfig?.backupDefaults?.ignoreVMIDs).toEqual(['1', '1', '2', '1']);+ });++ it('dedupes (after trim) on the read path for backup ignoreVMIDs', () => {+ const snapshot = readAlertsConfigurationSnapshot({+ overrides: {},+ backupDefaults: {+ enabled: true,+ warningDays: 7,+ criticalDays: 14,+ ignoreVMIDs: [' 1 ', '1', '2', '2', ''],+ },+ } as AlertConfig);++ expect(snapshot.backupDefaults.ignoreVMIDs).toEqual(['1', '2']);+ });+});++describe('cloneDays (via buildAlertsConfigurationPayload schedule.quietHours.days)', () => {+ it('produces a shallow copy that equals but is not the source reference', () => {+ const snapshot = createDefaultAlertsConfigurationSnapshot();+ const sourceDays = snapshot.scheduleQuietHours.days;++ const { alertConfig } = buildFromSnapshot(snapshot);+ const payloadDays = alertConfig?.schedule?.quietHours?.days;++ expect(payloadDays).toEqual(sourceDays);+ expect(payloadDays).not.toBe(sourceDays);+ });++ it('isolates payload-side mutations from the snapshot', () => {+ const snapshot = createDefaultAlertsConfigurationSnapshot();+ const beforeFriday = snapshot.scheduleQuietHours.days.friday;++ const { alertConfig } = buildFromSnapshot(snapshot);+ const payloadDays = alertConfig?.schedule?.quietHours?.days as Record<string, boolean>;+ payloadDays.friday = !beforeFriday;++ expect(snapshot.scheduleQuietHours.days.friday).toBe(beforeFriday);+ });++ it('spreads arbitrary day keys through the clone', () => {+ const snapshot = createDefaultAlertsConfigurationSnapshot();+ snapshot.scheduleQuietHours.days = {+ ...snapshot.scheduleQuietHours.days,+ customHoliday: true,+ };++ const { alertConfig } = buildFromSnapshot(snapshot);++ expect(+ (alertConfig?.schedule?.quietHours?.days as Record<string, boolean>)?.customHoliday,+ ).toBe(true);+ });+});++describe('cloneBackupDefaults (via createDefaultAlertsConfigurationSnapshot)', () => {+ it('returns a backupDefaults object that is a value-equal but distinct clone', () => {+ const snapshot = createDefaultAlertsConfigurationSnapshot();++ expect(snapshot.backupDefaults).not.toBe(FACTORY_BACKUP_DEFAULTS);+ expect(snapshot.backupDefaults.enabled).toBe(FACTORY_BACKUP_DEFAULTS.enabled);+ expect(snapshot.backupDefaults.warningDays).toBe(FACTORY_BACKUP_DEFAULTS.warningDays);+ expect(snapshot.backupDefaults.ignoreVMIDs).not.toBe(FACTORY_BACKUP_DEFAULTS.ignoreVMIDs);+ expect(snapshot.backupDefaults.ignoreVMIDs).toEqual([]);+ });++ it('isolates ignoreVMIDs mutations from the factory default', () => {+ const snapshot = createDefaultAlertsConfigurationSnapshot();+ // cloneBackupDefaults always yields a defined array (FACTORY_BACKUP_DEFAULTS ships []).+ const clonedIgnoreVMIDs = snapshot.backupDefaults.ignoreVMIDs as string[];+ clonedIgnoreVMIDs.push('999');++ expect(FACTORY_BACKUP_DEFAULTS.ignoreVMIDs).toEqual([]);+ });+});diff --git a/frontend-modern/src/features/standalone/__tests__/agentMachineTableModel.coverage.test.ts b/frontend-modern/src/features/standalone/__tests__/agentMachineTableModel.coverage.test.tsnew file mode 100644index 0000000000..fb62e7b979--- /dev/null+++ b/frontend-modern/src/features/standalone/__tests__/agentMachineTableModel.coverage.test.ts@@ -0,0 +1,450 @@+import { describe, expect, it } from 'vitest';+import type { HostDiskSMART } from '@/types/api';+import type { Resource } from '@/types/resource';+import {+ getAgentMachineDiskIODetails,+ getAgentMachineHottestSmartDiskType,+ getAgentMachineMemoryPercent,+ getAgentMachineRaidSummary,+ getAgentMachineTemperatureCelsius,+ getAgentMachineTemperatureDetailSections,+ timestampMillisFrom,+ type AgentMachineTemperatureDetailRow,+ type AgentMachineTemperatureDetailSection,+} from '../agentMachineTableModel';++const resource = (overrides: Partial<Resource>): Resource =>+ ({+ id: overrides.id ?? 'machine-1',+ name: overrides.name ?? overrides.id ?? 'machine-1',+ displayName: overrides.displayName ?? overrides.name ?? overrides.id ?? 'machine-1',+ type: 'agent',+ platformId: 'agent',+ platformType: 'agent',+ sourceType: 'agent',+ status: 'online',+ lastSeen: 1_700_000_000_000,+ ...overrides,+ }) as Resource;++const rowsFor = (+ sections: readonly AgentMachineTemperatureDetailSection[],+ heading: string,+): AgentMachineTemperatureDetailRow[] => sections.find((entry) => entry.heading === heading)?.rows ?? [];++describe('agentMachineTableModel coverage', () => {+ describe('getAgentMachineMemoryPercent', () => {+ it('derives the percentage from total/used and ignores the current fallback', () => {+ expect(+ getAgentMachineMemoryPercent(resource({ memory: { current: 99, total: 16_000, used: 4_000 } })),+ ).toBe(25);+ });++ it('returns zero when used is explicitly zero rather than the current fallback', () => {+ expect(+ getAgentMachineMemoryPercent(resource({ memory: { current: 99, total: 16_000, used: 0 } })),+ ).toBe(0);+ });++ it('falls back to memory.current when total is non-positive or missing', () => {+ expect(+ getAgentMachineMemoryPercent(resource({ memory: { current: 30, total: 0, used: 5 } })),+ ).toBe(30);+ expect(getAgentMachineMemoryPercent(resource({ memory: { current: 45 } }))).toBe(45);+ });++ it('falls back to memory.current when total is positive but used is not a number', () => {+ expect(getAgentMachineMemoryPercent(resource({ memory: { current: 60, total: 1000 } }))).toBe(+ 60,+ );+ });++ it('prefers memory.current over agent.memory.usage', () => {+ expect(+ getAgentMachineMemoryPercent(+ resource({ memory: { current: 33 }, agent: { memory: { usage: 88 } } }),+ ),+ ).toBe(33);+ });++ it('falls back to agent.memory.usage only when memory.current is absent', () => {+ expect(+ getAgentMachineMemoryPercent(resource({ agent: { memory: { usage: 42 } } })),+ ).toBe(42);+ });++ it('returns undefined when no memory source is available', () => {+ expect(getAgentMachineMemoryPercent(resource({}))).toBeUndefined();+ });+ });++ describe('timestampMillisFrom', () => {+ it('reads valid Date instances and rejects invalid ones', () => {+ const valid = new Date('2023-01-01T00:00:00Z');+ expect(timestampMillisFrom(valid)).toBe(valid.getTime());+ expect(timestampMillisFrom(new Date('not-a-date'))).toBeUndefined();+ });++ it('parses valid date strings and rejects unparseable strings', () => {+ expect(timestampMillisFrom('2023-01-01T00:00:00Z')).toBe(Date.parse('2023-01-01T00:00:00Z'));+ expect(timestampMillisFrom('not-a-date')).toBeUndefined();+ });++ it('treats sub-10^10 numbers as seconds and >=10^10 as milliseconds', () => {+ expect(timestampMillisFrom(1_700_000_000)).toBe(1_700_000_000_000);+ expect(timestampMillisFrom(1_700_000_000_000)).toBe(1_700_000_000_000);+ // Boundary: exactly 10_000_000_000 is treated as milliseconds (not multiplied).+ expect(timestampMillisFrom(10_000_000_000)).toBe(10_000_000_000);+ expect(timestampMillisFrom(9_999_999_999)).toBe(9_999_999_999_000);+ });++ it('returns undefined for non-positive, non-finite, missing, or mistyped inputs', () => {+ expect(timestampMillisFrom(0)).toBeUndefined();+ expect(timestampMillisFrom(-5)).toBeUndefined();+ expect(timestampMillisFrom(Number.NaN)).toBeUndefined();+ expect(timestampMillisFrom(Number.POSITIVE_INFINITY)).toBeUndefined();+ expect(timestampMillisFrom(undefined)).toBeUndefined();+ expect(timestampMillisFrom(true as unknown as number)).toBeUndefined();+ });+ });++ describe('getAgentMachineHottestSmartDiskType', () => {+ it('returns the transport type of the hottest active SMART disk', () => {+ const machine = resource({+ agent: {+ sensors: {+ smart: [+ { device: '/dev/sda', type: 'sata', temperature: 40 },+ { device: '/dev/nvme0', type: 'nvme', temperature: 55 },+ ],+ },+ },+ });+ expect(getAgentMachineHottestSmartDiskType(machine)).toBe('nvme');+ });++ it('keeps the earliest disk when multiple share the hottest temperature', () => {+ const machine = resource({+ agent: {+ sensors: {+ smart: [+ { device: '/dev/sda', type: 'ssd', temperature: 50 },+ { device: '/dev/sdb', type: 'hdd', temperature: 50 },+ ],+ },+ },+ });+ expect(getAgentMachineHottestSmartDiskType(machine)).toBe('ssd');+ });++ it('returns undefined when the hottest active disk has no transport type', () => {+ const machine = resource({+ agent: { sensors: { smart: [{ device: '/dev/sda', temperature: 50 }] } },+ });+ expect(getAgentMachineHottestSmartDiskType(machine)).toBeUndefined();+ });++ it('ignores standby disks', () => {+ const machine = resource({+ agent: {+ sensors: {+ smart: [{ device: '/dev/sda', type: 'sata', temperature: 55, standby: true }],+ },+ },+ });+ expect(getAgentMachineHottestSmartDiskType(machine)).toBeUndefined();+ });++ it('ignores active disks whose temperature is zero', () => {+ const machine = resource({+ agent: { sensors: { smart: [{ device: '/dev/sda', type: 'sata', temperature: 0 }] } },+ });+ expect(getAgentMachineHottestSmartDiskType(machine)).toBeUndefined();+ });++ it('returns undefined when there are no SMART disks', () => {+ expect(getAgentMachineHottestSmartDiskType(resource({}))).toBeUndefined();+ });+ });++ describe('temperature readings and ordering (private helpers)', () => {+ it('keeps only positive, finite sensor temperatures', () => {+ const sections = getAgentMachineTemperatureDetailSections(+ resource({+ agent: {+ sensors: {+ temperatureCelsius: { cpu: 60, ambient: 0, neg: -3, broken: Number.NaN },+ },+ },+ }),+ );+ expect(rowsFor(sections, 'Temperatures')).toEqual([{ label: 'cpu', value: '60°C' }]);+ });++ it('sorts sensor readings worst-first with a numeric label tiebreak', () => {+ const sections = getAgentMachineTemperatureDetailSections(+ resource({+ agent: { sensors: { temperatureCelsius: { hot: 99, t10: 50, t2: 50 } } },+ }),+ );+ expect(rowsFor(sections, 'Temperatures')).toEqual([+ { label: 'hot', value: '99°C' },+ { label: 't2', value: '50°C' },+ { label: 't10', value: '50°C' },+ ]);+ });++ it('sorts fan readings by label with numeric awareness', () => {+ const sections = getAgentMachineTemperatureDetailSections(+ resource({ agent: { sensors: { fanRpm: { fan10: 1000, fan2: 1000, fan1: 1000 } } } }),+ );+ expect(rowsFor(sections, 'Fan Speeds')).toEqual([+ { label: 'fan1', value: '1000 RPM' },+ { label: 'fan2', value: '1000 RPM' },+ { label: 'fan10', value: '1000 RPM' },+ ]);+ });++ it('caps sections at six rows and appends a trailing overflow marker', () => {+ const sections = getAgentMachineTemperatureDetailSections(+ resource({+ agent: {+ sensors: {+ temperatureCelsius: { s1: 10, s2: 20, s3: 30, s4: 40, s5: 50, s6: 60, s7: 70 },+ },+ },+ }),+ );+ const rows = rowsFor(sections, 'Temperatures');+ expect(rows).toHaveLength(7);+ // Worst-first, so the least alarming (s1=10°C) is dropped behind the marker.+ expect(rows.slice(0, 6).map((row) => row.value)).toEqual([+ '70°C',+ '60°C',+ '50°C',+ '40°C',+ '30°C',+ '20°C',+ ]);+ expect(rows[6]).toEqual({ label: '+1 more', value: '', muted: true });+ });++ it('does not cap sections with six or fewer rows', () => {+ const sections = getAgentMachineTemperatureDetailSections(+ resource({+ agent: { sensors: { temperatureCelsius: { s1: 10, s2: 20, s3: 30, s4: 40, s5: 50, s6: 60 } } },+ }),+ );+ const rows = rowsFor(sections, 'Temperatures');+ expect(rows).toHaveLength(6);+ expect(rows.at(-1)).toEqual({ label: 's1', value: '10°C' });+ });++ it('builds SMART labels from device/model, drops non-standby disks lacking a temperature, and marks standby disks', () => {+ const smart = [+ { device: '/dev/sda', model: 'Foo', temperature: 40 },+ { device: '/dev/sdb', temperature: 41 },+ { temperature: 42 },+ { device: '/dev/sdc', standby: true, temperature: 0 },+ { device: '/dev/sdd', temperature: 0 },+ ] as unknown as HostDiskSMART[];+ const sections = getAgentMachineTemperatureDetailSections(+ resource({ agent: { sensors: { smart } } }),+ );+ // Active readings sorted worst-first; standby appended and sorted by label;+ // the device-less disk falls back to "disk" and the zero-temp non-standby+ // disk (/dev/sdd) is skipped entirely.+ expect(rowsFor(sections, 'Disk Temperatures')).toEqual([+ { label: 'Disk disk', value: '42°C' },+ { label: 'Disk /dev/sdb', value: '41°C' },+ { label: 'Disk /dev/sda Foo', value: '40°C' },+ { label: 'Disk /dev/sdc', value: 'standby', muted: true },+ ]);+ });++ it('excludes zero-temperature active SMART disks from the fallback temperature', () => {+ expect(+ getAgentMachineTemperatureCelsius(+ resource({ agent: { sensors: { smart: [{ device: '/dev/sda', temperature: 0 }] } } }),+ ),+ ).toBeUndefined();+ });+ });++ describe('getAgentMachineRaidSummary', () => {+ it('returns an empty string when there are no RAID arrays', () => {+ expect(getAgentMachineRaidSummary(resource({}))).toBe('');+ });++ it('reports degraded arrays and prioritizes failure over rebuilding', () => {+ const failed = resource({+ agent: {+ raid: [+ {+ device: '/dev/md0',+ level: 'raid1',+ state: 'clean',+ totalDevices: 2,+ activeDevices: 1,+ workingDevices: 1,+ failedDevices: 1,+ spareDevices: 0,+ devices: [],+ rebuildPercent: 0,+ },+ ],+ },+ });+ expect(getAgentMachineRaidSummary(failed)).toBe('1/1 degraded');++ // A single array that is both failed and rebuilding still reports degraded.+ const failedAndRebuilding = resource({+ agent: {+ raid: [+ {+ device: '/dev/md0',+ level: 'raid1',+ state: 'clean',+ totalDevices: 2,+ activeDevices: 1,+ workingDevices: 1,+ failedDevices: 1,+ spareDevices: 0,+ devices: [],+ rebuildPercent: 50,+ },+ ],+ },+ });+ expect(getAgentMachineRaidSummary(failedAndRebuilding)).toBe('1/1 degraded');+ });++ it('reports rebuilding arrays when none have failed', () => {+ const rebuilding = resource({+ agent: {+ raid: [+ {+ device: '/dev/md0',+ level: 'raid5',+ state: 'clean',+ totalDevices: 3,+ activeDevices: 3,+ workingDevices: 3,+ failedDevices: 0,+ spareDevices: 0,+ devices: [],+ rebuildPercent: 50,+ },+ ],+ },+ });+ expect(getAgentMachineRaidSummary(rebuilding)).toBe('1/1 rebuilding');+ });++ it('summarizes arrays sharing a single state', () => {+ const uniform = resource({+ agent: {+ raid: [+ {+ device: '/dev/md0',+ level: 'raid1',+ state: 'clean',+ totalDevices: 2,+ activeDevices: 2,+ workingDevices: 2,+ failedDevices: 0,+ spareDevices: 0,+ devices: [],+ rebuildPercent: 0,+ },+ {+ device: '/dev/md1',+ level: 'raid1',+ state: 'clean',+ totalDevices: 2,+ activeDevices: 2,+ workingDevices: 2,+ failedDevices: 0,+ spareDevices: 0,+ devices: [],+ rebuildPercent: 0,+ },+ ],+ },+ });+ expect(getAgentMachineRaidSummary(uniform)).toBe('2 clean');+ });++ it('falls back to a count of arrays when states differ', () => {+ const mixed = resource({+ agent: {+ raid: [+ {+ device: '/dev/md0',+ level: 'raid1',+ state: 'clean',+ totalDevices: 2,+ activeDevices: 2,+ workingDevices: 2,+ failedDevices: 0,+ spareDevices: 0,+ devices: [],+ rebuildPercent: 0,+ },+ {+ device: '/dev/md1',+ level: 'raid5',+ state: 'resync',+ totalDevices: 3,+ activeDevices: 3,+ workingDevices: 3,+ failedDevices: 0,+ spareDevices: 0,+ devices: [],+ rebuildPercent: 0,+ },+ ],+ },+ });+ expect(getAgentMachineRaidSummary(mixed)).toBe('2 arrays');+ });+ });++ describe('getAgentMachineDiskIODetails', () => {+ it('reads from the lower-case diskIo fallback and includes read/write time counters', () => {+ const details = getAgentMachineDiskIODetails(+ resource({+ agent: {+ diskIo: [{ device: ' /dev/sda ', readBytes: 100, readTimeMs: 5, writeTimeMs: 8 }],+ },+ }),+ );+ expect(details).toEqual([+ { device: '/dev/sda', readBytes: 100, readTimeMs: 5, writeTimeMs: 8 },+ ]);+ });++ it('prefers diskIO over the lower-case diskIo fallback when both are present', () => {+ const details = getAgentMachineDiskIODetails(+ resource({+ agent: {+ diskIO: [{ device: '/dev/from-diskIO' }],+ diskIo: [{ device: '/dev/from-diskIo' }],+ },+ }),+ );+ expect(details).toEqual([{ device: '/dev/from-diskIO' }]);+ });++ it('omits negative counters while keeping zero values', () => {+ const details = getAgentMachineDiskIODetails(+ resource({+ agent: {+ diskIO: [{ device: ' /dev/sda ', readTimeMs: -5, writeOps: 0, ioTimeMs: 3 }],+ },+ }),+ );+ expect(details).toEqual([{ device: '/dev/sda', writeOps: 0, ioTimeMs: 3 }]);+ });+ });+});diff --git a/frontend-modern/src/features/storageBackups/__tests__/diskPresentation.coverage.test.ts b/frontend-modern/src/features/storageBackups/__tests__/diskPresentation.coverage.test.tsnew file mode 100644index 0000000000..c195db66bc--- /dev/null+++ b/frontend-modern/src/features/storageBackups/__tests__/diskPresentation.coverage.test.ts@@ -0,0 +1,295 @@+import { describe, expect, it } from 'vitest';+import type { Resource } from '@/types/resource';+import {+ getPhysicalDiskSourceBadgePresentation,+ getPhysicalDiskSourceKey,+ hasUnraidPhysicalDiskFaultSignal,+ isUnraidPhysicalDisk,+ normalizePhysicalDiskFacetFilter,+ type PhysicalDiskPresentationData,+} from '@/features/storageBackups/diskPresentation';++function makeDiskData(+ overrides: Partial<PhysicalDiskPresentationData> = {},+): PhysicalDiskPresentationData {+ return {+ node: '',+ instance: '',+ devPath: '',+ model: '',+ serial: '',+ wwn: '',+ size: 0,+ health: 'UNKNOWN',+ riskReasons: [],+ wearout: -1,+ type: '',+ temperature: 0,+ rpm: 0,+ used: '',+ ...overrides,+ };+}++// ---------------------------------------------------------------------------+// normalizePhysicalDiskState (module-private — exercised via isUnraidPhysicalDisk)+// ---------------------------------------------------------------------------++describe('normalizePhysicalDiskState via isUnraidPhysicalDisk', () => {+ it('lowercases and trims storageGroup before comparing to "unraid-array"', () => {+ expect(+ isUnraidPhysicalDisk(makeDiskData({ storageGroup: ' UNRAID-Array ' })),+ ).toBe(true);+ });++ it('lowercases and trims storageRole on the role+state path', () => {+ expect(+ isUnraidPhysicalDisk(+ makeDiskData({ storageRole: ' Cache ', storageState: ' spinning ' }),+ ),+ ).toBe(true);+ });++ it('returns false on the role path when storageState is whitespace-only', () => {+ expect(+ isUnraidPhysicalDisk(+ makeDiskData({ storageRole: 'data', storageState: ' ' }),+ ),+ ).toBe(false);+ });++ it('returns false when neither storageGroup nor role+state match', () => {+ expect(+ isUnraidPhysicalDisk(+ makeDiskData({ storageRole: 'hot-spare', storageState: 'active' }),+ ),+ ).toBe(false);+ });+});++// ---------------------------------------------------------------------------+// normalizePhysicalDiskHealth (module-private — exercised via hasUnraidPhysicalDiskFaultSignal)+// ---------------------------------------------------------------------------++describe('normalizePhysicalDiskHealth via hasUnraidPhysicalDiskFaultSignal', () => {+ it('uppercases and trims health before checking the bad-health set', () => {+ const disk = makeDiskData({+ storageGroup: 'unraid-array',+ storageState: 'online',+ health: ' faulted ',+ errorCount: 0,+ });+ expect(hasUnraidPhysicalDiskFaultSignal(disk)).toBe(true);+ });++ it('maps empty-string health to a value outside the bad-health set', () => {+ const disk = makeDiskData({+ storageGroup: 'unraid-array',+ storageState: 'online',+ health: '',+ errorCount: 0,+ });+ expect(hasUnraidPhysicalDiskFaultSignal(disk)).toBe(false);+ });+});++// ---------------------------------------------------------------------------+// hasUnraidPhysicalDiskFaultSignal+// ---------------------------------------------------------------------------++describe('hasUnraidPhysicalDiskFaultSignal', () => {+ it('returns false for a non-Unraid disk regardless of errors or fault state', () => {+ expect(+ hasUnraidPhysicalDiskFaultSignal(+ makeDiskData({+ storageGroup: 'proxmox',+ storageState: 'missing',+ health: 'FAILED',+ errorCount: 99,+ }),+ ),+ ).toBe(false);+ });++ it.each(['disabled', 'invalid', 'missing', 'wrong', 'error', 'failed', 'faulted'])(+ 'returns true for Unraid fault state "%s" via storageState (with clean health)',+ (faultState) => {+ expect(+ hasUnraidPhysicalDiskFaultSignal(+ makeDiskData({+ storageGroup: 'unraid-array',+ storageState: faultState,+ health: 'PASSED',+ errorCount: 0,+ }),+ ),+ ).toBe(true);+ },+ );++ it.each(['BAD', 'CRITICAL', 'ERROR', 'FAILED', 'FAIL', 'FAULTED', 'UNHEALTHY'])(+ 'returns true for bad-health "%s" when storageState is clean and errorCount is zero',+ (health) => {+ expect(+ hasUnraidPhysicalDiskFaultSignal(+ makeDiskData({+ storageGroup: 'unraid-array',+ storageState: 'online',+ health,+ errorCount: 0,+ }),+ ),+ ).toBe(true);+ },+ );++ it('returns false for an Unraid disk with undefined storageState and known-good health', () => {+ expect(+ hasUnraidPhysicalDiskFaultSignal(+ makeDiskData({+ storageGroup: 'unraid-array',+ storageState: undefined,+ health: 'PASSED',+ errorCount: 0,+ }),+ ),+ ).toBe(false);+ });+});++// ---------------------------------------------------------------------------+// readPhysicalDiskSourceCandidates (module-private — exercised via getPhysicalDiskSourceKey)+// ---------------------------------------------------------------------------++describe('readPhysicalDiskSourceCandidates via getPhysicalDiskSourceKey', () => {+ it('reads platformData.sources', () => {+ const resource = {+ platformType: '',+ platformData: { sources: ['truenas'] },+ } as unknown as Resource;+ expect(getPhysicalDiskSourceKey(resource)).toBe('truenas');+ });++ it('reads direct resource.sources', () => {+ const resource = {+ platformType: '',+ sources: ['kubernetes'],+ } as unknown as Resource;+ expect(getPhysicalDiskSourceKey(resource)).toBe('kubernetes');+ });++ it('reads keys from platformData.sourceStatus object', () => {+ const resource = {+ platformType: '',+ platformData: { sourceStatus: { docker: { state: 'ok' } } },+ } as unknown as Resource;+ expect(getPhysicalDiskSourceKey(resource)).toBe('docker');+ });++ it('merges all three source arrays into one candidate list', () => {+ const resource = {+ platformType: '',+ sources: ['agent'],+ platformData: {+ sources: ['docker'],+ sourceStatus: { kubernetes: {} },+ },+ } as unknown as Resource;+ // resolvePlatformTypeFromSources applies priority (kubernetes > docker > agent),+ // so the result 'kubernetes' (sourced from sourceStatus) proves all three arrays+ // were read and merged — the individual tests above isolate each source path.+ expect(getPhysicalDiskSourceKey(resource)).toBe('kubernetes');+ });++ it('filters non-string, empty, and whitespace-only entries from source arrays', () => {+ const resource = {+ platformType: '',+ sources: [42, null, { platform: 'x' }, '', ' ', 'truenas'],+ } as unknown as Resource;+ expect(getPhysicalDiskSourceKey(resource)).toBe('truenas');+ });++ it('ignores a non-array sources value (falls back to platformType)', () => {+ const resource = {+ platformType: 'proxmox-pve',+ sources: 'truenas' as unknown as string[],+ } as unknown as Resource;+ expect(getPhysicalDiskSourceKey(resource)).toBe('proxmox-pve');+ });++ it('ignores a non-object sourceStatus value', () => {+ const resource = {+ platformType: '',+ platformData: { sourceStatus: 'truenas' },+ } as unknown as Resource;+ expect(getPhysicalDiskSourceKey(resource)).toBe('');+ });+});++// ---------------------------------------------------------------------------+// getPhysicalDiskSourceBadgePresentation+// ---------------------------------------------------------------------------++describe('getPhysicalDiskSourceBadgePresentation fallback branches', () => {+ it('falls back to "Unknown" label and text-base-content tone for an empty source key', () => {+ const result = getPhysicalDiskSourceBadgePresentation({} as Resource);+ expect(result.label).toBe('Unknown');+ expect(result.className.startsWith('text-base-content')).toBe(true);+ expect(result.className).toContain('text-[9px]');+ });++ it('title-cases an unrecognized non-empty source key for the label', () => {+ const resource = { platformType: 'zebra-fs' } as unknown as Resource;+ const result = getPhysicalDiskSourceBadgePresentation(resource);+ expect(result.label).toBe('Zebra Fs');+ expect(result.className.startsWith('text-base-content')).toBe(true);+ });+});++// ---------------------------------------------------------------------------+// slugifyPhysicalDiskFacetValue (module-private — exercised via normalizePhysicalDiskFacetFilter)+// ---------------------------------------------------------------------------++describe('slugifyPhysicalDiskFacetValue via normalizePhysicalDiskFacetFilter', () => {+ it('replaces special-character runs with single hyphens', () => {+ expect(normalizePhysicalDiskFacetFilter('Foo Bar & Baz!')).toBe('foo-bar-baz');+ });++ it('strips leading and trailing non-alphanumeric characters', () => {+ expect(normalizePhysicalDiskFacetFilter('!!!Cache!!!')).toBe('cache');+ });++ it('collapses multiple separators into one hyphen', () => {+ expect(normalizePhysicalDiskFacetFilter('a b___c')).toBe('a-b-c');+ });++ it('returns "all" when only non-alphanumeric characters are provided', () => {+ expect(normalizePhysicalDiskFacetFilter('!!!???')).toBe('all');+ });+});++// ---------------------------------------------------------------------------+// normalizePhysicalDiskFacetFilter+// ---------------------------------------------------------------------------++describe('normalizePhysicalDiskFacetFilter', () => {+ it('returns "all" for null', () => {+ expect(normalizePhysicalDiskFacetFilter(null)).toBe('all');+ });++ it('returns "all" for undefined', () => {+ expect(normalizePhysicalDiskFacetFilter(undefined)).toBe('all');+ });++ it('returns "all" for empty string', () => {+ expect(normalizePhysicalDiskFacetFilter('')).toBe('all');+ });++ it('returns "all" when the slugified value equals the default filter "all"', () => {+ expect(normalizePhysicalDiskFacetFilter('ALL')).toBe('all');+ });++ it('preserves a normal slug value', () => {+ expect(normalizePhysicalDiskFacetFilter('Parity Disk 2')).toBe('parity-disk-2');+ });+});diff --git a/frontend-modern/src/features/storageBackups/__tests__/resourceStoragePresentation.coverage.test.ts b/frontend-modern/src/features/storageBackups/__tests__/resourceStoragePresentation.coverage.test.tsnew file mode 100644index 0000000000..c10570d0b3--- /dev/null+++ b/frontend-modern/src/features/storageBackups/__tests__/resourceStoragePresentation.coverage.test.ts@@ -0,0 +1,413 @@+import { describe, expect, it } from 'vitest';+import type { Resource, ResourceStorageRiskReason } from '@/types/resource';+import {+ getCanonicalStoragePlatformKey,+ getResourceStorageIssueLabel,+ getResourceStorageIssueSummary,+ getResourceStorageTopologyLabel,+ hasUnraidStorageAttentionIssue,+} from '@/features/storageBackups/resourceStoragePresentation';++// Mirrors the sibling test file's factory. Pure-function module, so no Solid+// root is required.+const makeResource = (overrides: Partial<Resource> = {}): Resource =>+ ({+ id: 'storage-1',+ type: 'storage',+ name: 'tank',+ platformType: 'truenas',+ sourceType: 'api',+ status: 'online',+ storage: {},+ ...overrides,+ }) as Resource;++// Module-private functions exercised here only through their public entry+// points (no export hacking):+// - getResourceStorageRiskIssue -> getResourceStorageIssueSummary / Label+// - collectRiskReasons -> getUnraidShortIssueLabel (via Label) /+// findRiskReason (via hasUnraidStorageAttentionIssue)+// - findRiskReason -> hasUnraidStorageAttentionIssue+// - getCompositePostureIssue -> getResourceStorageIssueSummary / Label++describe('getResourceStorageRiskIssue (via getResourceStorageIssueSummary)', () => {+ it('falls back to the first non-empty storage risk-reason summary when riskSummary is absent', () => {+ const resource = makeResource({+ storage: {+ risk: {+ level: 'warning',+ reasons: [+ { code: 'zfs_state', severity: 'warning', summary: '' },+ { code: 'zfs_state', severity: 'warning', summary: ' ' },+ { code: 'zfs_state', severity: 'warning', summary: ' ZFS pool degraded ' },+ ],+ },+ },+ });++ // Also proves firstRiskReasonSummary skips blank/whitespace-only summaries.+ expect(getResourceStorageIssueSummary(resource)).toBe('ZFS pool degraded');+ });++ it('falls through to PBS storage-risk reasons when storage risk has no usable summary', () => {+ const resource = makeResource({+ storage: {+ risk: {+ level: 'warning',+ reasons: [{ code: 'zfs_state', severity: 'warning', summary: ' ' }],+ },+ },+ pbs: {+ storageRisk: {+ level: 'warning',+ reasons: [+ { code: 'pbs_datastore_state', severity: 'warning', summary: 'PBS datastore degraded' },+ ],+ },+ },+ });++ expect(getResourceStorageIssueSummary(resource)).toBe('PBS datastore degraded');+ });++ it('returns an empty summary when every risk source is absent', () => {+ expect(getResourceStorageIssueSummary(makeResource())).toBe('');+ });+});++describe('collectRiskReasons (via getResourceStorageIssueLabel on Unraid resources)', () => {+ it('orders storage reasons ahead of PBS reasons so the storage copy wins', () => {+ const resource = makeResource({+ storage: {+ arrayState: 'STARTED',+ risk: {+ level: 'warning',+ reasons: [+ { code: 'unraid_disabled_disks', severity: 'warning', summary: 'storage-disk' },+ ],+ },+ },+ pbs: {+ storageRisk: {+ level: 'warning',+ reasons: [+ { code: 'unraid_disabled_disks', severity: 'warning', summary: 'pbs-disk' },+ ],+ },+ },+ });++ expect(getResourceStorageIssueLabel(resource)).toBe('storage-disk');+ });++ it('skips falsy entries inside the reasons arrays', () => {+ const resource = {+ ...makeResource(),+ storage: {+ arrayState: 'STARTED',+ risk: {+ level: 'warning',+ reasons: [+ null,+ { code: 'unraid_missing_disks', severity: 'warning', summary: 'missing' },+ ] as unknown as ResourceStorageRiskReason[],+ },+ },+ } as unknown as Resource;++ // A null entry that was not skipped would throw on `reason.code` access.+ expect(getResourceStorageIssueLabel(resource)).toBe('missing');+ });+});++describe('hasUnraidStorageAttentionIssue', () => {+ it('returns false for resources that are not Unraid storage resources', () => {+ expect(hasUnraidStorageAttentionIssue(makeResource())).toBe(false);+ });++ it('returns true when an attention reason code is present', () => {+ const resource = makeResource({+ storage: {+ arrayState: 'STARTED',+ risk: {+ level: 'warning',+ reasons: [{ code: 'unraid_disabled_disks', severity: 'warning', summary: 'disabled' }],+ },+ },+ });++ expect(hasUnraidStorageAttentionIssue(resource)).toBe(true);+ });++ it('returns false when the Unraid resource only carries non-attention reasons', () => {+ const resource = makeResource({+ storage: {+ arrayState: 'STARTED',+ risk: {+ level: 'warning',+ reasons: [{ code: 'unraid_sync_active', severity: 'warning', summary: 'syncing' }],+ },+ },+ });++ expect(hasUnraidStorageAttentionIssue(resource)).toBe(false);+ });+});++describe('findRiskReason (exercised via hasUnraidStorageAttentionIssue)', () => {+ it('matches reason codes case-insensitively', () => {+ const resource = makeResource({+ storage: {+ arrayState: 'STARTED',+ risk: {+ level: 'warning',+ reasons: [{ code: 'UNRAID_PARITY_UNAVAILABLE', severity: 'warning', summary: 'parity' }],+ },+ },+ });++ expect(hasUnraidStorageAttentionIssue(resource)).toBe(true);+ });++ it('does not match reasons with empty or missing codes', () => {+ const resource = {+ ...makeResource(),+ storage: {+ arrayState: 'STARTED',+ risk: {+ level: 'warning',+ reasons: [{ code: '', summary: 'x' }, { summary: 'y' }] as unknown as ResourceStorageRiskReason[],+ },+ },+ } as unknown as Resource;++ expect(hasUnraidStorageAttentionIssue(resource)).toBe(false);+ });++ it('finds a matching reason collected from the PBS storage risk', () => {+ const resource = makeResource({+ storage: { arrayState: 'STARTED' },+ pbs: {+ storageRisk: {+ level: 'warning',+ reasons: [{ code: 'unraid_missing_disks', severity: 'warning', summary: 'missing' }],+ },+ },+ });++ expect(hasUnraidStorageAttentionIssue(resource)).toBe(true);+ });+});++describe('getCompositePostureIssue (via getResourceStorageIssueSummary)', () => {+ it('surfaces the storage posture summary when status is an attention state', () => {+ const resource = makeResource({+ status: 'degraded',+ storage: { postureSummary: 'Redundancy degraded' },+ });++ expect(getResourceStorageIssueSummary(resource)).toBe('Redundancy degraded');+ });++ it('keeps a distinct posture even when non-matching impact summaries are present', () => {+ const resource = makeResource({+ status: 'degraded',+ storage: {+ postureSummary: 'Redundancy degraded',+ consumerImpactSummary: 'Affects 3 dependent resources',+ },+ });++ expect(getResourceStorageIssueSummary(resource)).toBe('Redundancy degraded');+ });++ it('prefers the PBS posture summary when storage posture is absent', () => {+ const resource = makeResource({+ status: 'warning',+ pbs: { postureSummary: 'Backup posture at risk' },+ });++ expect(getResourceStorageIssueSummary(resource)).toBe('Backup posture at risk');+ });++ it('suppresses posture that merely echoes the storage consumer impact summary', () => {+ const resource = makeResource({+ status: 'degraded',+ storage: {+ postureSummary: 'Affects 2 vms',+ consumerImpactSummary: 'Affects 2 vms',+ },+ });++ expect(getResourceStorageIssueSummary(resource)).toBe('');+ });++ it('suppresses posture that echoes the PBS protected workload summary', () => {+ const resource = makeResource({+ status: 'offline',+ pbs: {+ postureSummary: 'Puts 4 workloads at risk',+ protectedWorkloadSummary: 'Puts 4 workloads at risk',+ },+ });++ expect(getResourceStorageIssueSummary(resource)).toBe('');+ });++ it('suppresses posture that echoes the PBS affected datastore summary', () => {+ const resource = makeResource({+ status: 'degraded',+ pbs: {+ postureSummary: 'Datastore ds-1 unavailable',+ affectedDatastoreSummary: 'Datastore ds-1 unavailable',+ },+ });++ expect(getResourceStorageIssueSummary(resource)).toBe('');+ });++ it('returns no posture issue when the status is not an attention state', () => {+ const resource = makeResource({+ status: 'running',+ storage: { postureSummary: 'Something happened' },+ });++ expect(getResourceStorageIssueSummary(resource)).toBe('');+ });++ it('returns no posture issue when no posture summary is present', () => {+ const resource = makeResource({ status: 'degraded' });++ expect(getResourceStorageIssueSummary(resource)).toBe('');+ });+});++describe('getCanonicalStoragePlatformKey', () => {+ it('prefers a known storagePlatform argument over the resource platformType', () => {+ const resource = makeResource({ platformType: 'truenas' });++ expect(getCanonicalStoragePlatformKey(resource, 'vmware-vsphere')).toBe('vmware-vsphere');+ });++ it('normalizes aliased storagePlatform values', () => {+ const resource = makeResource({ platformType: 'generic' });++ expect(getCanonicalStoragePlatformKey(resource, 'pbs')).toBe('proxmox-pbs');+ });++ it('normalizes the storagePlatform case-insensitively', () => {+ const resource = makeResource({ platformType: 'generic' });++ expect(getCanonicalStoragePlatformKey(resource, 'TRUENAS')).toBe('truenas');+ });++ it('falls back to a known resource platformType when storagePlatform is unknown', () => {+ const resource = makeResource({ platformType: 'proxmox-pve' });++ expect(getCanonicalStoragePlatformKey(resource, 'mystery-box')).toBe('proxmox-pve');+ });++ it('returns the raw resource platformType when neither value normalizes', () => {+ const resource = { ...makeResource(), platformType: 'custom-platform' } as unknown as Resource;++ expect(getCanonicalStoragePlatformKey(resource)).toBe('custom-platform');+ });++ it('lowercases an unknown storagePlatform when platformType is empty', () => {+ const resource = { ...makeResource(), platformType: '' } as unknown as Resource;++ expect(getCanonicalStoragePlatformKey(resource, ' Custom Box ')).toBe('custom box');+ });++ it('falls back to generic when both platformType and storagePlatform are empty', () => {+ const resource = { ...makeResource(), platformType: '' } as unknown as Resource;++ expect(getCanonicalStoragePlatformKey(resource)).toBe('generic');+ });+});++describe('getResourceStorageTopologyLabel', () => {+ it('titleizes an explicit topology argument and bypasses storageType classification', () => {+ expect(getResourceStorageTopologyLabel(makeResource(), 'rbd', 'zfs-pool')).toBe('Zfs Pool');+ });++ it('titleizes multi-word delimited topology values', () => {+ expect(getResourceStorageTopologyLabel(makeResource(), 'anything', 'backup-target')).toBe(+ 'Backup Target',+ );+ });++ it('classifies a backup-target topology from storage metadata as Backup Target', () => {+ const resource = makeResource({ storage: { topology: 'backup-target' } });++ expect(getResourceStorageTopologyLabel(resource, 'dir')).toBe('Backup Target');+ });++ it('classifies PBS-platform storage as Backup Target from platformData when storage meta is absent', () => {+ const resource = makeResource({ storage: {}, platformData: { platform: 'proxmox-pbs' } });++ expect(getResourceStorageTopologyLabel(resource, 'dir')).toBe('Backup Target');+ });++ it('classifies a backup-target topology from platformData when storage meta is absent', () => {+ const resource = makeResource({ storage: {}, platformData: { topology: 'backup-target' } });++ expect(getResourceStorageTopologyLabel(resource, 'dir')).toBe('Backup Target');+ });++ it('labels a datastore resource type as Datastore', () => {+ const resource = makeResource({ type: 'datastore' });++ expect(getResourceStorageTopologyLabel(resource, 'vmfs')).toBe('Datastore');+ });++ it('labels a datastore VMware entity type as Datastore even when the resource type differs', () => {+ const resource = makeResource({+ type: 'storage',+ vmware: { entityType: 'datastore' },+ });++ expect(getResourceStorageTopologyLabel(resource, 'vmfs')).toBe('Datastore');+ });++ it('labels pool storage types', () => {+ const resource = makeResource();+ expect(getResourceStorageTopologyLabel(resource, 'zfspool')).toBe('Pool');+ expect(getResourceStorageTopologyLabel(resource, 'zfs-pool')).toBe('Pool');+ expect(getResourceStorageTopologyLabel(resource, 'pool')).toBe('Pool');+ });++ it('labels dataset storage types', () => {+ const resource = makeResource();+ expect(getResourceStorageTopologyLabel(resource, 'zfs-dataset')).toBe('Dataset');+ expect(getResourceStorageTopologyLabel(resource, 'dataset')).toBe('Dataset');+ });++ it('labels filesystem storage types', () => {+ const resource = makeResource();+ expect(getResourceStorageTopologyLabel(resource, 'dir')).toBe('Filesystem');+ expect(getResourceStorageTopologyLabel(resource, 'filesystem')).toBe('Filesystem');+ });++ it('labels ceph cluster storage types', () => {+ const resource = makeResource();+ expect(getResourceStorageTopologyLabel(resource, 'rbd')).toBe('Cluster Storage');+ expect(getResourceStorageTopologyLabel(resource, 'cephfs')).toBe('Cluster Storage');+ });++ it('titleizes unknown storage types in the default branch', () => {+ expect(getResourceStorageTopologyLabel(makeResource(), 'nfs-share')).toBe('Nfs Share');+ });++ it('falls back to the titleized resource type when storageType is empty', () => {+ const resource = makeResource({ type: 'network-share' });++ expect(getResourceStorageTopologyLabel(resource, '')).toBe('Network Share');+ });++ it('falls back to Storage when both storageType and resource type are empty', () => {+ const resource = { ...makeResource(), type: '' } as unknown as Resource;++ expect(getResourceStorageTopologyLabel(resource, '')).toBe('Storage');+ });+});diff --git a/frontend-modern/src/features/truenas/__tests__/truenasPageModel.coverage.test.ts b/frontend-modern/src/features/truenas/__tests__/truenasPageModel.coverage.test.tsnew file mode 100644index 0000000000..936469fce3--- /dev/null+++ b/frontend-modern/src/features/truenas/__tests__/truenasPageModel.coverage.test.ts@@ -0,0 +1,507 @@+import { describe, expect, it } from 'vitest';+import type { RecoveryPoint } from '@/types/recovery';+import type { Resource } from '@/types/resource';+import {+ buildTrueNASPageModel,+ buildTrueNASProtectionPosture,+ buildTrueNASStorageChildCounts,+ buildTrueNASStorageTopologyRows,+ buildTrueNASSystemChildCounts,+ mapTrueNASProtectionKind,+ mapTrueNASProtectionStatus,+ sortTrueNASProtectionPoints,+} from '../truenasPageModel';++const makeResource = (resource: Partial<Resource> & Pick<Resource, 'id' | 'type'>): Resource => ({+ name: resource.id,+ displayName: resource.id,+ platformId: 'lab',+ platformType: 'truenas',+ sourceType: 'api',+ status: 'online',+ lastSeen: 1_700_000_000_000,+ ...resource,+});++const makeRecoveryPoint = (+ point: Partial<RecoveryPoint> & Pick<RecoveryPoint, 'id' | 'kind' | 'mode'>,+): RecoveryPoint => ({+ outcome: 'success',+ platform: 'truenas',+ startedAt: '2026-05-20T00:00:00Z',+ completedAt: '2026-05-20T00:00:00Z',+ ...point,+});++describe('truenasPageModel coverage', () => {+ describe('dataset/share/disk type-dispatch fallbacks', () => {+ it('classifies type "pool" resources as pools without requiring storage.topology', () => {+ const model = buildTrueNASPageModel([+ makeResource({ id: 'sys', type: 'agent' }),+ makeResource({ id: 'tank', type: 'pool' }),+ ]);+ expect(model.pools.map((r) => r.id)).toEqual(['tank']);+ expect(model.resources.map((r) => r.id)).toContain('tank');+ });++ it('classifies type "dataset" resources as datasets without requiring storage.topology', () => {+ const model = buildTrueNASPageModel([+ makeResource({ id: 'sys', type: 'agent' }),+ makeResource({ id: 'media', type: 'dataset' }),+ ]);+ expect(model.datasets.map((r) => r.id)).toEqual(['media']);+ });++ it('counts pools via storage.topology when type is "storage" and topology is "pool"', () => {+ const pool = makeResource({+ id: 'tank',+ type: 'storage',+ storage: { topology: 'pool', platform: 'truenas' },+ });+ const counts = buildTrueNASSystemChildCounts(+ [makeResource({ id: 'sys', type: 'agent' }), pool],+ [makeResource({ id: 'sys', type: 'agent' })],+ );+ expect(counts.get('sys')?.pools).toBe(1);+ });++ it('returns an empty map when no systems are provided', () => {+ const counts = buildTrueNASSystemChildCounts(+ [makeResource({ id: 'orphan-pool', type: 'pool' })],+ [],+ );+ expect(counts.size).toBe(0);+ });++ it('counts zero services when system has no truenas metadata at all', () => {+ const system = makeResource({ id: 'sys', type: 'agent' });+ const counts = buildTrueNASSystemChildCounts([system], [system]);+ expect(counts.get(system.id)?.services).toBe(0);+ });++ it('counts zero services when system truenas exists but services array is absent', () => {+ const system = makeResource({ id: 'sys', type: 'agent', truenas: { hostname: 'nas' } });+ const counts = buildTrueNASSystemChildCounts([system], [system]);+ expect(counts.get(system.id)?.services).toBe(0);+ });++ it('does not count unparented resources when multiple systems exist', () => {+ const sysA = makeResource({ id: 'sys-a', type: 'agent' });+ const sysB = makeResource({ id: 'sys-b', type: 'agent' });+ const orphanPool = makeResource({ id: 'orphan-pool', type: 'pool' });+ const counts = buildTrueNASSystemChildCounts([sysA, sysB, orphanPool], [sysA, sysB]);+ expect(counts.get(sysA.id)?.pools).toBe(0);+ expect(counts.get(sysB.id)?.pools).toBe(0);+ });++ it('does not attribute a non-agent resource whose id collides with the single-system id', () => {+ const system = makeResource({ id: 'sys', type: 'agent' });+ const collidingPool = makeResource({ id: 'sys', type: 'pool' });+ const counts = buildTrueNASSystemChildCounts([system, collidingPool], [system]);+ expect(counts.get(system.id)?.pools).toBe(0);+ });++ it('does not increment storage child counts for non-storage child types', () => {+ const pool = makeResource({+ id: 'pool-tank',+ type: 'pool',+ storage: { topology: 'pool', platform: 'truenas' },+ });+ const vm = makeResource({ id: 'vm-1', type: 'vm', parentId: pool.id });+ const counts = buildTrueNASStorageChildCounts([pool, vm]);+ expect(counts.get(pool.id)).toEqual({ datasets: 0, shares: 0, disks: 0 });+ });++ it('does not infer pool relationship when resource has no inferable pool name', () => {+ const pool = makeResource({+ id: 'pool-tank',+ type: 'pool',+ name: 'tank',+ storage: { topology: 'pool', platform: 'truenas', zfsPoolState: 'ONLINE' },+ });+ const blankShare = makeResource({+ id: 'blank-share',+ type: 'network-share',+ name: ' ',+ displayName: ' ',+ });+ const counts = buildTrueNASStorageChildCounts([pool, blankShare]);+ expect(counts.get(pool.id)).toEqual({ datasets: 0, shares: 0, disks: 0 });+ });+ });++ describe('numeric guards', () => {+ it('treats absent timestamps as zero when sorting protection points', () => {+ const a = makeRecoveryPoint({+ id: 'a-point',+ kind: 'snapshot',+ mode: 'snapshot',+ completedAt: null,+ startedAt: null,+ });+ const z = makeRecoveryPoint({+ id: 'z-point',+ kind: 'snapshot',+ mode: 'snapshot',+ completedAt: null,+ startedAt: null,+ });+ const sorted = sortTrueNASProtectionPoints([z, a]);+ expect(sorted.map((p) => p.id)).toEqual(['a-point', 'z-point']);+ });++ it('falls back to startedAt when completedAt is absent', () => {+ const older = makeRecoveryPoint({+ id: 'older',+ kind: 'snapshot',+ mode: 'snapshot',+ completedAt: null,+ startedAt: '2026-01-01T00:00:00Z',+ });+ const newer = makeRecoveryPoint({+ id: 'newer',+ kind: 'snapshot',+ mode: 'snapshot',+ completedAt: null,+ startedAt: '2026-06-01T00:00:00Z',+ });+ expect(sortTrueNASProtectionPoints([older, newer]).map((p) => p.id)).toEqual([+ 'newer',+ 'older',+ ]);+ });++ it('treats an invalid date string as NaN and falls back to zero timestamp', () => {+ const invalid = makeRecoveryPoint({+ id: 'invalid',+ kind: 'snapshot',+ mode: 'snapshot',+ completedAt: 'not-a-real-date',+ startedAt: null,+ });+ const valid = makeRecoveryPoint({+ id: 'valid',+ kind: 'snapshot',+ mode: 'snapshot',+ completedAt: '2026-03-01T00:00:00Z',+ startedAt: '2026-03-01T00:00:00Z',+ });+ expect(sortTrueNASProtectionPoints([invalid, valid]).map((p) => p.id)).toEqual([+ 'valid',+ 'invalid',+ ]);+ });++ it('breaks ties by label when timestamps are equal', () => {+ const same = '2026-05-20T00:00:00Z';+ const z = makeRecoveryPoint({+ id: 'z-point',+ kind: 'snapshot',+ mode: 'snapshot',+ completedAt: same,+ startedAt: same,+ });+ const a = makeRecoveryPoint({+ id: 'a-point',+ kind: 'snapshot',+ mode: 'snapshot',+ completedAt: same,+ startedAt: same,+ });+ expect(sortTrueNASProtectionPoints([z, a]).map((p) => p.id)).toEqual(['a-point', 'z-point']);+ });+ });++ describe('replication status ranking', () => {+ it('maps "ok" outcome to the success bucket', () => {+ expect(+ mapTrueNASProtectionStatus(+ makeRecoveryPoint({ id: 'p', kind: 'snapshot', mode: 'snapshot', outcome: 'ok' }),+ ),+ ).toBe('success');+ });++ it('maps "warn" outcome to the warning bucket', () => {+ expect(+ mapTrueNASProtectionStatus(+ makeRecoveryPoint({ id: 'p', kind: 'snapshot', mode: 'snapshot', outcome: 'warn' }),+ ),+ ).toBe('warning');+ });++ it('maps "failed" outcome to the failed bucket', () => {+ expect(+ mapTrueNASProtectionStatus(+ makeRecoveryPoint({ id: 'p', kind: 'snapshot', mode: 'snapshot', outcome: 'failed' }),+ ),+ ).toBe('failed');+ });++ it('maps "failure" outcome to the failed bucket', () => {+ expect(+ mapTrueNASProtectionStatus(+ makeRecoveryPoint({ id: 'p', kind: 'snapshot', mode: 'snapshot', outcome: 'failure' }),+ ),+ ).toBe('failed');+ });++ it('maps "error" outcome to the failed bucket', () => {+ expect(+ mapTrueNASProtectionStatus(+ makeRecoveryPoint({ id: 'p', kind: 'snapshot', mode: 'snapshot', outcome: 'error' }),+ ),+ ).toBe('failed');+ });++ it('maps an unrecognized outcome string to the unknown bucket', () => {+ expect(+ mapTrueNASProtectionStatus(+ makeRecoveryPoint({ id: 'p', kind: 'snapshot', mode: 'snapshot', outcome: 'pending' }),+ ),+ ).toBe('unknown');+ });++ it('tallies failed and unknown outcomes in the protection posture', () => {+ const posture = buildTrueNASProtectionPosture([+ makeRecoveryPoint({ id: 'ok', kind: 'snapshot', mode: 'snapshot', outcome: 'success' }),+ makeRecoveryPoint({ id: 'fail', kind: 'snapshot', mode: 'snapshot', outcome: 'failed' }),+ makeRecoveryPoint({ id: 'mystery', kind: 'snapshot', mode: 'snapshot', outcome: 'pending' }),+ ]);+ expect(posture).toEqual({+ healthy: 1,+ warning: 0,+ failed: 1,+ running: 0,+ unknown: 1,+ attention: 1,+ });+ });++ it('returns a fully zeroed posture for an empty recovery-point array', () => {+ expect(buildTrueNASProtectionPosture([])).toEqual({+ healthy: 0,+ warning: 0,+ failed: 0,+ running: 0,+ unknown: 0,+ attention: 0,+ });+ });++ it('classifies as replication when only details.taskId is present', () => {+ expect(+ mapTrueNASProtectionKind(+ makeRecoveryPoint({+ id: 'p',+ kind: 'other',+ mode: 'local',+ details: { taskId: 'rep-task-42' },+ }),+ ),+ ).toBe('replication');+ });++ it('classifies as replication when only details.targetDataset is present', () => {+ expect(+ mapTrueNASProtectionKind(+ makeRecoveryPoint({+ id: 'p',+ kind: 'other',+ mode: 'local',+ details: { targetDataset: 'offsite/backup' },+ }),+ ),+ ).toBe('replication');+ });++ it('classifies as other when details is null and no replication signals exist', () => {+ expect(+ mapTrueNASProtectionKind(+ makeRecoveryPoint({+ id: 'p',+ kind: 'other',+ mode: 'local',+ details: null,+ }),+ ),+ ).toBe('other');+ });++ it('classifies as other when details has no replication fields', () => {+ expect(+ mapTrueNASProtectionKind(+ makeRecoveryPoint({+ id: 'p',+ kind: 'other',+ mode: 'local',+ details: { snapshot: 'auto-20260101' },+ }),+ ),+ ).toBe('other');+ });+ });++ describe('dataset-child merge without platformData.truenas', () => {+ it('places orphaned datasets with no pool or dataset parent at root level', () => {+ const orphan = makeResource({+ id: 'ds-orphan',+ type: 'dataset',+ name: 'lonely/data',+ storage: { topology: 'dataset', platform: 'truenas', path: '/mnt/lonely/data' },+ });+ const rows = buildTrueNASStorageTopologyRows([orphan]);+ expect(rows.map((r) => [r.id, r.depth, r.parentRowId])).toEqual([+ ['dataset:ds-orphan', 0, undefined],+ ]);+ });++ it('renders disks not under any pool at depth 0', () => {+ const disk = makeResource({+ id: 'loose-disk',+ type: 'physical_disk',+ name: 'sda',+ physicalDisk: { devPath: '/dev/sda', serial: 'x' },+ });+ const rows = buildTrueNASStorageTopologyRows([disk]);+ expect(rows.map((r) => [r.id, r.depth, r.parentRowId])).toEqual([+ ['disk:loose-disk', 0, undefined],+ ]);+ });++ it('infers dataset-share relationship from storage path when truenas metadata is absent', () => {+ const dataset = makeResource({+ id: 'ds-media',+ type: 'dataset',+ name: 'tank/media',+ storage: { topology: 'dataset', platform: 'truenas', path: '/mnt/tank/media' },+ });+ const share = makeResource({+ id: 'share-media',+ type: 'network-share',+ name: 'share-media',+ storage: { path: '/mnt/tank/media' },+ });+ const counts = buildTrueNASStorageChildCounts([dataset, share]);+ expect(counts.get(dataset.id)).toEqual({ datasets: 0, shares: 1, disks: 0 });+ });++ it('nests child datasets under explicit parentId even without truenas metadata', () => {+ const parent = makeResource({+ id: 'ds-parent',+ type: 'dataset',+ name: 'tank/media',+ storage: { topology: 'dataset', platform: 'truenas', path: '/mnt/tank/media' },+ });+ const child = makeResource({+ id: 'ds-child',+ type: 'dataset',+ name: 'tank/media/photos',+ parentId: parent.id,+ storage: { topology: 'dataset', platform: 'truenas', path: '/mnt/tank/media/photos' },+ });+ const rows = buildTrueNASStorageTopologyRows([parent, child]);+ expect(rows.map((r) => [r.id, r.depth, r.parentRowId])).toEqual([+ ['dataset:ds-parent', 0, undefined],+ ['dataset:ds-child', 1, 'dataset:ds-parent'],+ ]);+ });++ it('nests datasets by storage-path inference when parentId is absent', () => {+ const parent = makeResource({+ id: 'ds-tank',+ type: 'dataset',+ name: 'tank',+ storage: { topology: 'dataset', platform: 'truenas', path: '/mnt/tank' },+ });+ const child = makeResource({+ id: 'ds-tank-media',+ type: 'dataset',+ name: 'tank/media',+ storage: { topology: 'dataset', platform: 'truenas', path: '/mnt/tank/media' },+ });+ const rows = buildTrueNASStorageTopologyRows([parent, child]);+ expect(rows.map((r) => [r.id, r.depth, r.parentRowId])).toEqual([+ ['dataset:ds-tank', 0, undefined],+ ['dataset:ds-tank-media', 1, 'dataset:ds-tank'],+ ]);+ });++ it('attributes orphaned disks to the sole pool via single-pool fallback', () => {+ const pool = makeResource({+ id: 'only-pool',+ type: 'pool',+ name: 'tank',+ storage: { topology: 'pool', platform: 'truenas', zfsPoolState: 'ONLINE' },+ });+ const disk = makeResource({+ id: 'loose-disk',+ type: 'physical_disk',+ name: 'sda',+ physicalDisk: { devPath: '/dev/sda', serial: 'x' },+ });+ const rows = buildTrueNASStorageTopologyRows([pool, disk]);+ expect(rows.map((r) => [r.id, r.depth, r.parentRowId])).toEqual([+ ['pool:only-pool', 0, undefined],+ ['disk:loose-disk', 1, 'pool:only-pool'],+ ]);+ });++ it('does not nest datasets under candidates from a different pool', () => {+ const poolA = makeResource({+ id: 'pool-a',+ type: 'pool',+ name: 'alpha',+ storage: { topology: 'pool', platform: 'truenas', zfsPoolState: 'ONLINE' },+ });+ const poolB = makeResource({+ id: 'pool-b',+ type: 'pool',+ name: 'beta',+ storage: { topology: 'pool', platform: 'truenas', zfsPoolState: 'ONLINE' },+ });+ const datasetB = makeResource({+ id: 'ds-b',+ type: 'dataset',+ name: 'alpha/media',+ storage: {+ topology: 'dataset',+ platform: 'truenas',+ pool: 'beta',+ path: '/mnt/alpha/media',+ },+ });+ const datasetA = makeResource({+ id: 'ds-a',+ type: 'dataset',+ name: 'alpha/media/photos',+ storage: {+ topology: 'dataset',+ platform: 'truenas',+ path: '/mnt/alpha/media/photos',+ },+ });+ const rows = buildTrueNASStorageTopologyRows([poolA, poolB, datasetB, datasetA]);+ const aRow = rows.find((r) => r.id === 'dataset:ds-a');+ expect(aRow?.parentRowId).not.toBe('dataset:ds-b');+ const bRow = rows.find((r) => r.id === 'dataset:ds-b');+ expect(bRow?.parentRowId).not.toBe('dataset:ds-b');+ });++ it('returns empty storage child counts for a pool when no children match', () => {+ const pool = makeResource({+ id: 'pool-tank',+ type: 'pool',+ name: 'tank',+ storage: { topology: 'pool', platform: 'truenas', zfsPoolState: 'ONLINE' },+ });+ const unrelatedShare = makeResource({+ id: 'share-other',+ type: 'network-share',+ name: 'share-other',+ storage: { path: '/mnt/other/data' },+ });+ const counts = buildTrueNASStorageChildCounts([pool, unrelatedShare]);+ expect(counts.get(pool.id)).toEqual({ datasets: 0, shares: 0, disks: 0 });+ });+ });+});diff --git a/frontend-modern/src/utils/__tests__/alertOverviewPresentation.coverage.test.ts b/frontend-modern/src/utils/__tests__/alertOverviewPresentation.coverage.test.tsnew file mode 100644index 0000000000..7820b53bcc--- /dev/null+++ b/frontend-modern/src/utils/__tests__/alertOverviewPresentation.coverage.test.ts@@ -0,0 +1,144 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { DEFAULT_LOCALE, setActiveLocale } from '@/i18n';+import {+ getAlertFilteredEmptyState,+ getAlertOverviewAcknowledgedToggleLabel,+ getAlertOverviewAcknowledgementFailureNotification,+ getAlertOverviewBulkAcknowledgeFailureNotification,+ getAlertOverviewBulkAcknowledgedNotification,+ getAlertOverviewCardPresentation,+ getAlertOverviewTimelineActionLabel,+ getAlertTimelineEventTypeLabel,+} from '@/utils/alertOverviewPresentation';++describe('alertOverviewPresentation coverage', () => {+ beforeEach(() => {+ setActiveLocale(DEFAULT_LOCALE);+ });++ afterEach(() => {+ setActiveLocale(DEFAULT_LOCALE);+ });++ describe('severity projection — getAlertOverviewCardPresentation', () => {+ it('dims an acknowledged alert with opacity-60 when it is not processing', () => {+ const presentation = getAlertOverviewCardPresentation('critical', true, false);++ expect(presentation.cardClassName).toBe(+ 'border rounded-md p-3 sm:p-4 transition-all opacity-60 border-border bg-surface-alt',+ );+ expect(presentation.iconClassName).toBe(+ 'mr-3 mt-0.5 transition-all text-green-600 dark:text-green-400',+ );+ expect(presentation.resourceClassName).toBe(+ 'text-sm font-medium truncate text-red-700 dark:text-red-400',+ );+ });++ it('projects an unacknowledged, non-critical severity onto the warning palette', () => {+ const presentation = getAlertOverviewCardPresentation('warning', false, false);++ expect(presentation.cardClassName).toBe(+ 'border rounded-md p-3 sm:p-4 transition-all border-yellow-300 dark:border-yellow-800 bg-yellow-50 dark:bg-yellow-900',+ );+ expect(presentation.iconClassName).toBe(+ 'mr-3 mt-0.5 transition-all text-yellow-600 dark:text-yellow-400',+ );+ expect(presentation.resourceClassName).toBe(+ 'text-sm font-medium truncate text-yellow-700 dark:text-yellow-400',+ );+ });++ it('treats an unrecognized severity string as non-critical rather than critical', () => {+ const presentation = getAlertOverviewCardPresentation('info', false, false);++ expect(presentation.cardClassName).toContain('border-yellow-300');+ expect(presentation.cardClassName).not.toContain('border-red-300');+ expect(presentation.iconClassName).toContain('text-yellow-600');+ expect(presentation.resourceClassName).toContain('text-yellow-700');+ });+ });++ describe('ack-state projection', () => {+ it('reports a restore failure when an already-acknowledged alert fails to toggle', () => {+ expect(getAlertOverviewAcknowledgementFailureNotification(true)).toBe(+ 'Failed to restore alert',+ );+ });++ it('reports an acknowledge failure when an unacknowledged alert fails to toggle', () => {+ expect(getAlertOverviewAcknowledgementFailureNotification(false)).toBe(+ 'Failed to acknowledge alert',+ );+ });++ it('offers to show acknowledged alerts when they are currently hidden', () => {+ expect(getAlertOverviewAcknowledgedToggleLabel(false)).toBe('Show acknowledged');+ });++ it('offers to collapse the timeline when it is expanded', () => {+ expect(getAlertOverviewTimelineActionLabel(true)).toBe('Hide Timeline');+ });+ });++ describe('bulk acknowledgement notification thresholds', () => {+ it('uses the singular success copy for a single acknowledged alert', () => {+ expect(getAlertOverviewBulkAcknowledgedNotification(1)).toBe('Acknowledged 1 alert.');+ });++ it('uses the plural failure copy when several alerts fail to acknowledge', () => {+ expect(getAlertOverviewBulkAcknowledgeFailureNotification(2)).toBe(+ 'Failed to acknowledge 2 alerts.',+ );+ });+ });++ describe('timeline event-type projection', () => {+ it('labels an alert_fired event as Fired', () => {+ expect(getAlertTimelineEventTypeLabel('alert_fired')).toBe('Fired');+ });++ it('labels an alert_acknowledged event as Ack', () => {+ expect(getAlertTimelineEventTypeLabel('alert_acknowledged')).toBe('Ack');+ });++ it('labels an alert_unacknowledged event as Unack', () => {+ expect(getAlertTimelineEventTypeLabel('alert_unacknowledged')).toBe('Unack');+ });++ it('labels an ai_analysis event as Patrol', () => {+ expect(getAlertTimelineEventTypeLabel('ai_analysis')).toBe('Patrol');+ });++ it('labels a runbook event as Runbook', () => {+ expect(getAlertTimelineEventTypeLabel('runbook')).toBe('Runbook');+ });++ it('labels a note event as Note', () => {+ expect(getAlertTimelineEventTypeLabel('note')).toBe('Note');+ });+ });++ describe('filtered empty-state normalization', () => {+ it('falls back to the default subject and filter label with no arguments', () => {+ expect(getAlertFilteredEmptyState()).toEqual({+ title: 'No alerts match current filters',+ description: 'Adjust the search or active filter to see more alerts.',+ });+ });++ it('falls back to defaults when both arguments are only whitespace', () => {+ expect(getAlertFilteredEmptyState(' ', ' ')).toEqual({+ title: 'No alerts match current filters',+ description: 'Adjust the search or active filter to see more alerts.',+ });+ });++ it('keeps a provided subject but falls back to the default filter label', () => {+ expect(getAlertFilteredEmptyState('hosts', ' ')).toEqual({+ title: 'No hosts match current filters',+ description: 'Adjust the search or active filter to see more hosts.',+ });+ });+ });+});