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 for 12 pure modules (GLM wave 0712 tier 2b)

rcourtman353c5c63a425
diff --git a/frontend-modern/src/components/AI/Chat/__tests__/assistantOutputHygiene.branchcov0712b.test.ts b/frontend-modern/src/components/AI/Chat/__tests__/assistantOutputHygiene.branchcov0712b.test.ts
new file mode 100644
index 0000000000..b6d7c7204c
--- /dev/null
+++ b/frontend-modern/src/components/AI/Chat/__tests__/assistantOutputHygiene.branchcov0712b.test.ts
@@ -0,0 +1,258 @@
+import { describe, expect, it } from 'vitest';
+import {
+ appendVisibleTextBeforeAssistantOutputArtifacts,
+ createAssistantOutputArtifactStreamState,
+ flushPendingAssistantOutputText,
+ stripAssistantOutputArtifacts,
+} from '../assistantOutputHygiene';
+
+// Branch-coverage companion to assistantOutputHygiene.test.ts. The five target
+// functions (findJSONToolCallLeak, findFunctionToolCallLeak,
+// splitTrailingPotentialToolNamePrefix, isKnownAssistantToolNamePrefix,
+// isPotentialContentChannelReasoningPrelude) are all module-private, so every
+// branch is driven through the three public entry points and asserted against
+// concrete shapes/strings.
+
+const freshState = () => createAssistantOutputArtifactStreamState();
+
+// ---------------------------------------------------------------------------
+// findJSONToolCallLeak — reached via assistantOutputArtifactIndex, surfaced
+// through stripAssistantOutputArtifacts.
+// ---------------------------------------------------------------------------
+
+describe('findJSONToolCallLeak branch coverage', () => {
+ it('returns -1 (no artifact) when the JSON object name is not tool-like', () => {
+ // name 'helper' fails isAssistantToolLikeName -> loop yields no leak, and no
+ // other artifact marker is present, so the content is preserved verbatim.
+ expect(stripAssistantOutputArtifacts('{"name":"helper","x":1}')).toEqual({
+ text: '{"name":"helper","x":1}',
+ stripped: false,
+ });
+ });
+
+ it('returns -1 when no JSON tool-call object appears at all', () => {
+ expect(stripAssistantOutputArtifacts('just plain prose here')).toEqual({
+ text: 'just plain prose here',
+ stripped: false,
+ });
+ });
+
+ it('reports the artifact when the JSON name is tool-like via the fenced ```json arm', () => {
+ expect(stripAssistantOutputArtifacts('```json\n{"name":"pulse_exec","a":1}\n```')).toEqual({
+ text: '',
+ stripped: true,
+ });
+ });
+
+ it('continues past a non-tool JSON match and reports a later tool-like match', () => {
+ // First object 'helper' is skipped (isAssistantToolLikeName false -> loop
+ // continues); the second object 'pulse_query' matches -> leak index returned.
+ expect(
+ stripAssistantOutputArtifacts('{"name":"helper","x":1}\n{"name":"pulse_query"}'),
+ ).toEqual({
+ text: '{"name":"helper","x":1}',
+ stripped: true,
+ });
+ });
+});
+
+// ---------------------------------------------------------------------------
+// findFunctionToolCallLeak — reached via assistantOutputArtifactIndex.
+// ---------------------------------------------------------------------------
+
+describe('findFunctionToolCallLeak branch coverage', () => {
+ it('returns -1 (no artifact) when a function-call name is not tool-like', () => {
+ expect(stripAssistantOutputArtifacts('Call helper(target="x") in the demo.')).toEqual({
+ text: 'Call helper(target="x") in the demo.',
+ stripped: false,
+ });
+ });
+
+ it('reports the tool NAME position rather than the preceding non-word character', () => {
+ // 'pulse_read' is preceded by a space; the leak index must resolve to the
+ // 'p', so the visible prefix slices exactly to 'Run'.
+ expect(stripAssistantOutputArtifacts('Run pulse_read(target_host="x") now')).toEqual({
+ text: 'Run',
+ stripped: true,
+ });
+ });
+
+ it('continues past a non-tool function call and reports a later tool-like call', () => {
+ // 'helper(' is skipped; 'pulse_read(' matches -> the visible prefix is the
+ // prose before the tool name.
+ expect(stripAssistantOutputArtifacts('helper(x) pulse_read(y)')).toEqual({
+ text: 'helper(x)',
+ stripped: true,
+ });
+ });
+});
+
+// ---------------------------------------------------------------------------
+// splitTrailingPotentialToolNamePrefix — reached via the append() idx<0 path.
+// ---------------------------------------------------------------------------
+
+describe('splitTrailingPotentialToolNamePrefix branch coverage', () => {
+ it('emits all text with nothing held when there is no trailing tool-name run', () => {
+ // 'Hello.' ends in '.' (not a tool-name char) -> start === length arm.
+ const state = freshState();
+ expect(appendVisibleTextBeforeAssistantOutputArtifacts(state, 'Hello.')).toEqual({
+ text: 'Hello.',
+ stripped: false,
+ });
+ expect(state.pendingText).toBe('');
+ });
+
+ it('holds a trailing pulse_ prefix together with its preceding backtick', () => {
+ const state = freshState();
+ expect(appendVisibleTextBeforeAssistantOutputArtifacts(state, 'see `pulse_')).toEqual({
+ text: 'see ',
+ stripped: false,
+ });
+ expect(state.pendingText).toBe('`pulse_');
+ });
+
+ it('holds a trailing patrol partial prefix with no backtick', () => {
+ const state = freshState();
+ expect(appendVisibleTextBeforeAssistantOutputArtifacts(state, 'go pat')).toEqual({
+ text: 'go ',
+ stripped: false,
+ });
+ expect(state.pendingText).toBe('pat');
+ });
+
+ it('holds nothing when the trailing run is not a known tool prefix', () => {
+ // 'pulx' is a tool-name run but not a prefix of pulse_/patrol_ and matches
+ // neither regex -> token-not-known arm.
+ const state = freshState();
+ expect(appendVisibleTextBeforeAssistantOutputArtifacts(state, 'go pulx')).toEqual({
+ text: 'go pulx',
+ stripped: false,
+ });
+ expect(state.pendingText).toBe('');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// isKnownAssistantToolNamePrefix — reached via splitTrailingPotentialToolNamePrefix.
+// ---------------------------------------------------------------------------
+
+describe('isKnownAssistantToolNamePrefix branch coverage', () => {
+ it('matches a bare pulse partial prefix via the "pulse_".startsWith arm', () => {
+ // 'pulse' (no underscore) is a prefix of 'pulse_' -> startsWith arm true.
+ const state = freshState();
+ expect(appendVisibleTextBeforeAssistantOutputArtifacts(state, 'use pulse')).toEqual({
+ text: 'use ',
+ stripped: false,
+ });
+ expect(state.pendingText).toBe('pulse');
+ });
+
+ it('matches a full pulse_ tool name via the /^pulse_/ regex arm', () => {
+ const state = freshState();
+ expect(appendVisibleTextBeforeAssistantOutputArtifacts(state, 'use pulse_read')).toEqual({
+ text: 'use ',
+ stripped: false,
+ });
+ expect(state.pendingText).toBe('pulse_read');
+ // On flush the held token is normalized through the labels map.
+ expect(flushPendingAssistantOutputText(state)).toBe('read command');
+ });
+
+ it('matches a full patrol_ tool name via the /^patrol_/ regex arm', () => {
+ const state = freshState();
+ expect(
+ appendVisibleTextBeforeAssistantOutputArtifacts(state, 'try patrol_remediate'),
+ ).toEqual({
+ text: 'try ',
+ stripped: false,
+ });
+ expect(state.pendingText).toBe('patrol_remediate');
+ expect(flushPendingAssistantOutputText(state)).toBe('remediation');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// isPotentialContentChannelReasoningPrelude — reached via the append() hold path
+// (shouldHoldPotentialAssistantOutputPrelude) when rawVisibleText is empty.
+// ---------------------------------------------------------------------------
+
+describe('isPotentialContentChannelReasoningPrelude branch coverage', () => {
+ it('returns false for whitespace-only content (empty-trimmed early guard)', () => {
+ // ' ' trimStarts to '' -> !trimmed -> false, so nothing is held and the
+ // spaces flow through unchanged.
+ const state = freshState();
+ expect(appendVisibleTextBeforeAssistantOutputArtifacts(state, ' ')).toEqual({
+ text: ' ',
+ stripped: false,
+ });
+ expect(state.pendingText).toBe('');
+ });
+
+ it('holds a short lowercase prefix of "thinking" (partial-prefix true arm)', () => {
+ const state = freshState();
+ expect(appendVisibleTextBeforeAssistantOutputArtifacts(state, 'Think')).toEqual({
+ text: '',
+ stripped: false,
+ });
+ expect(state.pendingText).toBe('Think');
+ });
+
+ it('holds a mixed-case prefix via the toLowerCase + partial-prefix arm', () => {
+ // 'THINK'.toLowerCase() === 'think' is still a prefix of 'thinking'.
+ const state = freshState();
+ expect(appendVisibleTextBeforeAssistantOutputArtifacts(state, 'THINK')).toEqual({
+ text: '',
+ stripped: false,
+ });
+ expect(state.pendingText).toBe('THINK');
+ });
+
+ it('holds the full "thinking" token via the heading arm (length is not < 8)', () => {
+ const state = freshState();
+ expect(appendVisibleTextBeforeAssistantOutputArtifacts(state, 'Thinking')).toEqual({
+ text: '',
+ stripped: false,
+ });
+ expect(state.pendingText).toBe('Thinking');
+ });
+
+ it('holds a "reasoning" heading via the heading arm', () => {
+ const state = freshState();
+ expect(appendVisibleTextBeforeAssistantOutputArtifacts(state, 'Reasoning')).toEqual({
+ text: '',
+ stripped: false,
+ });
+ expect(state.pendingText).toBe('Reasoning');
+ });
+
+ it('holds a markdown-prefixed reasoning heading (the optional #{1,6} arm)', () => {
+ const state = freshState();
+ expect(appendVisibleTextBeforeAssistantOutputArtifacts(state, '## Thinking')).toEqual({
+ text: '',
+ stripped: false,
+ });
+ expect(state.pendingText).toBe('## Thinking');
+ });
+
+ it('does not hold a short token that is neither a thinking-prefix nor a heading', () => {
+ // 'xyz' length < 8 but not a prefix of 'thinking' (partial arm false) and not
+ // a heading (heading arm false) -> not held.
+ const state = freshState();
+ expect(appendVisibleTextBeforeAssistantOutputArtifacts(state, 'xyz')).toEqual({
+ text: 'xyz',
+ stripped: false,
+ });
+ expect(state.pendingText).toBe('');
+ });
+
+ it('does not hold a longer token whose length skips the partial arm but is no heading', () => {
+ // 'hello world' length >= 8 so the partial-prefix arm is skipped, and it is
+ // not a reasoning heading -> not held.
+ const state = freshState();
+ expect(appendVisibleTextBeforeAssistantOutputArtifacts(state, 'hello world')).toEqual({
+ text: 'hello world',
+ stripped: false,
+ });
+ expect(state.pendingText).toBe('');
+ });
+});
diff --git a/frontend-modern/src/components/Workloads/__tests__/workloadUrlSyncModel.branchcov0712b.test.ts b/frontend-modern/src/components/Workloads/__tests__/workloadUrlSyncModel.branchcov0712b.test.ts
new file mode 100644
index 0000000000..6f2bde7dbe
--- /dev/null
+++ b/frontend-modern/src/components/Workloads/__tests__/workloadUrlSyncModel.branchcov0712b.test.ts
@@ -0,0 +1,182 @@
+import { describe, expect, it } from 'vitest';
+
+import type { WorkloadsWorkloadUrlParams } from '../workloadUrlSyncModel';
+import {
+ resolveWorkloadsWorkloadRuntimeParam,
+ resolveWorkloadsWorkloadTypeParam,
+} from '../workloadUrlSyncModel';
+
+const params = (
+ overrides: Partial<WorkloadsWorkloadUrlParams> = {},
+): WorkloadsWorkloadUrlParams => ({
+ type: '',
+ platform: '',
+ runtime: '',
+ context: '',
+ namespace: '',
+ cluster: '',
+ agent: '',
+ resource: '',
+ ...overrides,
+});
+
+describe('resolveWorkloadsWorkloadTypeParam (branch coverage)', () => {
+ describe('normalizeWorkloadViewModeParam alias map', () => {
+ it.each([
+ ['all', 'all'],
+ ['vm', 'vm'],
+ ['container', 'container'],
+ ['system-container', 'system-container'],
+ ['docker', 'app-container'],
+ ['app-container', 'app-container'],
+ ['k8s', 'pod'],
+ ['kubernetes', 'pod'],
+ ['pod', 'pod'],
+ ])('resolves type="%s" to "%s" when no kubernetes scope is set', (raw, expected) => {
+ expect(resolveWorkloadsWorkloadTypeParam(params({ type: raw }))).toBe(expected);
+ });
+
+ it('trims and lowercases the raw type before alias resolution', () => {
+ expect(resolveWorkloadsWorkloadTypeParam(params({ type: ' VM ' }))).toBe('vm');
+ expect(resolveWorkloadsWorkloadTypeParam(params({ type: 'KUBERNETES' }))).toBe('pod');
+ });
+ });
+
+ describe('ungoverned type → null (normalizeWorkloadViewModeParam fall-through)', () => {
+ it('returns null when type is empty', () => {
+ expect(resolveWorkloadsWorkloadTypeParam(params({ type: '' }))).toBeNull();
+ });
+
+ it('returns null when type matches no known alias', () => {
+ expect(resolveWorkloadsWorkloadTypeParam(params({ type: 'spaceship' }))).toBeNull();
+ });
+ });
+
+ describe('kubernetes scope precedence (hasWorkloadsWorkloadKubernetesScope)', () => {
+ it('suppresses a non-pod mode when only context is set', () => {
+ expect(resolveWorkloadsWorkloadTypeParam(params({ type: 'vm', context: 'prod' }))).toBeNull();
+ });
+
+ it('suppresses a non-pod mode when only namespace is set', () => {
+ expect(
+ resolveWorkloadsWorkloadTypeParam(params({ type: 'docker', namespace: 'default' })),
+ ).toBeNull();
+ });
+
+ it('suppresses a non-pod mode when both context and namespace are set', () => {
+ expect(
+ resolveWorkloadsWorkloadTypeParam(
+ params({ type: 'all', context: 'prod', namespace: 'default' }),
+ ),
+ ).toBeNull();
+ });
+
+ it('keeps the pod mode when context is set (nextMode === "pod")', () => {
+ expect(resolveWorkloadsWorkloadTypeParam(params({ type: 'pod', context: 'prod' }))).toBe(
+ 'pod',
+ );
+ });
+
+ it('keeps the pod mode when namespace is set and the raw alias is "k8s"', () => {
+ expect(
+ resolveWorkloadsWorkloadTypeParam(params({ type: 'k8s', namespace: 'default' })),
+ ).toBe('pod');
+ });
+
+ it('treats whitespace-only context/namespace as no scope', () => {
+ // Boolean(" ".trim()) === false for both fields, so the precedence guard
+ // is skipped and the resolved mode is returned unchanged.
+ expect(
+ resolveWorkloadsWorkloadTypeParam(
+ params({ type: 'vm', context: ' ', namespace: ' ' }),
+ ),
+ ).toBe('vm');
+ });
+ });
+});
+
+describe('resolveWorkloadsWorkloadRuntimeParam (branch coverage)', () => {
+ describe('Branch 1 — runtimeRelevant=false (passthrough)', () => {
+ it('is not relevant when nextMode is a non-container view (ternary true-arm, isContainer=false)', () => {
+ // type="vm": nextMode="vm", isContainerWorkloadViewMode(vm)=false,
+ // params.type non-empty → disjunction false → runtimeRelevant=false.
+ expect(
+ resolveWorkloadsWorkloadRuntimeParam(params({ type: 'vm', runtime: 'containerd' })),
+ ).toStrictEqual({ forceViewMode: null, runtime: 'containerd', shouldApply: false });
+ });
+
+ it('is not relevant when nextMode is pod', () => {
+ expect(
+ resolveWorkloadsWorkloadRuntimeParam(params({ type: 'pod', runtime: 'containerd' })),
+ ).toStrictEqual({ forceViewMode: null, runtime: 'containerd', shouldApply: false });
+ });
+
+ it('is not relevant when type is unknown and non-empty (ternary false-arm of nextMode check)', () => {
+ // type="spaceship": nextMode=null → `(nextMode ? ... : false)` evaluates
+ // its false arm; combined with non-empty params.type the disjunction is false.
+ expect(
+ resolveWorkloadsWorkloadRuntimeParam(params({ type: 'spaceship', runtime: 'podman' })),
+ ).toStrictEqual({ forceViewMode: null, runtime: 'podman', shouldApply: false });
+ });
+
+ it('is not relevant when kubernetes scope is present, even for a container type', () => {
+ // !hasWorkloadsWorkloadKubernetesScope short-circuits the entire expression.
+ expect(
+ resolveWorkloadsWorkloadRuntimeParam(
+ params({ type: 'docker', runtime: 'containerd', context: 'prod' }),
+ ),
+ ).toStrictEqual({ forceViewMode: null, runtime: 'containerd', shouldApply: false });
+ });
+
+ it('is not relevant when kubernetes scope is set via namespace only', () => {
+ expect(
+ resolveWorkloadsWorkloadRuntimeParam(
+ params({ type: 'docker', runtime: 'containerd', namespace: 'kube-system' }),
+ ),
+ ).toStrictEqual({ forceViewMode: null, runtime: 'containerd', shouldApply: false });
+ });
+ });
+
+ describe('Branch 2 — runtimeRelevant=true, empty runtime', () => {
+ it('clears runtime to "" when runtime is empty for a container type', () => {
+ expect(
+ resolveWorkloadsWorkloadRuntimeParam(params({ type: 'docker', runtime: '' })),
+ ).toStrictEqual({ forceViewMode: null, runtime: '', shouldApply: true });
+ });
+
+ it('treats whitespace-only runtime as empty (trim branch) and emits runtime=""', () => {
+ // Branch 2 returns the literal "" — NOT params.runtime. Asserts that
+ // whitespace-only input is normalized via the `.trim()` guard.
+ expect(
+ resolveWorkloadsWorkloadRuntimeParam(params({ type: 'docker', runtime: ' ' })),
+ ).toStrictEqual({ forceViewMode: null, runtime: '', shouldApply: true });
+ });
+
+ it('reaches Branch 2 via the empty-type relevance path (!params.type.trim())', () => {
+ // type="": nextMode=null and the ternary returns false, but the
+ // `|| !params.type.trim()` disjunct flips runtimeRelevant to true.
+ expect(
+ resolveWorkloadsWorkloadRuntimeParam(params({ type: '', runtime: '' })),
+ ).toStrictEqual({ forceViewMode: null, runtime: '', shouldApply: true });
+ });
+ });
+
+ describe('Branch 3 — runtimeRelevant=true, present runtime (forceViewMode="container")', () => {
+ it('forces container view via the empty-type path when runtime is present', () => {
+ // type="" makes nextMode=null but the empty-type disjunct keeps relevance;
+ // a non-empty runtime then bypasses Branch 2.
+ expect(
+ resolveWorkloadsWorkloadRuntimeParam(params({ type: '', runtime: 'podman' })),
+ ).toStrictEqual({ forceViewMode: 'container', runtime: 'podman', shouldApply: true });
+ });
+
+ it('passes a whitespace-padded runtime through verbatim in Branch 3', () => {
+ // OBSERVATION (reported, not fixed): Branch 3 returns `runtime: params.runtime`
+ // untrimmed, while Branch 2 normalizes whitespace-only to "". The two arms
+ // trim inconsistently.
+ expect(
+ resolveWorkloadsWorkloadRuntimeParam(params({ type: 'docker', runtime: ' podman ' })),
+ ).toStrictEqual({ forceViewMode: 'container', runtime: ' podman ', shouldApply: true });
+ });
+ });
+});
diff --git a/frontend-modern/src/features/storageBackups/__tests__/diskPresentation.branchcov0712b.test.ts b/frontend-modern/src/features/storageBackups/__tests__/diskPresentation.branchcov0712b.test.ts
new file mode 100644
index 0000000000..118509f838
--- /dev/null
+++ b/frontend-modern/src/features/storageBackups/__tests__/diskPresentation.branchcov0712b.test.ts
@@ -0,0 +1,418 @@
+import { describe, expect, it } from 'vitest';
+import type { Resource } from '@/types/resource';
+import {
+ buildPhysicalDiskGroupFilterOptions,
+ buildPhysicalDiskPresentationDataMap,
+ buildPhysicalDiskRoleFilterOptions,
+ extractPhysicalDiskPresentationData,
+ filterAndSortPhysicalDisks,
+ getPhysicalDiskHealthSummary,
+ getPhysicalDiskLifeTextClass,
+ getPhysicalDiskPlatformLabel,
+ getPhysicalDiskRoleLabel,
+ matchesPhysicalDiskHealthFilter,
+ PHYSICAL_DISK_MUTED_PLACEHOLDER_CLASS,
+ type DiskHealthStatusPresentation,
+ type PhysicalDiskPresentationData,
+} from '@/features/storageBackups/diskPresentation';
+
+// Shared factory mirroring the convention in diskPresentation.test.ts and
+// diskPresentation.branchcov.test.ts so optional fields default safely.
+function makeDiskData(
+ overrides: Partial<PhysicalDiskPresentationData> = {},
+): PhysicalDiskPresentationData {
+ return {
+ node: '',
+ instance: '',
+ devPath: '',
+ model: '',
+ serial: '',
+ wwn: '',
+ size: 0,
+ health: 'UNKNOWN',
+ riskReasons: [],
+ wearout: -1,
+ type: '',
+ temperature: 0,
+ rpm: 0,
+ used: '',
+ ...overrides,
+ };
+}
+
+// Helper to build a Resource carrying a physicalDisk payload, cast to satisfy
+// the strict Resource type without depending on its full surface.
+const diskResource = (id: string, physicalDisk: Record<string, unknown>): Resource =>
+ ({
+ id,
+ name: id,
+ platformType: 'agent',
+ physicalDisk,
+ }) as unknown as Resource;
+
+// ---------------------------------------------------------------------------
+// titleize (module-private — exercised via getPhysicalDiskRoleLabel)
+// ---------------------------------------------------------------------------
+
+describe('titleize via getPhysicalDiskRoleLabel (branchcov2)', () => {
+ it('title-cases a single plain word with no separators', () => {
+ expect(getPhysicalDiskRoleLabel(makeDiskData({ storageRole: 'parity' }))).toBe('Parity');
+ });
+
+ it('preserves the remainder of the word verbatim (rest is NOT lowercased)', () => {
+ // 'DATA' -> charAt(0).toUpperCase() + slice(1) -> 'D' + 'ATA' -> 'DATA'
+ expect(getPhysicalDiskRoleLabel(makeDiskData({ storageRole: 'DATA' }))).toBe('DATA');
+ });
+
+ it('does not split camelCase and keeps inner capitalization verbatim', () => {
+ expect(getPhysicalDiskRoleLabel(makeDiskData({ storageRole: 'cachePool' }))).toBe('CachePool');
+ });
+
+ it('strips leading/trailing separators via filter(Boolean)', () => {
+ expect(getPhysicalDiskRoleLabel(makeDiskData({ storageRole: '-parity-' }))).toBe('Parity');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// getPhysicalDiskPlatformLabel
+// ---------------------------------------------------------------------------
+
+describe('getPhysicalDiskPlatformLabel (branchcov2)', () => {
+ it('returns the fallback label when it is a non-empty string', () => {
+ expect(getPhysicalDiskPlatformLabel({} as Resource, 'TrueNAS')).toBe('TrueNAS');
+ });
+
+ it('returns "Unknown" when the fallback label is empty', () => {
+ expect(getPhysicalDiskPlatformLabel({} as Resource, '')).toBe('Unknown');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// extractPhysicalDiskPresentationData
+// ---------------------------------------------------------------------------
+
+describe('extractPhysicalDiskPresentationData (branchcov2)', () => {
+ it('preserves an explicit wearout of 0 via nullish coalescing (not -1)', () => {
+ const data = extractPhysicalDiskPresentationData(
+ diskResource('d', { wearout: 0, temperature: 0 }),
+ );
+ // `pd.wearout ?? -1` keeps 0; an `||` would have collapsed it to -1.
+ expect(data.wearout).toBe(0);
+ expect(data.temperature).toBe(0);
+ });
+
+ it('falls back model to resource.name when physicalDisk is present but model is absent', () => {
+ const resource = {
+ id: 'd',
+ name: 'named-disk',
+ platformType: 'agent',
+ physicalDisk: { health: 'PASSED' },
+ } as unknown as Resource;
+ expect(extractPhysicalDiskPresentationData(resource).model).toBe('named-disk');
+ });
+
+ it('returns an empty model when both pd.model and resource.name are absent', () => {
+ const resource = {
+ id: 'd',
+ platformType: 'agent',
+ physicalDisk: { health: 'PASSED' },
+ } as unknown as Resource;
+ expect(extractPhysicalDiskPresentationData(resource).model).toBe('');
+ });
+
+ it('maps an empty smart object to a smartAttributes shell with all-undefined fields', () => {
+ const data = extractPhysicalDiskPresentationData(diskResource('d', { smart: {} }));
+ expect(data.smartAttributes).toStrictEqual({
+ powerOnHours: undefined,
+ powerCycles: undefined,
+ reallocatedSectors: undefined,
+ pendingSectors: undefined,
+ offlineUncorrectable: undefined,
+ udmaCrcErrors: undefined,
+ percentageUsed: undefined,
+ availableSpare: undefined,
+ mediaErrors: undefined,
+ unsafeShutdowns: undefined,
+ });
+ });
+
+ it('reads diskType into the type field and falls back sizeBytes/used to defaults when absent', () => {
+ const data = extractPhysicalDiskPresentationData(
+ diskResource('d', { diskType: 'nvme', health: 'GOOD' }),
+ );
+ expect(data.type).toBe('nvme');
+ expect(data.size).toBe(0);
+ expect(data.used).toBe('');
+ expect(data.health).toBe('GOOD');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// buildPhysicalDiskPresentationDataMap
+// ---------------------------------------------------------------------------
+
+describe('buildPhysicalDiskPresentationDataMap (branchcov2)', () => {
+ it('returns an empty Map for a null disks argument (defensive `disks || []` arm)', () => {
+ expect(buildPhysicalDiskPresentationDataMap(null as unknown as Resource[]).size).toBe(0);
+ });
+
+ it('returns an empty Map for an undefined disks argument', () => {
+ expect(buildPhysicalDiskPresentationDataMap(undefined as unknown as Resource[]).size).toBe(0);
+ });
+
+ it('keys entries by resource.id and extracts presentation data', () => {
+ const a = diskResource('a', { model: 'Drive A', health: 'PASSED' });
+ const b = diskResource('b', { model: 'Drive B', health: 'FAILED' });
+ const map = buildPhysicalDiskPresentationDataMap([a, b]);
+ expect(map.size).toBe(2);
+ expect(map.get('a')?.model).toBe('Drive A');
+ expect(map.get('a')?.health).toBe('PASSED');
+ expect(map.get('b')?.health).toBe('FAILED');
+ });
+
+ it('overwrites the entry when two resources share an id (last wins)', () => {
+ const first = diskResource('dup', { model: 'First' });
+ const second = diskResource('dup', { model: 'Second' });
+ const map = buildPhysicalDiskPresentationDataMap([first, second]);
+ expect(map.size).toBe(1);
+ expect(map.get('dup')?.model).toBe('Second');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// filterAndSortPhysicalDisks
+// ---------------------------------------------------------------------------
+
+describe('filterAndSortPhysicalDisks (branchcov2)', () => {
+ it('returns an empty array for a null disks argument', () => {
+ expect(
+ filterAndSortPhysicalDisks(null as unknown as Resource[], {
+ selectedNode: null,
+ searchTerm: '',
+ getDiskData: (d) => extractPhysicalDiskPresentationData(d),
+ matchesNode: () => true,
+ }),
+ ).toEqual([]);
+ });
+
+ it('filters by selectedNode via matchesNode, forwarding id/name/instance (incl. proxmox.instance)', () => {
+ const diskA = {
+ id: 'a',
+ name: 'a',
+ parentName: 'n1',
+ platformType: 'agent',
+ physicalDisk: { devPath: '/dev/sda', health: 'PASSED' },
+ } as unknown as Resource;
+ const diskB = {
+ id: 'b',
+ name: 'b',
+ parentName: 'n2',
+ platformType: 'agent',
+ physicalDisk: { devPath: '/dev/sdb', health: 'PASSED' },
+ } as unknown as Resource;
+ const selectedNode = {
+ id: 'node-1',
+ name: 'n1',
+ platformData: { proxmox: { instance: 'pve1' } },
+ } as unknown as Resource;
+
+ const captured: { id: string; name: string; instance?: string }[] = [];
+ const result = filterAndSortPhysicalDisks([diskA, diskB], {
+ selectedNode,
+ searchTerm: '',
+ getDiskData: (d) => extractPhysicalDiskPresentationData(d),
+ matchesNode: (disk, node) => {
+ captured.push({ id: node.id, name: node.name, instance: node.instance });
+ return disk.parentName === node.name;
+ },
+ });
+
+ // Both calls forward the derived node identity (instance read via the
+ // `(platformData as any)?.proxmox?.instance` optional chain).
+ expect(captured).toEqual([
+ { id: 'node-1', name: 'n1', instance: 'pve1' },
+ { id: 'node-1', name: 'n1', instance: 'pve1' },
+ ]);
+ expect(result.map((d) => d.id)).toEqual(['a']);
+ });
+
+ it('sorts by priority (critical risk before healthy) when no node is selected', () => {
+ const healthy = diskResource('healthy', { devPath: '/dev/sda', health: 'PASSED' });
+ const critical = diskResource('critical', {
+ devPath: '/dev/sdb',
+ health: 'PASSED',
+ risk: { level: 'critical' },
+ });
+ const result = filterAndSortPhysicalDisks([healthy, critical], {
+ selectedNode: null,
+ searchTerm: '',
+ getDiskData: (d) => extractPhysicalDiskPresentationData(d),
+ matchesNode: () => true,
+ });
+ expect(result.map((d) => d.id)).toEqual(['critical', 'healthy']);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// matchesPhysicalDiskHealthFilter
+// ---------------------------------------------------------------------------
+
+describe('matchesPhysicalDiskHealthFilter (branchcov2)', () => {
+ it('returns true for filter "all" regardless of health', () => {
+ expect(matchesPhysicalDiskHealthFilter('healthy', 'all')).toBe(true);
+ expect(matchesPhysicalDiskHealthFilter('critical', 'all')).toBe(true);
+ });
+
+ it.each([
+ ['warning'],
+ ['critical'],
+ ['offline'],
+ ] as const)('returns true for "attention" when health is %s', (health) => {
+ expect(matchesPhysicalDiskHealthFilter(health, 'attention')).toBe(true);
+ });
+
+ it.each(['healthy', 'unknown'])(
+ 'returns false for "attention" when health is %s',
+ (health) => {
+ expect(matchesPhysicalDiskHealthFilter(health as 'healthy', 'attention')).toBe(false);
+ },
+ );
+
+ it('returns true on an exact health/filter match', () => {
+ expect(matchesPhysicalDiskHealthFilter('warning', 'warning')).toBe(true);
+ expect(matchesPhysicalDiskHealthFilter('critical', 'critical')).toBe(true);
+ });
+
+ it('returns false on an exact health/filter mismatch', () => {
+ expect(matchesPhysicalDiskHealthFilter('healthy', 'warning')).toBe(false);
+ expect(matchesPhysicalDiskHealthFilter('offline', 'critical')).toBe(false);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// getPhysicalDiskHealthSummary
+// ---------------------------------------------------------------------------
+
+describe('getPhysicalDiskHealthSummary (branchcov2)', () => {
+ const statusWith = (summary?: string): DiskHealthStatusPresentation =>
+ ({ label: 'X', summary, tone: 't' } as unknown as DiskHealthStatusPresentation);
+
+ it('returns empty string when summary is undefined (optional-chain arm)', () => {
+ expect(getPhysicalDiskHealthSummary(statusWith(undefined))).toBe('');
+ });
+
+ it('returns empty string when summary is whitespace-only', () => {
+ expect(getPhysicalDiskHealthSummary(statusWith(' '))).toBe('');
+ });
+
+ it('returns empty string when summary equals the canonical "no issues" message', () => {
+ expect(
+ getPhysicalDiskHealthSummary(statusWith('No active disk-health issues.')),
+ ).toBe('');
+ });
+
+ it('returns the trimmed summary for a real, non-canonical message', () => {
+ expect(getPhysicalDiskHealthSummary(statusWith(' Pending sectors detected. '))).toBe(
+ 'Pending sectors detected.',
+ );
+ });
+});
+
+// ---------------------------------------------------------------------------
+// getPhysicalDiskLifeTextClass
+// ---------------------------------------------------------------------------
+
+describe('getPhysicalDiskLifeTextClass (branchcov2)', () => {
+ it('returns the muted placeholder class for the unreported boundary wearout -1', () => {
+ expect(getPhysicalDiskLifeTextClass(makeDiskData({ wearout: -1 }))).toBe(
+ PHYSICAL_DISK_MUTED_PLACEHOLDER_CLASS,
+ );
+ });
+
+ it('returns the muted placeholder class for wearout 0 (<= 0 branch)', () => {
+ expect(getPhysicalDiskLifeTextClass(makeDiskData({ wearout: 0 }))).toBe(
+ PHYSICAL_DISK_MUTED_PLACEHOLDER_CLASS,
+ );
+ });
+
+ it('returns the muted placeholder class when wearout is not a number', () => {
+ expect(
+ getPhysicalDiskLifeTextClass(makeDiskData({ wearout: 'nope' as unknown as number })),
+ ).toBe(PHYSICAL_DISK_MUTED_PLACEHOLDER_CLASS);
+ });
+
+ it('returns the red class for wearout just below 20', () => {
+ expect(getPhysicalDiskLifeTextClass(makeDiskData({ wearout: 19 }))).toBe(
+ 'text-red-600 dark:text-red-400',
+ );
+ });
+
+ it('returns the amber class at the wearout=20 boundary (< 20 is false, < 50 true)', () => {
+ expect(getPhysicalDiskLifeTextClass(makeDiskData({ wearout: 20 }))).toBe(
+ 'text-amber-600 dark:text-amber-400',
+ );
+ });
+
+ it('returns the amber class for wearout just below 50', () => {
+ expect(getPhysicalDiskLifeTextClass(makeDiskData({ wearout: 49 }))).toBe(
+ 'text-amber-600 dark:text-amber-400',
+ );
+ });
+
+ it('returns the green class at the wearout=50 boundary (< 50 is false)', () => {
+ expect(getPhysicalDiskLifeTextClass(makeDiskData({ wearout: 50 }))).toBe(
+ 'text-green-600 dark:text-green-400',
+ );
+ });
+});
+
+// ---------------------------------------------------------------------------
+// buildPhysicalDiskFacetOptions (module-private — exercised via
+// buildPhysicalDiskRoleFilterOptions / buildPhysicalDiskGroupFilterOptions)
+// ---------------------------------------------------------------------------
+
+describe('buildPhysicalDiskFacetOptions via role/group filter option builders (branchcov2)', () => {
+ it('returns only the "all" option for a null disks argument', () => {
+ const options = buildPhysicalDiskRoleFilterOptions(null as unknown as Resource[]);
+ expect(options).toEqual([{ value: 'all', label: 'All roles' }]);
+ });
+
+ it('deduplicates, skips empty labels, falls back to type, and sorts by label', () => {
+ const cacheA = diskResource('a', { storageRole: 'cache' });
+ const cacheB = diskResource('b', { storageRole: 'cache' }); // duplicate of 'cache'
+ const parity = diskResource('c', { storageRole: 'parity' });
+ const ssd = diskResource('d', { diskType: 'ssd' }); // role via type fallback -> 'SSD'
+ const empty = diskResource('e', {}); // no role, no type -> '' skipped
+
+ const options = buildPhysicalDiskRoleFilterOptions([cacheA, cacheB, parity, ssd, empty]);
+ expect(options).toEqual([
+ { value: 'all', label: 'All roles' },
+ { value: 'cache', label: 'Cache' },
+ { value: 'parity', label: 'Parity' },
+ { value: 'ssd', label: 'SSD' },
+ ]);
+ });
+
+ it('exercises the group-facet path: storageGroup label is deduped and sorted', () => {
+ const a = diskResource('a', { storageGroup: 'tank' });
+ const b = diskResource('b', { storageGroup: 'tank' }); // duplicate
+ const c = diskResource('c', { storageGroup: 'mirror' });
+ const d = diskResource('d', {}); // no group, no used -> '' skipped
+
+ const options = buildPhysicalDiskGroupFilterOptions([a, b, c, d]);
+ expect(options).toEqual([
+ { value: 'all', label: 'All groups' },
+ { value: 'mirror', label: 'mirror' },
+ { value: 'tank', label: 'tank' },
+ ]);
+ });
+
+ it('uses the "used" fallback label for group facet when storageGroup is absent', () => {
+ const zfs = diskResource('a', { used: 'ZFS' });
+ const options = buildPhysicalDiskGroupFilterOptions([zfs]);
+ expect(options).toEqual([
+ { value: 'all', label: 'All groups' },
+ { value: 'zfs', label: 'ZFS' },
+ ]);
+ });
+});
diff --git a/frontend-modern/src/features/storageBackups/__tests__/storageAdapters.branchcov0712b.test.ts b/frontend-modern/src/features/storageBackups/__tests__/storageAdapters.branchcov0712b.test.ts
new file mode 100644
index 0000000000..eb93b2c012
--- /dev/null
+++ b/frontend-modern/src/features/storageBackups/__tests__/storageAdapters.branchcov0712b.test.ts
@@ -0,0 +1,260 @@
+import { describe, expect, it } from 'vitest';
+import type { State } from '@/types/api';
+import type { Resource } from '@/types/resource';
+import type { StorageAdapterContext } from '@/features/storageBackups/models';
+import { DEFAULT_STORAGE_ADAPTERS } from '@/features/storageBackups/storageAdapters';
+
+const baseState = (overrides: Partial<State> = {}): State => ({
+ connectedInfrastructure: [],
+ metrics: [],
+ performance: {
+ apiCallDuration: {},
+ lastPollDuration: 0,
+ pollingStartTime: '',
+ totalApiCalls: 0,
+ failedApiCalls: 0,
+ cacheHits: 0,
+ cacheMisses: 0,
+ },
+ connectionHealth: {},
+ stats: { startTime: '', uptime: 0, pollingCycles: 0, webSocketClients: 0, version: 'dev' },
+ activeAlerts: [],
+ recentlyResolved: [],
+ lastUpdate: 0,
+ resources: [],
+ ...overrides,
+ pveTagColors: overrides.pveTagColors ?? {},
+ pveTagStyles: overrides.pveTagStyles ?? {},
+});
+
+const makeResource = (overrides: Partial<Resource> = {}): Resource =>
+ ({
+ id: 'storage-1',
+ type: 'storage',
+ name: 'local',
+ displayName: 'local',
+ platformId: 'cluster-a',
+ platformType: 'proxmox-pve',
+ sourceType: 'api',
+ status: 'online',
+ lastSeen: 1731000000000,
+ platformData: {
+ type: 'dir',
+ node: 'pve1',
+ instance: 'cluster-a',
+ shared: false,
+ },
+ ...overrides,
+ }) as Resource;
+
+const ctx = (resources: Resource[]): StorageAdapterContext => ({
+ state: baseState(),
+ resources,
+});
+
+const resourceAdapter = DEFAULT_STORAGE_ADAPTERS[0];
+
+describe('storageAdapters.branchcov2 - mapResourceStorageRecord', () => {
+ it('falls back to platformData.platform when no storage meta or storage.platform is set', () => {
+ const resource = makeResource({
+ id: 'pd-platform',
+ platformData: { platform: 'custom-plat', topology: 'custom-topo' },
+ });
+ const [record] = resourceAdapter.build(ctx([resource]));
+ expect(record.details?.platform).toBe('custom-plat');
+ expect(record.details?.topology).toBe('custom-topo');
+ });
+
+ it('reads proxmoxNode from resource.proxmox.node (the first || arm)', () => {
+ const resource = makeResource({
+ id: 'prox-node',
+ parentName: 'parent-host',
+ proxmox: { node: 'pve-prox' },
+ platformData: { type: 'dir', node: 'pd-node' },
+ });
+ const [record] = resourceAdapter.build(ctx([resource]));
+ expect(record.details?.node).toBe('pve-prox');
+ expect(record.details?.nodeHints).toEqual(expect.arrayContaining(['pve-prox']));
+ expect(record.location.label).toBe('parent-host');
+ });
+
+ it('resolves the non-backup location label to "Unknown" when every source is falsy', () => {
+ const resource = makeResource({
+ id: 'unknown-node',
+ parentName: undefined,
+ parentId: '',
+ platformId: '',
+ platformData: { type: 'dir' },
+ });
+ const [record] = resourceAdapter.build(ctx([resource]));
+ expect(record.location.label).toBe('Unknown');
+ expect(record.location.scope).toBe('node');
+ });
+
+ it('resolves the backup-repository location label to "Unknown" through the pbs arm', () => {
+ const resource = makeResource({
+ id: 'unknown-pbs',
+ type: 'datastore',
+ parentName: undefined,
+ parentId: '',
+ platformId: '',
+ platformData: { type: 'pbs' },
+ });
+ const [record] = resourceAdapter.build(ctx([resource]));
+ expect(record.location.label).toBe('Unknown');
+ expect(record.location.scope).toBe('cluster');
+ expect(record.category).toBe('backup-repository');
+ });
+
+ it('uses platformData.pbsInstanceName for the backup location label when parentName is absent', () => {
+ const resource = makeResource({
+ id: 'pbs-inst',
+ type: 'datastore',
+ parentName: undefined,
+ platformData: { type: 'pbs', pbsInstanceName: 'pbs-inst-7' },
+ });
+ const [record] = resourceAdapter.build(ctx([resource]));
+ expect(record.location.label).toBe('pbs-inst-7');
+ expect(record.details?.content).toBe('backup');
+ });
+
+ it('dedupes nodeHints and drops whitespace-only storage node entries', () => {
+ const resource = makeResource({
+ id: 'hints',
+ name: 'hints-store',
+ parentName: 'pve1',
+ parentId: 'agent-x',
+ platformId: 'cluster-a',
+ platformData: { type: 'dir', node: 'pve2' },
+ proxmox: { node: 'pve1' },
+ storage: { nodes: ['pve2', ' ', 'pve3'] },
+ });
+ const [record] = resourceAdapter.build(ctx([resource]));
+ expect(record.details?.nodeHints).toEqual(['pve1', 'pve2', 'pve3', 'agent-x', 'cluster-a']);
+ });
+
+ it('falls back to storageNodes[0] for details.node and the location label', () => {
+ const resource = makeResource({
+ id: 'sn-node',
+ parentName: undefined,
+ platformData: { type: 'dir' },
+ storage: { nodes: ['sn1', 'sn2'] },
+ });
+ const [record] = resourceAdapter.build(ctx([resource]));
+ expect(record.details?.node).toBe('sn1');
+ expect(record.location.label).toBe('sn1');
+ });
+
+ it('uses platformData.zfsPool when storageMeta has no zfsPool (the ?? right arm)', () => {
+ const resource = makeResource({
+ id: 'zfs-pd',
+ platformData: { zfsPool: { name: 'rpool', state: 'ONLINE' } },
+ storage: { type: 'dir' },
+ });
+ const [record] = resourceAdapter.build(ctx([resource]));
+ expect(record.details?.zfsPool).toEqual({ name: 'rpool', state: 'ONLINE' });
+ });
+
+ it('threads metricsTarget into refs.resourceId and the metricsTarget field', () => {
+ const resource = makeResource({
+ id: 'mt-res',
+ platformId: 'plat-9',
+ metricsTarget: { resourceType: 'storage', resourceId: 'metric-ref-9' },
+ });
+ const [record] = resourceAdapter.build(ctx([resource]));
+ expect(record.metricsTarget).toEqual({ resourceType: 'storage', resourceId: 'metric-ref-9' });
+ expect(record.refs?.resourceId).toBe('metric-ref-9');
+ expect(record.refs?.platformEntityId).toBe('plat-9');
+ });
+
+ it('falls back to resource.id for refs.resourceId when metricsTarget is absent', () => {
+ const resource = makeResource({ id: 'no-mt', platformId: 'plat-fb' });
+ const [record] = resourceAdapter.build(ctx([resource]));
+ expect(record.metricsTarget).toBeUndefined();
+ expect(record.refs?.resourceId).toBe('no-mt');
+ expect(record.refs?.platformEntityId).toBe('plat-fb');
+ });
+
+ it('produces all-null capacity when the resource has no disk metric', () => {
+ const resource = makeResource({ id: 'no-disk' });
+ const [record] = resourceAdapter.build(ctx([resource]));
+ expect(record.capacity).toStrictEqual({
+ totalBytes: null,
+ usedBytes: null,
+ freeBytes: null,
+ usagePercent: null,
+ });
+ });
+
+ it('coerces non-finite and non-number disk values to null capacity slots', () => {
+ const resource = makeResource({
+ id: 'bad-disk',
+ disk: {
+ current: Number.NaN,
+ total: Number.POSITIVE_INFINITY,
+ used: 'big' as unknown as number,
+ },
+ });
+ const [record] = resourceAdapter.build(ctx([resource]));
+ expect(record.capacity).toStrictEqual({
+ totalBytes: null,
+ usedBytes: null,
+ freeBytes: null,
+ usagePercent: null,
+ });
+ });
+
+ it('passes consumer/protected/affected counts, protection flags and incident fields straight through', () => {
+ const resource = makeResource({
+ id: 'rich',
+ platformData: { type: 'dir' },
+ storage: { consumerCount: 7, protectionReduced: true, rebuildInProgress: true },
+ pbs: { protectedWorkloadCount: 4, affectedDatastoreCount: 2 },
+ incidentCategory: 'recoverability',
+ incidentSeverity: 'critical',
+ incidentPriority: 42,
+ });
+ const [record] = resourceAdapter.build(ctx([resource]));
+ expect(record.consumerCount).toBe(7);
+ expect(record.protectedWorkloadCount).toBe(4);
+ expect(record.affectedDatastoreCount).toBe(2);
+ expect(record.protectionReduced).toBe(true);
+ expect(record.rebuildInProgress).toBe(true);
+ expect(record.incidentCategory).toBe('recoverability');
+ expect(record.incidentSeverity).toBe('critical');
+ expect(record.incidentPriority).toBe(42);
+ expect(record.details?.protectionReduced).toBe(true);
+ expect(record.details?.rebuildInProgress).toBe(true);
+ expect(record.details?.incidentCategory).toBe('recoverability');
+ expect(record.details?.incidentSeverity).toBe('critical');
+ expect(record.details?.incidentPriority).toBe(42);
+ });
+
+ it('surfaces enriched storage meta fields (content/contentTypes/path/protection/counts) into details', () => {
+ const resource = makeResource({
+ id: 'meta-detail',
+ platformData: {},
+ storage: {
+ type: 'dir',
+ contentTypes: ['images', 'rootdir'],
+ path: '/mnt/dir',
+ protection: 'replicated',
+ syncProgress: 55,
+ numProtected: 4,
+ numDisabled: 1,
+ numInvalid: 2,
+ numMissing: 3,
+ },
+ });
+ const [record] = resourceAdapter.build(ctx([resource]));
+ expect(record.details?.content).toBe('images,rootdir');
+ expect(record.details?.contentTypes).toEqual(['images', 'rootdir']);
+ expect(record.details?.path).toBe('/mnt/dir');
+ expect(record.details?.protection).toBe('replicated');
+ expect(record.details?.syncProgress).toBe(55);
+ expect(record.details?.numProtected).toBe(4);
+ expect(record.details?.numDisabled).toBe(1);
+ expect(record.details?.numInvalid).toBe(2);
+ expect(record.details?.numMissing).toBe(3);
+ });
+});
diff --git a/frontend-modern/src/features/storageBackups/__tests__/zfsPresentation.branchcov0712b.test.ts b/frontend-modern/src/features/storageBackups/__tests__/zfsPresentation.branchcov0712b.test.ts
new file mode 100644
index 0000000000..6365c2a1c9
--- /dev/null
+++ b/frontend-modern/src/features/storageBackups/__tests__/zfsPresentation.branchcov0712b.test.ts
@@ -0,0 +1,117 @@
+import { describe, expect, it } from 'vitest';
+import type { ZFSDevice } from '@/types/api';
+import { getZfsDeviceBlockClass } from '@/features/storageBackups/zfsPresentation';
+
+// ---------------------------------------------------------------------------
+// Fixture builder — mirror zfsPresentation.test.ts: a minimal `ZFSDevice` cast.
+// The only field getZfsDeviceBlockClass reads is `state`, so the factory only
+// needs a state override. Each test still passes a fully-typed ZFSDevice so the
+// pre-push tsconfig stays happy without `as any` on the call site.
+// ---------------------------------------------------------------------------
+
+const makeDevice = (overrides: Partial<ZFSDevice> = {}): ZFSDevice =>
+ ({
+ name: 'da0',
+ type: 'disk',
+ state: 'ONLINE',
+ readErrors: 0,
+ writeErrors: 0,
+ checksumErrors: 0,
+ ...overrides,
+ }) as ZFSDevice;
+
+// ===========================================================================
+// getZfsDeviceBlockClass
+//
+// Source branches:
+// L4 `device.state?.toUpperCase()` — optional-chain + normalization
+// L5 `state === 'ONLINE'` — true / false
+// L6 `state === 'DEGRADED'` — true / false
+// L7 `state === 'FAULTED' || state === 'UNAVAIL' || state === 'OFFLINE'`
+// — three OR arms
+// L10 default fall-through — slate
+// ===========================================================================
+
+describe('getZfsDeviceBlockClass branch coverage', () => {
+ // ---- L5 true arm: ONLINE → exact green block string ---------------------
+ it('returns the exact ONLINE green block class with hover variant', () => {
+ expect(getZfsDeviceBlockClass(makeDevice({ state: 'ONLINE' }))).toBe(
+ 'bg-green-500 dark:bg-green-500 hover:bg-green-400',
+ );
+ });
+
+ // ---- L5 false → L6 true arm: DEGRADED → exact yellow block string ------
+ it('returns the exact DEGRADED yellow block class with hover variant', () => {
+ expect(getZfsDeviceBlockClass(makeDevice({ state: 'DEGRADED' }))).toBe(
+ 'bg-yellow-500 dark:bg-yellow-500 hover:bg-yellow-400',
+ );
+ });
+
+ // ---- L7 first OR arm: FAULTED → exact red block string ------------------
+ it('returns the exact red block class for FAULTED (first OR arm)', () => {
+ expect(getZfsDeviceBlockClass(makeDevice({ state: 'FAULTED' }))).toBe(
+ 'bg-red-500 dark:bg-red-500 hover:bg-red-400',
+ );
+ });
+
+ // ---- L7 second OR arm: UNAVAIL → exact red block string -----------------
+ it('returns the exact red block class for UNAVAIL (second OR arm)', () => {
+ expect(getZfsDeviceBlockClass(makeDevice({ state: 'UNAVAIL' }))).toBe(
+ 'bg-red-500 dark:bg-red-500 hover:bg-red-400',
+ );
+ });
+
+ // ---- L7 third OR arm: OFFLINE → exact red block string ------------------
+ it('returns the exact red block class for OFFLINE (third OR arm)', () => {
+ expect(getZfsDeviceBlockClass(makeDevice({ state: 'OFFLINE' }))).toBe(
+ 'bg-red-500 dark:bg-red-500 hover:bg-red-400',
+ );
+ });
+
+ // ---- L10 default arm: unrecognized state → slate ------------------------
+ it('falls through to the slate default for an unrecognized state', () => {
+ // 'REMOVED' is listed in the ZFSDevice comment but NOT handled by the
+ // function → every conditional is false → final return.
+ expect(getZfsDeviceBlockClass(makeDevice({ state: 'REMOVED' }))).toBe(
+ 'bg-slate-400 hover:bg-slate-300',
+ );
+ // Any other arbitrary string also falls through.
+ expect(getZfsDeviceBlockClass(makeDevice({ state: 'SUSPENDED' }))).toBe(
+ 'bg-slate-400 hover:bg-slate-300',
+ );
+ });
+
+ // ---- L4 toUpperCase() normalization: lowercase/mixedcase states match ---
+ it('normalizes state via toUpperCase so lowercase and mixed-case forms match', () => {
+ // lowercase 'online' → 'ONLINE' → green (proves .toUpperCase() runs).
+ expect(getZfsDeviceBlockClass(makeDevice({ state: 'online' }))).toBe(
+ 'bg-green-500 dark:bg-green-500 hover:bg-green-400',
+ );
+ // mixed-case 'Degraded' → 'DEGRADED' → yellow.
+ expect(getZfsDeviceBlockClass(makeDevice({ state: 'Degraded' }))).toBe(
+ 'bg-yellow-500 dark:bg-yellow-500 hover:bg-yellow-400',
+ );
+ // lowercase 'faulted' → 'FAULTED' → red.
+ expect(getZfsDeviceBlockClass(makeDevice({ state: 'faulted' }))).toBe(
+ 'bg-red-500 dark:bg-red-500 hover:bg-red-400',
+ );
+ });
+
+ // ---- L4 optional-chain `state?.` arm: state undefined → slate default ---
+ it('exercises the state?. optional-chain when state is undefined and falls to slate', () => {
+ // ZFSDevice.state is typed as required string, so we must cast to bypass
+ // strict null checks. `state?.toUpperCase()` short-circuits to undefined
+ // → no conditional matches → default slate string.
+ const noState = { ...makeDevice(), state: undefined } as unknown as ZFSDevice;
+ expect(getZfsDeviceBlockClass(noState)).toBe('bg-slate-400 hover:bg-slate-300');
+ });
+
+ // ---- L4 defensive: state null → slate default ---------------------------
+ it('exercises the state?. optional-chain when state is null and falls to slate', () => {
+ // Same defensive optional-chain arm reached via null (the pre-push hook
+ // runs the real tsconfig, so the null value is injected through an
+ // `as unknown as` cast).
+ const nullState = { ...makeDevice(), state: null } as unknown as ZFSDevice;
+ expect(getZfsDeviceBlockClass(nullState)).toBe('bg-slate-400 hover:bg-slate-300');
+ });
+});
diff --git a/frontend-modern/src/utils/__tests__/agentProfileSuggestionPresentation.branchcov0712b.test.ts b/frontend-modern/src/utils/__tests__/agentProfileSuggestionPresentation.branchcov0712b.test.ts
new file mode 100644
index 0000000000..64e52b4c6a
--- /dev/null
+++ b/frontend-modern/src/utils/__tests__/agentProfileSuggestionPresentation.branchcov0712b.test.ts
@@ -0,0 +1,112 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ formatAgentProfileSuggestionValue,
+ getAgentProfileSuggestionRiskHints,
+} from '@/utils/agentProfileSuggestionPresentation';
+
+describe('formatAgentProfileSuggestionValue (branch coverage)', () => {
+ it('returns "unset" for the null arm of the nullish guard', () => {
+ expect(formatAgentProfileSuggestionValue(null)).toBe('unset');
+ });
+
+ it('returns the string verbatim for a non-empty string arm', () => {
+ expect(formatAgentProfileSuggestionValue('debug')).toBe('debug');
+ expect(formatAgentProfileSuggestionValue('k3s-agent')).toBe('k3s-agent');
+ });
+
+ it('serializes numbers through the typeof number arm', () => {
+ expect(formatAgentProfileSuggestionValue(0)).toBe('0');
+ expect(formatAgentProfileSuggestionValue(42)).toBe('42');
+ expect(formatAgentProfileSuggestionValue(-7)).toBe('-7');
+ expect(formatAgentProfileSuggestionValue(3.5)).toBe('3.5');
+ });
+
+ it('JSON-stringifies objects through the default arm', () => {
+ expect(formatAgentProfileSuggestionValue({ tag: 'prod', region: 'us-east' })).toBe(
+ '{"tag":"prod","region":"us-east"}',
+ );
+ });
+
+ it('JSON-stringifies arrays through the default arm', () => {
+ expect(formatAgentProfileSuggestionValue(['a', 'b'])).toBe('["a","b"]');
+ expect(formatAgentProfileSuggestionValue([])).toBe('[]');
+ });
+});
+
+describe('getAgentProfileSuggestionRiskHints (branch coverage)', () => {
+ it('pushes the docker-update-checks hint for the disable_docker_update_checks===true arm', () => {
+ expect(
+ getAgentProfileSuggestionRiskHints({ disable_docker_update_checks: true }),
+ ).toStrictEqual([
+ 'Docker update checks are disabled. Update visibility will be limited.',
+ ]);
+ });
+
+ it('pushes the host-monitoring hint for the enable_host===false arm', () => {
+ expect(getAgentProfileSuggestionRiskHints({ enable_host: false })).toStrictEqual([
+ 'Agent monitoring is disabled. Agent metrics and command execution will stop.',
+ ]);
+ });
+
+ it('pushes all five hints in source order when every risk flag is set', () => {
+ expect(
+ getAgentProfileSuggestionRiskHints({
+ disable_auto_update: true,
+ disable_docker_update_checks: true,
+ enable_host: false,
+ enable_docker: false,
+ disable_ceph: true,
+ }),
+ ).toStrictEqual([
+ 'Auto updates are disabled. Plan manual patching for agents.',
+ 'Docker update checks are disabled. Update visibility will be limited.',
+ 'Agent monitoring is disabled. Agent metrics and command execution will stop.',
+ 'Docker monitoring is disabled. Container metrics and update tracking will stop.',
+ 'Ceph monitoring is disabled. Cluster health checks will be skipped.',
+ ]);
+ });
+
+ it('returns an empty array for an empty config (all skip arms)', () => {
+ expect(getAgentProfileSuggestionRiskHints({})).toStrictEqual([]);
+ });
+
+ it('skips every flag when the config is empty of any matching keys', () => {
+ expect(
+ getAgentProfileSuggestionRiskHints({ unrelated_key: true, enable_docker: true }),
+ ).toStrictEqual([]);
+ });
+
+ it('does not treat a truthy-but-non-boolean disable_auto_update as === true', () => {
+ expect(
+ getAgentProfileSuggestionRiskHints({
+ disable_auto_update: 1,
+ disable_docker_update_checks: 'yes',
+ disable_ceph: 'true',
+ }),
+ ).toStrictEqual([]);
+ });
+
+ it('does not treat a falsy-but-non-boolean enable_host/enable_docker as === false', () => {
+ expect(
+ getAgentProfileSuggestionRiskHints({
+ enable_host: 0,
+ enable_docker: '',
+ }),
+ ).toStrictEqual([]);
+ });
+
+ it('only pushes hints for the flags that strictly match while skipping the rest', () => {
+ expect(
+ getAgentProfileSuggestionRiskHints({
+ disable_auto_update: 'true',
+ disable_ceph: true,
+ enable_docker: false,
+ enable_host: 'false',
+ }),
+ ).toStrictEqual([
+ 'Docker monitoring is disabled. Container metrics and update tracking will stop.',
+ 'Ceph monitoring is disabled. Cluster health checks will be skipped.',
+ ]);
+ });
+});
diff --git a/frontend-modern/src/utils/__tests__/alertConfigPresentation.branchcov0712b.test.ts b/frontend-modern/src/utils/__tests__/alertConfigPresentation.branchcov0712b.test.ts
new file mode 100644
index 0000000000..5a98ca2c67
--- /dev/null
+++ b/frontend-modern/src/utils/__tests__/alertConfigPresentation.branchcov0712b.test.ts
@@ -0,0 +1,109 @@
+import { describe, expect, it } from 'vitest';
+import {
+ ALERT_CONFIG_SUMMARY_GROUPING_PREFIX,
+ getAlertConfigSummaryEscalation,
+ getAlertConfigSummaryGrouping,
+} from '@/utils/alertConfigPresentation';
+
+// Branch-coverage companion to alertConfigPresentation.test.ts.
+// The sibling test only exercises getAlertConfigSummaryGrouping(10, true, false)
+// (the "by node" arm) and getAlertConfigSummaryEscalation(2) (the plural arm).
+// This file drives the remaining arms of every conditional in those two functions.
+//
+// Branches under test:
+// getAlertConfigSummaryGrouping:
+// - `byNode && 'node'` short-circuit (truthy -> 'node', falsy -> false)
+// - `byGuest && 'workload'` short-circuit (truthy -> 'workload', falsy -> false)
+// - `.filter(Boolean)` dropping the false entries
+// - `.join(' and ')` producing 0, 1, or 2 targets
+// - ternary `groupingTargets ? by-suffix : bare-window`
+// getAlertConfigSummaryEscalation:
+// - ternary `levelCount === 1 ? '' : 's'`
+
+const GROUPING_PREFIX = ALERT_CONFIG_SUMMARY_GROUPING_PREFIX;
+
+describe('alertConfigPresentation — branch coverage (branchcov2)', () => {
+ describe('getAlertConfigSummaryGrouping', () => {
+ it('emits the bare-window arm when neither flag is set (groupingTargets falsy)', () => {
+ // Drives both `&&` short-circuits to their falsy arm, leaves
+ // groupingTargets as '' after filter+join, and takes the ternary's
+ // falsy branch — omitting the " by ..." suffix entirely.
+ expect(getAlertConfigSummaryGrouping(0, false, false)).toBe(
+ `${GROUPING_PREFIX} 0 minute windows`,
+ );
+ expect(getAlertConfigSummaryGrouping(15, false, false)).toBe(
+ `${GROUPING_PREFIX} 15 minute windows`,
+ );
+ });
+
+ it('uses only "workload" when byNode is false and byGuest is true', () => {
+ // Exercises the byNode `&&` falsy arm and the byGuest `&&` truthy arm;
+ // groupingTargets is truthy so the "by workload" suffix branch is taken.
+ expect(getAlertConfigSummaryGrouping(5, false, true)).toBe(
+ `${GROUPING_PREFIX} 5 minute windows by workload`,
+ );
+ });
+
+ it('uses only "node" when byNode is true and byGuest is false', () => {
+ // Mirrors the sibling test's arm but with a different window value to
+ // confirm windowMinutes interpolation is independent of the flag logic.
+ expect(getAlertConfigSummaryGrouping(30, true, false)).toBe(
+ `${GROUPING_PREFIX} 30 minute windows by node`,
+ );
+ });
+
+ it('joins both targets with " and " when both flags are true', () => {
+ // The only path through which `.join(' and ')` produces a multi-target
+ // string: both `&&` expressions resolve to their string operands.
+ expect(getAlertConfigSummaryGrouping(10, true, true)).toBe(
+ `${GROUPING_PREFIX} 10 minute windows by node and workload`,
+ );
+ });
+
+ it('interpolates the exact numeric window value verbatim (no pluralization/coercion)', () => {
+ // Pins the `${windowMinutes}` slot so future refactors can't quietly
+ // round, clamp, or pluralize the window length.
+ expect(getAlertConfigSummaryGrouping(1, true, true)).toContain(
+ '1 minute windows by node and workload',
+ );
+ expect(getAlertConfigSummaryGrouping(120, false, false)).toContain(
+ '120 minute windows',
+ );
+ });
+ });
+
+ describe('getAlertConfigSummaryEscalation', () => {
+ it('uses the singular "level" form when exactly one level is configured', () => {
+ // The only input that takes the `levelCount === 1 ? ''` truthy arm
+ // (sibling test only covers the plural arm via levelCount=2).
+ expect(getAlertConfigSummaryEscalation(1)).toBe(
+ '• 1 escalation level configured',
+ );
+ });
+
+ it('uses the plural "levels" form for counts other than 1', () => {
+ // Drives the ternary's falsy arm across representative boundaries:
+ // zero, two, and a larger count.
+ expect(getAlertConfigSummaryEscalation(0)).toBe(
+ '• 0 escalation levels configured',
+ );
+ expect(getAlertConfigSummaryEscalation(2)).toBe(
+ '• 2 escalation levels configured',
+ );
+ expect(getAlertConfigSummaryEscalation(5)).toBe(
+ '• 5 escalation levels configured',
+ );
+ });
+
+ it('interpolates the count verbatim into the prefix bullet', () => {
+ // Confirms the template literal wiring: bullet, count, then the fixed
+ // trailing copy. Guards against accidental prefix changes.
+ expect(getAlertConfigSummaryEscalation(3)).toBe(
+ '• 3 escalation levels configured',
+ );
+ expect(getAlertConfigSummaryEscalation(1)).toMatch(
+ /^• 1 escalation level configured$/,
+ );
+ });
+ });
+});
diff --git a/frontend-modern/src/utils/__tests__/reportingPresentation.branchcov0712b.test.ts b/frontend-modern/src/utils/__tests__/reportingPresentation.branchcov0712b.test.ts
new file mode 100644
index 0000000000..d53ed083f9
--- /dev/null
+++ b/frontend-modern/src/utils/__tests__/reportingPresentation.branchcov0712b.test.ts
@@ -0,0 +1,106 @@
+import { describe, expect, it } from 'vitest';
+import {
+ getReportingInventoryExportErrorMessage,
+ getReportingInventoryExportSuccessMessage,
+ resolveReportingDownloadFilename,
+} from '@/utils/reportingPresentation';
+
+describe('getReportingInventoryExportSuccessMessage', () => {
+ it('returns the canonical VM inventory export success copy', () => {
+ expect(getReportingInventoryExportSuccessMessage()).toBe(
+ 'VM inventory export generated successfully',
+ );
+ });
+});
+
+describe('getReportingInventoryExportErrorMessage', () => {
+ it('returns the canonical VM inventory export error copy', () => {
+ expect(getReportingInventoryExportErrorMessage()).toBe(
+ 'Failed to generate VM inventory export',
+ );
+ });
+});
+
+describe('resolveReportingDownloadFilename', () => {
+ type ContentDisposition = Parameters<typeof resolveReportingDownloadFilename>[0];
+ const fallback = 'fallback-report.csv';
+
+ it('returns the fallback when content-disposition is null', () => {
+ expect(resolveReportingDownloadFilename(null, fallback)).toBe(fallback);
+ });
+
+ it('returns the fallback when content-disposition is not a string (defensive typeof guard)', () => {
+ expect(
+ resolveReportingDownloadFilename(
+ undefined as unknown as ContentDisposition,
+ fallback,
+ ),
+ ).toBe(fallback);
+ expect(
+ resolveReportingDownloadFilename(42 as unknown as ContentDisposition, fallback),
+ ).toBe(fallback);
+ });
+
+ it('returns the fallback when content-disposition is an empty string', () => {
+ expect(resolveReportingDownloadFilename('', fallback)).toBe(fallback);
+ });
+
+ it('returns the fallback when content-disposition is only whitespace', () => {
+ expect(resolveReportingDownloadFilename(' \t ', fallback)).toBe(fallback);
+ });
+
+ it('decodes RFC 5987 encoded filenames (decodeURIComponent success path)', () => {
+ expect(
+ resolveReportingDownloadFilename(
+ "attachment; filename*=UTF-8''fleet%20report%20march.csv",
+ fallback,
+ ),
+ ).toBe('fleet report march.csv');
+ });
+
+ it('prefers the RFC 5987 encoded filename over a quoted filename', () => {
+ expect(
+ resolveReportingDownloadFilename(
+ "attachment; filename=\"quoted.pdf\"; filename*=UTF-8''encoded%20report.csv",
+ fallback,
+ ),
+ ).toBe('encoded report.csv');
+ });
+
+ it('returns the raw encoded token when it cannot be URI-decoded (decodeRFC5987Value catch path)', () => {
+ // '%' is not a valid URI escape, so decodeURIComponent throws and the helper returns the original token.
+ expect(
+ resolveReportingDownloadFilename("attachment; filename*=UTF-8''%", fallback),
+ ).toBe('%');
+ });
+
+ it('returns the quoted filename when a quoted directive is present', () => {
+ expect(
+ resolveReportingDownloadFilename(
+ 'attachment; filename="canonical-report.pdf"',
+ fallback,
+ ),
+ ).toBe('canonical-report.pdf');
+ });
+
+ it('falls back to the plain (unquoted) filename when no quoted directive is present', () => {
+ expect(
+ resolveReportingDownloadFilename('attachment; filename=plain-report.csv', fallback),
+ ).toBe('plain-report.csv');
+ });
+
+ it('trims surrounding whitespace from the plain filename', () => {
+ expect(
+ resolveReportingDownloadFilename(
+ 'attachment; filename=plain-report.csv ; size=1234',
+ fallback,
+ ),
+ ).toBe('plain-report.csv');
+ });
+
+ it('returns the fallback when no filename directive is present at all', () => {
+ expect(resolveReportingDownloadFilename('attachment; size=1234', fallback)).toBe(
+ fallback,
+ );
+ });
+});
diff --git a/frontend-modern/src/utils/__tests__/resourceAssistantContextModel.branchcov0712b.test.ts b/frontend-modern/src/utils/__tests__/resourceAssistantContextModel.branchcov0712b.test.ts
new file mode 100644
index 0000000000..83c55dacba
--- /dev/null
+++ b/frontend-modern/src/utils/__tests__/resourceAssistantContextModel.branchcov0712b.test.ts
@@ -0,0 +1,292 @@
+import { describe, expect, it } from 'vitest';
+import {
+ buildResourceAssistantContextForTarget,
+ type ResourceAssistantContextTarget,
+} from '@/utils/resourceAssistantContextModel';
+import type { AIChatContext } from '@/stores/aiChat';
+import type {
+ ResourceDiscoveryReadiness,
+ ResourceDiscoveryTarget,
+} from '@/types/resource';
+
+// Minimal target factory matching the required fields of
+// `ResourceAssistantContextTarget`. Optional facets are layered in per-test to
+// drive specific branches of `buildResourceAssistantContextForTarget`.
+const makeTarget = (
+ overrides: Partial<ResourceAssistantContextTarget> = {},
+): ResourceAssistantContextTarget => ({
+ id: 'res-1',
+ name: 'res-1',
+ type: 'agent',
+ source: 'resource-detail-drawer',
+ ...overrides,
+});
+
+describe('buildResourceAssistantContextForTarget — branch coverage (branchcov2)', () => {
+ describe('displayName = target.name || target.id', () => {
+ it('uses target.name when it is a non-empty string', () => {
+ const context = buildResourceAssistantContextForTarget(
+ makeTarget({ id: 'id-7', name: 'web-prod-01' }),
+ );
+ expect(context.briefing?.title).toBe('web-prod-01');
+ expect(context.handoffResources?.[0]?.name).toBe('web-prod-01');
+ });
+
+ it('falls back to target.id when name is an empty string', () => {
+ const context = buildResourceAssistantContextForTarget(
+ makeTarget({ id: 'id-7', name: '' }),
+ );
+ expect(context.briefing?.title).toBe('id-7');
+ expect(context.handoffResources?.[0]?.name).toBe('id-7');
+ });
+
+ it('falls back to target.id when name is undefined', () => {
+ const context = buildResourceAssistantContextForTarget(
+ makeTarget({ id: 'id-9', name: undefined }),
+ );
+ expect(context.briefing?.title).toBe('id-9');
+ });
+ });
+
+ describe('subjectParts via compact() — type / status / technology routing', () => {
+ it('joins all three populated parts with " / "', () => {
+ const context = buildResourceAssistantContextForTarget(
+ makeTarget({ type: 'vm', status: 'online', technology: 'vmware' }),
+ );
+ expect(context.briefing?.subject).toBe('vm / online / vmware');
+ });
+
+ it('keeps only the parts that are present (technology dropped)', () => {
+ const context = buildResourceAssistantContextForTarget(
+ makeTarget({ type: 'agent', status: 'offline', technology: undefined }),
+ );
+ expect(context.briefing?.subject).toBe('agent / offline');
+ });
+
+ it('keeps only the type when status and technology are absent', () => {
+ const context = buildResourceAssistantContextForTarget(
+ makeTarget({ type: 'storage', status: undefined, technology: undefined }),
+ );
+ expect(context.briefing?.subject).toBe('storage');
+ });
+
+ it('drops whitespace-only and empty-string values so the subject collapses to empty', () => {
+ const context = buildResourceAssistantContextForTarget(
+ makeTarget({ type: ' ', status: '', technology: ' \t ' }),
+ );
+ expect(context.briefing?.subject).toBe('');
+ });
+ });
+
+ describe('statusLabel — readinessPresentation truthy vs null', () => {
+ it('appends the readiness statusLabel when a discoveryReadiness is present', () => {
+ // readiness present => readinessPresentation is non-null => concatenated arm.
+ const context = buildResourceAssistantContextForTarget(
+ makeTarget({
+ discoveryReadiness: { state: 'fresh' } satisfies ResourceDiscoveryReadiness,
+ }),
+ );
+ expect(context.briefing?.statusLabel).toBe(
+ 'Read-only context attached · Discovery fresh',
+ );
+ });
+
+ it('appends the unknown statusLabel when discoveryTarget exists but readiness is absent', () => {
+ // discoveryTarget truthy => Boolean(discoveryTarget) true => hasDiscoverySupport
+ // true => readinessPresentation is the "unknown" shape even without readiness.
+ const context = buildResourceAssistantContextForTarget(
+ makeTarget({
+ discoveryTarget: {
+ resourceType: 'vm',
+ agentId: 'agent-1',
+ resourceId: 'res-1',
+ } satisfies ResourceDiscoveryTarget,
+ }),
+ );
+ expect(context.briefing?.statusLabel).toBe(
+ 'Read-only context attached · Discovery unknown',
+ );
+ });
+
+ it('uses the plain statusLabel when neither readiness nor discoveryTarget are present', () => {
+ // readiness absent AND discoveryTarget absent => readinessPresentation null.
+ const context = buildResourceAssistantContextForTarget(makeTarget());
+ expect(context.briefing?.statusLabel).toBe('Read-only context attached');
+ });
+ });
+
+ describe('detailLines assembly — every conditional arm', () => {
+ it('includes the Primary identity line only when primaryIdentity is truthy and differs from id', () => {
+ // primaryIdentity && primaryIdentity !== target.id => truthy arm.
+ const context = buildResourceAssistantContextForTarget(
+ makeTarget({ id: 'r-1', primaryIdentity: 'web.example.com' }),
+ );
+ expect(context.briefing?.detailLines).toContain('Primary identity: web.example.com');
+ });
+
+ it('drops the Primary identity line when primaryIdentity equals id', () => {
+ // primaryIdentity truthy BUT primaryIdentity === target.id => '' falsy arm.
+ const context = buildResourceAssistantContextForTarget(
+ makeTarget({ id: 'r-1', primaryIdentity: 'r-1' }),
+ );
+ expect(context.briefing?.detailLines).toEqual(['Resource ID: r-1']);
+ });
+
+ it('drops the Primary identity line when primaryIdentity is absent', () => {
+ // primaryIdentity falsy => '' falsy arm.
+ const context = buildResourceAssistantContextForTarget(
+ makeTarget({ id: 'r-2', primaryIdentity: undefined }),
+ );
+ expect(context.briefing?.detailLines).toEqual(['Resource ID: r-2']);
+ });
+
+ it('includes the Parent line when parentName is truthy', () => {
+ const context = buildResourceAssistantContextForTarget(
+ makeTarget({ parentName: 'esxi-host-1' }),
+ );
+ expect(context.briefing?.detailLines).toContain('Parent: esxi-host-1');
+ // parentName also surfaces as the handoff node.
+ expect(context.handoffResources?.[0]?.node).toBe('esxi-host-1');
+ });
+
+ it('drops the Parent line and leaves node undefined when parentName is absent', () => {
+ const context = buildResourceAssistantContextForTarget(
+ makeTarget({ parentName: undefined }),
+ );
+ expect(context.briefing?.detailLines?.some((l) => l.startsWith('Parent:'))).toBe(false);
+ expect(context.handoffResources?.[0]?.node).toBeUndefined();
+ });
+
+ it('builds the Discovery line from discoveryTarget.resourceType:resourceId when present', () => {
+ const context = buildResourceAssistantContextForTarget(
+ makeTarget({
+ discoveryTarget: {
+ resourceType: 'system-container',
+ agentId: 'agent-2',
+ resourceId: 'ct-42',
+ } satisfies ResourceDiscoveryTarget,
+ }),
+ );
+ expect(context.briefing?.detailLines).toContain('Discovery: system-container:ct-42');
+ });
+
+ it('drops the Discovery line when discoveryTarget is absent', () => {
+ const context = buildResourceAssistantContextForTarget(
+ makeTarget({ discoveryTarget: null }),
+ );
+ expect(context.briefing?.detailLines?.some((l) => l.startsWith('Discovery:'))).toBe(false);
+ });
+
+ it('includes the readiness briefing line when discoveryReadiness is present', () => {
+ // readinessLine non-empty => included arm.
+ const context = buildResourceAssistantContextForTarget(
+ makeTarget({
+ discoveryReadiness: {
+ state: 'stale',
+ serviceName: 'Home Assistant',
+ factCount: 5,
+ ageSeconds: 120,
+ } satisfies ResourceDiscoveryReadiness,
+ }),
+ );
+ expect(context.briefing?.detailLines).toContain(
+ 'Discovery data: Discovery stale, service Home Assistant, 5 facts',
+ );
+ });
+
+ it('omits the readiness briefing line when discoveryReadiness is absent', () => {
+ // readinessLine === '' => compact drops it.
+ const context = buildResourceAssistantContextForTarget(
+ makeTarget({ discoveryReadiness: null }),
+ );
+ expect(context.briefing?.detailLines).toEqual(['Resource ID: res-1']);
+ });
+ });
+
+ describe('context + handoff shape', () => {
+ it('echoes status into context.resourceStatus when status is provided', () => {
+ const context = buildResourceAssistantContextForTarget(
+ makeTarget({ status: 'maintenance' }),
+ );
+ expect(context.context).toStrictEqual({
+ source: 'resource-detail-drawer',
+ resourceId: 'res-1',
+ resourceType: 'agent',
+ resourceStatus: 'maintenance',
+ });
+ });
+
+ it('leaves context.resourceStatus undefined when status is absent', () => {
+ const context = buildResourceAssistantContextForTarget(
+ makeTarget({ status: undefined }),
+ );
+ // Destructure to assert the literal key is absent (undefined), not omitted
+ // from the returned object via toStrictEqual semantics.
+ expect(context.context?.resourceStatus).toBeUndefined();
+ expect(context.context).toStrictEqual({
+ source: 'resource-detail-drawer',
+ resourceId: 'res-1',
+ resourceType: 'agent',
+ resourceStatus: undefined,
+ });
+ });
+ });
+
+ describe('full-shape maximal target', () => {
+ it('builds the complete AIChatContext when every optional facet is populated', () => {
+ const target = makeTarget({
+ id: 'vm-101',
+ name: 'web-prod-01',
+ type: 'vm',
+ source: 'resource-detail-drawer',
+ status: 'online',
+ technology: 'vmware',
+ parentName: 'esxi-host-1',
+ primaryIdentity: 'web-prod-01.example.com',
+ discoveryTarget: {
+ resourceType: 'vm',
+ agentId: 'agent-7',
+ resourceId: 'vm-101',
+ } satisfies ResourceDiscoveryTarget,
+ discoveryReadiness: {
+ state: 'stale',
+ serviceName: 'Home Assistant',
+ factCount: 5,
+ ageSeconds: 120,
+ } satisfies ResourceDiscoveryReadiness,
+ });
+
+ const expected: AIChatContext = {
+ targetType: 'resource',
+ targetId: 'vm-101',
+ context: {
+ source: 'resource-detail-drawer',
+ resourceId: 'vm-101',
+ resourceType: 'vm',
+ resourceStatus: 'online',
+ },
+ briefing: {
+ sourceLabel: 'Pulse resource context',
+ title: 'web-prod-01',
+ subject: 'vm / online / vmware',
+ statusLabel: 'Read-only context attached · Discovery stale',
+ detailLines: [
+ 'Resource ID: vm-101',
+ 'Primary identity: web-prod-01.example.com',
+ 'Parent: esxi-host-1',
+ 'Discovery: vm:vm-101',
+ 'Discovery data: Discovery stale, service Home Assistant, 5 facts',
+ ],
+ safetyNote: 'Approval required before any action.',
+ },
+ handoffResources: [
+ { id: 'vm-101', name: 'web-prod-01', type: 'vm', node: 'esxi-host-1' },
+ ],
+ handoffMetadata: { kind: 'resource_context' },
+ autonomousMode: false,
+ };
+
+ expect(buildResourceAssistantContextForTarget(target)).toStrictEqual(expected);
+ });
+ });
+});
diff --git a/frontend-modern/src/utils/__tests__/resourceCorrelationPresentation.branchcov0712b.test.ts b/frontend-modern/src/utils/__tests__/resourceCorrelationPresentation.branchcov0712b.test.ts
new file mode 100644
index 0000000000..0d641337e7
--- /dev/null
+++ b/frontend-modern/src/utils/__tests__/resourceCorrelationPresentation.branchcov0712b.test.ts
@@ -0,0 +1,320 @@
+import { describe, expect, it } from 'vitest';
+
+import type { ResourceCorrelation } from '@/types/aiIntelligence';
+import type { ResourceRelationship } from '@/types/resource';
+import {
+ formatResourceCorrelationSummary,
+ sortResourceCorrelations,
+ sortResourceRelationships,
+} from '@/utils/resourceCorrelationPresentation';
+
+// Branch-coverage companion to resourceCorrelationPresentation.branchcov.test.ts.
+// Focuses exclusively on the still-under-exercised branches of:
+// - parseGoDurationMs (private; reached via formatResourceCorrelationSummary
+// when `avg_delay` is a Go duration string)
+// - sortResourceCorrelations
+// - sortResourceRelationships
+const makeCorrelation = (
+ overrides: Partial<ResourceCorrelation> = {},
+): ResourceCorrelation => ({
+ source_id: 'storage-1',
+ source_name: 'Storage 1',
+ source_type: 'storage',
+ target_id: 'vm-42',
+ target_name: 'VM 42',
+ target_type: 'vm',
+ event_pattern: 'disk_full -> restart',
+ occurrences: 2,
+ avg_delay: 0,
+ confidence: NaN,
+ last_seen: '2026-03-18T12:00:00Z',
+ description: 'Disk pressure often precedes restarts',
+ ...overrides,
+});
+
+const makeRelationship = (
+ overrides: Partial<ResourceRelationship> = {},
+): ResourceRelationship => ({
+ sourceId: 'node:pve-1',
+ targetId: 'vm-42',
+ type: 'runs_on',
+ confidence: 0.98,
+ active: true,
+ discoverer: 'proxmox_adapter',
+ observedAt: '2026-03-18T12:00:00Z',
+ lastSeenAt: '2026-03-18T12:05:00Z',
+ ...overrides,
+});
+
+// parseGoDurationMs is a private (non-exported) function in the module. It is
+// reachable through formatResourceCorrelationSummary, which delegates to it
+// whenever `correlation.avg_delay` is a string rather than a number.
+describe('parseGoDurationMs (via formatResourceCorrelationSummary)', () => {
+ // Uses occurrences: 2 and confidence: NaN so the only varying summary part is
+ // the formatted delay, making assertions unambiguous.
+
+ it('returns null (omitting delay) for a whitespace-only string via the empty-normalized early return', () => {
+ expect(
+ formatResourceCorrelationSummary(makeCorrelation({ avg_delay: ' ' })),
+ ).toBe('2 occurrences');
+ });
+
+ it('trims surrounding whitespace before parsing', () => {
+ expect(
+ formatResourceCorrelationSummary(makeCorrelation({ avg_delay: ' 5s ' })),
+ ).toBe('2 occurrences · avg delay 5s');
+ });
+
+ it('parses the h (hour) unit', () => {
+ expect(
+ formatResourceCorrelationSummary(makeCorrelation({ avg_delay: '2h' })),
+ ).toBe('2 occurrences · avg delay 120m');
+ });
+
+ it('parses a fractional amount using the decimal part of the duration pattern', () => {
+ expect(
+ formatResourceCorrelationSummary(makeCorrelation({ avg_delay: '1.0s' })),
+ ).toBe('2 occurrences · avg delay 1s');
+ });
+
+ it('parses the us (microseconds) unit', () => {
+ expect(
+ formatResourceCorrelationSummary(makeCorrelation({ avg_delay: '2000us' })),
+ ).toBe('2 occurrences · avg delay 2ms');
+ });
+
+ it('parses the µs (unicode microseconds) unit', () => {
+ expect(
+ formatResourceCorrelationSummary(makeCorrelation({ avg_delay: '2000µs' })),
+ ).toBe('2 occurrences · avg delay 2ms');
+ });
+
+ it('parses the ns (nanoseconds) unit', () => {
+ expect(
+ formatResourceCorrelationSummary(
+ makeCorrelation({ avg_delay: '3000000ns' }),
+ ),
+ ).toBe('2 occurrences · avg delay 3ms');
+ });
+
+ it('accumulates multiple unit tokens in a single duration string', () => {
+ expect(
+ formatResourceCorrelationSummary(makeCorrelation({ avg_delay: '1h30m' })),
+ ).toBe('2 occurrences · avg delay 90m');
+ });
+
+ it('returns null when the matched amount is not finite (defensive continue branch)', () => {
+ // 400 nines overflow Number.parseFloat to Infinity, exercising the
+ // `if (!Number.isFinite(amount)) continue;` branch.
+ expect(
+ formatResourceCorrelationSummary(
+ makeCorrelation({ avg_delay: `${'9'.repeat(400)}s` }),
+ ),
+ ).toBe('2 occurrences');
+ });
+
+ it('returns null when the accumulated total overflows to Infinity', () => {
+ // A finite amount (1e300) multiplied by the hour factor overflows totalNs
+ // to Infinity, exercising the `!Number.isFinite(totalNs)` arm of the
+ // terminal guard.
+ expect(
+ formatResourceCorrelationSummary(
+ makeCorrelation({ avg_delay: `${'9'.repeat(300)}h` }),
+ ),
+ ).toBe('2 occurrences');
+ });
+
+ it('returns null when the parsed duration is zero (totalNs <= 0 guard)', () => {
+ expect(
+ formatResourceCorrelationSummary(makeCorrelation({ avg_delay: '0s' })),
+ ).toBe('2 occurrences');
+ });
+
+ it('returns null when no unit token matches at all (!matched guard)', () => {
+ expect(
+ formatResourceCorrelationSummary(makeCorrelation({ avg_delay: 'abc' })),
+ ).toBe('2 occurrences');
+ });
+
+ it('documents the current behaviour that an `ms` token is consumed as minutes', () => {
+ // The duration regex alternation is `h|m|s|ms|us|µs|ns`; because `m`
+ // precedes `ms`, the input `5ms` matches the `m` alternative first (as
+ // `5m`) and the trailing `s` is left unparsed. The result is therefore
+ // 5 minutes, not 5 milliseconds. This is reported as a suspected source
+ // bug; the assertion pins the actual current behaviour.
+ expect(
+ formatResourceCorrelationSummary(makeCorrelation({ avg_delay: '5ms' })),
+ ).toBe('2 occurrences · avg delay 5m');
+ });
+});
+
+describe('sortResourceCorrelations (branch coverage)', () => {
+ it('sorts by descending confidence, then descending last_seen, coalescing undefined/NaN confidence to 0', () => {
+ const sorted = sortResourceCorrelations([
+ makeCorrelation({
+ source_id: 'A-mid',
+ confidence: 0.9,
+ last_seen: '2026-06-01T00:00:00Z',
+ }),
+ makeCorrelation({
+ source_id: 'B-undef',
+ confidence: undefined as unknown as number,
+ last_seen: '2026-05-01T00:00:00Z',
+ }),
+ makeCorrelation({
+ source_id: 'C-nan-invalid-date',
+ confidence: NaN,
+ last_seen: 'garbage',
+ }),
+ makeCorrelation({
+ source_id: 'D-high-conf-newer',
+ confidence: 0.9,
+ last_seen: '2026-07-01T00:00:00Z',
+ }),
+ ]);
+
+ // Confidence tiers: 0.9 (A, D) > 0 (B undefined, C NaN).
+ // Within 0.9: D (2026-07) is newer than A (2026-06).
+ // Within 0: B has a finite date (2026-05) while C's date is invalid (-> 0).
+ expect(sorted.map((c) => c.source_id)).toEqual([
+ 'D-high-conf-newer',
+ 'A-mid',
+ 'B-undef',
+ 'C-nan-invalid-date',
+ ]);
+ });
+
+ it('treats both invalid last_seen dates as time zero, preserving input order on a full tie', () => {
+ const sorted = sortResourceCorrelations([
+ makeCorrelation({ source_id: 'first', confidence: 0.4, last_seen: 'nope' }),
+ makeCorrelation({
+ source_id: 'second',
+ confidence: 0.4,
+ last_seen: 'also-nope',
+ }),
+ ]);
+ expect(sorted.map((c) => c.source_id)).toEqual(['first', 'second']);
+ });
+
+ it('returns a new array instance (does not return the input reference)', () => {
+ const input: readonly ResourceCorrelation[] = [
+ makeCorrelation({ source_id: 'only', confidence: 0.1 }),
+ ];
+ const sorted = sortResourceCorrelations(input);
+ expect(sorted).not.toBe(input);
+ expect(sorted.map((c) => c.source_id)).toEqual(['only']);
+ });
+});
+
+describe('sortResourceRelationships (branch coverage)', () => {
+ it('keeps an already-active-first pair stable via the left.active truthy (-1) arm', () => {
+ // Input order is [active, inactive]; for a two-element array the comparator
+ // is invoked as (active, inactive), so left.active is truthy and the
+ // `left.active ? -1 : 1` expression evaluates the -1 branch.
+ const sorted = sortResourceRelationships([
+ makeRelationship({ sourceId: 'live', active: true, confidence: 0.1 }),
+ makeRelationship({ sourceId: 'sleeping', active: false, confidence: 1 }),
+ ]);
+ expect(sorted.map((r) => r.sourceId)).toEqual(['live', 'sleeping']);
+ });
+
+ it('treats an undefined active value as falsy, sorting it below a true-active relationship', () => {
+ const sorted = sortResourceRelationships([
+ makeRelationship({
+ sourceId: 'undefined-active',
+ active: undefined as unknown as boolean,
+ confidence: 1,
+ }),
+ makeRelationship({ sourceId: 'true-active', active: true, confidence: 0 }),
+ ]);
+ expect(sorted.map((r) => r.sourceId)).toEqual([
+ 'true-active',
+ 'undefined-active',
+ ]);
+ });
+
+ it('sorts active before inactive, then by confidence, then by observedAt fallback', () => {
+ const sorted = sortResourceRelationships([
+ makeRelationship({
+ sourceId: 'A-undef-conf',
+ active: true,
+ confidence: undefined as unknown as number,
+ lastSeenAt: '2026-06-01T00:00:00Z',
+ observedAt: '2026-06-01T00:00:00Z',
+ }),
+ makeRelationship({
+ sourceId: 'B-nan-conf-observed',
+ active: true,
+ confidence: NaN,
+ lastSeenAt: '',
+ observedAt: '2026-05-01T00:00:00Z',
+ }),
+ makeRelationship({
+ sourceId: 'C-high-conf-bad-date',
+ active: true,
+ confidence: 0.9,
+ lastSeenAt: 'garbage',
+ observedAt: 'garbage',
+ }),
+ makeRelationship({
+ sourceId: 'D-inactive',
+ active: false,
+ confidence: 1,
+ }),
+ ]);
+
+ // Active (A, B, C) before inactive (D).
+ // Among active: confidence tiers 0.9 (C) > 0 (A undefined, B NaN).
+ // A vs B tie at 0: A uses lastSeenAt 2026-06; B falls back to observedAt
+ // 2026-05. A is newer. C's date is invalid -> 0 but it already wins on
+ // confidence.
+ expect(sorted.map((r) => r.sourceId)).toEqual([
+ 'C-high-conf-bad-date',
+ 'A-undef-conf',
+ 'B-nan-conf-observed',
+ 'D-inactive',
+ ]);
+ });
+
+ it('falls back to observedAt and then to time zero across a three-way time tie-break', () => {
+ const sorted = sortResourceRelationships([
+ makeRelationship({
+ sourceId: 'no-times',
+ active: true,
+ confidence: 0.5,
+ lastSeenAt: '',
+ observedAt: '',
+ }),
+ makeRelationship({
+ sourceId: 'observed-only',
+ active: true,
+ confidence: 0.5,
+ lastSeenAt: '',
+ observedAt: '2026-04-01T00:00:00Z',
+ }),
+ makeRelationship({
+ sourceId: 'last-seen',
+ active: true,
+ confidence: 0.5,
+ lastSeenAt: '2026-05-01T00:00:00Z',
+ observedAt: '2020-01-01T00:00:00Z',
+ }),
+ ]);
+ // All active, all confidence 0.5 -> time tie-break, newest first.
+ // last-seen (2026-05) > observed-only (2026-04) > no-times (0).
+ expect(sorted.map((r) => r.sourceId)).toEqual([
+ 'last-seen',
+ 'observed-only',
+ 'no-times',
+ ]);
+ });
+
+ it('returns a new array instance (does not return the input reference)', () => {
+ const input: readonly ResourceRelationship[] = [
+ makeRelationship({ sourceId: 'only', active: true, confidence: 0.1 }),
+ ];
+ const sorted = sortResourceRelationships(input);
+ expect(sorted).not.toBe(input);
+ expect(sorted.map((r) => r.sourceId)).toEqual(['only']);
+ });
+});
diff --git a/frontend-modern/src/utils/__tests__/searchQuery.branchcov0712b.test.ts b/frontend-modern/src/utils/__tests__/searchQuery.branchcov0712b.test.ts
new file mode 100644
index 0000000000..dc73900ea8
--- /dev/null
+++ b/frontend-modern/src/utils/__tests__/searchQuery.branchcov0712b.test.ts
@@ -0,0 +1,541 @@
+import { describe, expect, it } from 'vitest';
+import { evaluateFilterStack, parseFilter, parseFilterStack } from '@/utils/searchQuery';
+import type { ComparisonOperator, FilterStack, MetricCondition, ParsedFilter } from '@/utils/searchQuery';
+import type { VM } from '@/types/api';
+
+/**
+ * Second branch-coverage companion to searchQuery.ts.
+ *
+ * Scope is limited to four named functions: `parseFilter`, `parseFilterStack`,
+ * `evaluateMetricCondition`, and `evaluateTextCondition`. The latter two are
+ * module-private (not exported) so they are driven through the exported
+ * `evaluateFilterStack`, exactly as the sibling `searchQuery.branchcov.test.ts`
+ * does. Helpers below mirror that file's fixture-builder style.
+ *
+ * Where the sibling file already exercised a branch with a single positive
+ * case, this file adds the *opposite* arm or a precise boundary so each
+ * conditional has a matched true/false pair. Branches that are genuinely
+ * unreachable from the public string API are documented in GLM_REPORT.md
+ * rather than forced with unsafe casts.
+ */
+
+// A plain-record base lets us `delete` keys to exercise the `'x' in guest`
+// false arms (a key set to `undefined` still satisfies `in`).
+const baseGuest = (): Record<string, unknown> => ({
+ id: 'vm-1',
+ vmid: 100,
+ name: 'test-vm',
+ node: 'node1',
+ instance: 'qemu',
+ status: 'running',
+ type: 'qemu',
+ cpu: 0.5, // 50%
+ cpus: 2,
+ memory: { usage: 1024, total: 2048, used: 1024, free: 1024 },
+ disk: { usage: 50, total: 100, used: 50, free: 50 },
+ networkIn: 100,
+ networkOut: 200,
+ diskRead: 300,
+ diskWrite: 400,
+ uptime: 3600,
+ template: false,
+ lastBackup: 0,
+ tags: ['production', 'web'],
+ lock: '',
+ lastSeen: '',
+});
+
+const makeGuest = (overrides: Record<string, unknown> = {}): VM =>
+ ({ ...baseGuest(), ...overrides }) as unknown as VM;
+
+/** Guest with the given keys removed entirely (so `'k' in guest` is false). */
+const guestWithout = (keys: string[], overrides: Record<string, unknown> = {}): VM => {
+ const g: Record<string, unknown> = { ...baseGuest(), ...overrides };
+ for (const k of keys) delete g[k];
+ return g as unknown as VM;
+};
+
+/** Build a single-filter stack from a raw ParsedFilter. */
+const single = (filter: ParsedFilter): FilterStack => ({ filters: [filter], operators: [] });
+
+const metric = (
+ field: MetricCondition['field'],
+ operator: ComparisonOperator,
+ value: number,
+): ParsedFilter => ({ type: 'metric', field, operator, value });
+
+const text = (field: string, value: string): ParsedFilter => ({ type: 'text', field, value });
+
+describe('parseFilter — both arms of every conditional', () => {
+ describe('metric regex arm (lines 78-95)', () => {
+ it('parses a tight metric term (no spaces) and lowercases the field', () => {
+ expect(parseFilter('CPU>80')).toStrictEqual({
+ type: 'metric',
+ field: 'cpu',
+ operator: '>',
+ value: 80,
+ });
+ });
+
+ it('parses the bare "=" operator distinctly from "=="', () => {
+ expect(parseFilter('disk=50')).toStrictEqual({
+ type: 'metric',
+ field: 'disk',
+ operator: '=',
+ value: 50,
+ });
+ expect(parseFilter('disk==50')).toStrictEqual({
+ type: 'metric',
+ field: 'disk',
+ operator: '==',
+ value: 50,
+ });
+ });
+
+ it('parses a decimal value and preserves the "<=" operator', () => {
+ expect(parseFilter('memory<=12.5')).toStrictEqual({
+ type: 'metric',
+ field: 'memory',
+ operator: '<=',
+ value: 12.5,
+ });
+ });
+
+ it('falls through to raw when the numeric tail is missing (operator only)', () => {
+ expect(parseFilter('cpu>')).toStrictEqual({ type: 'raw', rawText: 'cpu>' });
+ });
+
+ it('falls through to raw when the value is non-numeric', () => {
+ // The metric regex requires \d+(\.\d+)?; "high" fails it, and there is no
+ // colon, so the raw fallback is reached.
+ expect(parseFilter('cpu>high')).toStrictEqual({ type: 'raw', rawText: 'cpu>high' });
+ });
+ });
+
+ describe('text regex arm (lines 98-105)', () => {
+ it('trims whitespace around the value and lowercases the field', () => {
+ expect(parseFilter('Name: Prod ')).toStrictEqual({
+ type: 'text',
+ field: 'name',
+ value: 'Prod',
+ });
+ });
+
+ it('keeps a colon inside the value (greedy value capture)', () => {
+ expect(parseFilter('tags:key:value')).toStrictEqual({
+ type: 'text',
+ field: 'tags',
+ value: 'key:value',
+ });
+ });
+
+ it('returns raw (not text) when the value is empty after the colon', () => {
+ // `^(\w+)\s*:\s*(.+)$` requires at least one value char, so "name:" misses
+ // the text regex and lands in the raw fallback.
+ expect(parseFilter('name:')).toStrictEqual({ type: 'raw', rawText: 'name:' });
+ });
+
+ it('returns raw when the term is a lone colon (no word field)', () => {
+ expect(parseFilter(':value')).toStrictEqual({ type: 'raw', rawText: ':value' });
+ });
+ });
+
+ describe('raw fallback arm (lines 109-112)', () => {
+ it('preserves a multi-word raw term after trimming edges', () => {
+ expect(parseFilter(' hello world ')).toStrictEqual({
+ type: 'raw',
+ rawText: 'hello world',
+ });
+ });
+
+ it('returns an empty rawText for a whitespace-only term', () => {
+ expect(parseFilter('\t \t')).toStrictEqual({ type: 'raw', rawText: '' });
+ });
+ });
+});
+
+describe('parseFilterStack — both arms of every conditional', () => {
+ it('returns an empty stack for an empty string (the `!trimmed` early return)', () => {
+ expect(parseFilterStack('')).toStrictEqual({ filters: [], operators: [] });
+ });
+
+ it('returns an empty stack for a whitespace-only string (the `!trimmed` early return)', () => {
+ expect(parseFilterStack(' \t ')).toStrictEqual({ filters: [], operators: [] });
+ });
+
+ it('parses a single filter with no operators into a one-element stack', () => {
+ const result = parseFilterStack('cpu>80');
+ expect(result).toStrictEqual({
+ filters: [{ type: 'metric', field: 'cpu', operator: '>', value: 80 }],
+ operators: [],
+ });
+ });
+
+ it('threads each filter through parseFilter, mixing metric/text/raw kinds', () => {
+ const result = parseFilterStack('cpu>80 AND name:prod OR loose-term');
+ expect(result.filters).toStrictEqual([
+ { type: 'metric', field: 'cpu', operator: '>', value: 80 },
+ { type: 'text', field: 'name', value: 'prod' },
+ { type: 'raw', rawText: 'loose-term' },
+ ]);
+ expect(result.operators).toStrictEqual(['AND', 'OR']);
+ });
+
+ it('normalizes a fully lowercase "and" operator to AND', () => {
+ expect(parseFilterStack('cpu>80 and memory>10').operators).toStrictEqual(['AND']);
+ });
+
+ it('normalizes a fully lowercase "or" operator to OR', () => {
+ expect(parseFilterStack('cpu>80 or memory>10').operators).toStrictEqual(['OR']);
+ });
+
+ it('keeps operator ordering stable across four filters', () => {
+ const result = parseFilterStack('a:1 OR b:2 AND c:3 OR d:4');
+ expect(result.filters).toHaveLength(4);
+ expect(result.operators).toStrictEqual(['OR', 'AND', 'OR']);
+ });
+
+ it('treats a trailing operator token as part of the last filter (no split)', () => {
+ // No whitespace follows the trailing "AND", so the split regex does not fire
+ // there; the whole string survives as one part and parseFilter parses it as
+ // a text condition whose value includes the trailing "AND".
+ const result = parseFilterStack('a:1 AND');
+ expect(result.filters).toStrictEqual([{ type: 'text', field: 'a', value: '1 AND' }]);
+ expect(result.operators).toStrictEqual([]);
+ });
+});
+
+describe('evaluateMetricCondition — field-switch arms (via evaluateFilterStack)', () => {
+ describe('cpu field', () => {
+ it('multiplies the decimal by 100; `>` true above and false at the threshold', () => {
+ // 0.9 -> 90 ; 90 > 50 true
+ expect(evaluateFilterStack(makeGuest({ cpu: 0.9 }), single(metric('cpu', '>', 50)))).toBe(true);
+ // 0.4 -> 40 ; 40 > 50 false
+ expect(evaluateFilterStack(makeGuest({ cpu: 0.4 }), single(metric('cpu', '>', 50)))).toBe(false);
+ });
+ });
+
+ describe('memory field', () => {
+ it('reads usage when present and compares with `<`', () => {
+ expect(
+ evaluateFilterStack(
+ makeGuest({ memory: { usage: 900, total: 1000, used: 900, free: 100 } }),
+ single(metric('memory', '<', 1000)),
+ ),
+ ).toBe(true);
+ });
+ });
+
+ describe('disk field', () => {
+ it('reads usage when present (>= true at threshold)', () => {
+ expect(
+ evaluateFilterStack(
+ makeGuest({ disk: { usage: 50, total: 100, used: 50, free: 50 } }),
+ single(metric('disk', '>=', 50)),
+ ),
+ ).toBe(true);
+ });
+
+ it('returns 0 when disk is null (falsy short-circuit)', () => {
+ // null disk -> 0 ; 0 <= 0 true
+ expect(
+ evaluateFilterStack(
+ makeGuest({ disk: null as unknown as VM['disk'] }),
+ single(metric('disk', '<=', 0)),
+ ),
+ ).toBe(true);
+ });
+ });
+
+ describe('uptime field', () => {
+ it('uses uptime when running and truthy (> true)', () => {
+ expect(
+ evaluateFilterStack(
+ makeGuest({ status: 'running', uptime: 7200 }),
+ single(metric('uptime', '>', 3600)),
+ ),
+ ).toBe(true);
+ });
+
+ it('coerces a falsy-but-present uptime (0) to 0 via the `|| 0` arm when running', () => {
+ // status running + 'uptime' in guest (value 0) -> guest.uptime || 0 -> 0.
+ // Pin the value to exactly 0: >= 0 true, > 0 false.
+ expect(
+ evaluateFilterStack(
+ makeGuest({ status: 'running', uptime: 0 }),
+ single(metric('uptime', '>=', 0)),
+ ),
+ ).toBe(true);
+ expect(
+ evaluateFilterStack(
+ makeGuest({ status: 'running', uptime: 0 }),
+ single(metric('uptime', '>', 0)),
+ ),
+ ).toBe(false);
+ });
+
+ it('returns 0 when status is not running (the `: 0` ternary arm)', () => {
+ expect(
+ evaluateFilterStack(
+ makeGuest({ status: 'stopped', uptime: 9999 }),
+ single(metric('uptime', '>', 1)),
+ ),
+ ).toBe(false);
+ });
+
+ it('returns 0 when running but the uptime key is absent', () => {
+ expect(
+ evaluateFilterStack(guestWithout(['uptime']), single(metric('uptime', '>', 1))),
+ ).toBe(false);
+ });
+ });
+
+ describe('default field arm (switch-unlisted metric field)', () => {
+ it('reads a numeric present field and compares with `>`', () => {
+ expect(
+ evaluateFilterStack(makeGuest({ networkOut: 200 }), single(metric('networkOut', '>', 150))),
+ ).toBe(true);
+ expect(
+ evaluateFilterStack(makeGuest({ networkOut: 200 }), single(metric('networkOut', '>', 999))),
+ ).toBe(false);
+ });
+
+ it('coerces a numeric-looking string field via Number() || 0', () => {
+ // "300" -> 300 ; 300 >= 300 true
+ expect(
+ evaluateFilterStack(
+ makeGuest({ diskRead: '300' as unknown as number }),
+ single(metric('diskRead', '>=', 300)),
+ ),
+ ).toBe(true);
+ });
+
+ it('returns false when the field exists but its value is undefined', () => {
+ expect(
+ evaluateFilterStack(makeGuest({ networkIn: undefined }), single(metric('networkIn', '>', 0))),
+ ).toBe(false);
+ });
+
+ it('returns false when the field is absent from the guest', () => {
+ expect(
+ evaluateFilterStack(guestWithout(['networkOut']), single(metric('networkOut', '>', 0))),
+ ).toBe(false);
+ });
+ });
+
+ describe('operator switch arms (>=, <=, >, <)', () => {
+ // Columns: cpuPct, op, threshold, expected — value is cpuPct (cpu stored as
+ // cpuPct/100, the function multiplies back by 100).
+ it.each([
+ [50, '>=', 50, true],
+ [49, '>=', 50, false],
+ [50, '<=', 50, true],
+ [51, '<=', 50, false],
+ [51, '>', 50, true],
+ [50, '>', 50, false],
+ [49, '<', 50, true],
+ [50, '<', 50, false],
+ ] as const)('cpu %i%% %s %i yields %s', (cpuPct, op, threshold, expected) => {
+ expect(
+ evaluateFilterStack(makeGuest({ cpu: cpuPct / 100 }), single(metric('cpu', op, threshold))),
+ ).toBe(expected);
+ });
+ });
+
+ describe('`=` / `==` epsilon arm (Math.abs(v - cond.value) < 0.01)', () => {
+ it('matches within the 0.01 window for "="', () => {
+ // 50.0 vs 50.005 -> diff 0.005 -> true
+ expect(
+ evaluateFilterStack(makeGuest({ cpu: 0.5 }), single(metric('cpu', '=', 50.005))),
+ ).toBe(true);
+ });
+
+ it('does not match outside the 0.01 window for "="', () => {
+ // 50.0 vs 50.02 -> diff 0.02 -> false
+ expect(
+ evaluateFilterStack(makeGuest({ cpu: 0.5 }), single(metric('cpu', '=', 50.02))),
+ ).toBe(false);
+ });
+
+ it('matches exactly with "==" at the same value', () => {
+ expect(
+ evaluateFilterStack(makeGuest({ cpu: 0.5 }), single(metric('cpu', '==', 50))),
+ ).toBe(true);
+ });
+
+ it('does not match with "==" far from the value', () => {
+ expect(
+ evaluateFilterStack(makeGuest({ cpu: 0.5 }), single(metric('cpu', '==', 51))),
+ ).toBe(false);
+ });
+ });
+
+ describe('operator default arm', () => {
+ it('returns false for an unrecognized operator', () => {
+ const filter = {
+ type: 'metric',
+ field: 'cpu',
+ operator: '!=' as unknown as ComparisonOperator,
+ value: 50,
+ } as ParsedFilter;
+ expect(evaluateFilterStack(makeGuest({ cpu: 0.5 }), single(filter))).toBe(false);
+ });
+ });
+});
+
+describe('evaluateTextCondition — field-switch arms (via evaluateFilterStack)', () => {
+ describe('name field', () => {
+ it('matches case-insensitively and rejects a non-substring', () => {
+ expect(evaluateFilterStack(makeGuest({ name: 'Prod-Web' }), single(text('name', 'prod')))).toBe(
+ true,
+ );
+ expect(evaluateFilterStack(makeGuest({ name: 'Prod-Web' }), single(text('name', 'zzz')))).toBe(
+ false,
+ );
+ });
+
+ it('returns false when name is the empty string (falsy)', () => {
+ expect(evaluateFilterStack(makeGuest({ name: '' }), single(text('name', 'x')))).toBe(false);
+ });
+ });
+
+ describe('node field', () => {
+ it('matches a substring and rejects a miss', () => {
+ expect(
+ evaluateFilterStack(makeGuest({ node: 'cluster-a' }), single(text('node', 'cluster'))),
+ ).toBe(true);
+ expect(
+ evaluateFilterStack(makeGuest({ node: 'cluster-a' }), single(text('node', 'zone'))),
+ ).toBe(false);
+ });
+ });
+
+ describe('vmid field', () => {
+ it('matches a numeric substring of vmid', () => {
+ expect(evaluateFilterStack(makeGuest({ vmid: 100 }), single(text('vmid', '00')))).toBe(true);
+ });
+
+ it('returns false when vmid is falsy (0)', () => {
+ expect(evaluateFilterStack(makeGuest({ vmid: 0 }), single(text('vmid', '0')))).toBe(false);
+ });
+ });
+
+ describe('tags field', () => {
+ it('matches when the second comma-separated search tag hits (OR over search tags)', () => {
+ expect(
+ evaluateFilterStack(
+ makeGuest({ tags: ['production', 'web'] }),
+ single(text('tags', 'staging,web')),
+ ),
+ ).toBe(true);
+ });
+
+ it('returns false when no search tag matches any guest tag', () => {
+ expect(
+ evaluateFilterStack(
+ makeGuest({ tags: ['production', 'web'] }),
+ single(text('tags', 'staging,db')),
+ ),
+ ).toBe(false);
+ });
+
+ it('matches case-insensitively across array tags and search value', () => {
+ expect(
+ evaluateFilterStack(
+ makeGuest({ tags: ['Production'] }),
+ single(text('tags', 'PROD')),
+ ),
+ ).toBe(true);
+ });
+
+ it('splits a comma-separated tags STRING and matches a segment', () => {
+ expect(
+ evaluateFilterStack(
+ makeGuest({ tags: 'production,web,api' }),
+ single(text('tags', 'api')),
+ ),
+ ).toBe(true);
+ });
+
+ it('returns false when the tags string contains only empty segments', () => {
+ expect(
+ evaluateFilterStack(
+ makeGuest({ tags: ',,' }),
+ single(text('tags', 'production')),
+ ),
+ ).toBe(false);
+ });
+
+ it('returns false when tags is a non-array, non-string value', () => {
+ expect(
+ evaluateFilterStack(
+ makeGuest({ tags: 42 as unknown as string[] }),
+ single(text('tags', 'x')),
+ ),
+ ).toBe(false);
+ });
+
+ it('returns false when an array holds only non-string entries', () => {
+ expect(
+ evaluateFilterStack(
+ makeGuest({ tags: [1, 2] as unknown as string[] }),
+ single(text('tags', 'x')),
+ ),
+ ).toBe(false);
+ });
+
+ it('returns false when the tags key is absent', () => {
+ expect(evaluateFilterStack(guestWithout(['tags']), single(text('tags', 'x')))).toBe(false);
+ });
+ });
+
+ describe('default field arm (non-name/node/vmid/tags)', () => {
+ it('matches a string field via case-insensitive substring', () => {
+ expect(evaluateFilterStack(makeGuest({ type: 'qemu' }), single(text('type', 'QE')))).toBe(true);
+ });
+
+ it('matches a numeric field via toString substring', () => {
+ expect(evaluateFilterStack(makeGuest({ cpus: 2 }), single(text('cpus', '2')))).toBe(true);
+ });
+
+ it('boolean arm: a truthy `true` field matches the exact string "true"', () => {
+ expect(
+ evaluateFilterStack(makeGuest({ template: true }), single(text('template', 'true'))),
+ ).toBe(true);
+ });
+
+ it('boolean arm uses EXACT equality (not substring): searching "tru" on true misses', () => {
+ expect(
+ evaluateFilterStack(makeGuest({ template: true }), single(text('template', 'tru'))),
+ ).toBe(false);
+ });
+
+ // NOTE / suspected source bug documented in GLM_REPORT.md: a boolean `false`
+ // field is filtered out by the outer `if (fieldValue)` truthiness guard and
+ // can NEVER match, even when searching "false". This test pins the actual
+ // (buggy) behavior so a future fix is caught.
+ it('boolean arm: a falsy `false` field never matches because the outer truthiness guard skips it', () => {
+ expect(
+ evaluateFilterStack(makeGuest({ template: false }), single(text('template', 'false'))),
+ ).toBe(false);
+ });
+
+ it('returns false for an object field value (no string/number/boolean arm)', () => {
+ expect(
+ evaluateFilterStack(
+ makeGuest({ cpus: { n: 1 } as unknown as number }),
+ single(text('cpus', 'x')),
+ ),
+ ).toBe(false);
+ });
+
+ it('returns false when the default field is absent from the guest', () => {
+ expect(evaluateFilterStack(guestWithout(['lock']), single(text('lock', 'x')))).toBe(false);
+ });
+
+ it('returns false when the default field value is falsy', () => {
+ // 'lock' is '' on the base guest -> falsy -> the inner block is skipped.
+ expect(evaluateFilterStack(makeGuest(), single(text('lock', 'x')))).toBe(false);
+ });
+ });
+});
diff --git a/frontend-modern/src/utils/__tests__/storageSources.branchcov0712b.test.ts b/frontend-modern/src/utils/__tests__/storageSources.branchcov0712b.test.ts
new file mode 100644
index 0000000000..b756d431a4
--- /dev/null
+++ b/frontend-modern/src/utils/__tests__/storageSources.branchcov0712b.test.ts
@@ -0,0 +1,264 @@
+import { describe, expect, it } from 'vitest';
+import type { Storage } from '@/types/api';
+import {
+ getStorageSourceOption,
+ resolveStorageSourceKey,
+ type StorageSourceOption,
+} from '@/utils/storageSources';
+
+// Mirrors the factory pattern used by the sibling storageSources.test.ts suite
+// so this branch-coverage file stays consistent with existing conventions.
+const makeStorage = (overrides: Partial<Pick<Storage, 'platform' | 'type'>>): Storage =>
+ ({
+ id: 'storage-1',
+ name: 'storage-1',
+ node: 'node-1',
+ instance: 'instance-1',
+ type: 'dir',
+ status: 'active',
+ total: 100,
+ used: 10,
+ free: 90,
+ usage: 10,
+ content: 'images',
+ shared: false,
+ enabled: true,
+ active: true,
+ ...overrides,
+ }) as Storage;
+
+describe('storageSources.branchcov2', () => {
+ describe('resolveStorageSourceKey — platform-wins block', () => {
+ it.each([
+ ['truenas', 'zfs'],
+ ['vmware-vsphere', 'vsan'],
+ ['proxmox-pbs', 'lvm'],
+ ['proxmox-pmg', 'dir'],
+ ['kubernetes', 'csi'],
+ ['microsoft-hyperv', 'smb'],
+ ])(
+ 'returns the canonical platform %s even when on-disk type %s would resolve elsewhere',
+ (platform, type) => {
+ expect(resolveStorageSourceKey(makeStorage({ platform, type }))).toBe(platform);
+ },
+ );
+
+ it.each([
+ ['vmware', 'vmware-vsphere', 'vmfs'],
+ ['hyper-v', 'microsoft-hyperv', 'smb'],
+ ['pbs', 'proxmox-pbs', 'zfs'],
+ ['pmg', 'proxmox-pmg', 'dir'],
+ ['k8s', 'kubernetes', 'csi'],
+ ])(
+ 'normalizes the raw platform alias %s into the wins-list key %s before resolving (type=%s ignored)',
+ (rawPlatform, expected, type) => {
+ expect(resolveStorageSourceKey(makeStorage({ platform: rawPlatform, type }))).toBe(expected);
+ },
+ );
+
+ it('prefers a winning platform tag over a type that would itself classify as kubernetes', () => {
+ // platform=kubernetes wins before the type-based kubernetes classifier runs.
+ expect(resolveStorageSourceKey(makeStorage({ platform: 'kubernetes', type: 'csi-driver' })))
+ .toBe('kubernetes');
+ });
+ });
+
+ describe('resolveStorageSourceKey — platform fallthrough', () => {
+ it.each([
+ ['proxmox-pve', 'ceph'],
+ ['agent', 'dir'],
+ ['docker', 'dir'],
+ ['ceph', 'dir'],
+ ])(
+ 'ignores non-winning platform tag %s and resolves by on-disk type %s',
+ (platform, type) => {
+ // 'dir' -> proxmox-pve; 'ceph' -> ceph
+ const expected = type === 'ceph' ? 'ceph' : 'proxmox-pve';
+ expect(resolveStorageSourceKey(makeStorage({ platform, type }))).toBe(expected);
+ },
+ );
+
+ it('coerces an undefined platform to empty string and still resolves by type', () => {
+ const storage = { ...makeStorage({}), platform: undefined } as Storage;
+ delete storage.platform;
+ // type 'dir' -> proxmox-pve
+ expect(resolveStorageSourceKey(storage)).toBe('proxmox-pve');
+ });
+ });
+
+ describe('resolveStorageSourceKey — type-based canonical recognition', () => {
+ it.each([
+ ['proxmox-pbs'],
+ ['ceph'],
+ ['kubernetes'],
+ ['proxmox-pmg'],
+ ])('returns the recognized canonical type %s directly when platform is empty', (type) => {
+ expect(resolveStorageSourceKey(makeStorage({ platform: '', type }))).toBe(type);
+ });
+
+ it.each([['cephfs'], ['rbd']])(
+ 'collapses the ceph family member %s to ceph via CEPH_TYPES',
+ (type) => {
+ expect(resolveStorageSourceKey(makeStorage({ platform: '', type }))).toBe('ceph');
+ },
+ );
+ });
+
+ describe('resolveStorageSourceKey — proxmox-pve fallback bucket', () => {
+ it.each([
+ ['dir'],
+ ['nfs'],
+ ['cifs'],
+ ['lvm'],
+ ['lvmthin'],
+ ['zfspool'],
+ ['zfs'],
+ ['iscsi'],
+ ['glusterfs'],
+ ['btrfs'],
+ ])('classifies proxmox storage type %s as proxmox-pve', (type) => {
+ expect(resolveStorageSourceKey(makeStorage({ platform: '', type }))).toBe('proxmox-pve');
+ });
+
+ it.each([[''], ['storage']])(
+ 'falls back to proxmox-pve for the generic type bucket %s',
+ (type) => {
+ expect(resolveStorageSourceKey(makeStorage({ platform: '', type }))).toBe('proxmox-pve');
+ },
+ );
+ });
+
+ describe('resolveStorageSourceKey — kubernetes substring classifier', () => {
+ it.each([
+ ['csi-driver', 'csi'],
+ ['my-k8s-pv', 'k8s'],
+ ['kubernetes-csi', 'kubernetes'],
+ ['foo-csi-bar', 'csi'],
+ ])('classifies type %s as kubernetes via the %s substring arm', (type) => {
+ expect(resolveStorageSourceKey(makeStorage({ platform: '', type }))).toBe('kubernetes');
+ });
+
+ it('does not classify a type containing none of k8s/kubernetes/csi and returns it slugified', () => {
+ expect(resolveStorageSourceKey(makeStorage({ platform: '', type: 'random-thing' }))).toBe(
+ 'random-thing',
+ );
+ });
+ });
+
+ describe('resolveStorageSourceKey — final fallback', () => {
+ it('returns proxmox-pve when neither platform nor type resolve to anything', () => {
+ expect(resolveStorageSourceKey(makeStorage({ platform: '', type: '' }))).toBe('proxmox-pve');
+ });
+
+ it('coerces a missing on-disk type field to empty and falls back to proxmox-pve', () => {
+ // Defensive branch: normalizeStorageSourceKey receives undefined (the
+ // `type` field is required on `Storage`, so we cast a malformed payload
+ // through `unknown` to exercise the `value || ''` coercion).
+ const storage = { ...makeStorage({ platform: '' }), type: undefined } as unknown as Storage;
+ expect(resolveStorageSourceKey(storage)).toBe('proxmox-pve');
+ });
+ });
+
+ describe('getStorageSourceOption — all branch', () => {
+ it('returns the canonical all option for the normalized all token', () => {
+ expect(getStorageSourceOption('all')).toStrictEqual({
+ key: 'all',
+ label: 'All sources',
+ tone: 'slate',
+ });
+ });
+
+ it('normalizes whitespace/case variants of the all token to the canonical all option', () => {
+ expect(getStorageSourceOption(' ALL ')).toStrictEqual({
+ key: 'all',
+ label: 'All sources',
+ tone: 'slate',
+ });
+ });
+ });
+
+ describe('getStorageSourceOption — label ternary', () => {
+ it('uses the literal "Ceph" label for the ceph ternary arm', () => {
+ expect(getStorageSourceOption('ceph')).toStrictEqual({
+ key: 'ceph',
+ label: 'Ceph',
+ tone: 'teal',
+ });
+ });
+
+ it('uses getSourcePlatformLabel for the non-ceph ternary arm (microsoft-hyperv)', () => {
+ expect(getStorageSourceOption('microsoft-hyperv')).toStrictEqual({
+ key: 'microsoft-hyperv',
+ label: 'Hyper-V',
+ tone: 'slate',
+ });
+ });
+
+ it.each([
+ ['proxmox-pve', 'PVE', 'orange'],
+ ['proxmox-pbs', 'PBS', 'indigo'],
+ ['proxmox-pmg', 'PMG', 'rose'],
+ ['truenas', 'TrueNAS', 'blue'],
+ ['kubernetes', 'K8s', 'cyan'],
+ ])('returns the platform label and mapped tone for canonical key %s', (key, label, tone) => {
+ expect(getStorageSourceOption(key)).toStrictEqual({ key, label, tone });
+ });
+ });
+
+ describe('getStorageSourceOption — tone fallback', () => {
+ it('falls back to the slate tone for vmware-vsphere (not in the tone map)', () => {
+ expect(getStorageSourceOption('vmware-vsphere')).toStrictEqual({
+ key: 'vmware-vsphere',
+ label: 'vSphere',
+ tone: 'slate',
+ });
+ });
+
+ it('falls back to the slate tone and a title-cased label for an unknown key', () => {
+ expect(getStorageSourceOption('foo-bar')).toStrictEqual({
+ key: 'foo-bar',
+ label: 'Foo Bar',
+ tone: 'slate',
+ });
+ });
+
+ it('returns the Unknown label and slate tone for an empty key', () => {
+ expect(getStorageSourceOption('')).toStrictEqual({
+ key: '',
+ label: 'Unknown',
+ tone: 'slate',
+ });
+ });
+
+ it('normalizes null/undefined to an empty key with the Unknown label', () => {
+ expect(getStorageSourceOption(null)).toStrictEqual({
+ key: '',
+ label: 'Unknown',
+ tone: 'slate',
+ });
+ expect(getStorageSourceOption(undefined)).toStrictEqual({
+ key: '',
+ label: 'Unknown',
+ tone: 'slate',
+ });
+ });
+ });
+
+ describe('getStorageSourceOption — return shape contract', () => {
+ it('every StorageSourceTone declared in the tone map is reachable and typed correctly', () => {
+ const keys: string[] = [
+ 'proxmox-pve',
+ 'proxmox-pbs',
+ 'proxmox-pmg',
+ 'ceph',
+ 'truenas',
+ 'kubernetes',
+ ];
+ const tones = keys.map((key) => getStorageSourceOption(key).tone);
+ expect(tones).toStrictEqual(['orange', 'indigo', 'rose', 'teal', 'blue', 'cyan']);
+ // Type-level check: every option satisfies the StorageSourceOption interface.
+ const option = getStorageSourceOption('proxmox-pve') as StorageSourceOption;
+ expect(option.tone).toBe('orange');
+ });
+ });
+});