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
test(frontend): branch coverage for 8 pure modules (GLM wave 0712 tier 2c)
rcourtman48ecb9384887
diff --git a/frontend-modern/src/components/Workloads/__tests__/stackedDiskBarModel.branchcov0712b.test.ts b/frontend-modern/src/components/Workloads/__tests__/stackedDiskBarModel.branchcov0712b.test.tsnew file mode 100644index 0000000000..94e9a88cdf--- /dev/null+++ b/frontend-modern/src/components/Workloads/__tests__/stackedDiskBarModel.branchcov0712b.test.ts@@ -0,0 +1,467 @@+import { describe, expect, it } from 'vitest';++import type { AnomalyReport } from '@/types/aiIntelligence';+import type { Disk } from '@/types/api';++import { buildStackedDiskBarPresentation } from '../stackedDiskBarModel';++// The four small helpers under test (getDiskUsagePercent, getShortDiskLabel,+// getInlineDiskText, getStackedDiskColor) are module-private, so every branch+// is exercised through the exported buildStackedDiskBarPresentation and+// asserted on concrete fields (miniDisks[].percent / shortLabel / inlineText,+// segments[].color, verticalBars[].fillPercent, ...).++// Palette mirrored from the module under test (not exported).+const SEGMENT_COLORS = [+ 'rgba(34, 197, 94, 0.6)',+ 'rgba(59, 130, 246, 0.6)',+ 'rgba(168, 85, 247, 0.6)',+ 'rgba(249, 115, 22, 0.6)',+ 'rgba(236, 72, 153, 0.6)',+ 'rgba(20, 184, 166, 0.6)',+];+const NORMAL = 'rgba(34, 197, 94, 0.6)';+const WARNING = 'rgba(234, 179, 8, 0.6)';+const CRITICAL = 'rgba(239, 68, 68, 0.6)';++const makeDisk = (overrides: Partial<Disk> = {}): Disk => ({+ total: 100,+ used: 0,+ free: 100,+ usage: 0,+ mountpoint: '/',+ ...overrides,+});++const makeAnomaly = (overrides: Partial<AnomalyReport> = {}): AnomalyReport => ({+ resource_id: 'r1',+ resource_name: 'resource-1',+ resource_type: 'guest',+ metric: 'disk',+ current_value: 25,+ baseline_mean: 10,+ baseline_std_dev: 1,+ z_score: 15,+ severity: 'high',+ description: 'Disk usage spike',+ ...overrides,+});++describe('stackedDiskBarModel (branch coverage 2)', () => {+ describe('getDiskUsagePercent (via miniDisks[].percent)', () => {+ it('uses the used/total ratio when total > 0', () => {+ // Branch: disk.total > 0 -> (used / total) * 100.+ const p = buildStackedDiskBarPresentation(+ { disks: [makeDisk({ total: 200, used: 50, free: 150, usage: 25 })] },+ 400,+ );+ expect(p.miniDisks[0].percent).toBe(25);+ });++ it('scales a fractional usage (<=1) by 100 when total <= 0', () => {+ // Branch: total <= 0, Number.isFinite(usage), usage <= 1 -> usage * 100.+ const p = buildStackedDiskBarPresentation(+ { disks: [makeDisk({ total: 0, used: 0, free: 0, usage: 0.5 })] },+ 400,+ );+ expect(p.miniDisks[0].percent).toBe(50);+ });++ it('returns a usage value > 1 unchanged when total <= 0', () => {+ // Branch: total <= 0, usage finite, usage > 1 -> usage.+ const p = buildStackedDiskBarPresentation(+ { disks: [makeDisk({ total: 0, used: 0, free: 0, usage: 75 })] },+ 400,+ );+ expect(p.miniDisks[0].percent).toBe(75);+ });++ it('returns 0 when total <= 0 and usage is not finite', () => {+ // Branch: total <= 0, !Number.isFinite(usage) -> 0.+ const p = buildStackedDiskBarPresentation(+ { disks: [makeDisk({ total: 0, used: 0, free: 0, usage: Number.NaN })] },+ 400,+ );+ expect(p.miniDisks[0].percent).toBe(0);+ });+ });++ describe('getShortDiskLabel (via miniDisks[].shortLabel)', () => {+ it('strips /dev/, returns root, takes the last path segment, and returns short/long labels unchanged', () => {+ // Drives all five return arms in array order:+ // '/dev/sda1' -> slice '/dev/' -> 'sda1'+ // '/' -> trimmed === '/' -> '/'+ // '/var/log' -> absolute path -> last segment 'log'+ // 'data' -> length <= 12 -> 'data'+ // 'verylongmount' -> fall-through -> 'verylongmount'+ const p = buildStackedDiskBarPresentation(+ {+ disks: [+ makeDisk({ mountpoint: '/dev/sda1' }),+ makeDisk({ mountpoint: '/' }),+ makeDisk({ mountpoint: '/var/log' }),+ makeDisk({ mountpoint: 'data' }),+ makeDisk({ mountpoint: 'verylongmount' }),+ ],+ },+ 400,+ );+ expect(p.miniDisks.map((d) => d.shortLabel)).toEqual([+ 'sda1',+ '/',+ 'log',+ 'data',+ 'verylongmount',+ ]);+ });+ });++ describe('getInlineDiskText (via miniDisks[].inlineText)', () => {+ // estimateInlineTextWidth(text) = text.length * 5.4 + 4 (module-internal).+ it('returns the full text when slotWidth <= 0 (short-circuit)', () => {+ // slotWidth = containerWidth(0) / 1 = 0 -> first operand of the || .+ const p = buildStackedDiskBarPresentation(+ { disks: [makeDisk({ mountpoint: '/dev/sda1', total: 100, used: 50, free: 50, usage: 50 })] },+ 0,+ );+ expect(p.miniDisks[0].inlineText).toBe('sda1 50%');+ });++ it('returns the full text when it fits within the slot', () => {+ // 'sda1 50%' width = 8 * 5.4 + 4 = 47.2 <= slotWidth(60).+ const p = buildStackedDiskBarPresentation(+ { disks: [makeDisk({ mountpoint: '/dev/sda1', total: 100, used: 50, free: 50, usage: 50 })] },+ 60,+ );+ expect(p.miniDisks[0].inlineText).toBe('sda1 50%');+ });++ it('falls back to the percent label when only it fits', () => {+ // shortLabel 'a', percentLabel '100%'. full 'a 100%' width 36.4 > 30;+ // '100%' width 25.6 <= 30 -> returns '100%'.+ const p = buildStackedDiskBarPresentation(+ { disks: [makeDisk({ mountpoint: '/dev/a', total: 100, used: 100, free: 0, usage: 100 })] },+ 30,+ );+ expect(p.miniDisks[0].inlineText).toBe('100%');+ });++ it('falls back to the short label when the percent label does not fit but the short label does', () => {+ // slotWidth 20: full 36.4 > 20; percent '100%' 25.6 > 20; short 'a' 9.4 <= 20 -> 'a'.+ const p = buildStackedDiskBarPresentation(+ { disks: [makeDisk({ mountpoint: '/dev/a', total: 100, used: 100, free: 0, usage: 100 })] },+ 20,+ );+ expect(p.miniDisks[0].inlineText).toBe('a');+ });++ it('returns an empty string when neither label fits', () => {+ // slotWidth 5: every estimateInlineTextWidth > 5 -> ''.+ const p = buildStackedDiskBarPresentation(+ { disks: [makeDisk({ mountpoint: '/dev/a', total: 100, used: 100, free: 0, usage: 100 })] },+ 5,+ );+ expect(p.miniDisks[0].inlineText).toBe('');+ });+ });++ describe('getStackedDiskColor (via segments[].color, mode=stacked)', () => {+ it('maps to warning/critical severity colors and the palette by percent with default thresholds', () => {+ // Default thresholds (undefined -> ?? 90 / ?? 80).+ // 85 -> warning arm; 10 -> palette arm (index 1); 95 -> critical arm.+ const p = buildStackedDiskBarPresentation(+ {+ mode: 'stacked',+ disks: [+ makeDisk({ mountpoint: '/a', total: 100, used: 85, free: 15, usage: 85 }),+ makeDisk({ mountpoint: '/b', total: 100, used: 10, free: 90, usage: 10 }),+ makeDisk({ mountpoint: '/c', total: 100, used: 95, free: 5, usage: 95 }),+ ],+ },+ 400,+ );+ expect(p.segments.map((s) => s.color)).toEqual([WARNING, SEGMENT_COLORS[1], CRITICAL]);+ expect(p.segments.map((s) => s.diskUsagePercent)).toEqual([85, 10, 95]);+ expect(p.segments.map((s) => s.index)).toEqual([0, 1, 2]);+ // widthPercent = used / totalCapacity(300) * 100.+ expect(p.segments[0].widthPercent).toBeCloseTo(28.33, 1);+ expect(p.segments[2].widthPercent).toBeCloseTo(31.67, 1);+ });++ it('honors custom warning/critical thresholds', () => {+ // thresholds { warning: 60, critical: 70 } (no ?? defaults).+ // 65 -> warning (>=60, <70); 75 -> critical (>=70); 50 -> palette[2].+ const p = buildStackedDiskBarPresentation(+ {+ mode: 'stacked',+ thresholds: { warning: 60, critical: 70 },+ disks: [+ makeDisk({ mountpoint: '/a', total: 100, used: 65, free: 35, usage: 65 }),+ makeDisk({ mountpoint: '/b', total: 100, used: 75, free: 25, usage: 75 }),+ makeDisk({ mountpoint: '/c', total: 100, used: 50, free: 50, usage: 50 }),+ ],+ },+ 400,+ );+ expect(p.segments.map((s) => s.color)).toEqual([WARNING, CRITICAL, SEGMENT_COLORS[2]]);+ });++ it('falls back to default thresholds when thresholds is null and wraps the palette index past the end', () => {+ // thresholds null -> thresholds?.critical ?? 90 (nullish arm). All 5% (<80)+ // -> palette arm; index 6 wraps to SEGMENT_COLORS[0].+ const p = buildStackedDiskBarPresentation(+ {+ mode: 'stacked',+ thresholds: null,+ disks: Array.from({ length: 7 }, () =>+ makeDisk({ total: 100, used: 5, free: 95, usage: 5 }),+ ),+ },+ 400,+ );+ expect(p.segments.length).toBe(7);+ expect(p.segments[5].color).toBe(SEGMENT_COLORS[5]);+ expect(p.segments[6].color).toBe(SEGMENT_COLORS[0]);+ });+ });++ describe('buildStackedDiskBarPresentation', () => {+ it('renders an empty state when no disks and no aggregate disk are given', () => {+ // disks ?? [] arm (undefined); aggregateDisk absent; overallPercent final 0 arm.+ const p = buildStackedDiskBarPresentation({}, 400);+ expect(p.hasDisks).toBe(false);+ expect(p.hasMultipleDisks).toBe(false);+ expect(p.displayPercentValue).toBe(0);+ expect(p.barPercent).toBe(0);+ expect(p.displayLabel).toBe('0%');+ expect(p.segments).toEqual([]);+ expect(p.miniDisks).toEqual([]);+ expect(p.verticalBars).toEqual([]);+ expect(p.tooltipContent).toEqual([]);+ expect(p.tooltipTitle).toBe('Disk Usage');+ // No mode + no inline disk mode -> centered container class.+ expect(p.containerClass).toBe('metric-text w-full h-4 flex items-center justify-center');+ expect(p.anomalyClass).toBe('text-yellow-400');+ expect(p.anomalyRatio).toBe('');+ });++ it('renders a single disk without stacked segments', () => {+ // hasDisks true, hasMultipleDisks false; maxInfo from a single disk;+ // tooltip uses getStackedDiskColor palette (useUsageColors false).+ const p = buildStackedDiskBarPresentation(+ { disks: [makeDisk({ mountpoint: '/', total: 100, used: 25, free: 75, usage: 25 })] },+ 400,+ );+ expect(p.hasDisks).toBe(true);+ expect(p.hasMultipleDisks).toBe(false);+ expect(p.displayPercentValue).toBe(25);+ expect(p.barPercent).toBe(25);+ expect(p.displayLabel).toBe('25%');+ expect(p.displaySublabel).toBe('25.0 B/100 B');+ expect(p.maxLabelShort).toBe('max 25%');+ expect(p.maxLabelFull).toBe('Highest usage: / 25%');+ expect(p.useStackedSegments).toBe(false);+ expect(p.segments).toEqual([]);+ expect(p.miniDisks[0].shortLabel).toBe('/');+ expect(p.miniDisks[0].percent).toBe(25);+ expect(p.miniDisks[0].title).toBe('/: 25% (25.0 B/100 B)');+ expect(p.tooltipTitle).toBe('Disk Usage');+ expect(p.tooltipContent[0]).toStrictEqual({+ color: SEGMENT_COLORS[0],+ label: '/',+ percent: '25%',+ total: '100 B',+ used: '25.0 B',+ });+ });++ it('enables stacked segments and the disk-count flag in stacked mode with multiple disks', () => {+ // useStackedSegments = hasMultipleDisks && explicitStackedMode; totalCapacity > 0+ // -> segments built; showDiskCount = useStackedSegments || showDiskCount.+ const p = buildStackedDiskBarPresentation(+ {+ mode: 'stacked',+ disks: [+ makeDisk({ mountpoint: '/a', total: 100, used: 10, free: 90, usage: 10 }),+ makeDisk({ mountpoint: '/b', total: 100, used: 20, free: 80, usage: 20 }),+ ],+ },+ 400,+ );+ expect(p.useStackedSegments).toBe(true);+ expect(p.segments.length).toBe(2);+ expect(p.showDiskCount).toBe(true);+ expect(p.tooltipTitle).toBe('Disk Breakdown');+ // explicitStackedMode suppresses inlineDiskMode.+ expect(p.inlineDiskMode).toBe(false);+ });++ it('uses the total summary strategy in aggregate mode (overall percent, max label shown, usage-colored tooltip)', () => {+ // aggregateMode true; summaryStrategy defaults to 'total' -> useMaxSummary false;+ // displayPercentValue = overallPercent; barColor uses maxInfo.percent;+ // showMaxLabel true via the aggregate width check; tooltip useUsageColors true.+ const p = buildStackedDiskBarPresentation(+ {+ mode: 'aggregate',+ disks: [+ makeDisk({ mountpoint: '/a', total: 100, used: 80, free: 20, usage: 80 }),+ makeDisk({ mountpoint: '/b', total: 100, used: 20, free: 80, usage: 20 }),+ ],+ },+ 400,+ );+ expect(p.aggregateMode).toBe(true);+ expect(p.displayPercentValue).toBe(50); // 100 / 200 * 100+ expect(p.barPercent).toBe(50);+ expect(p.maxLabelShort).toBe('max 80%');+ expect(p.barColor).toBe(WARNING); // getMetricColorRgba(maxInfo.percent = 80)+ expect(p.showMaxLabel).toBe(true);+ expect(p.showSublabel).toBe(true);+ expect(p.tooltipContent.map((t) => t.color)).toEqual([WARNING, NORMAL]);+ });++ it('uses the max summary strategy in aggregate mode (display = max percent, sublabel suppressed)', () => {+ // useMaxSummary = aggregateMode && hasMultipleDisks && 'max' && maxInfo -> true;+ // displayPercentValue = maxInfo.percent; maxLabelShort = 'max'; displaySublabel = ''.+ const p = buildStackedDiskBarPresentation(+ {+ mode: 'aggregate',+ summaryStrategy: 'max',+ disks: [+ makeDisk({ mountpoint: '/a', total: 100, used: 30, free: 70, usage: 30 }),+ makeDisk({ mountpoint: '/b', total: 100, used: 90, free: 10, usage: 90 }),+ ],+ },+ 400,+ );+ expect(p.displayPercentValue).toBe(90);+ expect(p.barPercent).toBe(90);+ expect(p.maxLabelShort).toBe('max');+ expect(p.displaySublabel).toBe('');+ expect(p.showSublabel).toBe(false);+ expect(p.showMaxLabel).toBe(true);+ expect(p.barColor).toBe(CRITICAL); // getMetricColorRgba(90)+ });++ it('builds vertical bars clamped to 0..100 and the vertical-bars container class', () => {+ // verticalBarsMode = mode === 'vertical-bars' && hasDisks; fillPercent uses+ // Math.max(0, Math.min(percent, 100)) -> exercises both clamps.+ const p = buildStackedDiskBarPresentation(+ {+ mode: 'vertical-bars',+ disks: [+ makeDisk({ mountpoint: '/x', total: 100, used: 40, free: 60, usage: 40 }),+ makeDisk({ mountpoint: '/y', total: 100, used: 120, free: 0, usage: 120 }),+ makeDisk({ mountpoint: '/z', total: 100, used: -5, free: 105, usage: -5 }),+ ],+ },+ 400,+ );+ expect(p.verticalBarsMode).toBe(true);+ expect(p.containerClass).toBe('metric-text w-full h-4 min-w-0');+ expect(p.verticalBars.map((b) => b.fillPercent)).toEqual([40, 100, 0]);+ expect(p.verticalBars[0]).toStrictEqual({+ color: NORMAL,+ fillPercent: 40,+ title: '/x: 40% (40.0 B/100 B)',+ });+ expect(p.verticalBars[1].color).toBe(CRITICAL); // 120% -> critical+ });++ it('enables inline disk mode and its container class in mini mode', () => {+ // miniMode true -> inlineDiskMode true (miniMode && !aggregate && !stacked+ // && !verticalBars); containerClass = inline-disk arm.+ const p = buildStackedDiskBarPresentation(+ {+ mode: 'mini',+ disks: [makeDisk({ mountpoint: '/dev/nvme0', total: 100, used: 75, free: 25, usage: 75 })],+ },+ 400,+ );+ expect(p.miniMode).toBe(true);+ expect(p.inlineDiskMode).toBe(true);+ expect(p.containerClass).toBe('metric-text w-full h-4 min-w-0');+ expect(p.miniDisks[0].shortLabel).toBe('nvme0');+ });++ it('derives capacity and a Total tooltip from aggregateDisk when no disks array is given', () => {+ // hasDisks false -> totalCapacity/totalUsed from aggregateDisk;+ // tooltip aggregateDisk arm (total > 0) -> single Total item.+ const p = buildStackedDiskBarPresentation(+ { aggregateDisk: makeDisk({ total: 200, used: 50, free: 150, usage: 25 }) },+ 400,+ );+ expect(p.hasDisks).toBe(false);+ expect(p.displayPercentValue).toBe(25);+ expect(p.displaySublabel).toBe('50.0 B/200 B');+ expect(p.tooltipContent).toStrictEqual([+ {+ color: NORMAL,+ label: 'Total',+ percent: '25%',+ total: '200 B',+ used: '50.0 B',+ },+ ]);+ });++ it('falls back to getDiskUsagePercent(aggregateDisk) for overall percent when aggregate total is 0', () => {+ // totalCapacity 0 -> overallPercent = aggregateDisk ? getDiskUsagePercent(...) : 0.+ // getDiskUsagePercent: total <= 0, usage 75 (>1) -> 75. Tooltip total>0 arm+ // skipped (total 0) -> empty.+ const p = buildStackedDiskBarPresentation(+ { aggregateDisk: makeDisk({ total: 0, used: 0, free: 0, usage: 75 }) },+ 400,+ );+ expect(p.displayPercentValue).toBe(75);+ expect(p.barPercent).toBe(75);+ expect(p.displaySublabel).toBe('0 B/0 B');+ expect(p.tooltipContent).toEqual([]);+ });++ it('maps anomaly severity to a class and formats each anomaly-ratio tier', () => {+ // ratio >= 2 -> `${ratio}x`; 1.5..2 -> '↑↑'; 1..1.5 -> '↑'; baseline 0 -> ''.+ const high = buildStackedDiskBarPresentation(+ { anomaly: makeAnomaly({ severity: 'high', baseline_mean: 10, current_value: 25 }) },+ 400,+ );+ expect(high.anomalyClass).toBe('text-orange-400');+ expect(high.anomalyRatio).toBe('2.5x');+ expect(high.anomalyDescription).toBe('Disk usage spike');++ const critical = buildStackedDiskBarPresentation(+ { anomaly: makeAnomaly({ severity: 'critical', baseline_mean: 10, current_value: 17 }) },+ 400,+ );+ expect(critical.anomalyClass).toBe('text-red-400');+ expect(critical.anomalyRatio).toBe('↑↑');++ const lowTier = buildStackedDiskBarPresentation(+ { anomaly: makeAnomaly({ severity: 'low', baseline_mean: 10, current_value: 13 }) },+ 400,+ );+ expect(lowTier.anomalyClass).toBe('text-blue-400');+ expect(lowTier.anomalyRatio).toBe('↑');++ // Unknown severity -> ANOMALY_SEVERITY_CLASS[sev] ?? 'text-yellow-400';+ // baseline_mean 0 -> formatAnomalyRatio null -> ?? ''.+ const unknown = buildStackedDiskBarPresentation(+ { anomaly: makeAnomaly({ severity: 'weird', baseline_mean: 0, current_value: 0 }) },+ 400,+ );+ expect(unknown.anomalyClass).toBe('text-yellow-400');+ expect(unknown.anomalyRatio).toBe('');+ });++ it('suppresses the sublabel when containerWidth is too narrow to fit it', () => {+ // displaySublabel non-empty but containerWidth < estimateTextWidth(...) ->+ // showSublabel false (the width-failing arm of the && ).+ const p = buildStackedDiskBarPresentation(+ { disks: [makeDisk({ mountpoint: '/', total: 100, used: 25, free: 75, usage: 25 })] },+ 5,+ );+ expect(p.showSublabel).toBe(false);+ expect(p.displaySublabel).toBe('25.0 B/100 B');+ });+ });+});diff --git a/frontend-modern/src/features/storageBackups/__tests__/storageCapacityDeltaPresentation.branchcov0712b.test.ts b/frontend-modern/src/features/storageBackups/__tests__/storageCapacityDeltaPresentation.branchcov0712b.test.tsnew file mode 100644index 0000000000..d45dc23bd8--- /dev/null+++ b/frontend-modern/src/features/storageBackups/__tests__/storageCapacityDeltaPresentation.branchcov0712b.test.ts@@ -0,0 +1,249 @@+import { describe, expect, it } from 'vitest';+import type { MetricPoint } from '@/api/charts';+import { computeStorageCapacityDeltaAnalysis } from '@/features/storageBackups/storageCapacityDeltaPresentation';++// Branch-coverage extension for `storageCapacityDeltaPresentation`.+//+// `averageMetricValues` and `averageMetricTimestamps` are module-private (not+// exported), so they can only be driven transitively through the public+// `computeStorageCapacityDeltaAnalysis`. Every happy-path test below exercises+// their non-empty (reduce + divide) arm. Their `length === 0 -> 0` early-return+// arm is unreachable from the public API (the start/end windows are always+// non-empty once `normalized.length >= 2`) and is called out in GLM_REPORT.md.+//+// `computeStorageCapacityDeltaAnalysis` owns the meaningful branches: the+// `< 2 -> null` guard, the `sampleWindowSize` ternary, the+// `!isFinite(delta) || !isFinite(durationMs) || durationMs <= 0 -> null` guard,+// and the `Math.abs(delta) < 1 ? 0 : delta` clamp.++const point = (timestamp: number, value: number): MetricPoint => ({ timestamp, value });++// ---------------------------------------------------------------------------+// computeStorageCapacityDeltaAnalysis: normalized.length < 2 -> null+// ---------------------------------------------------------------------------++describe('computeStorageCapacityDeltaAnalysis branch coverage — < 2 points guard', () => {+ it('returns null for an empty series', () => {+ expect(computeStorageCapacityDeltaAnalysis([])).toBeNull();+ });++ it('returns null for a single point', () => {+ expect(computeStorageCapacityDeltaAnalysis([point(1_000, 100)])).toBeNull();+ });++ it('returns null when every point is dropped by the finite filter (NaN timestamp/value)', () => {+ const malformed = [+ { timestamp: NaN, value: 100 },+ { timestamp: 1_000, value: NaN },+ { timestamp: Infinity, value: 50 },+ ] as unknown as MetricPoint[];+ // All three are non-finite in at least one axis -> normalized is empty.+ expect(computeStorageCapacityDeltaAnalysis(malformed)).toBeNull();+ });++ it('returns null when only one point survives the finite filter', () => {+ const mixed = [+ { timestamp: NaN, value: 100 },+ { timestamp: 1_000, value: 100 },+ ] as unknown as MetricPoint[];+ expect(computeStorageCapacityDeltaAnalysis(mixed)).toBeNull();+ });+});++// ---------------------------------------------------------------------------+// sampleWindowSize ternary: length < 4 ? 1 : max(2, floor(length * 0.25))+// ---------------------------------------------------------------------------++describe('computeStorageCapacityDeltaAnalysis branch coverage — sampleWindowSize ternary', () => {+ it('uses a window of 1 for exactly two points (no averaging across the window)', () => {+ expect(computeStorageCapacityDeltaAnalysis([point(1_000, 100), point(2_000, 150)])).toEqual({+ deltaBytes: 50,+ durationMs: 1_000,+ startTimestamp: 1_000,+ endTimestamp: 2_000,+ });+ });++ it('uses a window of 1 for three points (start vs end point only)', () => {+ expect(+ computeStorageCapacityDeltaAnalysis([+ point(1_000, 100),+ point(2_000, 200),+ point(3_000, 300),+ ]),+ ).toEqual({+ deltaBytes: 200,+ durationMs: 2_000,+ startTimestamp: 1_000,+ endTimestamp: 3_000,+ });+ });++ it('uses a window of max(2, floor(4*0.25)=1) -> 2 for four points (averages both ends)', () => {+ expect(+ computeStorageCapacityDeltaAnalysis([+ point(1_000, 100),+ point(2_000, 120),+ point(3_000, 180),+ point(4_000, 200),+ ]),+ ).toEqual({+ deltaBytes: 80, // (180+200)/2 - (100+120)/2 = 190 - 110+ durationMs: 2_000, // (3000+4000)/2 - (1000+2000)/2 = 3500 - 1500+ startTimestamp: 1_500,+ endTimestamp: 3_500,+ });+ });++ it('uses a window of max(2, floor(12*0.25)=3) -> 3 for twelve points', () => {+ const points: MetricPoint[] = [+ point(0, 100),+ point(1_000, 100),+ point(2_000, 100),+ // middle six points are outside both windows; values are irrelevant+ point(3_000, 0),+ point(4_000, 0),+ point(5_000, 0),+ point(6_000, 0),+ point(7_000, 0),+ point(8_000, 0),+ point(9_000, 400),+ point(10_000, 400),+ point(11_000, 400),+ ];+ expect(computeStorageCapacityDeltaAnalysis(points)).toEqual({+ deltaBytes: 300, // avg(last 3)=400 - avg(first 3)=100+ durationMs: 9_000, // avg(last 3 ts)=10000 - avg(first 3 ts)=1000+ startTimestamp: 1_000, // (0+1000+2000)/3+ endTimestamp: 10_000, // (9000+10000+11000)/3+ });+ });++ it('sorts an out-of-order series by timestamp before selecting the windows', () => {+ expect(+ computeStorageCapacityDeltaAnalysis([+ point(4_000, 200),+ point(1_000, 100),+ point(3_000, 180),+ point(2_000, 120),+ ]),+ ).toEqual({+ deltaBytes: 80,+ durationMs: 2_000,+ startTimestamp: 1_500,+ endTimestamp: 3_500,+ });+ });+});++// ---------------------------------------------------------------------------+// delta sign + Math.abs(delta) < 1 ? 0 : delta clamp+// ---------------------------------------------------------------------------++describe('computeStorageCapacityDeltaAnalysis branch coverage — delta sign and clamp', () => {+ it('preserves a negative delta (used capacity shrank)', () => {+ expect(computeStorageCapacityDeltaAnalysis([point(1_000, 200), point(2_000, 100)])).toEqual({+ deltaBytes: -100,+ durationMs: 1_000,+ startTimestamp: 1_000,+ endTimestamp: 2_000,+ });+ });++ it('clamps a sub-byte positive delta (abs < 1) to exactly 0', () => {+ expect(+ computeStorageCapacityDeltaAnalysis([point(1_000, 100.0), point(2_000, 100.4)]),+ ).toEqual({+ deltaBytes: 0, // raw delta 0.4 -> clamped+ durationMs: 1_000,+ startTimestamp: 1_000,+ endTimestamp: 2_000,+ });+ });++ it('clamps a sub-byte negative delta (abs < 1) to exactly 0', () => {+ expect(+ computeStorageCapacityDeltaAnalysis([point(1_000, 100.0), point(2_000, 99.6)]),+ ).toEqual({+ deltaBytes: 0, // raw delta -0.4 -> abs < 1 -> clamped+ durationMs: 1_000,+ startTimestamp: 1_000,+ endTimestamp: 2_000,+ });+ });+});++// ---------------------------------------------------------------------------+// !isFinite(delta) || !isFinite(durationMs) || durationMs <= 0 -> null+// ---------------------------------------------------------------------------++describe('computeStorageCapacityDeltaAnalysis branch coverage — finite/duration guard', () => {+ it('returns null when start and end timestamps are equal (durationMs === 0, <= 0 arm)', () => {+ expect(+ computeStorageCapacityDeltaAnalysis([point(1_000, 100), point(1_000, 200)]),+ ).toBeNull();+ });++ it('returns null when end timestamp precedes start after sorting only equal timestamps collapse (durationMs 0)', () => {+ // Three identical timestamps -> startTimestamp === endTimestamp -> durationMs 0.+ expect(+ computeStorageCapacityDeltaAnalysis([+ point(5_000, 100),+ point(5_000, 150),+ point(5_000, 200),+ ]),+ ).toBeNull();+ });++ it('returns null when the value averages overflow to Infinity (delta becomes NaN) via MAX_VALUE sums', () => {+ // Number.MAX_VALUE is finite and passes the normalizer's filter, but+ // MAX_VALUE + MAX_VALUE = Infinity -> Infinity / 2 = Infinity for both+ // windows -> delta = Infinity - Infinity = NaN -> !isFinite(delta) arm.+ const points: MetricPoint[] = [+ point(1_000, Number.MAX_VALUE),+ point(2_000, Number.MAX_VALUE),+ point(3_000, Number.MAX_VALUE),+ point(4_000, Number.MAX_VALUE),+ ];+ expect(computeStorageCapacityDeltaAnalysis(points)).toBeNull();+ });++ it('returns null when the timestamp averages overflow to Infinity (durationMs becomes NaN)', () => {+ // Finite values keep delta finite, but MAX_VALUE timestamps overflow the+ // timestamp averages -> durationMs = Infinity - Infinity = NaN ->+ // !isFinite(durationMs) arm (distinct from the delta arm above).+ const points: MetricPoint[] = [+ point(Number.MAX_VALUE, 100),+ point(Number.MAX_VALUE, 120),+ point(Number.MAX_VALUE, 180),+ point(Number.MAX_VALUE, 200),+ ];+ expect(computeStorageCapacityDeltaAnalysis(points)).toBeNull();+ });+});++// ---------------------------------------------------------------------------+// averageMetricValues / averageMetricTimestamps (private) — transitive coverage+// ---------------------------------------------------------------------------++describe('averageMetricValues / averageMetricTimestamps (transitive, private helpers)', () => {+ it('averages the window values and timestamps (non-empty reduce arm) for a 4-point series', () => {+ // Exercises both helpers' `points.length > 0 -> reduce/divide` arm: the+ // emitted startTimestamp/endTimestamp are the arithmetic means of the+ // first/last windows, proving the timestamp averaging ran, and deltaBytes+ // is the difference of the value averages, proving the value averaging ran.+ expect(+ computeStorageCapacityDeltaAnalysis([+ point(1_000, 100),+ point(2_000, 120),+ point(3_000, 180),+ point(4_000, 200),+ ]),+ ).toEqual({+ deltaBytes: 80,+ durationMs: 2_000,+ startTimestamp: 1_500,+ endTimestamp: 3_500,+ });+ });+});diff --git a/frontend-modern/src/routing/__tests__/resourceLinks.branchcov0712b.test.ts b/frontend-modern/src/routing/__tests__/resourceLinks.branchcov0712b.test.tsnew file mode 100644index 0000000000..6a6bd7e066--- /dev/null+++ b/frontend-modern/src/routing/__tests__/resourceLinks.branchcov0712b.test.ts@@ -0,0 +1,379 @@+import { describe, expect, it } from 'vitest';+import {+ buildKubernetesPath,+ buildRecoveryRouteSearch,+ buildStorageRouteSearch,+ buildTrueNASPath,+ buildVmwarePath,+ buildWorkloadsRouteSearch,+ KUBERNETES_PATH,+ RECOVERY_QUERY_PARAMS,+ STORAGE_QUERY_PARAMS,+ TRUENAS_PATH,+ VMWARE_PATH,+ WORKLOADS_QUERY_PARAMS,+} from '@/routing/resourceLinks';++// Branch-coverage companion to resourceLinks.test.ts. Each block below+// targets branches in the named builders that the sibling suite does not+// yet exercise: per-field `if (x) params.set(...)` arms for option keys+// the sibling suite omits, the empty-options/falsy-normalized arms of the+// tab path builders, canonicalization switch arms reached through the+// build* entry points, and the default-parameter arm triggered by an+// explicit `undefined` argument.++describe('buildWorkloadsRouteSearch branch coverage', () => {+ it('returns an empty string when no options are supplied (empty URLSearchParams arm)', () => {+ expect(buildWorkloadsRouteSearch()).toBe('');+ expect(buildWorkloadsRouteSearch({})).toBe('');+ });++ it('emits the runtime, namespace, cluster, and summaryGroup params the sibling suite omits', () => {+ expect(+ buildWorkloadsRouteSearch({+ runtime: 'containerd',+ namespace: 'kube-system',+ cluster: 'prod-us-east',+ summaryGroup: 'compute',+ }),+ ).toBe(+ '?runtime=containerd&namespace=kube-system&cluster=prod-us-east&summaryGroup=compute',+ );+ });++ it('verifies the omitted query-param keys map to the canonical names', () => {+ expect(WORKLOADS_QUERY_PARAMS.runtime).toBe('runtime');+ expect(WORKLOADS_QUERY_PARAMS.namespace).toBe('namespace');+ expect(WORKLOADS_QUERY_PARAMS.cluster).toBe('cluster');+ expect(WORKLOADS_QUERY_PARAMS.summaryGroup).toBe('summaryGroup');+ });++ it('canonicalizes the "host" type alias to "agent" via canonicalizeWorkloadFilterType', () => {+ expect(buildWorkloadsRouteSearch({ type: 'host' })).toBe('?type=agent');+ });++ it('passes an unknown type through unchanged (canonicalize returns undefined fallback arm)', () => {+ expect(buildWorkloadsRouteSearch({ type: 'storage' })).toBe('?type=storage');+ });++ it('canonicalizes platform="all" to the "all" sentinel via normalizeSourcePlatformQueryValue', () => {+ expect(buildWorkloadsRouteSearch({ platform: 'all' })).toBe('?platform=all');+ });++ it('trims whitespace around every supported field before serializing', () => {+ expect(+ buildWorkloadsRouteSearch({+ type: ' pod ',+ platform: ' kubernetes ',+ runtime: ' cri-o ',+ context: ' ctx-1 ',+ namespace: ' ns-1 ',+ cluster: ' cl-1 ',+ agent: ' ag-1 ',+ resource: ' res-1 ',+ summaryGroup: ' sg-1 ',+ }),+ ).toBe(+ '?type=pod&platform=kubernetes&runtime=cri-o&context=ctx-1&namespace=ns-1&cluster=cl-1&agent=ag-1&resource=res-1&summaryGroup=sg-1',+ );+ });++ it('drops fields whose normalized value is empty (each per-field falsy arm)', () => {+ expect(+ buildWorkloadsRouteSearch({+ type: ' ',+ platform: '',+ runtime: null,+ context: undefined,+ namespace: ' ',+ cluster: '',+ agent: null,+ resource: undefined,+ summaryGroup: ' ',+ }),+ ).toBe('');+ });+});++describe('buildKubernetesPath branch coverage', () => {+ it('falls back to the default tab when called with an explicit undefined argument', () => {+ expect(+ buildKubernetesPath(undefined as unknown as Parameters<typeof buildKubernetesPath>[0]),+ ).toBe(`${KUBERNETES_PATH}/overview`);+ });++ it('returns the base path when the tab is empty (falsy normalized arm)', () => {+ expect(buildKubernetesPath('')).toBe(KUBERNETES_PATH);+ });++ it('returns the base path when the tab is whitespace-only (trim collapses to empty)', () => {+ expect(buildKubernetesPath(' ')).toBe(KUBERNETES_PATH);+ expect(buildKubernetesPath('\t\n')).toBe(KUBERNETES_PATH);+ });++ it('strips leading and trailing slashes but preserves inner path segments', () => {+ expect(buildKubernetesPath('/workloads/')).toBe(`${KUBERNETES_PATH}/workloads`);+ expect(buildKubernetesPath('///workloads///')).toBe(`${KUBERNETES_PATH}/workloads`);+ expect(buildKubernetesPath('/config/networking/')).toBe(+ `${KUBERNETES_PATH}/config/networking`,+ );+ });++ it('trims surrounding whitespace before slash-stripping', () => {+ expect(buildKubernetesPath(' workloads ')).toBe(`${KUBERNETES_PATH}/workloads`);+ expect(buildKubernetesPath(' /workloads/ ')).toBe(`${KUBERNETES_PATH}/workloads`);+ });+});++describe('buildTrueNASPath branch coverage', () => {+ it('falls back to the default tab when called with an explicit undefined argument', () => {+ expect(+ buildTrueNASPath(undefined as unknown as Parameters<typeof buildTrueNASPath>[0]),+ ).toBe(`${TRUENAS_PATH}/overview`);+ });++ it('returns the base path when the tab is empty or whitespace-only', () => {+ expect(buildTrueNASPath('')).toBe(TRUENAS_PATH);+ expect(buildTrueNASPath(' ')).toBe(TRUENAS_PATH);+ expect(buildTrueNASPath('\t')).toBe(TRUENAS_PATH);+ });++ it('strips surrounding slashes and whitespace while preserving inner segments', () => {+ expect(buildTrueNASPath('/storage/')).toBe(`${TRUENAS_PATH}/storage`);+ expect(buildTrueNASPath('///datasets///')).toBe(`${TRUENAS_PATH}/datasets`);+ expect(buildTrueNASPath(' /sharing/smb/ ')).toBe(`${TRUENAS_PATH}/sharing/smb`);+ });+});++describe('buildVmwarePath branch coverage', () => {+ it('falls back to the default tab when called with an explicit undefined argument', () => {+ expect(buildVmwarePath(undefined as unknown as Parameters<typeof buildVmwarePath>[0])).toBe(+ `${VMWARE_PATH}/overview`,+ );+ });++ it('returns the base path when the tab is empty or whitespace-only', () => {+ expect(buildVmwarePath('')).toBe(VMWARE_PATH);+ expect(buildVmwarePath(' ')).toBe(VMWARE_PATH);+ });++ it('strips surrounding slashes and whitespace while preserving inner segments', () => {+ expect(buildVmwarePath('/storage/')).toBe(`${VMWARE_PATH}/storage`);+ expect(buildVmwarePath('///hosts/clusters///')).toBe(`${VMWARE_PATH}/hosts/clusters`);+ expect(buildVmwarePath(' /networking/ ')).toBe(`${VMWARE_PATH}/networking`);+ });+});++describe('buildStorageRouteSearch branch coverage', () => {+ it('returns an empty string when no options are supplied', () => {+ expect(buildStorageRouteSearch()).toBe('');+ expect(buildStorageRouteSearch({})).toBe('');+ });++ it('emits the summaryGroup param the sibling suite omits', () => {+ expect(buildStorageRouteSearch({ summaryGroup: 'capacity' })).toBe(+ `?${STORAGE_QUERY_PARAMS.summaryGroup}=capacity`,+ );+ expect(STORAGE_QUERY_PARAMS.summaryGroup).toBe('summaryGroup');+ });++ it('canonicalizes raw ceph-family storage types through normalizeStorageSourceKey switch arms', () => {+ expect(buildStorageRouteSearch({ source: 'ceph' })).toBe('?source=ceph');+ expect(buildStorageRouteSearch({ source: 'cephfs' })).toBe('?source=ceph');+ expect(buildStorageRouteSearch({ source: 'rbd' })).toBe('?source=ceph');+ });++ it('maps the "all" storage source sentinel through the switch arm', () => {+ expect(buildStorageRouteSearch({ source: 'all' })).toBe('?source=all');+ });++ it('slugifies storage source input (lowercase, non-alnum collapsed to hyphens)', () => {+ expect(buildStorageRouteSearch({ source: ' Proxmox PBS ' })).toBe('?source=proxmox-pbs');+ expect(buildStorageRouteSearch({ source: 'CephFS!!' })).toBe('?source=ceph');+ });++ it('drops fields whose normalized value is empty (per-field falsy arms)', () => {+ expect(+ buildStorageRouteSearch({+ tab: ' ',+ group: '',+ source: null,+ status: undefined,+ diskRole: ' ',+ diskGroup: '',+ node: null,+ query: undefined,+ resource: ' ',+ sort: '',+ order: null,+ summaryGroup: undefined,+ }),+ ).toBe('');+ });++ it('serializes every supported option in canonical insertion order', () => {+ expect(+ buildStorageRouteSearch({+ tab: 'disks',+ group: 'storage',+ source: 'ceph',+ status: 'available',+ diskRole: 'nvme',+ diskGroup: 'data',+ node: 'pve1',+ query: 'lvm',+ resource: 'r-1',+ sort: 'usage',+ order: 'desc',+ summaryGroup: 'capacity',+ }),+ ).toBe(+ '?tab=disks&group=storage&source=ceph&status=available&diskRole=nvme&diskGroup=data&node=pve1&q=lvm&resource=r-1&sort=usage&order=desc&summaryGroup=capacity',+ );+ });+});++describe('buildRecoveryRouteSearch branch coverage', () => {+ it('returns an empty string when no options are supplied', () => {+ expect(buildRecoveryRouteSearch()).toBe('');+ expect(buildRecoveryRouteSearch({})).toBe('');+ });++ it('emits the rollupId param the sibling suite omits', () => {+ expect(buildRecoveryRouteSearch({ rollupId: 'rollup-42' })).toBe(+ `?${RECOVERY_QUERY_PARAMS.rollupId}=rollup-42`,+ );+ expect(RECOVERY_QUERY_PARAMS.rollupId).toBe('rollupId');+ });++ it('treats the affirmative stale synonyms "yes" and "on" as the "1" flag', () => {+ expect(buildRecoveryRouteSearch({ stale: 'yes', platform: 'proxmox-pve' })).toBe(+ '?platform=proxmox-pve&stale=1',+ );+ expect(buildRecoveryRouteSearch({ stale: 'on', platform: 'proxmox-pve' })).toBe(+ '?platform=proxmox-pve&stale=1',+ );+ });++ it('drops the stale flag entirely for non-affirmative values (falsey boolean arm + falsy if-arm)', () => {+ expect(buildRecoveryRouteSearch({ stale: 'no', platform: 'proxmox-pve' })).toBe(+ '?platform=proxmox-pve',+ );+ expect(buildRecoveryRouteSearch({ stale: 'off', platform: 'proxmox-pve' })).toBe(+ '?platform=proxmox-pve',+ );+ expect(buildRecoveryRouteSearch({ stale: '0', platform: 'proxmox-pve' })).toBe(+ '?platform=proxmox-pve',+ );+ expect(buildRecoveryRouteSearch({ stale: 'false', platform: 'proxmox-pve' })).toBe(+ '?platform=proxmox-pve',+ );+ });++ it('canonicalizes system-container item-type aliases through the switch arms', () => {+ expect(buildRecoveryRouteSearch({ itemType: 'lxc' })).toBe('?itemType=system-container');+ expect(buildRecoveryRouteSearch({ itemType: 'ct' })).toBe('?itemType=system-container');+ expect(buildRecoveryRouteSearch({ itemType: 'container' })).toBe(+ '?itemType=system-container',+ );+ expect(buildRecoveryRouteSearch({ itemType: 'oci-container' })).toBe(+ '?itemType=system-container',+ );+ });++ it('canonicalizes the app-container item-type aliases through the switch arms', () => {+ expect(buildRecoveryRouteSearch({ itemType: 'docker' })).toBe('?itemType=app-container');+ expect(buildRecoveryRouteSearch({ itemType: 'docker-container' })).toBe(+ '?itemType=app-container',+ );+ expect(buildRecoveryRouteSearch({ itemType: 'app-container' })).toBe(+ '?itemType=app-container',+ );+ });++ it('canonicalizes the remaining item-type switch arms (pod, pvc, cluster, dataset, velero, guest)', () => {+ expect(buildRecoveryRouteSearch({ itemType: 'k8s-pod' })).toBe('?itemType=pod');+ expect(buildRecoveryRouteSearch({ itemType: 'pvc' })).toBe('?itemType=pvc');+ expect(buildRecoveryRouteSearch({ itemType: 'kubernetes-cluster' })).toBe(+ '?itemType=cluster',+ );+ expect(buildRecoveryRouteSearch({ itemType: 'truenas-dataset' })).toBe(+ '?itemType=dataset',+ );+ expect(buildRecoveryRouteSearch({ itemType: 'velero-backup' })).toBe(+ '?itemType=velero-backup',+ );+ expect(buildRecoveryRouteSearch({ itemType: 'proxmox-guest' })).toBe('?itemType=guest');+ });++ it('strips the proxmox-/truenas-/k8s- prefixes via the default-arm branches', () => {+ expect(buildRecoveryRouteSearch({ itemType: 'proxmox-storage' })).toBe(+ '?itemType=storage',+ );+ expect(buildRecoveryRouteSearch({ itemType: 'truenas-share' })).toBe('?itemType=share');+ expect(buildRecoveryRouteSearch({ itemType: 'k8s-node' })).toBe('?itemType=node');+ });++ it('maps itemType="all" to an empty value so the param is dropped', () => {+ expect(buildRecoveryRouteSearch({ itemType: 'all', platform: 'proxmox-pve' })).toBe(+ '?platform=proxmox-pve',+ );+ expect(buildRecoveryRouteSearch({ itemType: '', platform: 'proxmox-pve' })).toBe(+ '?platform=proxmox-pve',+ );+ });++ it('passes an unrecognized itemType through the default arm unchanged', () => {+ expect(buildRecoveryRouteSearch({ itemType: 'machine-learning-job' })).toBe(+ '?itemType=machine-learning-job',+ );+ });++ it('serializes every supported option in canonical insertion order, including rollupId', () => {+ expect(+ buildRecoveryRouteSearch({+ rollupId: 'r-1',+ view: 'events',+ platform: 'proxmox-pve',+ state: 'stale',+ stale: '1',+ range: '7',+ cluster: 'c1',+ day: '2026-02-13',+ namespace: 'ns1',+ mode: 'remote',+ itemType: 'vm',+ scope: 'workload',+ status: 'failed',+ verification: 'verified',+ node: 'n1',+ query: 'q1',+ }),+ ).toBe(+ '?rollupId=r-1&view=events&platform=proxmox-pve&state=stale&stale=1&range=7&cluster=c1&day=2026-02-13&namespace=ns1&mode=remote&itemType=vm&scope=workload&status=failed&verification=verified&node=n1&q=q1',+ );+ });++ it('drops fields whose normalized value is empty (per-field falsy arms across every option)', () => {+ expect(+ buildRecoveryRouteSearch({+ rollupId: ' ',+ view: '',+ platform: null,+ state: undefined,+ stale: 'no',+ range: ' ',+ cluster: '',+ day: null,+ namespace: undefined,+ mode: ' ',+ itemType: 'all',+ scope: '',+ status: null,+ verification: undefined,+ node: ' ',+ query: '',+ }),+ ).toBe('');+ });+});diff --git a/frontend-modern/src/utils/__tests__/alertIncidentPresentation.branchcov0712b.test.ts b/frontend-modern/src/utils/__tests__/alertIncidentPresentation.branchcov0712b.test.tsnew file mode 100644index 0000000000..ff38e14e95--- /dev/null+++ b/frontend-modern/src/utils/__tests__/alertIncidentPresentation.branchcov0712b.test.ts@@ -0,0 +1,141 @@+import { describe, expect, it } from 'vitest';+import {+ ALERT_RESOURCE_INCIDENT_LOAD_FAILURE,+ ALERT_RESOURCE_INCIDENT_NOTE_SAVE_FAILURE,+ ALERT_RESOURCE_INCIDENT_VIEW_TITLE,+ getAlertHistoryStatusPresentation,+ getAlertResourceIncidentLoadFailure,+ getAlertResourceIncidentNoteSaveFailure,+ getAlertResourceIncidentTruncatedEventsLabel,+ getAlertResourceIncidentViewTitle,+} from '@/utils/alertIncidentPresentation';++// Branch-coverage companion to alertIncidentPresentation.test.ts. The sibling+// suite already exercises the canonical 'active'/'acknowledged'/'resolved'+// strings and three shapes of getAlertResourceIncidentTruncatedEventsLabel;+// these tests drive the remaining branches: null/undefined/whitespace+// normalization, case-insensitive matching, the `||` fallback in the default+// arm, the singular `event` pluralization branch, strict-less/zero boundaries,+// a non-number totalCount (null), and the three previously-uncovered+// constant-returning accessors.++describe('getAlertHistoryStatusPresentation — branch coverage', () => {+ it('matches the "active" arm case-insensitively after trim/lowercase', () => {+ expect(getAlertHistoryStatusPresentation(' ACTIVE ')).toStrictEqual({+ label: 'active',+ className:+ 'text-xs px-2 py-0.5 rounded bg-red-100 dark:bg-red-900 text-red-700 dark:text-red-300 font-medium',+ rowClassName: 'bg-red-50 dark:bg-red-900',+ });+ });++ it('matches the "acknowledged" arm case-insensitively (capitalized input)', () => {+ expect(getAlertHistoryStatusPresentation('Acknowledged')).toStrictEqual({+ label: 'acknowledged',+ className:+ 'text-xs px-2 py-0.5 rounded bg-yellow-100 dark:bg-yellow-900 text-yellow-700 dark:text-yellow-300',+ rowClassName: '',+ });+ });++ it('hits the default arm with a truthy normalized value (|| left operand)', () => {+ // 'pending' is unrecognized but non-empty, so `normalized || 'resolved'`+ // keeps the left operand verbatim.+ expect(getAlertHistoryStatusPresentation('pending')).toStrictEqual({+ label: 'pending',+ className: 'text-xs px-2 py-0.5 rounded bg-surface-hover text-base-content',+ rowClassName: '',+ });+ });++ it('lowercases an unrecognized status used as the label', () => {+ expect(getAlertHistoryStatusPresentation('PENDING')).toStrictEqual({+ label: 'pending',+ className: 'text-xs px-2 py-0.5 rounded bg-surface-hover text-base-content',+ rowClassName: '',+ });+ });++ it('falls back to "resolved" when status is null (?? right operand)', () => {+ expect(getAlertHistoryStatusPresentation(null)).toStrictEqual({+ label: 'resolved',+ className: 'text-xs px-2 py-0.5 rounded bg-surface-hover text-base-content',+ rowClassName: '',+ });+ });++ it('falls back to "resolved" when status is undefined (?? right operand)', () => {+ expect(getAlertHistoryStatusPresentation(undefined)).toStrictEqual({+ label: 'resolved',+ className: 'text-xs px-2 py-0.5 rounded bg-surface-hover text-base-content',+ rowClassName: '',+ });+ });++ it('falls back to "resolved" for a whitespace-only status (|| right operand)', () => {+ expect(getAlertHistoryStatusPresentation(' ')).toStrictEqual({+ label: 'resolved',+ className: 'text-xs px-2 py-0.5 rounded bg-surface-hover text-base-content',+ rowClassName: '',+ });+ });++ it('falls back to "resolved" for an empty-string status (?? passes "" through, || right operand)', () => {+ expect(getAlertHistoryStatusPresentation('')).toStrictEqual({+ label: 'resolved',+ className: 'text-xs px-2 py-0.5 rounded bg-surface-hover text-base-content',+ rowClassName: '',+ });+ });+});++describe('getAlertResourceIncidentTruncatedEventsLabel — branch coverage', () => {+ it('uses the singular "event" form when totalCount === 1 (ternary "" arm)', () => {+ expect(getAlertResourceIncidentTruncatedEventsLabel(1, 1)).toBe('Showing 1 event');+ });++ it('returns "Showing <totalCount> events" when totalCount is strictly less than count', () => {+ expect(getAlertResourceIncidentTruncatedEventsLabel(10, 3)).toBe('Showing 3 events');+ });++ it('uses the plural "events" form when totalCount === 0 (ternary "s" arm)', () => {+ expect(getAlertResourceIncidentTruncatedEventsLabel(10, 0)).toBe('Showing 0 events');+ });++ it('falls back to the count-only form when totalCount is null (typeof !== "number")', () => {+ expect(+ getAlertResourceIncidentTruncatedEventsLabel(6, null as unknown as number | undefined),+ ).toBe('Showing last 6 events');+ });++ it('falls back to the count-only form when totalCount is explicitly undefined', () => {+ expect(getAlertResourceIncidentTruncatedEventsLabel(6, undefined)).toBe(+ 'Showing last 6 events',+ );+ });++ it('renders the "last <count> of <total>" form when totalCount exceeds count', () => {+ expect(getAlertResourceIncidentTruncatedEventsLabel(6, 9)).toBe('Showing last 6 of 9 events');+ });+});++describe('getAlertResourceIncidentLoadFailure — branch coverage', () => {+ it('returns the canonical load-failure string and matches the exported constant', () => {+ expect(getAlertResourceIncidentLoadFailure()).toBe('Failed to load resource incidents');+ expect(getAlertResourceIncidentLoadFailure()).toBe(ALERT_RESOURCE_INCIDENT_LOAD_FAILURE);+ });+});++describe('getAlertResourceIncidentNoteSaveFailure — branch coverage', () => {+ it('returns the canonical note-save-failure string and matches the exported constant', () => {+ expect(getAlertResourceIncidentNoteSaveFailure()).toBe('Failed to save incident note');+ expect(getAlertResourceIncidentNoteSaveFailure()).toBe(ALERT_RESOURCE_INCIDENT_NOTE_SAVE_FAILURE);+ });+});++describe('getAlertResourceIncidentViewTitle — branch coverage', () => {+ it('returns the canonical view-title string and matches the exported constant', () => {+ expect(getAlertResourceIncidentViewTitle()).toBe('View incidents for this resource');+ expect(getAlertResourceIncidentViewTitle()).toBe(ALERT_RESOURCE_INCIDENT_VIEW_TITLE);+ });+});diff --git a/frontend-modern/src/utils/__tests__/alertWebhookPresentation.branchcov0712b.test.ts b/frontend-modern/src/utils/__tests__/alertWebhookPresentation.branchcov0712b.test.tsnew file mode 100644index 0000000000..9a82de824a--- /dev/null+++ b/frontend-modern/src/utils/__tests__/alertWebhookPresentation.branchcov0712b.test.ts@@ -0,0 +1,266 @@+import { describe, expect, it } from 'vitest';+import type { WebhookTemplate } from '@/api/notifications';+import {+ getAlertWebhookServices,+ hasAlertWebhookMentionSupportFromTemplates,+ getAlertWebhooksSectionTitle,+ getAlertWebhooksSectionDescription,+ getAlertWebhookMutationFailure,+} from '@/utils/alertWebhookPresentation';++function makeTemplate(overrides: Partial<WebhookTemplate> = {}): WebhookTemplate {+ return {+ service: 'discord',+ name: 'Discord Webhook',+ urlPattern: 'https://discord.com/api/webhooks/.../...',+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ payloadTemplate: '',+ instructions: '',+ ...overrides,+ };+}++describe('alertWebhookPresentation (branch coverage 2)', () => {+ describe('getAlertWebhookServices', () => {+ it('returns an empty array when no templates arg is provided (default param)', () => {+ expect(getAlertWebhookServices()).toEqual([]);+ });++ it('returns an empty array for an explicit empty list', () => {+ expect(getAlertWebhookServices([])).toEqual([]);+ });++ it('uses the template label and description when both are present', () => {+ const templates = [+ makeTemplate({+ service: 'discord',+ label: 'Discord',+ description: 'Discord server webhook',+ }),+ ];+ expect(getAlertWebhookServices(templates)).toEqual([+ {+ id: 'discord',+ label: 'Discord',+ description: 'Discord server webhook',+ },+ ]);+ });++ it('falls back to the canonical service label when label is missing', () => {+ const templates = [+ makeTemplate({ service: 'slack', label: undefined, description: 'Slack channel' }),+ ];+ expect(getAlertWebhookServices(templates)).toEqual([+ {+ id: 'slack',+ label: 'Slack',+ description: 'Slack channel',+ },+ ]);+ });++ it('falls back to the canonical service label when label is an empty string', () => {+ const templates = [+ makeTemplate({ service: 'telegram', label: '', description: 'Telegram chat' }),+ ];+ expect(getAlertWebhookServices(templates)).toEqual([+ {+ id: 'telegram',+ label: 'Telegram',+ description: 'Telegram chat',+ },+ ]);+ });++ it('falls back to template.name when description is missing', () => {+ const templates = [+ makeTemplate({+ service: 'discord',+ label: 'Discord',+ description: undefined,+ name: 'Discord Webhook',+ }),+ ];+ expect(getAlertWebhookServices(templates)).toEqual([+ {+ id: 'discord',+ label: 'Discord',+ description: 'Discord Webhook',+ },+ ]);+ });++ it('falls back to template.name when description is an empty string', () => {+ const templates = [+ makeTemplate({+ service: 'generic',+ label: 'Generic',+ description: '',+ name: 'Generic Webhook',+ }),+ ];+ expect(getAlertWebhookServices(templates)).toEqual([+ {+ id: 'generic',+ label: 'Generic',+ description: 'Generic Webhook',+ },+ ]);+ });++ it('echoes the raw service id when the service is unknown and no label/description', () => {+ const templates = [+ makeTemplate({+ service: 'totally-unknown',+ label: undefined,+ description: undefined,+ name: 'Mystery Hook',+ }),+ ];+ expect(getAlertWebhookServices(templates)).toEqual([+ {+ id: 'totally-unknown',+ label: 'totally-unknown',+ description: 'Mystery Hook',+ },+ ]);+ });++ it('preserves order across multiple templates with mixed fallbacks', () => {+ const templates = [+ makeTemplate({ service: 'discord', label: 'Discord', description: 'desc-d' }),+ makeTemplate({+ service: 'slack',+ label: undefined,+ description: undefined,+ name: 'Slack Webhook',+ }),+ ];+ expect(getAlertWebhookServices(templates)).toEqual([+ { id: 'discord', label: 'Discord', description: 'desc-d' },+ { id: 'slack', label: 'Slack', description: 'Slack Webhook' },+ ]);+ });+ });++ describe('hasAlertWebhookMentionSupportFromTemplates', () => {+ it('returns false when no templates are provided (default param)', () => {+ expect(hasAlertWebhookMentionSupportFromTemplates('discord')).toBe(false);+ });++ it('returns false when no template matches the service', () => {+ expect(+ hasAlertWebhookMentionSupportFromTemplates('unknown', [+ makeTemplate({ service: 'discord' }),+ ]),+ ).toBe(false);+ });++ it('returns true when a matching template has a non-empty mentionPlaceholder', () => {+ const templates = [+ makeTemplate({+ service: 'discord',+ mentionPlaceholder: '@here',+ mentionHelp: undefined,+ }),+ ];+ expect(hasAlertWebhookMentionSupportFromTemplates('discord', templates)).toBe(true);+ });++ it('returns true when mentionPlaceholder is absent but mentionHelp is non-empty', () => {+ const templates = [+ makeTemplate({+ service: 'slack',+ mentionPlaceholder: undefined,+ mentionHelp: 'Slack: use @here',+ }),+ ];+ expect(hasAlertWebhookMentionSupportFromTemplates('slack', templates)).toBe(true);+ });++ it('returns true when mentionPlaceholder is whitespace-only but mentionHelp is non-empty', () => {+ const templates = [+ makeTemplate({+ service: 'slack',+ mentionPlaceholder: ' ',+ mentionHelp: 'Slack: use @here',+ }),+ ];+ expect(hasAlertWebhookMentionSupportFromTemplates('slack', templates)).toBe(true);+ });++ it('returns false when both mentionPlaceholder and mentionHelp are whitespace-only', () => {+ const templates = [+ makeTemplate({+ service: 'discord',+ mentionPlaceholder: ' ',+ mentionHelp: '\t',+ }),+ ];+ expect(hasAlertWebhookMentionSupportFromTemplates('discord', templates)).toBe(false);+ });++ it('returns false when both mention fields are absent on the matching template', () => {+ const templates = [+ makeTemplate({+ service: 'telegram',+ mentionPlaceholder: undefined,+ mentionHelp: undefined,+ }),+ ];+ expect(hasAlertWebhookMentionSupportFromTemplates('telegram', templates)).toBe(false);+ });++ it('uses the first matching template when duplicates exist', () => {+ const templates = [+ makeTemplate({ service: 'discord', mentionPlaceholder: 'first-support' }),+ makeTemplate({+ service: 'discord',+ mentionPlaceholder: undefined,+ mentionHelp: undefined,+ }),+ ];+ expect(hasAlertWebhookMentionSupportFromTemplates('discord', templates)).toBe(true);+ });+ });++ describe('getAlertWebhooksSectionTitle', () => {+ it('returns the canonical section title', () => {+ expect(getAlertWebhooksSectionTitle()).toBe('Webhooks');+ });+ });++ describe('getAlertWebhooksSectionDescription', () => {+ it('returns the canonical section description', () => {+ expect(getAlertWebhooksSectionDescription()).toBe(+ 'Push alerts to chat apps or automation systems.',+ );+ });+ });++ describe('getAlertWebhookMutationFailure', () => {+ it('returns the add failure message', () => {+ expect(getAlertWebhookMutationFailure('add')).toBe('Failed to add webhook');+ });++ it('returns the update failure message', () => {+ expect(getAlertWebhookMutationFailure('update')).toBe('Failed to update webhook');+ });++ it('returns the delete failure message for the delete action', () => {+ expect(getAlertWebhookMutationFailure('delete')).toBe('Failed to delete webhook');+ });++ it('returns the delete failure message for any non-matching action (default arm)', () => {+ expect(+ getAlertWebhookMutationFailure(+ 'totally-bogus' as unknown as Parameters<+ typeof getAlertWebhookMutationFailure+ >[0],+ ),+ ).toBe('Failed to delete webhook');+ });+ });+});diff --git a/frontend-modern/src/utils/__tests__/apiTokenPresentation.branchcov0712b.test.ts b/frontend-modern/src/utils/__tests__/apiTokenPresentation.branchcov0712b.test.tsnew file mode 100644index 0000000000..6d9e5fa7b2--- /dev/null+++ b/frontend-modern/src/utils/__tests__/apiTokenPresentation.branchcov0712b.test.ts@@ -0,0 +1,138 @@+import { describe, expect, it } from 'vitest';+import type { APITokenUsagePresentationEntry } from '@/utils/apiTokenPresentation';+import {+ getAPITokenDockerPodmanUsageTitle,+ getAPITokenGenerateErrorMessage,+} from '@/utils/apiTokenPresentation';++// Branch-coverage companion to `apiTokenPresentation.test.ts`. The sibling+// suite already pins the happy paths (no-arg default, `Cannot grant scope`+// echo, and `missing_scope` with a known scope id). This file drives the+// remaining arms of `getAPITokenGenerateErrorMessage` (non-object input,+// non-403 status, non-string message, trim path, the `missing_scope` guard+// falling through for an unknown/whitespace/absent scope id, and the+// label-falsy fallback) and of `getAPITokenDockerPodmanUsageTitle`+// (`filter(Boolean)` emptying the list and the single/mixed-label join arms).++describe('apiTokenPresentation — branch coverage (branchcov2)', () => {+ describe('getAPITokenGenerateErrorMessage', () => {+ it('returns the default copy for a non-object primitive (typeof !== "object")', () => {+ // The outer `error && typeof error === 'object'` guard short-circuits,+ // skipping the entire typed block and falling through to the trailing+ // default return.+ expect(getAPITokenGenerateErrorMessage('server exploded')).toBe(+ 'Unable to generate the API token.',+ );+ expect(getAPITokenGenerateErrorMessage(503)).toBe('Unable to generate the API token.');+ });++ it('returns the default copy for a 403-shape error whose status is not 403', () => {+ // `typedError.status !== 403` is true -> early default inside the object block.+ const error = { status: 500, message: 'Internal failure' };+ expect(getAPITokenGenerateErrorMessage(error)).toBe('Unable to generate the API token.');+ });++ it('returns the default copy for a 403 whose message is not a string', () => {+ // status === 403 but `typeof typedError.message !== 'string'` is true,+ // so the same early default fires before `.trim()` is ever reached.+ const error = { status: 403, message: 42 } as unknown as Parameters<+ typeof getAPITokenGenerateErrorMessage+ >[0];+ expect(getAPITokenGenerateErrorMessage(error)).toBe('Unable to generate the API token.');+ });++ it('returns the trimmed message when it starts with "Cannot grant scope" (trim + startsWith true arm)', () => {+ // Drives `typedError.message.trim()` and the `startsWith('Cannot grant scope')`+ // true arm: leading/trailing whitespace is stripped before the message is echoed.+ const error = Object.assign(+ new Error(' Cannot grant scope "ai:execute": denied '),+ { status: 403 },+ );+ expect(getAPITokenGenerateErrorMessage(error)).toBe('Cannot grant scope "ai:execute": denied');+ });++ it('falls through to the default for a 403 message that matches neither sentinel', () => {+ // status === 403, message is a string, but it does not start with+ // "Cannot grant scope" and is not the literal "missing_scope" — so both+ // inner ifs are false and execution reaches the trailing default.+ const error = Object.assign(new Error('something else entirely'), { status: 403 });+ expect(getAPITokenGenerateErrorMessage(error)).toBe('Unable to generate the API token.');+ });++ it('falls through to the default when "missing_scope" is returned without a requiredScope', () => {+ // `message === 'missing_scope'` is true, but `typedError.requiredScope`+ // is undefined -> `requiredScope?.trim()` evaluates to undefined, which+ // is falsy, so the `if (requiredScope)` body is skipped and we fall+ // out of the missing_scope block to the trailing default.+ const error = Object.assign(new Error('missing_scope'), { status: 403 });+ expect(getAPITokenGenerateErrorMessage(error)).toBe('Unable to generate the API token.');+ });++ it('falls through to the default when requiredScope trims to an empty string', () => {+ // requiredScope is whitespace-only -> after `.trim()` it is '' (falsy),+ // so the labelled branch is skipped even though the field was present.+ const error = Object.assign(new Error('missing_scope'), {+ status: 403,+ requiredScope: ' ',+ });+ expect(getAPITokenGenerateErrorMessage(error)).toBe('Unable to generate the API token.');+ });++ it('falls back to the raw scope id when requiredScope has no friendly label (label falsy arm)', () => {+ // `API_SCOPE_LABELS[unknownScope]` is undefined, so the ternary picks the+ // right-hand template that interpolates only the raw id.+ const error = Object.assign(new Error('missing_scope'), {+ status: 403,+ requiredScope: 'totally:unknown:scope',+ });+ expect(getAPITokenGenerateErrorMessage(error)).toBe(+ 'This token is missing the required scope: totally:unknown:scope.',+ );+ });+ });++ describe('getAPITokenDockerPodmanUsageTitle', () => {+ it('returns the bare runtimes label when items is empty (labels.length === 0 arm)', () => {+ // `.map` over [] then `.filter(Boolean)` yields [], so the ternary+ // returns the right-hand `API_TOKEN_DOCKER_PODMAN_RUNTIMES_LABEL`.+ const entry: APITokenUsagePresentationEntry = { count: 0, items: [] };+ expect(getAPITokenDockerPodmanUsageTitle(entry)).toBe('Docker / Podman runtimes');+ });++ it('returns the bare runtimes label when every item label is empty (filter(Boolean) empties the list)', () => {+ // items is non-empty but every label is the falsy '' — `filter(Boolean)`+ // drops them all, exercising the same labels.length === 0 arm via a+ // different runtime path.+ const entry: APITokenUsagePresentationEntry = {+ count: 2,+ items: [{ label: '' }, { label: '' }],+ };+ expect(getAPITokenDockerPodmanUsageTitle(entry)).toBe('Docker / Podman runtimes');+ });++ it('joins a single truthy label after the colon (labels.length > 0, one element)', () => {+ // Single-element join produces no separator, confirming the join(', ')+ // behaves correctly for the n === 1 case.+ const entry: APITokenUsagePresentationEntry = {+ count: 1,+ items: [{ label: 'Edge Node' }],+ };+ expect(getAPITokenDockerPodmanUsageTitle(entry)).toBe(+ 'Docker / Podman runtimes: Edge Node',+ );+ });++ it('drops falsy labels and joins the remaining truthy ones with ", "', () => {+ // Mixed truthy/falsy labels: filter(Boolean) keeps 'Docker Edge' and+ // 'Podman Lab' while dropping the empty middle label, so the joined+ // output has exactly two entries with the canonical separator.+ const entry: APITokenUsagePresentationEntry = {+ count: 3,+ items: [{ label: 'Docker Edge' }, { label: '' }, { label: 'Podman Lab' }],+ };+ expect(getAPITokenDockerPodmanUsageTitle(entry)).toBe(+ 'Docker / Podman runtimes: Docker Edge, Podman Lab',+ );+ });+ });+});diff --git a/frontend-modern/src/utils/__tests__/recoveryItemTypePresentation.branchcov0712b.test.ts b/frontend-modern/src/utils/__tests__/recoveryItemTypePresentation.branchcov0712b.test.tsnew file mode 100644index 0000000000..3554a228fe--- /dev/null+++ b/frontend-modern/src/utils/__tests__/recoveryItemTypePresentation.branchcov0712b.test.ts@@ -0,0 +1,128 @@+import { describe, expect, it, vi } from 'vitest';++import { getRecoveryItemTypePresentation } from '@/utils/recoveryItemTypePresentation';++// vitest hoists vi.mock above the imports. We wrap getResourceTypePresentation+// so that a single sentinel key returns null — reaching the otherwise-dead+// defensive `else` branch in the default case of getRecoveryItemTypePresentation+// — while delegating every other call to the real implementation. The factory+// cannot reference outer consts (it is hoisted), so the sentinel literal is+// duplicated below in FORCE_NULL_KEY.+vi.mock('@/utils/resourceTypePresentation', async () => {+ const actual =+ await vi.importActual<typeof import('@/utils/resourceTypePresentation')>('@/utils/resourceTypePresentation');+ return {+ ...actual,+ getResourceTypePresentation: (+ ...args: Parameters<typeof actual.getResourceTypePresentation>+ ): ReturnType<typeof actual.getResourceTypePresentation> =>+ args[0] === '__force_null__' ? null : actual.getResourceTypePresentation(...args),+ };+});++// Must match the literal baked into the hoisted mock factory above.+const FORCE_NULL_KEY = '__force_null__';++// Badge-class building blocks mirrored from the source module so the assertions+// describe the documented badge composition rather than echoing the unit under+// test. These are the primitives the module concatenates.+const BADGE_BASE_CLASSES =+ 'inline-flex items-center rounded px-2 py-0.5 text-[10px] font-medium whitespace-nowrap';+const TABLE_BADGE_BASE_CLASSES =+ 'inline-flex items-center px-1 py-0.5 text-[10px] font-medium rounded whitespace-nowrap';+const DEFAULT_BADGE_TONE_CLASSES = 'bg-surface-alt text-base-content';+const DEFAULT_BADGE_CLASSES = `${BADGE_BASE_CLASSES} ${DEFAULT_BADGE_TONE_CLASSES}`;+const DEFAULT_TABLE_BADGE_CLASSES = `${TABLE_BADGE_BASE_CLASSES} ${DEFAULT_BADGE_TONE_CLASSES}`;++// Workload tones mirrored from workloadTypePresentation's PRESENTATION_MAP; the+// vm / system-container / app-container arms thread these through verbatim.+const VM_TONE = 'bg-blue-100 text-blue-700 dark:bg-blue-900 dark:text-blue-300';+const SYSTEM_CONTAINER_TONE =+ 'bg-green-100 text-green-700 dark:bg-green-900 dark:text-green-300';+const APP_CONTAINER_TONE = 'bg-sky-100 text-sky-700 dark:bg-sky-900 dark:text-sky-300';++describe('getRecoveryItemTypePresentation — branch coverage (branchcov2)', () => {+ it('composes the full vm presentation (workload-map badge + table badge composition)', () => {+ // Existing tests only assert key/label for this arm; this newly exercises+ // the badgeClasses / tableBadgeClasses concatenation lines for case 'vm'.+ expect(getRecoveryItemTypePresentation('vm')).toStrictEqual({+ key: 'vm',+ label: 'VM',+ badgeClasses: `${BADGE_BASE_CLASSES} ${VM_TONE}`,+ tableBadgeClasses: `${TABLE_BADGE_BASE_CLASSES} ${VM_TONE}`,+ });+ });++ it('composes the full system-container presentation from the workload map', () => {+ // case 'system-container' badge composition; the workload label is 'LXC'.+ expect(getRecoveryItemTypePresentation('system-container')).toStrictEqual({+ key: 'system-container',+ label: 'LXC',+ badgeClasses: `${BADGE_BASE_CLASSES} ${SYSTEM_CONTAINER_TONE}`,+ tableBadgeClasses: `${TABLE_BADGE_BASE_CLASSES} ${SYSTEM_CONTAINER_TONE}`,+ });+ });++ it('applies the App Container label override while keeping the app-container tone', () => {+ // case 'app-container' is the only arm that forwards label/title overrides+ // into getWorkloadTypePresentation; the override wins for `label` while the+ // className still comes from the app-container workload entry.+ expect(getRecoveryItemTypePresentation('app-container')).toStrictEqual({+ key: 'app-container',+ label: 'App Container',+ badgeClasses: `${BADGE_BASE_CLASSES} ${APP_CONTAINER_TONE}`,+ tableBadgeClasses: `${TABLE_BADGE_BASE_CLASSES} ${APP_CONTAINER_TONE}`,+ });+ });++ it('composes the full cluster presentation from the k8s-cluster resource entry', () => {+ // case 'cluster' badge composition; getResourceTypePresentation('k8s-cluster')+ // yields the default tone, so the || DEFAULT_BADGE_TONE_CLASSES arm is NOT+ // taken (presentation?.badgeClasses is truthy).+ expect(getRecoveryItemTypePresentation('cluster')).toStrictEqual({+ key: 'cluster',+ label: 'K8s Cluster',+ badgeClasses: `${BADGE_BASE_CLASSES} ${DEFAULT_BADGE_TONE_CLASSES}`,+ tableBadgeClasses: `${TABLE_BADGE_BASE_CLASSES} ${DEFAULT_BADGE_TONE_CLASSES}`,+ });+ });++ it('re-title-cases the key when the resource label equals the key (default, label === key arm)', () => {+ // 'custom-thing' is unknown to both recovery and resource maps, so+ // getResourceTypePresentation returns { label: 'custom-thing' } — equal to the+ // key — driving the ternary onto its titleCaseDelimitedLabel arm and using+ // presentation.badgeClasses for the badge strings.+ expect(getRecoveryItemTypePresentation('custom-thing')).toStrictEqual({+ key: 'custom-thing',+ label: 'Custom Thing',+ badgeClasses: `${BADGE_BASE_CLASSES} ${DEFAULT_BADGE_TONE_CLASSES}`,+ tableBadgeClasses: `${TABLE_BADGE_BASE_CLASSES} ${DEFAULT_BADGE_TONE_CLASSES}`,+ });+ });++ it('title-cases a hyphenated multi-token key whose first token is short (documents inert preserveShortAllCaps)', () => {+ // NOTE: source passes preserveShortAllCaps:true to titleCaseDelimitedLabel,+ // but normalizeRecoveryItemTypeQueryValue lowercases the key first, so the+ // 'nfs' token is already 'nfs' by the time title-casing runs and the option+ // cannot rescue it. The real, concrete output is therefore 'Nfs Share' —+ // asserting it pins this (suspected) inert-option behaviour in place.+ expect(getRecoveryItemTypePresentation('nfs-share')).toStrictEqual({+ key: 'nfs-share',+ label: 'Nfs Share',+ badgeClasses: `${BADGE_BASE_CLASSES} ${DEFAULT_BADGE_TONE_CLASSES}`,+ tableBadgeClasses: `${TABLE_BADGE_BASE_CLASSES} ${DEFAULT_BADGE_TONE_CLASSES}`,+ });+ });++ it('falls back to default badges when the resource presentation is null (default, else arm)', () => {+ // The sentinel key is force-mocked so getResourceTypePresentation returns+ // null, reaching the defensive else-branch that yields DEFAULT_*_BADGE_CLASSES.+ // '__force_null__' normalizes to itself and title-cases to 'Force Null'.+ expect(getRecoveryItemTypePresentation(FORCE_NULL_KEY)).toStrictEqual({+ key: FORCE_NULL_KEY,+ label: 'Force Null',+ badgeClasses: DEFAULT_BADGE_CLASSES,+ tableBadgeClasses: DEFAULT_TABLE_BADGE_CLASSES,+ });+ });+});diff --git a/frontend-modern/src/utils/__tests__/systemSettingsPresentation.branchcov0712b.test.ts b/frontend-modern/src/utils/__tests__/systemSettingsPresentation.branchcov0712b.test.tsnew file mode 100644index 0000000000..15709d4286--- /dev/null+++ b/frontend-modern/src/utils/__tests__/systemSettingsPresentation.branchcov0712b.test.ts@@ -0,0 +1,118 @@+import { afterEach, describe, expect, it } from 'vitest';+import { DEFAULT_LOCALE, setActiveLocale } from '@/i18n';+import {+ formatPvePollingDuration,+ getBackupIntervalSummary,+} from '@/utils/systemSettingsPresentation';++// Focused branch-coverage companion to systemSettingsPresentation.test.ts.+// The sibling test only exercised formatPvePollingDuration(90, 'de') and a+// handful of getBackupIntervalSummary rows; these cases drive the remaining+// arms of every conditional/ternary in the two target functions.++describe('systemSettingsPresentation — branch coverage (branchcov2)', () => {+ afterEach(() => {+ // Keep locale mutations local to this file so they cannot leak into peers.+ setActiveLocale(DEFAULT_LOCALE);+ });++ describe('formatPvePollingDuration', () => {+ it('returns the under-minute copy when seconds is below sixty (true arm of `seconds < 60`)', () => {+ expect(formatPvePollingDuration(59, 'en')).toBe('under a minute');+ expect(formatPvePollingDuration(30, 'es')).toBe('menos de un minuto');+ expect(formatPvePollingDuration(0, 'en')).toBe('under a minute');+ // Defensive negative still takes the early-return arm.+ expect(formatPvePollingDuration(-1, 'en')).toBe('under a minute');+ });++ it('treats exactly sixty seconds as one whole minute (boundary false arm + singular `minute` key)', () => {+ // seconds === 60 is the first value where `seconds < 60` is false; it also+ // forces minutes === 1 (singular) and minutes % 1 === 0 (maxFrac 0).+ expect(formatPvePollingDuration(60, 'en')).toBe('1 minute');+ expect(formatPvePollingDuration(60, 'de')).toBe('1 Minute');+ });++ it('formats whole-number minutes with no fraction (true arm of `minutes % 1 === 0`, plural)', () => {+ // 120s -> 2 whole minutes -> maximumFractionDigits 0 -> plural key.+ expect(formatPvePollingDuration(120, 'en')).toBe('2 minutes');+ expect(formatPvePollingDuration(1800, 'en')).toBe('30 minutes');+ });++ it('formats fractional minutes with one decimal (false arm of `minutes % 1 === 0`, plural)', () => {+ // 90s -> 1.5 -> maximumFractionDigits 1; 1.5 !== 1 so the plural key wins.+ expect(formatPvePollingDuration(90, 'en')).toBe('1.5 minutes');+ // 150s -> 2.5 -> exercises the fractional arm again with a different count.+ expect(formatPvePollingDuration(150, 'en')).toBe('2.5 minutes');+ });++ it('falls back to getActiveLocale() when locale is omitted (false arm of `locale ?? getActiveLocale()`)', () => {+ // No locale arg -> resolvePresentationLocale must consult getActiveLocale().+ setActiveLocale('es');+ expect(formatPvePollingDuration(30)).toBe('menos de un minuto');+ setActiveLocale('de');+ expect(formatPvePollingDuration(60)).toBe('1 Minute');+ });++ it('propagates NaN seconds through the >= 60 path without throwing (defensive)', () => {+ // NaN < 60 is false, so it falls through to the minutes formatting where+ // both ternaries evaluate their falsy arms (NaN === 0 is false, NaN === 1+ // is false), yielding the literal "NaN" token in the plural copy.+ expect(formatPvePollingDuration(Number.NaN, 'en')).toBe('NaN minutes');+ });+ });++ describe('getBackupIntervalSummary', () => {+ it('disables polling regardless of interval when the flag is falsy (true arm of `!backupPollingEnabled`)', () => {+ // A valid hourly interval is ignored once the disabled flag is set, and+ // the disabled branch wins over a non-boolean falsy value (JS coercion).+ expect(getBackupIntervalSummary(false, 3600)).toBe('Backup polling is disabled.');+ expect(+ getBackupIntervalSummary(0 as unknown as boolean, 86400),+ ).toBe('Backup polling is disabled.');+ });++ it('treats negative intervals as the default cadence (< 0 portion of `backupPollingInterval <= 0`)', () => {+ // The sibling test only used 0; these hit the strictly-negative side of+ // the `<= 0` guard, including a large negative that would otherwise be a+ // whole number of days.+ expect(getBackupIntervalSummary(true, -1)).toBe(+ 'Pulse checks backups and snapshots at the default cadence (~every 90 seconds).',+ );+ expect(getBackupIntervalSummary(true, -86400)).toBe(+ 'Pulse checks backups and snapshots at the default cadence (~every 90 seconds).',+ );+ });++ it('uses the singular "minute" for intervals that round to one minute (true arm of `minutes === 1`)', () => {+ // 60s: not divisible by 86400 or 3600, round(60/60) === 1 -> singular.+ expect(getBackupIntervalSummary(true, 60)).toBe('Pulse checks backups every minute.');+ });++ it('clamps sub-minute intervals up to one minute via Math.max (defensive clamp branch)', () => {+ // 1s -> round(1/60) === 0 -> Math.max(1, 0) === 1, so "minute" not "0 minutes".+ expect(getBackupIntervalSummary(true, 1)).toBe('Pulse checks backups every minute.');+ // 30s -> round(0.5) === 1 -> already 1; Math.max is a no-op here but the+ // path is shared with the clamp, so we pin it as the non-clamped sibling.+ expect(getBackupIntervalSummary(true, 30)).toBe('Pulse checks backups every minute.');+ });++ it('falls through the day and hour guards to the plural minutes fallback (false arms of `% 86400` and `% 3600`)', () => {+ // 5400s = 90 min: not divisible by an hour or a day -> minutes fallback, plural.+ expect(getBackupIntervalSummary(true, 5400)).toBe(+ 'Pulse checks backups every 90 minutes.',+ );+ // 300s = 5 min: same fall-through, plural count of 5.+ expect(getBackupIntervalSummary(true, 300)).toBe(+ 'Pulse checks backups every 5 minutes.',+ );+ });++ it('honors a truthy non-boolean flag as enabled (coercion through `!backupPollingEnabled`)', () => {+ // A non-empty string is truthy, so the disabled guard is skipped and the+ // interval is formatted normally. Cast satisfies the declared boolean type.+ expect(+ getBackupIntervalSummary('true' as unknown as boolean, 3600),+ ).toBe('Pulse checks backups every hour.');+ });+ });+});