Skip to content

armgit / Pulse

Public Imported from GitHub
0

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.

test(frontend): branch-coverage tests for 16 more pure model/presentation modules

rcourtman516179e5faad
diff --git a/frontend-modern/src/components/Infrastructure/__tests__/resourceDetailDrawerKubernetesModel.branchcov2.test.ts b/frontend-modern/src/components/Infrastructure/__tests__/resourceDetailDrawerKubernetesModel.branchcov2.test.ts
new file mode 100644
index 0000000000..2211234c07
--- /dev/null
+++ b/frontend-modern/src/components/Infrastructure/__tests__/resourceDetailDrawerKubernetesModel.branchcov2.test.ts
@@ -0,0 +1,326 @@
+import { describe, expect, it } from 'vitest';
+
+import type { ResourceKubernetesPodContainerStatus, Resource } from '@/types/resource';
+import type { DetailRow } from '@/components/shared/detailSectionModel';
+import {
+ buildKubernetesDetailSections,
+ buildKubernetesDetailsSummary,
+} from '../resourceDetailDrawerKubernetesModel';
+
+// Branch-coverage companion to resourceDetailDrawerKubernetesModel.test.ts.
+// Drives the still-uncovered arms of containerRow (module-private, so exercised
+// through the pod Containers section), buildKubernetesDetailsSummary and
+// buildKubernetesDetailSections. Each case pins a concrete shape/string rather
+// than truthiness.
+
+const makeResource = ({
+ id,
+ type,
+ ...overrides
+}: Partial<Resource> & Pick<Resource, 'id' | 'type'>): Resource => ({
+ id,
+ name: id,
+ displayName: id,
+ platformId: 'cluster-1',
+ platformType: 'kubernetes',
+ sourceType: 'agent',
+ sources: ['kubernetes'],
+ status: 'online',
+ type,
+ lastSeen: 1_700_000_000_000,
+ ...overrides,
+});
+
+const sectionsOf = (resource: Resource): ReturnType<typeof buildKubernetesDetailSections> =>
+ buildKubernetesDetailSections(resource);
+
+const sectionByLabel = (resource: Resource, label: string) =>
+ sectionsOf(resource).find((section) => section.label === label);
+
+const rowInSection = (
+ resource: Resource,
+ sectionLabel: string,
+ rowLabel: string,
+): DetailRow | undefined =>
+ sectionByLabel(resource, sectionLabel)?.rows.find((row) => row.label === rowLabel);
+
+// All fields of ResourceKubernetesPodContainerStatus are optional, so a partial
+// object is accepted directly; build a single-container pod and return that
+// container's rendered row.
+const singleContainerRow = (
+ container: ResourceKubernetesPodContainerStatus,
+): DetailRow | undefined =>
+ sectionByLabel(
+ makeResource({
+ id: 'pod-c',
+ type: 'pod',
+ kubernetes: { podContainers: [container] },
+ }),
+ 'Containers (1)',
+ )?.rows[0];
+
+describe('containerRow (via Containers section)', () => {
+ it('falls back to "unknown" state, "container N" label and warning tone when state/name/ready are absent', () => {
+ expect(singleContainerRow({ image: 'ghcr.io/acme/api:1.2.3' })).toEqual({
+ label: 'container 1',
+ value: 'unknown · not ready · ghcr.io/acme/api:1.2.3',
+ title: 'unknown · not ready · ghcr.io/acme/api:1.2.3',
+ tone: 'warning',
+ });
+ });
+
+ it('drops the parenthetical when reason matches state case-insensitively, and omits restarts at 0', () => {
+ expect(
+ singleContainerRow({
+ name: 'api',
+ state: 'running',
+ reason: 'Running',
+ ready: true,
+ restartCount: 0,
+ image: 'ghcr.io/acme/api:1.2.3',
+ }),
+ ).toEqual({
+ label: 'api',
+ value: 'running · ready · ghcr.io/acme/api:1.2.3',
+ title: 'running · ready · ghcr.io/acme/api:1.2.3',
+ tone: 'default',
+ });
+ });
+
+ it('omits restarts/image parts and folds the message into the title', () => {
+ expect(
+ singleContainerRow({
+ name: 'worker',
+ state: 'waiting',
+ reason: 'ImagePullBackOff',
+ ready: false,
+ message: 'manifest not found',
+ }),
+ ).toEqual({
+ label: 'worker',
+ value: 'waiting (ImagePullBackOff) · not ready',
+ title: 'waiting (ImagePullBackOff) · not ready: manifest not found',
+ tone: 'warning',
+ });
+ });
+
+ it('treats a negative restartCount as zero restarts', () => {
+ expect(singleContainerRow({ name: 'c', state: 'running', ready: true, restartCount: -3 })?.value).toBe(
+ 'running · ready',
+ );
+ });
+
+ it('treats whitespace-only state/name/image as absent', () => {
+ const row = singleContainerRow({ name: ' ', state: ' ', image: ' ', ready: true });
+ expect(row?.label).toBe('container 1');
+ expect(row?.value).toBe('unknown · ready');
+ expect(row?.title).toBe('unknown · ready');
+ expect(row?.tone).toBe('default');
+ });
+});
+
+describe('buildKubernetesDetailsSummary', () => {
+ it('returns null when there is no kubernetes metadata', () => {
+ expect(buildKubernetesDetailsSummary(makeResource({ id: 'vm-1', type: 'vm' }))).toBeNull();
+ });
+
+ it('pluralizes the container count for multi-container pods', () => {
+ expect(
+ buildKubernetesDetailsSummary(
+ makeResource({
+ id: 'pod-1',
+ type: 'pod',
+ kubernetes: { podContainers: [{ name: 'a' }, { name: 'b' }, { name: 'c' }] },
+ }),
+ ),
+ ).toBe('3 containers');
+ });
+
+ it('emits only QoS when the pod carries no containers', () => {
+ expect(
+ buildKubernetesDetailsSummary(
+ makeResource({ id: 'pod-2', type: 'pod', kubernetes: { qosClass: 'Burstable' } }),
+ ),
+ ).toBe('Burstable');
+ });
+
+ it('returns null for a pod with no containers and no QoS', () => {
+ expect(
+ buildKubernetesDetailsSummary(makeResource({ id: 'pod-3', type: 'pod', kubernetes: {} })),
+ ).toBeNull();
+ });
+
+ it('omits the QoS part when only containers are present', () => {
+ expect(
+ buildKubernetesDetailsSummary(
+ makeResource({ id: 'pod-4', type: 'pod', kubernetes: { podContainers: [{ name: 'a' }] } }),
+ ),
+ ).toBe('1 container');
+ });
+
+ it('omits the cordon marker when a node is schedulable', () => {
+ expect(
+ buildKubernetesDetailsSummary(
+ makeResource({ id: 'node-1', type: 'k8s-node', kubernetes: { osImage: 'Ubuntu 22.04' } }),
+ ),
+ ).toBe('Ubuntu 22.04');
+ });
+
+ it('surfaces only the cordon marker when the node has no OS image', () => {
+ expect(
+ buildKubernetesDetailsSummary(
+ makeResource({ id: 'node-2', type: 'k8s-node', kubernetes: { unschedulable: true } }),
+ ),
+ ).toBe('Cordoned');
+ });
+
+ it('returns null for a node with neither OS image nor cordon state', () => {
+ expect(
+ buildKubernetesDetailsSummary(makeResource({ id: 'node-3', type: 'k8s-node', kubernetes: {} })),
+ ).toBeNull();
+ });
+
+ it('returns null for a cluster without a server endpoint', () => {
+ expect(
+ buildKubernetesDetailsSummary(
+ makeResource({ id: 'cluster-1', type: 'k8s-cluster', kubernetes: {} }),
+ ),
+ ).toBeNull();
+ });
+
+ it('returns null for a non-pod/node/cluster type that still carries kubernetes metadata', () => {
+ expect(
+ buildKubernetesDetailsSummary(
+ makeResource({ id: 'vm-2', type: 'vm', kubernetes: { osImage: 'Talos 1.7' } }),
+ ),
+ ).toBeNull();
+ });
+
+ it('recognizes an agent carrying a nodeUid as a node', () => {
+ expect(
+ buildKubernetesDetailsSummary(
+ makeResource({
+ id: 'agent-uid',
+ type: 'agent',
+ kubernetes: { nodeUid: 'node-42', osImage: 'Flatcar' },
+ }),
+ ),
+ ).toBe('Flatcar');
+ });
+
+ it('returns null for an agent that is not a kubernetes node', () => {
+ expect(
+ buildKubernetesDetailsSummary(
+ makeResource({ id: 'agent-plain', type: 'agent', kubernetes: { podName: 'x' } }),
+ ),
+ ).toBeNull();
+ });
+});
+
+describe('buildKubernetesDetailSections', () => {
+ it('drops the Pod section when a pod has no QoS class', () => {
+ const pod = makeResource({
+ id: 'pod-q',
+ type: 'pod',
+ kubernetes: { podContainers: [{ name: 'a', state: 'running', ready: true }] },
+ });
+ expect(sectionsOf(pod).map((section) => section.label)).toEqual(['Containers (1)']);
+ });
+
+ it('drops the Containers section when a pod has no containers', () => {
+ const pod = makeResource({
+ id: 'pod-n',
+ type: 'pod',
+ kubernetes: { qosClass: 'Guaranteed' },
+ });
+ expect(sectionsOf(pod).map((section) => section.label)).toEqual(['Pod']);
+ expect(sectionByLabel(pod, 'Pod')?.rows).toEqual([{ label: 'QoS class', value: 'Guaranteed' }]);
+ });
+
+ it('returns no sections for a pod with neither QoS nor containers', () => {
+ expect(
+ buildKubernetesDetailSections(makeResource({ id: 'pod-e', type: 'pod', kubernetes: {} })),
+ ).toEqual([]);
+ });
+
+ it('omits the Scheduling row for a schedulable node', () => {
+ const node = makeResource({
+ id: 'node-s',
+ type: 'k8s-node',
+ kubernetes: { osImage: 'Ubuntu 22.04' },
+ });
+ const section = sectionByLabel(node, 'Kubernetes node');
+ expect(section?.rows.find((row) => row.label === 'Scheduling')).toBeUndefined();
+ expect(section?.rows.find((row) => row.label === 'OS image')?.value).toBe('Ubuntu 22.04');
+ });
+
+ it('formats node capacity as cores only when only CPU is set', () => {
+ const node = makeResource({
+ id: 'node-cpu',
+ type: 'k8s-node',
+ kubernetes: { capacityCpuCores: 8 },
+ });
+ expect(rowInSection(node, 'Kubernetes node', 'Capacity')?.value).toBe('8 cores');
+ });
+
+ it('formats node capacity as memory only when only memory is set', () => {
+ const node = makeResource({
+ id: 'node-mem',
+ type: 'k8s-node',
+ kubernetes: { capacityMemoryBytes: 2 * 1024 ** 3 },
+ });
+ expect(rowInSection(node, 'Kubernetes node', 'Capacity')?.value).toBe('2.00 GB');
+ });
+
+ it('formats node capacity as pods only when only the pod count is set', () => {
+ const node = makeResource({
+ id: 'node-pods',
+ type: 'k8s-node',
+ kubernetes: { capacityPods: 110 },
+ });
+ expect(rowInSection(node, 'Kubernetes node', 'Capacity')?.value).toBe('110 pods');
+ });
+
+ it('drops the Capacity row when no capacity field is finite/positive', () => {
+ const node = makeResource({
+ id: 'node-empty',
+ type: 'k8s-node',
+ kubernetes: { capacityCpuCores: 0, osImage: 'Ubuntu' },
+ });
+ const section = sectionByLabel(node, 'Kubernetes node');
+ expect(section?.rows.find((row) => row.label === 'Capacity')).toBeUndefined();
+ expect(section?.rows.find((row) => row.label === 'OS image')?.value).toBe('Ubuntu');
+ });
+
+ it('omits the Pending uninstall row for a cluster not pending uninstall', () => {
+ const cluster = makeResource({
+ id: 'cluster-ok',
+ type: 'k8s-cluster',
+ kubernetes: { server: 'https://k.local', context: 'admin' },
+ });
+ expect(sectionByLabel(cluster, 'Cluster')?.rows.map((row) => row.label)).toEqual([
+ 'API server',
+ 'Context',
+ ]);
+ });
+
+ it('recognizes an agent carrying a nodeUid as a node and renders its OS image', () => {
+ const node = makeResource({
+ id: 'agent-node-uid',
+ type: 'agent',
+ kubernetes: { nodeUid: 'node-9', osImage: 'Flatcar 3600.0.0' },
+ });
+ expect(sectionByLabel(node, 'Kubernetes node')?.rows).toContainEqual({
+ label: 'OS image',
+ value: 'Flatcar 3600.0.0',
+ });
+ });
+
+ it('returns no sections for a non-pod/node/cluster type carrying kubernetes metadata', () => {
+ expect(
+ buildKubernetesDetailSections(
+ makeResource({ id: 'vm-k', type: 'vm', kubernetes: { osImage: 'Talos' } }),
+ ),
+ ).toEqual([]);
+ });
+});
diff --git a/frontend-modern/src/components/Settings/__tests__/availabilitySettingsModel.branchcov2.test.ts b/frontend-modern/src/components/Settings/__tests__/availabilitySettingsModel.branchcov2.test.ts
new file mode 100644
index 0000000000..92db8578dd
--- /dev/null
+++ b/frontend-modern/src/components/Settings/__tests__/availabilitySettingsModel.branchcov2.test.ts
@@ -0,0 +1,311 @@
+/**
+ * Branch-coverage tests for the exported label/path helpers in
+ * availabilitySettingsModel. Each block targets a single function and drives
+ * both arms of every conditional / ternary / switch / optional-chain / guard
+ * branch reachable from the public surface.
+ *
+ * The sibling availabilitySettingsModel.test.ts covers the happy-path arms
+ * (TCP method, tcp address with port, http address join, machine/service kind
+ * label, Online-with-latency status). This file focuses on the remaining
+ * branches of getAvailabilityTargetStatusLabel, getAvailabilityTargetKindLabel,
+ * getAvailabilityTargetAddressLabel, getAvailabilityTargetMethodLabel, and
+ * getAvailabilityTargetAddKind.
+ */
+import { describe, expect, it } from 'vitest';
+import {
+ getAvailabilityTargetAddKind,
+ getAvailabilityTargetAddressLabel,
+ getAvailabilityTargetKindLabel,
+ getAvailabilityTargetMethodLabel,
+ getAvailabilityTargetStatusLabel,
+} from '../availabilitySettingsModel';
+import type {
+ AvailabilityProbeStatus,
+ AvailabilityTarget,
+} from '@/api/availabilityTargets';
+
+// ---- Fixtures ---------------------------------------------------------------
+// Mirrors the sibling availabilitySettingsModel.test.ts factory shape so the
+// two files stay consistent.
+
+const target = (overrides: Partial<AvailabilityTarget> = {}): AvailabilityTarget => ({
+ id: 'mqtt-broker',
+ name: 'MQTT broker',
+ address: 'mqtt.local',
+ protocol: 'tcp',
+ port: 1883,
+ enabled: true,
+ ...overrides,
+});
+
+const status = (
+ overrides: Partial<AvailabilityProbeStatus> = {},
+): AvailabilityProbeStatus => ({
+ targetId: 'mqtt-broker',
+ name: 'MQTT broker',
+ address: 'mqtt.local',
+ protocol: 'tcp',
+ enabled: true,
+ available: true,
+ ...overrides,
+});
+
+// ---- getAvailabilityTargetStatusLabel --------------------------------------
+// Branches: the !enabled early return ('Paused'), the !status early return
+// ('Not checked yet'), the status.available truthy arm with both ternary
+// operands (latency is a number vs not), and the status.available falsy arm
+// with both || operands (trimmed lastError vs 'Offline' fallback).
+
+describe('getAvailabilityTargetStatusLabel', () => {
+ it("returns 'Paused' when the target is disabled (!enabled arm)", () => {
+ expect(getAvailabilityTargetStatusLabel(target({ enabled: false }))).toBe('Paused');
+ });
+
+ it("returns 'Not checked yet' when enabled but status is absent (!status arm)", () => {
+ expect(getAvailabilityTargetStatusLabel(target())).toBe('Not checked yet');
+ });
+
+ it("returns 'Online' without latency when latencyMillis is undefined (ternary else arm)", () => {
+ expect(
+ getAvailabilityTargetStatusLabel(
+ target({ status: status({ available: true, latencyMillis: undefined }) }),
+ ),
+ ).toBe('Online');
+ });
+
+ it("returns 'Online' when latencyMillis is a non-number value (defensive typeof branch via cast)", () => {
+ expect(
+ getAvailabilityTargetStatusLabel(
+ target({
+ status: status({
+ available: true,
+ latencyMillis: 'fast' as unknown as number,
+ }),
+ }),
+ ),
+ ).toBe('Online');
+ });
+
+ it("returns the trimmed lastError for an unavailable target with one (|| left operand)", () => {
+ expect(
+ getAvailabilityTargetStatusLabel(
+ target({
+ status: status({ available: false, lastError: ' connection refused ' }),
+ }),
+ ),
+ ).toBe('connection refused');
+ });
+
+ it("returns 'Offline' for an unavailable target with no lastError (|| right operand)", () => {
+ expect(
+ getAvailabilityTargetStatusLabel(
+ target({ status: status({ available: false, lastError: undefined }) }),
+ ),
+ ).toBe('Offline');
+ });
+
+ it("returns 'Offline' when lastError trims to empty (|| right operand via whitespace)", () => {
+ expect(
+ getAvailabilityTargetStatusLabel(
+ target({ status: status({ available: false, lastError: ' ' }) }),
+ ),
+ ).toBe('Offline');
+ });
+});
+
+// ---- getAvailabilityTargetKindLabel ----------------------------------------
+// Branches: every switch arm. The sibling test already covers 'machine' and the
+// undefined arm; here we cover 'device', the explicit 'service' case, and the
+// default arm (only reachable via a cast, since targetKind is typed).
+
+describe('getAvailabilityTargetKindLabel', () => {
+ it("labels a device target as 'Device'", () => {
+ expect(getAvailabilityTargetKindLabel(target({ targetKind: 'device' }))).toBe('Device');
+ });
+
+ it("labels an explicit service target as 'Service'", () => {
+ expect(getAvailabilityTargetKindLabel(target({ targetKind: 'service' }))).toBe('Service');
+ });
+
+ it("labels an unrecognised kind as 'Endpoint' (default switch arm via cast)", () => {
+ expect(
+ getAvailabilityTargetKindLabel(
+ target({ targetKind: 'website' as unknown as AvailabilityTarget['targetKind'] }),
+ ),
+ ).toBe('Endpoint');
+ });
+});
+
+// ---- getAvailabilityTargetAddressLabel -------------------------------------
+// Branches: the http path-join body with both ternary arms (path already starts
+// with '/' vs needing one prepended), the endsWith guard (skip join), the
+// path?.trim() falsy arm (undefined / whitespace), the tcp-with-port arm, and
+// the final fallback arm (icmp / https / tcp-without-port).
+
+describe('getAvailabilityTargetAddressLabel', () => {
+ it("prepends a leading slash to an http path that lacks one (ternary else arm)", () => {
+ expect(
+ getAvailabilityTargetAddressLabel(
+ target({ protocol: 'http', address: 'http://api.local', path: 'v1/health' }),
+ ),
+ ).toBe('http://api.local/v1/health');
+ });
+
+ it("returns the address verbatim when it already ends with the path (endsWith guard)", () => {
+ expect(
+ getAvailabilityTargetAddressLabel(
+ target({ protocol: 'http', address: 'http://api.local/health', path: '/health' }),
+ ),
+ ).toBe('http://api.local/health');
+ });
+
+ it("returns the address verbatim for http when path is undefined (path falsy arm)", () => {
+ expect(
+ getAvailabilityTargetAddressLabel(
+ target({ protocol: 'http', address: 'http://api.local', path: undefined }),
+ ),
+ ).toBe('http://api.local');
+ });
+
+ it("returns the address verbatim for http when path is whitespace-only (trim -> falsy arm)", () => {
+ expect(
+ getAvailabilityTargetAddressLabel(
+ target({ protocol: 'http', address: 'http://api.local', path: ' ' }),
+ ),
+ ).toBe('http://api.local');
+ });
+
+ it('strips multiple trailing slashes before joining an http path', () => {
+ expect(
+ getAvailabilityTargetAddressLabel(
+ target({ protocol: 'http', address: 'http://api.local///', path: '/health' }),
+ ),
+ ).toBe('http://api.local/health');
+ });
+
+ it("returns the address verbatim for tcp without a port (port falsy arm)", () => {
+ expect(
+ getAvailabilityTargetAddressLabel(
+ target({ protocol: 'tcp', address: 'mqtt.local', port: undefined }),
+ ),
+ ).toBe('mqtt.local');
+ });
+
+ it("returns the address verbatim for icmp (final fallback arm)", () => {
+ expect(
+ getAvailabilityTargetAddressLabel(
+ target({ protocol: 'icmp', address: '10.0.0.1', port: undefined }),
+ ),
+ ).toBe('10.0.0.1');
+ });
+
+ it("returns the address verbatim for https (final fallback arm; no https special-case)", () => {
+ expect(
+ getAvailabilityTargetAddressLabel(
+ target({ protocol: 'https', address: 'https://api.local', path: '/health' }),
+ ),
+ ).toBe('https://api.local');
+ });
+});
+
+// ---- getAvailabilityTargetMethodLabel --------------------------------------
+// Branches: every switch arm. The sibling test covers 'icmp' and tcp-with-port;
+// here we cover the tcp-without-port arm (both via undefined and 0), 'http',
+// and the default arm (https plus an arbitrary protocol string via cast).
+
+describe('getAvailabilityTargetMethodLabel', () => {
+ it("returns 'TCP port' for a tcp target without a port (port falsy arm)", () => {
+ expect(getAvailabilityTargetMethodLabel(target({ protocol: 'tcp', port: undefined }))).toBe(
+ 'TCP port',
+ );
+ });
+
+ it("returns 'TCP port' for a tcp target whose port is 0 (port falsy arm via 0)", () => {
+ expect(getAvailabilityTargetMethodLabel(target({ protocol: 'tcp', port: 0 }))).toBe('TCP port');
+ });
+
+ it("returns 'HTTP check' for an http target", () => {
+ expect(getAvailabilityTargetMethodLabel(target({ protocol: 'http' }))).toBe('HTTP check');
+ });
+
+ it("uppercases an unrecognised but valid protocol via the default arm (https)", () => {
+ expect(getAvailabilityTargetMethodLabel(target({ protocol: 'https' }))).toBe('HTTPS');
+ });
+
+ it("uppercases an arbitrary protocol string via the default arm (cast)", () => {
+ expect(
+ getAvailabilityTargetMethodLabel(
+ target({ protocol: 'grpc' as unknown as AvailabilityTarget['protocol'] }),
+ ),
+ ).toBe('GRPC');
+ });
+});
+
+// ---- getAvailabilityTargetAddKind ------------------------------------------
+// Branches: the !shouldOpenAvailabilityTargetAddDialog guard (undefined) reached
+// via a wrong pathname, a missing/wrong add param, and an unnormalisable
+// targetKind; and the normalise arm returning each valid kind, plus
+// case/whitespace normalisation and the trailing-slash pathname variant.
+
+describe('getAvailabilityTargetAddKind', () => {
+ it('returns undefined when the pathname is not the availability settings path (guard)', () => {
+ expect(
+ getAvailabilityTargetAddKind('/settings/infrastructure', '?add=target&targetKind=machine'),
+ ).toBeUndefined();
+ });
+
+ it('returns undefined when the add query param is missing or wrong (guard)', () => {
+ expect(
+ getAvailabilityTargetAddKind('/settings/monitoring/availability', '?targetKind=machine'),
+ ).toBeUndefined();
+ expect(
+ getAvailabilityTargetAddKind('/settings/monitoring/availability', '?add=other'),
+ ).toBeUndefined();
+ });
+
+ it("returns undefined when the targetKind param does not normalise to a known kind (invalid kind guard)", () => {
+ expect(
+ getAvailabilityTargetAddKind(
+ '/settings/monitoring/availability',
+ '?add=target&targetKind=vm',
+ ),
+ ).toBeUndefined();
+ });
+
+ it("returns the normalised kind for 'service'", () => {
+ expect(
+ getAvailabilityTargetAddKind(
+ '/settings/monitoring/availability',
+ '?add=target&targetKind=service',
+ ),
+ ).toBe('service');
+ });
+
+ it("returns the normalised kind for 'device'", () => {
+ expect(
+ getAvailabilityTargetAddKind(
+ '/settings/monitoring/availability',
+ '?add=target&targetKind=device',
+ ),
+ ).toBe('device');
+ });
+
+ it('normalises case and surrounding whitespace on the targetKind param', () => {
+ // URLSearchParams decodes '+' as space, so '+Device+' parses to ' Device '.
+ expect(
+ getAvailabilityTargetAddKind(
+ '/settings/monitoring/availability',
+ '?add=target&targetKind=+Device+',
+ ),
+ ).toBe('device');
+ });
+
+ it('honours the trailing-slash pathname variant', () => {
+ expect(
+ getAvailabilityTargetAddKind(
+ '/settings/monitoring/availability/',
+ '?add=target&targetKind=service',
+ ),
+ ).toBe('service');
+ });
+});
diff --git a/frontend-modern/src/components/Settings/__tests__/diagnosticsModel.branchcov2.test.ts b/frontend-modern/src/components/Settings/__tests__/diagnosticsModel.branchcov2.test.ts
new file mode 100644
index 0000000000..61698afcb5
--- /dev/null
+++ b/frontend-modern/src/components/Settings/__tests__/diagnosticsModel.branchcov2.test.ts
@@ -0,0 +1,602 @@
+/**
+ * Branch-coverage tests for the still-uncovered named helpers in
+ * diagnosticsModel:
+ * sanitizeDiagnosticsData, formatUptime.
+ *
+ * Every if/else, ternary, optional-chain (`?.`), `Array.isArray` guard and
+ * regex alternation arm in each function is driven with a concrete input and
+ * asserted against the exact emitted shape (no truthiness-only checks).
+ *
+ * Import path mirrors the sibling `diagnosticsModel.test.ts` (alias `@/...`).
+ */
+import { describe, expect, it } from 'vitest';
+import {
+ formatUptime,
+ sanitizeDiagnosticsData,
+ type DiagnosticsData,
+} from '@/components/Settings/diagnosticsModel';
+
+// The helper also sanitizes a few arrays that are intentionally NOT part of the
+// typed DiagnosticsData surface (see diagnosticsModel.ts:261-286) and a couple
+// of untyped sub-fields (apiTokens.tokens/usage, dockerAgents.attention).
+// These aliases surface them so the test can build inputs and assert outputs.
+type ApiTokensDiagnosticWithExtras = NonNullable<DiagnosticsData['apiTokens']> & {
+ tokens?: Array<Record<string, unknown>>;
+ usage?: Array<Record<string, unknown>>;
+};
+
+type DockerAgentsDiagnosticWithExtras = NonNullable<DiagnosticsData['dockerAgents']> & {
+ attention?: Array<Record<string, unknown>>;
+};
+
+type DiagnosticsDataWithSnapshots = DiagnosticsData & {
+ nodeSnapshots?: Array<Record<string, unknown>>;
+ guestSnapshots?: Array<Record<string, unknown>>;
+ memorySources?: Array<Record<string, unknown>>;
+};
+
+// Minimal valid base — every test spreads this then overrides only the field(s)
+// needed to drive the branch under test.
+const baseData = (): DiagnosticsDataWithSnapshots => ({
+ version: '6.0.0',
+ runtime: 'go',
+ uptime: 0,
+ nodes: [],
+ pbs: [],
+ system: {
+ os: 'linux',
+ arch: 'amd64',
+ goVersion: 'go1.25',
+ numCPU: 8,
+ numGoroutine: 32,
+ memoryMB: 128,
+ },
+ errors: [],
+});
+
+// ---- formatUptime -----------------------------------------------------------
+
+describe('formatUptime', () => {
+ it('formats the sub-minute arm as "<n>s" (seconds < 60)', () => {
+ expect(formatUptime(0)).toBe('0s');
+ expect(formatUptime(45)).toBe('45s');
+ expect(formatUptime(59)).toBe('59s');
+ });
+
+ it('formats the minute+second arm for 60 <= seconds < 3600', () => {
+ expect(formatUptime(60)).toBe('1m 0s');
+ expect(formatUptime(125)).toBe('2m 5s');
+ expect(formatUptime(3599)).toBe('59m 59s');
+ });
+
+ it('formats the hours+minutes arm for 3600 <= seconds < 86400 (hours < 24)', () => {
+ expect(formatUptime(3600)).toBe('1h 0m');
+ expect(formatUptime(3660)).toBe('1h 1m');
+ expect(formatUptime(86399)).toBe('23h 59m');
+ });
+
+ it('formats the days+hours arm for seconds >= 86400 (hours >= 24)', () => {
+ expect(formatUptime(86400)).toBe('1d 0h');
+ expect(formatUptime(90000)).toBe('1d 1h');
+ expect(formatUptime(172800)).toBe('2d 0h');
+ });
+});
+
+// ---- sanitizeDiagnosticsData / nodes ---------------------------------------
+
+describe('sanitizeDiagnosticsData / nodes', () => {
+ it('overwrites host/name/id with positional placeholders and redacts IPs in node.error', () => {
+ const sanitized = sanitizeDiagnosticsData({
+ ...baseData(),
+ nodes: [
+ {
+ id: 'raw-id',
+ name: 'pve-01',
+ host: '10.0.0.5',
+ type: 'pve',
+ authMethod: 'token',
+ connected: true,
+ error: 'dial tcp 10.0.0.5:8006 failed',
+ },
+ ],
+ });
+
+ expect(sanitized.nodes).toStrictEqual([
+ {
+ id: 'node-1',
+ name: 'node-1',
+ host: 'node-1',
+ type: 'pve',
+ authMethod: 'token',
+ connected: true,
+ error: 'dial tcp [REDACTED_IP]:8006 failed',
+ },
+ ]);
+ });
+
+ it('sets error to undefined when a node has no error (else arm of the error ternary)', () => {
+ const sanitized = sanitizeDiagnosticsData({
+ ...baseData(),
+ nodes: [
+ {
+ id: 'raw',
+ name: 'pve-02',
+ host: '10.0.0.6',
+ type: 'pve',
+ authMethod: 'token',
+ connected: true,
+ },
+ ],
+ });
+
+ expect(sanitized.nodes[0]).toStrictEqual({
+ id: 'node-1',
+ name: 'node-1',
+ host: 'node-1',
+ type: 'pve',
+ authMethod: 'token',
+ connected: true,
+ error: undefined,
+ });
+ });
+
+ it('handles an empty nodes array (Array.isArray true, map yields [])', () => {
+ const sanitized = sanitizeDiagnosticsData({ ...baseData(), nodes: [] });
+ expect(sanitized.nodes).toStrictEqual([]);
+ });
+
+ it('redacts multiple IPs and the CIDR-suffix arm of the regex in a single error', () => {
+ const sanitized = sanitizeDiagnosticsData({
+ ...baseData(),
+ nodes: [
+ {
+ id: 'x',
+ name: 'x',
+ host: '1.2.3.4',
+ type: 'pve',
+ authMethod: 'token',
+ connected: false,
+ error: 'scan 10.0.0.0/24 then 10.0.0.5 and 192.168.1.1/32',
+ },
+ ],
+ });
+
+ expect(sanitized.nodes[0].error).toBe(
+ 'scan [REDACTED_IP] then [REDACTED_IP] and [REDACTED_IP]',
+ );
+ });
+});
+
+// ---- sanitizeDiagnosticsData / pbs -----------------------------------------
+
+describe('sanitizeDiagnosticsData / pbs', () => {
+ it('overwrites host/name/id with pbs-N placeholders and redacts IPs in pbs.error', () => {
+ const sanitized = sanitizeDiagnosticsData({
+ ...baseData(),
+ pbs: [
+ {
+ id: 'pbs-raw',
+ name: 'pbs-01',
+ host: '10.0.0.15',
+ connected: false,
+ error: 'Get https://10.0.0.15:8007: EOF',
+ },
+ ],
+ });
+
+ expect(sanitized.pbs).toStrictEqual([
+ {
+ id: 'pbs-1',
+ name: 'pbs-1',
+ host: 'pbs-1',
+ connected: false,
+ error: 'Get https://[REDACTED_IP]:8007: EOF',
+ },
+ ]);
+ });
+
+ it('sets error to undefined when a pbs has no error (else arm of the error ternary)', () => {
+ const sanitized = sanitizeDiagnosticsData({
+ ...baseData(),
+ pbs: [{ id: 'r', name: 'p', host: '10.0.0.16', connected: true }],
+ });
+
+ expect(sanitized.pbs[0]).toStrictEqual({
+ id: 'pbs-1',
+ name: 'pbs-1',
+ host: 'pbs-1',
+ connected: true,
+ error: undefined,
+ });
+ });
+});
+
+// ---- sanitizeDiagnosticsData / discovery -----------------------------------
+
+describe('sanitizeDiagnosticsData / discovery', () => {
+ it('leaves discovery undefined when absent (top-level guard false)', () => {
+ const sanitized = sanitizeDiagnosticsData({ ...baseData() });
+ expect(sanitized.discovery).toBeUndefined();
+ });
+
+ it('collapses every falsy subnet field to undefined and skips the optional-chain maps when the arrays are absent', () => {
+ const sanitized = sanitizeDiagnosticsData({
+ ...baseData(),
+ discovery: { enabled: true },
+ });
+
+ expect(sanitized.discovery).toStrictEqual({
+ enabled: true,
+ configuredSubnet: undefined,
+ activeSubnet: undefined,
+ environmentOverride: undefined,
+ subnetAllowlist: undefined,
+ subnetBlocklist: undefined,
+ });
+ });
+
+ it('preserves empty arrays through the optional-chain map (?. on [] returns [])', () => {
+ const sanitized = sanitizeDiagnosticsData({
+ ...baseData(),
+ discovery: { enabled: true, subnetAllowlist: [], subnetBlocklist: [] },
+ });
+
+ expect(sanitized.discovery?.subnetAllowlist).toStrictEqual([]);
+ expect(sanitized.discovery?.subnetBlocklist).toStrictEqual([]);
+ });
+
+ it('redacts every populated subnet/environment field (truthy ternary arms)', () => {
+ const sanitized = sanitizeDiagnosticsData({
+ ...baseData(),
+ discovery: {
+ enabled: true,
+ configuredSubnet: '10.0.0.0/24',
+ activeSubnet: '10.0.1.0/24',
+ environmentOverride: 'PULSE_DISCOVERY_SUBNET=10.0.2.0/24',
+ subnetAllowlist: ['10.0.0.0/24', '10.0.4.0/24'],
+ subnetBlocklist: ['10.0.3.0/24'],
+ },
+ });
+
+ expect(sanitized.discovery).toStrictEqual({
+ enabled: true,
+ configuredSubnet: '[REDACTED_SUBNET]',
+ activeSubnet: '[REDACTED_SUBNET]',
+ environmentOverride: '[REDACTED]',
+ subnetAllowlist: ['[REDACTED_SUBNET]', '[REDACTED_SUBNET]'],
+ subnetBlocklist: ['[REDACTED_SUBNET]'],
+ });
+ });
+
+ it('leaves history untouched when it is not an array (history guard false)', () => {
+ const sanitized = sanitizeDiagnosticsData({
+ ...baseData(),
+ discovery: {
+ enabled: true,
+ history: 'not-an-array',
+ } as unknown as DiagnosticsData['discovery'],
+ });
+
+ expect((sanitized.discovery as { history?: unknown }).history).toBe('not-an-array');
+ });
+
+ it('overwrites the subnet of every history entry (history guard true)', () => {
+ const sanitized = sanitizeDiagnosticsData({
+ ...baseData(),
+ discovery: {
+ enabled: true,
+ history: [
+ { subnet: '10.0.0.0/24', status: 'completed', serverCount: 3 },
+ { subnet: '10.0.1.0/24', status: 'failed', errorCount: 2 },
+ ],
+ },
+ });
+
+ expect(sanitized.discovery?.history).toStrictEqual([
+ { subnet: '[REDACTED_SUBNET]', status: 'completed', serverCount: 3 },
+ { subnet: '[REDACTED_SUBNET]', status: 'failed', errorCount: 2 },
+ ]);
+ });
+});
+
+// ---- sanitizeDiagnosticsData / apiTokens -----------------------------------
+
+describe('sanitizeDiagnosticsData / apiTokens', () => {
+ it('skips the apiTokens block entirely when apiTokens is absent (top guard false)', () => {
+ const sanitized = sanitizeDiagnosticsData({ ...baseData() });
+ expect(sanitized.apiTokens).toBeUndefined();
+ });
+
+ it('leaves apiTokens unchanged when neither tokens nor usage is an array', () => {
+ const sanitized = sanitizeDiagnosticsData({
+ ...baseData(),
+ apiTokens: {
+ enabled: true,
+ tokenCount: 2,
+ recommendTokenSetup: false,
+ unusedTokenCount: 0,
+ },
+ });
+
+ expect(sanitized.apiTokens).toStrictEqual({
+ enabled: true,
+ tokenCount: 2,
+ recommendTokenSetup: false,
+ unusedTokenCount: 0,
+ });
+ });
+
+ it('redacts token hint/name/id by position and nulls usage hosts (both Array guards true)', () => {
+ const sanitized = sanitizeDiagnosticsData({
+ ...baseData(),
+ apiTokens: {
+ enabled: true,
+ tokenCount: 2,
+ recommendTokenSetup: false,
+ tokens: [
+ { id: 'tok-aaa', name: 'Prod Token', hint: 'aaaa', extra: 'keep' },
+ { id: 'tok-bbb', name: 'Dev Token', hint: 'bbbb' },
+ ],
+ usage: [
+ { tokenId: 'tok-aaa', hosts: ['10.0.0.5', '10.0.0.6'], count: 3 },
+ { tokenId: 'tok-bbb', hosts: [], count: 0 },
+ ],
+ } as ApiTokensDiagnosticWithExtras,
+ });
+
+ const apiTokens = sanitized.apiTokens as unknown as ApiTokensDiagnosticWithExtras;
+ expect(apiTokens.tokens).toStrictEqual([
+ { id: 'token-1', name: 'token-1', hint: '[REDACTED]', extra: 'keep' },
+ { id: 'token-2', name: 'token-2', hint: '[REDACTED]' },
+ ]);
+ expect(apiTokens.usage).toStrictEqual([
+ { tokenId: 'tok-aaa', hosts: undefined, count: 3 },
+ { tokenId: 'tok-bbb', hosts: undefined, count: 0 },
+ ]);
+ });
+});
+
+// ---- sanitizeDiagnosticsData / dockerAgents --------------------------------
+
+describe('sanitizeDiagnosticsData / dockerAgents', () => {
+ it('skips the dockerAgents block entirely when dockerAgents is absent', () => {
+ const sanitized = sanitizeDiagnosticsData({ ...baseData() });
+ expect(sanitized.dockerAgents).toBeUndefined();
+ });
+
+ it('leaves dockerAgents unchanged when attention is not an array', () => {
+ const sanitized = sanitizeDiagnosticsData({
+ ...baseData(),
+ dockerAgents: {
+ agentsTotal: 3,
+ agentsOnline: 2,
+ agentsReportingVersion: 2,
+ agentsWithTokenBinding: 2,
+ agentsWithoutTokenBinding: 1,
+ agentsNeedingAttention: 1,
+ },
+ });
+
+ expect(sanitized.dockerAgents).toStrictEqual({
+ agentsTotal: 3,
+ agentsOnline: 2,
+ agentsReportingVersion: 2,
+ agentsWithTokenBinding: 2,
+ agentsWithoutTokenBinding: 1,
+ agentsNeedingAttention: 1,
+ });
+ });
+
+ it('rekeys attention entries by position and exercises both tokenHint ternary arms', () => {
+ const sanitized = sanitizeDiagnosticsData({
+ ...baseData(),
+ dockerAgents: {
+ agentsTotal: 3,
+ agentsOnline: 2,
+ agentsReportingVersion: 2,
+ agentsWithTokenBinding: 2,
+ agentsWithoutTokenBinding: 1,
+ agentsNeedingAttention: 2,
+ attention: [
+ {
+ agentId: 'agent-7',
+ name: 'docker-prod-01',
+ tokenHint: 'deadbeef',
+ reason: 'stale',
+ },
+ { agentId: 'agent-9', name: 'docker-dev-02', reason: 'offline' },
+ ],
+ } as DockerAgentsDiagnosticWithExtras,
+ });
+
+ const attention = (
+ sanitized.dockerAgents as unknown as DockerAgentsDiagnosticWithExtras
+ ).attention;
+ expect(attention).toStrictEqual([
+ {
+ agentId: 'docker-host-1',
+ name: 'docker-host-1',
+ tokenHint: '[REDACTED]',
+ reason: 'stale',
+ },
+ {
+ agentId: 'docker-host-2',
+ name: 'docker-host-2',
+ reason: 'offline',
+ tokenHint: undefined,
+ },
+ ]);
+ });
+});
+
+// ---- sanitizeDiagnosticsData / aiChat --------------------------------------
+
+describe('sanitizeDiagnosticsData / aiChat', () => {
+ it('redacts aiChat.url when present (truthy optional-chain guard)', () => {
+ const sanitized = sanitizeDiagnosticsData({
+ ...baseData(),
+ aiChat: {
+ enabled: true,
+ running: true,
+ healthy: true,
+ assistantRuntimeConnected: true,
+ url: 'http://10.0.0.5:11434',
+ model: 'gpt',
+ },
+ });
+
+ expect(sanitized.aiChat?.url).toBe('[REDACTED]');
+ expect(sanitized.aiChat?.model).toBe('gpt');
+ });
+
+ it('leaves aiChat untouched when url is absent (optional-chain guard false)', () => {
+ const sanitized = sanitizeDiagnosticsData({
+ ...baseData(),
+ aiChat: {
+ enabled: true,
+ running: false,
+ healthy: false,
+ assistantRuntimeConnected: false,
+ },
+ });
+
+ expect(sanitized.aiChat?.url).toBeUndefined();
+ expect(sanitized.aiChat).toStrictEqual({
+ enabled: true,
+ running: false,
+ healthy: false,
+ assistantRuntimeConnected: false,
+ });
+ });
+});
+
+// ---- sanitizeDiagnosticsData / alerts --------------------------------------
+
+describe('sanitizeDiagnosticsData / alerts', () => {
+ it('skips the alerts block entirely when alerts is absent (guard false)', () => {
+ const sanitized = sanitizeDiagnosticsData({ ...baseData() });
+ expect(sanitized.alerts).toBeUndefined();
+ });
+
+ it('keeps alerts but skips the overrides map when overrides is not an array', () => {
+ const sanitized = sanitizeDiagnosticsData({
+ ...baseData(),
+ alerts: { missingCooldown: true, missingGroupingWindow: false },
+ });
+
+ expect(sanitized.alerts).toStrictEqual({
+ missingCooldown: true,
+ missingGroupingWindow: false,
+ });
+ });
+
+ it('rekeys every override by position (overrides guard true)', () => {
+ const sanitized = sanitizeDiagnosticsData({
+ ...baseData(),
+ alerts: {
+ missingCooldown: false,
+ missingGroupingWindow: false,
+ overrides: [
+ { key: 'pve5-ceph', thresholds: { usage: 50 } },
+ { key: 'pve5-101', disabled: true },
+ ],
+ },
+ });
+
+ expect(sanitized.alerts?.overrides).toStrictEqual([
+ { key: 'override-1', thresholds: { usage: 50 } },
+ { key: 'override-2', disabled: true },
+ ]);
+ });
+});
+
+// ---- sanitizeDiagnosticsData / errors --------------------------------------
+
+describe('sanitizeDiagnosticsData / errors', () => {
+ it('leaves errors untouched when errors is not an array (Array.isArray false)', () => {
+ const sanitized = sanitizeDiagnosticsData({
+ ...baseData(),
+ errors: 'oops' as unknown as DiagnosticsData['errors'],
+ });
+
+ expect(sanitized.errors as unknown as string).toBe('oops');
+ });
+
+ it('redacts bare IPs and the CIDR-suffix arm across every error string', () => {
+ const sanitized = sanitizeDiagnosticsData({
+ ...baseData(),
+ errors: [
+ 'probe failed for 10.0.0.10 after timeout',
+ 'cidr scan 10.0.0.0/24 rejected',
+ 'no ip here',
+ ],
+ });
+
+ expect(sanitized.errors).toStrictEqual([
+ 'probe failed for [REDACTED_IP] after timeout',
+ 'cidr scan [REDACTED_IP] rejected',
+ 'no ip here',
+ ]);
+ });
+});
+
+// ---- sanitizeDiagnosticsData / snapshot arrays -----------------------------
+
+describe('sanitizeDiagnosticsData / snapshot arrays', () => {
+ it('stamps an instance placeholder on every nodeSnapshots entry', () => {
+ const sanitized = sanitizeDiagnosticsData({
+ ...baseData(),
+ nodeSnapshots: [
+ { instance: '10.0.0.5', cpu: 0.4 },
+ { instance: '10.0.0.6', mem: 8192 },
+ ],
+ } as DiagnosticsDataWithSnapshots);
+
+ const out = sanitized as unknown as DiagnosticsDataWithSnapshots;
+ expect(out.nodeSnapshots).toStrictEqual([
+ { instance: 'node-1', cpu: 0.4 },
+ { instance: 'node-2', mem: 8192 },
+ ]);
+ });
+
+ it('stamps an instance placeholder on every guestSnapshots entry', () => {
+ const sanitized = sanitizeDiagnosticsData({
+ ...baseData(),
+ guestSnapshots: [{ instance: 'vm-100', status: 'running' }],
+ } as DiagnosticsDataWithSnapshots);
+
+ const out = sanitized as unknown as DiagnosticsDataWithSnapshots;
+ expect(out.guestSnapshots).toStrictEqual([
+ { instance: 'node-1', status: 'running' },
+ ]);
+ });
+
+ it('stamps an instance placeholder on every memorySources entry', () => {
+ const sanitized = sanitizeDiagnosticsData({
+ ...baseData(),
+ memorySources: [{ instance: '10.0.0.7', source: 'balloon' }],
+ } as DiagnosticsDataWithSnapshots);
+
+ const out = sanitized as unknown as DiagnosticsDataWithSnapshots;
+ expect(out.memorySources).toStrictEqual([
+ { instance: 'node-1', source: 'balloon' },
+ ]);
+ });
+});
+
+// ---- sanitizeDiagnosticsData / defensive Array.isArray guards --------------
+
+describe('sanitizeDiagnosticsData / defensive guards', () => {
+ it('leaves nodes/pbs in place when they are not arrays (Array.isArray false arms)', () => {
+ const sanitized = sanitizeDiagnosticsData({
+ ...baseData(),
+ nodes: 'not-array' as unknown as DiagnosticsData['nodes'],
+ pbs: null as unknown as DiagnosticsData['pbs'],
+ errors: 42 as unknown as DiagnosticsData['errors'],
+ });
+
+ expect(sanitized.nodes as unknown as string).toBe('not-array');
+ expect(sanitized.pbs).toBeNull();
+ expect(sanitized.errors as unknown as number).toBe(42);
+ });
+});
diff --git a/frontend-modern/src/components/Settings/__tests__/infrastructureSettingsModel.branchcov2.test.ts b/frontend-modern/src/components/Settings/__tests__/infrastructureSettingsModel.branchcov2.test.ts
new file mode 100644
index 0000000000..ace0169fc7
--- /dev/null
+++ b/frontend-modern/src/components/Settings/__tests__/infrastructureSettingsModel.branchcov2.test.ts
@@ -0,0 +1,394 @@
+/**
+ * Branch-coverage tests for the still-uncovered named helpers in
+ * infrastructureSettingsModel:
+ * normalizeInfrastructureHost, collectRepresentedDiscoveryHosts,
+ * filterRepresentedDiscoveredServers, addClusterEndpointHosts,
+ * matchConfiguredNodeToResource.
+ *
+ * `addClusterEndpointHosts` is module-private, so its branches are driven
+ * indirectly through the exported `collectRepresentedDiscoveryHosts` (the only
+ * call site) by passing `pve` nodes that carry `clusterEndpoints`.
+ *
+ * Every if/else arm, optional-chain, `??`, regex branch and early-return is
+ * exercised with concrete inputs and asserted against the exact emitted shape
+ * (no truthiness-only checks).
+ */
+import { describe, expect, it } from 'vitest';
+
+import type { ClusterEndpoint, NodeConfigWithStatus } from '@/types/nodes';
+import type { Resource } from '@/types/resource';
+
+import {
+ collectRepresentedDiscoveryHosts,
+ filterRepresentedDiscoveredServers,
+ matchConfiguredNodeToResource,
+ normalizeInfrastructureHost,
+} from '../infrastructureSettingsModel';
+
+// ---- Fixtures ---------------------------------------------------------------
+
+/**
+ * Build a minimal `NodeConfigWithStatus`. The helpers under test only read
+ * `id`, `name`, `type`, `host`, `guestURL` and (optionally) `clusterEndpoints`,
+ * so a partial object cast through `unknown` is sufficient and keeps the tests
+ * focused on the branches rather than full node construction.
+ */
+const makeNode = (overrides: Record<string, unknown>): NodeConfigWithStatus =>
+ ({
+ id: 'node-id',
+ name: 'node-name',
+ type: 'pve',
+ host: undefined,
+ guestURL: undefined,
+ ...overrides,
+ }) as unknown as NodeConfigWithStatus;
+
+/** Minimal `Resource` carrying only the identity fields the matcher reads. */
+const makeResource = (id: string, name: string): Resource =>
+ ({ id, name }) as unknown as Resource;
+
+/** A fully-populated `ClusterEndpoint` with overridable fields. */
+const makeEndpoint = (overrides: Partial<ClusterEndpoint> = {}): ClusterEndpoint => ({
+ nodeId: 'node-1',
+ nodeName: 'node-1',
+ host: 'host.local',
+ ip: '127.0.0.1',
+ online: true,
+ lastSeen: '2026-01-01T00:00:00Z',
+ ...overrides,
+});
+
+// ---- normalizeInfrastructureHost -------------------------------------------
+
+describe('normalizeInfrastructureHost', () => {
+ it('returns null for undefined input (optional-chain + empty-trimmed arm)', () => {
+ expect(normalizeInfrastructureHost(undefined)).toBeNull();
+ });
+
+ it('returns null for null input', () => {
+ expect(normalizeInfrastructureHost(null)).toBeNull();
+ });
+
+ it('returns null for an empty string', () => {
+ expect(normalizeInfrastructureHost('')).toBeNull();
+ });
+
+ it('returns null for a whitespace-only string (trim produces empty)', () => {
+ expect(normalizeInfrastructureHost(' ')).toBeNull();
+ });
+
+ it('returns null for a bare scheme with no host ("http://")', () => {
+ // URL constructor throws; after stripping the scheme, withoutPath is empty.
+ expect(normalizeInfrastructureHost('http://')).toBeNull();
+ });
+
+ it('lowercases + returns the parsed hostname of a trimmed https URL, dropping port/path', () => {
+ expect(normalizeInfrastructureHost(' https://Example.COM:8006/Path ')).toBe('example.com');
+ });
+
+ it('returns the parsed hostname for an http URL with an IPv4 host', () => {
+ expect(normalizeInfrastructureHost('http://10.0.0.5:8006')).toBe('10.0.0.5');
+ });
+
+ it('falls through to string heuristics when a URL parses but has no hostname', () => {
+ // "foo:bar" is a valid non-special-scheme URL with an empty hostname, so
+ // the `parsed.hostname` arm is skipped; the heuristic then returns the
+ // whole string lowercased (no "://" to strip, no port to drop).
+ expect(normalizeInfrastructureHost('foo:bar')).toBe('foo:bar');
+ });
+
+ it('extracts a bare IPv4 address that is not a valid URL', () => {
+ expect(normalizeInfrastructureHost('192.168.1.1')).toBe('192.168.1.1');
+ });
+
+ it('strips a numeric port from a bare host via the host:port heuristic', () => {
+ expect(normalizeInfrastructureHost('192.168.1.1:8006')).toBe('192.168.1.1');
+ });
+
+ it('extracts a bracketed IPv6 address with a trailing port', () => {
+ expect(normalizeInfrastructureHost('[::1]:8006')).toBe('::1');
+ });
+
+ it('lowercases a bracketed IPv6 address with no port', () => {
+ expect(normalizeInfrastructureHost('[FE80::1]')).toBe('fe80::1');
+ });
+
+ it('keeps an unbracketed IPv6 + port whole (hostPortMatch arm rejected when capture contains ":")', () => {
+ // The hostPortMatch regex matches, but its `[1]` still contains a colon,
+ // so the guard skips it and the function falls through to returning the
+ // full string lowercased. (See GLM_REPORT.md — suspected source bug.)
+ expect(normalizeInfrastructureHost('::1:8006')).toBe('::1:8006');
+ });
+
+ it('strips a trailing path from a bare host', () => {
+ expect(normalizeInfrastructureHost('MyHost/path')).toBe('myhost');
+ });
+
+ it('lowercases a plain hostname with no scheme, port or path', () => {
+ expect(normalizeInfrastructureHost('MyHost')).toBe('myhost');
+ });
+});
+
+// ---- collectRepresentedDiscoveryHosts (+ private addClusterEndpointHosts) ---
+
+describe('collectRepresentedDiscoveryHosts', () => {
+ it('returns three empty sets when given no nodes and no rows', () => {
+ const result = collectRepresentedDiscoveryHosts([], []);
+ expect(result).toStrictEqual({
+ pve: new Set<string>(),
+ pbs: new Set<string>(),
+ pmg: new Set<string>(),
+ });
+ });
+
+ it('defaults the rows argument to empty (only nodes contribute)', () => {
+ const result = collectRepresentedDiscoveryHosts([
+ makeNode({ type: 'pbs', name: 'backupbox', host: 'https://backupbox:8007' }),
+ ]);
+ expect(result.pbs).toStrictEqual(new Set(['backupbox']));
+ expect(result.pve).toStrictEqual(new Set());
+ expect(result.pmg).toStrictEqual(new Set());
+ });
+
+ it('buckets each platform type into its own set, normalizing name + host + guestURL', () => {
+ const result = collectRepresentedDiscoveryHosts([
+ makeNode({ type: 'pve', name: 'pve-name', host: 'https://10.0.0.1:8006', guestURL: 'https://10.0.0.1:8006' }),
+ makeNode({ type: 'pbs', name: 'pbs-name', host: '10.0.0.2:8007' }),
+ makeNode({ type: 'pmg', name: 'pmg-name', host: 'pmg-host' }),
+ ]);
+ expect(result.pve).toStrictEqual(new Set(['pve-name', '10.0.0.1']));
+ expect(result.pbs).toStrictEqual(new Set(['pbs-name', '10.0.0.2']));
+ expect(result.pmg).toStrictEqual(new Set(['pmg-name', 'pmg-host']));
+ });
+
+ it('does not invoke cluster aggregation for a pve node missing the clusterEndpoints key', () => {
+ // `'clusterEndpoints' in node` is false → addClusterEndpointHosts is never
+ // called; only name/host/guestURL contribute.
+ const result = collectRepresentedDiscoveryHosts([
+ makeNode({ type: 'pve', name: 'standalone', host: 'https://10.0.0.50:8006' }),
+ ]);
+ // name 'standalone' + normalized host '10.0.0.50'; no cluster contribution.
+ expect(result.pve).toStrictEqual(new Set(['standalone', '10.0.0.50']));
+ });
+
+ it('no-ops cluster aggregation when clusterEndpoints is explicitly undefined (addClusterEndpointHosts undefined arm)', () => {
+ const result = collectRepresentedDiscoveryHosts([
+ makeNode({ type: 'pve', name: 'cluster', host: 'https://primary:8006', clusterEndpoints: undefined }),
+ ]);
+ // `'clusterEndpoints' in node` is true, but `endpoints?.forEach` is a no-op.
+ expect(result.pve).toStrictEqual(new Set(['cluster', 'primary']));
+ });
+
+ it('no-ops cluster aggregation when clusterEndpoints is an empty array', () => {
+ const result = collectRepresentedDiscoveryHosts([
+ makeNode({ type: 'pve', name: 'cluster', host: 'https://primary:8006', clusterEndpoints: [] }),
+ ]);
+ expect(result.pve).toStrictEqual(new Set(['cluster', 'primary']));
+ });
+
+ it('aggregates every cluster-endpoint host alias into the pve bucket (addClusterEndpointHosts populated arm)', () => {
+ const result = collectRepresentedDiscoveryHosts([
+ makeNode({
+ type: 'pve',
+ name: 'cluster',
+ host: 'https://primary:8006',
+ guestURL: 'https://primary:8006',
+ clusterEndpoints: [
+ makeEndpoint({
+ nodeId: 'id-alpha',
+ nodeName: 'alpha',
+ host: 'alpha.local',
+ ip: '10.0.0.11',
+ guestURL: 'https://alpha:8006',
+ }),
+ makeEndpoint({
+ nodeName: 'beta',
+ host: 'beta.local',
+ ip: '10.0.0.12',
+ }),
+ ],
+ }),
+ ]);
+
+ // Node-level: name + normalized host/guestURL host.
+ // Endpoint alpha: ip, host, guestURL-host, nodeName, nodeId.
+ // Endpoint beta: ip, host, nodeName, default nodeId ('node-1'); guestURL
+ // is undefined and is dropped by normalize→null.
+ expect(result.pve).toStrictEqual(
+ new Set([
+ 'cluster',
+ 'primary',
+ '10.0.0.11',
+ 'alpha.local',
+ 'alpha',
+ 'id-alpha',
+ '10.0.0.12',
+ 'beta.local',
+ 'beta',
+ 'node-1',
+ ]),
+ );
+ expect(result.pbs).toStrictEqual(new Set());
+ expect(result.pmg).toStrictEqual(new Set());
+ });
+
+ it('keeps cluster endpoints out of non-pve node types (short-circuit of the pve guard)', () => {
+ // A pbs node cannot carry clusterEndpoints in its type, but even if a
+ // malformed input does, the `node.type === 'pve' &&` guard skips it.
+ const result = collectRepresentedDiscoveryHosts([
+ makeNode({
+ type: 'pbs',
+ name: 'backup',
+ host: 'https://backup:8007',
+ clusterEndpoints: [makeEndpoint({ ip: '10.0.0.99', nodeName: 'should-not-appear' })],
+ }),
+ ]);
+ expect(result.pbs).toStrictEqual(new Set(['backup']));
+ expect(result.pve).toStrictEqual(new Set());
+ });
+});
+
+// ---- filterRepresentedDiscoveredServers ------------------------------------
+
+describe('filterRepresentedDiscoveredServers', () => {
+ it('removes a server whose normalized IP is represented by a configured node (IP arm)', () => {
+ const nodes = [makeNode({ type: 'pve', name: 'pve-node', host: 'https://10.0.0.5:8006' })];
+ const filtered = filterRepresentedDiscoveredServers(
+ [
+ { ip: '10.0.0.5', port: 8006, type: 'pve', version: '8.2.2' },
+ { ip: '10.0.0.99', port: 8006, type: 'pve', version: '8.2.2' },
+ ],
+ nodes,
+ );
+ expect(filtered).toEqual([
+ { ip: '10.0.0.99', port: 8006, type: 'pve', version: '8.2.2' },
+ ]);
+ });
+
+ it('removes a server whose hostname is represented even when its IP is not (hostname arm)', () => {
+ const nodes = [makeNode({ type: 'pve', name: 'proxmox', host: 'https://proxmox:8006' })];
+ const filtered = filterRepresentedDiscoveredServers(
+ [{ ip: '10.0.0.5', port: 8006, type: 'pve', version: '8.2.2', hostname: 'proxmox' }],
+ nodes,
+ );
+ expect(filtered).toEqual([]);
+ });
+
+ it('keeps a server whose IP and hostname are both unrepresented', () => {
+ const nodes = [makeNode({ type: 'pve', name: 'pve-node', host: 'https://10.0.0.5:8006' })];
+ const filtered = filterRepresentedDiscoveredServers(
+ [{ ip: '10.0.0.99', port: 8006, type: 'pve', version: '8.2.2', hostname: 'other' }],
+ nodes,
+ );
+ expect(filtered).toEqual([
+ { ip: '10.0.0.99', port: 8006, type: 'pve', version: '8.2.2', hostname: 'other' },
+ ]);
+ });
+
+ it('keeps a server with no hostname when its IP is unrepresented (normalizedHostname falsy arm)', () => {
+ const nodes = [makeNode({ type: 'pve', name: 'pve-node', host: 'https://10.0.0.5:8006' })];
+ const filtered = filterRepresentedDiscoveredServers(
+ [{ ip: '10.0.0.99', port: 8006, type: 'pve', version: '8.2.2' }],
+ nodes,
+ );
+ expect(filtered).toEqual([
+ { ip: '10.0.0.99', port: 8006, type: 'pve', version: '8.2.2' },
+ ]);
+ });
+
+ it('keeps a server whose IP normalizes to null when nothing represents its hostname (normalizedIP falsy arm)', () => {
+ const nodes = [makeNode({ type: 'pve', name: 'pve-node', host: 'https://10.0.0.5:8006' })];
+ const filtered = filterRepresentedDiscoveredServers(
+ [{ ip: ' ', port: 8006, type: 'pve', version: '8.2.2', hostname: 'unrepresented' }],
+ nodes,
+ );
+ expect(filtered).toEqual([
+ { ip: ' ', port: 8006, type: 'pve', version: '8.2.2', hostname: 'unrepresented' },
+ ]);
+ });
+
+ it('only matches within the same platform type (pve host does not suppress a pbs server)', () => {
+ const nodes = [makeNode({ type: 'pve', name: 'pve-node', host: 'https://10.0.0.5:8006' })];
+ const filtered = filterRepresentedDiscoveredServers(
+ [{ ip: '10.0.0.5', port: 8007, type: 'pbs', version: '3.0.1' }],
+ nodes,
+ );
+ expect(filtered).toEqual([
+ { ip: '10.0.0.5', port: 8007, type: 'pbs', version: '3.0.1' },
+ ]);
+ });
+});
+
+// ---- matchConfiguredNodeToResource -----------------------------------------
+
+describe('matchConfiguredNodeToResource', () => {
+ it('returns undefined when nodeResources is undefined', () => {
+ const result = matchConfiguredNodeToResource(
+ makeNode({ id: 'a', name: 'a' }),
+ undefined,
+ );
+ expect(result).toBeUndefined();
+ });
+
+ it('returns undefined when nodeResources is an empty array', () => {
+ const result = matchConfiguredNodeToResource(makeNode({ id: 'a', name: 'a' }), []);
+ expect(result).toBeUndefined();
+ });
+
+ it('matches when resource.id === configNode.id', () => {
+ const matched = makeResource('shared-id', 'different-name');
+ const result = matchConfiguredNodeToResource(
+ makeNode({ id: 'shared-id', name: 'config-name' }),
+ [makeResource('other', 'other'), matched],
+ );
+ expect(result).toBe(matched);
+ });
+
+ it('matches when resource.name === configNode.name (ids differ)', () => {
+ const matched = makeResource('r1', 'shared-name');
+ const result = matchConfiguredNodeToResource(
+ makeNode({ id: 'c1', name: 'shared-name' }),
+ [matched, makeResource('r2', 'other')],
+ );
+ expect(result).toBe(matched);
+ });
+
+ it('matches when the ".lan"-stripped name bases are equal', () => {
+ // configNode.name 'host.lan' and resource.name 'host' differ literally and
+ // by id, but both strip to 'host'.
+ const matched = makeResource('r1', 'host');
+ const result = matchConfiguredNodeToResource(
+ makeNode({ id: 'c1', name: 'host.lan' }),
+ [matched],
+ );
+ expect(result).toBe(matched);
+ });
+
+ it('matches when resource.id contains configNode.name', () => {
+ // id 'prefix-sub-suffix' includes 'sub'; names differ; bases differ.
+ const matched = makeResource('prefix-sub-suffix', 'unrelated');
+ const result = matchConfiguredNodeToResource(
+ makeNode({ id: 'c1', name: 'sub' }),
+ [matched],
+ );
+ expect(result).toBe(matched);
+ });
+
+ it('matches when configNode.name contains resource.name', () => {
+ // 'bigname'.includes('big'); id and name and bases all differ.
+ const matched = makeResource('r1', 'big');
+ const result = matchConfiguredNodeToResource(
+ makeNode({ id: 'c1', name: 'bigname' }),
+ [matched],
+ );
+ expect(result).toBe(matched);
+ });
+
+ it('returns undefined when no predicate matches', () => {
+ const result = matchConfiguredNodeToResource(
+ makeNode({ id: 'c1', name: 'zzz' }),
+ [makeResource('r1', 'yyy')],
+ );
+ expect(result).toBeUndefined();
+ });
+});
diff --git a/frontend-modern/src/components/Workloads/__tests__/nestedWorkloadContext.branchcov2.test.ts b/frontend-modern/src/components/Workloads/__tests__/nestedWorkloadContext.branchcov2.test.ts
new file mode 100644
index 0000000000..c3ad1e4559
--- /dev/null
+++ b/frontend-modern/src/components/Workloads/__tests__/nestedWorkloadContext.branchcov2.test.ts
@@ -0,0 +1,455 @@
+import { describe, expect, it } from 'vitest';
+import type { WorkloadGuest, WorkloadType } from '@/types/workloads';
+import { buildNestedWorkloadContextByGuestId } from '../nestedWorkloadContext';
+
+const makeGuest = (overrides: Partial<WorkloadGuest>): WorkloadGuest =>
+ ({
+ id: 'guest-1',
+ vmid: 101,
+ name: 'guest-1',
+ node: 'node-a',
+ instance: 'pve-a',
+ status: 'running',
+ type: 'lxc',
+ workloadType: 'system-container',
+ cpu: 0,
+ cpus: 1,
+ memory: { total: 0, used: 0, free: 0, usage: 0 },
+ disk: { total: 0, used: 0, free: 0, usage: 0 },
+ networkIn: 0,
+ networkOut: 0,
+ diskRead: 0,
+ diskWrite: 0,
+ uptime: 0,
+ template: false,
+ lastBackup: 0,
+ tags: [],
+ lock: '',
+ lastSeen: new Date().toISOString(),
+ ...overrides,
+ }) as WorkloadGuest;
+
+// App-container children default to Docker scope membership and carry no
+// Proxmox node/instance identity of their own so parent matching is driven
+// only by the fields each test deliberately exercises.
+const makeContainer = (overrides: Partial<WorkloadGuest>): WorkloadGuest =>
+ makeGuest({
+ id: 'app-container:x',
+ vmid: 0,
+ name: 'x',
+ type: 'app-container',
+ workloadType: 'app-container',
+ platformType: 'docker',
+ platformScopes: ['proxmox-pve', 'docker'],
+ containerRuntime: 'docker',
+ instance: '',
+ node: '',
+ ...overrides,
+ });
+
+const fullParent = (overrides: Partial<WorkloadGuest> = {}): WorkloadGuest =>
+ makeGuest({
+ id: 'lxc-141',
+ vmid: 141,
+ name: 'media-lxc',
+ node: 'node-a',
+ instance: 'pve-a',
+ ...overrides,
+ });
+
+const run = ({
+ guests,
+ visibleGuests,
+ excludedWorkloadTypes = ['app-container'],
+ platformScope = 'proxmox-pve',
+}: {
+ guests: readonly WorkloadGuest[];
+ visibleGuests: readonly WorkloadGuest[];
+ excludedWorkloadTypes?: readonly WorkloadType[];
+ platformScope?: string | null;
+}) => buildNestedWorkloadContextByGuestId({ guests, visibleGuests, excludedWorkloadTypes, platformScope });
+
+describe('nestedWorkloadContext (branch coverage)', () => {
+ describe('formatRuntimeLabel', () => {
+ it('maps a podman runtime (case/whitespace-insensitive) to "Podman"', () => {
+ const parent = fullParent();
+ const container = makeContainer({
+ id: 'app-container:kea',
+ name: 'kea',
+ containerRuntime: ' PODMAN ',
+ dockerHostId: 'proxmox-lxc-docker:pve-a:node-a:141',
+ dockerHostName: 'host-a',
+ });
+
+ const result = run({ guests: [container], visibleGuests: [parent] });
+
+ expect(result['pve-a:node-a:141']).toStrictEqual({
+ type: 'app-container',
+ label: 'Podman',
+ title: 'Nested Podman',
+ count: 1,
+ href: '/docker/overview?host=host-a',
+ items: [{ id: 'app-container:kea', name: 'kea', status: 'running', runtimeLabel: 'Podman' }],
+ });
+ });
+
+ it('maps any non-podman runtime to "Docker"', () => {
+ const parent = fullParent();
+ const container = makeContainer({
+ id: 'app-container:svc',
+ name: 'svc',
+ containerRuntime: 'containerd',
+ dockerHostId: 'proxmox-lxc-docker:pve-a:node-a:141',
+ dockerHostName: 'host-a',
+ });
+
+ const result = run({ guests: [container], visibleGuests: [parent] });
+
+ expect(result['pve-a:node-a:141']?.items[0]?.runtimeLabel).toBe('Docker');
+ expect(result['pve-a:node-a:141']?.label).toBe('Docker');
+ });
+ });
+
+ describe('formatStatusLabel', () => {
+ it('returns the cleaned status when present and "unknown" for empty/whitespace values', () => {
+ const parent = fullParent();
+ const exited = makeContainer({
+ id: 'app-container:alpha',
+ name: 'alpha',
+ status: 'exited',
+ dockerHostId: 'proxmox-lxc-docker:pve-a:node-a:141',
+ });
+ const emptyStatus = makeContainer({
+ id: 'app-container:beta',
+ name: 'beta',
+ status: '',
+ dockerHostId: 'proxmox-lxc-docker:pve-a:node-a:141',
+ });
+ const whitespaceStatus = makeContainer({
+ id: 'app-container:gamma',
+ name: 'gamma',
+ status: ' ',
+ dockerHostId: 'proxmox-lxc-docker:pve-a:node-a:141',
+ });
+
+ const result = run({ guests: [exited, emptyStatus, whitespaceStatus], visibleGuests: [parent] });
+
+ expect(result['pve-a:node-a:141']?.items.map((item) => item.status)).toEqual([
+ 'exited',
+ 'unknown',
+ 'unknown',
+ ]);
+ });
+ });
+
+ describe('createNestedItem', () => {
+ it('falls back to containerId when the name is empty', () => {
+ const parent = fullParent();
+ const container = makeContainer({
+ id: 'app-container:noid',
+ name: '',
+ containerId: 'cid-7',
+ dockerHostId: 'proxmox-lxc-docker:pve-a:node-a:141',
+ });
+
+ const result = run({ guests: [container], visibleGuests: [parent] });
+
+ expect(result['pve-a:node-a:141']?.items[0]?.name).toBe('cid-7');
+ });
+
+ it('falls back to the canonical workload id when both name and containerId are empty', () => {
+ const parent = fullParent();
+ const container = makeContainer({
+ id: 'app-container:orphan',
+ name: '',
+ containerId: '',
+ dockerHostId: 'proxmox-lxc-docker:pve-a:node-a:141',
+ });
+
+ const result = run({ guests: [container], visibleGuests: [parent] });
+
+ expect(result['pve-a:node-a:141']?.items[0]?.name).toBe('app-container:orphan');
+ });
+
+ it('uses contextLabel for the host facet when dockerHostName is empty', () => {
+ const parent = fullParent();
+ const container = makeContainer({
+ id: 'app-container:ctx',
+ name: 'ctx',
+ dockerHostName: '',
+ contextLabel: 'ctx-host',
+ dockerHostId: 'proxmox-lxc-docker:pve-a:node-a:141',
+ });
+
+ const result = run({ guests: [container], visibleGuests: [parent] });
+
+ expect(result['pve-a:node-a:141']?.href).toBe('/docker/overview?host=ctx-host');
+ });
+ });
+
+ describe('chooseContextLabel', () => {
+ it('returns "Containers" and a "Nested containers" title when runtimes are mixed', () => {
+ const parent = fullParent();
+ const dockerOne = makeContainer({
+ id: 'app-container:d',
+ name: 'd',
+ containerRuntime: 'docker',
+ dockerHostId: 'proxmox-lxc-docker:pve-a:node-a:141',
+ dockerHostName: 'shared-host',
+ });
+ const podmanOne = makeContainer({
+ id: 'app-container:p',
+ name: 'p',
+ containerRuntime: 'podman',
+ dockerHostId: 'proxmox-lxc-docker:pve-a:node-a:141',
+ dockerHostName: 'shared-host',
+ });
+
+ const result = run({ guests: [dockerOne, podmanOne], visibleGuests: [parent] });
+
+ expect(result['pve-a:node-a:141']?.label).toBe('Containers');
+ expect(result['pve-a:node-a:141']?.title).toBe('Nested containers');
+ expect(result['pve-a:node-a:141']?.count).toBe(2);
+ });
+ });
+
+ describe('addDockerHostIdentitySegments', () => {
+ it('matches a parent via an unprefixed 2-segment host id (prefix-false, >=2/>=1 arms)', () => {
+ const parent = fullParent();
+ const container = makeContainer({
+ id: 'app-container:two',
+ name: 'two',
+ dockerHostId: 'node-a:141',
+ });
+
+ const result = run({ guests: [container], visibleGuests: [parent] });
+
+ expect(Object.keys(result)).toEqual(['pve-a:node-a:141']);
+ expect(result['pve-a:node-a:141']?.items[0]?.name).toBe('two');
+ });
+
+ it('matches a parent via an unprefixed 1-segment host id (>=3/>=2 false, >=1 true)', () => {
+ const parent = fullParent();
+ const container = makeContainer({
+ id: 'app-container:one',
+ name: 'one',
+ dockerHostId: '141',
+ });
+
+ const result = run({ guests: [container], visibleGuests: [parent] });
+
+ expect(Object.keys(result)).toEqual(['pve-a:node-a:141']);
+ });
+
+ it('yields no parent match when only the lxc docker prefix is present (all segment arms false)', () => {
+ const parent = fullParent();
+ const container = makeContainer({
+ id: 'app-container:empty',
+ name: 'empty',
+ dockerHostId: 'proxmox-lxc-docker:',
+ });
+
+ const result = run({ guests: [container], visibleGuests: [parent] });
+
+ expect(result).toEqual({});
+ });
+
+ it('skips candidate extraction entirely when dockerHostId is empty (early return)', () => {
+ const parent = fullParent({ name: 'echo-host' });
+ const container = makeContainer({
+ id: 'app-container:echo',
+ name: 'echo',
+ dockerHostId: undefined,
+ contextLabel: 'echo-host',
+ });
+
+ const result = run({ guests: [container], visibleGuests: [parent] });
+
+ expect(Object.keys(result)).toEqual(['pve-a:node-a:141']);
+ expect(result['pve-a:node-a:141']?.items[0]?.name).toBe('echo');
+ });
+ });
+
+ describe('buildNodeScopedIdentityCandidates', () => {
+ it('emits an instance:vmid candidate when node is missing (line 70 true arm)', () => {
+ const parent = makeGuest({
+ id: 'lxc-p2',
+ vmid: 200,
+ name: 'p2',
+ node: '',
+ instance: 'pve-b',
+ workloadType: 'system-container',
+ type: 'lxc',
+ });
+ const container = makeContainer({
+ id: 'app-container:p2c',
+ name: 'p2c',
+ dockerHostId: 'pve-b:200',
+ });
+
+ const result = run({ guests: [container], visibleGuests: [parent] });
+
+ expect(Object.keys(result)).toEqual(['lxc-p2']);
+ });
+
+ it('emits a node:vmid candidate when instance is missing (line 71 true arm)', () => {
+ const parent = makeGuest({
+ id: 'lxc-p3',
+ vmid: 300,
+ name: 'p3',
+ node: 'node-c',
+ instance: '',
+ workloadType: 'system-container',
+ type: 'lxc',
+ });
+ const container = makeContainer({
+ id: 'app-container:p3c',
+ name: 'p3c',
+ dockerHostId: 'node-c:300',
+ });
+
+ const result = run({ guests: [container], visibleGuests: [parent] });
+
+ expect(Object.keys(result)).toEqual(['lxc-p3']);
+ });
+
+ it('emits a bare vmid candidate when instance and node are missing (line 72 true arm)', () => {
+ const parent = makeGuest({
+ id: 'lxc-p4',
+ vmid: 400,
+ name: 'p4',
+ node: '',
+ instance: '',
+ workloadType: 'system-container',
+ type: 'lxc',
+ });
+ const container = makeContainer({
+ id: 'app-container:p4c',
+ name: 'p4c',
+ dockerHostId: '400',
+ });
+
+ const result = run({ guests: [container], visibleGuests: [parent] });
+
+ expect(Object.keys(result)).toEqual(['lxc-p4']);
+ });
+
+ it('skips every vmid-keyed candidate when vmid is not finite (line 62 false arm)', () => {
+ const parent = makeGuest({
+ id: 'lxc-p5',
+ vmid: NaN,
+ name: 'echo-host',
+ node: 'node-e',
+ instance: 'pve-e',
+ workloadType: 'system-container',
+ type: 'lxc',
+ });
+ const container = makeContainer({
+ id: 'app-container:echoc',
+ name: 'echoc',
+ dockerHostId: undefined,
+ contextLabel: 'echo-host',
+ });
+
+ const result = run({ guests: [container], visibleGuests: [parent] });
+
+ expect(Object.keys(result)).toEqual(['lxc-p5']);
+ });
+ });
+
+ describe('buildNestedWorkloadContextByGuestId pipeline', () => {
+ it('produces a fully-shaped context for a canonical Docker app container', () => {
+ const parent = fullParent();
+ const container = makeContainer({
+ id: 'app-container:frigate',
+ name: 'frigate',
+ containerRuntime: 'docker',
+ status: 'running',
+ dockerHostId: 'proxmox-lxc-docker:pve-a:node-a:141',
+ dockerHostName: 'media-lxc.mist-stork.ts.net',
+ });
+
+ const result = run({ guests: [container], visibleGuests: [parent] });
+
+ expect(result).toStrictEqual({
+ 'pve-a:node-a:141': {
+ type: 'app-container',
+ label: 'Docker',
+ title: 'Nested Docker',
+ count: 1,
+ href: '/docker/overview?host=media-lxc.mist-stork.ts.net',
+ items: [
+ { id: 'app-container:frigate', name: 'frigate', status: 'running', runtimeLabel: 'Docker' },
+ ],
+ },
+ });
+ });
+
+ it('registers a vm parent and ignores non-parent/non-child workload types', () => {
+ const vmParent = makeGuest({
+ id: 'vm-500',
+ vmid: 500,
+ name: 'vmhost',
+ node: 'node-f',
+ instance: 'pve-f',
+ workloadType: 'vm',
+ type: 'qemu',
+ });
+ const strayContainer = makeContainer({
+ id: 'app-container:stray',
+ name: 'stray',
+ dockerHostId: 'proxmox-lxc-docker:pve-f:node-f:500',
+ });
+ const pod = makeGuest({
+ id: 'k8s:agent:pod:p1',
+ vmid: 0,
+ name: 'p1',
+ node: '',
+ instance: '',
+ workloadType: 'pod',
+ type: 'pod',
+ });
+ const service = makeContainer({
+ id: 'app-container:svc',
+ name: 'svc',
+ dockerHostId: 'proxmox-lxc-docker:pve-f:node-f:500',
+ dockerHostName: 'h',
+ });
+
+ const result = run({
+ guests: [vmParent, service],
+ visibleGuests: [vmParent, strayContainer, pod],
+ });
+
+ expect(Object.keys(result)).toEqual(['pve-f:node-f:500']);
+ expect(result['pve-f:node-f:500']?.items.map((item) => item.name)).toEqual(['svc']);
+ });
+
+ it('skips app containers that do not match the requested platform scope', () => {
+ const parent = fullParent();
+ const container = makeContainer({
+ id: 'app-container:scope',
+ name: 'scope',
+ dockerHostId: 'proxmox-lxc-docker:pve-a:node-a:141',
+ platformScopes: ['docker'],
+ });
+
+ const result = run({ guests: [container], visibleGuests: [parent] });
+
+ expect(result).toEqual({});
+ });
+
+ it('skips app containers whose host identity maps to no known parent', () => {
+ const parent = fullParent();
+ const container = makeContainer({
+ id: 'app-container:noparent',
+ name: 'noparent',
+ dockerHostId: 'proxmox-lxc-docker:999',
+ });
+
+ const result = run({ guests: [container], visibleGuests: [parent] });
+
+ expect(result).toEqual({});
+ });
+ });
+});
diff --git a/frontend-modern/src/components/Workloads/__tests__/nodeDrawerModel.branchcov2.test.ts b/frontend-modern/src/components/Workloads/__tests__/nodeDrawerModel.branchcov2.test.ts
new file mode 100644
index 0000000000..77c1f7dcf0
--- /dev/null
+++ b/frontend-modern/src/components/Workloads/__tests__/nodeDrawerModel.branchcov2.test.ts
@@ -0,0 +1,280 @@
+import { describe, expect, it } from 'vitest';
+
+import type { Node, Temperature } from '@/types/api';
+
+import { getNodeDrawerHistoryFallbackMetrics, getNodeDrawerHistoryTarget } from '../nodeDrawerModel';
+
+const makeNode = (overrides: Partial<Node> = {}): Node => ({
+ id: 'agent:pve-node-1',
+ name: 'pve-node-1',
+ instance: 'homelab',
+ host: 'pve-node-1',
+ status: 'online',
+ type: 'agent',
+ cpu: 0.42,
+ memory: { total: 8000, used: 3200, free: 4800, usage: 40 },
+ disk: { total: 10000, used: 4500, free: 5500, usage: 45 },
+ networkIn: 1200,
+ networkOut: 800,
+ diskRead: 400,
+ diskWrite: 300,
+ uptime: 3600,
+ loadAverage: [0.5],
+ kernelVersion: '6.8.0',
+ pveVersion: 'pve-manager/9.1.9',
+ cpuInfo: { model: 'Ryzen', cores: 8, sockets: 1, mhz: '3200' },
+ temperature: {
+ cpuPackage: 62.5,
+ cpuMax: 65,
+ available: true,
+ hasCPU: true,
+ lastUpdate: new Date().toISOString(),
+ },
+ temperatureMonitoringEnabled: true,
+ lastSeen: new Date().toISOString(),
+ connectionHealth: 'online',
+ isClusterMember: true,
+ clusterName: 'homelab',
+ linkedAgentId: '',
+ ...overrides,
+});
+
+const makeTemp = (overrides: Partial<Temperature> = {}): Temperature => ({
+ available: true,
+ lastUpdate: new Date().toISOString(),
+ ...overrides,
+});
+
+describe('nodeDrawerModel (branch coverage 2)', () => {
+ describe('getNodeDrawerHistoryTarget', () => {
+ it('prefers linkedAgentId and returns it unchanged when it has no agent: prefix', () => {
+ // || chain arm 1 (linkedAgentId truthy) + stripAgentPrefix false arm + success return.
+ const node = makeNode({
+ linkedAgentId: 'agent-uuid-9',
+ id: 'agent:pve-node-1',
+ name: 'pve-node-1',
+ });
+ expect(getNodeDrawerHistoryTarget(node)).toStrictEqual({
+ resourceType: 'agent',
+ resourceId: 'agent-uuid-9',
+ });
+ });
+
+ it('strips the agent: prefix from linkedAgentId', () => {
+ // stripAgentPrefix true arm (startsWith) on the linkedAgentId arm.
+ const node = makeNode({
+ linkedAgentId: 'agent:agent-uuid-9',
+ id: 'agent:pve-node-1',
+ name: 'pve-node-1',
+ });
+ expect(getNodeDrawerHistoryTarget(node)).toStrictEqual({
+ resourceType: 'agent',
+ resourceId: 'agent-uuid-9',
+ });
+ });
+
+ it('falls back to id (stripping agent:) when linkedAgentId is empty', () => {
+ // || chain arm 2 (linkedAgentId '' falsy -> id) + stripAgentPrefix true arm.
+ const node = makeNode({
+ linkedAgentId: '',
+ id: 'agent:pve-node-1',
+ name: 'pve-node-1',
+ });
+ expect(getNodeDrawerHistoryTarget(node)).toStrictEqual({
+ resourceType: 'agent',
+ resourceId: 'pve-node-1',
+ });
+ });
+
+ it('falls back to name when linkedAgentId and id are both empty', () => {
+ // || chain arm 3 (name) + stripAgentPrefix false arm (no prefix on name).
+ const node = makeNode({
+ linkedAgentId: '',
+ id: '',
+ name: 'pve-node-1',
+ });
+ expect(getNodeDrawerHistoryTarget(node)).toStrictEqual({
+ resourceType: 'agent',
+ resourceId: 'pve-node-1',
+ });
+ });
+
+ it('strips the agent: prefix from the name fallback', () => {
+ // || chain arm 3 (name) + stripAgentPrefix true arm.
+ const node = makeNode({
+ linkedAgentId: '',
+ id: '',
+ name: 'agent:pve-node-1',
+ });
+ expect(getNodeDrawerHistoryTarget(node)).toStrictEqual({
+ resourceType: 'agent',
+ resourceId: 'pve-node-1',
+ });
+ });
+
+ it('returns null when linkedAgentId, id, and name are all empty', () => {
+ // || chain arm 4 ('') + !resourceId true arm.
+ const node = makeNode({
+ linkedAgentId: '',
+ id: '',
+ name: '',
+ });
+ expect(getNodeDrawerHistoryTarget(node)).toBeNull();
+ });
+
+ it('returns null when the chosen value is whitespace-only (trim -> empty)', () => {
+ // ' ' is truthy -> chosen; .trim() -> '' -> !resourceId null.
+ const node = makeNode({
+ linkedAgentId: ' ',
+ id: 'agent:ignored',
+ name: 'ignored',
+ });
+ expect(getNodeDrawerHistoryTarget(node)).toBeNull();
+ });
+
+ it('returns null when the chosen value is exactly "agent:" (strip -> empty)', () => {
+ // stripAgentPrefix('agent:') -> '' -> !resourceId null.
+ const node = makeNode({
+ linkedAgentId: 'agent:',
+ id: 'agent:ignored',
+ name: 'ignored',
+ });
+ expect(getNodeDrawerHistoryTarget(node)).toBeNull();
+ });
+
+ it('trims surrounding whitespace before stripping the agent: prefix', () => {
+ // ' agent:foo '.trim() -> 'agent:foo' -> strip -> 'foo'.
+ const node = makeNode({
+ linkedAgentId: ' agent:foo ',
+ id: 'agent:ignored',
+ name: 'ignored',
+ });
+ expect(getNodeDrawerHistoryTarget(node)).toStrictEqual({
+ resourceType: 'agent',
+ resourceId: 'foo',
+ });
+ });
+
+ it('treats an absent (undefined) linkedAgentId as falsy and falls through to id', () => {
+ // Optional linkedAgentId absent -> || falls to id arm.
+ const node = makeNode({
+ linkedAgentId: undefined,
+ id: 'agent:node-7',
+ name: 'node-7',
+ });
+ expect(getNodeDrawerHistoryTarget(node)).toStrictEqual({
+ resourceType: 'agent',
+ resourceId: 'node-7',
+ });
+ });
+ });
+
+ describe('getNodeDrawerHistoryFallbackMetrics', () => {
+ it('returns temperature: undefined when node.temperature is undefined', () => {
+ // getCpuTemperature(undefined) -> !temperature?.available -> null -> ?? undefined.
+ const node = makeNode({ temperature: undefined });
+ expect(getNodeDrawerHistoryFallbackMetrics(node)).toStrictEqual({
+ temperature: undefined,
+ });
+ });
+
+ it('returns temperature: undefined when node.temperature is null', () => {
+ // getCpuTemperature(null) -> !temperature?.available -> null -> ?? undefined (right arm).
+ const node = makeNode({ temperature: null as unknown as Temperature });
+ expect(getNodeDrawerHistoryFallbackMetrics(node)).toStrictEqual({
+ temperature: undefined,
+ });
+ });
+
+ it('returns temperature: undefined when temperature.available is false', () => {
+ // !temperature?.available true arm -> null -> ?? undefined.
+ const node = makeNode({
+ temperature: makeTemp({ available: false, cpuPackage: 62 }),
+ });
+ expect(getNodeDrawerHistoryFallbackMetrics(node)).toStrictEqual({
+ temperature: undefined,
+ });
+ });
+
+ it('returns the cpuPackage value when available and finite', () => {
+ // ?? left arm: getCpuTemperature returns a number (cpuPackage only candidate).
+ const node = makeNode({
+ temperature: makeTemp({ cpuPackage: 62 }),
+ });
+ expect(getNodeDrawerHistoryFallbackMetrics(node)).toStrictEqual({
+ temperature: 62,
+ });
+ });
+
+ it('skips a non-finite cpuPackage and falls back to cpuMax', () => {
+ // isValidTemperature(cpuPackage) false (NaN); cpuMax valid -> single candidate.
+ const node = makeNode({
+ temperature: makeTemp({ cpuPackage: Number.NaN, cpuMax: 70 }),
+ });
+ expect(getNodeDrawerHistoryFallbackMetrics(node)).toStrictEqual({
+ temperature: 70,
+ });
+ });
+
+ it('returns Math.max across cpuPackage, cpuMax, and valid core temps', () => {
+ // cores is an array -> forEach -> isValidTemperature(core.temp) true -> candidate.
+ const node = makeNode({
+ temperature: makeTemp({
+ cpuPackage: 50,
+ cpuMax: 80,
+ cores: [
+ { core: 0, temp: 90 },
+ { core: 1, temp: 30 },
+ ],
+ }),
+ });
+ expect(getNodeDrawerHistoryFallbackMetrics(node)).toStrictEqual({
+ temperature: 90,
+ });
+ });
+
+ it('ignores non-finite core temps and still returns the max of valid candidates', () => {
+ // core.temp NaN -> isValidTemperature false -> skipped; cpuMax=80 wins.
+ const node = makeNode({
+ temperature: makeTemp({
+ cpuPackage: Number.NaN,
+ cpuMax: 80,
+ cores: [{ core: 0, temp: Number.NaN }],
+ }),
+ });
+ expect(getNodeDrawerHistoryFallbackMetrics(node)).toStrictEqual({
+ temperature: 80,
+ });
+ });
+
+ it('returns temperature: undefined when available is true but no candidates are valid', () => {
+ // cpuPackage/cpuMax NaN, cores absent -> candidates empty -> null -> ?? undefined.
+ const node = makeNode({
+ temperature: makeTemp({ cpuPackage: Number.NaN, cpuMax: Number.NaN }),
+ });
+ expect(getNodeDrawerHistoryFallbackMetrics(node)).toStrictEqual({
+ temperature: undefined,
+ });
+ });
+
+ it('returns temperature: undefined when cores is not an array and cpu fields are absent', () => {
+ // Array.isArray(undefined) === false -> cores branch skipped; no candidates -> null.
+ const node = makeNode({
+ temperature: makeTemp({ cpuPackage: undefined, cpuMax: undefined }),
+ });
+ expect(getNodeDrawerHistoryFallbackMetrics(node)).toStrictEqual({
+ temperature: undefined,
+ });
+ });
+
+ it('prefers a higher cpuMax over cpuPackage via Math.max', () => {
+ // cpuPackage=40, cpuMax=55, no cores -> Math.max(40,55)=55.
+ const node = makeNode({
+ temperature: makeTemp({ cpuPackage: 40, cpuMax: 55 }),
+ });
+ expect(getNodeDrawerHistoryFallbackMetrics(node)).toStrictEqual({
+ temperature: 55,
+ });
+ });
+ });
+});
diff --git a/frontend-modern/src/components/Workloads/__tests__/workloadRouteModel.branchcov2.test.ts b/frontend-modern/src/components/Workloads/__tests__/workloadRouteModel.branchcov2.test.ts
new file mode 100644
index 0000000000..fee32a854e
--- /dev/null
+++ b/frontend-modern/src/components/Workloads/__tests__/workloadRouteModel.branchcov2.test.ts
@@ -0,0 +1,418 @@
+import { describe, expect, it } from 'vitest';
+
+import type { WorkloadGuest } from '@/types/workloads';
+import {
+ buildWorkloadNodeOptions,
+ buildWorkloadsKubernetesNamespaceOptions,
+ buildWorkloadsVmwareClusterOptions,
+} from '../workloadRouteModel';
+
+const makeGuest = (overrides?: Partial<WorkloadGuest>): WorkloadGuest =>
+ ({
+ id: 'guest-1',
+ vmid: 101,
+ name: 'guest-1',
+ node: 'node-a',
+ instance: 'cluster-a',
+ status: 'running',
+ type: 'vm',
+ cpu: 0,
+ cpus: 2,
+ memory: { total: 1024, used: 256, free: 768, usage: 0.25 },
+ disk: { total: 1024, used: 256, free: 768, usage: 0.25 },
+ networkIn: 0,
+ networkOut: 0,
+ diskRead: 0,
+ diskWrite: 0,
+ uptime: 0,
+ template: false,
+ lastBackup: 0,
+ tags: [],
+ lock: '',
+ lastSeen: new Date().toISOString(),
+ workloadType: 'vm',
+ ...overrides,
+ }) as WorkloadGuest;
+
+describe('workloadRouteModel (branch coverage 2)', () => {
+ describe('buildWorkloadNodeOptions', () => {
+ it('disambiguates app-container hosts sharing a host label by appending scope when both scopes differ from the label', () => {
+ // Two Docker app-containers share contextLabel "tower.local" (the host
+ // label) but have distinct dockerHostId scopes. In loop 1 both register
+ // under disambiguationLabel "tower.local" -> set size 2. In loop 2 the
+ // app-container arm hits hasDuplicateHostLabel===true and, because each
+ // scope !== hostLabel, formats "${hostLabel} (${scope})".
+ const options = buildWorkloadNodeOptions([
+ makeGuest({
+ id: 'docker-a',
+ type: 'app-container',
+ workloadType: 'app-container',
+ node: '',
+ instance: '',
+ contextLabel: 'tower.local',
+ dockerHostId: 'docker-host-1',
+ }),
+ makeGuest({
+ id: 'docker-b',
+ type: 'app-container',
+ workloadType: 'app-container',
+ node: '',
+ instance: '',
+ contextLabel: 'tower.local',
+ dockerHostId: 'docker-host-2',
+ }),
+ ]);
+
+ expect(options).toEqual([
+ { value: 'docker-host-1', label: 'tower.local (docker-host-1)' },
+ { value: 'docker-host-2', label: 'tower.local (docker-host-2)' },
+ ]);
+ });
+
+ it('keeps the bare host label for the app-container whose scope equals the host label even when duplicates exist', () => {
+ // guestA has dockerHostId="" so its scope falls through to contextLabel
+ // "tower.local" == hostLabel; guestB has dockerHostId="dh1" so scope="dh1"
+ // != hostLabel. Both share hostLabel "tower.local" -> duplicate set size 2.
+ // For guestA: hasDuplicateHostLabel && scope !== hostLabel is true && false
+ // -> false arm -> bare hostLabel. For guestB: true arm -> disambiguated.
+ const options = buildWorkloadNodeOptions([
+ makeGuest({
+ id: 'docker-canonical',
+ type: 'app-container',
+ workloadType: 'app-container',
+ node: '',
+ instance: '',
+ contextLabel: 'tower.local',
+ dockerHostId: '',
+ }),
+ makeGuest({
+ id: 'docker-named',
+ type: 'app-container',
+ workloadType: 'app-container',
+ node: '',
+ instance: '',
+ contextLabel: 'tower.local',
+ dockerHostId: 'dh1',
+ }),
+ ]);
+
+ expect(options).toEqual([
+ { value: 'tower.local', label: 'tower.local' },
+ { value: 'dh1', label: 'tower.local (dh1)' },
+ ]);
+ });
+
+ it('skips vm guests whose node-scope id is the placeholder "-" (empty instance and node)', () => {
+ // workloadNodeScopeId = `${instance}-${node}` -> "-" when both empty.
+ // Loop 1: scope === '-' -> B2 dash arm skip. Loop 2: same -> B8 dash arm.
+ const options = buildWorkloadNodeOptions([
+ makeGuest({ id: 'empty-vm', node: '', instance: '' }),
+ makeGuest({ id: 'vm-real', node: 'node-a', instance: 'cluster-a' }),
+ ]);
+
+ expect(options).toEqual([{ value: 'cluster-a-node-a', label: 'node-a' }]);
+ });
+
+ it('skips app-container guests whose host scope is empty string (all host-id candidates blank)', () => {
+ // getWorkloadContainerHostId returns "" when dockerHostId, contextLabel,
+ // node and instance are all empty -> !scope true arm (loop 1 B2 and loop 2 B8).
+ const options = buildWorkloadNodeOptions([
+ makeGuest({
+ id: 'docker-blank',
+ type: 'app-container',
+ workloadType: 'app-container',
+ node: '',
+ instance: '',
+ contextLabel: '',
+ dockerHostId: '',
+ }),
+ makeGuest({
+ id: 'docker-real',
+ type: 'app-container',
+ workloadType: 'app-container',
+ node: '',
+ instance: '',
+ contextLabel: 'host-1',
+ dockerHostId: 'dh1',
+ }),
+ ]);
+
+ expect(options).toEqual([{ value: 'dh1', label: 'host-1' }]);
+ });
+
+ it('skips vm guests with a valid scope but empty node (empty host label) in both loops', () => {
+ // instance set, node empty -> scope "c1-" (non-empty, not "-") passes B2/B8.
+ // label = (node||'').trim() = "" -> loop 1 B3 (!label) skip. Loop 2 vm arm:
+ // nodeName = "" -> B13 (!nodeName) skip. The guest produces no option.
+ const options = buildWorkloadNodeOptions([
+ makeGuest({ id: 'no-node', node: '', instance: 'c1' }),
+ makeGuest({ id: 'with-node', node: 'node-a', instance: 'c2' }),
+ ]);
+
+ expect(options).toEqual([{ value: 'c2-node-a', label: 'node-a' }]);
+ });
+
+ it('falls back to the bare node name when a duplicate node has no instance to disambiguate with', () => {
+ // vm1: node 'shared', instance 'c1' -> scope 'c1-shared'.
+ // vm2: node 'shared', instance '' -> scope '-shared'.
+ // Loop 1: scopesByLabel['shared'] = {'c1-shared', '-shared'} size 2.
+ // Loop 2 vm2: hasDuplicateNodeName===true but instance is '' (falsy) ->
+ // `hasDuplicateNodeName && instance` short-circuits to false -> label = nodeName.
+ // vm1: true && 'c1' -> true arm -> 'shared (c1)'.
+ const options = buildWorkloadNodeOptions([
+ makeGuest({ id: 'vm-with-inst', node: 'shared', instance: 'c1' }),
+ makeGuest({ id: 'vm-no-inst', node: 'shared', instance: '' }),
+ ]);
+
+ expect(options).toEqual([
+ { value: '-shared', label: 'shared' },
+ { value: 'c1-shared', label: 'shared (c1)' },
+ ]);
+ });
+
+ it('skips pod guests in both passes so they never produce node options', () => {
+ const options = buildWorkloadNodeOptions([
+ makeGuest({
+ id: 'pod-a',
+ type: 'pod',
+ workloadType: 'pod',
+ node: 'worker-a',
+ instance: 'ctx',
+ }),
+ makeGuest({ id: 'vm-a', node: 'node-a', instance: 'cluster-a' }),
+ ]);
+
+ expect(options).toEqual([{ value: 'cluster-a-node-a', label: 'node-a' }]);
+ });
+
+ it('returns an empty array for an empty guest list', () => {
+ expect(buildWorkloadNodeOptions([])).toEqual([]);
+ });
+ });
+
+ describe('buildWorkloadsKubernetesNamespaceOptions', () => {
+ it('ignores the context filter when selectedContext is null and collects namespaces from pods in every context', () => {
+ // (selectedContext || '').trim() -> '' -> contextFilter falsy ->
+ // `contextFilter && ...` short-circuits to false (no skip) for every pod.
+ const guests = [
+ makeGuest({
+ id: 'pod-a',
+ type: 'pod',
+ workloadType: 'pod',
+ contextLabel: 'prod',
+ namespace: 'default',
+ }),
+ makeGuest({
+ id: 'pod-b',
+ type: 'pod',
+ workloadType: 'pod',
+ contextLabel: 'stage',
+ namespace: 'kube-system',
+ }),
+ makeGuest({
+ id: 'pod-c',
+ type: 'pod',
+ workloadType: 'pod',
+ contextLabel: 'prod',
+ namespace: 'default',
+ }),
+ ];
+
+ expect(buildWorkloadsKubernetesNamespaceOptions(guests, null)).toEqual([
+ 'default',
+ 'kube-system',
+ ]);
+ // Contrast: with an explicit context, only that context's namespaces surface.
+ expect(buildWorkloadsKubernetesNamespaceOptions(guests, 'prod')).toEqual(['default']);
+ expect(buildWorkloadsKubernetesNamespaceOptions(guests, 'stage')).toEqual(['kube-system']);
+ });
+
+ it('treats a whitespace-only selectedContext as no filter after trimming', () => {
+ const guests = [
+ makeGuest({
+ id: 'pod-a',
+ type: 'pod',
+ workloadType: 'pod',
+ contextLabel: 'prod',
+ namespace: 'default',
+ }),
+ makeGuest({
+ id: 'pod-b',
+ type: 'pod',
+ workloadType: 'pod',
+ contextLabel: 'stage',
+ namespace: 'observability',
+ }),
+ ];
+
+ // ' ' -> trim -> '' -> falsy -> both contexts' namespaces collected.
+ expect(buildWorkloadsKubernetesNamespaceOptions(guests, ' ')).toEqual([
+ 'default',
+ 'observability',
+ ]);
+ });
+
+ it('skips non-pod guests even when they carry a namespace', () => {
+ // resolveWorkloadType(guest) !== 'pod' -> continue (C2 true arm).
+ const guests = [
+ makeGuest({
+ id: 'vm-a',
+ type: 'vm',
+ workloadType: 'vm',
+ contextLabel: 'prod',
+ namespace: 'should-be-ignored',
+ }),
+ makeGuest({
+ id: 'app-a',
+ type: 'app-container',
+ workloadType: 'app-container',
+ contextLabel: 'prod',
+ namespace: 'also-ignored',
+ }),
+ makeGuest({
+ id: 'pod-a',
+ type: 'pod',
+ workloadType: 'pod',
+ contextLabel: 'prod',
+ namespace: 'default',
+ }),
+ ];
+
+ expect(buildWorkloadsKubernetesNamespaceOptions(guests, 'prod')).toEqual(['default']);
+ });
+
+ it('skips a pod whose namespace is missing or blank even when the context matches', () => {
+ // namespace undefined -> (guest.namespace || '').trim() -> '' (C4 ?? arm)
+ // -> if (namespace) false -> not added (C5 empty skip).
+ const guests = [
+ makeGuest({
+ id: 'pod-undef',
+ type: 'pod',
+ workloadType: 'pod',
+ contextLabel: 'prod',
+ }),
+ makeGuest({
+ id: 'pod-empty',
+ type: 'pod',
+ workloadType: 'pod',
+ contextLabel: 'prod',
+ namespace: '',
+ }),
+ makeGuest({
+ id: 'pod-ws',
+ type: 'pod',
+ workloadType: 'pod',
+ contextLabel: 'prod',
+ namespace: ' ',
+ }),
+ makeGuest({
+ id: 'pod-real',
+ type: 'pod',
+ workloadType: 'pod',
+ contextLabel: 'prod',
+ namespace: 'default',
+ }),
+ ];
+
+ expect(buildWorkloadsKubernetesNamespaceOptions(guests, 'prod')).toEqual(['default']);
+ });
+
+ it('drops pods whose context key does not match the selected context', () => {
+ // contextFilter truthy && getKubernetesContextKey(guest) !== contextFilter
+ // -> C3 true arm (mismatch skip). pod-b context 'stage' filtered out.
+ const guests = [
+ makeGuest({
+ id: 'pod-a',
+ type: 'pod',
+ workloadType: 'pod',
+ contextLabel: 'prod',
+ namespace: 'default',
+ }),
+ makeGuest({
+ id: 'pod-b',
+ type: 'pod',
+ workloadType: 'pod',
+ contextLabel: 'stage',
+ namespace: 'kube-system',
+ }),
+ ];
+
+ expect(buildWorkloadsKubernetesNamespaceOptions(guests, 'prod')).toEqual(['default']);
+ });
+
+ it('returns an empty array for an empty guest list regardless of context', () => {
+ expect(buildWorkloadsKubernetesNamespaceOptions([], 'prod')).toEqual([]);
+ expect(buildWorkloadsKubernetesNamespaceOptions([], null)).toEqual([]);
+ });
+ });
+
+ describe('buildWorkloadsVmwareClusterOptions', () => {
+ it('collects, deduplicates and sorts cluster names from vm guests', () => {
+ // resolveWorkloadType === 'vm' -> proceed (D1 false arm);
+ // clusterName non-empty -> add (D3 true arm).
+ const guests = [
+ makeGuest({ id: 'vm-a', clusterName: 'cluster-b' }),
+ makeGuest({ id: 'vm-b', clusterName: 'cluster-a' }),
+ makeGuest({ id: 'vm-c', clusterName: 'cluster-a' }),
+ makeGuest({ id: 'vm-d', clusterName: 'cluster-c' }),
+ ];
+
+ expect(buildWorkloadsVmwareClusterOptions(guests)).toEqual([
+ 'cluster-a',
+ 'cluster-b',
+ 'cluster-c',
+ ]);
+ });
+
+ it('skips vm guests whose clusterName is undefined', () => {
+ // (guest.clusterName || '').trim() -> '' (D2 ?? arm) -> if (cluster) false (D3 empty skip).
+ const guests = [
+ makeGuest({ id: 'vm-undef' }),
+ makeGuest({ id: 'vm-real', clusterName: 'cluster-a' }),
+ ];
+
+ expect(buildWorkloadsVmwareClusterOptions(guests)).toEqual(['cluster-a']);
+ });
+
+ it('skips vm guests whose clusterName is empty or whitespace-only', () => {
+ const guests = [
+ makeGuest({ id: 'vm-empty', clusterName: '' }),
+ makeGuest({ id: 'vm-ws', clusterName: ' ' }),
+ makeGuest({ id: 'vm-real', clusterName: 'cluster-a' }),
+ ];
+
+ expect(buildWorkloadsVmwareClusterOptions(guests)).toEqual(['cluster-a']);
+ });
+
+ it('skips non-vm guests even when they carry a clusterName', () => {
+ // resolveWorkloadType !== 'vm' -> continue (D1 true arm) for each.
+ const guests = [
+ makeGuest({
+ id: 'pod-a',
+ type: 'pod',
+ workloadType: 'pod',
+ clusterName: 'cluster-a',
+ }),
+ makeGuest({
+ id: 'app-a',
+ type: 'app-container',
+ workloadType: 'app-container',
+ clusterName: 'cluster-b',
+ }),
+ makeGuest({
+ id: 'lxc-a',
+ type: 'lxc',
+ workloadType: 'system-container',
+ clusterName: 'cluster-c',
+ }),
+ makeGuest({ id: 'vm-a', clusterName: 'cluster-real' }),
+ ];
+
+ expect(buildWorkloadsVmwareClusterOptions(guests)).toEqual(['cluster-real']);
+ });
+
+ it('returns an empty array for an empty guest list', () => {
+ expect(buildWorkloadsVmwareClusterOptions([])).toEqual([]);
+ });
+ });
+});
diff --git a/frontend-modern/src/components/Workloads/__tests__/workloadTopology.branchcov2.test.ts b/frontend-modern/src/components/Workloads/__tests__/workloadTopology.branchcov2.test.ts
new file mode 100644
index 0000000000..7b06a02372
--- /dev/null
+++ b/frontend-modern/src/components/Workloads/__tests__/workloadTopology.branchcov2.test.ts
@@ -0,0 +1,408 @@
+import { describe, expect, it } from 'vitest';
+import type { WorkloadGuest } from '@/types/workloads';
+import {
+ getKubernetesContextKey,
+ getWorkloadAlertResourceIdCandidates,
+ getWorkloadContainerHostId,
+ getWorkloadDockerHostId,
+ getWorkloadHostHintCandidates,
+ getWorkloadHostLabel,
+ workloadNodeScopeId,
+} from '@/components/Workloads/workloadTopology';
+
+const makeGuest = (i: number, overrides?: Partial<WorkloadGuest>): WorkloadGuest => ({
+ id: `guest-${i}`,
+ vmid: 100 + i,
+ name: `workload-${i}`,
+ node: `node-${i % 5}`,
+ instance: `cluster-${i % 3}`,
+ status: 'running',
+ type: 'vm',
+ cpu: 0,
+ cpus: 2,
+ memory: { total: 4096, used: 0, free: 4096, usage: 0 },
+ disk: { total: 102400, used: 0, free: 102400, usage: 0 },
+ networkIn: 0,
+ networkOut: 0,
+ diskRead: 0,
+ diskWrite: 0,
+ uptime: 0,
+ template: false,
+ lastBackup: 0,
+ tags: [],
+ lock: '',
+ lastSeen: new Date().toISOString(),
+ workloadType: 'vm',
+ ...overrides,
+});
+
+describe('workloadTopology (branch coverage 2)', () => {
+ describe('workloadNodeScopeId', () => {
+ it('exercises both `|| ""` fallback arms when instance and node are empty strings', () => {
+ const guest = makeGuest(1, { instance: '', node: '' });
+ // (guest.instance || '') and (guest.node || '') both take the falsy arm.
+ expect(workloadNodeScopeId(guest)).toBe('-');
+ });
+
+ it('keeps a present instance and falls back to empty for a missing node', () => {
+ const guest = makeGuest(1, { instance: 'only-inst', node: '' });
+ // instance truthy arm + node `|| ""` fallback arm.
+ expect(workloadNodeScopeId(guest)).toBe('only-inst-');
+ });
+
+ it('falls back to empty for a missing instance and keeps a present node', () => {
+ const guest = makeGuest(1, { instance: '', node: 'only-node' });
+ // instance `|| ""` fallback arm + node truthy arm.
+ expect(workloadNodeScopeId(guest)).toBe('-only-node');
+ });
+
+ it('trims whitespace on both segments when both are present', () => {
+ const guest = makeGuest(1, { instance: ' inst ', node: ' \tnode\t' });
+ expect(workloadNodeScopeId(guest)).toBe('inst-node');
+ });
+ });
+
+ describe('getKubernetesContextKey', () => {
+ it('returns the trimmed contextLabel when it is the first non-empty candidate', () => {
+ const guest = makeGuest(1, {
+ contextLabel: ' tower.local ',
+ instance: 'cluster-a',
+ node: 'worker-a',
+ });
+ // First loop iteration: contextLabel wins immediately.
+ expect(getKubernetesContextKey(guest)).toBe('tower.local');
+ });
+
+ it('falls through empty contextLabel and instance to return the node candidate', () => {
+ const guest = makeGuest(1, {
+ contextLabel: ' ',
+ instance: '',
+ node: 'worker-b',
+ });
+ // contextLabel and instance trim to '' -> loop continues -> node returned.
+ expect(getKubernetesContextKey(guest)).toBe('worker-b');
+ });
+
+ it('returns empty string when every candidate is empty or whitespace', () => {
+ const guest = makeGuest(1, {
+ contextLabel: ' ',
+ instance: '',
+ node: ' ',
+ });
+ // Loop exhausts all candidates -> final `return ''`.
+ expect(getKubernetesContextKey(guest)).toBe('');
+ });
+ });
+
+ describe('getWorkloadDockerHostId', () => {
+ it('short-circuits to empty string for a non-app-container type', () => {
+ const vm = makeGuest(1, { type: 'vm', workloadType: 'vm', dockerHostId: 'should-be-ignored' });
+ // type !== 'app-container' -> guard returns '' before touching dockerHostId.
+ expect(getWorkloadDockerHostId(vm)).toBe('');
+ });
+
+ it('short-circuits to empty string for a pod type', () => {
+ const pod = makeGuest(2, { type: 'pod', workloadType: 'pod', dockerHostId: 'ignored' });
+ expect(getWorkloadDockerHostId(pod)).toBe('');
+ });
+
+ it('returns the trimmed dockerHostId for an app-container', () => {
+ const app = makeGuest(3, {
+ type: 'app-container',
+ workloadType: 'app-container',
+ platformType: 'docker',
+ dockerHostId: ' docker-host-9 ',
+ });
+ // type === 'app-container' -> (guest.dockerHostId || '').trim().
+ expect(getWorkloadDockerHostId(app)).toBe('docker-host-9');
+ });
+
+ it('returns empty string for an app-container with an empty dockerHostId via the `|| ""` arm', () => {
+ const app = makeGuest(4, {
+ type: 'app-container',
+ workloadType: 'app-container',
+ platformType: 'docker',
+ dockerHostId: '',
+ });
+ expect(getWorkloadDockerHostId(app)).toBe('');
+ });
+ });
+
+ describe('firstTrimmed (exercised via getWorkloadContainerHostId / getWorkloadHostLabel)', () => {
+ it('returns the first non-empty candidate, trimming it', () => {
+ const app = makeGuest(1, {
+ type: 'app-container',
+ workloadType: 'app-container',
+ platformType: 'docker',
+ dockerHostId: ' host-zero ',
+ contextLabel: 'tower',
+ node: 'node-a',
+ instance: 'inst-a',
+ });
+ // getWorkloadContainerHostId orders dockerHostId first -> firstTrimmed first-wins arm.
+ expect(getWorkloadContainerHostId(app)).toBe('host-zero');
+ });
+
+ it('skips empty/whitespace candidates and returns the first populated later candidate', () => {
+ const app = makeGuest(2, {
+ type: 'app-container',
+ workloadType: 'app-container',
+ platformType: 'docker',
+ dockerHostId: ' ',
+ contextLabel: '',
+ node: ' node-b ',
+ instance: 'inst-b',
+ });
+ // dockerHostId and contextLabel trim to '' -> loop continues -> node returned.
+ expect(getWorkloadContainerHostId(app)).toBe('node-b');
+ });
+
+ it('returns empty string when every candidate is empty (final `return ""` arm)', () => {
+ const app = makeGuest(3, {
+ type: 'app-container',
+ workloadType: 'app-container',
+ platformType: 'docker',
+ dockerHostId: '',
+ contextLabel: ' ',
+ node: '',
+ instance: '',
+ });
+ // All four candidates trim to '' -> firstTrimmed loop exhausts -> ''.
+ expect(getWorkloadContainerHostId(app)).toBe('');
+ // Same arm reached through getWorkloadHostLabel's app-container candidate list.
+ expect(getWorkloadHostLabel(app)).toBe('');
+ });
+ });
+
+ describe('getWorkloadContainerHostId (guard arm)', () => {
+ it('short-circuits to empty string for a non-app-container type', () => {
+ const vm = makeGuest(1, {
+ type: 'vm',
+ workloadType: 'vm',
+ dockerHostId: 'ignored',
+ contextLabel: 'ignored',
+ node: 'node-a',
+ instance: 'inst-a',
+ });
+ // type !== 'app-container' -> guard returns '' without calling firstTrimmed.
+ expect(getWorkloadContainerHostId(vm)).toBe('');
+ });
+ });
+
+ describe('getWorkloadHostLabel', () => {
+ it('returns the trimmed contextLabel first for an app-container', () => {
+ const app = makeGuest(1, {
+ type: 'app-container',
+ workloadType: 'app-container',
+ platformType: 'docker',
+ contextLabel: ' ctx-host ',
+ node: 'node-a',
+ instance: 'inst-a',
+ dockerHostId: 'dhid',
+ });
+ // app-container branch -> firstTrimmed([contextLabel, ...]) -> contextLabel wins.
+ expect(getWorkloadHostLabel(app)).toBe('ctx-host');
+ });
+
+ it('returns the trimmed node for a vm via the else branch', () => {
+ const vm = makeGuest(2, { type: 'vm', workloadType: 'vm', node: ' pve1 ' });
+ // else arm: (guest.node || '').trim().
+ expect(getWorkloadHostLabel(vm)).toBe('pve1');
+ });
+
+ it('returns empty string for a vm with an empty node via the `|| ""` arm', () => {
+ const vm = makeGuest(3, { type: 'vm', workloadType: 'vm', node: '' });
+ expect(getWorkloadHostLabel(vm)).toBe('');
+ });
+
+ it('returns empty string for a vm whose node is null via the `|| ""` arm', () => {
+ const vm = makeGuest(4, {
+ type: 'vm',
+ workloadType: 'vm',
+ node: null as unknown as string,
+ });
+ // Deliberately-malformed input: null node -> (null || '').trim() -> ''.
+ expect(getWorkloadHostLabel(vm)).toBe('');
+ });
+ });
+
+ describe('getWorkloadHostHintCandidates', () => {
+ it('returns an empty array for a pod', () => {
+ const pod = makeGuest(1, {
+ type: 'pod',
+ workloadType: 'pod',
+ node: 'worker-a',
+ instance: 'cluster-a',
+ contextLabel: 'ctx',
+ });
+ // type === 'pod' -> early return [].
+ expect(getWorkloadHostHintCandidates(pod)).toEqual([]);
+ });
+
+ it('dedupes case-insensitively and preserves first-seen order for an app-container', () => {
+ const app = makeGuest(2, {
+ type: 'app-container',
+ workloadType: 'app-container',
+ platformType: 'docker',
+ dockerHostId: 'Host1',
+ contextLabel: 'host1',
+ node: 'node-a',
+ instance: 'inst-a',
+ });
+ // dedupeTrimmed lowercases keys for dedup but keeps original casing of first seen.
+ expect(getWorkloadHostHintCandidates(app)).toEqual(['Host1', 'node-a', 'inst-a']);
+ });
+
+ it('returns an empty array for an app-container whose candidates are all empty', () => {
+ const app = makeGuest(3, {
+ type: 'app-container',
+ workloadType: 'app-container',
+ platformType: 'docker',
+ dockerHostId: '',
+ contextLabel: ' ',
+ node: '',
+ instance: '',
+ });
+ expect(getWorkloadHostHintCandidates(app)).toEqual([]);
+ });
+
+ it('dedupes node/instance for a vm through the else branch', () => {
+ const vm = makeGuest(4, {
+ type: 'vm',
+ workloadType: 'vm',
+ node: 'dup',
+ instance: 'dup',
+ contextLabel: 'ctx-a',
+ });
+ // else arm: dedupeTrimmed([node, instance, contextLabel]) -> node and instance collapse.
+ expect(getWorkloadHostHintCandidates(vm)).toEqual(['dup', 'ctx-a']);
+ });
+
+ it('routes a system-container through the else branch', () => {
+ const lxc = makeGuest(5, {
+ type: 'lxc',
+ workloadType: 'system-container',
+ node: 'node-lxc',
+ instance: 'cluster-lxc',
+ contextLabel: 'ctx-lxc',
+ });
+ expect(getWorkloadHostHintCandidates(lxc)).toEqual([
+ 'node-lxc',
+ 'cluster-lxc',
+ 'ctx-lxc',
+ ]);
+ });
+ });
+
+ describe('getWorkloadAlertResourceIdCandidates', () => {
+ it('routes a vm through guestOverrideIdCandidates and emits stable + canonical + legacy ids', () => {
+ const vm = makeGuest(1, {
+ id: 'vm-resource-hash',
+ vmid: 103,
+ type: 'vm',
+ workloadType: 'vm',
+ node: 'pve1',
+ instance: 'cluster-a',
+ });
+ // type === 'vm' -> guestOverrideIdCandidates(guest); instance !== node so the
+ // stable guest: key and the legacy cluster key are both produced.
+ expect(getWorkloadAlertResourceIdCandidates(vm)).toEqual([
+ 'guest:cluster-a:103',
+ 'cluster-a:pve1:103',
+ 'vm-resource-hash',
+ 'cluster-a-103',
+ 'cluster-a-pve1-103',
+ ]);
+ });
+
+ it('routes a system-container through guestOverrideIdCandidates', () => {
+ const lxc = makeGuest(2, {
+ id: 'lxc-100',
+ vmid: 100,
+ type: 'lxc',
+ workloadType: 'system-container',
+ node: 'node-a',
+ instance: 'cluster-a',
+ });
+ expect(getWorkloadAlertResourceIdCandidates(lxc)).toEqual([
+ 'guest:cluster-a:100',
+ 'cluster-a:node-a:100',
+ 'lxc-100',
+ 'cluster-a-100',
+ 'cluster-a-node-a-100',
+ ]);
+ });
+
+ it('builds docker:host/container override ids for a docker-managed app-container with discovery', () => {
+ const app = makeGuest(3, {
+ id: 'app-container:docker-host-1:container-abc123',
+ type: 'app-container',
+ workloadType: 'app-container',
+ platformType: 'docker',
+ dockerHostId: 'docker-host-1',
+ containerId: 'container-abc123',
+ node: '',
+ instance: '',
+ });
+ // discoveryTarget resolved (docker-managed) -> agentId/resourceId feed host and
+ // container candidate lists; shortId = last id segment = container-abc123, and the
+ // canonical id is appended. node/instance blanked to isolate the discovery-driven host.
+ expect(getWorkloadAlertResourceIdCandidates(app)).toEqual([
+ 'docker:docker-host-1/container-abc123',
+ 'docker:docker-host-1/app-container:docker-host-1:container-abc123',
+ 'app-container:docker-host-1:container-abc123',
+ ]);
+ });
+
+ it('falls back to guest.id for shortId when the id has no usable segments', () => {
+ const app = makeGuest(4, {
+ id: '',
+ type: 'app-container',
+ workloadType: 'app-container',
+ platformType: 'docker',
+ dockerHostId: 'h1',
+ containerId: 'c1',
+ node: '',
+ instance: '',
+ });
+ // idSegments (after filter(Boolean)) is empty -> `idSegments[last] || guest.id`
+ // right operand fires; empty guest.id then drops out of dedupeTrimmed.
+ expect(getWorkloadAlertResourceIdCandidates(app)).toEqual(['docker:h1/c1']);
+ });
+
+ it('still emits docker:-prefixed ids for a non-docker (truenas) app-container with no discovery', () => {
+ const truenas = makeGuest(5, {
+ id: 'app-container:truenas-main:nextcloud',
+ type: 'app-container',
+ workloadType: 'app-container',
+ platformType: 'truenas',
+ dockerHostId: '',
+ node: 'truenas-main',
+ instance: 'truenas-main',
+ });
+ // resolveDiscoveryTargetForWorkload -> null (not docker-managed), so
+ // discoveryTarget?.agentId / resourceId are undefined; hostCandidates=[truenas-main]
+ // (node + instance collapse), shortId = nextcloud.
+ expect(getWorkloadAlertResourceIdCandidates(truenas)).toEqual([
+ 'docker:truenas-main/nextcloud',
+ 'docker:truenas-main/app-container:truenas-main:nextcloud',
+ 'app-container:truenas-main:nextcloud',
+ ]);
+ });
+
+ it('routes a pod through the fallback else branch returning the canonical id only', () => {
+ const pod = makeGuest(6, {
+ id: 'k8s:cluster-a:pod:pod-uid-1',
+ type: 'pod',
+ workloadType: 'pod',
+ node: 'worker-a',
+ instance: 'cluster-a',
+ });
+ // type === 'pod' -> else: dedupeTrimmed([getCanonicalWorkloadId(guest), guest.id]).
+ // getCanonicalWorkloadId returns guest.id for pods -> collapses to a single entry.
+ expect(getWorkloadAlertResourceIdCandidates(pod)).toEqual([
+ 'k8s:cluster-a:pod:pod-uid-1',
+ ]);
+ });
+ });
+});
diff --git a/frontend-modern/src/features/platformNavigation/__tests__/platformNavigationModel.branchcov2.test.ts b/frontend-modern/src/features/platformNavigation/__tests__/platformNavigationModel.branchcov2.test.ts
new file mode 100644
index 0000000000..284951d4de
--- /dev/null
+++ b/frontend-modern/src/features/platformNavigation/__tests__/platformNavigationModel.branchcov2.test.ts
@@ -0,0 +1,563 @@
+import { describe, expect, it } from 'vitest';
+import type { Resource } from '@/types/resource';
+import {
+ buildNavigableResourcePlatformScopeSet,
+ buildPrimaryPlatformNavigationVisibility,
+ collectResourcePlatformEvidence,
+ createEmptyPlatformNavigationVisibility,
+ filterPlatformNavigationShortcuts,
+ platformNavigationVisibilityFromResources,
+ type PlatformNavigationShortcut,
+ type PlatformNavigationVisibility,
+} from '../platformNavigationModel';
+
+// ---------------------------------------------------------------------------
+// Fixture builder — mirrors the sibling platformNavigationModel.test.ts
+// factory so import style and default platform posture stay aligned.
+// ---------------------------------------------------------------------------
+
+const resource = (overrides: Partial<Resource>): Resource =>
+ ({
+ id: overrides.id ?? 'resource-1',
+ name: overrides.name ?? overrides.id ?? 'resource-1',
+ displayName: overrides.displayName ?? overrides.name ?? overrides.id ?? 'resource-1',
+ type: overrides.type ?? 'agent',
+ platformId: overrides.platformId ?? 'platform-1',
+ platformType: overrides.platformType ?? 'agent',
+ sourceType: overrides.sourceType ?? 'api',
+ status: overrides.status ?? 'online',
+ lastSeen: overrides.lastSeen ?? 1_700_000_000_000,
+ ...overrides,
+ }) as Resource;
+
+const ALL_FALSE_VISIBILITY: PlatformNavigationVisibility = {
+ proxmox: false,
+ docker: false,
+ kubernetes: false,
+ truenas: false,
+ vmware: false,
+ standalone: false,
+};
+
+// ===========================================================================
+// addManifestPlatformId — module-private, exercised transitively through
+// collectResourcePlatformEvidence (its only call site among exported funcs).
+//
+// Branches:
+// a) normalized is null (value doesn't normalize to a known platform)
+// b) normalized === 'generic'
+// c) getSourcePlatformManifestEntry(normalized) is null (e.g. 'availability')
+// d) valid — adds the normalized id
+// ===========================================================================
+
+describe('addManifestPlatformId (via collectResourcePlatformEvidence)', () => {
+ it('skips a platformType that normalizes to null (unknown value)', () => {
+ // normalizeSourcePlatformKey('zzz-unknown') → null → early return, no add.
+ // resolveResourcePlatformType also yields null, so ids stays empty.
+ const r = resource({
+ id: 'unknown-pt',
+ platformType: 'zzz-unknown' as unknown as Resource['platformType'],
+ type: 'agent',
+ });
+ expect(collectResourcePlatformEvidence(r)).toEqual([]);
+ });
+
+ it('skips a platformType that normalizes to "generic"', () => {
+ // normalizeSourcePlatformKey('generic') → 'generic' → early return, no add.
+ const r = resource({
+ id: 'generic-pt',
+ platformType: 'generic',
+ type: 'agent',
+ });
+ expect(collectResourcePlatformEvidence(r)).toEqual([]);
+ });
+
+ it('skips a source that normalizes to a known key without a manifest entry (availability)', () => {
+ // normalizeSourcePlatformKey('availability') → 'availability', but
+ // getSourcePlatformManifestEntry('availability') → null → early return.
+ // 'agent' is still admitted from platformType.
+ const r = resource({
+ id: 'avail-src',
+ platformType: 'agent',
+ sources: ['availability'],
+ type: 'agent',
+ });
+ expect(collectResourcePlatformEvidence(r)).toEqual(['agent']);
+ });
+
+ it('skips "generic" in platformScopes but admits a valid scope alongside it', () => {
+ // platformScopes: ['generic', 'docker'] → 'generic' skipped, 'docker' added.
+ // Early-return path fires; addDirectDockerRuntimeEvidence does not add
+ // (ids has 'docker', not 'agent').
+ const r = resource({
+ id: 'mixed-scopes',
+ platformType: 'agent',
+ platformScopes: ['generic', 'docker'],
+ type: 'agent',
+ });
+ expect(collectResourcePlatformEvidence(r)).toEqual(['docker']);
+ });
+});
+
+// ===========================================================================
+// addDirectDockerRuntimeEvidence — module-private, exercised transitively
+// through collectResourcePlatformEvidence's early-return path (platformScopes
+// non-empty → ids.size > 0).
+//
+// Branches:
+// 1) resource.platformType normalizes to 'docker'
+// 2) resolveResourcePlatformType(resource) normalizes to 'docker'
+// 3) DOCKER_RESOURCE_TYPES.has(resource.type)
+// 4) ids.has('agent') && hasDockerRuntimeHostEvidence(resource)
+// 5) none of the above — no docker added
+// ===========================================================================
+
+describe('addDirectDockerRuntimeEvidence (via collectResourcePlatformEvidence early-return path)', () => {
+ it('adds docker when resource.platformType is "docker" (branch 1)', () => {
+ const r = resource({
+ id: 'docker-pt',
+ platformType: 'docker',
+ platformScopes: ['agent'],
+ type: 'agent',
+ });
+ expect(collectResourcePlatformEvidence(r)).toEqual(['agent', 'docker']);
+ });
+
+ it('adds docker when resolvedPlatformType is "docker" via sources fallback (branch 2)', () => {
+ // platformType is empty → resolveResourcePlatformType falls back to
+ // sources ['docker'] → returns 'docker'.
+ const r = resource({
+ id: 'resolved-docker',
+ platformType: '' as unknown as Resource['platformType'],
+ sources: ['docker'],
+ platformScopes: ['agent'],
+ type: 'agent',
+ });
+ expect(collectResourcePlatformEvidence(r)).toEqual(['agent', 'docker']);
+ });
+
+ it('adds docker when resource.type is a DOCKER_RESOURCE_TYPE (branch 3)', () => {
+ // type 'docker-service' is in DOCKER_RESOURCE_TYPES but
+ // hasDockerRuntimeHostEvidence returns false for it (not 'docker-host',
+ // not 'agent'), isolating branch 3 from branch 4.
+ const r = resource({
+ id: 'docker-svc',
+ platformType: 'truenas',
+ platformScopes: ['truenas'],
+ type: 'docker-service',
+ });
+ expect(collectResourcePlatformEvidence(r)).toEqual(['truenas', 'docker']);
+ });
+
+ it('does not add docker when agent scope lacks runtime evidence (branch 4 negative)', () => {
+ // ids has 'agent' but hasDockerRuntimeHostEvidence is false (no docker
+ // facet), so branch 4's condition is not met.
+ const r = resource({
+ id: 'agent-no-docker',
+ platformType: 'agent',
+ platformScopes: ['agent'],
+ type: 'agent',
+ });
+ expect(collectResourcePlatformEvidence(r)).toEqual(['agent']);
+ });
+});
+
+// ===========================================================================
+// collectResourcePlatformEvidence — full-path facet branches
+//
+// Each if-block has three OR arms (where applicable): resource.type,
+// resource.<facet>, asRecord(platformData?.<facet>). Using platformType
+// 'generic' ensures no 'agent' is added, so the only id in the result
+// comes from the facet under test.
+// ===========================================================================
+
+describe('collectResourcePlatformEvidence — full-path PBS evidence', () => {
+ it('admits proxmox-pbs from the resource.pbs facet', () => {
+ const r = resource({
+ id: 'pbs-facet',
+ platformType: 'generic',
+ type: 'agent',
+ pbs: { hostname: 'pbs-1' },
+ });
+ expect(collectResourcePlatformEvidence(r)).toEqual(['proxmox-pbs']);
+ });
+
+ it('admits proxmox-pbs from platformData.pbs', () => {
+ const r = resource({
+ id: 'pbs-platformdata',
+ platformType: 'generic',
+ type: 'agent',
+ platformData: { pbs: { hostname: 'pbs-1' } },
+ });
+ expect(collectResourcePlatformEvidence(r)).toEqual(['proxmox-pbs']);
+ });
+});
+
+describe('collectResourcePlatformEvidence — full-path PMG evidence', () => {
+ it('admits proxmox-pmg from the resource.pmg facet', () => {
+ const r = resource({
+ id: 'pmg-facet',
+ platformType: 'generic',
+ type: 'agent',
+ pmg: { hostname: 'pmg-1' },
+ });
+ expect(collectResourcePlatformEvidence(r)).toEqual(['proxmox-pmg']);
+ });
+
+ it('admits proxmox-pmg from platformData.pmg', () => {
+ const r = resource({
+ id: 'pmg-platformdata',
+ platformType: 'generic',
+ type: 'agent',
+ platformData: { pmg: { hostname: 'pmg-1' } },
+ });
+ expect(collectResourcePlatformEvidence(r)).toEqual(['proxmox-pmg']);
+ });
+});
+
+describe('collectResourcePlatformEvidence — full-path Proxmox PVE evidence', () => {
+ it('admits proxmox-pve from the resource.proxmox facet', () => {
+ const r = resource({
+ id: 'proxmox-facet',
+ platformType: 'generic',
+ type: 'agent',
+ proxmox: { vmid: 100 },
+ });
+ expect(collectResourcePlatformEvidence(r)).toEqual(['proxmox-pve']);
+ });
+
+ it('admits proxmox-pve from platformData.proxmox', () => {
+ const r = resource({
+ id: 'proxmox-platformdata',
+ platformType: 'generic',
+ type: 'agent',
+ platformData: { proxmox: { node: 'pve-1' } },
+ });
+ expect(collectResourcePlatformEvidence(r)).toEqual(['proxmox-pve']);
+ });
+});
+
+describe('collectResourcePlatformEvidence — full-path Ceph evidence', () => {
+ it('admits proxmox-pve from resource.type === "ceph"', () => {
+ const r = resource({
+ id: 'ceph-type',
+ platformType: 'generic',
+ type: 'ceph',
+ });
+ expect(collectResourcePlatformEvidence(r)).toEqual(['proxmox-pve']);
+ });
+
+ it('admits proxmox-pve from the resource.ceph facet', () => {
+ const r = resource({
+ id: 'ceph-facet',
+ platformType: 'generic',
+ type: 'agent',
+ ceph: {
+ healthStatus: 'ok',
+ numMons: 1,
+ numMgrs: 1,
+ numOsds: 1,
+ numOsdsUp: 1,
+ numOsdsIn: 1,
+ numPGs: 1,
+ },
+ });
+ expect(collectResourcePlatformEvidence(r)).toEqual(['proxmox-pve']);
+ });
+
+ it('admits proxmox-pve from platformData.ceph', () => {
+ const r = resource({
+ id: 'ceph-platformdata',
+ platformType: 'generic',
+ type: 'agent',
+ platformData: { ceph: { healthStatus: 'ok' } },
+ });
+ expect(collectResourcePlatformEvidence(r)).toEqual(['proxmox-pve']);
+ });
+});
+
+describe('collectResourcePlatformEvidence — full-path VMware evidence', () => {
+ it('admits vmware-vsphere from the resource.vmware facet', () => {
+ const r = resource({
+ id: 'vmware-facet',
+ platformType: 'generic',
+ type: 'agent',
+ vmware: { connectionName: 'vc-1' },
+ });
+ expect(collectResourcePlatformEvidence(r)).toEqual(['vmware-vsphere']);
+ });
+
+ it('admits vmware-vsphere from platformData.vmware', () => {
+ const r = resource({
+ id: 'vmware-platformdata',
+ platformType: 'generic',
+ type: 'agent',
+ platformData: { vmware: { connectionName: 'vc-1' } },
+ });
+ expect(collectResourcePlatformEvidence(r)).toEqual(['vmware-vsphere']);
+ });
+});
+
+describe('collectResourcePlatformEvidence — full-path Kubernetes evidence', () => {
+ it('admits kubernetes from the resource.kubernetes facet', () => {
+ const r = resource({
+ id: 'k8s-facet',
+ platformType: 'generic',
+ type: 'agent',
+ kubernetes: { clusterName: 'k8s-1' },
+ });
+ expect(collectResourcePlatformEvidence(r)).toEqual(['kubernetes']);
+ });
+
+ it('admits kubernetes from platformData.kubernetes', () => {
+ const r = resource({
+ id: 'k8s-platformdata',
+ platformType: 'generic',
+ type: 'agent',
+ platformData: { kubernetes: { clusterName: 'k8s-1' } },
+ });
+ expect(collectResourcePlatformEvidence(r)).toEqual(['kubernetes']);
+ });
+});
+
+// ===========================================================================
+// collectResourcePlatformEvidence — full-path runtime/type branches
+// ===========================================================================
+
+describe('collectResourcePlatformEvidence — full-path Docker and Kubernetes type branches', () => {
+ it('admits docker from hasDockerRuntimeHostEvidence in the full path', () => {
+ // type 'agent' + docker.runtime set → hasDockerRuntimeHostEvidence true.
+ // This is the FULL path (no platformScopes), distinct from the
+ // early-return path tested by the sibling test.
+ const r = resource({
+ id: 'docker-runtime-fullpath',
+ platformType: 'generic',
+ type: 'agent',
+ docker: { runtime: 'docker' },
+ });
+ expect(collectResourcePlatformEvidence(r)).toEqual(['docker']);
+ });
+
+ it('admits docker from DOCKER_RESOURCE_TYPES in the full path', () => {
+ // type 'docker-service' → hasDockerRuntimeHostEvidence false (not
+ // 'docker-host', not 'agent'), but DOCKER_RESOURCE_TYPES.has is true.
+ const r = resource({
+ id: 'docker-service-fullpath',
+ platformType: 'generic',
+ type: 'docker-service',
+ });
+ expect(collectResourcePlatformEvidence(r)).toEqual(['docker']);
+ });
+
+ it('admits kubernetes from KUBERNETES_RESOURCE_TYPES', () => {
+ const r = resource({
+ id: 'k8s-cluster-type',
+ platformType: 'generic',
+ type: 'k8s-cluster',
+ });
+ expect(collectResourcePlatformEvidence(r)).toEqual(['kubernetes']);
+ });
+});
+
+describe('collectResourcePlatformEvidence — full-path source-derivation branches', () => {
+ it('admits a platform id from resource.sources via addManifestPlatformId', () => {
+ const r = resource({
+ id: 'sources-derived',
+ platformType: 'generic',
+ type: 'agent',
+ sources: ['docker'],
+ });
+ expect(collectResourcePlatformEvidence(r)).toEqual(['docker']);
+ });
+
+ it('admits a platform id from platformData.sources array via addPlatformDataSources', () => {
+ const r = resource({
+ id: 'platformdata-sources',
+ platformType: 'generic',
+ type: 'agent',
+ platformData: { sources: ['docker'] },
+ });
+ expect(collectResourcePlatformEvidence(r)).toEqual(['docker']);
+ });
+});
+
+// ===========================================================================
+// buildNavigableResourcePlatformScopeSet
+//
+// Branches:
+// - manifestEntry is null → continue (unreachable through normal inputs;
+// collectResourcePlatformEvidence only returns ids with manifest entries)
+// - !NAVIGABLE_PLATFORM_ID_SET.has(manifestEntry.id) → continue
+// - both checks pass → add to set
+// ===========================================================================
+
+describe('buildNavigableResourcePlatformScopeSet', () => {
+ it('returns an empty set for no resources', () => {
+ expect(buildNavigableResourcePlatformScopeSet([])).toEqual(new Set<string>());
+ });
+
+ it('includes navigable platform ids and excludes non-navigable ones', () => {
+ // 'proxmox-pve' and 'docker' are navigable (in SUPPORTED_PLATFORM_IDS).
+ // 'unraid' has a manifest entry but is presentation-only (not in
+ // NAVIGABLE_PLATFORM_ID_SET), so it is skipped.
+ const resources = [
+ resource({ id: 'pve-1', platformType: 'proxmox-pve' }),
+ resource({ id: 'docker-1', platformType: 'docker' }),
+ resource({ id: 'unraid-1', platformType: 'unraid' }),
+ ];
+ expect(buildNavigableResourcePlatformScopeSet(resources)).toEqual(
+ new Set(['proxmox-pve', 'docker']),
+ );
+ });
+});
+
+// ===========================================================================
+// buildPrimaryPlatformNavigationVisibility
+//
+// Branches:
+// - hasAvailabilityEndpoints: three OR arms
+// a) resource.type === 'network-endpoint'
+// b) resource.platformType === 'availability'
+// c) resource.sources?.includes('availability')
+// - standalone: isPulseAgentPlatformResource || hasAvailabilityEndpoints
+// - per-platform scope .some() checks
+// ===========================================================================
+
+describe('buildPrimaryPlatformNavigationVisibility — standalone via availability endpoints', () => {
+ it('shows standalone when resource.type is "network-endpoint"', () => {
+ const visibility = buildPrimaryPlatformNavigationVisibility([
+ resource({ id: 'endpoint-1', type: 'network-endpoint', platformType: 'availability' }),
+ ]);
+ expect(visibility.standalone).toBe(true);
+ });
+
+ it('shows standalone when resource.platformType is "availability"', () => {
+ const visibility = buildPrimaryPlatformNavigationVisibility([
+ resource({ id: 'avail-1', type: 'agent', platformType: 'availability' }),
+ ]);
+ expect(visibility.standalone).toBe(true);
+ });
+
+ it('shows standalone when resource.sources includes "availability"', () => {
+ const visibility = buildPrimaryPlatformNavigationVisibility([
+ resource({ id: 'avail-src-1', type: 'agent', platformType: 'agent', sources: ['availability'] }),
+ ]);
+ expect(visibility.standalone).toBe(true);
+ });
+});
+
+describe('buildPrimaryPlatformNavigationVisibility — platform scope visibility', () => {
+ it('shows proxmox from a ceph resource type', () => {
+ const visibility = buildPrimaryPlatformNavigationVisibility([
+ resource({ id: 'ceph-1', type: 'ceph', platformType: 'generic' }),
+ ]);
+ expect(visibility.proxmox).toBe(true);
+ expect(visibility.docker).toBe(false);
+ expect(visibility.kubernetes).toBe(false);
+ expect(visibility.truenas).toBe(false);
+ expect(visibility.vmware).toBe(false);
+ expect(visibility.standalone).toBe(false);
+ });
+
+ it('returns all false for a non-navigable platform (unraid)', () => {
+ const visibility = buildPrimaryPlatformNavigationVisibility([
+ resource({ id: 'unraid-1', type: 'agent', platformType: 'unraid' }),
+ ]);
+ expect(visibility).toEqual(ALL_FALSE_VISIBILITY);
+ });
+});
+
+// ===========================================================================
+// createEmptyPlatformNavigationVisibility
+// ===========================================================================
+
+describe('createEmptyPlatformNavigationVisibility', () => {
+ it('returns every primary platform hidden', () => {
+ expect(createEmptyPlatformNavigationVisibility()).toEqual(ALL_FALSE_VISIBILITY);
+ });
+});
+
+// ===========================================================================
+// filterPlatformNavigationShortcuts
+//
+// Branches:
+// - !primaryPlatformNavigationIsVisible → continue (skip shortcut)
+// - visible → routes[shortcut.key] = shortcut.route
+// ===========================================================================
+
+describe('filterPlatformNavigationShortcuts', () => {
+ const allShortcuts: Record<string, PlatformNavigationShortcut> = {
+ proxmox: { key: 'p', route: '/proxmox' },
+ docker: { key: 'd', route: '/docker' },
+ kubernetes: { key: 'k', route: '/kubernetes' },
+ truenas: { key: 't', route: '/truenas' },
+ vmware: { key: 'v', route: '/vmware' },
+ standalone: { key: 's', route: '/standalone' },
+ };
+
+ it('returns all routes when every platform is visible', () => {
+ const allVisible: PlatformNavigationVisibility = {
+ proxmox: true,
+ docker: true,
+ kubernetes: true,
+ truenas: true,
+ vmware: true,
+ standalone: true,
+ };
+ expect(filterPlatformNavigationShortcuts(allShortcuts, allVisible)).toEqual({
+ p: '/proxmox',
+ d: '/docker',
+ k: '/kubernetes',
+ t: '/truenas',
+ v: '/vmware',
+ s: '/standalone',
+ });
+ });
+
+ it('returns an empty record when no platforms are visible', () => {
+ expect(filterPlatformNavigationShortcuts(allShortcuts, ALL_FALSE_VISIBILITY)).toEqual({});
+ });
+
+ it('returns only routes for visible platforms (mixed visibility)', () => {
+ const mixed: PlatformNavigationVisibility = {
+ proxmox: true,
+ docker: false,
+ kubernetes: true,
+ truenas: false,
+ vmware: false,
+ standalone: false,
+ };
+ expect(filterPlatformNavigationShortcuts(allShortcuts, mixed)).toEqual({
+ p: '/proxmox',
+ k: '/kubernetes',
+ });
+ });
+});
+
+// ===========================================================================
+// platformNavigationVisibilityFromResources
+//
+// Thin wrapper: delegates to buildPrimaryPlatformNavigationVisibility with
+// the Accessor's current value.
+// ===========================================================================
+
+describe('platformNavigationVisibilityFromResources', () => {
+ it('returns all-false for an empty accessor', () => {
+ expect(platformNavigationVisibilityFromResources(() => [])).toEqual(ALL_FALSE_VISIBILITY);
+ });
+
+ it('delegates to buildPrimaryPlatformNavigationVisibility for non-empty resources', () => {
+ const resources: readonly Resource[] = [
+ resource({ id: 'pve-1', platformType: 'proxmox-pve', type: 'agent' }),
+ resource({ id: 'docker-1', platformType: 'docker', type: 'docker-host' }),
+ ];
+ expect(platformNavigationVisibilityFromResources(() => resources)).toEqual({
+ proxmox: true,
+ docker: true,
+ kubernetes: false,
+ truenas: false,
+ vmware: false,
+ standalone: false,
+ });
+ });
+});
diff --git a/frontend-modern/src/features/storageBackups/__tests__/cephRecordPresentation.branchcov2.test.ts b/frontend-modern/src/features/storageBackups/__tests__/cephRecordPresentation.branchcov2.test.ts
new file mode 100644
index 0000000000..e7f31cb376
--- /dev/null
+++ b/frontend-modern/src/features/storageBackups/__tests__/cephRecordPresentation.branchcov2.test.ts
@@ -0,0 +1,633 @@
+import { describe, expect, it } from 'vitest';
+import type { CephCluster } from '@/types/api';
+import type { NormalizedHealth, StorageRecord } from '@/features/storageBackups/models';
+import {
+ consolidateCephClusterPoolRecords,
+ getCephClusterKeyFromStorageRecord,
+ getCephSummaryText,
+ isCephClusterPoolStorageRecord,
+} from '@/features/storageBackups/cephRecordPresentation';
+
+// ---------------------------------------------------------------------------
+// Fixture builders — mirror cephRecordPresentation.test.ts so casts and
+// import paths match the sibling suite. The defaults describe a healthy PVE
+// cephfs mount ("not" a cluster-internal pool row) so individual cases can
+// opt into pool-row synthesis by overriding `details`.
+// ---------------------------------------------------------------------------
+
+const makeRecord = (overrides: Partial<StorageRecord> = {}): StorageRecord => ({
+ id: 'storage-1',
+ name: 'ceph-pool',
+ category: 'pool',
+ health: 'healthy',
+ location: { label: 'pve1', scope: 'node' },
+ capacity: { totalBytes: 1_000, usedBytes: 400, freeBytes: 600, usagePercent: 40 },
+ capabilities: ['capacity', 'replication'],
+ source: {
+ platform: 'proxmox-pve',
+ family: 'virtualization',
+ origin: 'resource',
+ adapterId: 'resource-storage',
+ },
+ observedAt: Date.now(),
+ details: { type: 'rbd', parentId: 'cluster-a' },
+ refs: { platformEntityId: 'cluster-a' },
+ ...overrides,
+});
+
+// A cluster-internal Ceph pool row (models.StorageFromCephPool): type "ceph"
+// homed on the "cluster" pseudo-node.
+const makePoolRecord = (overrides: Partial<StorageRecord> = {}): StorageRecord =>
+ makeRecord({
+ id: 'pool-row',
+ name: 'cephfs-data',
+ health: 'warning',
+ details: { type: 'ceph', node: 'cluster', status: 'degraded' },
+ ...overrides,
+ });
+
+// A PVE-side mount row that is NOT itself a cluster pool row.
+const makeMountRecord = (overrides: Partial<StorageRecord> = {}): StorageRecord =>
+ makeRecord({
+ id: 'mount-row',
+ name: 'cephfs-data',
+ health: 'healthy',
+ details: { type: 'cephfs', node: 'shared', status: 'online' },
+ ...overrides,
+ });
+
+const makeCluster = (overrides: Partial<CephCluster> = {}): CephCluster =>
+ ({
+ id: 'ceph-1',
+ instance: 'cluster-a',
+ name: 'cluster-a Ceph',
+ health: 'HEALTH_OK',
+ healthMessage: '',
+ totalBytes: 1_000,
+ usedBytes: 400,
+ availableBytes: 600,
+ usagePercent: 40,
+ numMons: 3,
+ numMgrs: 2,
+ numOsds: 6,
+ numOsdsUp: 6,
+ numOsdsIn: 6,
+ numPGs: 256,
+ pools: [],
+ services: [],
+ lastUpdated: Date.now(),
+ ...overrides,
+ }) as CephCluster;
+
+// ===========================================================================
+// isCephClusterPoolStorageRecord
+// ===========================================================================
+
+describe('isCephClusterPoolStorageRecord branch coverage', () => {
+ it('returns false on the early-return arm when the derived type is not "ceph"', () => {
+ // type defaults to 'rbd' → getStorageRecordType !== 'ceph' → false.
+ expect(isCephClusterPoolStorageRecord(makeRecord())).toBe(false);
+ // category-derived type: no details.type, category 'pool' → 'pool' → false.
+ expect(
+ isCephClusterPoolStorageRecord(
+ makeRecord({ details: undefined, category: 'pool' }) as StorageRecord,
+ ),
+ ).toBe(false);
+ });
+
+ it('returns true when type is "ceph" and details.node === "cluster"', () => {
+ expect(
+ isCephClusterPoolStorageRecord(
+ makeRecord({ details: { type: 'ceph', node: 'cluster' } }),
+ ),
+ ).toBe(true);
+ });
+
+ it('returns false when type is "ceph" but details.node is not "cluster"', () => {
+ // Exercises the `details.node === 'cluster'` false arm with a valid ceph type.
+ expect(
+ isCephClusterPoolStorageRecord(
+ makeRecord({ details: { type: 'ceph', node: 'pve1' } }),
+ ),
+ ).toBe(false);
+ });
+
+ it('exercises the `(record.details || {})` defensive arm: details undefined with type "ceph"', () => {
+ // details is undefined → `(record.details || {})` yields {} → details.node
+ // is undefined → not 'cluster' → false. The type-only path proves the
+ // `|| {}` branch is taken (no throw, undefined.node coerced via {}).
+ expect(
+ isCephClusterPoolStorageRecord(
+ makeRecord({ details: { type: 'ceph' } }) as StorageRecord,
+ ),
+ ).toBe(false);
+ });
+});
+
+// ===========================================================================
+// consolidateCephClusterPoolRecords
+// (also exercises the module-private storageHealthRank, getRecordPoolDetail
+// and getRecordStatusDetail through the public surface)
+// ===========================================================================
+
+describe('consolidateCephClusterPoolRecords branch coverage', () => {
+ // ---- Branch: `poolRecords.length === 0` → returns the input reference ----
+ it('short-circuits and returns the exact input reference when there are no pool rows', () => {
+ const input: StorageRecord[] = [makeMountRecord(), makeMountRecord({ id: 'm2' })];
+ // Early return at `if (poolRecords.length === 0) return records;` — same ref.
+ expect(consolidateCephClusterPoolRecords(input)).toBe(input);
+ });
+
+ // ---- Branch: `consumedPoolIds.size === 0` → returns the input reference --
+ it('returns the exact input reference when pool rows exist but none match a mount', () => {
+ // A pool row plus a non-ceph record: the pool finds no ceph sibling, so
+ // consumedPoolIds stays empty and the second early-return fires.
+ const orphanPool = makePoolRecord({ id: 'orphan', name: 'unmatched-pool' });
+ const nonCeph = makeRecord({
+ id: 'local',
+ name: 'local-zfs',
+ details: { type: 'zfspool', node: 'pve1' },
+ capabilities: ['capacity'],
+ });
+ const input: StorageRecord[] = [orphanPool, nonCeph];
+ expect(consolidateCephClusterPoolRecords(input)).toBe(input);
+ });
+
+ // ---- Branch L83: `if (!pool) return record;` (record with no lifted pool) -
+ it('passes unrelated records through unchanged (by reference) during consolidation', () => {
+ const pool = makePoolRecord({ id: 'pool-1', name: 'cephfs-data', health: 'critical' });
+ const mount = makeMountRecord({ id: 'mount-1', name: 'cephfs-data' });
+ const unrelated = makeRecord({
+ id: 'unrelated-1',
+ name: 'local-zfs',
+ details: { type: 'zfspool', node: 'pve1' },
+ capabilities: ['capacity'],
+ });
+ const consolidated = consolidateCephClusterPoolRecords([pool, mount, unrelated]);
+ // Pool consumed; mount lifted; unrelated has no entry in liftBySiblingId
+ // → the `if (!pool) return record;` arm returns it by reference.
+ expect(consolidated.map((r) => r.id)).toEqual(['mount-1', 'unrelated-1']);
+ const unrelatedOut = consolidated.find((r) => r.id === 'unrelated-1');
+ expect(unrelatedOut).toBe(unrelated);
+ });
+
+ // ---- Branch L72 (!existing → set) + L84 lift + L85 status-detail arm ----
+ it('lifts the pool health onto a healthier mount and synthesizes a status from details.status', () => {
+ const pool = makePoolRecord({
+ id: 'pool-1',
+ name: 'cephfs-data',
+ health: 'warning',
+ details: { type: 'ceph', node: 'cluster', status: 'degraded' },
+ });
+ const mount = makeMountRecord({ id: 'mount-1', name: 'cephfs-data', health: 'healthy' });
+ const [survivor] = consolidateCephClusterPoolRecords([pool, mount]);
+ expect(survivor.id).toBe('mount-1');
+ expect(survivor.health).toBe('warning');
+ // getRecordStatusDetail string arm → 'degraded' feeds poolStatus.
+ expect(survivor.statusLabel).toBe('degraded');
+ expect(survivor.details?.status).toBe('degraded');
+ // No issueSummary on the pool → synthesized fallback string.
+ expect(survivor.issueSummary).toBe('Ceph reports pool cephfs-data degraded');
+ });
+
+ // ---- Branch L72 (existing present, new pool sicker → replace) -----------
+ it('keeps the sicker of two pools that mount onto the same sibling', () => {
+ const poolWarning = makePoolRecord({
+ id: 'pool-w',
+ name: 'cephfs-data',
+ health: 'warning',
+ details: { type: 'ceph', node: 'cluster', status: 'degraded' },
+ });
+ const poolCritical = makePoolRecord({
+ id: 'pool-c',
+ name: 'cephfs-data',
+ health: 'critical',
+ details: { type: 'ceph', node: 'cluster', status: 'unavailable' },
+ });
+ const mount = makeMountRecord({ id: 'mount-1', name: 'cephfs-data', health: 'healthy' });
+ // storageHealthRank('critical')=4 > storageHealthRank('warning')=2 → replace.
+ const consolidated = consolidateCephClusterPoolRecords([poolWarning, poolCritical, mount]);
+ expect(consolidated.map((r) => r.id)).toEqual(['mount-1']);
+ expect(consolidated[0].health).toBe('critical');
+ expect(consolidated[0].statusLabel).toBe('unavailable');
+ });
+
+ // ---- Branch L72 (existing present, new pool NOT sicker → keep existing) -
+ it('does not replace the existing lift when the second pool is not sicker', () => {
+ const poolCritical = makePoolRecord({
+ id: 'pool-c',
+ name: 'cephfs-data',
+ health: 'critical',
+ issueSummary: 'first pool wins',
+ details: { type: 'ceph', node: 'cluster', status: 'unavailable' },
+ });
+ const poolWarning = makePoolRecord({
+ id: 'pool-w',
+ name: 'cephfs-data',
+ health: 'warning',
+ issueSummary: 'second pool loses',
+ details: { type: 'ceph', node: 'cluster', status: 'degraded' },
+ });
+ const mount = makeMountRecord({ id: 'mount-1', name: 'cephfs-data', health: 'healthy' });
+ // storageHealthRank('warning')=2 > storageHealthRank('critical')=4 → false → keep critical.
+ const [survivor] = consolidateCephClusterPoolRecords([poolCritical, poolWarning, mount]);
+ expect(survivor.health).toBe('critical');
+ // existing (critical) pool's issueSummary is preserved verbatim.
+ expect(survivor.issueSummary).toBe('first pool wins');
+ });
+
+ // ---- Branch L84: pool not sicker than mount → record unchanged by ref ----
+ it('leaves a mount untouched (by reference) when the pool is not sicker than it', () => {
+ const healthyPool = makePoolRecord({
+ id: 'pool-1',
+ name: 'cephfs-data',
+ health: 'healthy',
+ details: { type: 'ceph', node: 'cluster', status: 'available' },
+ });
+ const sickMount = makeMountRecord({
+ id: 'mount-1',
+ name: 'cephfs-data',
+ health: 'critical',
+ statusLabel: 'unavailable',
+ });
+ // storageHealthRank('healthy')=0 <= storageHealthRank('critical')=4 → return record.
+ const consolidated = consolidateCephClusterPoolRecords([healthyPool, sickMount]);
+ expect(consolidated).toEqual([sickMount]);
+ expect(consolidated[0]).toBe(sickMount);
+ });
+
+ // ---- storageHealthRank `?? 0` arm: unrecognized record health → rank 0 --
+ it('treats an unrecognized mount health as rank 0 so a sicker pool still lifts', () => {
+ const pool = makePoolRecord({
+ id: 'pool-1',
+ name: 'cephfs-data',
+ health: 'critical',
+ details: { type: 'ceph', node: 'cluster', status: 'unavailable' },
+ });
+ const mount = makeMountRecord({
+ id: 'mount-1',
+ name: 'cephfs-data',
+ // 'quarantined' is not in STORAGE_HEALTH_SEVERITY_RANK → `?? 0`.
+ health: 'quarantined' as unknown as NormalizedHealth,
+ });
+ const [survivor] = consolidateCephClusterPoolRecords([pool, mount]);
+ // pool rank 4 > record rank 0 → lift happens; the bogus record health is
+ // overwritten by the pool's 'critical'.
+ expect(survivor.id).toBe('mount-1');
+ expect(survivor.health).toBe('critical');
+ });
+
+ // ---- getRecordPoolDetail string arm + trim(): pool detail with whitespace
+ it('matches a mount via the backing pool detail and trims whitespace before comparing', () => {
+ const pool = makePoolRecord({
+ id: 'pool-1',
+ name: 'vm-pool',
+ health: 'critical',
+ details: { type: 'ceph', node: 'cluster', status: 'unavailable' },
+ });
+ const mount = makeMountRecord({
+ id: 'mount-1',
+ name: 'fast-rbd',
+ // details.pool has surrounding whitespace; getRecordPoolDetail trims it
+ // to 'vm-pool', which then equals pool.name.
+ details: { type: 'rbd', node: 'shared', pool: ' vm-pool ', status: 'online' },
+ });
+ const consolidated = consolidateCephClusterPoolRecords([pool, mount]);
+ expect(consolidated.map((r) => r.id)).toEqual(['mount-1']);
+ expect(consolidated[0].health).toBe('critical');
+ });
+
+ // ---- getRecordPoolDetail non-string arm: pool detail is a non-string ----
+ it('does not treat a non-string pool detail as a backing-pool match', () => {
+ const pool = makePoolRecord({
+ id: 'pool-1',
+ name: 'vm-pool',
+ health: 'critical',
+ details: { type: 'ceph', node: 'cluster', status: 'unavailable' },
+ });
+ const mount = makeMountRecord({
+ id: 'mount-1',
+ name: 'different-name',
+ // details.pool is a number → getRecordPoolDetail returns '' (the
+ // `typeof pool === 'string'` false arm). '' !== 'vm-pool' and the names
+ // differ too, so this pool is orphaned and the mount is left as-is.
+ details: { type: 'rbd', node: 'shared', pool: 999, status: 'online' } as Record<
+ string,
+ unknown
+ >,
+ });
+ const input: StorageRecord[] = [pool, mount];
+ // No sibling consumed → second early-return hands back the input reference.
+ expect(consolidateCephClusterPoolRecords(input)).toBe(input);
+ });
+
+ // ---- getRecordStatusDetail non-string arm → falls through to statusLabel -
+ it('falls back to pool.statusLabel when details.status is not a string', () => {
+ const pool = makePoolRecord({
+ id: 'pool-1',
+ name: 'cephfs-data',
+ health: 'warning',
+ statusLabel: 'down-label',
+ details: {
+ type: 'ceph',
+ node: 'cluster',
+ // status is a number → getRecordStatusDetail returns '' → the `||`
+ // chain falls through to pool.statusLabel ('down-label').
+ status: 42,
+ } as Record<string, unknown>,
+ });
+ const mount = makeMountRecord({ id: 'mount-1', name: 'cephfs-data', health: 'healthy' });
+ const [survivor] = consolidateCephClusterPoolRecords([pool, mount]);
+ expect(survivor.health).toBe('warning');
+ expect(survivor.statusLabel).toBe('down-label');
+ expect(survivor.details?.status).toBe('down-label');
+ expect(survivor.issueSummary).toBe('Ceph reports pool cephfs-data down-label');
+ });
+
+ // ---- getRecordStatusDetail empty → statusLabel empty → falls to health ---
+ it('falls back to pool.health when neither details.status nor statusLabel resolve', () => {
+ const pool = makePoolRecord({
+ id: 'pool-1',
+ name: 'cephfs-data',
+ health: 'critical',
+ statusLabel: undefined,
+ details: {
+ type: 'ceph',
+ node: 'cluster',
+ // status is a boolean → getRecordStatusDetail returns '' (non-string).
+ status: true,
+ } as Record<string, unknown>,
+ });
+ const mount = makeMountRecord({ id: 'mount-1', name: 'cephfs-data', health: 'healthy' });
+ const [survivor] = consolidateCephClusterPoolRecords([pool, mount]);
+ // getRecordStatusDetail('') || statusLabel(undefined) || health('critical').
+ expect(survivor.statusLabel).toBe('critical');
+ expect(survivor.details?.status).toBe('critical');
+ expect(survivor.issueSummary).toBe('Ceph reports pool cephfs-data critical');
+ });
+
+ // ---- L91 `pool.issueSummary?.trim() || ...` truthy arm ------------------
+ it('preserves the pool issueSummary verbatim when it trims to a non-empty value', () => {
+ const pool = makePoolRecord({
+ id: 'pool-1',
+ name: 'cephfs-data',
+ health: 'warning',
+ issueSummary: 'Ceph cluster HEALTH_WARN',
+ details: { type: 'ceph', node: 'cluster', status: 'degraded' },
+ });
+ const mount = makeMountRecord({ id: 'mount-1', name: 'cephfs-data', health: 'healthy' });
+ const [survivor] = consolidateCephClusterPoolRecords([pool, mount]);
+ expect(survivor.issueSummary).toBe('Ceph cluster HEALTH_WARN');
+ });
+
+ // ---- L91 `pool.issueSummary?.trim() || ...` whitespace-only arm ---------
+ it('synthesizes the issue summary when the pool issueSummary is only whitespace', () => {
+ const pool = makePoolRecord({
+ id: 'pool-1',
+ name: 'cephfs-data',
+ health: 'warning',
+ issueSummary: ' ',
+ details: { type: 'ceph', node: 'cluster', status: 'degraded' },
+ });
+ const mount = makeMountRecord({ id: 'mount-1', name: 'cephfs-data', health: 'healthy' });
+ const [survivor] = consolidateCephClusterPoolRecords([pool, mount]);
+ // ' '.trim() === '' → falsy → synthesized fallback string.
+ expect(survivor.issueSummary).toBe('Ceph reports pool cephfs-data degraded');
+ });
+
+ // ---- L92 `{ ...(record.details || {}), status: poolStatus }` arm --------
+ it('preserves the surviving mount details and overlays the lifted status', () => {
+ const pool = makePoolRecord({
+ id: 'pool-1',
+ name: 'cephfs-data',
+ health: 'warning',
+ details: { type: 'ceph', node: 'cluster', status: 'degraded' },
+ });
+ const mount = makeMountRecord({
+ id: 'mount-1',
+ name: 'cephfs-data',
+ health: 'healthy',
+ details: { type: 'cephfs', node: 'shared', status: 'online', extra: 'kept' },
+ });
+ const [survivor] = consolidateCephClusterPoolRecords([pool, mount]);
+ // record.details was truthy → spread keeps existing keys, status overridden.
+ expect(survivor.details).toEqual({
+ type: 'cephfs',
+ node: 'shared',
+ status: 'degraded',
+ extra: 'kept',
+ });
+ });
+});
+
+// ===========================================================================
+// getCephClusterKeyFromStorageRecord
+// ===========================================================================
+
+describe('getCephClusterKeyFromStorageRecord branch coverage', () => {
+ it('prefers refs.platformEntityId when it is a non-empty string', () => {
+ expect(getCephClusterKeyFromStorageRecord(makeRecord())).toBe('cluster-a');
+ });
+
+ it('uses details.parentId when refs is undefined (optional-chain short-circuit)', () => {
+ // refs undefined → `record.refs?.platformEntityId` is undefined → falls to
+ // parent. Exercises the `record.refs?.` optional-chain falsy arm.
+ const record = makeRecord({
+ refs: undefined,
+ details: { type: 'rbd', parentId: 'parent-key' },
+ });
+ expect(getCephClusterKeyFromStorageRecord(record)).toBe('parent-key');
+ });
+
+ it('uses details.parentId when refs.platformEntityId is an empty string', () => {
+ const record = makeRecord({
+ refs: { platformEntityId: '' },
+ details: { type: 'rbd', parentId: 'parent-key' },
+ });
+ expect(getCephClusterKeyFromStorageRecord(record)).toBe('parent-key');
+ });
+
+ it('coerces a non-string parentId to "" (defensive ternary false arm) then uses location.label', () => {
+ const record = makeRecord({
+ refs: { platformEntityId: '' },
+ details: { type: 'rbd', parentId: 999 } as Record<string, unknown>,
+ location: { label: 'loc-key', scope: 'cluster' },
+ });
+ // typeof parentId === 'string' is false → parent '' → next fallback wins.
+ expect(getCephClusterKeyFromStorageRecord(record)).toBe('loc-key');
+ });
+
+ it('falls back to location.label when refs and parentId are both absent', () => {
+ const record = makeRecord({
+ refs: undefined,
+ details: { type: 'rbd' },
+ location: { label: 'loc-key', scope: 'cluster' },
+ });
+ expect(getCephClusterKeyFromStorageRecord(record)).toBe('loc-key');
+ });
+
+ it('exercises the `(record.details || {})` arm then falls to source.platform', () => {
+ // details undefined → {} → parent '' → refs/platformEntityId absent →
+ // location.label '' → final fallback source.platform.
+ const record = makeRecord({
+ refs: undefined,
+ details: undefined,
+ location: { label: '', scope: 'cluster' },
+ source: {
+ platform: 'proxmox-pve',
+ family: 'virtualization',
+ origin: 'resource',
+ adapterId: 'resource-storage',
+ },
+ });
+ expect(getCephClusterKeyFromStorageRecord(record)).toBe('proxmox-pve');
+ });
+
+ it('reaches the source.platform final fallback when every higher-precedence key is empty', () => {
+ const record = makeRecord({
+ refs: { platformEntityId: '' },
+ details: { type: 'rbd', parentId: '' },
+ location: { label: '', scope: 'cluster' },
+ source: {
+ platform: 'truenas',
+ family: 'virtualization',
+ origin: 'resource',
+ adapterId: 'resource-storage',
+ },
+ });
+ expect(getCephClusterKeyFromStorageRecord(record)).toBe('truenas');
+ });
+});
+
+// ===========================================================================
+// getCephSummaryText
+// ===========================================================================
+
+describe('getCephSummaryText branch coverage', () => {
+ // ---- Cluster arm: capacity + OSDs + PGs (all three parts) ---------------
+ it('formats capacity, OSDs and PGs parts when the cluster provides all three', () => {
+ // totalBytes 1000, usedBytes 400 → 40% → "400 B / 1000 B (40%)".
+ // numOsds/numOsdsUp finite (6/6) and numPGs > 0 (256) → all parts pushed.
+ expect(getCephSummaryText(makeRecord(), makeCluster())).toBe(
+ '400 B / 1000 B (40%) • OSDs 6/6 • PGs 256',
+ );
+ });
+
+ // ---- Cluster arm: percent===0 when totalBytes is 0 (no division) -------
+ it('renders a zero-capacity cluster as "0 B / 0 B (0%)" without dividing by zero', () => {
+ expect(
+ getCephSummaryText(
+ makeRecord(),
+ makeCluster({ totalBytes: 0, usedBytes: 0, availableBytes: 0, numOsds: NaN, numPGs: 0 }),
+ ),
+ ).toBe('0 B / 0 B (0%)');
+ });
+
+ // ---- Cluster arm: OSDs omitted when numOsds/numOsdsUp not finite --------
+ it('omits the OSDs part when numOsds is NaN', () => {
+ expect(
+ getCephSummaryText(
+ makeRecord(),
+ makeCluster({ numOsds: NaN, numOsdsUp: 6, numPGs: 0 }),
+ ),
+ ).toBe('400 B / 1000 B (40%)');
+ });
+
+ it('omits the OSDs part when numOsdsUp is NaN even if numOsds is finite', () => {
+ expect(
+ getCephSummaryText(
+ makeRecord(),
+ makeCluster({ numOsds: 6, numOsdsUp: NaN, numPGs: 0 }),
+ ),
+ ).toBe('400 B / 1000 B (40%)');
+ });
+
+ // ---- Cluster arm: PGs omitted when numPGs is 0 or not finite ------------
+ it('keeps OSDs but omits PGs when numPGs is 0', () => {
+ expect(
+ getCephSummaryText(makeRecord(), makeCluster({ numPGs: 0 })),
+ ).toBe('400 B / 1000 B (40%) • OSDs 6/6');
+ });
+
+ it('omits PGs when numPGs is NaN (Number.isFinite false)', () => {
+ expect(
+ getCephSummaryText(makeRecord(), makeCluster({ numPGs: NaN })),
+ ).toBe('400 B / 1000 B (40%) • OSDs 6/6');
+ });
+
+ // ---- Cluster arm: large numPGs is rendered via toLocaleString ----------
+ it('renders a large numPGs count with toLocaleString grouping', () => {
+ expect(
+ getCephSummaryText(makeRecord(), makeCluster({ numPGs: 1_500 })),
+ ).toBe('400 B / 1000 B (40%) • OSDs 6/6 • PGs 1,500');
+ });
+
+ // ---- Cluster `|| 0` clamps: negative bytes treated as 0 ----------------
+ it('clamps negative cluster total/used bytes to 0 before formatting', () => {
+ // Math.max(0, totalBytes || 0): totalBytes -1000 is truthy → max(0,-1000)=0.
+ // usedBytes -400 → 0. percent total>0? no → 0.
+ expect(
+ getCephSummaryText(
+ makeRecord(),
+ makeCluster({
+ totalBytes: -1_000,
+ usedBytes: -400,
+ availableBytes: 0,
+ numOsds: NaN,
+ numPGs: 0,
+ }),
+ ),
+ ).toBe('0 B / 0 B (0%)');
+ });
+
+ // ---- Cluster guard false: totalBytes NaN → else (record capacity) branch
+ it('falls back to record capacity when cluster.totalBytes is not finite', () => {
+ // Number.isFinite(NaN) is false → the whole cluster arm is skipped.
+ expect(
+ getCephSummaryText(
+ makeRecord({ capacity: { totalBytes: 1_000, usedBytes: 400, freeBytes: 600, usagePercent: 40 } }),
+ makeCluster({ totalBytes: NaN }),
+ ),
+ ).toBe('400 B / 1000 B (40%)');
+ });
+
+ // ---- Cluster guard false: cluster null → else (record capacity) branch --
+ it('formats the record capacity summary when cluster is null', () => {
+ expect(
+ getCephSummaryText(
+ makeRecord({ capacity: { totalBytes: 1_000, usedBytes: 400, freeBytes: 600, usagePercent: 40 } }),
+ null,
+ ),
+ ).toBe('400 B / 1000 B (40%)');
+ });
+
+ // ---- Else branch: record total <= 0 → '' -------------------------------
+ it('returns the empty string when the record capacity total is <= 0 and there is no cluster', () => {
+ expect(
+ getCephSummaryText(
+ makeRecord({
+ capacity: { totalBytes: 0, usedBytes: 0, freeBytes: 0, usagePercent: 0 },
+ }),
+ null,
+ ),
+ ).toBe('');
+ });
+
+ // ---- Else branch: record `|| 0` clamps nullish bytes -------------------
+ it('treats null total/used bytes as 0 in the record fallback and returns ""', () => {
+ // totalBytes null → `record.capacity.totalBytes || 0` → 0 → total <= 0 → ''.
+ expect(
+ getCephSummaryText(
+ makeRecord({
+ capacity: {
+ totalBytes: null,
+ usedBytes: null,
+ freeBytes: null,
+ usagePercent: null,
+ },
+ }),
+ null,
+ ),
+ ).toBe('');
+ });
+});
diff --git a/frontend-modern/src/features/storageBackups/__tests__/storageModelCore.branchcov2.test.ts b/frontend-modern/src/features/storageBackups/__tests__/storageModelCore.branchcov2.test.ts
new file mode 100644
index 0000000000..a67236bda8
--- /dev/null
+++ b/frontend-modern/src/features/storageBackups/__tests__/storageModelCore.branchcov2.test.ts
@@ -0,0 +1,408 @@
+import { describe, expect, it } from 'vitest';
+import type { StorageCapability, StorageRecord } from '@/features/storageBackups/models';
+import {
+ findSelectedStorageNode,
+ groupStorageRecords,
+ matchesStorageRecordNode,
+ matchesStorageRecordSearch,
+ sortStorageRecords,
+ type StorageNodeOption,
+ type StorageSortContext,
+} from '@/features/storageBackups/storageModelCore';
+
+const makeNode = (overrides: Partial<StorageNodeOption> = {}): StorageNodeOption => ({
+ id: 'node-1',
+ label: 'pve1',
+ aliases: ['cluster-main', 'pve1.local'],
+ ...overrides,
+});
+
+const makeRecord = (overrides: Partial<StorageRecord> = {}): StorageRecord =>
+ ({
+ id: 'storage-1',
+ name: 'tank',
+ category: 'pool',
+ health: 'healthy',
+ location: { label: 'pve1', scope: 'node' },
+ capacity: { totalBytes: 100, usedBytes: 40, freeBytes: 60, usagePercent: 40 },
+ capabilities: ['capacity'],
+ source: {
+ platform: 'proxmox-pve',
+ family: 'virtualization',
+ origin: 'resource',
+ adapterId: 'resource-storage',
+ },
+ observedAt: Date.now(),
+ statusLabel: 'Healthy',
+ details: { node: 'pve1', nodeHints: ['cluster-main'] },
+ refs: { platformEntityId: '' },
+ ...overrides,
+ }) as StorageRecord;
+
+const growthEntry = (deltaBytes: number | null) => ({
+ deltaBytes,
+ label: deltaBytes === null ? '—' : `${deltaBytes}`,
+ title: 'growth',
+ toneClass: 'text-muted',
+});
+
+// ---------------------------------------------------------------------------
+// findSelectedStorageNode
+// ---------------------------------------------------------------------------
+
+describe('findSelectedStorageNode branch coverage', () => {
+ it('returns null for the "all" sentinel (early return)', () => {
+ expect(findSelectedStorageNode('all', [makeNode()])).toBeNull();
+ });
+
+ it('returns null when no node option matches (|| null arm)', () => {
+ expect(findSelectedStorageNode('does-not-exist', [makeNode()])).toBeNull();
+ });
+
+ it('returns null when the options array is empty (find -> undefined -> || null)', () => {
+ expect(findSelectedStorageNode('x', [])).toBeNull();
+ });
+
+ it('returns the exact matching node option', () => {
+ const a = makeNode({ id: 'a', label: 'alpha' });
+ const b = makeNode({ id: 'b', label: 'beta' });
+ expect(findSelectedStorageNode('b', [a, b])).toStrictEqual(b);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// matchesStorageRecordNode
+// ---------------------------------------------------------------------------
+
+describe('matchesStorageRecordNode branch coverage', () => {
+ it('returns true when node is null (!node early return)', () => {
+ expect(matchesStorageRecordNode(makeRecord(), null)).toBe(true);
+ });
+
+ it('matches via the node id against a record hint', () => {
+ const node = makeNode({ id: 'pve1', label: 'other', aliases: [] });
+ expect(matchesStorageRecordNode(makeRecord(), node)).toBe(true);
+ });
+
+ it('matches via an alias when id and label do not match any hint', () => {
+ const node = makeNode({ id: 'unrelated', label: 'unrelated', aliases: ['cluster-main'] });
+ expect(matchesStorageRecordNode(makeRecord(), node)).toBe(true);
+ });
+
+ it('uses [] when node.aliases is undefined (|| [] arm)', () => {
+ const node: StorageNodeOption = { id: 'pve1', label: 'pve1' };
+ expect(matchesStorageRecordNode(makeRecord(), node)).toBe(true);
+ });
+
+ it('normalizes falsy id/label to "" and drops them ((value || "") + filter(Boolean))', () => {
+ const node = makeNode({ id: '', label: '', aliases: ['pve1'] });
+ expect(matchesStorageRecordNode(makeRecord(), node)).toBe(true);
+ });
+
+ it('returns false when no alias matches any hint', () => {
+ const node = makeNode({ id: 'zzz', label: 'yyy', aliases: ['nope'] });
+ expect(matchesStorageRecordNode(makeRecord(), node)).toBe(false);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// groupStorageRecords
+// ---------------------------------------------------------------------------
+
+describe('groupStorageRecords branch coverage', () => {
+ it('returns [] for empty input (records.length === 0)', () => {
+ expect(groupStorageRecords([], 'node')).toEqual([]);
+ expect(groupStorageRecords([], 'type')).toEqual([]);
+ });
+
+ it('groups everything under "All" with merged stats when groupBy is "none"', () => {
+ const a = makeRecord({ id: 'a' });
+ const b = makeRecord({ id: 'b' });
+ const result = groupStorageRecords([a, b], 'none');
+ expect(result).toHaveLength(1);
+ expect(result[0].key).toBe('All');
+ expect(result[0].items).toStrictEqual([a, b]);
+ expect(result[0].stats).toStrictEqual({
+ totalBytes: 200,
+ usedBytes: 80,
+ usagePercent: 40,
+ byHealth: { healthy: 2, warning: 0, critical: 0, offline: 0, unknown: 0 },
+ });
+ });
+
+ it('groups by type and sorts the group keys ascending', () => {
+ const zfs = makeRecord({ id: 'z', name: 'zfs-pool', details: { type: 'zfs' } });
+ const dir = makeRecord({ id: 'd', name: 'dir-pool', details: { type: 'dir' } });
+ const result = groupStorageRecords([zfs, dir], 'type');
+ expect(result.map((group) => group.key)).toEqual(['dir', 'zfs']);
+ expect(result[0].items).toStrictEqual([dir]);
+ expect(result[1].items).toStrictEqual([zfs]);
+ });
+
+ it('groups by node via getStorageRecordNodeLabel (else arm) and buckets repeats', () => {
+ const a = makeRecord({ id: 'a', details: { node: 'pve1' } });
+ const b = makeRecord({ id: 'b', details: { node: 'pve1' } });
+ const c = makeRecord({ id: 'c', details: { node: 'pve2' } });
+ const result = groupStorageRecords([a, b, c], 'node');
+ expect(result.map((group) => group.key)).toEqual(['pve1', 'pve2']);
+ expect(result[0].items).toStrictEqual([a, b]);
+ expect(result[1].items).toStrictEqual([c]);
+ });
+
+ it('groups by status via getStorageRecordStatus and sorts keys', () => {
+ const ok = makeRecord({ id: 'a', details: { status: 'available' } });
+ const bad = makeRecord({ id: 'b', details: { status: 'degraded' } });
+ const result = groupStorageRecords([ok, bad], 'status');
+ expect(result.map((group) => group.key)).toEqual(['available', 'degraded']);
+ });
+
+ it('collapses a whitespace-only type key to "unknown" (key.trim() || "unknown")', () => {
+ const rec = makeRecord({ id: 'x', name: 'X', details: { type: ' ' } });
+ const result = groupStorageRecords([rec], 'type');
+ expect(result.map((group) => group.key)).toEqual(['unknown']);
+ });
+
+ it('reuses an existing group bucket (if (!groups.has) branch, false arm)', () => {
+ const a = makeRecord({ id: 'a', details: { type: 'zfs' } });
+ const b = makeRecord({ id: 'b', details: { type: 'zfs' } });
+ const result = groupStorageRecords([a, b], 'type');
+ expect(result).toHaveLength(1);
+ expect(result[0].key).toBe('zfs');
+ expect(result[0].items).toStrictEqual([a, b]);
+ expect(result[0].stats).toStrictEqual({
+ totalBytes: 200,
+ usedBytes: 80,
+ usagePercent: 40,
+ byHealth: { healthy: 2, warning: 0, critical: 0, offline: 0, unknown: 0 },
+ });
+ });
+});
+
+// ---------------------------------------------------------------------------
+// matchesStorageRecordSearch
+// ---------------------------------------------------------------------------
+
+describe('matchesStorageRecordSearch branch coverage', () => {
+ it('returns true for an empty query (!query arm)', () => {
+ expect(matchesStorageRecordSearch(makeRecord(), '')).toBe(true);
+ });
+
+ it('returns true when only node terms match and there are no free terms', () => {
+ expect(matchesStorageRecordSearch(makeRecord(), 'node:pve1')).toBe(true);
+ });
+
+ it('returns false when a node term fails (matchesStorageNodeTerms false branch)', () => {
+ expect(matchesStorageRecordSearch(makeRecord(), 'node:nope')).toBe(false);
+ });
+
+ it('matches a free term found in capabilities', () => {
+ const rec = makeRecord({ capabilities: ['replication', 'snapshots'] });
+ expect(matchesStorageRecordSearch(rec, 'replication')).toBe(true);
+ });
+
+ it('spreads [] when capabilities is undefined (... || [] arm) and drops the capability token', () => {
+ const rec = makeRecord({
+ capabilities: undefined as unknown as StorageCapability[],
+ });
+ expect(matchesStorageRecordSearch(rec, 'tank')).toBe(true);
+ // 'capacity' was the default capability; now absent from the haystack.
+ expect(matchesStorageRecordSearch(rec, 'capacity')).toBe(false);
+ });
+
+ it('matches a free term present in an optional summary field (actionSummary)', () => {
+ const rec = makeRecord({ actionSummary: 'Scrub running' });
+ expect(matchesStorageRecordSearch(rec, 'scrub')).toBe(true);
+ });
+
+ it('returns false when one free term matches but another does not (every() false arm)', () => {
+ expect(matchesStorageRecordSearch(makeRecord(), 'tank missing')).toBe(false);
+ });
+
+ it('returns false when no free term matches at all', () => {
+ expect(matchesStorageRecordSearch(makeRecord(), 'zzzzzz')).toBe(false);
+ });
+
+ it('returns true when a node term and a free term both match', () => {
+ expect(matchesStorageRecordSearch(makeRecord(), 'node:cluster-main tank')).toBe(true);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// sortStorageRecords (and the inner numericCompare closure)
+// ---------------------------------------------------------------------------
+
+describe('sortStorageRecords branch coverage', () => {
+ it('sorts by usage asc and desc (numericCompare < and > arms)', () => {
+ const low = makeRecord({
+ id: 'low',
+ name: 'low',
+ capacity: { totalBytes: 100, usedBytes: 10, freeBytes: 90, usagePercent: 10 },
+ });
+ const high = makeRecord({
+ id: 'high',
+ name: 'high',
+ capacity: { totalBytes: 100, usedBytes: 90, freeBytes: 10, usagePercent: 90 },
+ });
+ expect(sortStorageRecords([high, low], 'usage', 'asc').map((r) => r.id)).toEqual([
+ 'low',
+ 'high',
+ ]);
+ expect(sortStorageRecords([low, high], 'usage', 'desc').map((r) => r.id)).toEqual([
+ 'high',
+ 'low',
+ ]);
+ });
+
+ it('numericCompare === arm: equal usage falls through to the name tie-break', () => {
+ const a = makeRecord({
+ id: 'a',
+ name: 'Bravo',
+ capacity: { totalBytes: 100, usedBytes: 50, freeBytes: 50, usagePercent: 50 },
+ });
+ const b = makeRecord({
+ id: 'b',
+ name: 'Alpha',
+ capacity: { totalBytes: 100, usedBytes: 50, freeBytes: 50, usagePercent: 50 },
+ });
+ expect(sortStorageRecords([a, b], 'usage', 'asc').map((r) => r.name)).toEqual([
+ 'Alpha',
+ 'Bravo',
+ ]);
+ expect(sortStorageRecords([a, b], 'usage', 'desc').map((r) => r.name)).toEqual([
+ 'Bravo',
+ 'Alpha',
+ ]);
+ });
+
+ it('sorts by name through the default else arm', () => {
+ const a = makeRecord({ id: 'a', name: 'Zeta' });
+ const b = makeRecord({ id: 'b', name: 'Alpha' });
+ expect(sortStorageRecords([a, b], 'name', 'asc').map((r) => r.name)).toEqual([
+ 'Alpha',
+ 'Zeta',
+ ]);
+ expect(sortStorageRecords([a, b], 'name', 'desc').map((r) => r.name)).toEqual([
+ 'Zeta',
+ 'Alpha',
+ ]);
+ });
+
+ it('sorts by type via textCompare', () => {
+ const zfs = makeRecord({ id: 'a', name: 'a', details: { type: 'zfs' } });
+ const dir = makeRecord({ id: 'b', name: 'b', details: { type: 'dir' } });
+ expect(sortStorageRecords([zfs, dir], 'type', 'asc').map((r) => r.id)).toEqual(['b', 'a']);
+ });
+
+ it('sorts by priority, defaulting a missing incidentPriority to 0 (|| 0 arm)', () => {
+ const withPrio = makeRecord({ id: 'p', name: 'p', incidentPriority: 5 });
+ const noPrio = makeRecord({ id: 'n', name: 'n' });
+ expect(sortStorageRecords([withPrio, noPrio], 'priority', 'asc').map((r) => r.id)).toEqual([
+ 'n',
+ 'p',
+ ]);
+ expect(sortStorageRecords([withPrio, noPrio], 'priority', 'desc').map((r) => r.id)).toEqual([
+ 'p',
+ 'n',
+ ]);
+ });
+
+ it('growth: left null, right non-null returns 1 (null sorts after in asc)', () => {
+ const withGrowth = makeRecord({ id: 'g', name: 'g' });
+ const noGrowth = makeRecord({ id: 'n', name: 'n' });
+ const ctx: StorageSortContext = {
+ growthBySeriesId: new Map([['g', growthEntry(100)]]),
+ };
+ expect(
+ sortStorageRecords([noGrowth, withGrowth], 'growth', 'asc', ctx).map((r) => r.id),
+ ).toEqual(['g', 'n']);
+ });
+
+ it('growth: left non-null, right null returns -1 (early return bypasses direction flip)', () => {
+ const withGrowth = makeRecord({ id: 'g', name: 'g' });
+ const noGrowth = makeRecord({ id: 'n', name: 'n' });
+ const ctx: StorageSortContext = {
+ growthBySeriesId: new Map([['g', growthEntry(100)]]),
+ };
+ // Even in desc the null-growth record stays last because of the early `return -1`.
+ expect(
+ sortStorageRecords([withGrowth, noGrowth], 'growth', 'desc', ctx).map((r) => r.id),
+ ).toEqual(['g', 'n']);
+ });
+
+ it('growth: both null -> comparison 0 -> name tie-break', () => {
+ const a = makeRecord({ id: 'a', name: 'Bravo' });
+ const b = makeRecord({ id: 'b', name: 'Alpha' });
+ const ctx: StorageSortContext = { growthBySeriesId: new Map() };
+ expect(sortStorageRecords([a, b], 'growth', 'asc', ctx).map((r) => r.name)).toEqual([
+ 'Alpha',
+ 'Bravo',
+ ]);
+ });
+
+ it('growth: no context -> growthBySeriesId undefined -> ?? null for all -> name tie-break', () => {
+ const a = makeRecord({ id: 'a', name: 'Bravo' });
+ const b = makeRecord({ id: 'b', name: 'Alpha' });
+ expect(sortStorageRecords([a, b], 'growth', 'asc').map((r) => r.name)).toEqual([
+ 'Alpha',
+ 'Bravo',
+ ]);
+ });
+
+ it('growth: both non-null -> numericCompare (asc and desc)', () => {
+ const small = makeRecord({ id: 's', name: 's' });
+ const big = makeRecord({ id: 'b', name: 'b' });
+ const ctx: StorageSortContext = {
+ growthBySeriesId: new Map([
+ ['s', growthEntry(10)],
+ ['b', growthEntry(999)],
+ ]),
+ };
+ expect(sortStorageRecords([big, small], 'growth', 'asc', ctx).map((r) => r.id)).toEqual([
+ 's',
+ 'b',
+ ]);
+ expect(sortStorageRecords([small, big], 'growth', 'desc', ctx).map((r) => r.id)).toEqual([
+ 'b',
+ 's',
+ ]);
+ });
+
+ it('growth: deltaBytes === 0 is NOT collapsed to null by ?? (compared as 0)', () => {
+ const zero = makeRecord({ id: 'z', name: 'z' });
+ const big = makeRecord({ id: 'b', name: 'b' });
+ const ctx: StorageSortContext = {
+ growthBySeriesId: new Map([
+ ['z', growthEntry(0)],
+ ['b', growthEntry(999)],
+ ]),
+ };
+ expect(sortStorageRecords([big, zero], 'growth', 'asc', ctx).map((r) => r.id)).toEqual([
+ 'z',
+ 'b',
+ ]);
+ });
+
+ it('growth: entry present but deltaBytes null -> treated as null', () => {
+ const nullDelta = makeRecord({ id: 'nd', name: 'nd' });
+ const val = makeRecord({ id: 'v', name: 'v' });
+ const ctx: StorageSortContext = {
+ growthBySeriesId: new Map([
+ ['nd', growthEntry(null)],
+ ['v', growthEntry(50)],
+ ]),
+ };
+ expect(
+ sortStorageRecords([nullDelta, val], 'growth', 'asc', ctx).map((r) => r.id),
+ ).toEqual(['v', 'nd']);
+ });
+
+ it('returns a new sorted array and does not mutate the input ([...records] copy)', () => {
+ const a = makeRecord({ id: 'a', name: 'a' });
+ const b = makeRecord({ id: 'b', name: 'b' });
+ const input = [b, a];
+ const sorted = sortStorageRecords(input, 'name', 'asc');
+ expect(sorted).not.toBe(input);
+ expect(input.map((r) => r.id)).toEqual(['b', 'a']);
+ expect(sorted.map((r) => r.id)).toEqual(['a', 'b']);
+ });
+});
diff --git a/frontend-modern/src/utils/__tests__/alertTargetTypes.branchcov2.test.ts b/frontend-modern/src/utils/__tests__/alertTargetTypes.branchcov2.test.ts
new file mode 100644
index 0000000000..24d42702f1
--- /dev/null
+++ b/frontend-modern/src/utils/__tests__/alertTargetTypes.branchcov2.test.ts
@@ -0,0 +1,246 @@
+import { describe, expect, it } from 'vitest';
+import { inferAlertTargetTypeFromResourceId } from '@/utils/alertTargetTypes';
+
+describe('alertTargetTypes · inferAlertTargetTypeFromResourceId (branch coverage)', () => {
+ describe('empty / falsy input → undefined (guard branch)', () => {
+ it('returns undefined for undefined input', () => {
+ expect(inferAlertTargetTypeFromResourceId(undefined)).toBeUndefined();
+ });
+
+ it('returns undefined for empty string', () => {
+ expect(inferAlertTargetTypeFromResourceId('')).toBeUndefined();
+ });
+
+ it('returns undefined for whitespace-only string (normalized is empty)', () => {
+ expect(inferAlertTargetTypeFromResourceId(' ')).toBeUndefined();
+ });
+
+ it('returns undefined for null cast to string | undefined', () => {
+ const maybeNull = null as unknown as string | undefined;
+ expect(inferAlertTargetTypeFromResourceId(maybeNull)).toBeUndefined();
+ });
+ });
+
+ describe('VM inference (startsWith vm- / qemu- / includes /qemu/)', () => {
+ it('detects "vm-" prefix', () => {
+ expect(inferAlertTargetTypeFromResourceId('vm-101')).toBe('vm');
+ });
+
+ it('detects "qemu-" prefix', () => {
+ expect(inferAlertTargetTypeFromResourceId('qemu-202')).toBe('vm');
+ });
+
+ it('detects "/qemu/" segment in a path-style id', () => {
+ expect(inferAlertTargetTypeFromResourceId('nodes/prox/qemu/303')).toBe('vm');
+ });
+
+ it('is case-insensitive via normalization', () => {
+ expect(inferAlertTargetTypeFromResourceId('VM-404')).toBe('vm');
+ expect(inferAlertTargetTypeFromResourceId(' QEMU-505 ')).toBe('vm');
+ });
+ });
+
+ describe('system-container inference (ct- / lxc- / includes /lxc/)', () => {
+ it('detects "ct-" prefix', () => {
+ expect(inferAlertTargetTypeFromResourceId('ct-100')).toBe('system-container');
+ });
+
+ it('detects "lxc-" prefix', () => {
+ expect(inferAlertTargetTypeFromResourceId('lxc-100')).toBe('system-container');
+ });
+
+ it('detects "/lxc/" segment in a path-style id', () => {
+ expect(inferAlertTargetTypeFromResourceId('nodes/prox/lxc/101')).toBe('system-container');
+ });
+ });
+
+ describe('app-container inference (docker: / app-container: / includes /container:)', () => {
+ it('detects "docker:" prefix', () => {
+ expect(inferAlertTargetTypeFromResourceId('docker:abc')).toBe('app-container');
+ });
+
+ it('detects "app-container:" prefix', () => {
+ expect(inferAlertTargetTypeFromResourceId('app-container:my-svc')).toBe('app-container');
+ });
+
+ it('detects "/container:" segment in a path-style id', () => {
+ expect(inferAlertTargetTypeFromResourceId('host/stack/container:worker')).toBe(
+ 'app-container',
+ );
+ });
+ });
+
+ describe('singleton-prefix targets', () => {
+ it('detects "node:" → agent', () => {
+ expect(inferAlertTargetTypeFromResourceId('node:host1')).toBe('agent');
+ });
+
+ it('detects "storage:" → storage', () => {
+ expect(inferAlertTargetTypeFromResourceId('storage:zfs-pool')).toBe('storage');
+ });
+
+ it('detects "disk:" → disk', () => {
+ expect(inferAlertTargetTypeFromResourceId('disk:sdb')).toBe('disk');
+ });
+
+ it('detects "pbs:" → pbs', () => {
+ expect(inferAlertTargetTypeFromResourceId('pbs:main')).toBe('pbs');
+ });
+
+ it('detects "pmg:" → pmg', () => {
+ expect(inferAlertTargetTypeFromResourceId('pmg:mail')).toBe('pmg');
+ });
+ });
+
+ describe('pod inference (k8s-pod: / k8s-pod- / pod: / includes :pod:)', () => {
+ it('detects "k8s-pod:" prefix', () => {
+ expect(inferAlertTargetTypeFromResourceId('k8s-pod:ns/web')).toBe('pod');
+ });
+
+ it('detects "k8s-pod-" prefix (hyphen form, takes priority over k8s: cluster fallback)', () => {
+ expect(inferAlertTargetTypeFromResourceId('k8s-pod-abc')).toBe('pod');
+ });
+
+ it('detects "pod:" prefix', () => {
+ expect(inferAlertTargetTypeFromResourceId('pod:ns/name')).toBe('pod');
+ });
+
+ it('detects ":pod:" embedded segment', () => {
+ expect(inferAlertTargetTypeFromResourceId('cluster:pod:web')).toBe('pod');
+ });
+ });
+
+ describe('k8s: hierarchy (nested conditionals)', () => {
+ it('detects ":deployment:" inside k8s: → k8s-deployment', () => {
+ expect(inferAlertTargetTypeFromResourceId('k8s:cluster-1:deployment:api')).toBe(
+ 'k8s-deployment',
+ );
+ });
+
+ it('detects ":namespace:" inside k8s: → k8s-namespace', () => {
+ expect(inferAlertTargetTypeFromResourceId('k8s:cluster-1:namespace:default')).toBe(
+ 'k8s-namespace',
+ );
+ });
+
+ it('detects ":node:" inside k8s: → k8s-node', () => {
+ expect(inferAlertTargetTypeFromResourceId('k8s:cluster-1:node:worker-1')).toBe('k8s-node');
+ });
+
+ it('falls back to k8s-cluster when no nested marker is present', () => {
+ expect(inferAlertTargetTypeFromResourceId('k8s:cluster-1')).toBe('k8s-cluster');
+ });
+ });
+
+ describe('truenas / disk targets', () => {
+ it('detects "truenas-system:" prefix → truenas', () => {
+ expect(inferAlertTargetTypeFromResourceId('truenas-system:box-1')).toBe('truenas');
+ });
+
+ it('detects "system:truenas" prefix → truenas (alternate spelling)', () => {
+ expect(inferAlertTargetTypeFromResourceId('system:truenas')).toBe('truenas');
+ });
+
+ it('detects "truenas-pool:" prefix → pool', () => {
+ expect(inferAlertTargetTypeFromResourceId('truenas-pool:tank')).toBe('pool');
+ });
+
+ it('detects "truenas-dataset:" prefix → truenas-dataset', () => {
+ expect(inferAlertTargetTypeFromResourceId('truenas-dataset:tank/media')).toBe(
+ 'truenas-dataset',
+ );
+ });
+
+ it('detects "truenas-disk:" prefix → physical_disk', () => {
+ expect(inferAlertTargetTypeFromResourceId('truenas-disk:da0')).toBe('physical_disk');
+ });
+
+ it('detects "physical-disk:" prefix → physical_disk (alternate spelling)', () => {
+ expect(inferAlertTargetTypeFromResourceId('physical-disk:sda')).toBe('physical_disk');
+ });
+ });
+
+ describe('vmware / vsphere prefix forms (startsWith branches)', () => {
+ it('detects "vmware-host:" prefix → vmware-host', () => {
+ expect(inferAlertTargetTypeFromResourceId('vmware-host:host-1')).toBe('vmware-host');
+ });
+
+ it('detects "vsphere-host:" prefix → vmware-host', () => {
+ expect(inferAlertTargetTypeFromResourceId('vsphere-host:host-2')).toBe('vmware-host');
+ });
+
+ it('detects "vmware-vm:" prefix → vmware-vm', () => {
+ expect(inferAlertTargetTypeFromResourceId('vmware-vm:vm-1')).toBe('vmware-vm');
+ });
+
+ it('detects "vsphere-vm:" prefix → vmware-vm', () => {
+ expect(inferAlertTargetTypeFromResourceId('vsphere-vm:vm-2')).toBe('vmware-vm');
+ });
+
+ it('detects "vmware-datastore:" prefix → vmware-datastore', () => {
+ expect(inferAlertTargetTypeFromResourceId('vmware-datastore:ds-1')).toBe('vmware-datastore');
+ });
+
+ it('detects "vsphere-datastore:" prefix → vmware-datastore', () => {
+ expect(inferAlertTargetTypeFromResourceId('vsphere-datastore:ds-2')).toBe('vmware-datastore');
+ });
+
+ it('detects "vmware-network:" prefix → vmware-network', () => {
+ expect(inferAlertTargetTypeFromResourceId('vmware-network:net-1')).toBe('vmware-network');
+ });
+
+ it('detects "vsphere-network:" prefix → vmware-network', () => {
+ expect(inferAlertTargetTypeFromResourceId('vsphere-network:net-2')).toBe('vmware-network');
+ });
+ });
+
+ describe('vmware: / vsphere: generic block (nested conditionals)', () => {
+ it('detects ":host:" inside "vmware:" → vmware-host', () => {
+ expect(inferAlertTargetTypeFromResourceId('vmware:vc-1:host:host-101')).toBe('vmware-host');
+ });
+
+ it('detects ":vm:" inside "vmware:" → vmware-vm', () => {
+ expect(inferAlertTargetTypeFromResourceId('vmware:vc-1:vm:vm-201')).toBe('vmware-vm');
+ });
+
+ it('detects ":datastore:" inside "vmware:" → vmware-datastore', () => {
+ expect(inferAlertTargetTypeFromResourceId('vmware:vc-1:datastore:ds-301')).toBe(
+ 'vmware-datastore',
+ );
+ });
+
+ it('detects ":network:" inside "vmware:" → vmware-network', () => {
+ expect(inferAlertTargetTypeFromResourceId('vmware:vc-1:network:net-401')).toBe(
+ 'vmware-network',
+ );
+ });
+
+ it('falls back to vmware-vsphere when "vmware:" has no nested marker', () => {
+ expect(inferAlertTargetTypeFromResourceId('vmware:vc-1')).toBe('vmware-vsphere');
+ });
+
+ it('handles "vsphere:" generic block fallback → vmware-vsphere', () => {
+ expect(inferAlertTargetTypeFromResourceId('vsphere:vc-2')).toBe('vmware-vsphere');
+ });
+
+ it('detects nested marker inside "vsphere:" → vmware-vm', () => {
+ expect(inferAlertTargetTypeFromResourceId('vsphere:vc-2:vm:vm-9')).toBe('vmware-vm');
+ });
+ });
+
+ describe('terminating fallthrough → undefined', () => {
+ it('returns undefined for a completely unknown id shape', () => {
+ expect(inferAlertTargetTypeFromResourceId('random-resource-xyz')).toBeUndefined();
+ });
+
+ it('returns undefined when a partial substring would match but no prefix does', () => {
+ // "vm" appears but not at the start; nothing matches → undefined
+ expect(inferAlertTargetTypeFromResourceId('service-vm-runner')).toBeUndefined();
+ });
+
+ it('returns undefined for a bare colon-only string', () => {
+ // normalize yields ":" which has no matching prefix
+ expect(inferAlertTargetTypeFromResourceId(':')).toBeUndefined();
+ });
+ });
+});
diff --git a/frontend-modern/src/utils/__tests__/metricThresholds.branchcov2.test.ts b/frontend-modern/src/utils/__tests__/metricThresholds.branchcov2.test.ts
new file mode 100644
index 0000000000..5f7c2978f2
--- /dev/null
+++ b/frontend-modern/src/utils/__tests__/metricThresholds.branchcov2.test.ts
@@ -0,0 +1,492 @@
+import { describe, expect, it } from 'vitest';
+import type { AlertConfig, RawOverrideConfig } from '@/types/alerts';
+import {
+ getDefaultDisplayMetricThresholds,
+ getDefaultMetricDisplayThresholds,
+ getMetricSeverity,
+ resolveMetricDisplayThresholds,
+} from '@/utils/metricThresholds';
+
+// `resolveThreshold`, `getScopeThresholds`, `getOverrideValue`, `normalizeMargin`,
+// `getBaseThresholdValue`, `getFallbackCritical`, and `getFallbackSeverityThresholds`
+// are module-private (non-exported) helpers, so they are exercised indirectly
+// through the exported entry points below, asserting on their observable outputs
+// (mirroring the sibling availabilityProbePresentation branchcov2 convention).
+
+// Minimal valid AlertConfig base; callers override individual fields. Every scope
+// that resolves off the base falls through to the seeded factory fallbacks.
+const makeConfig = (overrides: Partial<AlertConfig> = {}): AlertConfig => ({
+ enabled: true,
+ guestDefaults: {},
+ nodeDefaults: {},
+ storageDefault: { trigger: 92, clear: 86 },
+ overrides: {},
+ ...overrides,
+});
+
+// Builds an override entry that may hold deliberately wrong-typed values (plain
+// numbers where the public type expects a HysteresisThreshold, or a hysteresis
+// object missing `clear`). The cast keeps the file type-checking under the real
+// tsconfig while still driving the defensive `typeof value === 'number'` and
+// `clear === null` branches at runtime.
+const malformedOverride = (value: Record<string, unknown>): RawOverrideConfig =>
+ value as unknown as RawOverrideConfig;
+
+describe('metricThresholds — branch coverage (branchcov2)', () => {
+ describe('normalizeMargin (via resolveMetricDisplayThresholds)', () => {
+ // A guest cpu override of `{ trigger: 90 }` (no clear) hits resolveThreshold's
+ // hysteresis clear-null arm, which yields `warning = max(0, critical - margin)`.
+ // That makes normalizeMargin(config.hysteresisMargin) observable as `90 - margin`.
+
+ it('defaults to the 5-point margin when hysteresisMargin is absent', () => {
+ const config = makeConfig({
+ overrides: { r1: malformedOverride({ cpu: { trigger: 90 } }) },
+ });
+ expect(resolveMetricDisplayThresholds(config, 'guest', 'cpu', 'r1')).toEqual({
+ warning: 85,
+ critical: 90,
+ });
+ });
+
+ it('honors a positive configured hysteresisMargin', () => {
+ const config = makeConfig({
+ hysteresisMargin: 10,
+ overrides: { r1: malformedOverride({ cpu: { trigger: 90 } }) },
+ });
+ expect(resolveMetricDisplayThresholds(config, 'guest', 'cpu', 'r1')).toEqual({
+ warning: 80,
+ critical: 90,
+ });
+ });
+
+ it('clamps a negative hysteresisMargin to 0', () => {
+ const config = makeConfig({
+ hysteresisMargin: -3,
+ overrides: { r1: malformedOverride({ cpu: { trigger: 90 } }) },
+ });
+ expect(resolveMetricDisplayThresholds(config, 'guest', 'cpu', 'r1')).toEqual({
+ warning: 90,
+ critical: 90,
+ });
+ });
+
+ it('falls back to the default margin for a NaN hysteresisMargin', () => {
+ const config = makeConfig({
+ hysteresisMargin: NaN,
+ overrides: { r1: malformedOverride({ cpu: { trigger: 90 } }) },
+ });
+ expect(resolveMetricDisplayThresholds(config, 'guest', 'cpu', 'r1')).toEqual({
+ warning: 85,
+ critical: 90,
+ });
+ });
+
+ it('falls back to the default margin for a non-finite (Infinity) hysteresisMargin', () => {
+ const config = makeConfig({
+ hysteresisMargin: Infinity,
+ overrides: { r1: malformedOverride({ cpu: { trigger: 90 } }) },
+ });
+ expect(resolveMetricDisplayThresholds(config, 'guest', 'cpu', 'r1')).toEqual({
+ warning: 85,
+ critical: 90,
+ });
+ });
+ });
+
+ describe('getScopeThresholds (via resolveMetricDisplayThresholds) — every switch arm', () => {
+ it('reads guestDefaults for the guest scope', () => {
+ const config = makeConfig({ guestDefaults: { cpu: { trigger: 82, clear: 77 } } });
+ expect(resolveMetricDisplayThresholds(config, 'guest', 'cpu')).toEqual({
+ warning: 77,
+ critical: 82,
+ });
+ });
+
+ it('reads nodeDefaults for the node scope', () => {
+ const config = makeConfig({
+ nodeDefaults: { temperature: { trigger: 85, clear: 80 } },
+ });
+ expect(resolveMetricDisplayThresholds(config, 'node', 'temperature')).toEqual({
+ warning: 80,
+ critical: 85,
+ });
+ });
+
+ it('reads pbsDefaults for the pbs scope', () => {
+ const config = makeConfig({ pbsDefaults: { cpu: { trigger: 70, clear: 65 } } });
+ expect(resolveMetricDisplayThresholds(config, 'pbs', 'cpu')).toEqual({
+ warning: 65,
+ critical: 70,
+ });
+ });
+
+ it('reads agentDefaults for the agent scope', () => {
+ const config = makeConfig({
+ agentDefaults: { diskTemperature: { trigger: 60, clear: 55 } },
+ });
+ expect(resolveMetricDisplayThresholds(config, 'agent', 'diskTemperature')).toEqual({
+ warning: 55,
+ critical: 60,
+ });
+ });
+
+ it('reads dockerDefaults for the docker scope', () => {
+ const config = makeConfig({ dockerDefaults: { cpu: { trigger: 88, clear: 82 } } });
+ expect(resolveMetricDisplayThresholds(config, 'docker', 'cpu')).toEqual({
+ warning: 82,
+ critical: 88,
+ });
+ });
+
+ it('reads storageDefault for the storage scope', () => {
+ // storageDefault is the whole-object HysteresisThreshold; usage/disk read it.
+ expect(resolveMetricDisplayThresholds(makeConfig(), 'storage', 'usage')).toEqual({
+ warning: 86,
+ critical: 92,
+ });
+ });
+
+ it('returns undefined for every scope when config is null (optional chaining)', () => {
+ // config?.<field> short-circuits to undefined; fallbacks still resolve.
+ expect(resolveMetricDisplayThresholds(null, 'guest', 'cpu')).toEqual({
+ warning: 75,
+ critical: 80,
+ });
+ expect(resolveMetricDisplayThresholds(null, 'agent', 'diskTemperature')).toEqual({
+ warning: 50,
+ critical: 55,
+ });
+ });
+ });
+
+ describe('getOverrideValue (via resolveMetricDisplayThresholds)', () => {
+ it('returns undefined when no override matches the resource id', () => {
+ // No matching override → falls through to base/fallback (guest cpu → 80).
+ const config = makeConfig({
+ overrides: { other: malformedOverride({ cpu: 88 }) },
+ });
+ expect(resolveMetricDisplayThresholds(config, 'guest', 'cpu', 'missing')).toEqual({
+ warning: 75,
+ critical: 80,
+ });
+ });
+
+ it('returns a plain numeric override value verbatim', () => {
+ const config = makeConfig({ overrides: { r1: malformedOverride({ cpu: 88 }) } });
+ expect(resolveMetricDisplayThresholds(config, 'guest', 'cpu', 'r1')).toEqual({
+ warning: 83,
+ critical: 88,
+ });
+ });
+
+ it('returns a hysteresis override value', () => {
+ const config = makeConfig({
+ overrides: { r1: malformedOverride({ cpu: { trigger: 90, clear: 80 } }) },
+ });
+ expect(resolveMetricDisplayThresholds(config, 'guest', 'cpu', 'r1')).toEqual({
+ warning: 80,
+ critical: 90,
+ });
+ });
+
+ it('aliases override.usage to disk when disk is absent (numeric)', () => {
+ const config = makeConfig({ overrides: { r1: malformedOverride({ usage: 88 }) } });
+ expect(resolveMetricDisplayThresholds(config, 'guest', 'disk', 'r1')).toEqual({
+ warning: 83,
+ critical: 88,
+ });
+ });
+
+ it('aliases override.usage to disk when disk is absent (hysteresis)', () => {
+ const config = makeConfig({
+ overrides: { r1: malformedOverride({ usage: { trigger: 90, clear: 84 } }) },
+ });
+ expect(resolveMetricDisplayThresholds(config, 'guest', 'disk', 'r1')).toEqual({
+ warning: 84,
+ critical: 90,
+ });
+ });
+
+ it('returns undefined for disk when neither disk nor usage is present on the override', () => {
+ // Override holds only cpu; getOverrideValue(disk) is undefined → baseValue used.
+ const config = makeConfig({
+ guestDefaults: { disk: { trigger: 90, clear: 85 } },
+ overrides: { r1: malformedOverride({ cpu: 50 }) },
+ });
+ expect(resolveMetricDisplayThresholds(config, 'guest', 'disk', 'r1')).toEqual({
+ warning: 85,
+ critical: 90,
+ });
+ });
+
+ it('does not consult the usage alias for non-disk metrics', () => {
+ // Override has only usage; asking for cpu → undefined → fallback guest cpu 80.
+ const config = makeConfig({ overrides: { r1: malformedOverride({ usage: 88 }) } });
+ expect(resolveMetricDisplayThresholds(config, 'guest', 'cpu', 'r1')).toEqual({
+ warning: 75,
+ critical: 80,
+ });
+ });
+ });
+
+ describe('getBaseThresholdValue (via resolveMetricDisplayThresholds)', () => {
+ it('returns undefined when scope thresholds are entirely absent', () => {
+ // pbsDefaults omitted → getScopeThresholds returns undefined → base undefined
+ // → fallback SCOPE_DEFAULTS.pbs.cpu = 80.
+ expect(resolveMetricDisplayThresholds(makeConfig(), 'pbs', 'cpu')).toEqual({
+ warning: 75,
+ critical: 80,
+ });
+ });
+
+ it('returns the whole-object hysteresis for storage + usage/disk', () => {
+ expect(resolveMetricDisplayThresholds(makeConfig(), 'storage', 'usage')).toEqual({
+ warning: 86,
+ critical: 92,
+ });
+ expect(resolveMetricDisplayThresholds(makeConfig(), 'storage', 'disk')).toEqual({
+ warning: 86,
+ critical: 92,
+ });
+ });
+
+ it('returns undefined for storage + a non-disk/usage metric (whole-object guard)', () => {
+ // storageDefault is a HysteresisThreshold but metric is cpu → base undefined
+ // → fallback undefined → null.
+ expect(resolveMetricDisplayThresholds(makeConfig(), 'storage', 'cpu')).toBeNull();
+ });
+
+ it('returns a numeric field on a record threshold', () => {
+ const config = makeConfig({
+ guestDefaults: { cpu: 88 } as unknown as AlertConfig['guestDefaults'],
+ });
+ expect(resolveMetricDisplayThresholds(config, 'guest', 'cpu')).toEqual({
+ warning: 83,
+ critical: 88,
+ });
+ });
+
+ it('returns a hysteresis field on a record threshold', () => {
+ const config = makeConfig({ guestDefaults: { cpu: { trigger: 82, clear: 77 } } });
+ expect(resolveMetricDisplayThresholds(config, 'guest', 'cpu')).toEqual({
+ warning: 77,
+ critical: 82,
+ });
+ });
+
+ it('returns undefined when the metric field is absent from the record', () => {
+ // guestDefaults present but empty → base undefined → fallback guest cpu 80.
+ expect(
+ resolveMetricDisplayThresholds(makeConfig({ guestDefaults: {} }), 'guest', 'cpu'),
+ ).toEqual({ warning: 75, critical: 80 });
+ });
+ });
+
+ describe('getFallbackCritical (via getDefaultDisplayMetricThresholds)', () => {
+ it('returns FACTORY_STORAGE_DEFAULT for storage + disk/usage', () => {
+ expect(getDefaultDisplayMetricThresholds('usage', 'storage')).toEqual({
+ warning: 80,
+ critical: 85,
+ });
+ expect(getDefaultDisplayMetricThresholds('disk', 'storage')).toEqual({
+ warning: 80,
+ critical: 85,
+ });
+ });
+
+ it('returns undefined for storage + a non-disk/usage metric', () => {
+ expect(getDefaultDisplayMetricThresholds('cpu', 'storage')).toBeNull();
+ expect(getDefaultDisplayMetricThresholds('temperature', 'storage')).toBeNull();
+ });
+
+ it('maps each non-storage scope to its seeded factory default', () => {
+ expect(getDefaultDisplayMetricThresholds('cpu', 'guest')).toEqual({
+ warning: 75,
+ critical: 80,
+ });
+ expect(getDefaultDisplayMetricThresholds('temperature', 'node')).toEqual({
+ warning: 75,
+ critical: 80,
+ });
+ expect(getDefaultDisplayMetricThresholds('cpu', 'pbs')).toEqual({
+ warning: 75,
+ critical: 80,
+ });
+ expect(getDefaultDisplayMetricThresholds('diskTemperature', 'agent')).toEqual({
+ warning: 50,
+ critical: 55,
+ });
+ expect(getDefaultDisplayMetricThresholds('cpu', 'docker')).toEqual({
+ warning: 75,
+ critical: 80,
+ });
+ });
+
+ it('returns null when the scope has no default for the metric', () => {
+ // FACTORY_PBS_DEFAULTS has no disk/temperature entry → fallback undefined.
+ expect(getDefaultDisplayMetricThresholds('disk', 'pbs')).toBeNull();
+ expect(getDefaultDisplayMetricThresholds('temperature', 'pbs')).toBeNull();
+ });
+ });
+
+ describe('resolveThreshold (via resolveMetricDisplayThresholds / getDefaultDisplayMetricThresholds)', () => {
+ it('returns null when a hysteresis trigger is non-finite (NaN)', () => {
+ const config = makeConfig({
+ overrides: { r1: malformedOverride({ cpu: { trigger: NaN, clear: 70 } }) },
+ });
+ expect(resolveMetricDisplayThresholds(config, 'guest', 'cpu', 'r1')).toBeNull();
+ });
+
+ it('returns null when a hysteresis trigger is <= 0', () => {
+ const triggerZero = makeConfig({
+ overrides: { r1: malformedOverride({ cpu: { trigger: 0, clear: 0 } }) },
+ });
+ expect(resolveMetricDisplayThresholds(triggerZero, 'guest', 'cpu', 'r1')).toBeNull();
+ const triggerNeg = makeConfig({
+ overrides: { r1: malformedOverride({ cpu: { trigger: -5, clear: 0 } }) },
+ });
+ expect(resolveMetricDisplayThresholds(triggerNeg, 'guest', 'cpu', 'r1')).toBeNull();
+ });
+
+ it('derives warning from (critical - margin) when clear is absent or non-finite', () => {
+ const noClear = makeConfig({
+ overrides: { r1: malformedOverride({ cpu: { trigger: 90 } }) },
+ });
+ expect(resolveMetricDisplayThresholds(noClear, 'guest', 'cpu', 'r1')).toEqual({
+ warning: 85,
+ critical: 90,
+ });
+ const badClear = makeConfig({
+ overrides: { r1: malformedOverride({ cpu: { trigger: 90, clear: NaN } }) },
+ });
+ expect(resolveMetricDisplayThresholds(badClear, 'guest', 'cpu', 'r1')).toEqual({
+ warning: 85,
+ critical: 90,
+ });
+ });
+
+ it('clamps a negative (critical - margin) warning to 0', () => {
+ // trigger 3, no clear, margin 5 → max(0, 3 - 5) = 0.
+ const config = makeConfig({
+ overrides: { r1: malformedOverride({ cpu: { trigger: 3 } }) },
+ });
+ expect(resolveMetricDisplayThresholds(config, 'guest', 'cpu', 'r1')).toEqual({
+ warning: 0,
+ critical: 3,
+ });
+ });
+
+ it('uses min(clear, critical) when clear is finite and below critical', () => {
+ const config = makeConfig({
+ overrides: { r1: malformedOverride({ cpu: { trigger: 90, clear: 80 } }) },
+ });
+ expect(resolveMetricDisplayThresholds(config, 'guest', 'cpu', 'r1')).toEqual({
+ warning: 80,
+ critical: 90,
+ });
+ });
+
+ it('caps clear at critical when clear exceeds critical', () => {
+ // min(95, 80) = 80 === critical.
+ const config = makeConfig({
+ overrides: { r1: malformedOverride({ cpu: { trigger: 80, clear: 95 } }) },
+ });
+ expect(resolveMetricDisplayThresholds(config, 'guest', 'cpu', 'r1')).toEqual({
+ warning: 80,
+ critical: 80,
+ });
+ });
+
+ it('returns null for a numeric value <= 0', () => {
+ const zero = makeConfig({ overrides: { r1: malformedOverride({ cpu: 0 }) } });
+ expect(resolveMetricDisplayThresholds(zero, 'guest', 'cpu', 'r1')).toBeNull();
+ const neg = makeConfig({ overrides: { r1: malformedOverride({ cpu: -5 }) } });
+ expect(resolveMetricDisplayThresholds(neg, 'guest', 'cpu', 'r1')).toBeNull();
+ });
+
+ it('returns {critical: numeric, warning: numeric - margin} for a positive numeric value', () => {
+ const config = makeConfig({ overrides: { r1: malformedOverride({ cpu: 88 }) } });
+ expect(resolveMetricDisplayThresholds(config, 'guest', 'cpu', 'r1')).toEqual({
+ warning: 83,
+ critical: 88,
+ });
+ });
+
+ it('clamps a numeric warning (numeric - margin) to 0', () => {
+ // numeric 3, margin 5 → max(0, -2) = 0.
+ const config = makeConfig({ overrides: { r1: malformedOverride({ cpu: 3 }) } });
+ expect(resolveMetricDisplayThresholds(config, 'guest', 'cpu', 'r1')).toEqual({
+ warning: 0,
+ critical: 3,
+ });
+ });
+
+ it('returns null when value and fallback are both absent', () => {
+ // pbs has no disk default and FACTORY_PBS_DEFAULTS has no disk → null.
+ expect(resolveMetricDisplayThresholds(makeConfig(), 'pbs', 'disk')).toBeNull();
+ });
+
+ it('returns null when no usable fallback is available', () => {
+ // storage + cpu: getFallbackCritical returns undefined → resolveThreshold null.
+ expect(resolveMetricDisplayThresholds(makeConfig(), 'storage', 'cpu')).toBeNull();
+ });
+
+ it('builds thresholds from a valid fallback when value is absent', () => {
+ // guest cpu: no override/base → fallback FACTORY_GUEST_DEFAULTS.cpu = 80.
+ expect(resolveMetricDisplayThresholds(makeConfig(), 'guest', 'cpu')).toEqual({
+ warning: 75,
+ critical: 80,
+ });
+ });
+ });
+
+ describe('getDefaultMetricDisplayThresholds', () => {
+ it('returns the static generic thresholds for the "generic" bar metric', () => {
+ expect(getDefaultMetricDisplayThresholds('generic')).toEqual({
+ warning: 75,
+ critical: 90,
+ });
+ });
+
+ it('derives cpu/memory/disk from the guest factory defaults via resolveThreshold', () => {
+ expect(getDefaultMetricDisplayThresholds('cpu')).toEqual({ warning: 75, critical: 80 });
+ expect(getDefaultMetricDisplayThresholds('memory')).toEqual({ warning: 80, critical: 85 });
+ expect(getDefaultMetricDisplayThresholds('disk')).toEqual({ warning: 85, critical: 90 });
+ });
+ });
+
+ describe('getFallbackSeverityThresholds (via getMetricSeverity without thresholds)', () => {
+ it('uses METRIC_THRESHOLDS for cpu/memory/disk', () => {
+ // cpu: warning 80 / critical 90
+ expect(getMetricSeverity(79, 'cpu')).toBe('normal');
+ expect(getMetricSeverity(80, 'cpu')).toBe('warning');
+ expect(getMetricSeverity(90, 'cpu')).toBe('critical');
+ // memory: warning 75 / critical 85
+ expect(getMetricSeverity(74, 'memory')).toBe('normal');
+ expect(getMetricSeverity(75, 'memory')).toBe('warning');
+ expect(getMetricSeverity(85, 'memory')).toBe('critical');
+ });
+
+ it('uses the node temperature default for temperature', () => {
+ // getFallbackSeverityThresholds('temperature') → getDefaultDisplayMetricThresholds
+ // default scope 'node', fallback 80 → { warning: 75, critical: 80 }.
+ expect(getMetricSeverity(74, 'temperature')).toBe('normal');
+ expect(getMetricSeverity(75, 'temperature')).toBe('warning');
+ expect(getMetricSeverity(80, 'temperature')).toBe('critical');
+ });
+
+ it('uses the agent diskTemperature default for diskTemperature', () => {
+ // default scope 'agent', fallback 55 → { warning: 50, critical: 55 }.
+ expect(getMetricSeverity(49, 'diskTemperature')).toBe('normal');
+ expect(getMetricSeverity(50, 'diskTemperature')).toBe('warning');
+ expect(getMetricSeverity(55, 'diskTemperature')).toBe('critical');
+ });
+
+ it('uses the storage usage default for usage', () => {
+ // default scope 'storage', fallback 85 → { warning: 80, critical: 85 }.
+ expect(getMetricSeverity(79, 'usage')).toBe('normal');
+ expect(getMetricSeverity(80, 'usage')).toBe('warning');
+ expect(getMetricSeverity(85, 'usage')).toBe('critical');
+ });
+ });
+});
diff --git a/frontend-modern/src/utils/__tests__/metricsKeys.branchcov2.test.ts b/frontend-modern/src/utils/__tests__/metricsKeys.branchcov2.test.ts
new file mode 100644
index 0000000000..5643ee10bb
--- /dev/null
+++ b/frontend-modern/src/utils/__tests__/metricsKeys.branchcov2.test.ts
@@ -0,0 +1,283 @@
+/**
+ * Branch-coverage tests for the private `toMetricResourceKind` helper.
+ *
+ * `toMetricResourceKind` is not exported, so we exercise every branch
+ * indirectly through the public `buildMetricKeyForUnifiedResource`, which
+ * calls it and prefixes its result onto `{kind}:{id}`. Asserting the full
+ * built key gives us a concrete observable for each switch arm.
+ *
+ * The function has two switch statements:
+ * 1. Over `resource.metricsTarget?.resourceType` (skipped when
+ * `metricsTarget` is absent OR its `resourceType` matches no case).
+ * 2. Over `resource.type`, with a `default -> 'agent'` fallback.
+ *
+ * The sibling test (`metricsKeys.test.ts`) only covers:
+ * - first switch: `docker-host`
+ * - second switch: `k8s-cluster` (via an unmatched `'k8s'` target), `default`
+ * This file targets every other arm.
+ */
+import { describe, expect, it } from 'vitest';
+import type { Resource } from '@/types/resource';
+import { buildMetricKeyForUnifiedResource } from '@/utils/metricsKeys';
+
+/**
+ * Build a minimal resource shape that satisfies the
+ * `Pick<Resource, 'id' | 'type' | 'metricsTarget'>` contract used by
+ * `buildMetricKeyForUnifiedResource`. Cast through `unknown` because we
+ * intentionally populate only the three relevant fields.
+ */
+function makeResource(
+ input: Pick<Resource, 'id' | 'type' | 'metricsTarget'>,
+): Pick<Resource, 'id' | 'type' | 'metricsTarget'> {
+ return input;
+}
+
+describe('metricsKeys.toMetricResourceKind — branch coverage (branchcov2)', () => {
+ describe('first switch — metricsTarget.resourceType arms', () => {
+ it("maps metricsTarget 'vm' onto the 'vm' kind", () => {
+ // First switch case: `case 'vm': return 'vm'`
+ expect(
+ buildMetricKeyForUnifiedResource(
+ makeResource({
+ id: 'fallback-id-ignored',
+ type: 'agent',
+ metricsTarget: { resourceType: 'vm', resourceId: 'vm-100' },
+ }),
+ ),
+ ).toBe('vm:vm-100');
+ });
+
+ it("maps metricsTarget 'system-container' onto the 'container' kind", () => {
+ // First switch case: `case 'system-container': return 'container'`
+ expect(
+ buildMetricKeyForUnifiedResource(
+ makeResource({
+ id: 'unused',
+ type: 'vm',
+ metricsTarget: { resourceType: 'system-container', resourceId: 'lxc-200' },
+ }),
+ ),
+ ).toBe('container:lxc-200');
+ });
+
+ it("maps metricsTarget 'oci-container' onto the 'container' kind", () => {
+ // First switch case: `case 'oci-container': return 'container'`
+ expect(
+ buildMetricKeyForUnifiedResource(
+ makeResource({
+ id: 'unused',
+ type: 'vm',
+ metricsTarget: { resourceType: 'oci-container', resourceId: 'oci-300' },
+ }),
+ ),
+ ).toBe('container:oci-300');
+ });
+
+ it("maps metricsTarget 'app-container' onto the 'container' kind", () => {
+ // First switch case: `case 'app-container': return 'container'`
+ expect(
+ buildMetricKeyForUnifiedResource(
+ makeResource({
+ id: 'unused',
+ type: 'vm',
+ metricsTarget: { resourceType: 'app-container', resourceId: 'app-ctr-1' },
+ }),
+ ),
+ ).toBe('container:app-ctr-1');
+ });
+
+ it("maps metricsTarget 'k8s-cluster' onto the 'k8s' kind", () => {
+ // First switch case: `case 'k8s-cluster': return 'k8s'`
+ expect(
+ buildMetricKeyForUnifiedResource(
+ makeResource({
+ id: 'unused',
+ type: 'agent',
+ metricsTarget: { resourceType: 'k8s-cluster', resourceId: 'cluster-1' },
+ }),
+ ),
+ ).toBe('k8s:cluster-1');
+ });
+
+ it("maps metricsTarget 'k8s-node' onto the 'k8s' kind", () => {
+ // First switch case: `case 'k8s-node': return 'k8s'`
+ expect(
+ buildMetricKeyForUnifiedResource(
+ makeResource({
+ id: 'unused',
+ type: 'agent',
+ metricsTarget: { resourceType: 'k8s-node', resourceId: 'node-7' },
+ }),
+ ),
+ ).toBe('k8s:node-7');
+ });
+
+ it("maps metricsTarget 'pod' onto the 'k8s' kind", () => {
+ // First switch case: `case 'pod': return 'k8s'`
+ expect(
+ buildMetricKeyForUnifiedResource(
+ makeResource({
+ id: 'unused',
+ type: 'agent',
+ metricsTarget: { resourceType: 'pod', resourceId: 'pod-abcd' },
+ }),
+ ),
+ ).toBe('k8s:pod-abcd');
+ });
+
+ it("maps metricsTarget 'agent' onto the 'agent' kind", () => {
+ // First switch case: `case 'agent': return 'agent'`
+ expect(
+ buildMetricKeyForUnifiedResource(
+ makeResource({
+ id: 'unused',
+ type: 'vm',
+ metricsTarget: { resourceType: 'agent', resourceId: 'agent-9' },
+ }),
+ ),
+ ).toBe('agent:agent-9');
+ });
+ });
+
+ describe('first switch — fall-through to second switch', () => {
+ it('falls through when metricsTarget is absent (optional-chain undefined arm)', () => {
+ // `resource.metricsTarget?.resourceType` evaluates to undefined, so
+ // no first-switch case matches and the second switch runs.
+ // `type: 'vm'` hits the `case 'vm'` second-switch arm.
+ expect(
+ buildMetricKeyForUnifiedResource(
+ makeResource({
+ id: 'vm-200',
+ type: 'vm',
+ }),
+ ),
+ ).toBe('vm:vm-200');
+ });
+
+ it('falls through when metricsTarget.resourceType is a recognised-but-unhandled value', () => {
+ // 'k8s-deployment' is part of MetricsHistoryTargetResourceType but has
+ // NO case in the first switch, so execution falls through to switch #2.
+ // `type: 'docker-host'` then hits `case 'docker-host'` in switch #2.
+ // Note: buildMetricKeyForUnifiedResource still prefers the metricsTarget
+ // resourceId, so the suffix is the target id, not resource.id.
+ expect(
+ buildMetricKeyForUnifiedResource(
+ makeResource({
+ id: 'host-1',
+ type: 'docker-host',
+ metricsTarget: { resourceType: 'k8s-deployment', resourceId: 'deploy-x' },
+ }),
+ ),
+ ).toBe('dockerHost:deploy-x');
+ });
+ });
+
+ describe('second switch — resource.type arms', () => {
+ it("maps type 'docker-host' onto the 'dockerHost' kind", () => {
+ // Second switch case: `case 'docker-host': return 'dockerHost'`
+ expect(
+ buildMetricKeyForUnifiedResource(
+ makeResource({
+ id: 'host-2',
+ type: 'docker-host',
+ }),
+ ),
+ ).toBe('dockerHost:host-2');
+ });
+
+ it("maps type 'k8s-cluster' onto the 'k8s' kind", () => {
+ // Second switch case: `case 'k8s-cluster': return 'k8s'`
+ expect(
+ buildMetricKeyForUnifiedResource(
+ makeResource({
+ id: 'cluster-2',
+ type: 'k8s-cluster',
+ }),
+ ),
+ ).toBe('k8s:cluster-2');
+ });
+
+ it("maps type 'k8s-node' onto the 'k8s' kind", () => {
+ // Second switch case: `case 'k8s-node': return 'k8s'`
+ expect(
+ buildMetricKeyForUnifiedResource(
+ makeResource({
+ id: 'node-2',
+ type: 'k8s-node',
+ }),
+ ),
+ ).toBe('k8s:node-2');
+ });
+
+ it("maps type 'pod' onto the 'k8s' kind", () => {
+ // Second switch case: `case 'pod': return 'k8s'`
+ expect(
+ buildMetricKeyForUnifiedResource(
+ makeResource({
+ id: 'pod-2',
+ type: 'pod',
+ }),
+ ),
+ ).toBe('k8s:pod-2');
+ });
+
+ it("maps type 'system-container' onto the 'container' kind", () => {
+ // Second switch case: `case 'system-container': return 'container'`
+ expect(
+ buildMetricKeyForUnifiedResource(
+ makeResource({
+ id: 'ct-300',
+ type: 'system-container',
+ }),
+ ),
+ ).toBe('container:ct-300');
+ });
+
+ it("maps type 'oci-container' onto the 'container' kind", () => {
+ // Second switch case: `case 'oci-container': return 'container'`
+ expect(
+ buildMetricKeyForUnifiedResource(
+ makeResource({
+ id: 'oci-400',
+ type: 'oci-container',
+ }),
+ ),
+ ).toBe('container:oci-400');
+ });
+
+ it("maps type 'app-container' onto the 'container' kind", () => {
+ // Second switch case: `case 'app-container': return 'container'`
+ expect(
+ buildMetricKeyForUnifiedResource(
+ makeResource({
+ id: 'app-ctr-2',
+ type: 'app-container',
+ }),
+ ),
+ ).toBe('container:app-ctr-2');
+ });
+ });
+
+ describe('second switch — default fallback arm', () => {
+ it("defaults an unhandled resource type onto the 'agent' kind", () => {
+ // `type: 'k8s-deployment'` is a valid ResourceType but has no case in
+ // switch #2, so the `default` arm returns 'agent'. Cast through
+ // `unknown` because not every literal ResourceType is individually
+ // modelled in this fixture.
+ const resource = makeResource({
+ id: 'deploy-1',
+ type: 'k8s-deployment' as unknown as Resource['type'],
+ });
+ expect(buildMetricKeyForUnifiedResource(resource)).toBe('agent:deploy-1');
+ });
+
+ it("defaults a totally foreign resource type onto the 'agent' kind", () => {
+ // Defensive: a never-modelled string literal still hits `default`.
+ const resource = makeResource({
+ id: 'weird-1',
+ type: 'something-not-in-the-union' as unknown as Resource['type'],
+ });
+ expect(buildMetricKeyForUnifiedResource(resource)).toBe('agent:weird-1');
+ });
+ });
+});
diff --git a/frontend-modern/src/utils/__tests__/recoveryDatePresentation.branchcov2.test.ts b/frontend-modern/src/utils/__tests__/recoveryDatePresentation.branchcov2.test.ts
new file mode 100644
index 0000000000..a84c9beea3
--- /dev/null
+++ b/frontend-modern/src/utils/__tests__/recoveryDatePresentation.branchcov2.test.ts
@@ -0,0 +1,161 @@
+import { describe, expect, it } from 'vitest';
+import {
+ normalizeRecoveryDateSearchText,
+ parseRecoveryDateKey,
+ resolveRecoveryDateSearchKey,
+} from '@/utils/recoveryDatePresentation';
+
+describe('recoveryDatePresentation branch coverage (part 2)', () => {
+ describe('normalizeRecoveryDateSearchText', () => {
+ it('returns an empty string for a falsy value (value || "" branch)', () => {
+ expect(normalizeRecoveryDateSearchText('')).toBe('');
+ });
+
+ it('strips 1st/2nd/3rd/4th and 21st-style ordinals before punctuation collapse', () => {
+ expect(normalizeRecoveryDateSearchText('The 1st 2nd 3rd 4th and 21st')).toBe(
+ 'the 1 2 3 4 and 21',
+ );
+ });
+
+ it('collapses mixed punctuation, tabs, and repeated whitespace into single spaces', () => {
+ expect(normalizeRecoveryDateSearchText(' Friday, Feb\t14th ')).toBe('friday feb 14');
+ });
+
+ it('lowercases and trims alphabetic-only input without ordinals', () => {
+ expect(normalizeRecoveryDateSearchText(' FEBRUARY ')).toBe('february');
+ });
+ });
+
+ describe('parseRecoveryDateKey', () => {
+ it('falls back to new Date(key) when the year component is missing/NaN', () => {
+ const date = parseRecoveryDateKey('');
+ expect(Number.isNaN(date.getTime())).toBe(true);
+ });
+
+ it('falls back to new Date(key) when the month component is zero (!month branch)', () => {
+ const date = parseRecoveryDateKey('2026-0-05');
+ expect(Number.isNaN(date.getTime())).toBe(true);
+ });
+
+ it('falls back to new Date(key) when the day component is zero (!day branch)', () => {
+ const date = parseRecoveryDateKey('2026-03-0');
+ expect(Number.isNaN(date.getTime())).toBe(true);
+ });
+
+ it('parses a well-formed key into local Y/M/D components', () => {
+ const date = parseRecoveryDateKey('2026-07-12');
+ expect(date.getFullYear()).toBe(2026);
+ expect(date.getMonth()).toBe(6);
+ expect(date.getDate()).toBe(12);
+ });
+ });
+
+ describe('resolveRecoveryDateSearchKey', () => {
+ describe('length guard', () => {
+ it('returns null when normalized text is shorter than 5 characters', () => {
+ expect(resolveRecoveryDateSearchKey('Feb', [])).toBeNull();
+ });
+
+ it('proceeds when normalized text is exactly 5 characters (boundary)', () => {
+ expect(resolveRecoveryDateSearchKey('vm 12', [])).toBeNull();
+ });
+ });
+
+ describe('ISO-ish branch (yyyy m d)', () => {
+ it('resolves a normalized ISO-ish date to a key', () => {
+ expect(resolveRecoveryDateSearchKey('2026-02-14', [])).toBe('2026-02-14');
+ });
+
+ it('returns null when the ISO-ish month overflows (rollover guard in getRecoveryDateSearchKey)', () => {
+ expect(resolveRecoveryDateSearchKey('2026 13 01', [])).toBeNull();
+ });
+
+ it('returns null when the ISO-ish day is impossible for the month (Feb 30 rollover)', () => {
+ expect(resolveRecoveryDateSearchKey('2026 2 30', [])).toBeNull();
+ });
+ });
+
+ describe('weekday prefix stripping', () => {
+ it('strips a long weekday name before parsing the remainder', () => {
+ expect(resolveRecoveryDateSearchKey('Monday Feb 14 2026', [])).toBe('2026-02-14');
+ });
+
+ it('strips a short weekday alias before parsing the remainder', () => {
+ expect(resolveRecoveryDateSearchKey('Tue Feb 14 2026', [])).toBe('2026-02-14');
+ });
+ });
+
+ describe('token count guard', () => {
+ it('returns null when only a single non-weekday token remains (length < 2)', () => {
+ expect(resolveRecoveryDateSearchKey('hello', [])).toBeNull();
+ });
+
+ it('returns null when a weekday is the only token (length 0 after shift)', () => {
+ expect(resolveRecoveryDateSearchKey('monday', [])).toBeNull();
+ });
+
+ it('returns null when more than 3 tokens remain (length > 3)', () => {
+ expect(resolveRecoveryDateSearchKey('feb 14 2026 foo', [])).toBeNull();
+ });
+ });
+
+ describe('month/day validation', () => {
+ it('returns null when the month token is not a recognized month alias (monthIndex null)', () => {
+ expect(resolveRecoveryDateSearchKey('vm 14', [])).toBeNull();
+ });
+
+ it('returns null when the day token is non-numeric (Number.isInteger(day) false)', () => {
+ expect(resolveRecoveryDateSearchKey('Feb ab', [])).toBeNull();
+ });
+ });
+
+ describe('explicit-year (tokens[2]) branch', () => {
+ it('returns null when tokens[2] is not a 4-digit year', () => {
+ expect(resolveRecoveryDateSearchKey('Feb 14 26', [])).toBeNull();
+ });
+
+ it('returns null when the explicit year + month + day roll over (getRecoveryDateSearchKey guard)', () => {
+ expect(resolveRecoveryDateSearchKey('Feb 30 2026', [])).toBeNull();
+ });
+ });
+
+ describe('candidate resolution branch', () => {
+ it('returns the single candidate key matching month/day', () => {
+ expect(resolveRecoveryDateSearchKey('Feb 14', ['2026-02-13', '2026-02-14'])).toBe(
+ '2026-02-14',
+ );
+ });
+
+ it('returns null when multiple distinct candidate keys match the month/day', () => {
+ expect(resolveRecoveryDateSearchKey('Feb 14', ['2025-02-14', '2026-02-14'])).toBeNull();
+ });
+
+ it('ignores falsy/blank candidate entries via the String(key || "") defensive mapping', () => {
+ const keys = [null, undefined, '', '2026-02-14'] as unknown as readonly string[];
+ expect(resolveRecoveryDateSearchKey('Feb 14', keys)).toBe('2026-02-14');
+ });
+
+ it('de-duplicates repeated matching candidate keys before the count check', () => {
+ expect(
+ resolveRecoveryDateSearchKey('Feb 14', ['2026-02-14', '2026-02-14', '2026-02-14']),
+ ).toBe('2026-02-14');
+ });
+
+ it('falls back to the current year when candidates are present but none match', () => {
+ expect(resolveRecoveryDateSearchKey('Feb 14', ['2026-03-09'], new Date(2026, 0, 1))).toBe(
+ '2026-02-14',
+ );
+ });
+
+ it('falls back to the provided now year when there are no candidates', () => {
+ expect(resolveRecoveryDateSearchKey('Feb 14', [], new Date(2026, 4, 14))).toBe(
+ '2026-02-14',
+ );
+ });
+
+ it('returns null when the fallback date rolls over for the current year (Feb 30)', () => {
+ expect(resolveRecoveryDateSearchKey('Feb 30', [], new Date(2026, 0, 1))).toBeNull();
+ });
+ });
+ });
+});
diff --git a/frontend-modern/src/utils/__tests__/theme.branchcov2.test.ts b/frontend-modern/src/utils/__tests__/theme.branchcov2.test.ts
new file mode 100644
index 0000000000..0bd30ffa96
--- /dev/null
+++ b/frontend-modern/src/utils/__tests__/theme.branchcov2.test.ts
@@ -0,0 +1,291 @@
+/**
+ * Branch-coverage tests for theme.ts — second pass.
+ *
+ * Targets branches of the named helpers that the sibling theme.test.ts does
+ * not yet reach:
+ * - normalizeThemePreference: the `value ?? null` coalescing for `undefined`,
+ * the isThemePreference truthy arm for 'dark'/'system', and the falsy
+ * fallback for empty / malformed non-string input.
+ * - hasStoredThemePreference / getStoredThemePreference: the safeGet catch arm
+ * (localStorage.getItem throws), the non-canonical-stored fallback, and the
+ * SSR (`typeof window === 'undefined'`) early null-return arm.
+ * - persistThemePreference: the safeSet catch arm (setItem throws, swallowed),
+ * the 'light' canonical write, and the SSR no-op arm.
+ * - computeIsDark: the 'system' arm reading matchMedia for both match outcomes,
+ * the exact media-query string passed through, and the SSR early-return.
+ * - applyThemeClass: classList.toggle force semantics (idempotent add/remove)
+ * and the SSR no-op arm.
+ *
+ * SSR arms are reached by stubbing `window` to undefined for a single assertion
+ * and restoring it inside a `finally`; the module guards on
+ * `typeof window === 'undefined'` before touching window/document, so the stub
+ * is safe as long as it is removed before any other code runs.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { STORAGE_KEYS } from '@/utils/localStorage';
+import {
+ applyThemeClass,
+ computeIsDark,
+ getStoredThemePreference,
+ hasStoredThemePreference,
+ normalizeThemePreference,
+ persistThemePreference,
+} from '@/utils/theme';
+
+const THEME_KEY = STORAGE_KEYS.THEME_PREFERENCE;
+const DARK_MEDIA_QUERY = '(prefers-color-scheme: dark)';
+
+describe('normalizeThemePreference (branch coverage)', () => {
+ it("returns each canonical preference unchanged via the isThemePreference truthy arm", () => {
+ // 'dark' and 'system' arms are not exercised by the sibling test.
+ expect(normalizeThemePreference('dark')).toBe('dark');
+ expect(normalizeThemePreference('system')).toBe('system');
+ expect(normalizeThemePreference('light')).toBe('light');
+ });
+
+ it('coalesces undefined to null via `??` and falls back to system (falsy arm)', () => {
+ // `value ?? null` evaluates the right-hand `null` for undefined input.
+ expect(normalizeThemePreference(undefined)).toBe('system');
+ expect(normalizeThemePreference(null)).toBe('system');
+ });
+
+ it('normalizes an empty string to system (falsy isThemePreference arm)', () => {
+ expect(normalizeThemePreference('')).toBe('system');
+ });
+
+ it('falls back to system for a malformed non-string value cast through the param type', () => {
+ const malformed = 42 as unknown as Parameters<typeof normalizeThemePreference>[0];
+ expect(normalizeThemePreference(malformed)).toBe('system');
+ });
+});
+
+describe('hasStoredThemePreference (branch coverage)', () => {
+ beforeEach(() => {
+ window.localStorage.clear();
+ });
+
+ it('returns true for every canonical value stored under the canonical key', () => {
+ window.localStorage.setItem(THEME_KEY, 'light');
+ expect(hasStoredThemePreference()).toBe(true);
+
+ window.localStorage.setItem(THEME_KEY, 'system');
+ expect(hasStoredThemePreference()).toBe(true);
+ });
+
+ it('returns false when the stored value is not a recognized preference', () => {
+ window.localStorage.setItem(THEME_KEY, 'banana');
+ expect(hasStoredThemePreference()).toBe(false);
+ });
+
+ it('returns false (swallowing the throw) when localStorage.getItem throws', () => {
+ // safeGet catch arm.
+ const spy = vi.spyOn(window.localStorage, 'getItem').mockImplementation(() => {
+ throw new Error('SecurityError');
+ });
+ expect(hasStoredThemePreference()).toBe(false);
+ spy.mockRestore();
+ });
+
+ it('returns false in an SSR context where window is undefined (safeGet early null arm)', () => {
+ vi.stubGlobal('window', undefined);
+ try {
+ expect(hasStoredThemePreference()).toBe(false);
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ });
+});
+
+describe('getStoredThemePreference (branch coverage)', () => {
+ beforeEach(() => {
+ window.localStorage.clear();
+ });
+
+ it('returns dark and system verbatim when stored (truthy isThemePreference arm)', () => {
+ window.localStorage.setItem(THEME_KEY, 'dark');
+ expect(getStoredThemePreference()).toBe('dark');
+
+ window.localStorage.setItem(THEME_KEY, 'system');
+ expect(getStoredThemePreference()).toBe('system');
+ });
+
+ it('falls back to system when nothing is stored (explicitPreference === null)', () => {
+ expect(getStoredThemePreference()).toBe('system');
+ });
+
+ it('falls back to system for a non-canonical stored value (falsy arm)', () => {
+ window.localStorage.setItem(THEME_KEY, 'garbage');
+ expect(getStoredThemePreference()).toBe('system');
+ });
+
+ it('falls back to system when localStorage.getItem throws (safeGet catch arm)', () => {
+ const spy = vi.spyOn(window.localStorage, 'getItem').mockImplementation(() => {
+ throw new Error('SecurityError');
+ });
+ expect(getStoredThemePreference()).toBe('system');
+ spy.mockRestore();
+ });
+
+ it('returns system in an SSR context where window is undefined (safeGet early null arm)', () => {
+ vi.stubGlobal('window', undefined);
+ try {
+ expect(getStoredThemePreference()).toBe('system');
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ });
+});
+
+describe('persistThemePreference (branch coverage)', () => {
+ beforeEach(() => {
+ window.localStorage.clear();
+ });
+
+ it('writes the light preference verbatim under the canonical key', () => {
+ persistThemePreference('light');
+ expect(window.localStorage.getItem(THEME_KEY)).toBe('light');
+ });
+
+ it('overwrites a previous value with the latest preference', () => {
+ persistThemePreference('dark');
+ persistThemePreference('light');
+ expect(window.localStorage.getItem(THEME_KEY)).toBe('light');
+ });
+
+ it('swallows the error and does not throw when localStorage.setItem throws (safeSet catch arm)', () => {
+ const spy = vi.spyOn(window.localStorage, 'setItem').mockImplementation(() => {
+ throw new Error('QuotaExceededError');
+ });
+ expect(() => persistThemePreference('dark')).not.toThrow();
+ // The throw short-circuited the write, so nothing was persisted.
+ expect(window.localStorage.getItem(THEME_KEY)).toBeNull();
+ spy.mockRestore();
+ });
+
+ it('is a no-op in an SSR context where window is undefined (safeSet early-return arm)', () => {
+ vi.stubGlobal('window', undefined);
+ try {
+ expect(() => persistThemePreference('dark')).not.toThrow();
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ // No write occurred because the SSR guard returned before touching storage.
+ expect(window.localStorage.getItem(THEME_KEY)).toBeNull();
+ });
+});
+
+describe('computeIsDark (branch coverage)', () => {
+ const originalMatchMediaDescriptor = Object.getOwnPropertyDescriptor(window, 'matchMedia');
+
+ afterEach(() => {
+ if (originalMatchMediaDescriptor) {
+ Object.defineProperty(window, 'matchMedia', originalMatchMediaDescriptor);
+ }
+ });
+
+ it('queries the exact prefers-color-scheme query and returns false when the OS reports light', () => {
+ const matchMedia = vi.fn().mockImplementation((query: string) => ({
+ matches: false,
+ media: query,
+ onchange: null,
+ addListener: vi.fn(),
+ removeListener: vi.fn(),
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ dispatchEvent: vi.fn(),
+ }));
+ Object.defineProperty(window, 'matchMedia', {
+ writable: true,
+ configurable: true,
+ value: matchMedia,
+ });
+
+ expect(computeIsDark('system')).toBe(false);
+ expect(matchMedia).toHaveBeenCalledTimes(1);
+ expect(matchMedia).toHaveBeenCalledWith(DARK_MEDIA_QUERY);
+ });
+
+ it('returns true for system when the OS reports a dark scheme (matchMedia matches arm)', () => {
+ Object.defineProperty(window, 'matchMedia', {
+ writable: true,
+ configurable: true,
+ value: vi.fn().mockImplementation((query: string) => ({
+ matches: true,
+ media: query,
+ onchange: null,
+ addListener: vi.fn(),
+ removeListener: vi.fn(),
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ dispatchEvent: vi.fn(),
+ })),
+ });
+
+ expect(computeIsDark('system')).toBe(true);
+ });
+
+ it('short-circuits to true/false for dark/light without consulting matchMedia', () => {
+ const matchMedia = vi.fn();
+ Object.defineProperty(window, 'matchMedia', {
+ writable: true,
+ configurable: true,
+ value: matchMedia,
+ });
+
+ expect(computeIsDark('dark')).toBe(true);
+ expect(computeIsDark('light')).toBe(false);
+ expect(matchMedia).not.toHaveBeenCalled();
+ });
+
+ it('returns false for system in an SSR context (typeof window === "undefined" arm)', () => {
+ vi.stubGlobal('window', undefined);
+ try {
+ expect(computeIsDark('system')).toBe(false);
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ });
+});
+
+describe('applyThemeClass (branch coverage)', () => {
+ beforeEach(() => {
+ document.documentElement.classList.remove('dark');
+ });
+
+ afterEach(() => {
+ document.documentElement.classList.remove('dark');
+ });
+
+ it('force-adds and force-removes the dark class (classList.toggle second-arg semantics)', () => {
+ expect(document.documentElement.classList.contains('dark')).toBe(false);
+
+ applyThemeClass(true);
+ expect(document.documentElement.classList.contains('dark')).toBe(true);
+
+ // Idempotent: force=true keeps the class even when already present.
+ applyThemeClass(true);
+ expect(document.documentElement.classList.contains('dark')).toBe(true);
+
+ applyThemeClass(false);
+ expect(document.documentElement.classList.contains('dark')).toBe(false);
+
+ // Idempotent: force=false keeps it absent.
+ applyThemeClass(false);
+ expect(document.documentElement.classList.contains('dark')).toBe(false);
+ });
+
+ it('is a no-op in an SSR context where window is undefined (early-return arm)', () => {
+ applyThemeClass(true); // establish a known starting state in jsdom.
+ expect(document.documentElement.classList.contains('dark')).toBe(true);
+
+ vi.stubGlobal('window', undefined);
+ try {
+ expect(() => applyThemeClass(false)).not.toThrow();
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ // SSR guard returned before touching document, so the class is unchanged.
+ expect(document.documentElement.classList.contains('dark')).toBe(true);
+ });
+});