Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

test(frontend): branch-coverage tests for 19 more pure frontend modules

rcourtmanc0bbed1c592a
diff --git a/frontend-modern/src/components/AI/Chat/__tests__/activeTurnStatus.branchcov.test.ts b/frontend-modern/src/components/AI/Chat/__tests__/activeTurnStatus.branchcov.test.ts
new file mode 100644
index 0000000000..461a196e91
--- /dev/null
+++ b/frontend-modern/src/components/AI/Chat/__tests__/activeTurnStatus.branchcov.test.ts
@@ -0,0 +1,582 @@
+import { describe, expect, it } from 'vitest';
+import { formatAssistantWorkflowStatus, getAssistantActiveTurnStatus } from '../activeTurnStatus';
+import type { ChatMessage, StreamDisplayEvent } from '../types';
+
+// Fixture builders — mirror the conventions of the sibling activeTurnStatus.test.ts.
+const assistantMessage = (overrides: Partial<ChatMessage> = {}): ChatMessage => ({
+ id: 'assistant-1',
+ role: 'assistant',
+ content: '',
+ timestamp: new Date(1_000),
+ ...overrides,
+});
+
+const activeTurn = (overrides: Partial<ChatMessage> = {}, now?: number) =>
+ getAssistantActiveTurnStatus([assistantMessage(overrides)], true, now);
+
+const readToolInput = (command: string): string =>
+ JSON.stringify({ action: 'exec', command, target_host: 'current_resource' });
+
+// ---------------------------------------------------------------------------
+// formatPendingToolStatus — reachable via getAssistantActiveTurnStatus
+// (pendingTools state, stream pending_tool events, and the no-pendingTool guard)
+// ---------------------------------------------------------------------------
+
+describe('formatPendingToolStatus branch coverage', () => {
+ it('renders a waiting tool from a command preview ("Waiting on …")', () => {
+ expect(
+ activeTurn({
+ pendingTools: [
+ {
+ id: 'tool-1',
+ name: 'pulse_read',
+ input: readToolInput('ls /dev | wc -l'),
+ status: 'waiting',
+ startedAt: 500,
+ },
+ ],
+ }),
+ ).toEqual({
+ type: 'tool',
+ text: 'Waiting on $ ls /dev | wc -l',
+ startedAt: 500,
+ });
+ });
+
+ it('renders a waiting tool from the label fallback when no activity is parseable', () => {
+ expect(
+ activeTurn({
+ pendingTools: [
+ { id: 'tool-1', name: 'pulse_get_nodes', input: '{}', status: 'waiting' },
+ ],
+ }),
+ ).toEqual({
+ type: 'tool',
+ text: 'Waiting on get nodes',
+ });
+ });
+
+ it('ignores a generic "Running" progress in favor of a real command preview', () => {
+ // progress truthy + commandPreview truthy + isGenericToolProgress(progress) true
+ // -> the progress short-circuit is skipped and the command preview wins.
+ expect(
+ activeTurn({
+ pendingTools: [
+ {
+ id: 'tool-1',
+ name: 'pulse_read',
+ input: readToolInput('df -h'),
+ progress: 'Running',
+ status: 'running',
+ startedAt: 100,
+ },
+ ],
+ }),
+ ).toEqual({
+ type: 'tool',
+ text: 'Running $ df -h',
+ startedAt: 100,
+ });
+ });
+
+ it('ignores a generic "Running command." progress in favor of a real command preview', () => {
+ expect(
+ activeTurn({
+ pendingTools: [
+ {
+ id: 'tool-1',
+ name: 'pulse_read',
+ input: readToolInput('uptime'),
+ progress: 'Running command.',
+ status: 'running',
+ },
+ ],
+ }),
+ ).toEqual({
+ type: 'tool',
+ text: 'Running $ uptime',
+ });
+ });
+
+ it('drops a pending_tool stream event that carries no pendingTool payload', () => {
+ // formatPendingToolStatus(undefined) -> '' -> no candidate; the turn falls
+ // back to the initial request status instead of surfacing a tool row.
+ expect(
+ activeTurn({
+ streamEvents: [{ type: 'pending_tool', toolId: 'tool-1' }],
+ }),
+ ).toEqual({
+ type: 'thinking',
+ text: 'Sending prompt.',
+ startedAt: 1_000,
+ });
+ });
+});
+
+// ---------------------------------------------------------------------------
+// sanitizeWorkflowStatusMessage — reachable via formatAssistantWorkflowStatus
+// ---------------------------------------------------------------------------
+
+describe('sanitizeWorkflowStatusMessage branch coverage', () => {
+ it('strips a trailing "using <tool>." clause and keeps the terminating period', () => {
+ expect(
+ formatAssistantWorkflowStatus({
+ message: 'Reading inventory using pulse_query.',
+ tool: 'pulse_query',
+ }),
+ ).toBe('Reading inventory.');
+ });
+
+ it('strips a trailing "with <tool>" clause that has no terminating period', () => {
+ expect(
+ formatAssistantWorkflowStatus({
+ message: 'Reading inventory with pulse_query',
+ tool: 'pulse_query',
+ }),
+ ).toBe('Reading inventory');
+ });
+
+ it('strips a trailing "via the <tool>" clause (label re-attached as a suffix)', () => {
+ // After the trailing clause is removed the message no longer references the
+ // tool, so formatAssistantWorkflowStatus re-attaches the friendly label.
+ expect(
+ formatAssistantWorkflowStatus({
+ message: 'Gathering data via the pulse_query.',
+ tool: 'pulse_query',
+ }),
+ ).toBe('Gathering data. · inventory');
+ });
+
+ it('rewrites a bare internal tool identifier in the middle of a message', () => {
+ expect(
+ formatAssistantWorkflowStatus({
+ message: 'Running pulse_query now',
+ tool: 'pulse_query',
+ }),
+ ).toBe('Running inventory now');
+ });
+
+ it('collapses runs of whitespace and lone spaced-out periods', () => {
+ expect(
+ formatAssistantWorkflowStatus({ message: 'Working on it .' }),
+ ).toBe('Working on it.');
+ });
+
+ it('leaves a plain message unchanged when no tool context is present', () => {
+ expect(formatAssistantWorkflowStatus({ message: 'Waiting for assistant.' })).toBe(
+ 'Waiting for assistant.',
+ );
+ });
+});
+
+// ---------------------------------------------------------------------------
+// messageContainsToolLabel — reachable via formatAssistantWorkflowStatus
+// ---------------------------------------------------------------------------
+
+describe('messageContainsToolLabel branch coverage', () => {
+ it('appends the tool suffix when the friendly label is absent from the message', () => {
+ // messageContainsToolLabel('Working', 'read') -> \bread\b does not match -> false
+ // -> toolSuffix is appended.
+ expect(
+ formatAssistantWorkflowStatus({ message: 'Working', tool: 'pulse_read' }),
+ ).toBe('Working · read');
+ });
+
+ it('withholds the tool suffix when the message already mentions the label as a word', () => {
+ // messageContainsToolLabel('Reading storage', 'read') -> \bread\b does not
+ // match inside "Reading" -> false -> suffix appended (boundary edge case).
+ expect(
+ formatAssistantWorkflowStatus({ message: 'Reading storage', tool: 'pulse_read' }),
+ ).toBe('Reading storage · read');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// formatRetryDelay — reachable via formatAssistantWorkflowStatus (now omitted
+// so remainingRetryDelay returns retryAfterMs verbatim)
+// ---------------------------------------------------------------------------
+
+describe('formatRetryDelay branch coverage', () => {
+ const retry = (overrides: Record<string, unknown>) =>
+ formatAssistantWorkflowStatus({ message: 'Retrying.', ...overrides } as Parameters<
+ typeof formatAssistantWorkflowStatus
+ >[0]);
+
+ it('formats sub-second delays in milliseconds', () => {
+ expect(retry({ attempt: 1, retryAfterMs: 500 })).toBe('Retrying. · attempt 1 · retrying in 500ms');
+ expect(retry({ attempt: 1, retryAfterMs: 999 })).toBe('Retrying. · attempt 1 · retrying in 999ms');
+ });
+
+ it('formats the one-second boundary and sub-ten-second delays with one decimal', () => {
+ expect(retry({ attempt: 1, retryAfterMs: 1_000 })).toBe(
+ 'Retrying. · attempt 1 · retrying in 1s',
+ );
+ expect(retry({ attempt: 1, retryAfterMs: 9_500 })).toBe(
+ 'Retrying. · attempt 1 · retrying in 9.5s',
+ );
+ });
+
+ it('formats sub-minute second delays as whole seconds', () => {
+ expect(retry({ attempt: 1, retryAfterMs: 30_000 })).toBe(
+ 'Retrying. · attempt 1 · retrying in 30s',
+ );
+ });
+
+ it('formats sub-ten-minute delays with one decimal minute', () => {
+ expect(retry({ attempt: 1, retryAfterMs: 90_000 })).toBe(
+ 'Retrying. · attempt 1 · retrying in 1.5m',
+ );
+ });
+
+ it('formats delays of ten minutes or more as whole minutes', () => {
+ expect(retry({ attempt: 1, retryAfterMs: 600_000 })).toBe(
+ 'Retrying. · attempt 1 · retrying in 10m',
+ );
+ expect(retry({ attempt: 1, retryAfterMs: 900_000 })).toBe(
+ 'Retrying. · attempt 1 · retrying in 15m',
+ );
+ });
+
+ it('hits the formatRetryDelay empty-result branch once a countdown reaches zero', () => {
+ // remainingRetryDelay(retryAfterMs 3200, startedAt 1000, now 4500) -> 0,
+ // formatRetryDelay(0) -> '' -> formatRetryStatusSuffix emits "retrying now".
+ expect(
+ formatAssistantWorkflowStatus(
+ { message: 'Retrying.', attempt: 1, retryAfterMs: 3_200, startedAt: 1_000 },
+ 4_500,
+ ),
+ ).toBe('Retrying. · attempt 1 · retrying now');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// formatRetryStatusSuffix — reachable via formatAssistantWorkflowStatus
+// ---------------------------------------------------------------------------
+
+describe('formatRetryStatusSuffix branch coverage', () => {
+ it('emits only the attempt count when maxAttempts is missing', () => {
+ expect(formatAssistantWorkflowStatus({ message: 'Working', attempt: 2 })).toBe(
+ 'Working · attempt 2',
+ );
+ });
+
+ it('emits the attempt ratio when both attempt and maxAttempts are present', () => {
+ expect(formatAssistantWorkflowStatus({ message: 'Working', attempt: 2, maxAttempts: 3 })).toBe(
+ 'Working · attempt 2/3',
+ );
+ });
+
+ it('emits a retry delay without an attempt count', () => {
+ expect(formatAssistantWorkflowStatus({ message: 'Working', retryAfterMs: 500 })).toBe(
+ 'Working · retrying in 500ms',
+ );
+ });
+
+ it('omits the suffix entirely when there is no attempt or retry metadata', () => {
+ expect(formatAssistantWorkflowStatus({ message: 'Working' })).toBe('Working');
+ });
+
+ it('returns an empty string when there is no message at all', () => {
+ expect(formatAssistantWorkflowStatus({ message: '' })).toBe('');
+ expect(formatAssistantWorkflowStatus(undefined)).toBe('');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// thinkingStatusText — reachable via getAssistantActiveTurnStatus
+// ---------------------------------------------------------------------------
+
+describe('thinkingStatusText branch coverage', () => {
+ it('falls back to the bare "Thinking" label when no reasoning title is extractable', () => {
+ expect(
+ activeTurn({
+ streamEvents: [
+ { type: 'thinking', thinking: 'Plain reasoning with no bold heading.', startedAt: 2_000 },
+ ],
+ }),
+ ).toEqual({
+ type: 'thinking',
+ text: 'Thinking',
+ startedAt: 2_000,
+ });
+ });
+
+ it('ignores a whitespace-only thinking payload so no thinking status is surfaced', () => {
+ // thinkingStatusText -> '' -> no candidate -> falls back to initial request status.
+ expect(
+ activeTurn({
+ streamEvents: [{ type: 'thinking', thinking: ' ', startedAt: 2_000 }],
+ }),
+ ).toEqual({
+ type: 'thinking',
+ text: 'Sending prompt.',
+ startedAt: 1_000,
+ });
+ });
+});
+
+// ---------------------------------------------------------------------------
+// toolCancelStatusText — reachable via getAssistantActiveTurnStatus
+// ---------------------------------------------------------------------------
+
+describe('toolCancelStatusText branch coverage', () => {
+ it('omits the reason when none is supplied', () => {
+ expect(
+ activeTurn({
+ streamEvents: [
+ {
+ type: 'tool_cancel',
+ toolId: 'tool-1',
+ toolCancel: { id: 'tool-1', name: 'pulse_read', input: '{}' },
+ startedAt: 1_500,
+ },
+ ],
+ }),
+ ).toEqual({
+ type: 'tool',
+ text: 'Skipped read',
+ startedAt: 1_500,
+ });
+ });
+
+ it('treats a whitespace-only reason as absent', () => {
+ expect(
+ activeTurn({
+ streamEvents: [
+ {
+ type: 'tool_cancel',
+ toolId: 'tool-1',
+ toolCancel: { id: 'tool-1', name: 'pulse_read', input: '{}', reason: ' ' },
+ startedAt: 1_500,
+ },
+ ],
+ }),
+ ).toEqual({
+ type: 'tool',
+ text: 'Skipped read',
+ startedAt: 1_500,
+ });
+ });
+
+ it('falls back to pendingTool.name when toolCancel.name is empty', () => {
+ expect(
+ activeTurn({
+ streamEvents: [
+ {
+ type: 'tool_cancel',
+ toolId: 'tool-1',
+ toolCancel: { id: 'tool-1', name: '', input: '{}' },
+ pendingTool: { id: 'tool-1', name: 'pulse_read', input: '{}' },
+ startedAt: 1_500,
+ },
+ ],
+ }),
+ ).toEqual({
+ type: 'tool',
+ text: 'Skipped read',
+ startedAt: 1_500,
+ });
+ });
+});
+
+// ---------------------------------------------------------------------------
+// completedToolStatusText — reachable via getAssistantActiveTurnStatus
+// ---------------------------------------------------------------------------
+
+describe('completedToolStatusText branch coverage', () => {
+ it('reports "Completed" with the label fallback for placeholder input', () => {
+ expect(
+ activeTurn({
+ streamEvents: [
+ {
+ type: 'tool',
+ toolId: 'tool-1',
+ tool: { name: 'pulse_get_nodes', input: '{}', output: 'ok', success: true },
+ startedAt: 1_100,
+ },
+ ],
+ }),
+ ).toEqual({
+ type: 'tool',
+ text: 'Completed get nodes',
+ });
+ });
+
+ it('reports "Completed" with a parsed input summary when available', () => {
+ expect(
+ activeTurn({
+ streamEvents: [
+ {
+ type: 'tool',
+ toolId: 'tool-1',
+ tool: {
+ name: 'pulse_query',
+ input: JSON.stringify({ action: 'list' }),
+ output: 'ok',
+ success: true,
+ },
+ startedAt: 1_100,
+ },
+ ],
+ }),
+ ).toEqual({
+ type: 'tool',
+ text: 'Completed list resources',
+ });
+ });
+
+ it('drops a tool stream event that carries no tool payload', () => {
+ // completedToolStatusText -> `if (!tool) return ''` -> no candidate.
+ expect(
+ activeTurn({
+ streamEvents: [{ type: 'tool', toolId: 'tool-1' }],
+ }),
+ ).toEqual({
+ type: 'thinking',
+ text: 'Sending prompt.',
+ startedAt: 1_000,
+ });
+ });
+});
+
+// ---------------------------------------------------------------------------
+// latestStreamActivityStatus — uncovered switch arms / guard-false arms
+// ---------------------------------------------------------------------------
+
+describe('latestStreamActivityStatus branch coverage', () => {
+ it('ignores an unknown event type via the default switch arm', () => {
+ expect(
+ activeTurn({
+ streamEvents: [{ type: 'bogus' } as unknown as StreamDisplayEvent],
+ }),
+ ).toEqual({
+ type: 'thinking',
+ text: 'Sending prompt.',
+ startedAt: 1_000,
+ });
+ });
+
+ it('ignores a content event whose payload is only whitespace', () => {
+ // `if (event.content?.trim())` guard is false -> no generating candidate.
+ expect(
+ activeTurn({
+ streamEvents: [{ type: 'content', content: ' ' }],
+ }),
+ ).toEqual({
+ type: 'thinking',
+ text: 'Sending prompt.',
+ startedAt: 1_000,
+ });
+ });
+
+ it('ignores an approval event that carries no approval payload', () => {
+ expect(
+ activeTurn({
+ streamEvents: [{ type: 'approval' }],
+ }),
+ ).toEqual({
+ type: 'thinking',
+ text: 'Sending prompt.',
+ startedAt: 1_000,
+ });
+ });
+
+ it('ignores a question event that carries no question payload', () => {
+ expect(
+ activeTurn({
+ streamEvents: [{ type: 'question' }],
+ }),
+ ).toEqual({
+ type: 'thinking',
+ text: 'Sending prompt.',
+ startedAt: 1_000,
+ });
+ });
+
+ it('surfaces the later of two equally-timed thinking events via the order tiebreak', () => {
+ // Both events have no startedAt/updatedAt -> activityAt undefined for both.
+ // isFresherStatusCandidate falls through to the order tiebreak.
+ expect(
+ activeTurn({
+ streamEvents: [
+ { type: 'thinking', thinking: '**Alpha**' },
+ { type: 'thinking', thinking: '**Beta**' },
+ ],
+ }),
+ ).toEqual({
+ type: 'thinking',
+ text: 'Thinking: Beta',
+ });
+ });
+});
+
+// ---------------------------------------------------------------------------
+// isFresherStatusCandidate — observable arms via getAssistantActiveTurnStatus
+// ---------------------------------------------------------------------------
+
+describe('isFresherStatusCandidate branch coverage', () => {
+ it('prefers a current workflow status over an older generic content row', () => {
+ // currentWorkflow candidate vs genericContent current -> returns true.
+ expect(
+ activeTurn(
+ {
+ isStreaming: true,
+ workflowStatus: {
+ phase: 'stream_idle',
+ message: 'Still working; waiting for more response data.',
+ startedAt: 2_000,
+ },
+ streamEvents: [
+ {
+ type: 'workflow_status',
+ workflowStatus: {
+ phase: 'stream_idle',
+ message: 'Still working; waiting for more response data.',
+ startedAt: 2_000,
+ },
+ startedAt: 2_000,
+ updatedAt: 2_000,
+ },
+ { type: 'content', content: 'partial token', startedAt: 3_000, updatedAt: 3_000 },
+ ],
+ },
+ 3_500,
+ ),
+ ).toEqual({
+ type: 'thinking',
+ text: 'Still working; waiting for more response data.',
+ startedAt: 2_000,
+ });
+ });
+
+ it('prefers a newer-activity tool over an older tool regardless of array order', () => {
+ // Two pending tools in state; the one with the later updatedAt wins via the
+ // candidateTime > currentTime arm of isFresherStatusCandidate.
+ expect(
+ activeTurn({
+ pendingTools: [
+ {
+ id: 'tool-a',
+ name: 'pulse_get_nodes',
+ input: '{}',
+ status: 'running',
+ startedAt: 100,
+ updatedAt: 200,
+ },
+ {
+ id: 'tool-b',
+ name: 'pulse_read',
+ input: '{}',
+ status: 'running',
+ startedAt: 100,
+ updatedAt: 500,
+ },
+ ],
+ }),
+ ).toEqual({
+ type: 'tool',
+ text: 'Running read',
+ startedAt: 100,
+ });
+ });
+});
diff --git a/frontend-modern/src/components/Infrastructure/__tests__/infrastructureSelectors.branchcov.test.ts b/frontend-modern/src/components/Infrastructure/__tests__/infrastructureSelectors.branchcov.test.ts
new file mode 100644
index 0000000000..191c5472d7
--- /dev/null
+++ b/frontend-modern/src/components/Infrastructure/__tests__/infrastructureSelectors.branchcov.test.ts
@@ -0,0 +1,424 @@
+import { describe, expect, it } from 'vitest';
+import type { Resource } from '@/types/resource';
+import {
+ buildInfrastructureSummaryGroupScope,
+ computeIOScale,
+ filterResources,
+ getOutlierEmphasis,
+ infrastructureHasVisibleSummaryGroupScope,
+ matchesSearch,
+ sortResources,
+} from '@/components/Infrastructure/infrastructureSelectors';
+
+/**
+ * Branch-coverage suite for the currently-uncovered branches of the target
+ * functions in infrastructureSelectors.ts. The module-private helpers
+ * (getSortValue, compareValues, defaultComparison, computeMedian,
+ * computePercentile) are NOT exported, so they are exercised exclusively
+ * through the exported entry points (sortResources, computeIOScale) and
+ * asserted on observable return values — never re-implemented or imported
+ * directly. The sibling infrastructureSelectors.test.ts already covers the
+ * happy paths; this file targets only the remaining guard/edge arms.
+ */
+
+const makeResource = (i: number, overrides: Partial<Resource> = {}): Resource => ({
+ id: `resource-${i}`,
+ type: 'agent',
+ name: `host-${i}`,
+ displayName: `Host ${i}`,
+ platformId: `platform-${i}`,
+ platformType: 'proxmox-pve',
+ sourceType: 'api',
+ status: 'online',
+ lastSeen: 1_700_000_000_000 + i,
+ platformData: { sources: ['proxmox'] },
+ ...overrides,
+});
+
+const BASELINE = { fontWeight: 'normal', color: 'text-muted', showOutlierHint: false };
+const MEDIUM = { fontWeight: '500', color: 'text-base-content', showOutlierHint: true };
+const HIGH = { fontWeight: '600', color: 'text-base-content', showOutlierHint: true };
+
+describe('getSortValue (observed via sortResources)', () => {
+ it('sorts by uptime and substitutes 0 when uptime is absent', () => {
+ const resources = [
+ makeResource(1, { displayName: 'Bravo', uptime: 100 }),
+ makeResource(2, { displayName: 'Alpha', uptime: 50 }),
+ makeResource(3, { displayName: 'Charlie' }), // uptime ?? 0
+ ];
+ expect(sortResources(resources, 'uptime', 'asc').map((r) => r.id)).toEqual([
+ 'resource-3',
+ 'resource-2',
+ 'resource-1',
+ ]);
+ });
+
+ it('sorts by memory percent and yields null when memory is absent', () => {
+ const resources = [
+ makeResource(1, { displayName: 'Bravo', memory: { current: 80, total: 100, used: 80 } }),
+ makeResource(2, { displayName: 'Alpha', memory: { current: 20, total: 100, used: 20 } }),
+ makeResource(3, { displayName: 'Charlie' }), // null → bottom
+ ];
+ expect(sortResources(resources, 'memory', 'asc').map((r) => r.id)).toEqual([
+ 'resource-2',
+ 'resource-1',
+ 'resource-3',
+ ]);
+ });
+
+ it('sorts by disk percent and yields null when disk is absent', () => {
+ const resources = [
+ makeResource(1, { displayName: 'Bravo', disk: { current: 90, total: 100, used: 90 } }),
+ makeResource(2, { displayName: 'Alpha', disk: { current: 10, total: 100, used: 10 } }),
+ makeResource(3, { displayName: 'Charlie' }), // null → bottom
+ ];
+ expect(sortResources(resources, 'disk', 'asc').map((r) => r.id)).toEqual([
+ 'resource-2',
+ 'resource-1',
+ 'resource-3',
+ ]);
+ });
+
+ it('sorts by network byte total and yields null when network is absent', () => {
+ const resources = [
+ makeResource(1, { displayName: 'Bravo', network: { rxBytes: 100, txBytes: 50 } }),
+ makeResource(2, { displayName: 'Alpha', network: { rxBytes: 10, txBytes: 5 } }),
+ makeResource(3, { displayName: 'Charlie' }), // null → bottom
+ ];
+ expect(sortResources(resources, 'network', 'asc').map((r) => r.id)).toEqual([
+ 'resource-2',
+ 'resource-1',
+ 'resource-3',
+ ]);
+ });
+
+ it('sorts by disk io rate total and yields null when diskIO is absent', () => {
+ const resources = [
+ makeResource(1, { displayName: 'Bravo', diskIO: { readRate: 200, writeRate: 100 } }),
+ makeResource(2, { displayName: 'Alpha', diskIO: { readRate: 20, writeRate: 10 } }),
+ makeResource(3, { displayName: 'Charlie' }), // null → bottom
+ ];
+ expect(sortResources(resources, 'diskio', 'asc').map((r) => r.id)).toEqual([
+ 'resource-2',
+ 'resource-1',
+ 'resource-3',
+ ]);
+ });
+
+ it('sorts by temperature and yields null when temperature is absent', () => {
+ const resources = [
+ makeResource(1, { displayName: 'Bravo', temperature: 75 }),
+ makeResource(2, { displayName: 'Alpha', temperature: 35 }),
+ makeResource(3, { displayName: 'Charlie' }), // null → bottom
+ ];
+ expect(sortResources(resources, 'temp', 'asc').map((r) => r.id)).toEqual([
+ 'resource-2',
+ 'resource-1',
+ 'resource-3',
+ ]);
+ });
+
+ it('returns null for an unknown sort key so ordering falls back to default', () => {
+ const resources = [
+ makeResource(1, { displayName: 'Bravo', status: 'offline' }),
+ makeResource(2, { displayName: 'Alpha', status: 'online' }),
+ ];
+ // unknown key → getSortValue null for both → compareValues(null,null)=0
+ // → defaultComparison (online first)
+ expect(sortResources(resources, 'totally-unknown-key', 'asc').map((r) => r.id)).toEqual([
+ 'resource-2',
+ 'resource-1',
+ ]);
+ });
+});
+
+describe('compareValues (observed via sortResources)', () => {
+ it('sorts a null metric after a finite metric in asc order (aEmpty branch)', () => {
+ const resources = [
+ makeResource(1, { displayName: 'Alpha' }), // no cpu → null
+ makeResource(2, { displayName: 'Bravo', cpu: { current: 42 } }),
+ ];
+ expect(sortResources(resources, 'cpu', 'asc').map((r) => r.id)).toEqual([
+ 'resource-2',
+ 'resource-1',
+ ]);
+ });
+
+ it('places a finite metric before a null metric in asc order (bEmpty branch)', () => {
+ const resources = [
+ makeResource(1, { displayName: 'Alpha', cpu: { current: 42 } }),
+ makeResource(2, { displayName: 'Bravo' }), // no cpu → null
+ ];
+ expect(sortResources(resources, 'cpu', 'asc').map((r) => r.id)).toEqual([
+ 'resource-1',
+ 'resource-2',
+ ]);
+ });
+
+ it('treats two null metric values as equal and defers to the default tie-break', () => {
+ const resources = [
+ makeResource(1, { displayName: 'Bravo', status: 'online' }), // no cpu
+ makeResource(2, { displayName: 'Alpha', status: 'online' }), // no cpu
+ ];
+ // compareValues(null,null) === 0 → defaultComparison → Alpha before Bravo
+ expect(sortResources(resources, 'cpu', 'asc').map((r) => r.id)).toEqual([
+ 'resource-2',
+ 'resource-1',
+ ]);
+ });
+});
+
+describe('defaultComparison (observed via sortResources default key)', () => {
+ it('orders two offline resources by display name via localeCompare', () => {
+ const resources = [
+ makeResource(1, { displayName: 'Zeta', status: 'offline' }),
+ makeResource(2, { displayName: 'Alpha', status: 'offline' }),
+ ];
+ expect(sortResources(resources, 'default', 'asc').map((r) => r.id)).toEqual([
+ 'resource-2',
+ 'resource-1',
+ ]);
+ });
+
+ it('treats a "stopped" status as offline via the second isResourceOnline guard', () => {
+ const resources = [
+ makeResource(1, { displayName: 'Stopped-One', status: 'stopped' }),
+ makeResource(2, { displayName: 'Online-One', status: 'online' }),
+ ];
+ // 'stopped' → isResourceOnline false → online resource sorts first
+ expect(sortResources(resources, 'default', 'asc').map((r) => r.id)).toEqual([
+ 'resource-2',
+ 'resource-1',
+ ]);
+ });
+});
+
+describe('matchesSearch (branch coverage)', () => {
+ it('returns true for an empty search term', () => {
+ expect(matchesSearch(makeResource(1), '')).toBe(true);
+ });
+
+ it('matches against identity.hostname', () => {
+ const resource = makeResource(1, {
+ displayName: 'Showcase',
+ identity: { hostname: 'db-prod-01.example.com' },
+ });
+ expect(matchesSearch(resource, 'db-prod-01')).toBe(true);
+ expect(matchesSearch(resource, 'EXAMPLE.COM')).toBe(true);
+ });
+
+ it('does not crash and still matches by name/id when identity and tags are absent', () => {
+ const resource = makeResource(1, { identity: undefined });
+ expect(matchesSearch(resource, 'resource-1')).toBe(true);
+ expect(matchesSearch(resource, 'host')).toBe(true);
+ expect(matchesSearch(resource, 'no-such-term')).toBe(false);
+ });
+});
+
+describe('filterResources (branch coverage)', () => {
+ it('drops resources that carry no platform sources when a sources filter is active', () => {
+ const resources = [
+ makeResource(1, { platformData: { sources: ['proxmox'] } }),
+ makeResource(2, { platformData: {} }), // resourceSources.length === 0 → excluded
+ makeResource(3, { platformData: { sources: ['docker'] } }),
+ ];
+ expect(
+ filterResources(resources, new Set(['proxmox-pve', 'docker']), new Set(), []).map(
+ (r) => r.id,
+ ),
+ ).toEqual(['resource-1', 'resource-3']);
+ });
+
+ it('excludes resources whose sources do not intersect the active source filter', () => {
+ const resources = [
+ makeResource(1, { platformData: { sources: ['proxmox'] } }),
+ makeResource(2, { platformData: { sources: ['docker'] } }),
+ ];
+ expect(
+ filterResources(resources, new Set(['proxmox-pve']), new Set(), []).map((r) => r.id),
+ ).toEqual(['resource-1']);
+ });
+
+ it('normalizes a missing status to "unknown" and filters against it', () => {
+ const resources = [
+ makeResource(1, { status: 'online' }),
+ makeResource(2, { status: '' as unknown as Resource['status'] }), // || 'unknown'
+ makeResource(3, { status: 'degraded' }),
+ ];
+ expect(
+ filterResources(resources, new Set(), new Set(['unknown']), []).map((r) => r.id),
+ ).toEqual(['resource-2']);
+ });
+});
+
+describe('buildInfrastructureSummaryGroupScope (branch coverage)', () => {
+ it('returns null when the group has no resources', () => {
+ expect(buildInfrastructureSummaryGroupScope({ cluster: 'alpha', resources: [] })).toBeNull();
+ });
+
+ it('returns null when every resource id is blank or whitespace', () => {
+ const resources = [makeResource(1, { id: ' ' }), makeResource(2, { id: '' })];
+ expect(buildInfrastructureSummaryGroupScope({ cluster: 'alpha', resources })).toBeNull();
+ });
+
+ it('deduplicates series ids and emits a plural cluster label', () => {
+ const resources = [
+ makeResource(1, { id: 'node-a' }),
+ makeResource(2, { id: 'node-a' }),
+ makeResource(3, { id: 'node-b' }),
+ ];
+ expect(buildInfrastructureSummaryGroupScope({ cluster: 'beta', resources })).toEqual({
+ id: 'cluster:beta',
+ label: 'beta (3 resources)',
+ seriesIds: ['node-a', 'node-b'],
+ });
+ });
+
+ it('emits a standalone label and plural resourceCount for an empty cluster', () => {
+ const resources = [makeResource(1, { id: 'solo-1' }), makeResource(2, { id: 'solo-2' })];
+ expect(buildInfrastructureSummaryGroupScope({ cluster: '', resources })).toEqual({
+ id: 'cluster:__standalone__',
+ label: 'Standalone (2 resources)',
+ seriesIds: ['solo-1', 'solo-2'],
+ });
+ });
+});
+
+describe('infrastructureHasVisibleSummaryGroupScope (branch coverage)', () => {
+ const resources = [makeResource(1, { id: 'node-a' })];
+
+ it('returns false when scope is null', () => {
+ expect(infrastructureHasVisibleSummaryGroupScope(resources, null)).toBe(false);
+ });
+
+ it('returns false when scope is undefined', () => {
+ expect(infrastructureHasVisibleSummaryGroupScope(resources, undefined)).toBe(false);
+ });
+
+ it('returns false when resources is empty but scope is present', () => {
+ expect(
+ infrastructureHasVisibleSummaryGroupScope([], {
+ id: 'cluster:alpha',
+ label: 'alpha (1 resource)',
+ seriesIds: ['node-a'],
+ }),
+ ).toBe(false);
+ });
+
+ it('trims series ids before comparing against visible resource ids', () => {
+ expect(
+ infrastructureHasVisibleSummaryGroupScope(resources, {
+ id: 'cluster:alpha',
+ label: 'alpha (1 resource)',
+ seriesIds: [' node-a '],
+ }),
+ ).toBe(true);
+ });
+});
+
+describe('getOutlierEmphasis (branch coverage)', () => {
+ const denseStats = { median: 10, mad: 2, max: 30, p97: 20, p99: 25, count: 10 };
+
+ it('returns baseline for a non-finite value', () => {
+ expect(getOutlierEmphasis(Number.NaN, denseStats)).toEqual(BASELINE);
+ });
+
+ it('returns baseline when value is <= 0', () => {
+ expect(getOutlierEmphasis(0, denseStats)).toEqual(BASELINE);
+ expect(getOutlierEmphasis(-5, denseStats)).toEqual(BASELINE);
+ });
+
+ it('returns baseline when stats.max <= 0', () => {
+ expect(
+ getOutlierEmphasis(5, { median: 0, mad: 0, max: 0, p97: 0, p99: 0, count: 5 }),
+ ).toEqual(BASELINE);
+ });
+
+ describe('small sample path (count < 4)', () => {
+ const smallStats = { median: 50, mad: 0, max: 100, p97: 99, p99: 99, count: 3 };
+
+ it('returns medium emphasis at and above the 0.995 ratio boundary', () => {
+ expect(getOutlierEmphasis(100, smallStats)).toEqual(MEDIUM); // ratio 1.0
+ expect(getOutlierEmphasis(99.5, smallStats)).toEqual(MEDIUM); // ratio 0.995
+ });
+
+ it('returns baseline just below the 0.995 ratio boundary', () => {
+ expect(getOutlierEmphasis(99.4, smallStats)).toEqual(BASELINE); // ratio 0.994
+ expect(getOutlierEmphasis(50, smallStats)).toEqual(BASELINE);
+ });
+ });
+
+ describe('flat distribution path (mad === 0, count >= 4)', () => {
+ const flatStats = { median: 50, mad: 0, max: 100, p97: 80, p99: 90, count: 5 };
+
+ it('returns high emphasis when value >= p99', () => {
+ expect(getOutlierEmphasis(90, flatStats)).toEqual(HIGH);
+ expect(getOutlierEmphasis(95, flatStats)).toEqual(HIGH);
+ });
+
+ it('returns medium emphasis when value >= p97 but < p99', () => {
+ expect(getOutlierEmphasis(80, flatStats)).toEqual(MEDIUM);
+ expect(getOutlierEmphasis(85, flatStats)).toEqual(MEDIUM);
+ });
+
+ it('returns baseline when value > 0 but < p97', () => {
+ expect(getOutlierEmphasis(70, flatStats)).toEqual(BASELINE);
+ });
+ });
+
+ it('returns baseline when modifiedZ is high but value sits below p97 (both && guards fail)', () => {
+ // median 10, mad 0.1, value 15 → modifiedZ = 0.6745 * 50 = 33.7 (>= 6.5)
+ // but 15 < p99(25) and 15 < p97(20) → neither outlier guard passes.
+ const stats = { median: 10, mad: 0.1, max: 30, p97: 20, p99: 25, count: 10 };
+ expect(getOutlierEmphasis(15, stats)).toEqual(BASELINE);
+ });
+});
+
+describe('computeMedian / computePercentile (observed via computeIOScale)', () => {
+ it('averages the two middle values for an even count of samples', () => {
+ const resources = [
+ makeResource(1, {
+ network: { rxBytes: 10, txBytes: 0 }, // total 10
+ diskIO: { readRate: 1, writeRate: 0 }, // total 1
+ }),
+ makeResource(2, {
+ network: { rxBytes: 20, txBytes: 0 }, // total 20
+ diskIO: { readRate: 3, writeRate: 0 }, // total 3
+ }),
+ ];
+ expect(computeIOScale(resources)).toEqual({
+ network: { median: 15, mad: 5, max: 20, p97: 20, p99: 20, count: 2 },
+ diskIO: { median: 2, mad: 1, max: 3, p97: 3, p99: 3, count: 2 },
+ });
+ });
+
+ it('selects the upper percentile element for a larger odd-length sample', () => {
+ const values = [2, 4, 6, 8, 100];
+ const resources = values.map((rxBytes, i) =>
+ makeResource(i + 1, { network: { rxBytes, txBytes: 0 } }),
+ );
+ expect(computeIOScale(resources).network).toEqual({
+ median: 6, // sorted[2]
+ mad: 2, // deviations from 6: 4,2,0,2,94 → sorted 0,2,2,4,94 → median 2
+ max: 100,
+ p97: 100, // index = ceil(0.97 * 5) - 1 = 4
+ p99: 100,
+ count: 5,
+ });
+ });
+
+ it('reports zeroed diskIO stats when no resource contributes diskIO samples', () => {
+ const resources = [
+ makeResource(1, { network: { rxBytes: 5, txBytes: 5 } }),
+ makeResource(2, { network: { rxBytes: 15, txBytes: 5 } }),
+ ];
+ expect(computeIOScale(resources).diskIO).toEqual({
+ median: 0,
+ mad: 0,
+ max: 0,
+ p97: 0,
+ p99: 0,
+ count: 0,
+ });
+ });
+});
diff --git a/frontend-modern/src/components/Infrastructure/__tests__/resourceDetailDiscoveryModel.branchcov.test.ts b/frontend-modern/src/components/Infrastructure/__tests__/resourceDetailDiscoveryModel.branchcov.test.ts
new file mode 100644
index 0000000000..fcba43f58a
--- /dev/null
+++ b/frontend-modern/src/components/Infrastructure/__tests__/resourceDetailDiscoveryModel.branchcov.test.ts
@@ -0,0 +1,554 @@
+import { describe, expect, it } from 'vitest';
+
+import { toDiscoveryConfig } from '@/components/Infrastructure/resourceDetailDiscoveryModel';
+import type { Resource, ResourceDiscoveryTarget } from '@/types/resource';
+
+/**
+ * Branch-coverage suite for the currently-uncovered functions in
+ * resourceDetailDiscoveryModel.ts.
+ *
+ * `hasSource` and `getPreferredHostLabel` are module-private (never exported),
+ * so they are driven exclusively through the single exported entry point
+ * `toDiscoveryConfig`:
+ * - `getPreferredHostLabel` is observed via the `hostname` field of the
+ * returned DiscoveryConfig (computed by `getPreferredHostLabel` in the
+ * main switch path, and as a fallback for an absent explicit hostname).
+ * - `hasSource` is observed via `hasVMwareScope`, which gates the `vm`
+ * switch case's early-null arm. A vm that carries a vmware source yields
+ * `null`; a vm without one yields a vm-shaped config.
+ *
+ * No private symbol is imported. Real exported functions are called with
+ * fixture resources and the actual returned values are asserted.
+ */
+
+const baseResource = (overrides: Partial<Resource> = {}): Resource =>
+ ({
+ id: 'res-1',
+ type: 'storage',
+ name: 'res-name',
+ displayName: 'Res Name',
+ platformId: 'platform-1',
+ platformType: 'proxmox-pve',
+ sourceType: 'hybrid',
+ status: 'online',
+ lastSeen: 1_700_000_000_000,
+ ...overrides,
+ }) as unknown as Resource;
+
+const discoveryTarget = (overrides: Partial<ResourceDiscoveryTarget> = {}): ResourceDiscoveryTarget =>
+ ({
+ resourceType: 'agent',
+ agentId: 'agent-default',
+ resourceId: 'rid-default',
+ ...overrides,
+ }) as ResourceDiscoveryTarget;
+
+describe('getPreferredHostLabel (observed via toDiscoveryConfig hostname field)', () => {
+ it('uses the identity hostname when getPreferredResourceHostname resolves it (arm 1)', () => {
+ // identity.hostname is the first source getPreferredResourceHostname checks
+ // after canonicalIdentity.hostname; with no canonical identity set, the
+ // identity hostname wins and is surfaced as the discovery hostname.
+ const resource = baseResource({
+ type: 'vm',
+ identity: { hostname: 'host-via-identity' },
+ });
+ expect(toDiscoveryConfig(resource)?.hostname).toBe('host-via-identity');
+ });
+
+ it('falls back to the infrastructure display name when no hostname source resolves (arm 2)', () => {
+ // name/platformId are blanked so getPreferredResourceHostname returns
+ // undefined; displayName then becomes the winning label via
+ // getPreferredInfrastructureDisplayName.
+ const resource = baseResource({
+ type: 'vm',
+ name: '',
+ platformId: '',
+ displayName: 'Display-Label',
+ });
+ expect(toDiscoveryConfig(resource)?.hostname).toBe('Display-Label');
+ });
+
+ it('falls back to resource.id when neither hostname nor display name resolve (arm 3)', () => {
+ // Every hostname and display-name source is blanked, so the label chain
+ // bottoms out at resource.id (via getPrimaryResourceIdentity).
+ const resource = baseResource({
+ type: 'vm',
+ id: 'fallback-id',
+ name: '',
+ platformId: '',
+ displayName: '',
+ });
+ expect(toDiscoveryConfig(resource)?.hostname).toBe('fallback-id');
+ });
+});
+
+describe('hasSource (observed via hasVMwareScope in the vm switch case)', () => {
+ it('matches a vmware entry in resource.sources and returns null for the vm', () => {
+ const resource = baseResource({ type: 'vm', sources: ['vmware'] });
+ expect(toDiscoveryConfig(resource)).toBeNull();
+ });
+
+ it('matches a vmware-vsphere entry in platformData.sources and returns null for the vm', () => {
+ const resource = baseResource({
+ type: 'vm',
+ platformData: { sources: ['vmware-vsphere'] },
+ });
+ expect(toDiscoveryConfig(resource)).toBeNull();
+ });
+
+ it('matches a VMWARE entry (case-insensitive) in resource.platformScopes and returns null', () => {
+ const resource = baseResource({ type: 'vm', platformScopes: ['VMWARE'] });
+ expect(toDiscoveryConfig(resource)).toBeNull();
+ });
+
+ it('trims whitespace before comparing a vmware candidate', () => {
+ const resource = baseResource({ type: 'vm', sources: [' vmware '] });
+ expect(toDiscoveryConfig(resource)).toBeNull();
+ });
+
+ it('ignores non-string candidates and falls through to a vm config', () => {
+ // A numeric source entry is not a string, so asString() drops it; with no
+ // vmware match anywhere the vm case proceeds and returns a config.
+ const resource = baseResource({
+ type: 'vm',
+ id: 'vm-nostring',
+ name: 'vm-nostring',
+ sources: [42, { platform: 'vmware-vsphere' }] as unknown as string[],
+ });
+ const result = toDiscoveryConfig(resource);
+ expect(result).not.toBeNull();
+ expect(result?.resourceType).toBe('vm');
+ });
+
+ it('returns a vm config when every source array is absent', () => {
+ // No sources, no platformScopes, no platformData: hasSource sees zero
+ // candidates from every array (Array.isArray guards all short-circuit).
+ const resource = baseResource({ type: 'vm', id: 'vm-bare', name: 'vm-bare' });
+ const result = toDiscoveryConfig(resource);
+ expect(result).not.toBeNull();
+ expect(result?.resourceType).toBe('vm');
+ });
+});
+
+describe('toDiscoveryConfig — explicit discoveryTarget branch', () => {
+ describe('explicit happy paths (each supported resourceType)', () => {
+ it('maps an explicit agent target to an agent discovery config', () => {
+ const resource = baseResource({
+ type: 'agent',
+ discoveryTarget: discoveryTarget({
+ resourceType: 'agent',
+ agentId: 'agent-explicit',
+ resourceId: 'rid-explicit',
+ hostname: 'explicit-host',
+ }),
+ });
+ expect(toDiscoveryConfig(resource)).toEqual({
+ resourceType: 'agent',
+ agentId: 'agent-explicit',
+ resourceId: 'rid-explicit',
+ hostname: 'explicit-host',
+ metadataKind: 'agent',
+ metadataId: 'agent-explicit',
+ targetLabel: 'agent',
+ });
+ });
+
+ it('maps an explicit vm target to a guest config and derives hostname from getPreferredHostLabel', () => {
+ const resource = baseResource({
+ type: 'vm',
+ name: 'vm-name',
+ discoveryTarget: discoveryTarget({
+ resourceType: 'vm',
+ agentId: 'vm-agent',
+ resourceId: 'vm-rid',
+ }),
+ });
+ // No explicit hostname => getPreferredHostLabel(resource) wins.
+ expect(toDiscoveryConfig(resource)).toEqual({
+ resourceType: 'vm',
+ agentId: 'vm-agent',
+ resourceId: 'vm-rid',
+ hostname: 'vm-name',
+ metadataKind: 'guest',
+ metadataId: 'vm-rid',
+ targetLabel: 'guest',
+ });
+ });
+
+ it('maps an explicit system-container target to a guest config', () => {
+ const resource = baseResource({
+ type: 'system-container',
+ discoveryTarget: discoveryTarget({
+ resourceType: 'system-container',
+ agentId: 'sc-agent',
+ resourceId: 'sc-rid',
+ }),
+ });
+ const result = toDiscoveryConfig(resource);
+ expect(result?.resourceType).toBe('system-container');
+ expect(result?.metadataKind).toBe('guest');
+ expect(result?.metadataId).toBe('sc-rid');
+ expect(result?.targetLabel).toBe('guest');
+ });
+
+ it('maps an explicit pod target to a workload config', () => {
+ const resource = baseResource({
+ type: 'pod',
+ discoveryTarget: discoveryTarget({
+ resourceType: 'pod',
+ agentId: 'pod-agent',
+ resourceId: 'pod-rid',
+ }),
+ });
+ const result = toDiscoveryConfig(resource);
+ expect(result?.resourceType).toBe('pod');
+ expect(result?.metadataKind).toBe('guest');
+ expect(result?.targetLabel).toBe('workload');
+ });
+
+ it('maps an explicit app-container target without docker metadata to a guest container config', () => {
+ const resource = baseResource({
+ type: 'app-container',
+ discoveryTarget: discoveryTarget({
+ resourceType: 'app-container',
+ agentId: 'app-agent',
+ resourceId: 'app-rid',
+ }),
+ });
+ const result = toDiscoveryConfig(resource);
+ expect(result?.resourceType).toBe('app-container');
+ expect(result?.metadataKind).toBe('guest');
+ expect(result?.metadataId).toBe('app-rid');
+ expect(result?.targetLabel).toBe('container');
+ });
+
+ it('maps an explicit app-container target with docker metadata to a docker container config', () => {
+ const resource = baseResource({
+ type: 'app-container',
+ docker: { hostSourceId: 'dhost', containerId: 'dcont' },
+ discoveryTarget: discoveryTarget({
+ resourceType: 'app-container',
+ agentId: 'app-agent',
+ resourceId: 'app-rid',
+ }),
+ });
+ const result = toDiscoveryConfig(resource);
+ expect(result?.metadataKind).toBe('docker');
+ expect(result?.metadataId).toBe('dhost:container:dcont');
+ expect(result?.targetLabel).toBe('container');
+ });
+ });
+
+ describe('explicit hostname fallback arm', () => {
+ it('uses the explicit hostname when present (short-circuits getPreferredHostLabel)', () => {
+ const resource = baseResource({
+ type: 'vm',
+ name: 'should-be-ignored',
+ discoveryTarget: discoveryTarget({
+ resourceType: 'vm',
+ agentId: 'a',
+ resourceId: 'r',
+ hostname: 'from-explicit-target',
+ }),
+ });
+ expect(toDiscoveryConfig(resource)?.hostname).toBe('from-explicit-target');
+ });
+ });
+
+ describe('explicit resourceType switch default (falls through to the main switch)', () => {
+ it("drops an explicit 'disk' target and falls back to the main switch for an agent", () => {
+ // 'disk' canonicalizes to 'disk' which hits the switch default in the
+ // explicit branch => resourceType becomes null => the explicit block is
+ // skipped and the main switch handles the resource by its real type.
+ // Discriminator: the explicit resourceType was 'disk', yet the returned
+ // config carries resourceType 'agent' (derived from resource.type), never
+ // 'disk' — proving the explicit target was discarded.
+ const resource = baseResource({
+ type: 'agent',
+ name: 'real-agent',
+ discoveryTarget: discoveryTarget({
+ resourceType: 'disk',
+ agentId: 'explicit-agent-id',
+ resourceId: 'explicit-rid',
+ } as ResourceDiscoveryTarget),
+ });
+ const result = toDiscoveryConfig(resource);
+ expect(result).not.toBeNull();
+ expect(result?.resourceType).toBe('agent');
+ // NOTE: getActionableAgentIdFromResource falls back to
+ // discoveryTarget.agentId unconditionally, so the explicit agentId leaks
+ // into the main-switch agentLookupId even though the explicit resourceType
+ // ('disk') was dropped. Observed here as the Section B agentId value.
+ expect(result?.agentId).toBe('explicit-agent-id');
+ expect(result?.targetLabel).toBe('agent');
+ });
+ });
+
+ describe('explicit guard rejections (falls through to the main switch)', () => {
+ it('returns null when no discoveryTarget is set and the type is unmapped', () => {
+ expect(toDiscoveryConfig(baseResource({ type: 'storage' }))).toBeNull();
+ });
+
+ it('rejects an explicit target with a blank resourceType', () => {
+ const resource = baseResource({
+ type: 'storage',
+ discoveryTarget: discoveryTarget({
+ resourceType: '' as ResourceDiscoveryTarget['resourceType'],
+ agentId: 'a',
+ resourceId: 'r',
+ }),
+ });
+ expect(toDiscoveryConfig(resource)).toBeNull();
+ });
+
+ it("rejects an explicit agentId that is 'redacted by policy'", () => {
+ const resource = baseResource({
+ type: 'storage',
+ discoveryTarget: discoveryTarget({
+ resourceType: 'agent',
+ agentId: 'redacted by policy',
+ resourceId: 'r',
+ }),
+ });
+ // isDiscoveryLookupValue treats the redaction sentinel as absent, so the
+ // guard fails and the storage resource maps to null.
+ expect(toDiscoveryConfig(resource)).toBeNull();
+ });
+
+ it('rejects an explicit resourceId that is empty', () => {
+ const resource = baseResource({
+ type: 'storage',
+ discoveryTarget: discoveryTarget({
+ resourceType: 'agent',
+ agentId: 'a',
+ resourceId: '',
+ }),
+ });
+ expect(toDiscoveryConfig(resource)).toBeNull();
+ });
+ });
+});
+
+describe('toDiscoveryConfig — main switch (no usable explicit target)', () => {
+ describe('agent-family cases (agent / docker-host / pbs / pmg / k8s-cluster / k8s-node)', () => {
+ it('maps an agent resource to an agent config derived from its name', () => {
+ const resource = baseResource({ type: 'agent', name: 'node-a' });
+ expect(toDiscoveryConfig(resource)).toEqual({
+ resourceType: 'agent',
+ agentId: 'node-a',
+ resourceId: 'node-a',
+ hostname: 'node-a',
+ metadataKind: 'agent',
+ metadataId: 'node-a',
+ targetLabel: 'agent',
+ });
+ });
+
+ it('maps a docker-host resource through the shared agent case', () => {
+ const resource = baseResource({ type: 'docker-host', name: 'docker-1' });
+ const result = toDiscoveryConfig(resource);
+ expect(result?.resourceType).toBe('agent');
+ expect(result?.agentId).toBe('docker-1');
+ expect(result?.targetLabel).toBe('agent');
+ });
+
+ it('maps a pbs resource through the shared agent case', () => {
+ const resource = baseResource({ type: 'pbs', name: 'pbs-1' });
+ expect(toDiscoveryConfig(resource)?.resourceType).toBe('agent');
+ });
+
+ it('maps a k8s-cluster resource through the shared agent case', () => {
+ const resource = baseResource({ type: 'k8s-cluster', name: 'k8s-1' });
+ expect(toDiscoveryConfig(resource)?.resourceType).toBe('agent');
+ });
+
+ it("returns null when the agent lookup id is 'redacted by policy'", () => {
+ const resource = baseResource({
+ type: 'agent',
+ name: 'redacted by policy',
+ });
+ expect(toDiscoveryConfig(resource)).toBeNull();
+ });
+ });
+
+ describe('vm case', () => {
+ it('returns a vm config with resource.id as resourceId when no proxmox vmid is present', () => {
+ const resource = baseResource({ type: 'vm', id: 'vm-plain', name: 'vm-plain' });
+ expect(toDiscoveryConfig(resource)).toEqual({
+ resourceType: 'vm',
+ agentId: 'vm-plain',
+ resourceId: 'vm-plain',
+ hostname: 'vm-plain',
+ metadataKind: 'guest',
+ metadataId: 'vm-plain',
+ targetLabel: 'guest',
+ });
+ });
+
+ it('uses the proxmox vmid as resourceId when a vmware scope is overridden by proxmox coords', () => {
+ // hasVMwareScope is true (platformData.vmware), but proxmoxNodeName +
+ // vmidResourceId are both present, so the early-null guard is bypassed
+ // and the vm resolves against the proxmox coordinates.
+ const resource = baseResource({
+ type: 'vm',
+ id: 'vm-with-proxmox',
+ name: 'vm-with-proxmox',
+ proxmox: { nodeName: 'pve-1', vmid: 100 },
+ platformData: { vmware: { clusterName: 'vc-1' } },
+ });
+ const result = toDiscoveryConfig(resource);
+ expect(result?.resourceId).toBe('100');
+ expect(result?.agentId).toBe('pve-1');
+ expect(result?.resourceType).toBe('vm');
+ });
+
+ it('returns null when hasVMwareScope is true and there is no proxmox override', () => {
+ const resource = baseResource({
+ type: 'vm',
+ vmware: { clusterName: 'vc-1' } as Resource['vmware'],
+ });
+ expect(toDiscoveryConfig(resource)).toBeNull();
+ });
+
+ it("returns null when the workload agent id is 'redacted by policy'", () => {
+ const resource = baseResource({
+ type: 'vm',
+ name: 'redacted by policy',
+ });
+ expect(toDiscoveryConfig(resource)).toBeNull();
+ });
+ });
+
+ describe('system-container / oci-container cases', () => {
+ it('maps a system-container resource to a guest config', () => {
+ const resource = baseResource({ type: 'system-container', id: 'lxc-1', name: 'lxc-1' });
+ expect(toDiscoveryConfig(resource)).toEqual({
+ resourceType: 'system-container',
+ agentId: 'lxc-1',
+ resourceId: 'lxc-1',
+ hostname: 'lxc-1',
+ metadataKind: 'guest',
+ metadataId: 'lxc-1',
+ targetLabel: 'guest',
+ });
+ });
+
+ it('routes an oci-container resource through the shared system-container case', () => {
+ const resource = baseResource({ type: 'oci-container', id: 'oci-1', name: 'oci-1' });
+ const result = toDiscoveryConfig(resource);
+ expect(result?.resourceType).toBe('system-container');
+ expect(result?.targetLabel).toBe('guest');
+ });
+
+ it("returns null when the workload agent id is 'redacted by policy'", () => {
+ const resource = baseResource({
+ type: 'system-container',
+ name: 'redacted by policy',
+ });
+ expect(toDiscoveryConfig(resource)).toBeNull();
+ });
+ });
+
+ describe('app-container case', () => {
+ it('maps an app-container without docker metadata to a guest container config', () => {
+ const resource = baseResource({ type: 'app-container', id: 'c-1', name: 'c-1' });
+ expect(toDiscoveryConfig(resource)).toEqual({
+ resourceType: 'app-container',
+ agentId: 'c-1',
+ resourceId: 'c-1',
+ hostname: 'c-1',
+ metadataKind: 'guest',
+ metadataId: 'c-1',
+ targetLabel: 'container',
+ });
+ });
+
+ it('uses the docker container id and docker metadata when platformData.docker is populated', () => {
+ const resource = baseResource({
+ type: 'app-container',
+ id: 'c-docker',
+ name: 'c-docker',
+ platformData: {
+ docker: { hostSourceId: 'dhost', containerId: 'dcont', hostname: 'dhost-h' },
+ },
+ });
+ const result = toDiscoveryConfig(resource);
+ expect(result?.resourceId).toBe('dcont');
+ expect(result?.metadataKind).toBe('docker');
+ expect(result?.metadataId).toBe('dhost:container:dcont');
+ expect(result?.targetLabel).toBe('container');
+ });
+
+ it("returns null when the workload agent id is 'redacted by policy'", () => {
+ const resource = baseResource({
+ type: 'app-container',
+ name: 'redacted by policy',
+ });
+ expect(toDiscoveryConfig(resource)).toBeNull();
+ });
+ });
+
+ describe('pod / k8s-deployment / k8s-service cases', () => {
+ it('maps a bare pod to a workload config with resource.id as resourceId', () => {
+ const resource = baseResource({ type: 'pod', id: 'pod-1', name: 'pod-1' });
+ expect(toDiscoveryConfig(resource)).toEqual({
+ resourceType: 'pod',
+ agentId: 'pod-1',
+ resourceId: 'pod-1',
+ hostname: 'pod-1',
+ metadataKind: 'guest',
+ metadataId: 'pod-1',
+ targetLabel: 'workload',
+ });
+ });
+
+ it('uses the kubernetes podUid as resourceId when present', () => {
+ const resource = baseResource({
+ type: 'pod',
+ id: 'pod-uid',
+ name: 'pod-uid',
+ kubernetes: { podUid: 'uid-1' } as Resource['kubernetes'],
+ });
+ expect(toDiscoveryConfig(resource)?.resourceId).toBe('uid-1');
+ });
+
+ it('derives resourceId from namespace/podName when podUid is absent', () => {
+ const resource = baseResource({
+ type: 'pod',
+ id: 'pod-ns',
+ name: 'pod-ns',
+ kubernetes: { namespace: 'ns', podName: 'web' } as Resource['kubernetes'],
+ });
+ expect(toDiscoveryConfig(resource)?.resourceId).toBe('ns/web');
+ });
+
+ it('routes a k8s-deployment resource through the shared pod case', () => {
+ const resource = baseResource({
+ type: 'k8s-deployment',
+ id: 'dep-1',
+ name: 'dep-1',
+ });
+ const result = toDiscoveryConfig(resource);
+ expect(result?.resourceType).toBe('pod');
+ expect(result?.targetLabel).toBe('workload');
+ });
+
+ it("returns null when the workload agent id is 'redacted by policy'", () => {
+ const resource = baseResource({
+ type: 'pod',
+ name: 'redacted by policy',
+ });
+ expect(toDiscoveryConfig(resource)).toBeNull();
+ });
+ });
+
+ describe('default case', () => {
+ it('returns null for an unmapped resource type', () => {
+ expect(toDiscoveryConfig(baseResource({ type: 'storage' }))).toBeNull();
+ });
+
+ it('returns null for a jail resource type', () => {
+ expect(toDiscoveryConfig(baseResource({ type: 'jail', name: 'jail-1' }))).toBeNull();
+ });
+ });
+});
diff --git a/frontend-modern/src/components/Settings/__tests__/connectionsTableModel.branchcov.test.ts b/frontend-modern/src/components/Settings/__tests__/connectionsTableModel.branchcov.test.ts
new file mode 100644
index 0000000000..2eb78d7a56
--- /dev/null
+++ b/frontend-modern/src/components/Settings/__tests__/connectionsTableModel.branchcov.test.ts
@@ -0,0 +1,502 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type {
+ Connection,
+ ConnectionState,
+ ConnectionFleetConfigDriftStatus,
+ ConnectionFleetCredentialHealthStatus,
+ ConnectionFleetGovernance,
+ ConnectionFleetRolloutStatus,
+} from '@/api/connections';
+import {
+ agentAttachmentProblem,
+ connectionAgentEndpointDisplay,
+ connectionAgentIdentitySummary,
+ connectionAgentVersionPresentation,
+ fleetGovernanceSignalsForConnection,
+ lastActivityTextFromLastSeen,
+ type FleetGovernanceSignal,
+ type FleetGovernanceSignalKey,
+ type FleetGovernanceSignalTone,
+} from '../connectionsTableModel';
+
+// ---- Fixtures ---------------------------------------------------------------
+// Mirrors the sibling coverage test so the private signal builders below are
+// driven through the single exported orchestrator (fleetGovernanceSignalsForConnection).
+
+const connectionFixture = (overrides: Partial<Connection> = {}): Connection => ({
+ id: 'agent:host-1',
+ type: 'agent',
+ name: 'host-1',
+ address: 'host-1',
+ state: 'active',
+ stateReason: '',
+ enabled: true,
+ surfaces: ['host'],
+ scope: { host: true },
+ lastSeen: '2026-04-23T12:00:00Z',
+ lastError: null,
+ source: 'agent',
+ capabilities: { supportsPause: false, supportsScope: false, supportsTest: false },
+ ...overrides,
+});
+
+const fleetFixture = (
+ overrides: Partial<ConnectionFleetGovernance> = {},
+): ConnectionFleetGovernance => ({
+ enrollmentState: 'enrolled',
+ livenessState: 'active',
+ versionDrift: 'current',
+ adapterHealth: 'healthy',
+ configRollout: 'reported',
+ credentialStatus: 'verified',
+ updateStatus: 'current',
+ remoteControl: 'disabled',
+ ...overrides,
+});
+
+const signalByKey = (
+ connection: Connection,
+ key: FleetGovernanceSignalKey,
+): FleetGovernanceSignal | undefined =>
+ fleetGovernanceSignalsForConnection(connection).find((signal) => signal.key === key);
+
+// The pinned instant every relative-age assertion is computed against.
+const PINNED_NOW = new Date('2026-07-11T12:00:00.000Z');
+
+// ---- lastActivityTextFromLastSeen ------------------------------------------
+
+describe('lastActivityTextFromLastSeen', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it.each([undefined, null, ''].map((value) => [value] as [string | null | undefined]))(
+ 'returns "No activity yet" for a falsy lastSeen (%s)',
+ (lastSeen) => {
+ vi.setSystemTime(PINNED_NOW);
+ expect(lastActivityTextFromLastSeen(lastSeen)).toBe('No activity yet');
+ },
+ );
+
+ it.each(['not-a-date', ' '] as const)(
+ 'returns "Unknown" for a truthy but unparseable lastSeen (%s)',
+ (lastSeen) => {
+ // A whitespace-only string is truthy, so it bypasses the !lastSeen guard
+ // and falls through to Date.parse -> NaN -> "Unknown".
+ vi.setSystemTime(PINNED_NOW);
+ expect(lastActivityTextFromLastSeen(lastSeen)).toBe('Unknown');
+ },
+ );
+
+ it('reports 0s ago for a timestamp at exactly the current instant', () => {
+ vi.setSystemTime(PINNED_NOW);
+ expect(lastActivityTextFromLastSeen('2026-07-11T12:00:00.000Z')).toBe('0s ago');
+ });
+
+ it('clamps a future timestamp to 0s ago instead of a negative age', () => {
+ vi.setSystemTime(PINNED_NOW);
+ expect(lastActivityTextFromLastSeen('2026-07-11T13:00:00.000Z')).toBe('0s ago');
+ });
+
+ it.each([
+ ['2026-07-11T11:59:30.000Z', '30s ago'],
+ ['2026-07-11T11:59:00.000Z', '1m ago'],
+ ['2026-07-11T11:55:00.000Z', '5m ago'],
+ ['2026-07-11T11:00:00.000Z', '1h ago'],
+ ['2026-07-11T09:00:00.000Z', '3h ago'],
+ ['2026-07-10T12:00:00.000Z', '1d ago'],
+ ['2026-07-08T12:00:00.000Z', '3d ago'],
+ ] as const satisfies ReadonlyArray<[string, string]>)(
+ 'formats %s as %s relative to the pinned now',
+ (lastSeen, expected) => {
+ vi.setSystemTime(PINNED_NOW);
+ expect(lastActivityTextFromLastSeen(lastSeen)).toBe(expected);
+ },
+ );
+});
+
+// ---- agentAttachmentProblem -------------------------------------------------
+
+describe('agentAttachmentProblem', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('appends the relative-age suffix for a stale agent with a known lastSeen', () => {
+ vi.setSystemTime(PINNED_NOW);
+ const problem = agentAttachmentProblem(
+ connectionFixture({
+ state: 'stale',
+ lastSeen: '2026-07-11T08:00:00.000Z',
+ stateReason: 'no keepalive',
+ }),
+ );
+ expect(problem).toEqual({
+ label: 'Agent offline · 4h ago',
+ detail: 'no keepalive',
+ tone: 'warning',
+ });
+ });
+
+ it('omits the suffix when lastSeen is null (No activity yet) and uses the fallback detail', () => {
+ vi.setSystemTime(PINNED_NOW);
+ const problem = agentAttachmentProblem(
+ connectionFixture({ state: 'stale', lastSeen: null, stateReason: '' }),
+ );
+ expect(problem?.label).toBe('Agent offline');
+ expect(problem?.detail).toBe(
+ 'The Pulse Agent on this host has not reported recently. Proxmox API metrics are unaffected.',
+ );
+ expect(problem?.tone).toBe('warning');
+ });
+
+ it('omits the suffix when lastSeen is unparseable (Unknown)', () => {
+ vi.setSystemTime(PINNED_NOW);
+ const problem = agentAttachmentProblem(
+ connectionFixture({ state: 'stale', lastSeen: 'garbage', stateReason: '' }),
+ );
+ expect(problem?.label).toBe('Agent offline');
+ });
+
+ it.each([
+ ['unreachable', 'Agent unreachable', 'Pulse cannot currently reach the agent on this host.', 'critical'],
+ ['unauthorized', 'Agent unauthorized', 'The Pulse Agent token is being rejected.', 'critical'],
+ ['pending', 'Agent pending first report', 'The Pulse Agent has not reported yet.', 'warning'],
+ ] as const satisfies ReadonlyArray<[ConnectionState, string, string, 'critical' | 'warning']>)(
+ 'uses the fallback detail for state %s when stateReason is empty',
+ (state, label, detail, tone) => {
+ vi.setSystemTime(PINNED_NOW);
+ expect(agentAttachmentProblem(connectionFixture({ state, stateReason: '' }))).toEqual({
+ label,
+ detail,
+ tone,
+ });
+ },
+ );
+
+ it.each([
+ ['unreachable', 'Agent unreachable'],
+ ['unauthorized', 'Agent unauthorized'],
+ ['pending', 'Agent pending first report'],
+ ] as const satisfies ReadonlyArray<[ConnectionState, string]>)(
+ 'uses the explicit stateReason for state %s when one is provided',
+ (state, label) => {
+ vi.setSystemTime(PINNED_NOW);
+ const problem = agentAttachmentProblem(
+ connectionFixture({ state, stateReason: 'explicit operator reason' }),
+ );
+ expect(problem?.label).toBe(label);
+ expect(problem?.detail).toBe('explicit operator reason');
+ },
+ );
+
+ it.each(['active', 'paused'] as const)('returns undefined for the non-problem state %s', (state) => {
+ vi.setSystemTime(PINNED_NOW);
+ expect(agentAttachmentProblem(connectionFixture({ state }))).toBeUndefined();
+ });
+});
+
+// ---- connectionAgentVersionPresentation -------------------------------------
+
+describe('connectionAgentVersionPresentation', () => {
+ it('renders the amber "Update available" badge when both versions and the flag are set', () => {
+ const presentation = connectionAgentVersionPresentation(
+ connectionFixture({
+ agentVersion: '6.0.0',
+ expectedAgentVersion: '6.0.3',
+ agentUpdateAvailable: true,
+ }),
+ );
+ expect(presentation).toMatchObject({
+ badgeLabel: 'Update available',
+ detail: '6.0.0 -> 6.0.3',
+ title: 'Pulse Agent update available: 6.0.0 -> 6.0.3',
+ });
+ expect(presentation?.badgeClassName).toContain('amber');
+ });
+
+ it('trims whitespace from both versions before composing the update detail', () => {
+ const presentation = connectionAgentVersionPresentation(
+ connectionFixture({
+ agentVersion: ' 6.0.0 ',
+ expectedAgentVersion: ' 6.0.3 ',
+ agentUpdateAvailable: true,
+ }),
+ );
+ expect(presentation?.detail).toBe('6.0.0 -> 6.0.3');
+ expect(presentation?.title).toBe('Pulse Agent update available: 6.0.0 -> 6.0.3');
+ });
+
+ it('falls through to the version-target badge when the flag is set but the current version is blank', () => {
+ // agentUpdateAvailable is true, but currentVersion trims to '' so the
+ // update branch short-circuits; the plain agent-version branch also needs
+ // a current version, so the expected-version ("Version target") branch wins.
+ const presentation = connectionAgentVersionPresentation(
+ connectionFixture({ agentVersion: ' ', expectedAgentVersion: '6.0.3', agentUpdateAvailable: true }),
+ );
+ expect(presentation?.badgeLabel).toBe('Version target');
+ expect(presentation?.detail).toBe('6.0.3');
+ });
+
+ it('renders the agent-version badge when the flag is set but the expected version is blank', () => {
+ const presentation = connectionAgentVersionPresentation(
+ connectionFixture({ agentVersion: '6.0.0', expectedAgentVersion: '', agentUpdateAvailable: true }),
+ );
+ expect(presentation?.badgeLabel).toBe('Agent version');
+ expect(presentation?.detail).toBe('6.0.0');
+ });
+
+ it('renders the neutral agent-version badge when no update is flagged', () => {
+ const presentation = connectionAgentVersionPresentation(
+ connectionFixture({ agentVersion: '6.0.0', expectedAgentVersion: '6.0.3', agentUpdateAvailable: false }),
+ );
+ expect(presentation).toMatchObject({ badgeLabel: 'Agent version', detail: '6.0.0' });
+ expect(presentation?.badgeClassName).not.toContain('amber');
+ });
+
+ it('renders the version-target badge when only the expected version is known', () => {
+ const presentation = connectionAgentVersionPresentation(
+ connectionFixture({ agentVersion: undefined, expectedAgentVersion: '6.0.3' }),
+ );
+ expect(presentation).toMatchObject({
+ badgeLabel: 'Version target',
+ detail: '6.0.3',
+ title: 'Pulse Agent target version 6.0.3',
+ });
+ });
+
+ it('returns null when neither version is present and no update is flagged', () => {
+ expect(
+ connectionAgentVersionPresentation(
+ connectionFixture({
+ agentVersion: undefined,
+ expectedAgentVersion: undefined,
+ agentUpdateAvailable: false,
+ }),
+ ),
+ ).toBeNull();
+ });
+
+ it('returns null when agentUpdateAvailable is unset and no versions are known', () => {
+ // agentUpdateAvailable is optional; undefined is falsy and must not surface a badge.
+ expect(
+ connectionAgentVersionPresentation(
+ connectionFixture({ agentVersion: undefined, expectedAgentVersion: undefined }),
+ ),
+ ).toBeNull();
+ });
+});
+
+// ---- connectionAgentEndpointDisplay (remaining branches) -------------------
+
+describe('connectionAgentEndpointDisplay (remaining branches)', () => {
+ it('skips a hostname that equals the name case-insensitively and falls through to a distinct address', () => {
+ const endpoint = connectionAgentEndpointDisplay(
+ connectionFixture({ name: 'Host-1', address: '10.0.0.7', agentIdentity: { hostname: 'host-1' } }),
+ );
+ // hostname 'host-1' lowercased equals name 'Host-1' lowercased -> skipped;
+ // address '10.0.0.7' is distinct -> returned.
+ expect(endpoint).toBe('10.0.0.7');
+ });
+
+ it('returns null when no reportIp, alias, hostname, or address is available', () => {
+ expect(
+ connectionAgentEndpointDisplay(
+ connectionFixture({ name: 'host-1', address: '', agentIdentity: undefined, hostAliases: [] }),
+ ),
+ ).toBeNull();
+ });
+});
+
+// ---- prettifyPlatform (private) via connectionAgentIdentitySummary ----------
+//
+// prettifyPlatform is module-private and only reachable through
+// connectionAgentHostProfileLabel -> connectionAgentIdentitySummary. An identity
+// carrying only `platform` (no hostProfile/osName/osVersion) reduces the summary
+// to the prettified platform value, exercising every switch arm.
+
+describe('prettifyPlatform (via connectionAgentIdentitySummary)', () => {
+ const platformOnly = (platform: string): Connection =>
+ connectionFixture({ agentIdentity: { platform } });
+
+ it.each([
+ ['linux', 'Linux'],
+ ['windows', 'Windows'],
+ ['darwin', 'macOS'],
+ ['macos', 'macOS'],
+ ['freebsd', 'FreeBSD'],
+ ] as const satisfies ReadonlyArray<[string, string]>)(
+ 'prettifies the canonical platform %s to %s',
+ (platform, expected) => {
+ expect(connectionAgentIdentitySummary(platformOnly(platform))).toBe(expected);
+ },
+ );
+
+ it('normalizes case before matching (LINUX -> Linux, macOS stays macOS)', () => {
+ expect(connectionAgentIdentitySummary(platformOnly('LINUX'))).toBe('Linux');
+ expect(connectionAgentIdentitySummary(platformOnly('macOS'))).toBe('macOS');
+ });
+
+ it('returns the trimmed original casing for an unknown platform (default switch arm)', () => {
+ // ' Arch Linux ' lowercases to 'arch linux' which is not a canonical
+ // case; the default arm returns the trimmed ORIGINAL casing.
+ expect(connectionAgentIdentitySummary(platformOnly(' Arch Linux '))).toBe('Arch Linux');
+ });
+
+ it.each(['', ' '])('returns null for a blank platform (%s)', (platform) => {
+ expect(connectionAgentIdentitySummary(platformOnly(platform))).toBeNull();
+ });
+
+ it('returns null when platform is undefined and no other identity field is set', () => {
+ expect(
+ connectionAgentIdentitySummary(connectionFixture({ agentIdentity: { platform: undefined } })),
+ ).toBeNull();
+ });
+});
+
+// ---- connectionAgentHostProfileLabel (private) via connectionAgentIdentitySummary
+
+describe('connectionAgentHostProfileLabel (via connectionAgentIdentitySummary)', () => {
+ it('returns the manifest family for a known host profile', () => {
+ expect(
+ connectionAgentIdentitySummary(connectionFixture({ agentIdentity: { hostProfile: 'unraid' } })),
+ ).toBe('Unraid');
+ });
+
+ it('resolves a host-profile alias token to its family', () => {
+ expect(
+ connectionAgentIdentitySummary(connectionFixture({ agentIdentity: { hostProfile: 'unraid-os' } })),
+ ).toBe('Unraid');
+ });
+
+ it('falls back to prettifyPlatform when the host profile is not in the manifest', () => {
+ // 'centos' has no manifest family and is not a canonical platform case, so
+ // the default arm of prettifyPlatform returns the trimmed value verbatim.
+ expect(
+ connectionAgentIdentitySummary(connectionFixture({ agentIdentity: { hostProfile: 'centos' } })),
+ ).toBe('centos');
+ });
+
+ it('combines the host-profile family with an os version when both are present', () => {
+ expect(
+ connectionAgentIdentitySummary(
+ connectionFixture({ agentIdentity: { hostProfile: 'unraid', osVersion: '7.1.0' } }),
+ ),
+ ).toBe('Unraid 7.1.0');
+ });
+
+ it('returns the osName alone when osVersion is missing and hostProfile is absent', () => {
+ // hostProfile is null here, so the summary cannot be coming from the
+ // hostProfile branch; this isolates the `if (osName) return osName` arm.
+ expect(
+ connectionAgentIdentitySummary(connectionFixture({ agentIdentity: { osName: 'Custom OS' } })),
+ ).toBe('Custom OS');
+ });
+
+ it('returns null when every identity field is blank', () => {
+ expect(
+ connectionAgentIdentitySummary(
+ connectionFixture({
+ agentIdentity: { platform: ' ', osName: '', osVersion: ' ', hostProfile: '' },
+ }),
+ ),
+ ).toBeNull();
+ });
+});
+
+// ---- configDriftSignal (private) via fleetGovernanceSignalsForConnection ----
+//
+// An explicit fleet.configDrift overrides the derived path, so passing
+// { status } with no reason exercises every switch case of configDriftSignal
+// AND the `state.reason || <fallback>` falsy arm for each.
+
+describe('configDriftSignal (via fleetGovernanceSignalsForConnection)', () => {
+ it.each([
+ ['current', 'Config current', 'Desired and applied configuration fingerprints match.', 'ok'],
+ ['drifted', 'Config drift', 'Desired and applied configuration fingerprints do not match.', 'warning'],
+ ['pending', 'Config pending', 'Pulse is waiting for applied configuration confirmation.', 'warning'],
+ ['paused', 'Config paused', 'Configuration rollout is paused for this source.', 'muted'],
+ ['unknown', 'Config unknown', 'Pulse does not yet have enough config fingerprint data.', 'warning'],
+ ['not-applicable', 'No config drift', 'This source is not governed by desired/applied config rollout.', 'muted'],
+ ] as const satisfies ReadonlyArray<
+ [ConnectionFleetConfigDriftStatus, string, string, FleetGovernanceSignalTone]
+ >)('uses the fallback detail when configDrift %s carries no reason', (status, label, detail, tone) => {
+ const signal = signalByKey(
+ connectionFixture({ fleet: fleetFixture({ configDrift: { status } }) }),
+ 'config-drift',
+ );
+ expect(signal).toMatchObject({ key: 'config-drift', label, detail, tone });
+ });
+
+ it('honours an explicit reason over the fallback copy (pending case)', () => {
+ const signal = signalByKey(
+ connectionFixture({
+ fleet: fleetFixture({ configDrift: { status: 'pending', reason: 'awaiting agent ack' } }),
+ }),
+ 'config-drift',
+ );
+ expect(signal?.detail).toBe('awaiting agent ack');
+ expect(signal?.tone).toBe('warning');
+ });
+});
+
+// ---- rolloutSignal (private) ------------------------------------------------
+
+describe('rolloutSignal (via fleetGovernanceSignalsForConnection)', () => {
+ it.each([
+ ['current', 'Rollout current', 'The rollout state is current.', 'ok'],
+ ['pending', 'Rollout pending', 'The staged rollout is waiting for confirmation.', 'warning'],
+ ['paused', 'Rollout paused', 'The staged rollout is paused.', 'warning'],
+ ['blocked', 'Rollout blocked', 'The rollout is blocked by the current connection state.', 'critical'],
+ ['unknown', 'Rollout unknown', 'Pulse has not classified staged rollout state yet.', 'warning'],
+ ['not-applicable', 'No rollout', 'This source does not use staged rollout control.', 'muted'],
+ ] as const satisfies ReadonlyArray<
+ [ConnectionFleetRolloutStatus, string, string, FleetGovernanceSignalTone]
+ >)('uses the fallback detail when rollout %s carries no reason', (status, label, detail, tone) => {
+ const signal = signalByKey(
+ connectionFixture({ fleet: fleetFixture({ rollout: { status } }) }),
+ 'rollout',
+ );
+ expect(signal).toMatchObject({ key: 'rollout', label, detail, tone });
+ });
+
+ it('honours an explicit reason over the fallback copy (pending case)', () => {
+ const signal = signalByKey(
+ connectionFixture({
+ fleet: fleetFixture({ rollout: { status: 'pending', reason: 'canary batch paused' } }),
+ }),
+ 'rollout',
+ );
+ expect(signal?.detail).toBe('canary batch paused');
+ expect(signal?.tone).toBe('warning');
+ });
+});
+
+// ---- credentialHealthSignal (private) ---------------------------------------
+//
+// credentialHealthSignal emits fixed detail copy (no reason fallback). The
+// sibling coverage test already covers verified/invalid/expired/paused/unknown;
+// these cover the two remaining statuses.
+
+describe('credentialHealthSignal (via fleetGovernanceSignalsForConnection)', () => {
+ it.each([
+ ['expiring', 'Credentials expiring', 'The credential is approaching its configured expiration.', 'warning'],
+ ['not-applicable', 'No credentials', 'This source does not use a stored credential path.', 'muted'],
+ ] as const satisfies ReadonlyArray<
+ [ConnectionFleetCredentialHealthStatus, string, string, FleetGovernanceSignalTone]
+ >)('maps credential-health status %s to its fixed signal', (status, label, detail, tone) => {
+ const signal = signalByKey(
+ connectionFixture({ fleet: fleetFixture({ credentialHealth: { status } }) }),
+ 'credential-health',
+ );
+ expect(signal).toMatchObject({ key: 'credential-health', label, detail, tone });
+ });
+});
diff --git a/frontend-modern/src/components/Settings/__tests__/settingsNavigationModel.branchcov.test.ts b/frontend-modern/src/components/Settings/__tests__/settingsNavigationModel.branchcov.test.ts
new file mode 100644
index 0000000000..f16e7781cb
--- /dev/null
+++ b/frontend-modern/src/components/Settings/__tests__/settingsNavigationModel.branchcov.test.ts
@@ -0,0 +1,305 @@
+/**
+ * Branch-coverage tests for settingsNavigationModel.
+ *
+ * Focuses exclusively on branches NOT already exercised by the sibling
+ * `settingsRouting.test.ts` suite, for these target functions:
+ * - deriveTabFromQuery (exported)
+ * - deriveTabFromPath (exported)
+ * - isRouteableSettingsPath (exported)
+ * - isRouteableSettingsLocation (exported)
+ * - normalizeSettingsPath (NOT exported — a module-local const, exercised
+ * indirectly through resolveCanonicalSettingsPath
+ * and isRouteableSettingsPath, which are the
+ * closest exported callers)
+ */
+import { describe, expect, it } from 'vitest';
+import {
+ DEFAULT_SETTINGS_TAB,
+ deriveTabFromPath,
+ deriveTabFromQuery,
+ isRouteableSettingsLocation,
+ isRouteableSettingsPath,
+ resolveCanonicalSettingsPath,
+ type SettingsTab,
+} from '../settingsNavigationModel';
+
+// ---- deriveTabFromQuery: uncovered switch arms -----------------------------
+// The sibling suite already covers the `infrastructure`, `availability`,
+// `monitoring-availability`, `system-ai`, `patrol`, `assistant`, `discovery`,
+// `system-relay`, `system-billing`, `diagnostics`, `reporting`, `logs`,
+// `system-recovery`, `organization-overview`, `organization-billing`,
+// `security-overview`, `data-handling`, `resource-privacy` cases and the OAuth
+// callback + unknown/default arms. Here we cover every remaining switch case.
+
+describe('deriveTabFromQuery — uncovered switch cases', () => {
+ const cases: Array<[string, SettingsTab]> = [
+ ['?tab=system-updates', 'system-updates'],
+ ['?tab=system-network', 'system-network'],
+ ['?tab=system-general', 'system-general'],
+ ['?tab=pulse-intelligence', 'system-ai'],
+ ['?tab=provider-models', 'system-ai'],
+ ['?tab=provider', 'system-ai'],
+ ['?tab=system-ai-patrol', 'system-ai-patrol'],
+ ['?tab=system-ai-assistant', 'system-ai-assistant'],
+ // NOTE: `system-ai-discovery` and `discovery` intentionally map to
+ // `system-ai-assistant` here (see GLM_REPORT.md suspected bug).
+ ['?tab=system-ai-discovery', 'system-ai-assistant'],
+ ['?tab=support-diagnostics', 'support-diagnostics'],
+ ['?tab=support-reporting', 'support-reporting'],
+ ['?tab=support-logs', 'support-logs'],
+ ['?tab=api', 'api'],
+ ['?tab=organization-access', 'organization-access'],
+ ['?tab=organization-sharing', 'organization-sharing'],
+ ['?tab=organization-billing-admin', 'organization-billing-admin'],
+ ['?tab=security-data-handling', 'security-data-handling'],
+ ['?tab=security-auth', 'security-auth'],
+ ['?tab=security-sso', 'security-sso'],
+ ['?tab=security-roles', 'security-roles'],
+ ['?tab=security-users', 'security-users'],
+ ['?tab=security-audit', 'security-audit'],
+ ['?tab=security-webhooks', 'security-webhooks'],
+ ];
+
+ for (const [query, expectedTab] of cases) {
+ it(`maps ${query} to the '${expectedTab}' tab`, () => {
+ expect(deriveTabFromQuery(query)).toBe(expectedTab);
+ });
+ }
+});
+
+// ---- deriveTabFromQuery: guard / normalization branches --------------------
+
+describe('deriveTabFromQuery — guard and normalization branches', () => {
+ it('returns null for an empty search string (no tab param)', () => {
+ expect(deriveTabFromQuery('')).toBeNull();
+ });
+
+ it('returns null when the search carries no tab parameter', () => {
+ expect(deriveTabFromQuery('?foo=bar&baz=qux')).toBeNull();
+ });
+
+ it('returns null when the tab parameter value is empty', () => {
+ expect(deriveTabFromQuery('?tab=')).toBeNull();
+ });
+
+ it('returns null when the tab parameter is only whitespace', () => {
+ expect(deriveTabFromQuery('?tab= ')).toBeNull();
+ });
+
+ it('lowercases the tab value before matching (case-insensitive)', () => {
+ expect(deriveTabFromQuery('?tab=SYSTEM-AI')).toBe('system-ai');
+ });
+
+ it('trims surrounding whitespace from the tab value before matching', () => {
+ expect(deriveTabFromQuery('?tab= system-ai ')).toBe('system-ai');
+ });
+
+ it('honors the OAuth-callback guard ahead of an otherwise-valid tab', () => {
+ // isAISettingsOAuthCallbackQuery(search) short-circuits to 'system-ai'
+ // even when a different tab is also present.
+ expect(deriveTabFromQuery('?ai_oauth_success=true&tab=organization-overview')).toBe(
+ 'system-ai',
+ );
+ });
+
+ it('honors the OAuth-error guard ahead of an otherwise-valid tab', () => {
+ expect(deriveTabFromQuery('?ai_oauth_error=denied&tab=security-auth')).toBe('system-ai');
+ });
+});
+
+// ---- deriveTabFromPath: uncovered path arms --------------------------------
+// The sibling suite already covers the organization access/sharing/billing and
+// the billing plan/usage subroutes plus support diagnostics/reporting/logs.
+// Here we cover every remaining path-prefix / includes arm and the fallback.
+
+describe('deriveTabFromPath — uncovered path arms', () => {
+ const cases: Array<[string, SettingsTab]> = [
+ ['/settings', DEFAULT_SETTINGS_TAB],
+ ['/settings/infrastructure', 'infrastructure-systems'],
+ ['/settings/monitoring/availability', 'monitoring-availability'],
+ ['/settings/pulse-intelligence/patrol', 'system-ai-patrol'],
+ ['/settings/pulse-intelligence/assistant', 'system-ai-assistant'],
+ // NOTE: the discovery route canonicalizes to the *assistant* path today
+ // (resolveCanonicalSettingsPath maps PULSE_INTELLIGENCE_DISCOVERY_PREFIX to
+ // settingsTabPath('system-ai-assistant')), so deriveTabFromPath observes
+ // 'system-ai-assistant'. See GLM_REPORT.md suspected bug #1.
+ ['/settings/pulse-intelligence/discovery', 'system-ai-assistant'],
+ ['/settings/pulse-intelligence/provider', 'system-ai'],
+ // Legacy /settings/system-ai canonicalizes to the provider prefix.
+ ['/settings/system-ai', 'system-ai'],
+ ['/settings/system-general', 'system-general'],
+ ['/settings/system-network', 'system-network'],
+ ['/settings/system-updates', 'system-updates'],
+ ['/settings/system-recovery', 'system-recovery'],
+ ['/settings/system-relay', 'system-relay'],
+ // SUPPORT_PREFIX exact-value arm collapses to diagnostics.
+ ['/settings/support', 'support-diagnostics'],
+ ['/settings/security/api', 'api'],
+ ['/settings/security-overview', 'security-overview'],
+ ['/settings/security-data-handling', 'security-data-handling'],
+ ['/settings/security-auth', 'security-auth'],
+ ['/settings/security-sso', 'security-sso'],
+ ['/settings/security-roles', 'security-roles'],
+ ['/settings/security-users', 'security-users'],
+ ['/settings/security-audit', 'security-audit'],
+ ['/settings/security-webhooks', 'security-webhooks'],
+ ['/settings/organization/billing-admin', 'organization-billing-admin'],
+ ];
+
+ for (const [path, expectedTab] of cases) {
+ it(`maps ${path} to the '${expectedTab}' tab`, () => {
+ expect(deriveTabFromPath(path)).toBe(expectedTab);
+ });
+ }
+
+ it('falls back to the default tab for an unrecognized settings path', () => {
+ expect(deriveTabFromPath('/settings/unknown')).toBe(DEFAULT_SETTINGS_TAB);
+ });
+
+ it('falls back to the default tab for a non-settings path', () => {
+ // resolveCanonicalSettingsPath returns null -> the normalizeSettingsPath
+ // fallback is used -> no arm matches -> default tab.
+ expect(deriveTabFromPath('/totally/elsewhere')).toBe(DEFAULT_SETTINGS_TAB);
+ });
+
+ it("matches the loose '/settings/system-ai' includes arm for an uncanonicalized path", () => {
+ // '/settings/system-ai-foo' is not retired and not canonicalized, so it
+ // passes through resolveCanonicalSettingsPath unchanged and then hits the
+ // broad `canonicalPath.includes('/settings/system-ai')` arm.
+ expect(deriveTabFromPath('/settings/system-ai-foo')).toBe('system-ai');
+ });
+});
+
+// ---- normalizeSettingsPath (indirect, via exported callers) ----------------
+// normalizeSettingsPath is a module-local const and is not exported. Its three
+// branches (empty/falsy -> '/settings'; trailing-slash strip; passthrough) are
+// observed through resolveCanonicalSettingsPath and isRouteableSettingsPath.
+
+describe('normalizeSettingsPath (exercised via resolveCanonicalSettingsPath)', () => {
+ it("normalizes an empty string to '/settings' before canonical resolution", () => {
+ // '' trims to '' -> '/settings' -> resolved to the default tab path.
+ expect(resolveCanonicalSettingsPath('')).toBe('/settings/infrastructure');
+ // Equivalent to passing '/settings' directly.
+ expect(resolveCanonicalSettingsPath('')).toBe(resolveCanonicalSettingsPath('/settings'));
+ });
+
+ it("defends against a null runtime input by treating it as '' (the `path || ''` arm)", () => {
+ expect(resolveCanonicalSettingsPath(null as unknown as string)).toBe('/settings/infrastructure');
+ });
+
+ it("defends against an undefined runtime input by treating it as '' (the `path || ''` arm)", () => {
+ expect(resolveCanonicalSettingsPath(undefined as unknown as string)).toBe(
+ '/settings/infrastructure',
+ );
+ });
+
+ it('strips a single trailing slash from a settings path', () => {
+ expect(resolveCanonicalSettingsPath('/settings/system-general/')).toBe(
+ '/settings/system-general',
+ );
+ });
+
+ it('strips multiple trailing slashes from a settings path', () => {
+ expect(resolveCanonicalSettingsPath('/settings/system-general//')).toBe(
+ '/settings/system-general',
+ );
+ });
+
+ it("does not strip a lone '/' (length === 1) and therefore resolves it to null", () => {
+ // '/' has length 1 so the `length > 1 && endsWith('/')` arm is skipped;
+ // the value stays '/', which is neither '/settings' nor under '/settings/'.
+ expect(resolveCanonicalSettingsPath('/')).toBeNull();
+ });
+});
+
+describe('normalizeSettingsPath (exercised via isRouteableSettingsPath)', () => {
+ it("treats an empty path as routeable because it normalizes to '/settings'", () => {
+ expect(isRouteableSettingsPath('')).toBe(true);
+ });
+
+ it('treats a trailing-slash routeable path as routeable after normalization', () => {
+ expect(isRouteableSettingsPath('/settings/system-general/')).toBe(true);
+ });
+});
+
+// ---- isRouteableSettingsPath: uncovered branches ---------------------------
+
+describe('isRouteableSettingsPath — uncovered branches', () => {
+ it('returns false for a non-settings path (canonical resolution is null)', () => {
+ // Covers the `canonicalPath ? ROUTEABLE_SETTINGS_PATHS.has(...) : false`
+ // false arm driven by a null canonical resolution.
+ expect(isRouteableSettingsPath('/totally/elsewhere')).toBe(false);
+ });
+
+ it('returns true for the monitoring prefix which canonicalizes to the availability path', () => {
+ // '/settings/monitoring' resolves to '/settings/monitoring/availability',
+ // which is in the routeable set — exercises canonical-resolve-then-check.
+ expect(isRouteableSettingsPath('/settings/monitoring')).toBe(true);
+ });
+});
+
+// ---- isRouteableSettingsLocation: uncovered branches -----------------------
+// The sibling suite covers the infra `?add=agent`(true)/`?add=availability`
+// (false) and availability `?add=target`(true)/`?add=availability`(false)
+// pairs. Here we cover the default-search arm, the short-circuit-false arm, the
+// remaining infra/availability guard arms, and the availability kind branches.
+
+describe('isRouteableSettingsLocation — uncovered branches', () => {
+ it('defaults the search argument to an empty string (routeable, no add guard)', () => {
+ expect(isRouteableSettingsLocation('/settings/infrastructure')).toBe(true);
+ });
+
+ it('short-circuits to false when the path is not routeable, regardless of search', () => {
+ expect(isRouteableSettingsLocation('/totally/elsewhere', '?add=agent')).toBe(false);
+ });
+
+ it('short-circuits to false for a retired settings path', () => {
+ expect(isRouteableSettingsLocation('/settings/workloads', '')).toBe(false);
+ });
+
+ it('stays routeable on the infrastructure path with a non-add query parameter', () => {
+ // params.has('add') is false -> the infrastructure add guard is skipped.
+ expect(isRouteableSettingsLocation('/settings/infrastructure', '?agentUpdates=1')).toBe(true);
+ });
+
+ it('stays routeable on the infrastructure path with a recognized add step', () => {
+ // deriveAddStepFromSearch('?add=pve') === 'pve' (not null) -> guard skipped.
+ expect(isRouteableSettingsLocation('/settings/infrastructure', '?add=pve')).toBe(true);
+ });
+
+ it('rejects the infrastructure path when the add step is unrecognized', () => {
+ // deriveAddStepFromSearch('?add=bogus') === null -> infra guard returns false.
+ expect(isRouteableSettingsLocation('/settings/infrastructure', '?add=bogus')).toBe(false);
+ });
+
+ it('stays routeable on the availability path with no add parameter', () => {
+ expect(isRouteableSettingsLocation('/settings/monitoring/availability', '')).toBe(true);
+ });
+
+ it('rejects the availability path when add is present but not the target value', () => {
+ // shouldOpenAvailabilityTargetAddDialog is false because add !== 'target'.
+ expect(isRouteableSettingsLocation('/settings/monitoring/availability', '?add=foo')).toBe(
+ false,
+ );
+ });
+
+ it('rejects the availability path when add=target but the target kind is invalid', () => {
+ // targetKind 'bogus' normalizes to undefined -> shouldOpen...() false.
+ expect(
+ isRouteableSettingsLocation(
+ '/settings/monitoring/availability',
+ '?add=target&targetKind=bogus',
+ ),
+ ).toBe(false);
+ });
+
+ it('stays routeable on the availability path when add=target and the kind is valid', () => {
+ // targetKind 'machine' is valid -> shouldOpen...() true -> guard skipped.
+ expect(
+ isRouteableSettingsLocation(
+ '/settings/monitoring/availability',
+ '?add=target&targetKind=machine',
+ ),
+ ).toBe(true);
+ });
+});
diff --git a/frontend-modern/src/components/SetupWizard/__tests__/setupCompletionModel.branchcov.test.ts b/frontend-modern/src/components/SetupWizard/__tests__/setupCompletionModel.branchcov.test.ts
new file mode 100644
index 0000000000..1f6d5658b2
--- /dev/null
+++ b/frontend-modern/src/components/SetupWizard/__tests__/setupCompletionModel.branchcov.test.ts
@@ -0,0 +1,484 @@
+import { beforeEach, describe, expect, it } from 'vitest';
+import { DEFAULT_LOCALE, setActiveLocale } from '@/i18n';
+import type { Resource } from '@/types/resource';
+import {
+ buildSetupCompletionConnectedSystems,
+ type ConnectedSetupSystem,
+} from '../setupCompletionModel';
+
+type ResourceSeed = Partial<Resource> & Pick<Resource, 'id' | 'type'>;
+
+const makeResource = (seed: ResourceSeed): Resource => ({
+ name: '',
+ displayName: '',
+ platformId: '',
+ platformType: 'agent',
+ sourceType: 'agent',
+ status: 'online',
+ lastSeen: 0,
+ ...seed,
+});
+
+const namesOf = (systems: readonly ConnectedSetupSystem[]): string[] => systems.map((s) => s.name);
+const idsOf = (systems: readonly ConnectedSetupSystem[]): string[] => systems.map((s) => s.id);
+
+describe('setupCompletionModel branch coverage', () => {
+ beforeEach(() => {
+ setActiveLocale(DEFAULT_LOCALE);
+ });
+
+ describe('isSetupCompletionInfrastructureResource (via inclusion/exclusion)', () => {
+ it('admits agent resources with an agent facet onto the agent connection path', () => {
+ const systems = buildSetupCompletionConnectedSystems([
+ makeResource({ id: 'agent-1', type: 'agent', name: 'Tower', agent: { agentId: 'agent-1' } }),
+ ]);
+
+ expect(systems).toHaveLength(1);
+ expect(systems[0]!.connectionPath).toBe('agent');
+ expect(systems[0]!.name).toBe('Tower');
+ expect(systems[0]!.typeLabel).toBe('Agent');
+ expect(systems[0]!.host).toBe('Tower');
+ });
+
+ it('admits pbs resources onto the api connection path regardless of agent facet', () => {
+ const systems = buildSetupCompletionConnectedSystems([
+ makeResource({
+ id: 'pbs-1',
+ type: 'pbs',
+ name: 'pbs-node',
+ displayName: 'PBS Main',
+ platformId: 'pbs-1',
+ }),
+ ]);
+
+ expect(systems).toHaveLength(1);
+ expect(systems[0]!.connectionPath).toBe('api');
+ expect(systems[0]!.id).toBe('pbs-1');
+ expect(systems[0]!.name).toBe('PBS Main');
+ expect(systems[0]!.typeLabel).toBe('Proxmox Backup Server');
+ });
+
+ it('admits pmg resources onto the api connection path', () => {
+ const systems = buildSetupCompletionConnectedSystems([
+ makeResource({
+ id: 'pmg-1',
+ type: 'pmg',
+ name: 'pmg-node',
+ displayName: 'PMG Main',
+ platformId: 'pmg-1',
+ }),
+ ]);
+
+ expect(systems).toHaveLength(1);
+ expect(systems[0]!.connectionPath).toBe('api');
+ expect(systems[0]!.typeLabel).toBe('Proxmox Mail Gateway');
+ });
+
+ it('drops non-infrastructure resource types (vm) entirely', () => {
+ const vm = makeResource({ id: 'vm-1', type: 'vm', name: 'myvm' });
+ expect(buildSetupCompletionConnectedSystems([vm])).toEqual([]);
+
+ const mixed = buildSetupCompletionConnectedSystems([
+ vm,
+ makeResource({ id: 'agent-1', type: 'agent', name: 'Tower', agent: { agentId: 'agent-1' } }),
+ ]);
+ expect(namesOf(mixed)).toEqual(['Tower']);
+ });
+ });
+
+ describe('getSetupCompletionPlatformKey / getSetupCompletionPlatformLabel (typeLabel)', () => {
+ it('maps pbs type to the proxmox-pbs manifest label', () => {
+ const systems = buildSetupCompletionConnectedSystems([
+ makeResource({
+ id: 'pbs-1',
+ type: 'pbs',
+ name: 'pbs',
+ displayName: 'PBS Main',
+ platformId: 'pbs-1',
+ platformType: 'agent',
+ }),
+ ]);
+ expect(systems[0]!.typeLabel).toBe('Proxmox Backup Server');
+ });
+
+ it('maps pmg type to the proxmox-pmg manifest label', () => {
+ const systems = buildSetupCompletionConnectedSystems([
+ makeResource({
+ id: 'pmg-1',
+ type: 'pmg',
+ name: 'pmg',
+ displayName: 'PMG Main',
+ platformId: 'pmg-1',
+ platformType: 'agent',
+ }),
+ ]);
+ expect(systems[0]!.typeLabel).toBe('Proxmox Mail Gateway');
+ });
+
+ it('maps a truenas agent (platformType truenas) to the truenas key and api path', () => {
+ const systems = buildSetupCompletionConnectedSystems([
+ makeResource({
+ id: 'tn-1',
+ type: 'agent',
+ platformType: 'truenas',
+ name: 'tn',
+ displayName: 'TrueNAS Main',
+ platformId: 'tn-1',
+ sourceType: 'api',
+ identity: { hostname: 'tn-host' },
+ }),
+ ]);
+ expect(systems[0]!.typeLabel).toBe('TrueNAS');
+ expect(systems[0]!.connectionPath).toBe('api');
+ expect(systems[0]!.host).toBe('tn-host');
+ });
+
+ it('passes a known platformType (vmware-vsphere) through to the manifest label', () => {
+ const systems = buildSetupCompletionConnectedSystems([
+ makeResource({
+ id: 'vc-1',
+ type: 'agent',
+ platformType: 'vmware-vsphere',
+ name: 'vcsa',
+ displayName: 'vCenter',
+ platformId: 'vc-1',
+ sourceType: 'api',
+ }),
+ ]);
+ expect(systems[0]!.typeLabel).toBe('VMware vSphere');
+ expect(systems[0]!.connectionPath).toBe('api');
+ });
+
+ it('falls back to the Agent typeLabel when platformType is absent from the manifest', () => {
+ const systems = buildSetupCompletionConnectedSystems([
+ makeResource({
+ id: 'gen-1',
+ type: 'agent',
+ platformType: 'generic',
+ name: 'box',
+ agent: { agentId: 'gen-1' },
+ }),
+ ]);
+ expect(systems[0]!.typeLabel).toBe('Agent');
+ expect(systems[0]!.connectionPath).toBe('agent');
+ });
+
+ it('falls back to the Agent typeLabel when platformType is empty (null key)', () => {
+ const emptyPlatformType: Resource = {
+ ...makeResource({
+ id: 'emptypt-1',
+ type: 'agent',
+ name: 'box',
+ agent: { agentId: 'emptypt-1' },
+ }),
+ platformType: '' as Resource['platformType'],
+ };
+
+ const systems = buildSetupCompletionConnectedSystems([emptyPlatformType]);
+ expect(systems).toHaveLength(1);
+ expect(systems[0]!.typeLabel).toBe('Agent');
+ });
+ });
+
+ describe('getConnectedSetupSystemHost fallback chain', () => {
+ it('uses the canonical hostname from identity when present (happy path)', () => {
+ const systems = buildSetupCompletionConnectedSystems([
+ makeResource({
+ id: 'h-1',
+ type: 'agent',
+ name: 'raw',
+ platformId: 'h-1',
+ agent: { agentId: 'h-1' },
+ identity: { hostname: 'real-host.example' },
+ }),
+ ]);
+ expect(systems[0]!.host).toBe('real-host.example');
+ });
+
+ it('falls back to platformData.proxmox.instance when no preferred hostname exists', () => {
+ const systems = buildSetupCompletionConnectedSystems([
+ makeResource({
+ id: 'pve-1',
+ type: 'agent',
+ platformType: 'agent',
+ name: '',
+ platformId: '',
+ agent: { agentId: 'pve-1' },
+ platformData: { proxmox: { instance: 'pve-node-1' } },
+ }),
+ ]);
+ expect(systems[0]!.host).toBe('pve-node-1');
+ expect(systems[0]!.id).toBe('pve-1');
+ expect(systems[0]!.name).toBe('agent:pve-1');
+ });
+
+ it('falls back to platformData.truenas.hostname when no preferred hostname exists', () => {
+ const systems = buildSetupCompletionConnectedSystems([
+ makeResource({
+ id: 'tn-host-1',
+ type: 'agent',
+ platformType: 'truenas',
+ name: '',
+ platformId: '',
+ platformData: { truenas: { hostname: 'tn-array-host' } },
+ }),
+ ]);
+ expect(systems[0]!.host).toBe('tn-array-host');
+ expect(systems[0]!.connectionPath).toBe('api');
+ });
+
+ it('falls back to platformData.vmware.hostname when no preferred hostname exists', () => {
+ const systems = buildSetupCompletionConnectedSystems([
+ makeResource({
+ id: 'vc-host-1',
+ type: 'agent',
+ platformType: 'vmware-vsphere',
+ name: '',
+ platformId: '',
+ platformData: { vmware: { hostname: 'vc-array-host' } },
+ }),
+ ]);
+ expect(systems[0]!.host).toBe('vc-array-host');
+ });
+
+ it('returns an empty host string when nothing is resolvable', () => {
+ const systems = buildSetupCompletionConnectedSystems([
+ makeResource({
+ id: 'empty-1',
+ type: 'agent',
+ platformType: 'agent',
+ name: '',
+ platformId: '',
+ agent: { agentId: 'empty-1' },
+ }),
+ ]);
+ expect(systems[0]!.host).toBe('');
+ expect(systems[0]!.connectionPath).toBe('agent');
+ });
+ });
+
+ describe('toConnectedSetupSystem (id/name/connectionPath/null arms)', () => {
+ it('returns null for an agent resource with neither api nor agent connection evidence', () => {
+ const orphan = makeResource({
+ id: 'orphan-1',
+ type: 'agent',
+ platformType: 'agent',
+ name: 'orphan',
+ });
+ expect(buildSetupCompletionConnectedSystems([orphan])).toEqual([]);
+ });
+
+ it('keeps a connected sibling while dropping the unconnected orphan', () => {
+ const systems = buildSetupCompletionConnectedSystems([
+ makeResource({
+ id: 'orphan-1',
+ type: 'agent',
+ platformType: 'agent',
+ name: 'orphan',
+ }),
+ makeResource({
+ id: 'agent-1',
+ type: 'agent',
+ platformType: 'agent',
+ name: 'Tower',
+ agent: { agentId: 'agent-1' },
+ }),
+ ]);
+ expect(namesOf(systems)).toEqual(['Tower']);
+ });
+
+ it('resolves id from getActionableAgentIdFromResource when platformId is empty', () => {
+ const systems = buildSetupCompletionConnectedSystems([
+ makeResource({
+ id: 'res-id',
+ type: 'agent',
+ platformType: 'agent',
+ name: '',
+ platformId: '',
+ agent: { agentId: 'agent-xyz' },
+ }),
+ ]);
+ expect(systems[0]!.id).toBe('agent-xyz');
+ });
+
+ it('resolves id from resource.id when neither platformId nor agent id is set', () => {
+ const systems = buildSetupCompletionConnectedSystems([
+ makeResource({
+ id: 'tn-fallback',
+ type: 'agent',
+ platformType: 'truenas',
+ name: '',
+ platformId: '',
+ platformData: { truenas: { hostname: 'tn-h' } },
+ }),
+ ]);
+ expect(systems[0]!.id).toBe('tn-fallback');
+ });
+
+ it('prefers displayName for the system name', () => {
+ const systems = buildSetupCompletionConnectedSystems([
+ makeResource({
+ id: 'd-1',
+ type: 'agent',
+ platformType: 'agent',
+ name: 'rawname',
+ displayName: 'Pretty Name',
+ agent: { agentId: 'd-1' },
+ }),
+ ]);
+ expect(systems[0]!.name).toBe('Pretty Name');
+ });
+
+ it('falls back to resource.name when displayName is empty', () => {
+ const systems = buildSetupCompletionConnectedSystems([
+ makeResource({
+ id: 'n-1',
+ type: 'agent',
+ platformType: 'agent',
+ name: 'myhost',
+ agent: { agentId: 'n-1' },
+ }),
+ ]);
+ expect(systems[0]!.name).toBe('myhost');
+ });
+ });
+
+ describe('buildSetupCompletionConnectedSystems (dedupe, merge, sort)', () => {
+ it('returns an empty array for an empty input list', () => {
+ expect(buildSetupCompletionConnectedSystems([])).toEqual([]);
+ });
+
+ it('keeps the first entry when two api systems share a key and no merge rule fires', () => {
+ const systems = buildSetupCompletionConnectedSystems([
+ makeResource({
+ id: 'vc-a',
+ type: 'agent',
+ platformType: 'vmware-vsphere',
+ name: 'vcsa-a',
+ displayName: 'First VC',
+ platformId: 'shared-vc',
+ sourceType: 'api',
+ }),
+ makeResource({
+ id: 'vc-b',
+ type: 'agent',
+ platformType: 'vmware-vsphere',
+ name: 'vcsa-b',
+ displayName: 'Second VC',
+ platformId: 'shared-vc',
+ sourceType: 'api',
+ }),
+ ]);
+ expect(systems).toHaveLength(1);
+ expect(systems[0]!.name).toBe('First VC');
+ expect(systems[0]!.connectionPath).toBe('api');
+ });
+
+ it('upgrades an agent entry to api and replaces an Unknown name with a real one', () => {
+ const systems = buildSetupCompletionConnectedSystems([
+ makeResource({
+ id: 'a-unk',
+ type: 'agent',
+ platformType: 'agent',
+ name: 'Unknown',
+ platformId: 'shared-key',
+ agent: { agentId: 'a-unk' },
+ }),
+ makeResource({
+ id: 'b-api',
+ type: 'agent',
+ platformType: 'truenas',
+ name: 'b-real',
+ displayName: 'Real System',
+ platformId: 'shared-key',
+ sourceType: 'api',
+ identity: { hostname: 'real-host' },
+ }),
+ ]);
+ expect(systems).toHaveLength(1);
+ expect(systems[0]!.connectionPath).toBe('api');
+ expect(systems[0]!.typeLabel).toBe('TrueNAS');
+ expect(systems[0]!.name).toBe('Real System');
+ expect(systems[0]!.host).toBe('Unknown');
+ });
+
+ it('copies a missing host from a later same-key system onto an empty-host entry', () => {
+ const systems = buildSetupCompletionConnectedSystems([
+ makeResource({
+ id: 'a-empty',
+ type: 'agent',
+ platformType: 'agent',
+ name: '',
+ platformId: '',
+ agent: { agentId: 'a-empty' },
+ }),
+ makeResource({
+ id: 'b-vc',
+ type: 'agent',
+ platformType: 'vmware-vsphere',
+ name: 'bvc',
+ displayName: 'VC Box',
+ platformId: 'a-empty',
+ sourceType: 'api',
+ identity: { hostname: 'vc-host' },
+ }),
+ ]);
+ expect(systems).toHaveLength(1);
+ expect(systems[0]!.host).toBe('vc-host');
+ expect(systems[0]!.connectionPath).toBe('api');
+ expect(systems[0]!.typeLabel).toBe('VMware vSphere');
+ });
+
+ it('sorts systems by name, then by id', () => {
+ const systems = buildSetupCompletionConnectedSystems([
+ makeResource({
+ id: 'c1',
+ type: 'agent',
+ platformType: 'agent',
+ name: 'Charlie',
+ platformId: 'c1',
+ agent: { agentId: 'c1' },
+ }),
+ makeResource({
+ id: 'a1',
+ type: 'agent',
+ platformType: 'agent',
+ name: 'Alpha',
+ platformId: 'a1',
+ agent: { agentId: 'a1' },
+ }),
+ makeResource({
+ id: 'b1',
+ type: 'agent',
+ platformType: 'agent',
+ name: 'Bravo',
+ platformId: 'b1',
+ agent: { agentId: 'b1' },
+ }),
+ ]);
+ expect(namesOf(systems)).toEqual(['Alpha', 'Bravo', 'Charlie']);
+ expect(idsOf(systems)).toEqual(['a1', 'b1', 'c1']);
+ });
+
+ it('breaks a name tie by id', () => {
+ const systems = buildSetupCompletionConnectedSystems([
+ makeResource({
+ id: 's-z',
+ type: 'pbs',
+ name: 'samebox',
+ displayName: 'Same Name',
+ platformId: 's-z',
+ }),
+ makeResource({
+ id: 's-a',
+ type: 'pbs',
+ name: 'samebox2',
+ displayName: 'Same Name',
+ platformId: 's-a',
+ }),
+ ]);
+ expect(namesOf(systems)).toEqual(['Same Name', 'Same Name']);
+ expect(idsOf(systems)).toEqual(['s-a', 's-z']);
+ });
+ });
+});
diff --git a/frontend-modern/src/components/Storage/__tests__/storagePageState.branchcov.test.ts b/frontend-modern/src/components/Storage/__tests__/storagePageState.branchcov.test.ts
new file mode 100644
index 0000000000..62e61f1faf
--- /dev/null
+++ b/frontend-modern/src/components/Storage/__tests__/storagePageState.branchcov.test.ts
@@ -0,0 +1,602 @@
+import { describe, expect, it, vi } from 'vitest';
+import type { Resource } from '@/types/resource';
+import type { StorageRecord } from '@/features/storageBackups/models';
+import type { ParsedStorageSearch } from '@/components/Storage/useStorageRouteState';
+import {
+ buildStorageNodeOnlineByLabel,
+ buildStorageRouteFields,
+ countActiveStorageFilters,
+ countVisiblePhysicalDisksForNode,
+ DEFAULT_STORAGE_DISK_GROUP_FILTER,
+ DEFAULT_STORAGE_DISK_ROLE_FILTER,
+ DEFAULT_STORAGE_GROUP_KEY,
+ DEFAULT_STORAGE_SORT_DIRECTION,
+ DEFAULT_STORAGE_SORT_KEY,
+ DEFAULT_STORAGE_SOURCE_FILTER,
+ DEFAULT_STORAGE_STATUS_FILTER,
+ getStorageMetaBoolean,
+ hasActiveStorageFilters,
+ isStorageRecordCeph,
+ toStorageHealthFilterValue,
+ type StorageFilterActivityState,
+ type StoragePageNodeOption,
+ type StorageStatusFilterValue,
+} from '@/components/Storage/storagePageState';
+
+const makeResource = (overrides: Partial<Resource> = {}): Resource =>
+ ({
+ id: 'node-1',
+ type: 'agent',
+ name: 'pve1',
+ displayName: 'pve1',
+ platformId: 'cluster-main',
+ platformType: 'proxmox-pve',
+ sourceType: 'api',
+ status: 'online',
+ uptime: 1,
+ lastSeen: 0,
+ ...overrides,
+ }) as Resource;
+
+const makeDisk = (overrides: Partial<Resource> = {}): Resource =>
+ ({
+ id: 'disk-1',
+ type: 'physical_disk',
+ name: '/dev/sda',
+ displayName: '/dev/sda',
+ platformId: 'cluster-main',
+ platformType: 'proxmox-pve',
+ sourceType: 'api',
+ parentId: 'node-1',
+ status: 'online',
+ lastSeen: 0,
+ ...overrides,
+ }) as Resource;
+
+const makeStorageRecord = (overrides: Partial<StorageRecord> = {}): StorageRecord => ({
+ id: 'storage-1',
+ name: 'pool-1',
+ category: 'pool',
+ health: 'healthy',
+ location: { label: 'pve1', scope: 'node' },
+ capacity: { totalBytes: 100, usedBytes: 40, freeBytes: 60, usagePercent: 40 },
+ capabilities: [],
+ source: {
+ platform: 'truenas',
+ family: 'generic',
+ origin: 'resource',
+ adapterId: 'adapter-1',
+ },
+ observedAt: 0,
+ ...overrides,
+});
+
+const makeParsed = (overrides: Partial<ParsedStorageSearch> = {}): ParsedStorageSearch => ({
+ tab: '',
+ group: '',
+ source: '',
+ status: '',
+ diskRole: '',
+ diskGroup: '',
+ node: '',
+ query: '',
+ resource: '',
+ sort: '',
+ order: '',
+ summaryGroup: '',
+ ...overrides,
+});
+
+const buildFields = () =>
+ buildStorageRouteFields({
+ view: () => 'pools',
+ setView: () => {},
+ sourceFilter: () => 'all',
+ setSourceFilter: () => {},
+ healthFilter: () => 'all',
+ setHealthFilter: () => {},
+ diskRoleFilter: () => 'all',
+ setDiskRoleFilter: () => {},
+ diskGroupFilter: () => 'all',
+ setDiskGroupFilter: () => {},
+ selectedNodeId: () => 'all',
+ setSelectedNodeId: () => {},
+ groupBy: () => 'none',
+ setGroupBy: () => {},
+ sortKey: () => 'priority',
+ setSortKey: () => {},
+ sortDirection: () => 'desc',
+ setSortDirection: () => {},
+ search: () => '',
+ setSearch: () => {},
+ });
+
+describe('storagePageState branch coverage', () => {
+ describe('toStorageHealthFilterValue', () => {
+ it.each<[StorageStatusFilterValue, ReturnType<typeof toStorageHealthFilterValue>]>([
+ ['warning', 'warning'],
+ ['critical', 'critical'],
+ ['offline', 'offline'],
+ ['unknown', 'unknown'],
+ ])('passes %s through unchanged (fallthrough arm)', (input, expected) => {
+ expect(toStorageHealthFilterValue(input)).toBe(expected);
+ });
+ });
+
+ describe('countActiveStorageFilters', () => {
+ // Only the required fields are populated; every optional filter is left
+ // undefined so the `|| <default>` fallback arm fires for each dimension.
+ const baseRequiredOnly: StorageFilterActivityState = {
+ search: '',
+ sortKey: DEFAULT_STORAGE_SORT_KEY,
+ sortDirection: DEFAULT_STORAGE_SORT_DIRECTION,
+ };
+
+ it('returns 0 when every optional field is undefined (fallback arms all fire)', () => {
+ expect(countActiveStorageFilters({ ...baseRequiredOnly })).toBe(0);
+ });
+
+ it('counts a non-whitespace search even when optional fields are undefined', () => {
+ expect(countActiveStorageFilters({ ...baseRequiredOnly, search: 'tank' })).toBe(1);
+ });
+
+ it('ignores whitespace-only search', () => {
+ expect(countActiveStorageFilters({ ...baseRequiredOnly, search: '\t \n' })).toBe(0);
+ });
+
+ it.each<[string, Partial<StorageFilterActivityState>]>([
+ ['groupBy', { groupBy: 'node' }],
+ ['statusFilter', { statusFilter: 'critical' }],
+ ['sourceFilter', { sourceFilter: 'agent' }],
+ ['diskRoleFilter', { diskRoleFilter: 'nvme-disk' }],
+ ['diskGroupFilter', { diskGroupFilter: 'data-pool' }],
+ ])('counts an active %s while the remaining optionals stay undefined', (_field, patch) => {
+ expect(countActiveStorageFilters({ ...baseRequiredOnly, ...patch })).toBe(1);
+ });
+
+ it('accumulates across an intermediate mix of active filters (3 of 6)', () => {
+ expect(
+ countActiveStorageFilters({
+ ...baseRequiredOnly,
+ search: 'tank',
+ groupBy: 'node',
+ statusFilter: 'warning',
+ }),
+ ).toBe(3);
+ });
+
+ it('accumulates across four active filters including both disk facets', () => {
+ expect(
+ countActiveStorageFilters({
+ ...baseRequiredOnly,
+ search: 'tank',
+ groupBy: 'type',
+ diskRoleFilter: 'nvme-disk',
+ diskGroupFilter: 'data-pool',
+ }),
+ ).toBe(4);
+ });
+
+ it('trims leading/trailing whitespace before deciding search is active', () => {
+ expect(countActiveStorageFilters({ ...baseRequiredOnly, search: ' tank ' })).toBe(1);
+ });
+ });
+
+ describe('hasActiveStorageFilters', () => {
+ const baseRequiredOnly: StorageFilterActivityState = {
+ search: '',
+ sortKey: DEFAULT_STORAGE_SORT_KEY,
+ sortDirection: DEFAULT_STORAGE_SORT_DIRECTION,
+ };
+
+ it('returns false when every optional field is undefined and required fields are default', () => {
+ expect(hasActiveStorageFilters({ ...baseRequiredOnly })).toBe(false);
+ });
+
+ it.each<[string, Partial<StorageFilterActivityState>]>([
+ ['search', { search: 'tank' }],
+ ['sortKey', { sortKey: 'name' }],
+ ['sortDirection', { sortDirection: 'asc' }],
+ ['groupBy', { groupBy: 'node' }],
+ ['statusFilter', { statusFilter: 'warning' }],
+ ['sourceFilter', { sourceFilter: 'agent' }],
+ ['diskRoleFilter', { diskRoleFilter: 'nvme-disk' }],
+ ['diskGroupFilter', { diskGroupFilter: 'data-pool' }],
+ ])('returns true when only %s deviates from default', (_field, patch) => {
+ expect(hasActiveStorageFilters({ ...baseRequiredOnly, ...patch })).toBe(true);
+ });
+
+ it('returns false when every optional field is explicitly set to its default', () => {
+ expect(
+ hasActiveStorageFilters({
+ ...baseRequiredOnly,
+ groupBy: DEFAULT_STORAGE_GROUP_KEY,
+ statusFilter: DEFAULT_STORAGE_STATUS_FILTER,
+ sourceFilter: DEFAULT_STORAGE_SOURCE_FILTER,
+ diskRoleFilter: DEFAULT_STORAGE_DISK_ROLE_FILTER,
+ diskGroupFilter: DEFAULT_STORAGE_DISK_GROUP_FILTER,
+ }),
+ ).toBe(false);
+ });
+ });
+
+ describe('buildStorageNodeOnlineByLabel', () => {
+ it('returns an empty map for an empty node list', () => {
+ expect(buildStorageNodeOnlineByLabel([])).toEqual(new Map<string, boolean>());
+ });
+
+ it('skips nodes whose name is empty or whitespace-only', () => {
+ expect(buildStorageNodeOnlineByLabel([makeResource({ name: '' })])).toEqual(
+ new Map<string, boolean>(),
+ );
+ expect(buildStorageNodeOnlineByLabel([makeResource({ name: ' ' })])).toEqual(
+ new Map<string, boolean>(),
+ );
+ });
+
+ it('skips nodes that report neither a status string nor an uptime number', () => {
+ const node = makeResource({ name: 'host-a', status: undefined, uptime: undefined });
+ expect(buildStorageNodeOnlineByLabel([node])).toEqual(new Map<string, boolean>());
+ });
+
+ it('marks a node online only when status is "online" AND uptime is a positive number', () => {
+ expect(
+ buildStorageNodeOnlineByLabel([makeResource({ name: 'host-a', status: 'online', uptime: 1 })]),
+ ).toEqual(new Map([['host-a', true]]));
+ });
+
+ it('marks a node NOT online when status is "online" but uptime is missing', () => {
+ // status alone is insufficient: (uptime || 0) > 0 must also hold.
+ expect(
+ buildStorageNodeOnlineByLabel([
+ makeResource({ name: 'host-a', status: 'online', uptime: undefined }),
+ ]),
+ ).toEqual(new Map([['host-a', false]]));
+ });
+
+ it('marks a node NOT online when status is "online" but uptime is 0 (boundary)', () => {
+ expect(
+ buildStorageNodeOnlineByLabel([
+ makeResource({ name: 'host-a', status: 'online', uptime: 0 }),
+ ]),
+ ).toEqual(new Map([['host-a', false]]));
+ });
+
+ it('marks a node NOT online when uptime is present but status is not "online"', () => {
+ expect(
+ buildStorageNodeOnlineByLabel([
+ makeResource({ name: 'host-a', status: 'offline', uptime: 500 }),
+ ]),
+ ).toEqual(new Map([['host-a', false]]));
+ });
+
+ it('enters the map (as false) when uptime is 0 but status is missing', () => {
+ // uptime 0 is still typeof 'number', so the node is not skipped; the
+ // online predicate evaluates to false because status !== 'online'.
+ expect(
+ buildStorageNodeOnlineByLabel([
+ makeResource({ name: 'host-a', status: undefined, uptime: 0 }),
+ ]),
+ ).toEqual(new Map([['host-a', false]]));
+ });
+
+ it('treats a whitespace-only status string as no status', () => {
+ expect(
+ buildStorageNodeOnlineByLabel([
+ makeResource({
+ name: 'host-a',
+ status: ' ',
+ uptime: 100,
+ } as unknown as Partial<Resource>),
+ ]),
+ ).toEqual(new Map([['host-a', false]]));
+ });
+
+ it('normalizes the map key to trimmed lowercase', () => {
+ expect(
+ buildStorageNodeOnlineByLabel([
+ makeResource({ name: ' PVE-1 ', status: 'online', uptime: 10 }),
+ ]),
+ ).toEqual(new Map([['pve-1', true]]));
+ });
+
+ it('lets a later node with the same normalized label overwrite an earlier entry', () => {
+ const nodes = [
+ makeResource({ id: 'a', name: 'dup', status: 'online', uptime: 5 }),
+ makeResource({ id: 'b', name: 'DUP', status: 'offline', uptime: 0 }),
+ ];
+ expect(buildStorageNodeOnlineByLabel(nodes)).toEqual(new Map([['dup', false]]));
+ });
+ });
+
+ describe('getStorageMetaBoolean', () => {
+ it('returns null when details is undefined', () => {
+ expect(getStorageMetaBoolean(makeStorageRecord({ details: undefined }), 'isCeph')).toBeNull();
+ });
+
+ it('returns null when details is null (falsy-coalesces to {})', () => {
+ const record = makeStorageRecord({
+ details: null as unknown as Record<string, unknown>,
+ });
+ expect(getStorageMetaBoolean(record, 'isCeph')).toBeNull();
+ });
+
+ it('returns null when details is an empty object', () => {
+ expect(getStorageMetaBoolean(makeStorageRecord({ details: {} }), 'isZfs')).toBeNull();
+ });
+
+ it('returns null when the requested key is absent', () => {
+ expect(
+ getStorageMetaBoolean(makeStorageRecord({ details: { other: 1 } }), 'isCeph'),
+ ).toBeNull();
+ });
+
+ it('returns the stored boolean for isCeph (true and false)', () => {
+ expect(
+ getStorageMetaBoolean(makeStorageRecord({ details: { isCeph: true } }), 'isCeph'),
+ ).toBe(true);
+ expect(
+ getStorageMetaBoolean(makeStorageRecord({ details: { isCeph: false } }), 'isCeph'),
+ ).toBe(false);
+ });
+
+ it('returns the stored boolean for isZfs (true and false)', () => {
+ expect(
+ getStorageMetaBoolean(makeStorageRecord({ details: { isZfs: true } }), 'isZfs'),
+ ).toBe(true);
+ expect(
+ getStorageMetaBoolean(makeStorageRecord({ details: { isZfs: false } }), 'isZfs'),
+ ).toBe(false);
+ });
+
+ it('returns null for non-boolean values (string, number, null)', () => {
+ expect(
+ getStorageMetaBoolean(makeStorageRecord({ details: { isCeph: 'true' } }), 'isCeph'),
+ ).toBeNull();
+ expect(
+ getStorageMetaBoolean(makeStorageRecord({ details: { isCeph: 1 } }), 'isCeph'),
+ ).toBeNull();
+ expect(
+ getStorageMetaBoolean(
+ makeStorageRecord({ details: { isCeph: null } }),
+ 'isCeph',
+ ),
+ ).toBeNull();
+ });
+ });
+
+ describe('isStorageRecordCeph', () => {
+ it('short-circuits to true when details.isCeph is the boolean true', () => {
+ // The underlying type/category would otherwise read as non-ceph; the
+ // meta flag must win.
+ const record = makeStorageRecord({
+ details: { isCeph: true, type: 'zfs' },
+ capabilities: [],
+ source: { platform: 'truenas', family: 'generic', origin: 'resource', adapterId: 'a' },
+ });
+ expect(isStorageRecordCeph(record)).toBe(true);
+ });
+
+ it('short-circuits to false when details.isCeph is the boolean false even if the type is ceph', () => {
+ const record = makeStorageRecord({
+ details: { isCeph: false, type: 'rbd' },
+ capabilities: ['replication'],
+ source: { platform: 'proxmox-pve', family: 'virtualization', origin: 'resource', adapterId: 'a' },
+ });
+ expect(isStorageRecordCeph(record)).toBe(false);
+ });
+
+ it('falls back to isCephStorageRecord and returns true for a ceph type', () => {
+ const record = makeStorageRecord({
+ details: { type: 'rbd' },
+ capabilities: [],
+ source: { platform: 'proxmox-pve', family: 'virtualization', origin: 'resource', adapterId: 'a' },
+ });
+ expect(isStorageRecordCeph(record)).toBe(true);
+ });
+
+ it('falls back to isCephStorageRecord and returns true for replication + proxmox platform', () => {
+ const record = makeStorageRecord({
+ details: { type: 'lvm' },
+ capabilities: ['capacity', 'replication'],
+ source: { platform: 'proxmox-pve', family: 'virtualization', origin: 'resource', adapterId: 'a' },
+ });
+ expect(isStorageRecordCeph(record)).toBe(true);
+ });
+
+ it('returns false when type is non-ceph and replication is absent', () => {
+ const record = makeStorageRecord({
+ details: { type: 'zfs' },
+ capabilities: ['capacity'],
+ source: { platform: 'truenas-scale', family: 'generic', origin: 'resource', adapterId: 'a' },
+ });
+ expect(isStorageRecordCeph(record)).toBe(false);
+ });
+
+ it('returns false when replication is present but the platform is not proxmox', () => {
+ const record = makeStorageRecord({
+ details: { type: 'lvm' },
+ capabilities: ['capacity', 'replication'],
+ source: { platform: 'truenas', family: 'generic', origin: 'resource', adapterId: 'a' },
+ });
+ expect(isStorageRecordCeph(record)).toBe(false);
+ });
+
+ it('returns false when the platform is proxmox but replication is absent', () => {
+ const record = makeStorageRecord({
+ details: { type: 'lvm' },
+ capabilities: ['capacity'],
+ source: { platform: 'proxmox-pve', family: 'virtualization', origin: 'resource', adapterId: 'a' },
+ });
+ expect(isStorageRecordCeph(record)).toBe(false);
+ });
+ });
+
+ describe('countVisiblePhysicalDisksForNode', () => {
+ const nodeOptions: StoragePageNodeOption[] = [
+ { id: 'node-1', label: 'pve1', instance: 'cluster-main' },
+ { id: 'node-2', label: 'pve2', instance: 'cluster-main' },
+ ];
+
+ it('returns the full disk count when the selected node is "all"', () => {
+ const disks = [
+ makeDisk({ id: 'd1', parentId: 'node-1' }),
+ makeDisk({ id: 'd2', parentId: 'node-2' }),
+ makeDisk({ id: 'd3', parentId: 'node-1' }),
+ ];
+ expect(countVisiblePhysicalDisksForNode('all', nodeOptions, disks)).toBe(3);
+ });
+
+ it('returns the full disk count when the selected node is not in nodeOptions', () => {
+ const disks = [makeDisk({ id: 'd1', parentId: 'node-1' })];
+ expect(countVisiblePhysicalDisksForNode('missing', nodeOptions, disks)).toBe(1);
+ });
+
+ it('counts only disks matching the selected node by parentId', () => {
+ const disks = [
+ makeDisk({ id: 'd1', parentId: 'node-1' }),
+ makeDisk({ id: 'd2', parentId: 'node-2' }),
+ makeDisk({ id: 'd3', parentId: 'node-1' }),
+ ];
+ expect(countVisiblePhysicalDisksForNode('node-1', nodeOptions, disks)).toBe(2);
+ });
+
+ it('returns 0 when the selected node matches no disks', () => {
+ const disks = [makeDisk({ id: 'd1', parentId: 'node-2' })];
+ expect(countVisiblePhysicalDisksForNode('node-1', nodeOptions, disks)).toBe(0);
+ });
+
+ it('returns 0 for a known node when the disk list is empty', () => {
+ expect(countVisiblePhysicalDisksForNode('node-1', nodeOptions, [])).toBe(0);
+ });
+
+ it('returns 0 for "all" when the disk list is empty', () => {
+ expect(countVisiblePhysicalDisksForNode('all', nodeOptions, [])).toBe(0);
+ });
+
+ it('matches disks by node label/instance when parentId is absent', () => {
+ const diskByName = makeDisk({
+ id: 'd-name',
+ parentId: undefined,
+ identity: { hostname: 'pve1' },
+ canonicalIdentity: { hostname: 'pve1' },
+ platformData: { proxmox: { nodeName: 'pve1', instance: 'cluster-main' } },
+ });
+ expect(countVisiblePhysicalDisksForNode('node-1', nodeOptions, [diskByName])).toBe(1);
+ });
+ });
+
+ describe('buildStorageRouteFields', () => {
+ describe('tab field', () => {
+ it('write returns the value when it is not the default view', () => {
+ expect(buildFields().tab!.write?.('disks')).toBe('disks');
+ });
+
+ it('get returns the accessor value and set forwards to the setter', () => {
+ const setView = vi.fn();
+ const fields = buildStorageRouteFields({
+ view: () => 'disks',
+ setView,
+ sourceFilter: () => 'all',
+ setSourceFilter: () => {},
+ healthFilter: () => 'all',
+ setHealthFilter: () => {},
+ diskRoleFilter: () => 'all',
+ setDiskRoleFilter: () => {},
+ diskGroupFilter: () => 'all',
+ setDiskGroupFilter: () => {},
+ selectedNodeId: () => 'all',
+ setSelectedNodeId: () => {},
+ groupBy: () => 'none',
+ setGroupBy: () => {},
+ sortKey: () => 'priority',
+ setSortKey: () => {},
+ sortDirection: () => 'desc',
+ setSortDirection: () => {},
+ search: () => '',
+ setSearch: () => {},
+ });
+ expect(fields.tab!.get()).toBe('disks');
+ fields.tab!.set('pools');
+ expect(setView).toHaveBeenCalledWith('pools');
+ });
+ });
+
+ describe('source field', () => {
+ it('write collapses whitespace-only/empty input to null via the default', () => {
+ expect(buildFields().source!.write?.(' ')).toBeNull();
+ expect(buildFields().source!.write?.('')).toBeNull();
+ });
+ });
+
+ describe('status field', () => {
+ it.each([
+ ['critical', 'critical'],
+ ['offline', 'offline'],
+ ['unknown', 'unknown'],
+ ] as const)('write passes %s through getStorageStatusFilterValue unchanged', (input, expected) => {
+ expect(buildFields().status!.write?.(input)).toBe(expected);
+ });
+ });
+
+ describe('diskRole field', () => {
+ it('write slugifies spaced/cased input to the canonical facet value', () => {
+ expect(buildFields().diskRole!.write?.(' NVME Disk ')).toBe('nvme-disk');
+ });
+
+ it('write returns null when the slugified value collapses to the default', () => {
+ expect(buildFields().diskRole!.write?.(' All ')).toBeNull();
+ });
+ });
+
+ describe('diskGroup field', () => {
+ it('write slugifies spaced/cased input to the canonical facet value', () => {
+ expect(buildFields().diskGroup!.write?.(' Data Pool ')).toBe('data-pool');
+ });
+
+ it('write returns null when the slugified value collapses to the default', () => {
+ expect(buildFields().diskGroup!.write?.(' All ')).toBeNull();
+ });
+ });
+
+ describe('group field', () => {
+ it.each([
+ ['none', 'none'],
+ ['node', 'node'],
+ ['type', 'type'],
+ ])('read normalizes %s to its canonical group key', (input, expected) => {
+ expect(buildFields().group!.read(makeParsed({ group: input }))).toBe(expected);
+ });
+
+ it('write returns the value when it is not the default', () => {
+ expect(buildFields().group!.write?.('node')).toBe('node');
+ });
+ });
+
+ describe('sort field', () => {
+ it.each(['priority', 'name', 'type', 'host'])('read accepts canonical sort key %s', (key) => {
+ expect(buildFields().sort!.read(makeParsed({ sort: key }))).toBe(key);
+ });
+
+ it('write returns the value when it is not the default', () => {
+ expect(buildFields().sort!.write?.('name')).toBe('name');
+ });
+ });
+
+ describe('order field', () => {
+ it('read returns "desc" for an explicit "desc" token', () => {
+ expect(buildFields().order!.read(makeParsed({ order: 'desc' }))).toBe('desc');
+ });
+
+ it('write returns "asc" when it is not the default', () => {
+ expect(buildFields().order!.write?.('asc')).toBe('asc');
+ });
+ });
+
+ describe('query field', () => {
+ it('write returns null for an empty string (distinct from whitespace)', () => {
+ expect(buildFields().query!.write?.('')).toBeNull();
+ });
+ });
+ });
+});
diff --git a/frontend-modern/src/components/Workloads/__tests__/workloadMetricHistoryModel.branchcov.test.ts b/frontend-modern/src/components/Workloads/__tests__/workloadMetricHistoryModel.branchcov.test.ts
new file mode 100644
index 0000000000..ed3e325a67
--- /dev/null
+++ b/frontend-modern/src/components/Workloads/__tests__/workloadMetricHistoryModel.branchcov.test.ts
@@ -0,0 +1,456 @@
+import { describe, expect, it } from 'vitest';
+
+import type { ChartData, MetricPoint } from '@/api/charts';
+import type { WorkloadGuest } from '@/types/workloads';
+
+import type { WorkloadTableMetric } from '../workloadMetricHistoryModel';
+import {
+ computeMetricMiniSparklineHoverState,
+ findChartDataForCandidates,
+ getMetricMiniSparklineTimeRange,
+ getMetricSparklineSeriesFromChartData,
+ getWorkloadChartKeyCandidates,
+ normalizeWorkloadChartKey,
+} from '../workloadMetricHistoryModel';
+
+const makeGuest = (overrides?: Partial<WorkloadGuest>): WorkloadGuest =>
+ ({
+ id: 'guest-0',
+ vmid: 100,
+ name: 'workload-0',
+ node: 'pve',
+ instance: 'cluster-a',
+ status: 'running',
+ type: 'qemu',
+ workloadType: 'vm',
+ ...overrides,
+ }) as WorkloadGuest;
+
+const seriesPoint = (timestamp: number, value: number): MetricPoint => ({ timestamp, value });
+
+describe('workloadMetricHistoryModel (branch coverage)', () => {
+ describe('normalizeWorkloadChartKey', () => {
+ it('returns empty string for blank input', () => {
+ expect(normalizeWorkloadChartKey('')).toBe('');
+ expect(normalizeWorkloadChartKey(' ')).toBe('');
+ });
+
+ it('passes colon-bearing keys through after trimming', () => {
+ expect(normalizeWorkloadChartKey(' a:b:c ')).toBe('a:b:c');
+ });
+
+ it('normalizes a two-part node-vmid key', () => {
+ expect(normalizeWorkloadChartKey('pve-101')).toBe('pve:pve:101');
+ });
+
+ it('returns trimmed input for a two-part key with a non-digit vmid', () => {
+ expect(normalizeWorkloadChartKey('node-abc')).toBe('node-abc');
+ });
+
+ it('returns trimmed input for a two-part key with an empty node (leading dash)', () => {
+ expect(normalizeWorkloadChartKey('-101')).toBe('-101');
+ });
+
+ it('returns a single-token input unchanged', () => {
+ expect(normalizeWorkloadChartKey('foo')).toBe('foo');
+ });
+
+ it('normalizes a three-plus-part instance-node-vmid key', () => {
+ expect(normalizeWorkloadChartKey('cluster-a-pve-101')).toBe('cluster-a:pve:101');
+ });
+
+ it('returns trimmed input when the instance part is empty', () => {
+ expect(normalizeWorkloadChartKey('-pve-101')).toBe('-pve-101');
+ });
+
+ it('returns trimmed input when the node part is empty', () => {
+ expect(normalizeWorkloadChartKey('cluster-a--101')).toBe('cluster-a--101');
+ });
+
+ it('returns trimmed input when the vmid part is non-digit in a 3+ part key', () => {
+ expect(normalizeWorkloadChartKey('a-b-c')).toBe('a-b-c');
+ });
+ });
+
+ describe('getWorkloadChartKeyCandidates', () => {
+ it('skips node/vmid candidates when vmid is not positive', () => {
+ const guest = makeGuest({ id: 'g1', node: 'pve', instance: 'c', vmid: 0, type: 'qemu' });
+ expect(getWorkloadChartKeyCandidates(guest)).toEqual(['g1']);
+ });
+
+ it('emits node variants but no instance variants when instance is empty', () => {
+ const guest = makeGuest({
+ id: 'pve-101',
+ node: 'pve',
+ instance: '',
+ vmid: 101,
+ type: 'qemu',
+ });
+ expect(getWorkloadChartKeyCandidates(guest)).toEqual(['pve-101', 'pve:pve:101']);
+ });
+
+ it('emits canonical, raw, node, and instance candidates in deduped order', () => {
+ const guest = makeGuest({
+ id: 'cluster-a-pve-101',
+ instance: 'cluster-a',
+ node: 'pve',
+ vmid: 101,
+ type: 'qemu',
+ });
+ expect(getWorkloadChartKeyCandidates(guest)).toEqual([
+ 'cluster-a:pve:101',
+ 'cluster-a-pve-101',
+ 'pve-101',
+ 'pve:pve:101',
+ ]);
+ });
+
+ it('includes containerId and skips the node block when node is empty', () => {
+ const guest = makeGuest({
+ id: 'cid-1',
+ containerId: 'docker-abc',
+ node: '',
+ instance: '',
+ vmid: 0,
+ type: 'app-container',
+ workloadType: 'app-container',
+ });
+ expect(getWorkloadChartKeyCandidates(guest)).toEqual(['cid-1', 'cid:cid:1', 'docker-abc']);
+ });
+ });
+
+ describe('findChartDataForCandidates / readChartData', () => {
+ const data: ChartData = { cpu: [seriesPoint(1, 5)] };
+
+ it('returns undefined for empty candidates', () => {
+ expect(findChartDataForCandidates([], [{ x: data }])).toBeUndefined();
+ });
+
+ it('returns undefined when no source contains any candidate', () => {
+ expect(findChartDataForCandidates(['x', 'y'], [{ z: data }])).toBeUndefined();
+ });
+
+ it('returns undefined when the source is undefined', () => {
+ expect(findChartDataForCandidates(['x'], [undefined])).toBeUndefined();
+ });
+
+ it('returns undefined for a blank candidate key (readChartData !key guard)', () => {
+ expect(findChartDataForCandidates([''], [{ '': data }])).toBeUndefined();
+ });
+
+ it('finds a direct hit in a record source', () => {
+ expect(findChartDataForCandidates(['pve:pve:101'], [{ 'pve:pve:101': data }])).toBe(data);
+ });
+
+ it('finds a direct hit in a Map source', () => {
+ const map = new Map<string, ChartData>([['pve:pve:101', data]]);
+ expect(findChartDataForCandidates(['pve:pve:101'], [map])).toBe(data);
+ });
+
+ it('finds a normalized hit in a Map source', () => {
+ const map = new Map<string, ChartData>([['pve:pve:101', data]]);
+ expect(findChartDataForCandidates(['pve-101'], [map])).toBe(data);
+ });
+
+ it('skips the normalized lookup when the candidate already normalizes to itself', () => {
+ const source = { 'pve-101': data };
+ expect(findChartDataForCandidates(['pve-101'], [source])).toBe(data);
+ });
+
+ it('finds a hit across multiple sources, returning the first match', () => {
+ const other: ChartData = { memory: [seriesPoint(1, 2)] };
+ expect(findChartDataForCandidates(['key'], [{}, { key: other }])).toBe(other);
+ });
+ });
+
+ describe('getMetricSparklineSeriesFromChartData / sanitizeMetricPoints / clamp', () => {
+ it('returns an empty array when chartData is undefined', () => {
+ expect(getMetricSparklineSeriesFromChartData(undefined, 'cpu')).toEqual([]);
+ });
+
+ it('returns the default empty array for an unrecognized metric', () => {
+ expect(
+ getMetricSparklineSeriesFromChartData(
+ { cpu: [] },
+ 'bogus' as unknown as WorkloadTableMetric,
+ ),
+ ).toEqual([]);
+ });
+
+ it('clamps cpu values via clampPercent (>100, <0, in-range)', () => {
+ const series = getMetricSparklineSeriesFromChartData(
+ {
+ cpu: [
+ seriesPoint(1, 150),
+ seriesPoint(2, -5),
+ seriesPoint(3, 50),
+ ],
+ },
+ 'cpu',
+ );
+ expect(series).toHaveLength(1);
+ expect(series[0].id).toBe('cpu');
+ expect(series[0].label).toBe('CPU');
+ expect(series[0].points).toEqual([
+ { timestamp: 1, value: 100 },
+ { timestamp: 2, value: 0 },
+ { timestamp: 3, value: 50 },
+ ]);
+ });
+
+ it('filters non-finite points and sorts by timestamp for memory', () => {
+ const series = getMetricSparklineSeriesFromChartData(
+ {
+ memory: [
+ seriesPoint(3, 30),
+ seriesPoint(1, 10),
+ seriesPoint(2, NaN),
+ seriesPoint(NaN, 40),
+ seriesPoint(4, 40),
+ ],
+ },
+ 'memory',
+ );
+ expect(series[0].id).toBe('memory');
+ expect(series[0].points).toEqual([
+ { timestamp: 1, value: 10 },
+ { timestamp: 3, value: 30 },
+ { timestamp: 4, value: 40 },
+ ]);
+ });
+
+ it('emits a disk series with the disk color', () => {
+ const series = getMetricSparklineSeriesFromChartData(
+ { disk: [seriesPoint(1, 99)] },
+ 'disk',
+ );
+ expect(series[0].id).toBe('disk');
+ expect(series[0].color).toBe('#10b981');
+ });
+
+ it('returns empty points when the metric array is undefined/empty', () => {
+ const series = getMetricSparklineSeriesFromChartData({}, 'cpu');
+ expect(series[0].points).toEqual([]);
+ });
+
+ it('clamps netIo values via clampNonNegative and returns paired series', () => {
+ const series = getMetricSparklineSeriesFromChartData(
+ {
+ netin: [seriesPoint(1, -10), seriesPoint(2, 30)],
+ netout: [seriesPoint(1, 7)],
+ },
+ 'netIo',
+ );
+ expect(series.map((s) => s.id)).toEqual(['netin', 'netout']);
+ expect(series[0].points).toEqual([
+ { timestamp: 1, value: 0 },
+ { timestamp: 2, value: 30 },
+ ]);
+ expect(series[1].points).toEqual([{ timestamp: 1, value: 7 }]);
+ });
+
+ it('clamps diskIo values via clampNonNegative and filters non-finite', () => {
+ const series = getMetricSparklineSeriesFromChartData(
+ {
+ diskread: [seriesPoint(1, -10), seriesPoint(2, 30)],
+ diskwrite: [seriesPoint(1, NaN), seriesPoint(2, 7)],
+ },
+ 'diskIo',
+ );
+ expect(series.map((s) => s.id)).toEqual(['diskread', 'diskwrite']);
+ expect(series[0].points).toEqual([
+ { timestamp: 1, value: 0 },
+ { timestamp: 2, value: 30 },
+ ]);
+ expect(series[1].points).toEqual([{ timestamp: 2, value: 7 }]);
+ });
+ });
+
+ describe('getMetricMiniSparklineTimeRange', () => {
+ it('returns null for an empty series array', () => {
+ expect(getMetricMiniSparklineTimeRange([])).toBeNull();
+ });
+
+ it('returns null when all points are non-finite', () => {
+ expect(
+ getMetricMiniSparklineTimeRange([
+ {
+ id: 'a',
+ label: 'A',
+ color: '#fff',
+ points: [seriesPoint(NaN, 1), seriesPoint(1, NaN)],
+ },
+ ]),
+ ).toBeNull();
+ });
+
+ it('returns null when min and max timestamps are equal (single point)', () => {
+ expect(
+ getMetricMiniSparklineTimeRange([
+ {
+ id: 'a',
+ label: 'A',
+ color: '#fff',
+ points: [seriesPoint(5, 1)],
+ },
+ ]),
+ ).toBeNull();
+ });
+
+ it('ignores invalid points and reports the range of valid points only', () => {
+ expect(
+ getMetricMiniSparklineTimeRange([
+ {
+ id: 'a',
+ label: 'A',
+ color: '#fff',
+ points: [
+ seriesPoint(2, 5),
+ seriesPoint(10, NaN),
+ seriesPoint(8, 9),
+ seriesPoint(NaN, 1),
+ ],
+ },
+ ]),
+ ).toEqual({ minTimestamp: 2, maxTimestamp: 8 });
+ });
+
+ it('combines ranges across multiple series', () => {
+ expect(
+ getMetricMiniSparklineTimeRange([
+ {
+ id: 'a',
+ label: 'A',
+ color: '#fff',
+ points: [seriesPoint(100, 1), seriesPoint(200, 2)],
+ },
+ {
+ id: 'b',
+ label: 'B',
+ color: '#000',
+ points: [seriesPoint(50, 1), seriesPoint(300, 2)],
+ },
+ ]),
+ ).toEqual({ minTimestamp: 50, maxTimestamp: 300 });
+ });
+ });
+
+ describe('computeMetricMiniSparklineHoverState / findNearestMetricMiniSparklinePoint', () => {
+ const twoPointSeries = [
+ {
+ id: 'a',
+ label: 'A',
+ color: '#fff',
+ points: [seriesPoint(1000, 10), seriesPoint(2000, 20)],
+ },
+ ];
+
+ it('returns null when there is no valid time range (empty series)', () => {
+ expect(computeMetricMiniSparklineHoverState([], 10, 100)).toBeNull();
+ });
+
+ it('returns null for non-positive width', () => {
+ expect(computeMetricMiniSparklineHoverState(twoPointSeries, 10, 0)).toBeNull();
+ expect(computeMetricMiniSparklineHoverState(twoPointSeries, 10, -5)).toBeNull();
+ });
+
+ it('returns null for non-finite width', () => {
+ expect(
+ computeMetricMiniSparklineHoverState(twoPointSeries, 10, Number.NaN),
+ ).toBeNull();
+ });
+
+ it('clamps a negative cursorX to zero (left edge)', () => {
+ const hover = computeMetricMiniSparklineHoverState(twoPointSeries, -50, 100);
+ expect(hover).not.toBeNull();
+ expect(hover?.cursorX).toBe(0);
+ expect(hover?.cursorRatio).toBe(0);
+ expect(hover?.timestamp).toBe(1000);
+ expect(hover?.entries[0].value).toBe(10);
+ });
+
+ it('clamps a cursorX beyond width to the right edge', () => {
+ const hover = computeMetricMiniSparklineHoverState(twoPointSeries, 300, 100);
+ expect(hover).not.toBeNull();
+ expect(hover?.cursorX).toBe(100);
+ expect(hover?.cursorRatio).toBe(1);
+ expect(hover?.timestamp).toBe(2000);
+ expect(hover?.entries[0].value).toBe(20);
+ });
+
+ it('selects the previous point when the cursor is closer to it', () => {
+ const series = [
+ {
+ id: 'a',
+ label: 'A',
+ color: '#fff',
+ points: [seriesPoint(1000, 10), seriesPoint(3000, 30)],
+ },
+ ];
+ const hover = computeMetricMiniSparklineHoverState(series, 50, 200);
+ expect(hover?.timestamp).toBe(1000);
+ expect(hover?.entries[0].value).toBe(10);
+ });
+
+ it('selects the candidate point when the cursor is closer to it', () => {
+ const series = [
+ {
+ id: 'a',
+ label: 'A',
+ color: '#fff',
+ points: [seriesPoint(1000, 10), seriesPoint(3000, 30)],
+ },
+ ];
+ const hover = computeMetricMiniSparklineHoverState(series, 150, 200);
+ expect(hover?.timestamp).toBe(3000);
+ expect(hover?.entries[0].value).toBe(30);
+ });
+
+ it('resolves an exact midpoint to the previous point (<= tiebreak)', () => {
+ const series = [
+ {
+ id: 'a',
+ label: 'A',
+ color: '#fff',
+ points: [seriesPoint(1000, 10), seriesPoint(3000, 30)],
+ },
+ ];
+ const hover = computeMetricMiniSparklineHoverState(series, 100, 200);
+ expect(hover?.timestamp).toBe(1000);
+ });
+
+ it('finds the exact matching point among three points via binary search', () => {
+ const series = [
+ {
+ id: 'a',
+ label: 'A',
+ color: '#fff',
+ points: [seriesPoint(1000, 1), seriesPoint(2000, 2), seriesPoint(3000, 3)],
+ },
+ ];
+ const hover = computeMetricMiniSparklineHoverState(series, 50, 100);
+ expect(hover?.timestamp).toBe(2000);
+ expect(hover?.entries[0].value).toBe(2);
+ });
+
+ it('only emits entries for series with renderable points', () => {
+ const series = [
+ {
+ id: 'a',
+ label: 'A',
+ color: '#fff',
+ points: [seriesPoint(1000, 1), seriesPoint(2000, 2)],
+ },
+ {
+ id: 'b',
+ label: 'B',
+ color: '#000',
+ points: [] as MetricPoint[],
+ },
+ ];
+ const hover = computeMetricMiniSparklineHoverState(series, 0, 100);
+ expect(hover).not.toBeNull();
+ expect(hover?.entries.map((e) => e.id)).toEqual(['a']);
+ });
+ });
+});
diff --git a/frontend-modern/src/features/alerts/thresholds/__tests__/thresholdsResourceModel.branchcov.test.ts b/frontend-modern/src/features/alerts/thresholds/__tests__/thresholdsResourceModel.branchcov.test.ts
new file mode 100644
index 0000000000..9508ffa955
--- /dev/null
+++ b/frontend-modern/src/features/alerts/thresholds/__tests__/thresholdsResourceModel.branchcov.test.ts
@@ -0,0 +1,373 @@
+import { describe, expect, it } from 'vitest';
+
+import type { Resource } from '@/types/resource';
+
+import type { Override } from '../types';
+import {
+ agentDiskResourceId,
+ buildNodeHeaderMeta,
+ createOverridesMap,
+ dockerHostOverrideIdCandidates,
+ getFriendlyNodeName,
+ hostActionId,
+ storageCoords,
+} from '../thresholdsResourceModel';
+
+/**
+ * Build a minimal Resource fixture. `as unknown as Resource` keeps strict
+ * TypeScript clean while letting us exercise the runtime guards with
+ * deliberately partial / malformed payloads.
+ */
+const makeNode = (overrides: Partial<Resource> = {}): Resource =>
+ ({
+ id: 'node-id',
+ type: 'agent',
+ name: 'node-name',
+ displayName: 'node-display',
+ platformId: 'platform-id',
+ platformType: 'generic',
+ sourceType: 'agent',
+ status: 'online',
+ lastSeen: 0,
+ ...overrides,
+ }) as unknown as Resource;
+
+const makeOverride = (id: string, thresholds: Override['thresholds'] = {}): Override =>
+ ({
+ id,
+ name: id,
+ type: 'guest',
+ thresholds,
+ }) as Override;
+
+describe('thresholdsResourceModel branch coverage', () => {
+ describe('getFriendlyNodeName', () => {
+ it('returns empty string unchanged (guard arm)', () => {
+ expect(getFriendlyNodeName('')).toBe('');
+ });
+
+ it('passes through a simple single-word name unchanged', () => {
+ expect(getFriendlyNodeName('titan')).toBe('titan');
+ });
+
+ it('strips a trailing domain suffix to the first label', () => {
+ expect(getFriendlyNodeName('titan.example.com')).toBe('titan');
+ });
+
+ it('prefers a divergent parenthetical alias over the base token', () => {
+ expect(getFriendlyNodeName('titan (relay)')).toBe('relay');
+ });
+
+ it('returns the base token when the parenthetical normalizes to the same value', () => {
+ expect(getFriendlyNodeName('titan (titan)')).toBe('titan');
+ });
+
+ it('strips a cluster-name token from a multi-word name when clusterName is supplied', () => {
+ expect(getFriendlyNodeName('node1 prod-cluster', 'prod-cluster')).toBe('node1');
+ });
+
+ it('falls back to the trimmed raw value when the cluster filter empties the token', () => {
+ // value is exactly the cluster name; after filtering nothing remains,
+ // so the function falls back to `value.trim()`.
+ expect(getFriendlyNodeName('prod-cluster', 'prod-cluster')).toBe('prod-cluster');
+ });
+
+ it('ignores a whitespace-only clusterName (no filtering applied)', () => {
+ expect(getFriendlyNodeName('titan', ' ')).toBe('titan');
+ });
+
+ it('returns an empty string for a whitespace-only value', () => {
+ expect(getFriendlyNodeName(' ')).toBe('');
+ });
+ });
+
+ describe('buildNodeHeaderMeta', () => {
+ it('uses guestURL as-is when it already starts with http', () => {
+ const node = makeNode({
+ platformData: { guestURL: 'http://titan.local:8006' },
+ });
+ const { headerMeta } = buildNodeHeaderMeta(node);
+ expect(headerMeta.host).toBe('http://titan.local:8006');
+ });
+
+ it('prepends https:// when guestURL has no scheme', () => {
+ const node = makeNode({ platformData: { guestURL: 'titan.local' } });
+ const { headerMeta } = buildNodeHeaderMeta(node);
+ expect(headerMeta.host).toBe('https://titan.local');
+ });
+
+ it('uses host verbatim when it starts with http and guestURL is absent', () => {
+ const node = makeNode({ platformData: { host: 'https://titan.local' } });
+ const { headerMeta } = buildNodeHeaderMeta(node);
+ expect(headerMeta.host).toBe('https://titan.local');
+ });
+
+ it('appends the default :8006 port when host lacks both scheme and port', () => {
+ const node = makeNode({ platformData: { host: '192.0.2.10' } });
+ const { headerMeta } = buildNodeHeaderMeta(node);
+ expect(headerMeta.host).toBe('https://192.0.2.10:8006');
+ });
+
+ it('keeps an explicit port on host without appending :8006', () => {
+ const node = makeNode({ platformData: { host: '192.0.2.10:9000' } });
+ const { headerMeta } = buildNodeHeaderMeta(node);
+ expect(headerMeta.host).toBe('https://192.0.2.10:9000');
+ });
+
+ it('falls back to node.name with default port when neither guestURL nor host is set', () => {
+ const node = makeNode({ name: 'titan-node' });
+ const { headerMeta } = buildNodeHeaderMeta(node);
+ expect(headerMeta.host).toBe('https://titan-node:8006');
+ });
+
+ it('keeps an explicit port on node.name without appending :8006', () => {
+ const node = makeNode({ name: 'titan-node:9000' });
+ const { headerMeta } = buildNodeHeaderMeta(node);
+ expect(headerMeta.host).toBe('https://titan-node:9000');
+ });
+
+ it('leaves host undefined when guestURL, host and name are all absent', () => {
+ const node = makeNode({ name: '', displayName: 'titan' });
+ const { headerMeta } = buildNodeHeaderMeta(node);
+ expect(headerMeta.host).toBeUndefined();
+ });
+
+ it('marks the header as a cluster member with the trimmed cluster name', () => {
+ const node = makeNode({
+ platformData: { isClusterMember: true, clusterName: ' prod-cluster ' },
+ });
+ const { headerMeta } = buildNodeHeaderMeta(node);
+ expect(headerMeta.isClusterMember).toBe(true);
+ expect(headerMeta.clusterName).toBe('prod-cluster');
+ });
+
+ it('falls back to the literal "Cluster" when isClusterMember is true but clusterName is empty', () => {
+ const node = makeNode({
+ platformData: { isClusterMember: true, clusterName: ' ' },
+ });
+ const { headerMeta } = buildNodeHeaderMeta(node);
+ expect(headerMeta.isClusterMember).toBe(true);
+ expect(headerMeta.clusterName).toBe('Cluster');
+ });
+
+ it('derives isClusterMember from node.clusterId when platformData omits it', () => {
+ const node = makeNode({ clusterId: 'cluster-7', platformData: {} });
+ const { headerMeta } = buildNodeHeaderMeta(node);
+ expect(headerMeta.isClusterMember).toBe(true);
+ });
+
+ it('reports isClusterMember=false and clusterName=undefined when no cluster signal is present', () => {
+ const node = makeNode({});
+ const { headerMeta } = buildNodeHeaderMeta(node);
+ expect(headerMeta.isClusterMember).toBe(false);
+ expect(headerMeta.clusterName).toBeUndefined();
+ });
+
+ it('threads node.status through and tags the header type as node', () => {
+ const node = makeNode({ status: 'warning' });
+ const { headerMeta } = buildNodeHeaderMeta(node);
+ expect(headerMeta.type).toBe('node');
+ expect(headerMeta.status).toBe('warning');
+ });
+
+ it('collects distinct non-empty name/displayName/friendlyName tokens into the keys set', () => {
+ // displayName "titan" -> friendlyName "titan"; name differs.
+ const node = makeNode({ name: 'titan-host', displayName: 'titan' });
+ const { keys } = buildNodeHeaderMeta(node);
+ expect(keys.has('titan-host')).toBe(true);
+ expect(keys.has('titan')).toBe(true);
+ expect(keys.size).toBe(2);
+ });
+
+ it('collapses to a single key when name, display and friendly names agree', () => {
+ const node = makeNode({ name: 'titan', displayName: 'titan' });
+ const { keys } = buildNodeHeaderMeta(node);
+ expect(keys.size).toBe(1);
+ expect(keys.has('titan')).toBe(true);
+ });
+ });
+
+ describe('dockerHostOverrideIdCandidates', () => {
+ it('leads with discoveryTarget.resourceId when the discovery type is app-container', () => {
+ const node = makeNode({
+ id: 'runtime-1',
+ discoveryTarget: {
+ resourceType: 'app-container',
+ resourceId: 'container-123',
+ agentId: 'agent-7',
+ },
+ platformData: {
+ docker: { hostSourceId: 'docker-platform' },
+ hostSourceId: 'host-platform',
+ },
+ });
+ expect(dockerHostOverrideIdCandidates(node)).toEqual([
+ 'container-123',
+ 'docker-platform',
+ 'host-platform',
+ 'agent-7',
+ 'runtime-1',
+ ]);
+ });
+
+ it('omits discoveryTarget.resourceId when the discovery type is not app-container', () => {
+ const node = makeNode({
+ id: 'runtime-1',
+ discoveryTarget: {
+ resourceType: 'agent',
+ resourceId: 'should-not-appear',
+ agentId: 'agent-7',
+ },
+ });
+ const result = dockerHostOverrideIdCandidates(node);
+ expect(result).not.toContain('should-not-appear');
+ expect(result).toEqual(['agent-7', 'runtime-1']);
+ });
+
+ it('returns just resource.id when no discovery target or platform data is present', () => {
+ const node = makeNode({ id: 'lone-host' });
+ expect(dockerHostOverrideIdCandidates(node)).toEqual(['lone-host']);
+ });
+
+ it('dedupes repeated hostSourceId values across docker record and top-level platform data', () => {
+ const node = makeNode({
+ id: 'host-1',
+ platformData: {
+ docker: { hostSourceId: 'shared' },
+ hostSourceId: 'shared',
+ },
+ });
+ const result = dockerHostOverrideIdCandidates(node);
+ expect(result).toEqual(['shared', 'host-1']);
+ });
+ });
+
+ describe('storageCoords', () => {
+ it('uses pbsInstanceId / pbsInstanceName for datastore rows', () => {
+ const storage = makeNode({
+ type: 'datastore',
+ platformData: { pbsInstanceId: 'pbs-1', pbsInstanceName: 'backup-server' },
+ });
+ expect(storageCoords(storage)).toEqual({ node: 'backup-server', instance: 'pbs-1' });
+ });
+
+ it('falls back to parentId then platformId then "pbs" for the datastore instance', () => {
+ const fromParent = makeNode({ type: 'datastore', parentId: 'parent-1' });
+ expect(storageCoords(fromParent).instance).toBe('parent-1');
+
+ const fromPlatform = makeNode({
+ type: 'datastore',
+ platformId: 'platform-1',
+ });
+ expect(storageCoords(fromPlatform).instance).toBe('platform-1');
+
+ const fallback = makeNode({ type: 'datastore', platformId: '', parentId: undefined });
+ expect(storageCoords(fallback).instance).toBe('pbs');
+ // node mirrors instance when pbsInstanceName is absent.
+ expect(storageCoords(fallback).node).toBe('pbs');
+ });
+
+ it('reads node/instance from platformData for non-datastore rows', () => {
+ const storage = makeNode({
+ type: 'storage',
+ platformData: { node: 'node-a', instance: 'instance-b' },
+ });
+ expect(storageCoords(storage)).toEqual({ node: 'node-a', instance: 'instance-b' });
+ });
+
+ it('returns empty node and platformId instance when platformData is absent on a non-datastore row', () => {
+ const storage = makeNode({ type: 'storage', platformId: 'platform-9' });
+ const coords = storageCoords(storage);
+ expect(coords.node).toBe('');
+ expect(coords.instance).toBe('platform-9');
+ });
+
+ it('returns empty strings for node and instance when nothing is available on a non-datastore row', () => {
+ const storage = makeNode({ type: 'storage', platformId: '' });
+ const coords = storageCoords(storage);
+ expect(coords.node).toBe('');
+ expect(coords.instance).toBe('');
+ });
+ });
+
+ describe('agentDiskResourceId', () => {
+ it('falls back to the literal "disk" label when mountpoint and device are both empty', () => {
+ expect(agentDiskResourceId('agent-1', '', '')).toBe('agent:agent-1/disk:disk');
+ });
+
+ it('falls back to "disk" when mountpoint and device are whitespace-only', () => {
+ expect(agentDiskResourceId('agent-1', ' ', ' ')).toBe('agent:agent-1/disk:disk');
+ });
+
+ it('collapses non-alphanumeric runs into single dashes and strips edges', () => {
+ // Multiple slashes/spaces collapse; leading slash is stripped.
+ expect(agentDiskResourceId('agent-1', '/var///lib data', '')).toBe(
+ 'agent:agent-1/disk:var-lib-data',
+ );
+ });
+
+ it('uses the "unknown" sentinel when the sanitized label is empty', () => {
+ // punctuation-only input becomes all dashes -> stripped to empty -> "unknown".
+ expect(agentDiskResourceId('agent-1', '!!!', '')).toBe('agent:agent-1/disk:unknown');
+ });
+
+ it('prefers a non-empty mountpoint over device', () => {
+ expect(agentDiskResourceId('agent-1', '/mnt/data', '/dev/sda1')).toBe(
+ 'agent:agent-1/disk:mnt-data',
+ );
+ });
+ });
+
+ describe('createOverridesMap', () => {
+ it('returns an empty Map for undefined input', () => {
+ expect(createOverridesMap(undefined).size).toBe(0);
+ });
+
+ it('returns an empty Map for an empty array', () => {
+ expect(createOverridesMap([]).size).toBe(0);
+ });
+
+ it('keys the map by override.id and preserves insertion order', () => {
+ const a = makeOverride('a', { cpu: 80 });
+ const b = makeOverride('b', { memory: 70 });
+ const map = createOverridesMap([a, b]);
+ expect([...map.keys()]).toEqual(['a', 'b']);
+ expect(map.get('a')).toBe(a);
+ expect(map.get('b')).toBe(b);
+ });
+
+ it('lets later duplicates shadow earlier entries with the same id (Map semantics)', () => {
+ const first = makeOverride('a', { cpu: 1 });
+ const second = makeOverride('a', { cpu: 2 });
+ const map = createOverridesMap([first, second]);
+ expect(map.size).toBe(1);
+ expect(map.get('a')).toBe(second);
+ });
+ });
+
+ describe('hostActionId', () => {
+ it('returns the first host override candidate when candidates are non-empty', () => {
+ const node = makeNode({
+ id: 'runtime-1',
+ discoveryTarget: {
+ resourceType: 'agent',
+ resourceId: 'agent-discovery',
+ agentId: 'agent-7',
+ },
+ });
+ // hostOverrideIdCandidates leads with getAgentDiscoveryResourceId -> "agent-discovery".
+ expect(hostActionId(node)).toBe('agent-discovery');
+ });
+
+ it('falls back to resource.id when every candidate (including id) is invalid', () => {
+ // All sources blank -> uniqueIds returns [] -> [0] is undefined -> fallback.
+ const node = makeNode({ id: '' });
+ expect(hostActionId(node)).toBe('');
+ });
+
+ it('falls back to resource.id when no discovery/agent/platform signals exist', () => {
+ const node = makeNode({ id: 'lone-agent' });
+ expect(hostActionId(node)).toBe('lone-agent');
+ });
+ });
+});
diff --git a/frontend-modern/src/features/storageBackups/__tests__/cephSummaryPresentation.branchcov.test.ts b/frontend-modern/src/features/storageBackups/__tests__/cephSummaryPresentation.branchcov.test.ts
new file mode 100644
index 0000000000..1d39a922a2
--- /dev/null
+++ b/frontend-modern/src/features/storageBackups/__tests__/cephSummaryPresentation.branchcov.test.ts
@@ -0,0 +1,581 @@
+import { describe, expect, it } from 'vitest';
+import type { CephCluster } from '@/types/api';
+import type { Resource } from '@/types/resource';
+import type { StorageRecord } from '@/features/storageBackups/models';
+import {
+ buildExplicitCephClusters,
+ deriveCephClustersFromStorageRecords,
+ resolveCephClusterForStorageRecord,
+ summarizeCephClusters,
+} from '@/features/storageBackups/cephSummaryPresentation';
+
+// ---------------------------------------------------------------------------
+// Fixture builders — mirror the shapes used by the sibling
+// cephSummaryPresentation.test.ts so casts and import paths match.
+// ---------------------------------------------------------------------------
+
+const makeRecord = (overrides: Partial<StorageRecord> = {}): StorageRecord =>
+ ({
+ id: 'storage-1',
+ name: 'ceph-store',
+ category: 'pool',
+ health: 'healthy',
+ location: { label: 'cluster-main', scope: 'cluster' },
+ capacity: { totalBytes: 100, usedBytes: 40, freeBytes: 60, usagePercent: 40 },
+ capabilities: ['capacity'],
+ source: {
+ platform: 'proxmox-pve',
+ family: 'virtualization',
+ origin: 'resource',
+ adapterId: 'resource-storage',
+ },
+ observedAt: 1_700_000_000_000,
+ details: {
+ type: 'rbd',
+ node: 'pve1',
+ parentName: 'pve1',
+ },
+ refs: { platformEntityId: 'cluster-main' },
+ ...overrides,
+ }) as StorageRecord;
+
+const makeResource = (overrides: Partial<Resource> = {}): Resource =>
+ ({
+ id: 'ceph-1',
+ type: 'ceph',
+ name: 'ceph-main',
+ displayName: 'ceph-main',
+ platformId: 'cluster-main',
+ platformType: 'proxmox-pve',
+ sourceType: 'api',
+ status: 'online',
+ lastSeen: 1_700_000_000_000,
+ disk: { current: 40, total: 300, used: 120, free: 180 },
+ platformData: {
+ proxmox: { instance: 'cluster-main' },
+ ceph: {
+ fsid: 'fsid-1',
+ healthStatus: 'HEALTH_OK',
+ healthMessage: 'all good',
+ numMons: 3,
+ numMgrs: 2,
+ numOsds: 6,
+ numOsdsUp: 6,
+ numOsdsIn: 6,
+ numPGs: 128,
+ pools: [
+ {
+ id: 11,
+ name: 'rbd',
+ storedBytes: 50,
+ availableBytes: 50,
+ objects: 10,
+ percentUsed: 50,
+ },
+ ],
+ services: [{ type: 'mon', running: 3, total: 3 }],
+ },
+ },
+ ...overrides,
+ }) as Resource;
+
+const makeCluster = (overrides: Partial<CephCluster> = {}): CephCluster =>
+ ({
+ id: 'c-1',
+ instance: 'cluster-main',
+ name: 'cluster-main Ceph',
+ health: 'HEALTH_OK',
+ healthMessage: '',
+ totalBytes: 300,
+ usedBytes: 120,
+ availableBytes: 180,
+ usagePercent: 40,
+ numMons: 3,
+ numMgrs: 2,
+ numOsds: 6,
+ numOsdsUp: 6,
+ numOsdsIn: 6,
+ numPGs: 128,
+ pools: [],
+ services: [],
+ lastUpdated: 1_700_000_000_000,
+ ...overrides,
+ }) as CephCluster;
+
+// ===========================================================================
+// buildExplicitCephClusters
+// ===========================================================================
+
+describe('buildExplicitCephClusters branch coverage', () => {
+ it('returns an empty array when resources is empty', () => {
+ expect(buildExplicitCephClusters([])).toEqual([]);
+ });
+
+ it('maps a fully-populated resource including pools and services', () => {
+ const [cluster] = buildExplicitCephClusters([makeResource()]);
+ expect(cluster).toMatchObject({
+ id: 'ceph-1',
+ instance: 'cluster-main',
+ name: 'ceph-main',
+ fsid: 'fsid-1',
+ health: 'HEALTH_OK',
+ healthMessage: 'all good',
+ totalBytes: 300,
+ usedBytes: 120,
+ availableBytes: 180,
+ usagePercent: 40,
+ numMons: 3,
+ numMgrs: 2,
+ numOsds: 6,
+ numOsdsUp: 6,
+ numOsdsIn: 6,
+ numPGs: 128,
+ lastUpdated: 1_700_000_000_000,
+ });
+ // pools are mapped to the cluster-internal shape (id is always 0 — see
+ // suspected bug note in GLM_REPORT.md).
+ expect(cluster.pools).toEqual([
+ {
+ id: 0,
+ name: 'rbd',
+ storedBytes: 50,
+ availableBytes: 50,
+ objects: 10,
+ percentUsed: 50,
+ },
+ ]);
+ expect(cluster.services).toEqual([{ type: 'mon', running: 3, total: 3 }]);
+ });
+
+ it('defaults everything when platformData is missing entirely', () => {
+ const [cluster] = buildExplicitCephClusters([
+ makeResource({ platformData: undefined }),
+ ]);
+ // platformData || {} -> cephMeta {} -> all ceph fields default.
+ expect(cluster.health).toBe('HEALTH_UNKNOWN');
+ expect(cluster.healthMessage).toBe('');
+ expect(cluster.fsid).toBeUndefined();
+ expect(cluster.numMons).toBe(0);
+ expect(cluster.numOsds).toBe(0);
+ expect(cluster.numPGs).toBe(0);
+ expect(cluster.pools).toBeUndefined();
+ expect(cluster.services).toBeUndefined();
+ // proxmox?.instance is absent -> falls back to platformId.
+ expect(cluster.instance).toBe('cluster-main');
+ });
+
+ it('defaults ceph counts to 0 and health to HEALTH_UNKNOWN when ceph meta exists but is sparse', () => {
+ const [cluster] = buildExplicitCephClusters([
+ makeResource({
+ platformData: { proxmox: { instance: 'cluster-main' }, ceph: {} },
+ }),
+ ]);
+ expect(cluster.health).toBe('HEALTH_UNKNOWN');
+ expect(cluster.healthMessage).toBe('');
+ expect(cluster.numMons).toBe(0);
+ expect(cluster.numMgrs).toBe(0);
+ expect(cluster.numOsds).toBe(0);
+ expect(cluster.numOsdsUp).toBe(0);
+ expect(cluster.numOsdsIn).toBe(0);
+ expect(cluster.numPGs).toBe(0);
+ });
+
+ it('falls back to resource.platformId when proxmox.instance is absent', () => {
+ const [cluster] = buildExplicitCephClusters([
+ makeResource({
+ platformId: 'fallback-pid',
+ platformData: { proxmox: {}, ceph: {} },
+ }),
+ ]);
+ expect(cluster.instance).toBe('fallback-pid');
+ });
+
+ it('falls back to empty string when neither proxmox.instance nor platformId exist', () => {
+ const [cluster] = buildExplicitCephClusters([
+ makeResource({
+ platformId: '',
+ platformData: { proxmox: {}, ceph: {} },
+ }),
+ ]);
+ expect(cluster.instance).toBe('');
+ });
+
+ it('defaults all disk metrics to 0 when resource.disk is absent', () => {
+ const [cluster] = buildExplicitCephClusters([
+ makeResource({ disk: undefined }),
+ ]);
+ expect(cluster.totalBytes).toBe(0);
+ expect(cluster.usedBytes).toBe(0);
+ expect(cluster.availableBytes).toBe(0);
+ expect(cluster.usagePercent).toBe(0);
+ });
+
+ it('maps pools with default values when individual pool fields are missing', () => {
+ const [cluster] = buildExplicitCephClusters([
+ makeResource({
+ platformData: {
+ proxmox: { instance: 'cluster-main' },
+ ceph: {
+ pools: [
+ {}, // all fields absent
+ { name: 'only-name' },
+ ],
+ },
+ },
+ }),
+ ]);
+ expect(cluster.pools).toEqual([
+ { id: 0, name: '', storedBytes: 0, availableBytes: 0, objects: 0, percentUsed: 0 },
+ { id: 0, name: 'only-name', storedBytes: 0, availableBytes: 0, objects: 0, percentUsed: 0 },
+ ]);
+ });
+
+ it('maps services with default values when individual service fields are missing', () => {
+ const [cluster] = buildExplicitCephClusters([
+ makeResource({
+ platformData: {
+ proxmox: { instance: 'cluster-main' },
+ ceph: {
+ services: [{}, { type: 'mgr' }],
+ },
+ },
+ }),
+ ]);
+ expect(cluster.services).toEqual([
+ { type: '', running: 0, total: 0 },
+ { type: 'mgr', running: 0, total: 0 },
+ ]);
+ });
+
+ it('uses lastSeen verbatim when it is a positive finite number', () => {
+ const [cluster] = buildExplicitCephClusters([
+ makeResource({ lastSeen: 9_999_999 }),
+ ]);
+ expect(cluster.lastUpdated).toBe(9_999_999);
+ });
+
+ it('falls back to Date.now() for lastUpdated when lastSeen is 0 (falsy)', () => {
+ const before = Date.now();
+ const [cluster] = buildExplicitCephClusters([makeResource({ lastSeen: 0 })]);
+ const after = Date.now();
+ expect(cluster.lastUpdated).toBeGreaterThanOrEqual(before);
+ expect(cluster.lastUpdated).toBeLessThanOrEqual(after);
+ });
+});
+
+// ===========================================================================
+// deriveCephClustersFromStorageRecords
+// ===========================================================================
+
+describe('deriveCephClustersFromStorageRecords branch coverage', () => {
+ it('returns an empty array when records is empty', () => {
+ expect(deriveCephClustersFromStorageRecords([])).toEqual([]);
+ });
+
+ it('returns an empty array when no records are ceph storage records', () => {
+ // type 'dir' is not ceph, capabilities lack 'replication'.
+ const nonCeph = makeRecord({
+ id: 'nc-1',
+ details: { type: 'dir', node: 'pve1', parentName: 'pve1' },
+ capabilities: ['capacity'],
+ source: {
+ platform: 'truenas-scale',
+ family: 'virtualization',
+ origin: 'resource',
+ adapterId: 'a',
+ },
+ });
+ expect(deriveCephClustersFromStorageRecords([nonCeph])).toEqual([]);
+ });
+
+ it('skips non-ceph records and processes only ceph records in a mixed set', () => {
+ const nonCeph = makeRecord({
+ id: 'nc-1',
+ name: 'local',
+ details: { type: 'dir', node: 'pve1', parentName: 'pve1' },
+ capabilities: ['capacity'],
+ source: {
+ platform: 'truenas-scale',
+ family: 'virtualization',
+ origin: 'resource',
+ adapterId: 'a',
+ },
+ });
+ const ceph = makeRecord({
+ id: 'ceph-1',
+ details: { type: 'rbd', node: 'pve1', parentName: 'pve1' },
+ });
+ const clusters = deriveCephClustersFromStorageRecords([nonCeph, ceph]);
+ expect(clusters).toHaveLength(1);
+ expect(clusters[0].instance).toBe('cluster-main');
+ });
+
+ it('produces separate clusters when cluster keys differ', () => {
+ const clusterA = makeRecord({
+ id: 'r-a',
+ details: { type: 'rbd', node: 'pve1', parentName: 'pve1' },
+ refs: { platformEntityId: 'cluster-a' },
+ });
+ const clusterB = makeRecord({
+ id: 'r-b',
+ details: { type: 'rbd', node: 'pve2', parentName: 'pve2' },
+ refs: { platformEntityId: 'cluster-b' },
+ });
+ const clusters = deriveCephClustersFromStorageRecords([clusterA, clusterB]);
+ expect(clusters).toHaveLength(2);
+ const instances = clusters.map((c) => c.instance).sort();
+ expect(instances).toEqual(['cluster-a', 'cluster-b']);
+ });
+
+ it('clamps negative totalBytes and usedBytes to 0', () => {
+ const [cluster] = deriveCephClustersFromStorageRecords([
+ makeRecord({
+ id: 'neg-1',
+ capacity: {
+ totalBytes: -100,
+ usedBytes: -50,
+ freeBytes: 0,
+ usagePercent: null,
+ },
+ }),
+ ]);
+ expect(cluster.totalBytes).toBe(0);
+ expect(cluster.usedBytes).toBe(0);
+ expect(cluster.usagePercent).toBe(0);
+ });
+
+ it('computes freeBytes from total - used when freeBytes is null (the ?? arm)', () => {
+ const [cluster] = deriveCephClustersFromStorageRecords([
+ makeRecord({
+ id: 'null-free',
+ capacity: { totalBytes: 200, usedBytes: 80, freeBytes: null, usagePercent: null },
+ }),
+ ]);
+ expect(cluster.availableBytes).toBe(120);
+ });
+
+ it('uses freeBytes verbatim when it is 0 (not nullish — the ?? short-circuit)', () => {
+ // freeBytes 0 is NOT nullish, so ?? does NOT kick in. availableBytes is 0,
+ // NOT total - used (which would be 60). This distinguishes ?? from ||.
+ const [cluster] = deriveCephClustersFromStorageRecords([
+ makeRecord({
+ id: 'zero-free',
+ capacity: { totalBytes: 100, usedBytes: 40, freeBytes: 0, usagePercent: null },
+ }),
+ ]);
+ expect(cluster.availableBytes).toBe(0);
+ });
+
+ it('clamps negative freeBytes to 0', () => {
+ const [cluster] = deriveCephClustersFromStorageRecords([
+ makeRecord({
+ id: 'neg-free',
+ capacity: { totalBytes: 100, usedBytes: 40, freeBytes: -30, usagePercent: null },
+ }),
+ ]);
+ expect(cluster.availableBytes).toBe(0);
+ });
+
+ it('computes usagePercent from used/total when total is positive', () => {
+ const [cluster] = deriveCephClustersFromStorageRecords([
+ makeRecord({
+ id: 'pct-1',
+ capacity: { totalBytes: 400, usedBytes: 100, freeBytes: 300, usagePercent: null },
+ }),
+ ]);
+ expect(cluster.usagePercent).toBe(25);
+ });
+
+ it('yields usagePercent 0 when total bytes for a cluster is 0', () => {
+ const [cluster] = deriveCephClustersFromStorageRecords([
+ makeRecord({
+ id: 'zero-total',
+ capacity: { totalBytes: 0, usedBytes: 0, freeBytes: 0, usagePercent: null },
+ }),
+ ]);
+ expect(cluster.usagePercent).toBe(0);
+ });
+
+ it('sets numMons to 1 and numMgrs to 1 when the cluster has a single node', () => {
+ const [cluster] = deriveCephClustersFromStorageRecords([makeRecord()]);
+ expect(cluster.numMons).toBe(1);
+ expect(cluster.numMgrs).toBe(1);
+ });
+
+ it('caps numMons at 3 and sets numMgrs to 2 when node count exceeds 3', () => {
+ // Five records with distinct node labels but the same cluster key -> 5
+ // unique nodes -> Math.min(3, Math.max(1, 5)) = 3 mons; numMgrs = 2.
+ const records: StorageRecord[] = ['n1', 'n2', 'n3', 'n4', 'n5'].map((node) =>
+ makeRecord({
+ id: `r-${node}`,
+ details: { type: 'rbd', node, parentName: node },
+ capacity: { totalBytes: 100, usedBytes: 10, freeBytes: 90, usagePercent: 10 },
+ }),
+ );
+ const [cluster] = deriveCephClustersFromStorageRecords(records);
+ expect(cluster.numMons).toBe(3);
+ expect(cluster.numMgrs).toBe(2);
+ });
+
+ it('sets numMons to 2 for exactly two distinct nodes', () => {
+ const records: StorageRecord[] = ['n1', 'n2'].map((node) =>
+ makeRecord({
+ id: `r-${node}`,
+ details: { type: 'rbd', node, parentName: node },
+ }),
+ );
+ const [cluster] = deriveCephClustersFromStorageRecords(records);
+ expect(cluster.numMons).toBe(2);
+ expect(cluster.numMgrs).toBe(2);
+ });
+
+ it('derives numOsds and numPGs from record count', () => {
+ // 3 records -> numOsds = max(1, 3*2) = 6; numPGs = max(128, 3*64) = 192.
+ const records: StorageRecord[] = ['n1', 'n2', 'n3'].map((node) =>
+ makeRecord({
+ id: `r-${node}`,
+ details: { type: 'rbd', node, parentName: node },
+ }),
+ );
+ const [cluster] = deriveCephClustersFromStorageRecords(records);
+ expect(cluster.numOsds).toBe(6);
+ expect(cluster.numOsdsUp).toBe(6);
+ expect(cluster.numOsdsIn).toBe(6);
+ expect(cluster.numPGs).toBe(192);
+ });
+
+ it('uses the derived cluster shape with HEALTH_UNKNOWN and a diagnostic healthMessage', () => {
+ const [cluster] = deriveCephClustersFromStorageRecords([makeRecord()]);
+ expect(cluster.health).toBe('HEALTH_UNKNOWN');
+ expect(cluster.healthMessage).toBe(
+ 'Derived from storage metrics - live Ceph telemetry unavailable.',
+ );
+ expect(cluster.pools).toBeUndefined();
+ expect(cluster.services).toBeUndefined();
+ expect(cluster.name).toBe('cluster-main Ceph');
+ });
+});
+
+// ===========================================================================
+// summarizeCephClusters
+// ===========================================================================
+
+describe('summarizeCephClusters branch coverage', () => {
+ it('returns all-zero totals and usagePercent 0 for an empty clusters array', () => {
+ expect(summarizeCephClusters([])).toEqual({
+ clusters: [],
+ totalBytes: 0,
+ usedBytes: 0,
+ availableBytes: 0,
+ usagePercent: 0,
+ });
+ });
+
+ it('clamps negative byte values to 0 in the totals', () => {
+ const result = summarizeCephClusters([
+ makeCluster({ totalBytes: -100, usedBytes: -50, availableBytes: -25 }),
+ ]);
+ expect(result.totalBytes).toBe(0);
+ expect(result.usedBytes).toBe(0);
+ expect(result.availableBytes).toBe(0);
+ expect(result.usagePercent).toBe(0);
+ });
+
+ it('treats null byte fields as 0 via the || fallback', () => {
+ const result = summarizeCephClusters([
+ {
+ ...makeCluster(),
+ totalBytes: null as unknown as number,
+ usedBytes: null as unknown as number,
+ availableBytes: null as unknown as number,
+ },
+ ]);
+ expect(result.totalBytes).toBe(0);
+ expect(result.usedBytes).toBe(0);
+ expect(result.availableBytes).toBe(0);
+ });
+
+ it('sums totals across multiple clusters and computes aggregate usagePercent', () => {
+ const result = summarizeCephClusters([
+ makeCluster({ totalBytes: 400, usedBytes: 100, availableBytes: 300 }),
+ makeCluster({
+ id: 'c-2',
+ instance: 'c2',
+ name: 'c2 Ceph',
+ totalBytes: 600,
+ usedBytes: 300,
+ availableBytes: 300,
+ }),
+ ]);
+ expect(result.clusters).toHaveLength(2);
+ expect(result.totalBytes).toBe(1000);
+ expect(result.usedBytes).toBe(400);
+ expect(result.availableBytes).toBe(600);
+ expect(result.usagePercent).toBe(40);
+ });
+
+ it('yields usagePercent 0 when the summed total is 0', () => {
+ const result = summarizeCephClusters([
+ makeCluster({ totalBytes: 0, usedBytes: 50, availableBytes: 0 }),
+ ]);
+ expect(result.usagePercent).toBe(0);
+ });
+});
+
+// ===========================================================================
+// resolveCephClusterForStorageRecord
+// ===========================================================================
+
+describe('resolveCephClusterForStorageRecord branch coverage', () => {
+ it('returns null when the lookup is empty', () => {
+ expect(resolveCephClusterForStorageRecord(makeRecord(), {})).toBeNull();
+ });
+
+ it('returns null when the resolved key is not present in the lookup', () => {
+ const cluster = makeCluster({ instance: 'other-cluster' });
+ expect(
+ resolveCephClusterForStorageRecord(makeRecord(), { 'other-cluster': cluster }),
+ ).toBeNull();
+ });
+
+ it('resolves via refs.platformEntityId (first-precedence key source)', () => {
+ const cluster = makeCluster();
+ const record = makeRecord({ refs: { platformEntityId: 'pe-key' } });
+ expect(resolveCephClusterForStorageRecord(record, { 'pe-key': cluster })).toBe(cluster);
+ });
+
+ it('resolves via details.parentId when platformEntityId is empty', () => {
+ const cluster = makeCluster();
+ const record = makeRecord({
+ refs: { platformEntityId: '' },
+ details: { type: 'rbd', parentId: 'par-key', node: 'pve1', parentName: 'pve1' },
+ });
+ expect(resolveCephClusterForStorageRecord(record, { 'par-key': cluster })).toBe(cluster);
+ });
+
+ it('resolves via location.label when platformEntityId and parentId are absent', () => {
+ const cluster = makeCluster();
+ const record = makeRecord({
+ refs: { platformEntityId: '' },
+ details: { type: 'rbd', node: 'pve1', parentName: 'pve1' },
+ location: { label: 'loc-key', scope: 'cluster' },
+ });
+ expect(resolveCephClusterForStorageRecord(record, { 'loc-key': cluster })).toBe(cluster);
+ });
+
+ it('resolves via source.platform when all higher-precedence identity fields are empty', () => {
+ const cluster = makeCluster();
+ const record = makeRecord({
+ refs: { platformEntityId: '' },
+ details: { type: 'rbd', node: 'pve1', parentName: 'pve1' },
+ location: { label: '', scope: 'cluster' },
+ source: {
+ platform: 'plat-key',
+ family: 'virtualization',
+ origin: 'resource',
+ adapterId: 'a',
+ },
+ });
+ expect(resolveCephClusterForStorageRecord(record, { 'plat-key': cluster })).toBe(cluster);
+ });
+});
diff --git a/frontend-modern/src/features/storageBackups/__tests__/resourceStoragePresentation.branchcov.test.ts b/frontend-modern/src/features/storageBackups/__tests__/resourceStoragePresentation.branchcov.test.ts
new file mode 100644
index 0000000000..2481f4c9c9
--- /dev/null
+++ b/frontend-modern/src/features/storageBackups/__tests__/resourceStoragePresentation.branchcov.test.ts
@@ -0,0 +1,646 @@
+import { describe, expect, it } from 'vitest';
+import type { Resource } from '@/types/resource';
+import {
+ getResourceStorageActionSummary,
+ getResourceStorageImpactSummary,
+ getResourceStorageIssueLabel,
+ getResourceStorageProtectionLabel,
+ getResourceStorageTopologyLabel,
+ isUnraidStorageResource,
+} from '@/features/storageBackups/resourceStoragePresentation';
+
+// Mirrors the sibling test factories. Pure-function module, so no Solid root
+// is required. Module-private target functions
+// (unraidShortSyncLabel / getUnraidShortProtectionLabel /
+// getUnraidShortIssueLabel / isAttentionStatus) are exercised transitively
+// through their exported callers.
+const makeResource = (overrides: Partial<Resource> = {}): Resource =>
+ ({
+ id: 'storage-1',
+ type: 'storage',
+ name: 'tank',
+ platformType: 'truenas',
+ sourceType: 'api',
+ status: 'online',
+ storage: {},
+ ...overrides,
+ }) as Resource;
+
+// ---------------------------------------------------------------------------
+// isUnraidStorageResource (exported)
+// ---------------------------------------------------------------------------
+
+describe('isUnraidStorageResource', () => {
+ it('returns false when storage metadata is absent', () => {
+ const resource = { ...makeResource(), storage: undefined } as unknown as Resource;
+ expect(isUnraidStorageResource(resource)).toBe(false);
+ });
+
+ it('returns false for empty storage metadata with no array, sync, or risk reasons', () => {
+ expect(isUnraidStorageResource(makeResource({ storage: {} }))).toBe(false);
+ });
+
+ it('returns true when arrayState is present', () => {
+ expect(isUnraidStorageResource(makeResource({ storage: { arrayState: 'STARTED' } }))).toBe(
+ true,
+ );
+ });
+
+ it('returns true when only syncAction is present (no arrayState)', () => {
+ expect(isUnraidStorageResource(makeResource({ storage: { syncAction: 'check' } }))).toBe(true);
+ });
+
+ it('returns true when a risk reason code starts with unraid_', () => {
+ const resource = makeResource({
+ storage: {
+ risk: {
+ level: 'warning',
+ reasons: [
+ { code: 'zfs_state', severity: 'warning', summary: 'irrelevant' },
+ { code: 'unraid_sync_active', severity: 'warning', summary: 'syncing' },
+ ],
+ },
+ },
+ });
+ expect(isUnraidStorageResource(resource)).toBe(true);
+ });
+
+ it('returns false when risk reasons exist but none start with unraid_', () => {
+ const resource = makeResource({
+ storage: {
+ risk: {
+ level: 'warning',
+ reasons: [{ code: 'zfs_state', severity: 'warning', summary: 'degraded' }],
+ },
+ },
+ });
+ expect(isUnraidStorageResource(resource)).toBe(false);
+ });
+
+ it('returns false when the risk reasons array is empty', () => {
+ const resource = makeResource({
+ storage: { risk: { level: 'warning', reasons: [] } },
+ });
+ expect(isUnraidStorageResource(resource)).toBe(false);
+ });
+
+ it('does not throw when a reason code is missing', () => {
+ const resource = {
+ ...makeResource(),
+ storage: {
+ risk: {
+ level: 'warning',
+ reasons: [{ summary: 'no code' }] as unknown as Resource['storage'] extends {
+ risk?: { reasons?: infer R };
+ }
+ ? R
+ : never,
+ },
+ },
+ } as unknown as Resource;
+ expect(isUnraidStorageResource(resource)).toBe(false);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// unraidShortSyncLabel (private) — exercised via getResourceStorageProtectionLabel
+// on Unraid resources with rebuildInProgress === true.
+// ---------------------------------------------------------------------------
+
+describe('unraidShortSyncLabel (via getResourceStorageProtectionLabel)', () => {
+ const rebuildResource = (syncAction: string | undefined, syncProgress?: number): Resource =>
+ makeResource({
+ storage: {
+ arrayState: 'STARTED',
+ rebuildInProgress: true,
+ syncAction,
+ syncProgress,
+ },
+ });
+
+ it('labels a parity rebuild for recon-p and rebuild sync actions', () => {
+ expect(getResourceStorageProtectionLabel(rebuildResource('recon-p'))).toBe('Parity rebuild');
+ expect(getResourceStorageProtectionLabel(rebuildResource('rebuild'))).toBe('Parity rebuild');
+ });
+
+ it('labels a parity sync action', () => {
+ expect(getResourceStorageProtectionLabel(rebuildResource('sync'))).toBe('Parity sync');
+ });
+
+ it('labels a clear action', () => {
+ expect(getResourceStorageProtectionLabel(rebuildResource('clear'))).toBe('Clearing');
+ });
+
+ it('falls back to Rebuilding for an empty sync action', () => {
+ expect(getResourceStorageProtectionLabel(rebuildResource(''))).toBe('Rebuilding');
+ });
+
+ it('falls back to Rebuilding for a whitespace-only sync action', () => {
+ expect(getResourceStorageProtectionLabel(rebuildResource(' '))).toBe('Rebuilding');
+ });
+
+ it('titleizes an unknown sync action in the default branch', () => {
+ expect(getResourceStorageProtectionLabel(rebuildResource('foo'))).toBe('Foo');
+ });
+
+ it('titleizes a multi-word unknown sync action', () => {
+ expect(getResourceStorageProtectionLabel(rebuildResource('parity-sync'))).toBe('Parity Sync');
+ });
+
+ it('titleizes an unknown sync action case-insensitively', () => {
+ expect(getResourceStorageProtectionLabel(rebuildResource('CHECK'))).toBe('Parity check');
+ });
+
+ it('omits the progress suffix when syncProgress is zero', () => {
+ expect(getResourceStorageProtectionLabel(rebuildResource('check', 0))).toBe('Parity check');
+ });
+
+ it('omits the progress suffix when syncProgress is NaN (not finite)', () => {
+ expect(getResourceStorageProtectionLabel(rebuildResource('check', NaN))).toBe('Parity check');
+ });
+
+ it('omits the progress suffix when syncProgress is Infinity', () => {
+ expect(getResourceStorageProtectionLabel(rebuildResource('check', Infinity))).toBe(
+ 'Parity check',
+ );
+ });
+
+ it('omits the progress suffix when syncProgress is negative', () => {
+ expect(getResourceStorageProtectionLabel(rebuildResource('check', -5))).toBe('Parity check');
+ });
+
+ it('omits the progress suffix when syncProgress is not a number type', () => {
+ const resource = {
+ ...makeResource(),
+ storage: {
+ arrayState: 'STARTED',
+ rebuildInProgress: true,
+ syncAction: 'check',
+ syncProgress: '50' as unknown as number,
+ },
+ } as unknown as Resource;
+ expect(getResourceStorageProtectionLabel(resource)).toBe('Parity check');
+ });
+
+ it('rounds and appends positive syncProgress', () => {
+ expect(getResourceStorageProtectionLabel(rebuildResource('check', 47.6))).toBe(
+ 'Parity check (48%)',
+ );
+ });
+
+ it('omits the progress suffix when syncProgress is undefined', () => {
+ expect(getResourceStorageProtectionLabel(rebuildResource('recon'))).toBe('Parity rebuild');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// getUnraidShortProtectionLabel (private) — via getResourceStorageProtectionLabel
+// on Unraid resources without an active rebuild.
+// ---------------------------------------------------------------------------
+
+describe('getUnraidShortProtectionLabel (via getResourceStorageProtectionLabel)', () => {
+ it('returns No parity from the unraid_no_parity risk reason when protection is not "none"', () => {
+ const resource = makeResource({
+ storage: {
+ arrayState: 'STARTED',
+ protection: 'single',
+ protectionReduced: true,
+ risk: {
+ level: 'warning',
+ reasons: [
+ { code: 'unraid_no_parity', severity: 'warning', summary: 'no parity running' },
+ ],
+ },
+ },
+ });
+ expect(getResourceStorageProtectionLabel(resource)).toBe('No parity');
+ });
+
+ it('returns Parity unavailable when the unraid_parity_unavailable reason is present', () => {
+ const resource = makeResource({
+ storage: {
+ arrayState: 'STARTED',
+ protection: 'single',
+ protectionReduced: true,
+ risk: {
+ level: 'warning',
+ reasons: [
+ {
+ code: 'unraid_parity_unavailable',
+ severity: 'warning',
+ summary: 'parity disk unavailable',
+ },
+ ],
+ },
+ },
+ });
+ expect(getResourceStorageProtectionLabel(resource)).toBe('Parity unavailable');
+ });
+
+ it('returns Protection reduced when protection is reduced but no parity reason is present', () => {
+ const resource = makeResource({
+ storage: {
+ arrayState: 'STARTED',
+ protection: 'single',
+ protectionReduced: true,
+ },
+ });
+ // getUnraidShortProtectionLabel returns 'Protection reduced'; the caller
+ // then does NOT fall through because the label is non-empty.
+ expect(getResourceStorageProtectionLabel(resource)).toBe('Protection reduced');
+ });
+
+ it('falls through to the generic protection path when the Unraid array is healthy', () => {
+ // rebuildInProgress false + protectionReduced false => getUnraidShortProtectionLabel
+ // returns '' so getResourceStorageProtectionLabel continues.
+ const resource = makeResource({
+ storage: {
+ arrayState: 'STARTED',
+ protection: 'dual',
+ },
+ });
+ expect(getResourceStorageProtectionLabel(resource)).toBe('Dual');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// getUnraidShortIssueLabel (private) — via getResourceStorageIssueLabel
+// on Unraid resources.
+// ---------------------------------------------------------------------------
+
+describe('getUnraidShortIssueLabel (via getResourceStorageIssueLabel)', () => {
+ it('returns Parity unavailable for the unraid_parity_unavailable reason code', () => {
+ const resource = makeResource({
+ storage: {
+ arrayState: 'STARTED',
+ risk: {
+ level: 'warning',
+ reasons: [
+ {
+ code: 'unraid_parity_unavailable',
+ severity: 'warning',
+ summary: 'parity disk is down',
+ },
+ ],
+ },
+ },
+ });
+ expect(getResourceStorageIssueLabel(resource)).toBe('Parity unavailable');
+ });
+
+ it('returns the summary for the unraid_invalid_disks reason code', () => {
+ const resource = makeResource({
+ storage: {
+ arrayState: 'STARTED',
+ risk: {
+ level: 'warning',
+ reasons: [
+ { code: 'unraid_invalid_disks', severity: 'warning', summary: '2 invalid disks' },
+ ],
+ },
+ },
+ });
+ expect(getResourceStorageIssueLabel(resource)).toBe('2 invalid disks');
+ });
+
+ it('strips a leading "Unraid array reports " prefix from the summary', () => {
+ const resource = makeResource({
+ storage: {
+ arrayState: 'STARTED',
+ risk: {
+ level: 'warning',
+ reasons: [
+ {
+ code: 'unraid_disabled_disks',
+ severity: 'warning',
+ summary: 'Unraid array reports 1 disabled disk',
+ },
+ ],
+ },
+ },
+ });
+ expect(getResourceStorageIssueLabel(resource)).toBe('1 disabled disk');
+ });
+
+ it('leaves a bare "Unraid array reports" prefix intact because trim removes the trailing whitespace the regex needs', () => {
+ // trimSummary trims trailing whitespace BEFORE the prefix regex runs, so
+ // the regex's required `\s+` can only match internal whitespace — a bare
+ // prefix string passes through unchanged.
+ const resource = makeResource({
+ storage: {
+ arrayState: 'STARTED',
+ risk: {
+ level: 'warning',
+ reasons: [
+ {
+ code: 'unraid_missing_disks',
+ severity: 'warning',
+ summary: 'Unraid array reports ',
+ },
+ ],
+ },
+ },
+ });
+ expect(getResourceStorageIssueLabel(resource)).toBe('Unraid array reports');
+ });
+
+ it('falls back to Disk issue when the summary is whitespace only', () => {
+ const resource = makeResource({
+ storage: {
+ arrayState: 'STARTED',
+ risk: {
+ level: 'warning',
+ reasons: [{ code: 'unraid_invalid_disks', severity: 'warning', summary: ' ' }],
+ },
+ },
+ });
+ expect(getResourceStorageIssueLabel(resource)).toBe('Disk issue');
+ });
+
+ it('returns Healthy when the Unraid resource carries only non-attention reason codes', () => {
+ const resource = makeResource({
+ storage: {
+ arrayState: 'STARTED',
+ risk: {
+ level: 'warning',
+ reasons: [{ code: 'unraid_sync_active', severity: 'warning', summary: 'syncing' }],
+ },
+ },
+ });
+ expect(getResourceStorageIssueLabel(resource)).toBe('Healthy');
+ });
+
+ it('returns Healthy when the Unraid resource has no risk reasons at all', () => {
+ const resource = makeResource({ storage: { arrayState: 'STARTED' } });
+ expect(getResourceStorageIssueLabel(resource)).toBe('Healthy');
+ });
+
+ it('returns the first matching attention issue, not a later reason', () => {
+ const resource = makeResource({
+ storage: {
+ arrayState: 'STARTED',
+ risk: {
+ level: 'warning',
+ reasons: [
+ { code: 'unraid_sync_active', severity: 'warning', summary: 'syncing' },
+ { code: 'unraid_missing_disks', severity: 'warning', summary: '3 missing' },
+ ],
+ },
+ },
+ });
+ expect(getResourceStorageIssueLabel(resource)).toBe('3 missing');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// isAttentionStatus (private) — exercised via getResourceStorageIssueLabel,
+// which surfaces the composite posture summary only for attention statuses.
+// ---------------------------------------------------------------------------
+
+describe('isAttentionStatus (via getResourceStorageIssueLabel)', () => {
+ const postureResource = (status: string | undefined): Resource =>
+ makeResource({
+ status: status as Resource['status'],
+ storage: { postureSummary: 'At risk' },
+ });
+
+ it.each([
+ ['warn'],
+ ['critical'],
+ ['faulted'],
+ ['failed'],
+ ['error'],
+ ['unhealthy'],
+ ['down'],
+ ['unavailable'],
+ ])('treats status %s as an attention status', (status) => {
+ expect(getResourceStorageIssueLabel(postureResource(status))).toBe('At risk');
+ });
+
+ it('treats uppercase attention statuses case-insensitively', () => {
+ expect(getResourceStorageIssueLabel(postureResource('CRITICAL'))).toBe('At risk');
+ });
+
+ it.each([['unknown'], ['running'], ['idle'], ['online']])(
+ 'does not treat status %s as an attention status',
+ (status) => {
+ expect(getResourceStorageIssueLabel(postureResource(status))).toBe('Healthy');
+ },
+ );
+
+ it('returns false for an empty-string status', () => {
+ expect(getResourceStorageIssueLabel(postureResource(''))).toBe('Healthy');
+ });
+
+ it('returns false for a whitespace-only status', () => {
+ expect(getResourceStorageIssueLabel(postureResource(' '))).toBe('Healthy');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// getResourceStorageImpactSummary (exported)
+// ---------------------------------------------------------------------------
+
+describe('getResourceStorageImpactSummary', () => {
+ it('prefers incidentImpactSummary over every storage/PBS impact summary', () => {
+ const resource = makeResource({
+ incidentImpactSummary: 'Incident-level impact',
+ storage: { consumerImpactSummary: 'consumer impact' },
+ pbs: {
+ protectedWorkloadSummary: 'protected workload impact',
+ affectedDatastoreSummary: 'affected datastore impact',
+ },
+ });
+ expect(getResourceStorageImpactSummary(resource)).toBe('Incident-level impact');
+ });
+
+ it('returns the PBS affected datastore summary when no other impact is present', () => {
+ const resource = makeResource({
+ pbs: { affectedDatastoreSummary: 'Datastore ds-2 unavailable' },
+ });
+ expect(getResourceStorageImpactSummary(resource)).toBe('Datastore ds-2 unavailable');
+ });
+
+ it('prefers the storage consumer impact over PBS summaries', () => {
+ const resource = makeResource({
+ storage: { consumerImpactSummary: 'Affects 1 dependent resource' },
+ pbs: { affectedDatastoreSummary: 'should not win' },
+ });
+ expect(getResourceStorageImpactSummary(resource)).toBe('Affects 1 dependent resource');
+ });
+
+ it('prefers the PBS protected workload summary over the affected datastore summary', () => {
+ const resource = makeResource({
+ pbs: {
+ protectedWorkloadSummary: 'workload impact',
+ affectedDatastoreSummary: 'datastore impact',
+ },
+ });
+ expect(getResourceStorageImpactSummary(resource)).toBe('workload impact');
+ });
+
+ it('returns the default dependent-resources copy when every summary is blank', () => {
+ expect(getResourceStorageImpactSummary(makeResource())).toBe('No dependent resources');
+ });
+
+ it('returns the default when summaries are whitespace only', () => {
+ const resource = makeResource({
+ incidentImpactSummary: ' ',
+ storage: { consumerImpactSummary: ' ' },
+ });
+ expect(getResourceStorageImpactSummary(resource)).toBe('No dependent resources');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// getResourceStorageActionSummary (exported)
+// ---------------------------------------------------------------------------
+
+describe('getResourceStorageActionSummary', () => {
+ it('short-circuits to Monitor for an Unraid resource without an attention issue', () => {
+ const resource = makeResource({
+ incidentAction: 'should not win',
+ storage: {
+ arrayState: 'STARTED',
+ syncAction: 'check',
+ },
+ });
+ expect(getResourceStorageActionSummary(resource)).toBe('Monitor');
+ });
+
+ it('uses the rebuild summary when a non-Unraid rebuild is in progress', () => {
+ const resource = makeResource({
+ storage: {
+ rebuildInProgress: true,
+ rebuildSummary: 'Resilvering in progress',
+ },
+ });
+ expect(getResourceStorageActionSummary(resource)).toBe('Resilvering in progress');
+ });
+
+ it('falls back to Monitor rebuild progress when rebuildSummary is absent', () => {
+ const resource = makeResource({ storage: { rebuildInProgress: true } });
+ expect(getResourceStorageActionSummary(resource)).toBe('Monitor rebuild progress');
+ });
+
+ it('uses the protection summary when protection is reduced', () => {
+ const resource = makeResource({
+ storage: {
+ protectionReduced: true,
+ protectionSummary: 'Restore redundancy immediately',
+ },
+ });
+ expect(getResourceStorageActionSummary(resource)).toBe('Restore redundancy immediately');
+ });
+
+ it('falls back to Restore redundancy when protectionSummary is absent', () => {
+ const resource = makeResource({ storage: { protectionReduced: true } });
+ expect(getResourceStorageActionSummary(resource)).toBe('Restore redundancy');
+ });
+
+ it('prefers an incident action over rebuild/protection states', () => {
+ const resource = makeResource({
+ incidentAction: 'Investigate now',
+ storage: { rebuildInProgress: true, rebuildSummary: 'rebuilding' },
+ });
+ expect(getResourceStorageActionSummary(resource)).toBe('Investigate now');
+ });
+
+ it('returns Monitor for a healthy resource with no actionable state', () => {
+ expect(getResourceStorageActionSummary(makeResource())).toBe('Monitor');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// getResourceStorageTopologyLabel (exported) — edge cases complementing the
+// already-thorough coverage test.
+// ---------------------------------------------------------------------------
+
+describe('getResourceStorageTopologyLabel (edge cases)', () => {
+ it('lowercases storageType before switching so uppercase pool types classify', () => {
+ expect(getResourceStorageTopologyLabel(makeResource(), 'POOL')).toBe('Pool');
+ });
+
+ it('classifies a CEPHFS storage type case-insensitively', () => {
+ expect(getResourceStorageTopologyLabel(makeResource(), 'CephFS')).toBe('Cluster Storage');
+ });
+
+ it('titleizes an explicit topology arg that uses multiple delimiters', () => {
+ expect(getResourceStorageTopologyLabel(makeResource(), 'rbd', 'rebuilt_target')).toBe(
+ 'Rebuilt Target',
+ );
+ });
+
+ it('falls back through titleized storageType to titleized resource type for an unknown type', () => {
+ const resource = makeResource({ type: 'network' });
+ expect(getResourceStorageTopologyLabel(resource, '')).toBe('Network');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// getResourceStorageIssueLabel (exported) — Unraid issue surfacing.
+// ---------------------------------------------------------------------------
+
+describe('getResourceStorageIssueLabel (Unraid issue surfacing)', () => {
+ it('returns the Unraid attention issue rather than the Healthy default', () => {
+ const resource = makeResource({
+ storage: {
+ arrayState: 'STARTED',
+ risk: {
+ level: 'warning',
+ reasons: [
+ { code: 'unraid_parity_unavailable', severity: 'warning', summary: 'parity down' },
+ ],
+ },
+ },
+ });
+ expect(getResourceStorageIssueLabel(resource)).toBe('Parity unavailable');
+ });
+
+ it('returns Healthy for an Unraid resource whose issue is not an attention issue', () => {
+ const resource = makeResource({
+ storage: {
+ arrayState: 'STARTED',
+ risk: {
+ level: 'warning',
+ reasons: [{ code: 'unraid_sync_active', severity: 'warning', summary: 'syncing' }],
+ },
+ },
+ });
+ expect(getResourceStorageIssueLabel(resource)).toBe('Healthy');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// getResourceStorageProtectionLabel (exported) — fallback branches.
+// ---------------------------------------------------------------------------
+
+describe('getResourceStorageProtectionLabel (fallback branches)', () => {
+ it('uses Rebuild In Progress when a non-Unraid rebuild has no rebuildSummary', () => {
+ const resource = makeResource({ storage: { rebuildInProgress: true } });
+ expect(getResourceStorageProtectionLabel(resource)).toBe('Rebuild In Progress');
+ });
+
+ it('uses Protection Reduced when protection is reduced with no protectionSummary', () => {
+ const resource = makeResource({ storage: { protectionReduced: true } });
+ expect(getResourceStorageProtectionLabel(resource)).toBe('Protection Reduced');
+ });
+
+ it('uses Backup Risk for a recoverability incident with no incident label', () => {
+ const resource = makeResource({ incidentCategory: 'recoverability' });
+ expect(getResourceStorageProtectionLabel(resource)).toBe('Backup Risk');
+ });
+
+ it('returns Protected for a backup-repository resource with no explicit protection', () => {
+ const resource = makeResource({
+ type: 'pbs',
+ platformType: 'proxmox-pbs',
+ storage: { platform: 'proxmox-pbs', type: 'pbs' },
+ });
+ expect(getResourceStorageProtectionLabel(resource)).toBe('Protected');
+ });
+
+ it('returns Healthy for a plain non-repository resource with no protection metadata', () => {
+ expect(getResourceStorageProtectionLabel(makeResource({ storage: {} }))).toBe('Healthy');
+ });
+});
diff --git a/frontend-modern/src/features/storageBackups/__tests__/storagePoolDetailPresentation.branchcov.test.ts b/frontend-modern/src/features/storageBackups/__tests__/storagePoolDetailPresentation.branchcov.test.ts
new file mode 100644
index 0000000000..4d662bb933
--- /dev/null
+++ b/frontend-modern/src/features/storageBackups/__tests__/storagePoolDetailPresentation.branchcov.test.ts
@@ -0,0 +1,423 @@
+import { describe, expect, it } from 'vitest';
+import type { Resource } from '@/types/resource';
+import type { StorageRecord } from '@/features/storageBackups/models';
+import {
+ buildStoragePoolDetailConfigRows,
+ buildStoragePoolDetailTopologyRows,
+ buildStoragePoolDetailZfsSummary,
+ getStoragePoolLinkedDisks,
+ type StoragePoolDetailLinkedDisk,
+} from '@/features/storageBackups/storagePoolDetailPresentation';
+
+const buildRecord = (overrides: Partial<StorageRecord> = {}): StorageRecord => ({
+ id: 'storage-1',
+ name: 'tank',
+ category: 'pool',
+ health: 'healthy',
+ location: { label: 'host-1', scope: 'host' },
+ capacity: { totalBytes: 1000, usedBytes: 400, freeBytes: 600, usagePercent: 40 },
+ capabilities: ['capacity', 'health'],
+ source: {
+ platform: 'truenas',
+ family: 'onprem',
+ origin: 'resource',
+ adapterId: 'resource-storage',
+ },
+ observedAt: Date.now(),
+ ...overrides,
+});
+
+const unraidSource = (adapterId = 'resource-storage') => ({
+ platform: 'unraid',
+ family: 'onprem' as const,
+ origin: 'resource' as const,
+ adapterId,
+});
+
+const rowValue = (rows: { label: string; value: string }[], label: string): string | undefined =>
+ rows.find((row) => row.label === label)?.value;
+
+// ---------------------------------------------------------------------------
+// buildStoragePoolDetailConfigRows
+// ---------------------------------------------------------------------------
+
+describe('buildStoragePoolDetailConfigRows branch coverage', () => {
+ it('splices a Content row at index 3 (before Status) when details.content is present', () => {
+ const rows = buildStoragePoolDetailConfigRows(buildRecord({ details: { content: 'Media share' } }));
+ expect(rows[3]).toEqual({ label: 'Content', value: 'Media share' });
+ expect(rows[4]).toEqual({ label: 'Status', value: 'available' });
+ });
+
+ it('omits the Content row entirely when details.content is absent or blank', () => {
+ const rows = buildStoragePoolDetailConfigRows(buildRecord({ details: {} }));
+ expect(rows.some((row) => row.label === 'Content')).toBe(false);
+ });
+
+ it('renders Shared as "Yes" / "No" from a boolean details.shared and "-" when absent', () => {
+ expect(rowValue(buildStoragePoolDetailConfigRows(buildRecord({ details: { shared: true } })), 'Shared')).toBe(
+ 'Yes',
+ );
+ expect(rowValue(buildStoragePoolDetailConfigRows(buildRecord({ details: { shared: false } })), 'Shared')).toBe(
+ 'No',
+ );
+ expect(rowValue(buildStoragePoolDetailConfigRows(buildRecord({ details: {} })), 'Shared')).toBe('-');
+ });
+
+ it('shows "n/a" for Used/Free/Total when totalBytes is null (falsy)', () => {
+ const rows = buildStoragePoolDetailConfigRows(
+ buildRecord({ capacity: { totalBytes: null, usedBytes: null, freeBytes: null, usagePercent: null } }),
+ );
+ expect(rowValue(rows, 'Used')).toBe('n/a');
+ expect(rowValue(rows, 'Free')).toBe('n/a');
+ expect(rowValue(rows, 'Total')).toBe('n/a');
+ });
+
+ it('computes freeBytes from total - used when freeBytes is null and totalBytes > 0', () => {
+ const rows = buildStoragePoolDetailConfigRows(
+ buildRecord({ capacity: { totalBytes: 2048, usedBytes: 1024, freeBytes: null, usagePercent: 50 } }),
+ );
+ expect(rowValue(rows, 'Used')).toBe('1.00 KB');
+ expect(rowValue(rows, 'Free')).toBe('1.00 KB');
+ expect(rowValue(rows, 'Total')).toBe('2.00 KB');
+ });
+
+ it('clamps the computed freeBytes to 0 when used exceeds total', () => {
+ const rows = buildStoragePoolDetailConfigRows(
+ buildRecord({ capacity: { totalBytes: 100, usedBytes: 200, freeBytes: null, usagePercent: 200 } }),
+ );
+ expect(rowValue(rows, 'Free')).toBe('0 B');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// buildStoragePoolDetailTopologyRows
+// (also exercises module-private pluralize + readRecordDetailNumber)
+// ---------------------------------------------------------------------------
+
+describe('buildStoragePoolDetailTopologyRows branch coverage', () => {
+ it('returns an empty array for a non-UnRAID record', () => {
+ expect(buildStoragePoolDetailTopologyRows(buildRecord(), [])).toEqual([]);
+ });
+
+ it('summarizes a cache pool with "Cache pool" kind, cache-device count, and optional state/errors', () => {
+ const record = buildRecord({
+ source: unraidSource(),
+ details: { type: 'unraid-cache-pool', platform: 'unraid', arrayState: 'STARTED' },
+ });
+ const linkedDisks = [
+ { role: 'cache', spunDown: false, errorCount: 0 },
+ { role: 'cache', spunDown: false, errorCount: 0 },
+ { role: 'cache', spunDown: true, errorCount: 5 },
+ ] as unknown as StoragePoolDetailLinkedDisk[];
+
+ const rows = buildStoragePoolDetailTopologyRows(record, linkedDisks);
+
+ expect(rowValue(rows, 'Kind')).toBe('Cache pool');
+ expect(rowValue(rows, 'State')).toBe('Started');
+ expect(rowValue(rows, 'Devices')).toBe('3 disks'); // plural arm of pluralize
+ expect(rowValue(rows, 'Spun down')).toBe('1 disk'); // singular arm of pluralize
+ expect(rowValue(rows, 'Disk errors')).toBe('5');
+ expect(rowValue(rows, 'Parity')).toBeUndefined();
+ expect(rowValue(rows, 'Sync')).toBeUndefined();
+ });
+
+ it('falls back to linkedDisks.length for Devices when no disk carries the cache role', () => {
+ const record = buildRecord({
+ source: unraidSource(),
+ details: { type: 'unraid-cache-pool', platform: 'unraid' },
+ });
+ const linkedDisks = [
+ { role: '', spunDown: false, errorCount: 0 },
+ { role: '', spunDown: false, errorCount: 0 },
+ ] as unknown as StoragePoolDetailLinkedDisk[];
+
+ const rows = buildStoragePoolDetailTopologyRows(record, linkedDisks);
+
+ expect(rowValue(rows, 'Devices')).toBe('2 disks');
+ expect(rowValue(rows, 'State')).toBeUndefined(); // arrayState absent -> no State row
+ });
+
+ it('reports "None configured" parity and pluralized data disks for a minimal array', () => {
+ const record = buildRecord({
+ source: unraidSource(),
+ details: { type: 'unraid-array', platform: 'unraid', topology: 'array' },
+ });
+ const linkedDisks = [
+ { role: 'data', spunDown: false, errorCount: 0 },
+ { role: 'data', spunDown: false, errorCount: 0 },
+ ] as unknown as StoragePoolDetailLinkedDisk[];
+
+ const rows = buildStoragePoolDetailTopologyRows(record, linkedDisks);
+
+ expect(rowValue(rows, 'Kind')).toBe('Array');
+ expect(rowValue(rows, 'Parity')).toBe('None configured'); // parityDisks === 0 arm
+ expect(rowValue(rows, 'Data disks')).toBe('2 disks'); // plural arm of pluralize
+ expect(rowValue(rows, 'State')).toBeUndefined();
+ expect(rowValue(rows, 'Spun down')).toBeUndefined();
+ expect(rowValue(rows, 'Disk errors')).toBeUndefined();
+ expect(rowValue(rows, 'Sync')).toBeUndefined();
+ });
+
+ it('renders the Sync action without a percentage when syncProgress is 0', () => {
+ const record = buildRecord({
+ source: unraidSource(),
+ details: { type: 'unraid-array', platform: 'unraid', topology: 'array', syncAction: 'checking', syncProgress: 0 },
+ });
+ expect(rowValue(buildStoragePoolDetailTopologyRows(record, []), 'Sync')).toBe('checking');
+ });
+
+ it('renders the Sync action with a rounded percentage when syncProgress > 0', () => {
+ const record = buildRecord({
+ source: unraidSource(),
+ details: {
+ type: 'unraid-array',
+ platform: 'unraid',
+ topology: 'array',
+ syncAction: 'rebuilding',
+ syncProgress: 45.6,
+ },
+ });
+ expect(rowValue(buildStoragePoolDetailTopologyRows(record, []), 'Sync')).toBe('rebuilding (46%)');
+ });
+
+ it.each([
+ ['a string', 'not-a-number'],
+ ['NaN', Number.NaN],
+ ['Infinity', Number.POSITIVE_INFINITY],
+ ['-Infinity', Number.NEGATIVE_INFINITY],
+ ])('treats non-finite/non-numeric syncProgress (%s) as 0 so no percentage is shown', (_label, progress) => {
+ const record = buildRecord({
+ source: unraidSource(),
+ details: {
+ type: 'unraid-array',
+ platform: 'unraid',
+ topology: 'array',
+ syncAction: 'checking',
+ syncProgress: progress,
+ },
+ });
+ expect(rowValue(buildStoragePoolDetailTopologyRows(record, []), 'Sync')).toBe('checking');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// buildStoragePoolDetailZfsSummary
+// ---------------------------------------------------------------------------
+
+describe('buildStoragePoolDetailZfsSummary branch coverage', () => {
+ it('returns null when the record has no valid zfs pool', () => {
+ expect(buildStoragePoolDetailZfsSummary(buildRecord({ details: {} }))).toBeNull();
+ // Malformed pool: toZfsPool rejects a candidate whose devices field is not an array.
+ expect(
+ buildStoragePoolDetailZfsSummary(buildRecord({ details: { zfsPool: { state: 'ONLINE' } } })),
+ ).toBeNull();
+ });
+
+ it('produces an empty scan and a null errorSummary for a clean pool with scan "none"', () => {
+ const record = buildRecord({
+ details: {
+ zfsPool: {
+ state: 'ONLINE',
+ scan: 'none',
+ readErrors: 0,
+ writeErrors: 0,
+ checksumErrors: 0,
+ devices: [],
+ },
+ },
+ });
+ expect(buildStoragePoolDetailZfsSummary(record)).toEqual({
+ state: 'ONLINE',
+ scan: '',
+ errorSummary: null,
+ devices: [],
+ });
+ });
+
+ it('treats an empty-string scan the same as "none"', () => {
+ const record = buildRecord({
+ details: {
+ zfsPool: { state: 'DEGRADED', scan: '', readErrors: 0, writeErrors: 0, checksumErrors: 0, devices: [] },
+ },
+ });
+ expect(buildStoragePoolDetailZfsSummary(record)).toEqual({
+ state: 'DEGRADED',
+ scan: '',
+ errorSummary: null,
+ devices: [],
+ });
+ });
+
+ it('defaults missing device fields and yields an empty per-device error summary when all errors are zero', () => {
+ const record = buildRecord({
+ details: {
+ zfsPool: {
+ state: 'ONLINE',
+ scan: 'scrub ok',
+ readErrors: 0,
+ writeErrors: 0,
+ checksumErrors: 0,
+ devices: [{ name: 'sdc' }],
+ },
+ },
+ });
+ expect(buildStoragePoolDetailZfsSummary(record)).toEqual({
+ state: 'ONLINE',
+ scan: 'scrub ok',
+ errorSummary: null,
+ devices: [{ name: 'sdc', type: '', state: '', errorSummary: '', message: '' }],
+ });
+ });
+
+ it('builds a non-null pool-level errorSummary when any pool error counter is positive', () => {
+ const record = buildRecord({
+ details: {
+ zfsPool: {
+ state: 'FAULTED',
+ scan: 'none',
+ readErrors: 1,
+ writeErrors: 0,
+ checksumErrors: 0,
+ devices: [],
+ },
+ },
+ });
+ expect(buildStoragePoolDetailZfsSummary(record)).toEqual({
+ state: 'FAULTED',
+ scan: '',
+ errorSummary: 'Errors: R:1 W:0 C:0',
+ devices: [],
+ });
+ });
+});
+
+// ---------------------------------------------------------------------------
+// getStoragePoolLinkedDisks
+// (also exercises module-private diskRoleRank, readPhysicalDisk, readDiskDevPath,
+// and getUnraidStorageGroup)
+// ---------------------------------------------------------------------------
+
+describe('getStoragePoolLinkedDisks branch coverage', () => {
+ it('links a disk whose parentId matches record.id (direct-parent arm)', () => {
+ const record = buildRecord({ id: 'pool-1' });
+ const disk = {
+ id: 'd-1',
+ name: 'd-1',
+ parentId: 'pool-1',
+ physicalDisk: { devPath: '/dev/sda', storageRole: 'data', storageGroup: 'other' },
+ } as unknown as Resource;
+
+ expect(getStoragePoolLinkedDisks(record, [disk]).map((d) => d.id)).toEqual(['d-1']);
+ });
+
+ it('links a disk whose parentId matches refs.resourceId (legacy ref arm)', () => {
+ const record = buildRecord({ id: 'pool-1', refs: { resourceId: 'legacy-pool-1' } });
+ const disk = {
+ id: 'd-1',
+ name: 'd-1',
+ parentId: 'legacy-pool-1',
+ physicalDisk: { devPath: '/dev/sda', storageRole: 'data', storageGroup: 'other' },
+ } as unknown as Resource;
+
+ expect(getStoragePoolLinkedDisks(record, [disk]).map((d) => d.id)).toEqual(['d-1']);
+ });
+
+ it('falls back to disk.name for devPath and "Unknown" model when physicalDisk is entirely absent', () => {
+ const record = buildRecord({ id: 'pool-1' });
+ const disk = { id: 'bare-1', name: 'bare-1', parentId: 'pool-1' } as unknown as Resource;
+
+ const [linked] = getStoragePoolLinkedDisks(record, [disk]);
+
+ expect(linked.devPath).toBe('bare-1'); // readDiskDevPath -> '' -> fallback to disk.name
+ expect(linked.model).toBe('Unknown'); // readDiskModel default
+ expect(linked.temperature).toBe(0);
+ expect(linked.sizeLabel).toBe('');
+ expect(linked.diskType).toBe('');
+ expect(linked.hasIssue).toBe(false);
+ expect(linked.errorCount).toBe(0);
+ expect(linked.ioLabel).toBe('');
+ });
+
+ it('falls back to disk.name when physicalDisk exists but devPath is missing', () => {
+ const record = buildRecord({ id: 'pool-1' });
+ const disk = {
+ id: 'nodev',
+ name: 'NodevDisk',
+ parentId: 'pool-1',
+ physicalDisk: { storageRole: 'data' },
+ } as unknown as Resource;
+
+ expect(getStoragePoolLinkedDisks(record, [disk])[0].devPath).toBe('NodevDisk');
+ });
+
+ it('breaks role ties by devPath localeCompare', () => {
+ const record = buildRecord({ id: 'pool-1' });
+ const disks = [
+ { id: 'b', name: 'b', parentId: 'pool-1', physicalDisk: { devPath: '/dev/sdd', storageRole: 'data' } },
+ { id: 'a', name: 'a', parentId: 'pool-1', physicalDisk: { devPath: '/dev/sdc', storageRole: 'data' } },
+ ] as unknown as Resource[];
+
+ expect(getStoragePoolLinkedDisks(record, disks).map((d) => d.devPath)).toEqual(['/dev/sdc', '/dev/sdd']);
+ });
+
+ it('ranks roles parity(0) < data(1) < cache(2) < unknown(3)', () => {
+ const record = buildRecord({ id: 'pool-1' });
+ const disks = [
+ { id: 'u', name: 'u', parentId: 'pool-1', physicalDisk: { devPath: '/dev/sdz', storageRole: 'spare' } },
+ { id: 'c', name: 'c', parentId: 'pool-1', physicalDisk: { devPath: '/dev/sdy', storageRole: 'cache' } },
+ { id: 'p', name: 'p', parentId: 'pool-1', physicalDisk: { devPath: '/dev/sdv', storageRole: 'parity' } },
+ { id: 'd', name: 'd', parentId: 'pool-1', physicalDisk: { devPath: '/dev/sdx', storageRole: 'data' } },
+ ] as unknown as Resource[];
+
+ expect(getStoragePoolLinkedDisks(record, disks).map((d) => d.role)).toEqual([
+ 'parity',
+ 'data',
+ 'cache',
+ 'spare',
+ ]);
+ });
+
+ it('matches an UnRAID cache-pool disk by the trimmed record name used as storage group', () => {
+ const record = buildRecord({
+ id: 'cache-pool-1',
+ name: ' My Cache ',
+ source: unraidSource(),
+ details: { type: 'unraid-cache-pool', platform: 'unraid' },
+ });
+ const disks = [
+ { id: 'in', name: 'in', physicalDisk: { devPath: '/dev/sda', storageRole: 'cache', storageGroup: 'My Cache' } },
+ { id: 'out', name: 'out', physicalDisk: { devPath: '/dev/sdb', storageRole: 'cache', storageGroup: 'other' } },
+ ] as unknown as Resource[];
+
+ expect(getStoragePoolLinkedDisks(record, disks).map((d) => d.id)).toEqual(['in']);
+ });
+
+ it('matches an UnRAID array disk via topology "array" even when type is generic', () => {
+ const record = buildRecord({
+ id: 'arr-1',
+ name: 'Tower',
+ source: unraidSource(),
+ details: { type: 'pool', platform: 'unraid', topology: 'array' },
+ });
+ const disks = [
+ { id: 'in', name: 'in', physicalDisk: { devPath: '/dev/sda', storageRole: 'data', storageGroup: 'unraid-array' } },
+ { id: 'out', name: 'out', physicalDisk: { devPath: '/dev/sdb', storageRole: 'data', storageGroup: 'nope' } },
+ ] as unknown as Resource[];
+
+ expect(getStoragePoolLinkedDisks(record, disks).map((d) => d.id)).toEqual(['in']);
+ });
+
+ it('excludes disks when the UnRAID record resolves to an empty storage group', () => {
+ const record = buildRecord({
+ id: 'arr-2',
+ name: 'Tower',
+ source: unraidSource(),
+ details: { type: 'pool', platform: 'unraid', topology: '' },
+ });
+ const disks = [
+ { id: 'x', name: 'x', physicalDisk: { devPath: '/dev/sda', storageRole: 'data', storageGroup: 'unraid-array' } },
+ ] as unknown as Resource[];
+
+ expect(getStoragePoolLinkedDisks(record, disks)).toEqual([]);
+ });
+});
diff --git a/frontend-modern/src/utils/__tests__/discoveryPresentation.branchcov.test.ts b/frontend-modern/src/utils/__tests__/discoveryPresentation.branchcov.test.ts
new file mode 100644
index 0000000000..581c030415
--- /dev/null
+++ b/frontend-modern/src/utils/__tests__/discoveryPresentation.branchcov.test.ts
@@ -0,0 +1,438 @@
+import { describe, expect, it } from 'vitest';
+
+import type { DiscoveryFact, ResourceDiscovery } from '@/types/discovery';
+import {
+ getDiscoveryIdentifiedSummary,
+ getDiscoverySuggestedURLReason,
+ getDiscoveryURLSuggestionSourceLabel,
+ getNetworkDiscoverySectionPresentation,
+ hasMeaningfulDiscoveryContext,
+} from '@/utils/discoveryPresentation';
+
+// Baseline discovery record carries no meaningful signal: every "unknown" /
+// empty value, no ports, paths, facts, url or probe. hasMeaningfulDiscoveryContext
+// returns false for it, so individual tests add exactly one signal to isolate a branch.
+const makeDiscovery = (overrides: Partial<ResourceDiscovery> = {}): ResourceDiscovery =>
+ ({
+ id: 'disc-1',
+ resource_type: 'docker',
+ resource_id: 'res-1',
+ target_id: 'agent-1',
+ hostname: 'host',
+ service_type: 'unknown',
+ service_name: 'unknown',
+ service_version: 'unknown',
+ category: 'unknown',
+ cli_access: '',
+ facts: [],
+ config_paths: [],
+ data_paths: [],
+ log_paths: [],
+ ports: [],
+ user_notes: '',
+ user_secrets: {},
+ confidence: 0,
+ ai_reasoning: '',
+ discovered_at: '',
+ updated_at: '',
+ scan_duration: 0,
+ ...overrides,
+ }) as ResourceDiscovery;
+
+// Default fact is meaningful (value 'running', category 'service'): a record that
+// carries only this fact has meaningful context. Tests override one field at a time
+// to steer isMeaningfulDiscoveryFact down each rejection branch.
+const makeFact = (overrides: Partial<DiscoveryFact> = {}): DiscoveryFact => ({
+ category: 'service',
+ key: 'status',
+ value: 'running',
+ source: 'systemd',
+ confidence: 1,
+ discovered_at: '2026-06-01T00:00:00Z',
+ ...overrides,
+});
+
+describe('getDiscoveryURLSuggestionSourceLabel (branch coverage)', () => {
+ it.each<[string, string]>([
+ ['service_default_match', 'Known service default'],
+ ['service_default_variation_match', 'Known service variant'],
+ ['web_port_inference', 'Detected web port'],
+ ['host_management_profile_proxmox_node', 'Proxmox node profile'],
+ ['host_management_profile_linked_proxmox_node', 'Proxmox node profile'],
+ ['host_management_profile_pve', 'Proxmox node profile'],
+ ['host_management_profile_pbs', 'Proxmox Backup profile'],
+ ['host_management_profile_pmg', 'Proxmox Mail Gateway profile'],
+ ['host_management_profile_nas', 'NAS node profile'],
+ ['unrecognized_code', 'Discovery heuristic'],
+ ['', 'Discovery heuristic'],
+ ])('maps %p to %p', (code, label) => {
+ expect(getDiscoveryURLSuggestionSourceLabel(code)).toBe(label);
+ });
+
+ it('treats null and undefined codes as the empty default branch', () => {
+ expect(getDiscoveryURLSuggestionSourceLabel(null)).toBe('Discovery heuristic');
+ expect(getDiscoveryURLSuggestionSourceLabel(undefined)).toBe('Discovery heuristic');
+ });
+
+ it('trims surrounding whitespace before matching a known case', () => {
+ expect(getDiscoveryURLSuggestionSourceLabel(' web_port_inference ')).toBe('Detected web port');
+ expect(getDiscoveryURLSuggestionSourceLabel('\tservice_default_match\n')).toBe(
+ 'Known service default',
+ );
+ });
+});
+
+describe('getDiscoverySuggestedURLReason (branch coverage)', () => {
+ it('returns empty text/title when discovery is null or undefined', () => {
+ expect(getDiscoverySuggestedURLReason(null)).toEqual({ text: '', title: '' });
+ expect(getDiscoverySuggestedURLReason(undefined)).toEqual({ text: '', title: '' });
+ });
+
+ it('uses the source label for both text and title when only a code is present', () => {
+ expect(getDiscoverySuggestedURLReason({ suggested_url_source_code: 'web_port_inference' })).toEqual({
+ text: 'Detected web port',
+ title: 'Detected web port',
+ });
+ });
+
+ it('falls back to the generic heuristic title and empty text with neither code nor detail', () => {
+ expect(getDiscoverySuggestedURLReason({})).toEqual({ text: '', title: 'Discovery heuristic' });
+ });
+
+ it('capitalises a lowercase detail sentence and pairs it with the default label title', () => {
+ expect(
+ getDiscoverySuggestedURLReason({ suggested_url_source_detail: 'guessed from http banner' }),
+ ).toEqual({
+ text: 'Guessed from http banner',
+ title: 'Discovery heuristic: guessed from http banner',
+ });
+ });
+
+ it('keeps the raw detail in the title but sentences it for the text', () => {
+ // toSentence trims+capitalises the detail; the title template interpolates the raw
+ // detail, so a trailing-space detail surfaces verbatim in the title only.
+ expect(
+ getDiscoverySuggestedURLReason({
+ suggested_url_source_code: 'web_port_inference',
+ suggested_url_source_detail: ' detected on 8080/tcp ',
+ }),
+ ).toEqual({
+ text: 'Detected on 8080/tcp',
+ title: 'Detected web port: detected on 8080/tcp ',
+ });
+ });
+});
+
+describe('hasMeaningfulDiscoveryContext (branch coverage)', () => {
+ it('returns false for null and undefined', () => {
+ expect(hasMeaningfulDiscoveryContext(null)).toBe(false);
+ expect(hasMeaningfulDiscoveryContext(undefined)).toBe(false);
+ });
+
+ it('returns false for an all-unknown, empty baseline record', () => {
+ expect(hasMeaningfulDiscoveryContext(makeDiscovery())).toBe(false);
+ });
+
+ it('treats non-array port/path fields as zero-length rather than throwing', () => {
+ const discovery = makeDiscovery({
+ ports: undefined,
+ config_paths: null as unknown as string[],
+ data_paths: undefined,
+ log_paths: null as unknown as string[],
+ });
+ expect(hasMeaningfulDiscoveryContext(discovery)).toBe(false);
+ });
+
+ it('is truthy on a meaningful service_name alone', () => {
+ expect(hasMeaningfulDiscoveryContext(makeDiscovery({ service_name: 'Nginx' }))).toBe(true);
+ });
+
+ it('is truthy on a meaningful service_type alone', () => {
+ expect(hasMeaningfulDiscoveryContext(makeDiscovery({ service_type: 'postgres' }))).toBe(true);
+ });
+
+ it('is truthy on a meaningful service_version alone', () => {
+ expect(hasMeaningfulDiscoveryContext(makeDiscovery({ service_version: '1.2.3' }))).toBe(true);
+ });
+
+ it('is truthy on a meaningful category alone', () => {
+ expect(hasMeaningfulDiscoveryContext(makeDiscovery({ category: 'database' }))).toBe(true);
+ });
+
+ it('is truthy when any port is present', () => {
+ expect(
+ hasMeaningfulDiscoveryContext(
+ makeDiscovery({ ports: [{ port: 5432, protocol: 'tcp', process: 'postgres', address: '0.0.0.0' }] }),
+ ),
+ ).toBe(true);
+ });
+
+ it('is truthy when only config_paths are present', () => {
+ expect(hasMeaningfulDiscoveryContext(makeDiscovery({ config_paths: ['/etc/nginx/nginx.conf'] }))).toBe(true);
+ });
+
+ it('is truthy when only data_paths are present', () => {
+ expect(hasMeaningfulDiscoveryContext(makeDiscovery({ data_paths: ['/var/lib/postgres'] }))).toBe(true);
+ });
+
+ it('is truthy when only log_paths are present', () => {
+ expect(hasMeaningfulDiscoveryContext(makeDiscovery({ log_paths: ['/var/log/nginx'] }))).toBe(true);
+ });
+
+ it('is truthy when only a suggested_url is present', () => {
+ expect(hasMeaningfulDiscoveryContext(makeDiscovery({ suggested_url: 'https://example.local' }))).toBe(true);
+ });
+
+ it('is truthy when only a suggested_availability_probe is present', () => {
+ expect(
+ hasMeaningfulDiscoveryContext(
+ makeDiscovery({
+ suggested_availability_probe: {
+ protocol: 'http',
+ address: '192.0.2.10',
+ port: 3000,
+ service_name: 'Grafana',
+ reason: 'service default',
+ },
+ }),
+ ),
+ ).toBe(true);
+ });
+});
+
+// isMeaningfulDiscoveryFact is module-private, so it is exercised through
+// hasMeaningfulDiscoveryContext using records that carry exactly one fact.
+describe('isMeaningfulDiscoveryFact (via hasMeaningfulDiscoveryContext, branch coverage)', () => {
+ const factOnly = (fact: DiscoveryFact): ResourceDiscovery => makeDiscovery({ facts: [fact] });
+
+ it('rejects a fact whose value is a non-meaningful token', () => {
+ // Bare stoplist tokens...
+ expect(hasMeaningfulDiscoveryContext(factOnly(makeFact({ value: 'unknown' })))).toBe(false);
+ expect(hasMeaningfulDiscoveryContext(factOnly(makeFact({ value: 'none' })))).toBe(false);
+ expect(hasMeaningfulDiscoveryContext(factOnly(makeFact({ value: '' })))).toBe(false);
+ // ...and the hyphen/underscore form of "n a", which normalises into the stoplist.
+ expect(hasMeaningfulDiscoveryContext(factOnly(makeFact({ value: 'N-A' })))).toBe(false);
+ expect(hasMeaningfulDiscoveryContext(factOnly(makeFact({ value: 'system_container' })))).toBe(false);
+ });
+
+ it('treats a slash-bearing token like "n/a" as meaningful (slashes are not normalised away)', () => {
+ expect(hasMeaningfulDiscoveryContext(factOnly(makeFact({ value: 'n/a' })))).toBe(true);
+ });
+
+ it('rejects a metadata-sourced status fact', () => {
+ expect(
+ hasMeaningfulDiscoveryContext(factOnly(makeFact({ key: 'status', source: 'metadata' }))),
+ ).toBe(false);
+ });
+
+ it('rejects an availability fact whose value mentions missing', () => {
+ expect(
+ hasMeaningfulDiscoveryContext(
+ factOnly(makeFact({ key: 'config_availability', value: 'missing config file' })),
+ ),
+ ).toBe(false);
+ });
+
+ it('rejects a key that starts with missing', () => {
+ expect(
+ hasMeaningfulDiscoveryContext(factOnly(makeFact({ key: 'missing_key', value: 'present' }))),
+ ).toBe(false);
+ });
+
+ it('rejects a key that ends with missing', () => {
+ expect(
+ hasMeaningfulDiscoveryContext(factOnly(makeFact({ key: 'port_missing', value: 'present' }))),
+ ).toBe(false);
+ });
+
+ it('rejects a value that starts with "missing "', () => {
+ expect(
+ hasMeaningfulDiscoveryContext(factOnly(makeFact({ key: 'cfg', value: 'missing config' }))),
+ ).toBe(false);
+ });
+
+ it('rejects a value containing " missing "', () => {
+ expect(
+ hasMeaningfulDiscoveryContext(factOnly(makeFact({ key: 'cfg', value: 'a missing file' }))),
+ ).toBe(false);
+ });
+
+ it('rejects values containing "does not exist"', () => {
+ expect(
+ hasMeaningfulDiscoveryContext(factOnly(makeFact({ key: 'cfg', value: 'file does not exist' }))),
+ ).toBe(false);
+ });
+
+ it('rejects values containing "not found"', () => {
+ expect(
+ hasMeaningfulDiscoveryContext(factOnly(makeFact({ key: 'cfg', value: 'binary not found' }))),
+ ).toBe(false);
+ });
+
+ it('rejects values containing "failed"', () => {
+ expect(
+ hasMeaningfulDiscoveryContext(factOnly(makeFact({ key: 'cfg', value: 'command failed' }))),
+ ).toBe(false);
+ });
+
+ it('rejects values containing "error"', () => {
+ expect(
+ hasMeaningfulDiscoveryContext(factOnly(makeFact({ key: 'cfg', value: 'connection error' }))),
+ ).toBe(false);
+ });
+
+ it('rejects a fact whose category is outside the allow-list', () => {
+ expect(
+ hasMeaningfulDiscoveryContext(
+ factOnly(makeFact({ category: 'hardware', key: 'cpu', value: 'amd ryzen' })),
+ ),
+ ).toBe(false);
+ });
+
+ it('accepts a meaningful fact in an allowed category', () => {
+ expect(
+ hasMeaningfulDiscoveryContext(
+ factOnly(makeFact({ category: 'version', key: 'app_version', value: '1.2.3' })),
+ ),
+ ).toBe(true);
+ });
+});
+
+describe('getDiscoveryIdentifiedSummary (branch coverage)', () => {
+ it('zeroes out non-numeric confidence and non-array port/path counts', () => {
+ const summary = getDiscoveryIdentifiedSummary(
+ makeDiscovery({
+ service_name: 'Nginx',
+ confidence: 'high' as unknown as number,
+ ports: undefined,
+ config_paths: null as unknown as string[],
+ data_paths: undefined,
+ log_paths: null as unknown as string[],
+ }),
+ );
+ expect(summary).not.toBeNull();
+ expect(summary?.confidence).toBe(0);
+ expect(summary?.confidencePercent).toBe('0%');
+ expect(summary?.portCount).toBe(0);
+ expect(summary?.configPathCount).toBe(0);
+ expect(summary?.dataPathCount).toBe(0);
+ expect(summary?.logPathCount).toBe(0);
+ });
+
+ it('labels an unnamed service "Unidentified service" and trims meaningful type/version/category', () => {
+ const summary = getDiscoveryIdentifiedSummary(
+ makeDiscovery({
+ service_name: 'unknown',
+ service_type: ' nginx ',
+ service_version: ' 1.25.0 ',
+ category: 'web_server',
+ ports: [{ port: 80, protocol: 'tcp', process: 'nginx', address: '0.0.0.0' }],
+ }),
+ );
+ expect(summary?.serviceName).toBe('Unidentified service');
+ expect(summary?.serviceType).toBe('nginx');
+ expect(summary?.serviceVersion).toBe('1.25.0');
+ expect(summary?.category).toBe('web_server');
+ expect(summary?.portCount).toBe(1);
+ });
+
+ it('drops non-meaningful service_type/version/category even when the record is meaningful', () => {
+ const summary = getDiscoveryIdentifiedSummary(
+ makeDiscovery({
+ service_name: 'Redis',
+ service_type: 'service',
+ service_version: 'unknown',
+ category: 'unknown',
+ }),
+ );
+ expect(summary?.serviceName).toBe('Redis');
+ expect(summary?.serviceType).toBeUndefined();
+ expect(summary?.serviceVersion).toBeUndefined();
+ expect(summary?.category).toBeUndefined();
+ });
+
+ it('prefers updated_at for observedAt and falls back to discovered_at then undefined', () => {
+ const both = getDiscoveryIdentifiedSummary(
+ makeDiscovery({
+ service_name: 'X',
+ discovered_at: '2026-06-01T00:00:00Z',
+ updated_at: '2026-06-02T00:00:00Z',
+ }),
+ );
+ expect(both?.discoveredAt).toBe('2026-06-01T00:00:00Z');
+ expect(both?.observedAt).toBe('2026-06-02T00:00:00Z');
+
+ const discoveredOnly = getDiscoveryIdentifiedSummary(
+ makeDiscovery({ service_name: 'X', discovered_at: '2026-06-01T00:00:00Z' }),
+ );
+ expect(discoveredOnly?.observedAt).toBe('2026-06-01T00:00:00Z');
+
+ const neither = getDiscoveryIdentifiedSummary(makeDiscovery({ service_name: 'X' }));
+ expect(neither?.observedAt).toBeUndefined();
+ expect(neither?.discoveredAt).toBeUndefined();
+ });
+
+ it('trims cli_access and drops whitespace-only cli_access', () => {
+ const trimmed = getDiscoveryIdentifiedSummary(
+ makeDiscovery({ service_name: 'X', cli_access: ' docker exec -it web /bin/sh ' }),
+ );
+ expect(trimmed?.cliAccess).toBe('docker exec -it web /bin/sh');
+
+ const blank = getDiscoveryIdentifiedSummary(makeDiscovery({ service_name: 'X', cli_access: ' ' }));
+ expect(blank?.cliAccess).toBeUndefined();
+ });
+
+ it('normalises a whitespace-only suggested_url to undefined and flips hasEndpointCandidate', () => {
+ const summary = getDiscoveryIdentifiedSummary(
+ makeDiscovery({ service_name: 'X', suggested_url: ' ' }),
+ );
+ expect(summary?.suggestedUrl).toBeUndefined();
+ expect(summary?.hasEndpointCandidate).toBe(false);
+ });
+
+ it('trims a present suggested_url_diagnostic and drops an empty one', () => {
+ const present = getDiscoveryIdentifiedSummary(
+ makeDiscovery({ service_name: 'X', suggested_url_diagnostic: ' no host candidate ' }),
+ );
+ expect(present?.suggestedUrlDiagnostic).toBe('no host candidate');
+
+ const empty = getDiscoveryIdentifiedSummary(makeDiscovery({ service_name: 'X', suggested_url_diagnostic: '' }));
+ expect(empty?.suggestedUrlDiagnostic).toBeUndefined();
+ });
+
+ it('forwards a suggested availability probe and undefined when absent', () => {
+ const probe = {
+ protocol: 'http',
+ address: '192.0.2.10',
+ port: 3000,
+ service_name: 'Grafana',
+ reason: 'service default',
+ };
+ const withProbe = getDiscoveryIdentifiedSummary(
+ makeDiscovery({ service_name: 'Grafana', suggested_availability_probe: probe }),
+ );
+ expect(withProbe?.suggestedAvailabilityProbe).toEqual(probe);
+
+ const withoutProbe = getDiscoveryIdentifiedSummary(makeDiscovery({ service_name: 'Grafana' }));
+ expect(withoutProbe?.suggestedAvailabilityProbe).toBeUndefined();
+ });
+});
+
+describe('getNetworkDiscoverySectionPresentation (branch coverage)', () => {
+ it('labels the toggle "Disabled" when discovery is disabled', () => {
+ const presentation = getNetworkDiscoverySectionPresentation(false);
+ expect(presentation.toggleStateLabel).toBe('Disabled');
+ expect(presentation).toEqual({
+ headerTitle: 'Network discovery',
+ headerDescription: 'Control how Pulse scans your network for Proxmox services.',
+ toggleTitle: 'Automatic scanning',
+ toggleDescription:
+ 'Enable discovery to surface Proxmox VE, Proxmox Backup Server, and Proxmox Mail Gateway endpoints automatically.',
+ toggleStateLabel: 'Disabled',
+ scanScopeLabel: 'Scan scope',
+ commonNetworksLabel: 'Common networks',
+ environmentOverrideMessage:
+ 'Discovery settings are locked by environment variables. Update the service configuration and restart Pulse to change them here.',
+ });
+ });
+});
diff --git a/frontend-modern/src/utils/__tests__/infrastructureSummaryCache.branchcov.test.ts b/frontend-modern/src/utils/__tests__/infrastructureSummaryCache.branchcov.test.ts
new file mode 100644
index 0000000000..51b598cffc
--- /dev/null
+++ b/frontend-modern/src/utils/__tests__/infrastructureSummaryCache.branchcov.test.ts
@@ -0,0 +1,380 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import type {
+ ChartStats,
+ InfrastructureChartsResponse,
+ TimeRange,
+} from '@/api/charts';
+import { setOrgID } from '@/utils/apiClient';
+import {
+ __resetInfrastructureSummaryFetchesForTests,
+ extractInfrastructureSummaryChartMapFromInfrastructureResponse,
+ fetchInfrastructureSummaryAndCache,
+ persistInfrastructureSummaryCache,
+ readInfrastructureSummaryCache,
+} from '@/utils/infrastructureSummaryCache';
+
+// ChartsAPI is mocked so fetchInfrastructureSummaryAndCache is deterministic and
+// offline. apiClient stays real (setOrgID) and orgScope/events stay real, exactly
+// like the sibling infrastructureSummaryCache.test.ts.
+const mockGetCharts = vi.fn();
+
+vi.mock('@/api/charts', async () => {
+ const actual = await vi.importActual<typeof import('@/api/charts')>('@/api/charts');
+ return {
+ ...actual,
+ ChartsAPI: {
+ ...actual.ChartsAPI,
+ getInfrastructureSummaryCharts: (...args: unknown[]) => mockGetCharts(...args),
+ },
+ };
+});
+
+const DEFAULT_METRICS_KEY = 'cpu,memory,disk,diskread,diskwrite,netin,netout';
+
+const cacheKeyForRange = (
+ range: TimeRange,
+ orgScope = 'default',
+ metrics = DEFAULT_METRICS_KEY,
+) => `pulse.infrastructureSummaryCharts.${encodeURIComponent(orgScope)}::${range}::${metrics}`;
+
+interface MetricPoint {
+ timestamp: number;
+ value: number;
+}
+
+const metricPoint = (timestamp: number, value: number): MetricPoint => ({ timestamp, value });
+
+// Build a series of N points starting at `start`, stepping by `step` ms.
+const makeSeries = (count: number, start = 0, step = 30_000): MetricPoint[] =>
+ Array.from({ length: count }, (_, i) => metricPoint(start + i * step, i));
+
+const now = () => Date.now();
+
+// A minimal, type-correct InfrastructureChartsResponse fixture.
+const makeInfraResponse = (
+ overrides: Partial<InfrastructureChartsResponse> = {},
+): InfrastructureChartsResponse => ({
+ nodeData: {},
+ timestamp: now(),
+ stats: { oldestDataTimestamp: now() - 60_000 },
+ ...overrides,
+});
+
+// Shape of the JSON payload persistInfrastructureSummaryCache writes. Used to
+// hand-craft localStorage entries that exercise readInfrastructureSummaryCache's
+// invalidation / coercion branches directly.
+interface StoredPayload {
+ version: number;
+ range: TimeRange;
+ cachedAt: number;
+ metrics: string[];
+ oldestDataTimestamp: number | string | null;
+ charts: Record<string, Record<string, unknown>> | undefined;
+}
+
+const storePayload = (
+ range: TimeRange,
+ payload: StoredPayload,
+ orgScope = 'default',
+ metrics = DEFAULT_METRICS_KEY,
+) => {
+ window.localStorage.setItem(cacheKeyForRange(range, orgScope, metrics), JSON.stringify(payload));
+};
+
+const buildPayload = (overrides: Partial<StoredPayload> = {}): StoredPayload => ({
+ version: 5,
+ range: '1h',
+ cachedAt: now(),
+ metrics: ['cpu', 'memory', 'disk', 'diskread', 'diskwrite', 'netin', 'netout'],
+ oldestDataTimestamp: null,
+ charts: {},
+ ...overrides,
+});
+
+describe('extractInfrastructureSummaryChartMapFromInfrastructureResponse', () => {
+ it('returns an empty map when every data field is absent', () => {
+ const map = extractInfrastructureSummaryChartMapFromInfrastructureResponse(
+ makeInfraResponse({ nodeData: undefined }),
+ );
+ expect(map.size).toBe(0);
+ });
+
+ it('defaults missing nodeData to an empty object while still indexing agentData', () => {
+ const map = extractInfrastructureSummaryChartMapFromInfrastructureResponse(
+ makeInfraResponse({
+ nodeData: undefined,
+ agentData: {
+ 'agent-1': { cpu: makeSeries(2) },
+ },
+ }),
+ );
+ expect(map.size).toBe(1);
+ expect(map.get('agent-1')?.cpu?.length).toBe(2);
+ });
+
+ it('indexes node, dockerHost and agent entries as distinct keys', () => {
+ const map = extractInfrastructureSummaryChartMapFromInfrastructureResponse(
+ makeInfraResponse({
+ nodeData: { 'node-1': { cpu: makeSeries(1) } },
+ dockerHostData: { 'docker-1': { memory: makeSeries(1) } },
+ agentData: { 'agent-1': { disk: makeSeries(1) } },
+ }),
+ );
+ expect([...map.keys()].sort()).toEqual(['agent-1', 'docker-1', 'node-1']);
+ expect(map.get('node-1')?.cpu?.length).toBe(1);
+ expect(map.get('docker-1')?.memory?.length).toBe(1);
+ expect(map.get('agent-1')?.disk?.length).toBe(1);
+ });
+});
+
+describe('readInfrastructureSummaryCache invalidation', () => {
+ beforeEach(() => {
+ setOrgID('default');
+ localStorage.clear();
+ });
+
+ it('returns null on a cache miss (no raw entry)', () => {
+ expect(readInfrastructureSummaryCache('1h')).toBeNull();
+ });
+
+ it('evicts and returns null when the stored version mismatches', () => {
+ storePayload('1h', buildPayload({ version: 4 }));
+ expect(readInfrastructureSummaryCache('1h')).toBeNull();
+ expect(localStorage.getItem(cacheKeyForRange('1h'))).toBeNull();
+ });
+
+ it('evicts and returns null when the stored range mismatches', () => {
+ storePayload('1h', buildPayload({ range: '24h' }));
+ expect(readInfrastructureSummaryCache('1h')).toBeNull();
+ expect(localStorage.getItem(cacheKeyForRange('1h'))).toBeNull();
+ });
+
+ it('evicts and returns null when the stored metrics mismatch', () => {
+ storePayload('1h', buildPayload({ metrics: ['cpu'] }));
+ expect(readInfrastructureSummaryCache('1h')).toBeNull();
+ expect(localStorage.getItem(cacheKeyForRange('1h'))).toBeNull();
+ });
+
+ it('evicts and returns null when cachedAt is not a number', () => {
+ storePayload('1h', buildPayload({ cachedAt: 'recent' as unknown as number }));
+ expect(readInfrastructureSummaryCache('1h')).toBeNull();
+ expect(localStorage.getItem(cacheKeyForRange('1h'))).toBeNull();
+ });
+
+ it('evicts and returns null when the entry is older than a custom maxAgeMs', () => {
+ storePayload('1h', buildPayload({ cachedAt: now() - 100_000 }));
+ // default TTL (5m) still fresh
+ expect(readInfrastructureSummaryCache('1h')).not.toBeNull();
+ localStorage.clear();
+ storePayload('1h', buildPayload({ cachedAt: now() - 100_000 }));
+ expect(readInfrastructureSummaryCache('1h', 50_000)).toBeNull();
+ expect(localStorage.getItem(cacheKeyForRange('1h'))).toBeNull();
+ });
+
+ it('returns an empty map when charts is missing', () => {
+ storePayload('1h', buildPayload({ charts: undefined }));
+ const cached = readInfrastructureSummaryCache('1h');
+ expect(cached).not.toBeNull();
+ expect(cached?.map.size).toBe(0);
+ expect(cached?.cachedAt).toBeTypeOf('number');
+ });
+
+ it('coerces non-array series fields to empty arrays', () => {
+ storePayload(
+ '1h',
+ buildPayload({
+ charts: {
+ 'node-1': {
+ cpu: makeSeries(1),
+ memory: 123,
+ disk: 'not-an-array',
+ diskread: null,
+ diskwrite: undefined,
+ netin: {},
+ netout: [],
+ },
+ },
+ }),
+ );
+ const cached = readInfrastructureSummaryCache('1h');
+ const series = cached?.map.get('node-1');
+ expect(series).toBeDefined();
+ expect(series?.cpu?.length).toBe(1);
+ expect(series?.memory).toEqual([]);
+ expect(series?.disk).toEqual([]);
+ expect(series?.diskread).toEqual([]);
+ expect(series?.diskwrite).toEqual([]);
+ expect(series?.netin).toEqual([]);
+ expect(series?.netout).toEqual([]);
+ });
+
+ it('returns null oldestDataTimestamp when the stored value is not a finite number', () => {
+ storePayload(
+ '1h',
+ buildPayload({ oldestDataTimestamp: 'not-a-number', charts: undefined }),
+ );
+ const cached = readInfrastructureSummaryCache('1h');
+ expect(cached).not.toBeNull();
+ expect(cached?.oldestDataTimestamp).toBeNull();
+ });
+
+ it('returns the numeric oldestDataTimestamp on the happy path', () => {
+ const ts = now() - 5_000;
+ storePayload(
+ '1h',
+ buildPayload({ oldestDataTimestamp: ts, charts: undefined }),
+ );
+ expect(readInfrastructureSummaryCache('1h')?.oldestDataTimestamp).toBe(ts);
+ });
+
+ it('swallows malformed JSON and returns null', () => {
+ window.localStorage.setItem(cacheKeyForRange('1h'), '{not valid json');
+ expect(readInfrastructureSummaryCache('1h')).toBeNull();
+ });
+});
+
+describe('persistInfrastructureSummaryCache write-failure path', () => {
+ beforeEach(() => {
+ setOrgID('default');
+ localStorage.clear();
+ });
+
+ it('swallows a localStorage.setItem failure without throwing', () => {
+ const spy = vi
+ .spyOn(Storage.prototype, 'setItem')
+ .mockImplementation(() => {
+ throw new Error('QuotaExceededError');
+ });
+ try {
+ expect(() =>
+ persistInfrastructureSummaryCache(
+ '1h',
+ new Map([['node-1', { cpu: makeSeries(2) }]]),
+ now() - 60_000,
+ ),
+ ).not.toThrow();
+ expect(spy).toHaveBeenCalled();
+ } finally {
+ spy.mockRestore();
+ }
+ });
+});
+
+describe('toCachedChartData / trimPoints coverage via persist', () => {
+ beforeEach(() => {
+ setOrgID('default');
+ localStorage.clear();
+ });
+
+ it('fills absent series with empty arrays (?? [] arm) and keeps present series', () => {
+ persistInfrastructureSummaryCache(
+ '1h',
+ new Map([
+ // cpu present, every other series absent -> exercises the `data.X ?? []`
+ // fallback arm in toCachedChartData for all optional fields.
+ ['node-1', { cpu: makeSeries(3) }],
+ ]),
+ null,
+ );
+ const series = readInfrastructureSummaryCache('1h')?.map.get('node-1');
+ expect(series).toBeDefined();
+ expect(series?.cpu?.length).toBe(3);
+ expect(series?.memory).toEqual([]);
+ expect(series?.disk).toEqual([]);
+ expect(series?.diskread).toEqual([]);
+ expect(series?.diskwrite).toEqual([]);
+ expect(series?.netin).toEqual([]);
+ expect(series?.netout).toEqual([]);
+ });
+
+ it('returns the trimmed series as-is when it fits within the budget (result.length <= max arm)', () => {
+ // 361 points (> 360 max) exercises the stride-sampling path but produces a
+ // result shorter than max, so the final `result.length > max ? slice : result`
+ // ternary takes its `result` arm rather than re-slicing.
+ const series = makeSeries(361, now() - 361 * 30_000);
+ persistInfrastructureSummaryCache(
+ '1h',
+ new Map([['node-1', { cpu: series }]]),
+ null,
+ );
+ const cached = readInfrastructureSummaryCache('1h')?.map.get('node-1');
+ expect(cached?.cpu).toBeDefined();
+ // Stride of 2 over 361 points keeps the newest point and yields 181 samples.
+ const cachedCpu = cached?.cpu ?? [];
+ expect(cachedCpu.length).toBe(181);
+ expect(cachedCpu[cachedCpu.length - 1]?.timestamp).toBe(
+ series[series.length - 1]?.timestamp,
+ );
+ });
+});
+
+describe('countChartMapPoints coverage via fetch', () => {
+ beforeEach(() => {
+ mockGetCharts.mockReset();
+ __resetInfrastructureSummaryFetchesForTests();
+ setOrgID('default');
+ localStorage.clear();
+ });
+
+ it('counts points across mixed partial-series entries without dropping undefined fields', async () => {
+ // node-1 has only `cpu` (truthy length) and every other field undefined, so
+ // countChartMapPoints' `data.X?.length ?? 0` expression evaluates both the
+ // length arm (cpu) and the `?? 0` fallback (memory/disk/...). The perf-log
+ // data object is built eagerly on every successful fetch, so this exercises
+ // countChartMapPoints even though perf logging is disabled in tests.
+ const response = makeInfraResponse({
+ nodeData: { 'node-1': { cpu: makeSeries(4) } },
+ });
+ mockGetCharts.mockResolvedValueOnce(response);
+
+ const result = await fetchInfrastructureSummaryAndCache('1h', { caller: 'branchcov' });
+
+ expect(result.map.get('node-1')?.cpu?.length).toBe(4);
+ expect(mockGetCharts).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('fetchInfrastructureSummaryAndCache error + caller + stats branches', () => {
+ beforeEach(() => {
+ mockGetCharts.mockReset();
+ __resetInfrastructureSummaryFetchesForTests();
+ setOrgID('default');
+ localStorage.clear();
+ });
+
+ it('rethrows when ChartsAPI rejects (covers .catch perf-log + rethrow)', async () => {
+ mockGetCharts.mockRejectedValueOnce(new Error('boom'));
+ await expect(fetchInfrastructureSummaryAndCache('1h')).rejects.toThrow('boom');
+ // in-flight entry is cleared by .finally, so a second call issues a new request
+ mockGetCharts.mockRejectedValueOnce(new Error('boom2'));
+ await expect(fetchInfrastructureSummaryAndCache('1h')).rejects.toThrow('boom2');
+ expect(mockGetCharts).toHaveBeenCalledTimes(2);
+ });
+
+ it('falls back to null oldestDataTimestamp when stats.oldestDataTimestamp is missing', async () => {
+ const stats = {} as ChartStats;
+ mockGetCharts.mockResolvedValueOnce(
+ makeInfraResponse({ nodeData: { 'node-1': { cpu: makeSeries(1) } }, stats }),
+ );
+ const result = await fetchInfrastructureSummaryAndCache('1h');
+ expect(result.oldestDataTimestamp).toBeNull();
+ expect(result.map.get('node-1')?.cpu?.length).toBe(1);
+ });
+
+ it('falls back to null oldestDataTimestamp when stats.oldestDataTimestamp is non-numeric', async () => {
+ const stats = { oldestDataTimestamp: 'nope' } as unknown as ChartStats;
+ mockGetCharts.mockResolvedValueOnce(
+ makeInfraResponse({ nodeData: { 'node-1': { cpu: makeSeries(1) } }, stats }),
+ );
+ const result = await fetchInfrastructureSummaryAndCache('1h');
+ expect(result.oldestDataTimestamp).toBeNull();
+ });
+
+ it('defaults caller to unknown when options are omitted', async () => {
+ mockGetCharts.mockResolvedValueOnce(makeInfraResponse());
+ // No caller -> the `options?.caller || 'unknown'` expression takes its
+ // 'unknown' arm; the call still resolves and persists a cache entry.
+ await fetchInfrastructureSummaryAndCache('1h');
+ expect(readInfrastructureSummaryCache('1h')).not.toBeNull();
+ });
+});
diff --git a/frontend-modern/src/utils/__tests__/monitoredSystemPresentation.branchcov.test.ts b/frontend-modern/src/utils/__tests__/monitoredSystemPresentation.branchcov.test.ts
new file mode 100644
index 0000000000..808d48ceae
--- /dev/null
+++ b/frontend-modern/src/utils/__tests__/monitoredSystemPresentation.branchcov.test.ts
@@ -0,0 +1,296 @@
+import { describe, expect, it } from 'vitest';
+
+import type { MonitoredSystemImpactPreviewSummaryInput } from '@/utils/monitoredSystemPresentation';
+import {
+ buildMonitoredSystemImpactPreviewUnavailableState,
+ formatMonitoredSystemImpactPreviewSummary,
+ formatMonitoredSystemImpactPreviewUnavailableMessage,
+ formatMonitoredSystemSurfaceAttribution,
+ formatMonitoredSystemUsageUnavailableMessage,
+ getMonitoredSystemImpactPreviewTitle,
+ getMonitoredSystemSourceLabel,
+ getMonitoredSystemSurfaceTypeLabel,
+} from '@/utils/monitoredSystemPresentation';
+
+describe('getMonitoredSystemSourceLabel (branch coverage)', () => {
+ it('maps each canonical source token to its display label', () => {
+ expect(getMonitoredSystemSourceLabel('agent')).toBe('Agent');
+ expect(getMonitoredSystemSourceLabel('docker')).toBe('Docker');
+ expect(getMonitoredSystemSourceLabel('kubernetes')).toBe('Kubernetes');
+ expect(getMonitoredSystemSourceLabel('multiple')).toBe('Multiple Sources');
+ expect(getMonitoredSystemSourceLabel('pbs')).toBe('PBS');
+ expect(getMonitoredSystemSourceLabel('pmg')).toBe('PMG');
+ expect(getMonitoredSystemSourceLabel('proxmox')).toBe('Proxmox');
+ expect(getMonitoredSystemSourceLabel('truenas')).toBe('TrueNAS');
+ });
+
+ it('normalizes case and surrounding whitespace before matching', () => {
+ expect(getMonitoredSystemSourceLabel('DOCKER')).toBe('Docker');
+ expect(getMonitoredSystemSourceLabel(' Multiple ')).toBe('Multiple Sources');
+ });
+
+ it('returns an empty string for an empty or undefined source', () => {
+ expect(getMonitoredSystemSourceLabel('')).toBe('');
+ expect(getMonitoredSystemSourceLabel(undefined)).toBe('');
+ });
+
+ it('passes an unrecognized source through trimmed (without lower-casing) on the default arm', () => {
+ expect(getMonitoredSystemSourceLabel('BackupNinja')).toBe('BackupNinja');
+ expect(getMonitoredSystemSourceLabel(' HybridCloud ')).toBe('HybridCloud');
+ });
+});
+
+describe('getMonitoredSystemSurfaceTypeLabel (branch coverage)', () => {
+ it('maps each canonical surface type token to its display label', () => {
+ expect(getMonitoredSystemSurfaceTypeLabel('agent')).toBe('Host');
+ expect(getMonitoredSystemSurfaceTypeLabel('host')).toBe('Host');
+ expect(getMonitoredSystemSurfaceTypeLabel('kubernetes-cluster')).toBe('Kubernetes Cluster');
+ expect(getMonitoredSystemSurfaceTypeLabel('pbs-server')).toBe('PBS Server');
+ expect(getMonitoredSystemSurfaceTypeLabel('pmg-server')).toBe('PMG Server');
+ expect(getMonitoredSystemSurfaceTypeLabel('proxmox-node')).toBe('Proxmox Node');
+ expect(getMonitoredSystemSurfaceTypeLabel('truenas-system')).toBe('TrueNAS System');
+ });
+
+ it('returns the generic "System" label for an empty or undefined type', () => {
+ expect(getMonitoredSystemSurfaceTypeLabel('')).toBe('System');
+ expect(getMonitoredSystemSurfaceTypeLabel(undefined)).toBe('System');
+ });
+
+ it('title-cases a custom type with dashes and underscores on the default arm', () => {
+ expect(getMonitoredSystemSurfaceTypeLabel('custom_backend')).toBe('Custom Backend');
+ expect(getMonitoredSystemSurfaceTypeLabel('weird--type__x')).toBe('Weird Type X');
+ });
+
+ it('normalizes case before matching a canonical token', () => {
+ expect(getMonitoredSystemSurfaceTypeLabel('AGENT')).toBe('Host');
+ });
+});
+
+describe('formatMonitoredSystemUsageUnavailableMessage (branch coverage)', () => {
+ it('returns the rebuild-pending message for the rebuild reason', () => {
+ expect(
+ formatMonitoredSystemUsageUnavailableMessage('supplemental_inventory_rebuild_pending'),
+ ).toBe(
+ 'Pulse has collected provider-owned inventory and is rebuilding the canonical monitored-system ledger. Usage will appear when that rebuild finishes.',
+ );
+ });
+
+ it('falls back to the generic message for an unrecognized, empty, or missing reason', () => {
+ expect(formatMonitoredSystemUsageUnavailableMessage('some_other_reason')).toBe(
+ 'Pulse cannot currently verify monitored-system usage for this installation. Refresh after the monitoring runtime settles.',
+ );
+ expect(formatMonitoredSystemUsageUnavailableMessage('')).toBe(
+ 'Pulse cannot currently verify monitored-system usage for this installation. Refresh after the monitoring runtime settles.',
+ );
+ expect(formatMonitoredSystemUsageUnavailableMessage(undefined)).toBe(
+ 'Pulse cannot currently verify monitored-system usage for this installation. Refresh after the monitoring runtime settles.',
+ );
+ expect(formatMonitoredSystemUsageUnavailableMessage(' ')).toBe(
+ 'Pulse cannot currently verify monitored-system usage for this installation. Refresh after the monitoring runtime settles.',
+ );
+ });
+
+ it('matches the unsettled reason case-insensitively', () => {
+ expect(formatMonitoredSystemUsageUnavailableMessage('SUPPLEMENTAL_INVENTORY_UNSETTLED')).toBe(
+ 'Pulse is still collecting the first provider-owned inventory baseline. The monitored-system ledger will appear after that baseline completes.',
+ );
+ });
+});
+
+describe('formatMonitoredSystemImpactPreviewUnavailableMessage (branch coverage)', () => {
+ it('returns the unsettled impact message for the unsettled reason', () => {
+ expect(
+ formatMonitoredSystemImpactPreviewUnavailableMessage('supplemental_inventory_unsettled'),
+ ).toBe(
+ 'Pulse is still settling provider-owned inventory for this platform connection. You can still save the connection and review the impact after the first baseline finishes.',
+ );
+ });
+
+ it('falls back to the generic impact message for an unrecognized or missing reason', () => {
+ expect(formatMonitoredSystemImpactPreviewUnavailableMessage('unrecognized_reason')).toBe(
+ 'Pulse cannot verify monitored-system impact right now. You can still save the connection and review the impact after inventory refreshes.',
+ );
+ expect(formatMonitoredSystemImpactPreviewUnavailableMessage(undefined)).toBe(
+ 'Pulse cannot verify monitored-system impact right now. You can still save the connection and review the impact after inventory refreshes.',
+ );
+ expect(formatMonitoredSystemImpactPreviewUnavailableMessage('')).toBe(
+ 'Pulse cannot verify monitored-system impact right now. You can still save the connection and review the impact after inventory refreshes.',
+ );
+ });
+});
+
+describe('buildMonitoredSystemImpactPreviewUnavailableState (branch coverage)', () => {
+ it('returns null when the error code does not match', () => {
+ expect(buildMonitoredSystemImpactPreviewUnavailableState({ code: 'other_error' })).toBeNull();
+ expect(
+ buildMonitoredSystemImpactPreviewUnavailableState({ code: null, reason: 'supplemental_inventory_unsettled' }),
+ ).toBeNull();
+ });
+
+ it('matches the unavailable error code case-insensitively', () => {
+ expect(
+ buildMonitoredSystemImpactPreviewUnavailableState({
+ code: 'MONITORED_SYSTEM_USAGE_UNAVAILABLE',
+ reason: 'supplemental_inventory_unsettled',
+ }),
+ ).toEqual({
+ reason: 'supplemental_inventory_unsettled',
+ title: 'Monitored-system verification is temporarily unavailable',
+ message:
+ 'Pulse is still settling provider-owned inventory for this platform connection. You can still save the connection and review the impact after the first baseline finishes.',
+ });
+ });
+
+ it('coerces a null or whitespace-only reason to null and uses the fallback message', () => {
+ expect(
+ buildMonitoredSystemImpactPreviewUnavailableState({
+ code: 'monitored_system_usage_unavailable',
+ reason: undefined,
+ }),
+ ).toEqual({
+ reason: null,
+ title: 'Monitored-system verification is temporarily unavailable',
+ message:
+ 'Pulse cannot verify monitored-system impact right now. You can still save the connection and review the impact after inventory refreshes.',
+ });
+ expect(
+ buildMonitoredSystemImpactPreviewUnavailableState({
+ code: 'monitored_system_usage_unavailable',
+ reason: ' ',
+ }),
+ ).toEqual({
+ reason: null,
+ title: 'Monitored-system verification is temporarily unavailable',
+ message:
+ 'Pulse cannot verify monitored-system impact right now. You can still save the connection and review the impact after inventory refreshes.',
+ });
+ });
+
+ it('uses the rebuild-pending message for the rebuild reason', () => {
+ expect(
+ buildMonitoredSystemImpactPreviewUnavailableState({
+ code: 'monitored_system_usage_unavailable',
+ reason: 'supplemental_inventory_rebuild_pending',
+ }),
+ ).toEqual({
+ reason: 'supplemental_inventory_rebuild_pending',
+ title: 'Monitored-system verification is temporarily unavailable',
+ message:
+ 'Pulse has settled provider-owned inventory and is rebuilding the canonical monitored-system view. You can still save the connection and review the impact in a moment.',
+ });
+ });
+});
+
+describe('getMonitoredSystemImpactPreviewTitle (branch coverage)', () => {
+ it('falls back to the default title for an undefined preview', () => {
+ expect(getMonitoredSystemImpactPreviewTitle(undefined)).toBe('Monitored-system impact');
+ });
+
+ it('falls back to current when projected_count is absent or non-finite (delta 0)', () => {
+ expect(getMonitoredSystemImpactPreviewTitle({ current_count: 7 })).toBe(
+ 'This change keeps monitored-system count unchanged',
+ );
+ expect(
+ getMonitoredSystemImpactPreviewTitle({ current_count: 7, projected_count: Number.NaN }),
+ ).toBe('This change keeps monitored-system count unchanged');
+ });
+
+ it('clamps a negative current count to zero before computing delta', () => {
+ expect(getMonitoredSystemImpactPreviewTitle({ current_count: -3, projected_count: 1 })).toBe(
+ 'This change adds monitored systems',
+ );
+ });
+
+ it('clamps a negative projected count to zero so a drop registers as a removal', () => {
+ expect(getMonitoredSystemImpactPreviewTitle({ current_count: 1, projected_count: -2 })).toBe(
+ 'This change removes monitored systems',
+ );
+ });
+
+ it('treats a non-finite current count as zero', () => {
+ expect(
+ getMonitoredSystemImpactPreviewTitle({
+ current_count: Number.NaN,
+ projected_count: Number.NaN,
+ }),
+ ).toBe('This change keeps monitored-system count unchanged');
+ });
+});
+
+describe('formatMonitoredSystemImpactPreviewSummary (branch coverage)', () => {
+ it('describes an unchanged count and uses the singular form for one system', () => {
+ expect(
+ formatMonitoredSystemImpactPreviewSummary({ current_count: 3, projected_count: 3 }),
+ ).toBe(
+ 'Pulse currently counts 3 monitored systems. Saving this change would keep the count at 3 monitored systems.',
+ );
+ expect(
+ formatMonitoredSystemImpactPreviewSummary({ current_count: 1, projected_count: 1 }),
+ ).toBe(
+ 'Pulse currently counts 1 monitored system. Saving this change would keep the count at 1 monitored system.',
+ );
+ });
+
+ it('renders a negative delta without a leading plus sign', () => {
+ expect(
+ formatMonitoredSystemImpactPreviewSummary({ current_count: 5, projected_count: 2 }),
+ ).toBe(
+ 'Pulse currently counts 5 monitored systems. Saving this change would bring the count to 2 monitored systems (-3).',
+ );
+ });
+
+ it('falls back to current when projected_count is absent (delta 0)', () => {
+ expect(
+ formatMonitoredSystemImpactPreviewSummary({ current_count: 4 } as MonitoredSystemImpactPreviewSummaryInput),
+ ).toBe(
+ 'Pulse currently counts 4 monitored systems. Saving this change would keep the count at 4 monitored systems.',
+ );
+ });
+});
+
+describe('formatMonitoredSystemSurfaceAttribution (branch coverage)', () => {
+ it('omits the "via" clause when the source label is empty', () => {
+ expect(
+ formatMonitoredSystemSurfaceAttribution({ name: 'node-1', type: 'host', source: '' }),
+ ).toBe('node-1 (Host)');
+ });
+
+ it('omits the "via" clause when the source is undefined', () => {
+ expect(formatMonitoredSystemSurfaceAttribution({ name: 'node-1', type: 'host' })).toBe(
+ 'node-1 (Host)',
+ );
+ });
+
+ it('omits the "via" clause when the source label matches the type label case-insensitively', () => {
+ expect(
+ formatMonitoredSystemSurfaceAttribution({ name: 'pve', type: 'host', source: 'Host' }),
+ ).toBe('pve (Host)');
+ });
+
+ it('falls back to "Unnamed source" when the name is empty or whitespace', () => {
+ expect(
+ formatMonitoredSystemSurfaceAttribution({ name: '', type: 'host', source: 'vmware' }),
+ ).toBe('Unnamed source (Host via VMware)');
+ expect(
+ formatMonitoredSystemSurfaceAttribution({ name: ' ', type: 'docker-host', source: 'docker' }),
+ ).toBe('Unnamed source (Docker Host via Docker)');
+ });
+
+ it('renders both type and source when they differ', () => {
+ expect(
+ formatMonitoredSystemSurfaceAttribution({
+ name: 'cluster-1',
+ type: 'kubernetes-cluster',
+ source: 'kubernetes',
+ }),
+ ).toBe('cluster-1 (Kubernetes Cluster via Kubernetes)');
+ });
+
+ it('falls back to "Unnamed source" when the name property is missing', () => {
+ expect(
+ formatMonitoredSystemSurfaceAttribution(
+ { type: 'host', source: 'vmware' } as Parameters<typeof formatMonitoredSystemSurfaceAttribution>[0],
+ ),
+ ).toBe('Unnamed source (Host via VMware)');
+ });
+});
diff --git a/frontend-modern/src/utils/__tests__/patrolRunPresentation.branchcov.test.ts b/frontend-modern/src/utils/__tests__/patrolRunPresentation.branchcov.test.ts
new file mode 100644
index 0000000000..c12cc2ff4f
--- /dev/null
+++ b/frontend-modern/src/utils/__tests__/patrolRunPresentation.branchcov.test.ts
@@ -0,0 +1,773 @@
+import { describe, expect, it } from 'vitest';
+
+import type { PatrolRunRecord, PatrolTriggerStatus } from '@/api/patrol';
+import {
+ formatPatrolActivityBreakdown,
+ getPatrolActivityBreakdown,
+ getPatrolLatestRunPresentation,
+ getPatrolRunCoverageSummary,
+ getPatrolRunOperatorRecordPresentation,
+ getPatrolRunRecordSummaryPresentation,
+ getPatrolRunResourcesHeading,
+ getPatrolTriggerStatusSummary,
+} from '@/utils/patrolRunPresentation';
+import type { PatrolActivityBreakdown } from '@/utils/patrolRunPresentation';
+
+const REFERENCE_DATE = new Date('2026-03-12T12:00:00Z');
+
+const makeRun = (overrides: Partial<PatrolRunRecord> = {}): PatrolRunRecord => ({
+ id: 'run-1',
+ started_at: '2026-03-12T10:00:00Z',
+ completed_at: '2026-03-12T10:01:00Z',
+ duration_ms: 60_000,
+ type: 'patrol',
+ resources_checked: 0,
+ nodes_checked: 0,
+ guests_checked: 0,
+ docker_checked: 0,
+ storage_checked: 0,
+ hosts_checked: 0,
+ truenas_checked: 0,
+ pbs_checked: 0,
+ pmg_checked: 0,
+ kubernetes_checked: 0,
+ new_findings: 0,
+ existing_findings: 0,
+ rejected_findings: 0,
+ resolved_findings: 0,
+ auto_fix_count: 0,
+ findings_summary: 'ok',
+ finding_ids: [],
+ error_count: 0,
+ status: 'healthy',
+ triage_flags: 0,
+ tool_call_count: 0,
+ ...overrides,
+});
+
+const makeTriggerStatus = (
+ overrides: Partial<PatrolTriggerStatus> = {},
+): PatrolTriggerStatus => ({
+ running: false,
+ pending_triggers: 0,
+ current_interval_ms: 300_000,
+ recent_events: 0,
+ is_busy_mode: false,
+ alert_triggers_enabled: true,
+ anomaly_triggers_enabled: true,
+ ...overrides,
+});
+
+describe('getPatrolRunOperatorRecordPresentation (branch coverage)', () => {
+ it('falls back to generic review copy when status is error but runtimeFailure summary is unavailable', () => {
+ const result = getPatrolRunOperatorRecordPresentation(
+ makeRun({
+ status: 'error',
+ error_count: 0,
+ resources_checked: 10,
+ duration_ms: 60_000,
+ scope_resource_ids: [],
+ effective_scope_resource_ids: [],
+ }),
+ );
+ expect(result).toEqual({
+ headline: 'Patrol needs attention',
+ detail: 'Checked 10 resources in 1m. It ended with issues that need review.',
+ });
+ });
+
+ it('reports a completed-check headline for legacy runs without finding_ids', () => {
+ const result = getPatrolRunOperatorRecordPresentation(
+ makeRun({
+ status: 'healthy',
+ error_count: 0,
+ finding_ids: undefined,
+ resources_checked: 10,
+ duration_ms: 60_000,
+ }),
+ );
+ expect(result).toEqual({
+ headline: 'Completed check',
+ detail: 'Checked 10 resources in 1m. This older run has no issue list.',
+ });
+ });
+
+ it('reports fixed count without new findings', () => {
+ const result = getPatrolRunOperatorRecordPresentation(
+ makeRun({
+ auto_fix_count: 3,
+ new_findings: 0,
+ resources_checked: 10,
+ duration_ms: 60_000,
+ }),
+ );
+ expect(result).toEqual({
+ headline: 'Fixed 3 issues',
+ detail: 'Checked 10 resources in 1m. Fixed 3 issues.',
+ });
+ });
+
+ it('reports singular fixed count', () => {
+ const result = getPatrolRunOperatorRecordPresentation(
+ makeRun({
+ auto_fix_count: 1,
+ new_findings: 0,
+ resources_checked: 10,
+ duration_ms: 60_000,
+ }),
+ );
+ expect(result.headline).toBe('Fixed 1 issue');
+ });
+
+ it('reports confirmed-resolved findings', () => {
+ const result = getPatrolRunOperatorRecordPresentation(
+ makeRun({
+ resolved_findings: 2,
+ resources_checked: 10,
+ duration_ms: 60_000,
+ }),
+ );
+ expect(result).toEqual({
+ headline: 'Confirmed 2 issues resolved',
+ detail: 'Checked 10 resources in 1m. Confirmed 2 issues resolved.',
+ });
+ });
+
+ it('reports new findings ready for review when nothing was fixed', () => {
+ const result = getPatrolRunOperatorRecordPresentation(
+ makeRun({
+ new_findings: 5,
+ auto_fix_count: 0,
+ resources_checked: 10,
+ duration_ms: 60_000,
+ }),
+ );
+ expect(result).toEqual({
+ headline: 'Found 5 new issues',
+ detail: 'Checked 10 resources in 1m. Ready for review.',
+ });
+ });
+
+ it('reports singular new finding headline', () => {
+ const result = getPatrolRunOperatorRecordPresentation(
+ makeRun({
+ new_findings: 1,
+ resources_checked: 10,
+ duration_ms: 60_000,
+ }),
+ );
+ expect(result.headline).toBe('Found 1 new issue');
+ });
+
+ it('reports existing findings still open', () => {
+ const result = getPatrolRunOperatorRecordPresentation(
+ makeRun({
+ existing_findings: 4,
+ resources_checked: 10,
+ duration_ms: 60_000,
+ }),
+ );
+ expect(result).toEqual({
+ headline: '4 issues still open',
+ detail: 'Checked 10 resources in 1m. No new issues.',
+ });
+ });
+
+ it('reports singular existing finding headline', () => {
+ const result = getPatrolRunOperatorRecordPresentation(
+ makeRun({
+ existing_findings: 1,
+ resources_checked: 10,
+ duration_ms: 60_000,
+ }),
+ );
+ expect(result.headline).toBe('1 issue still open');
+ });
+
+ it('flags critical status with finding_ids as needing attention even without errors', () => {
+ const result = getPatrolRunOperatorRecordPresentation(
+ makeRun({
+ status: 'critical',
+ error_count: 0,
+ finding_ids: [],
+ resources_checked: 10,
+ duration_ms: 60_000,
+ }),
+ );
+ expect(result).toEqual({
+ headline: 'Patrol needs attention',
+ detail: 'Checked 10 resources in 1m. It ended with issues that need review.',
+ });
+ });
+
+ // formatRunActionContext: exercised through operator presentation detail string
+ it('exercises formatRunActionContext with coverage but no duration', () => {
+ const result = getPatrolRunOperatorRecordPresentation(
+ makeRun({
+ duration_ms: 0,
+ resources_checked: 7,
+ scope_resource_ids: [],
+ effective_scope_resource_ids: [],
+ }),
+ );
+ expect(result.detail).toBe('Checked 7 resources. No issues recorded.');
+ });
+
+ it('exercises formatRunActionContext with duration but no coverage', () => {
+ const result = getPatrolRunOperatorRecordPresentation(
+ makeRun({
+ duration_ms: 120_000,
+ resources_checked: 0,
+ scope_resource_ids: [],
+ effective_scope_resource_ids: [],
+ }),
+ );
+ expect(result.detail).toBe('Patrol ran in 2m. No issues recorded.');
+ });
+
+ it('exercises formatRunActionContext with neither coverage nor duration', () => {
+ const result = getPatrolRunOperatorRecordPresentation(
+ makeRun({
+ duration_ms: 0,
+ resources_checked: 0,
+ scope_resource_ids: [],
+ effective_scope_resource_ids: [],
+ }),
+ );
+ expect(result.detail).toBe('Patrol ran. No issues recorded.');
+ });
+});
+
+describe('getPatrolLatestRunPresentation (branch coverage)', () => {
+ it('returns undefined for an empty runs array', () => {
+ expect(getPatrolLatestRunPresentation([])).toBeUndefined();
+ });
+
+ it('returns undefined when no run has a non-empty timestamp', () => {
+ expect(
+ getPatrolLatestRunPresentation([
+ makeRun({ id: 'blank', started_at: ' ', completed_at: '' }),
+ makeRun({ id: 'blank2', started_at: '', completed_at: ' ' }),
+ ]),
+ ).toBeUndefined();
+ });
+
+ it('falls back to started_at for the timestamp when completed_at is empty', () => {
+ const result = getPatrolLatestRunPresentation([
+ makeRun({
+ id: 'started-only',
+ started_at: '2026-03-12T09:30:00Z',
+ completed_at: '',
+ type: 'patrol',
+ status: 'healthy',
+ error_count: 0,
+ finding_ids: ['finding-1'],
+ resources_checked: 0,
+ scope_resource_ids: [],
+ effective_scope_resource_ids: [],
+ }),
+ ]);
+ expect(result).toBeDefined();
+ expect(result?.timestamp).toBe('2026-03-12T09:30:00Z');
+ expect(result?.findingsSnapshotAvailable).toBe(true);
+ expect(result?.kindLabel).toBe('Patrol check');
+ });
+
+ it('reports findingsSnapshotAvailable true when finding_ids is an empty array', () => {
+ const result = getPatrolLatestRunPresentation([
+ makeRun({
+ finding_ids: [],
+ status: 'healthy',
+ error_count: 0,
+ resources_checked: 5,
+ scope_resource_ids: [],
+ effective_scope_resource_ids: [],
+ type: 'scoped',
+ }),
+ ]);
+ expect(result?.findingsSnapshotAvailable).toBe(true);
+ expect(result?.kindLabel).toBe('Targeted check');
+ });
+
+ it('skips runs with empty timestamps and finds the first run with a usable one', () => {
+ const result = getPatrolLatestRunPresentation([
+ makeRun({ id: 'empty-ts', started_at: '', completed_at: '' }),
+ makeRun({ id: 'real-ts', started_at: '2026-03-12T08:00:00Z', completed_at: '' }),
+ ]);
+ expect(result).toBeDefined();
+ expect(result?.timestamp).toBe('2026-03-12T08:00:00Z');
+ });
+});
+
+describe('getPatrolRunRecordSummaryPresentation (branch coverage)', () => {
+ it('returns generic review outcome when unhealthy without runtime failure detail', () => {
+ const result = getPatrolRunRecordSummaryPresentation(
+ makeRun({
+ status: 'critical',
+ error_count: 0,
+ finding_ids: [],
+ resources_checked: 10,
+ duration_ms: 60_000,
+ scope_resource_ids: [],
+ effective_scope_resource_ids: [],
+ }),
+ );
+ expect(result.summary).toBe('Checked 10 resources in 1m.');
+ expect(result.outcome).toBe('Patrol ended with issues requiring review.');
+ expect(result.action).toBeUndefined();
+ });
+
+ it('explains legacy runs without finding records', () => {
+ const result = getPatrolRunRecordSummaryPresentation(
+ makeRun({
+ status: 'healthy',
+ error_count: 0,
+ finding_ids: undefined,
+ resources_checked: 10,
+ duration_ms: 60_000,
+ }),
+ );
+ expect(result.summary).toBe('Checked 10 resources in 1m.');
+ expect(result.outcome).toBe(
+ 'This older run has no finding record, so Patrol cannot show its issue list.',
+ );
+ });
+
+ it('reports new findings without any fixes', () => {
+ const result = getPatrolRunRecordSummaryPresentation(
+ makeRun({
+ new_findings: 3,
+ auto_fix_count: 0,
+ resources_checked: 10,
+ duration_ms: 60_000,
+ }),
+ );
+ expect(result.outcome).toBe('Patrol found 3 new issues.');
+ });
+
+ it('reports new findings with fixes applied', () => {
+ const result = getPatrolRunRecordSummaryPresentation(
+ makeRun({
+ new_findings: 2,
+ auto_fix_count: 1,
+ resources_checked: 10,
+ duration_ms: 60_000,
+ }),
+ );
+ expect(result.outcome).toBe('Patrol found 2 new issues. Patrol fixed 1 issue.');
+ });
+
+ it('uses singular form for one new finding', () => {
+ const result = getPatrolRunRecordSummaryPresentation(
+ makeRun({
+ new_findings: 1,
+ auto_fix_count: 0,
+ resources_checked: 10,
+ duration_ms: 60_000,
+ }),
+ );
+ expect(result.outcome).toBe('Patrol found 1 new issue.');
+ });
+
+ it('reports existing findings with plural remain form', () => {
+ const result = getPatrolRunRecordSummaryPresentation(
+ makeRun({
+ existing_findings: 3,
+ new_findings: 0,
+ resources_checked: 10,
+ duration_ms: 60_000,
+ }),
+ );
+ expect(result.outcome).toBe('No new issues. 3 existing issues remain.');
+ });
+
+ it('reports existing findings with singular remains form', () => {
+ const result = getPatrolRunRecordSummaryPresentation(
+ makeRun({
+ existing_findings: 1,
+ new_findings: 0,
+ resources_checked: 10,
+ duration_ms: 60_000,
+ }),
+ );
+ expect(result.outcome).toBe('No new issues. 1 existing issue remains.');
+ });
+
+ it('omits duration from summary when duration_ms is zero', () => {
+ const result = getPatrolRunRecordSummaryPresentation(
+ makeRun({
+ duration_ms: 0,
+ resources_checked: 4,
+ scope_resource_ids: [],
+ effective_scope_resource_ids: [],
+ }),
+ );
+ expect(result.summary).toBe('Checked 4 resources.');
+ });
+});
+
+describe('formatPatrolActivityBreakdown (branch coverage)', () => {
+ it('formats alert-cleared segment', () => {
+ expect(
+ formatPatrolActivityBreakdown({
+ totalRuns: 1,
+ fullPatrols: 0,
+ verificationChecks: 0,
+ alertTriggeredRuns: 0,
+ anomalyTriggeredRuns: 0,
+ alertClearedRuns: 1,
+ otherScopedRuns: 0,
+ newFindings: 0,
+ } satisfies PatrolActivityBreakdown),
+ ).toBe('1 alert-cleared check');
+ });
+
+ it('formats verification segment', () => {
+ expect(
+ formatPatrolActivityBreakdown({
+ totalRuns: 1,
+ fullPatrols: 0,
+ verificationChecks: 1,
+ alertTriggeredRuns: 0,
+ anomalyTriggeredRuns: 0,
+ alertClearedRuns: 0,
+ otherScopedRuns: 0,
+ newFindings: 0,
+ } satisfies PatrolActivityBreakdown),
+ ).toBe('1 follow-up check');
+ });
+
+ it('formats other-scoped segment', () => {
+ expect(
+ formatPatrolActivityBreakdown({
+ totalRuns: 1,
+ fullPatrols: 0,
+ verificationChecks: 0,
+ alertTriggeredRuns: 0,
+ anomalyTriggeredRuns: 0,
+ alertClearedRuns: 0,
+ otherScopedRuns: 1,
+ newFindings: 0,
+ } satisfies PatrolActivityBreakdown),
+ ).toBe('1 targeted check');
+ });
+
+ it('returns empty string when all segments are zero', () => {
+ expect(
+ formatPatrolActivityBreakdown({
+ totalRuns: 0,
+ fullPatrols: 0,
+ verificationChecks: 0,
+ alertTriggeredRuns: 0,
+ anomalyTriggeredRuns: 0,
+ alertClearedRuns: 0,
+ otherScopedRuns: 0,
+ newFindings: 0,
+ } satisfies PatrolActivityBreakdown),
+ ).toBe('');
+ });
+
+ it('renders all segments in canonical order with plurals', () => {
+ expect(
+ formatPatrolActivityBreakdown({
+ totalRuns: 8,
+ fullPatrols: 2,
+ verificationChecks: 2,
+ alertTriggeredRuns: 2,
+ anomalyTriggeredRuns: 1,
+ alertClearedRuns: 1,
+ otherScopedRuns: 1,
+ newFindings: 0,
+ } satisfies PatrolActivityBreakdown),
+ ).toBe(
+ '2 full checks, 2 alert-triggered checks, 1 anomaly-triggered check, 1 alert-cleared check, 2 follow-up checks, 1 targeted check',
+ );
+ });
+});
+
+describe('getPatrolTriggerStatusSummary (branch coverage)', () => {
+ it('returns undefined when status is undefined', () => {
+ expect(getPatrolTriggerStatusSummary(undefined)).toBeUndefined();
+ });
+
+ it('returns undefined when triggers are unblocked and all flags are clean', () => {
+ expect(getPatrolTriggerStatusSummary(makeTriggerStatus())).toBeUndefined();
+ });
+
+ it('returns undefined when triggers are blocked but manual run is explicitly available', () => {
+ expect(
+ getPatrolTriggerStatusSummary(
+ makeTriggerStatus({ event_triggers_blocked: true }),
+ { manualRunAvailable: true },
+ ),
+ ).toBeUndefined();
+ });
+
+ it('returns undefined when blocked, manual unavailable, but no blocked reason given', () => {
+ expect(
+ getPatrolTriggerStatusSummary(
+ makeTriggerStatus({ event_triggers_blocked: true }),
+ { manualRunAvailable: false },
+ ),
+ ).toBeUndefined();
+ });
+
+ it('returns alerts-off note when only alert triggers are disabled', () => {
+ expect(
+ getPatrolTriggerStatusSummary(
+ makeTriggerStatus({
+ alert_triggers_enabled: false,
+ }),
+ ),
+ ).toBe('alerts off');
+ });
+
+ it('combines queued and busy-mode notes', () => {
+ expect(
+ getPatrolTriggerStatusSummary(
+ makeTriggerStatus({
+ pending_triggers: 2,
+ is_busy_mode: true,
+ }),
+ ),
+ ).toBe('2 queued · busy mode');
+ });
+
+ it('combines anomalies-off and alerts-off notes', () => {
+ expect(
+ getPatrolTriggerStatusSummary(
+ makeTriggerStatus({
+ alert_triggers_enabled: false,
+ anomaly_triggers_enabled: false,
+ }),
+ ),
+ ).toBe('alerts off · anomalies off');
+ });
+
+ it('returns the in-progress summary when manual is blocked by an already-running reason', () => {
+ expect(
+ getPatrolTriggerStatusSummary(
+ makeTriggerStatus({ event_triggers_blocked: true }),
+ {
+ manualRunAvailable: false,
+ manualRunBlockedReason: 'Patrol run is in progress',
+ },
+ ),
+ ).toBe(
+ 'A Patrol run is already in progress. New automatic and manual runs are paused until it finishes.',
+ );
+ });
+});
+
+describe('getPatrolActivityBreakdown + isSameLocalDay (branch coverage)', () => {
+ it('counts alert-cleared triggered scoped runs', () => {
+ const result = getPatrolActivityBreakdown(
+ [
+ makeRun({
+ id: 'cleared-1',
+ type: 'scoped',
+ trigger_reason: 'alert_cleared',
+ }),
+ ],
+ REFERENCE_DATE,
+ );
+ expect(result.alertClearedRuns).toBe(1);
+ expect(result.totalRuns).toBe(1);
+ });
+
+ it('counts verification-type runs as follow-up checks', () => {
+ const result = getPatrolActivityBreakdown(
+ [
+ makeRun({
+ id: 'verif-1',
+ type: 'verification',
+ trigger_reason: 'alert_fired',
+ }),
+ ],
+ REFERENCE_DATE,
+ );
+ expect(result.verificationChecks).toBe(1);
+ expect(result.alertTriggeredRuns).toBe(0);
+ });
+
+ it('counts unknown trigger reasons as other scoped runs', () => {
+ const result = getPatrolActivityBreakdown(
+ [
+ makeRun({
+ id: 'manual-1',
+ type: 'scoped',
+ trigger_reason: 'manual',
+ }),
+ ],
+ REFERENCE_DATE,
+ );
+ expect(result.otherScopedRuns).toBe(1);
+ });
+
+ it('counts scoped runs with no trigger reason as other scoped runs', () => {
+ const result = getPatrolActivityBreakdown(
+ [
+ makeRun({
+ id: 'no-trigger',
+ type: 'scoped',
+ trigger_reason: undefined,
+ }),
+ ],
+ REFERENCE_DATE,
+ );
+ expect(result.otherScopedRuns).toBe(1);
+ });
+
+ it('skips runs on a different local day', () => {
+ const result = getPatrolActivityBreakdown(
+ [
+ makeRun({
+ id: 'yesterday',
+ started_at: '2026-03-11T10:00:00Z',
+ completed_at: '2026-03-11T10:01:00Z',
+ type: 'patrol',
+ }),
+ ],
+ REFERENCE_DATE,
+ );
+ expect(result.totalRuns).toBe(0);
+ expect(result.fullPatrols).toBe(0);
+ });
+
+ it('skips runs with an invalid started_at timestamp (isSameLocalDay invalid-date branch)', () => {
+ const result = getPatrolActivityBreakdown(
+ [
+ makeRun({
+ id: 'bad-date',
+ started_at: 'not-a-valid-date',
+ }),
+ ],
+ REFERENCE_DATE,
+ );
+ expect(result.totalRuns).toBe(0);
+ });
+
+ it('skips runs with an empty started_at string (isSameLocalDay empty-timestamp branch)', () => {
+ const result = getPatrolActivityBreakdown(
+ [
+ makeRun({
+ id: 'empty-date',
+ started_at: '',
+ } as unknown as PatrolRunRecord),
+ ],
+ REFERENCE_DATE,
+ );
+ expect(result.totalRuns).toBe(0);
+ });
+
+ it('clamps negative new_findings to zero', () => {
+ const result = getPatrolActivityBreakdown(
+ [
+ makeRun({
+ id: 'neg-findings',
+ type: 'patrol',
+ new_findings: -5,
+ }),
+ ],
+ REFERENCE_DATE,
+ );
+ expect(result.totalRuns).toBe(1);
+ expect(result.newFindings).toBe(0);
+ });
+
+ it('accumulates new findings across multiple same-day runs', () => {
+ const result = getPatrolActivityBreakdown(
+ [
+ makeRun({ id: 'a', type: 'patrol', new_findings: 2 }),
+ makeRun({ id: 'b', type: 'patrol', new_findings: 3 }),
+ ],
+ REFERENCE_DATE,
+ );
+ expect(result.newFindings).toBe(5);
+ expect(result.fullPatrols).toBe(2);
+ });
+});
+
+describe('getPatrolRunResourcesHeading (branch coverage)', () => {
+ it('falls back to plain count when scoped resources exist but nothing was checked', () => {
+ expect(
+ getPatrolRunResourcesHeading({
+ resources_checked: 0,
+ scope_resource_ids: ['r1'],
+ effective_scope_resource_ids: ['r1'],
+ }),
+ ).toBe('Resources checked (0)');
+ });
+
+ it('falls back to plain count when all scoped resources were checked', () => {
+ expect(
+ getPatrolRunResourcesHeading({
+ resources_checked: 2,
+ scope_resource_ids: ['r1', 'r2'],
+ effective_scope_resource_ids: ['r1', 'r2'],
+ }),
+ ).toBe('Resources checked (2)');
+ });
+
+ it('returns zero count when no resources checked and no scope', () => {
+ expect(
+ getPatrolRunResourcesHeading({
+ resources_checked: 0,
+ scope_resource_ids: [],
+ effective_scope_resource_ids: [],
+ }),
+ ).toBe('Resources checked (0)');
+ });
+
+ it('shows partial count when fewer resources checked than scoped', () => {
+ expect(
+ getPatrolRunResourcesHeading({
+ resources_checked: 1,
+ scope_resource_ids: ['r1', 'r2', 'r3'],
+ effective_scope_resource_ids: ['r1', 'r2', 'r3'],
+ }),
+ ).toBe('Resources checked (1 of 3 scoped)');
+ });
+});
+
+describe('formatResourceCount via getPatrolRunCoverageSummary (branch coverage)', () => {
+ it('produces singular scoped-resource label for one checked of one scoped', () => {
+ expect(
+ getPatrolRunCoverageSummary({
+ resources_checked: 1,
+ scope_resource_ids: ['r1'],
+ effective_scope_resource_ids: ['r1'],
+ }),
+ ).toBe('Checked 1 scoped resource');
+ });
+
+ it('produces plural scoped-resource label for multiple checked meeting scope', () => {
+ expect(
+ getPatrolRunCoverageSummary({
+ resources_checked: 3,
+ scope_resource_ids: ['r1', 'r2', 'r3'],
+ effective_scope_resource_ids: ['r1', 'r2', 'r3'],
+ }),
+ ).toBe('Checked 3 scoped resources');
+ });
+
+ it('produces singular resource label without qualifier for one non-scoped resource', () => {
+ expect(
+ getPatrolRunCoverageSummary({
+ resources_checked: 1,
+ scope_resource_ids: [],
+ effective_scope_resource_ids: [],
+ }),
+ ).toBe('Checked 1 resource');
+ });
+
+ it('produces empty coverage summary when nothing checked and no scope', () => {
+ expect(
+ getPatrolRunCoverageSummary({
+ resources_checked: 0,
+ scope_resource_ids: [],
+ effective_scope_resource_ids: [],
+ }),
+ ).toBe('');
+ });
+});
diff --git a/frontend-modern/src/utils/__tests__/recoveryItemTypePresentation.branchcov.test.ts b/frontend-modern/src/utils/__tests__/recoveryItemTypePresentation.branchcov.test.ts
new file mode 100644
index 0000000000..018e053e05
--- /dev/null
+++ b/frontend-modern/src/utils/__tests__/recoveryItemTypePresentation.branchcov.test.ts
@@ -0,0 +1,193 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ getRecoveryItemTypeBadgeClass,
+ getRecoveryItemTypeLabel,
+ getRecoveryItemTypePresentation,
+ getRecoveryPointItemTypeKey,
+ getRecoveryRollupItemTypeKey,
+ normalizeRecoveryItemTypeQueryValue,
+} from '@/utils/recoveryItemTypePresentation';
+
+// These class-string constants are mirrored from the source module so assertions
+// describe the documented badge composition rather than echoing the function
+// under test. They are the building blocks the module concatenates.
+const BADGE_BASE_CLASSES =
+ 'inline-flex items-center rounded px-2 py-0.5 text-[10px] font-medium whitespace-nowrap';
+const TABLE_BADGE_BASE_CLASSES =
+ 'inline-flex items-center px-1 py-0.5 text-[10px] font-medium rounded whitespace-nowrap';
+const DEFAULT_BADGE_TONE_CLASSES = 'bg-surface-alt text-base-content';
+
+describe('recoveryItemTypePresentation branch coverage', () => {
+ describe('normalizeRecoveryItemTypeQueryValue', () => {
+ it('collapses nullish, empty, whitespace-only, and the "all" alias to an empty sentinel', () => {
+ expect(normalizeRecoveryItemTypeQueryValue(null)).toBe('');
+ expect(normalizeRecoveryItemTypeQueryValue(undefined)).toBe('');
+ expect(normalizeRecoveryItemTypeQueryValue('')).toBe('');
+ expect(normalizeRecoveryItemTypeQueryValue(' ')).toBe('');
+ // Case-insensitive: "ALL" lowercases into the explicit 'all' alias arm.
+ expect(normalizeRecoveryItemTypeQueryValue('ALL')).toBe('');
+ expect(normalizeRecoveryItemTypeQueryValue('all')).toBe('');
+ });
+
+ it('maps every vm-family alias onto the canonical "vm" key', () => {
+ expect(normalizeRecoveryItemTypeQueryValue('vm')).toBe('vm');
+ expect(normalizeRecoveryItemTypeQueryValue('vm-backup')).toBe('vm');
+ // 'proxmox-vm' / 'proxmox-vm-backup' already covered by the sibling test.
+ });
+
+ it('maps every system-container alias onto "system-container"', () => {
+ expect(normalizeRecoveryItemTypeQueryValue('proxmox-lxc')).toBe('system-container');
+ expect(normalizeRecoveryItemTypeQueryValue('lxc')).toBe('system-container');
+ expect(normalizeRecoveryItemTypeQueryValue('ct')).toBe('system-container');
+ expect(normalizeRecoveryItemTypeQueryValue('container')).toBe('system-container');
+ expect(normalizeRecoveryItemTypeQueryValue('system-container')).toBe('system-container');
+ expect(normalizeRecoveryItemTypeQueryValue('oci-container')).toBe('system-container');
+ });
+
+ it('maps the app-container family and bare aliases', () => {
+ expect(normalizeRecoveryItemTypeQueryValue('docker')).toBe('app-container');
+ expect(normalizeRecoveryItemTypeQueryValue('app-container')).toBe('app-container');
+ // 'docker-container' already covered by the sibling test.
+ });
+
+ it('maps k8s pod, pvc, and cluster bare aliases', () => {
+ expect(normalizeRecoveryItemTypeQueryValue('k8s-pod')).toBe('pod');
+ expect(normalizeRecoveryItemTypeQueryValue('pod')).toBe('pod');
+ expect(normalizeRecoveryItemTypeQueryValue('pvc')).toBe('pvc');
+ expect(normalizeRecoveryItemTypeQueryValue('cluster')).toBe('cluster');
+ // 'k8s-pvc', 'k8s-cluster', 'kubernetes-cluster' already covered.
+ });
+
+ it('maps dataset, velero, and guest aliases', () => {
+ expect(normalizeRecoveryItemTypeQueryValue('dataset')).toBe('dataset');
+ expect(normalizeRecoveryItemTypeQueryValue('velero-backup')).toBe('velero-backup');
+ expect(normalizeRecoveryItemTypeQueryValue('proxmox-guest')).toBe('guest');
+ expect(normalizeRecoveryItemTypeQueryValue('guest')).toBe('guest');
+ // 'truenas-dataset' already covered.
+ });
+
+ it('strips the proxmox-/truenas-/k8s- prefixes for otherwise-unknown values', () => {
+ // Each prefix arm of the default branch.
+ expect(normalizeRecoveryItemTypeQueryValue('proxmox-storage')).toBe('storage');
+ expect(normalizeRecoveryItemTypeQueryValue('truenas-replication-task')).toBe(
+ 'replication-task',
+ );
+ // 'k8s-node' is not an explicit case here, so it hits the k8s- prefix arm.
+ expect(normalizeRecoveryItemTypeQueryValue('k8s-node')).toBe('node');
+ });
+
+ it('passes through unknown values verbatim (final default return)', () => {
+ // Whitespace is trimmed and casing is lowered before the passthrough.
+ expect(normalizeRecoveryItemTypeQueryValue(' Widget-Thing ')).toBe('widget-thing');
+ });
+ });
+
+ describe('getRecoveryItemTypePresentation', () => {
+ it('returns null when the normalized key is empty', () => {
+ expect(getRecoveryItemTypePresentation(null)).toBeNull();
+ expect(getRecoveryItemTypePresentation(undefined)).toBeNull();
+ expect(getRecoveryItemTypePresentation('')).toBeNull();
+ // 'all' normalizes to '' so it must also collapse to null.
+ expect(getRecoveryItemTypePresentation('all')).toBeNull();
+ expect(getRecoveryItemTypePresentation(' ')).toBeNull();
+ });
+
+ it('renders the pod case via the workload presentation path', () => {
+ const podTone = 'bg-amber-100 text-amber-700 dark:bg-amber-900 dark:text-amber-300';
+ const presentation = getRecoveryItemTypePresentation('pod');
+ expect(presentation).not.toBeNull();
+ expect(presentation).toMatchObject({
+ key: 'pod',
+ label: 'Pod',
+ badgeClasses: `${BADGE_BASE_CLASSES} ${podTone}`,
+ tableBadgeClasses: `${TABLE_BADGE_BASE_CLASSES} ${podTone}`,
+ });
+ });
+
+ it('renders the pvc case via the resource presentation path with its PVC fallback label', () => {
+ const presentation = getRecoveryItemTypePresentation('pvc');
+ expect(presentation).not.toBeNull();
+ expect(presentation).toMatchObject({
+ key: 'pvc',
+ label: 'PVC',
+ badgeClasses: `${BADGE_BASE_CLASSES} ${DEFAULT_BADGE_TONE_CLASSES}`,
+ tableBadgeClasses: `${TABLE_BADGE_BASE_CLASSES} ${DEFAULT_BADGE_TONE_CLASSES}`,
+ });
+ });
+
+ it('uses the resource presentation label verbatim when it differs from the key (default arm B)', () => {
+ // 'jail' is not a recovery-specific case, so it falls through to the
+ // default branch. getResourceTypePresentation('jail') returns a label
+ // ('Jail') that differs from the key ('jail'), exercising the arm that
+ // keeps presentation.label instead of re-titleCasing the key.
+ const presentation = getRecoveryItemTypePresentation('jail');
+ expect(presentation).not.toBeNull();
+ expect(presentation).toMatchObject({
+ key: 'jail',
+ label: 'Jail',
+ badgeClasses: `${BADGE_BASE_CLASSES} ${DEFAULT_BADGE_TONE_CLASSES}`,
+ tableBadgeClasses: `${TABLE_BADGE_BASE_CLASSES} ${DEFAULT_BADGE_TONE_CLASSES}`,
+ });
+ });
+ });
+
+ describe('getRecoveryItemTypeValue (covered transitively via the rollup/point keys)', () => {
+ // getRecoveryItemTypeValue is not exported; it is reached through the
+ // exported getRecoveryRollupItemTypeKey / getRecoveryPointItemTypeKey
+ // wrappers. These cases exercise the value-resolution arms the sibling
+ // test does not: the itemRef.type fallback and the all-empty '' fallback.
+ it('falls back to itemRef.type when display and subjectRef carry nothing', () => {
+ expect(
+ getRecoveryRollupItemTypeKey({
+ display: {},
+ itemRef: { type: 'proxmox-vm' },
+ }),
+ ).toBe('vm');
+ });
+
+ it('returns the empty sentinel (and thus an empty key) when every source is absent', () => {
+ expect(getRecoveryRollupItemTypeKey(null)).toBe('');
+ expect(getRecoveryPointItemTypeKey(undefined)).toBe('');
+ expect(getRecoveryPointItemTypeKey({})).toBe('');
+ // Explicitly-null nested refs still resolve to ''.
+ expect(
+ getRecoveryPointItemTypeKey({ display: null, itemRef: null, subjectRef: null }),
+ ).toBe('');
+ });
+ });
+
+ describe('getRecoveryItemTypeLabel', () => {
+ it('returns an empty string when no presentation exists', () => {
+ expect(getRecoveryItemTypeLabel(null)).toBe('');
+ expect(getRecoveryItemTypeLabel(undefined)).toBe('');
+ expect(getRecoveryItemTypeLabel('')).toBe('');
+ expect(getRecoveryItemTypeLabel('all')).toBe('');
+ });
+
+ it('returns the resolved presentation label for known keys', () => {
+ expect(getRecoveryItemTypeLabel('pod')).toBe('Pod');
+ expect(getRecoveryItemTypeLabel('pvc')).toBe('PVC');
+ });
+ });
+
+ describe('getRecoveryItemTypeBadgeClass', () => {
+ it('returns the default table badge classes when no presentation exists', () => {
+ const expectedDefault = `${TABLE_BADGE_BASE_CLASSES} ${DEFAULT_BADGE_TONE_CLASSES}`;
+ expect(getRecoveryItemTypeBadgeClass(null)).toBe(expectedDefault);
+ expect(getRecoveryItemTypeBadgeClass(undefined)).toBe(expectedDefault);
+ expect(getRecoveryItemTypeBadgeClass('')).toBe(expectedDefault);
+ expect(getRecoveryItemTypeBadgeClass('all')).toBe(expectedDefault);
+ });
+
+ it('returns the table badge classes for known keys', () => {
+ const podTone = 'bg-amber-100 text-amber-700 dark:bg-amber-900 dark:text-amber-300';
+ expect(getRecoveryItemTypeBadgeClass('pod')).toBe(
+ `${TABLE_BADGE_BASE_CLASSES} ${podTone}`,
+ );
+ expect(getRecoveryItemTypeBadgeClass('pvc')).toBe(
+ `${TABLE_BADGE_BASE_CLASSES} ${DEFAULT_BADGE_TONE_CLASSES}`,
+ );
+ });
+ });
+});
diff --git a/frontend-modern/src/utils/__tests__/resourceCorrelationPresentation.branchcov.test.ts b/frontend-modern/src/utils/__tests__/resourceCorrelationPresentation.branchcov.test.ts
new file mode 100644
index 0000000000..8ea9b42cec
--- /dev/null
+++ b/frontend-modern/src/utils/__tests__/resourceCorrelationPresentation.branchcov.test.ts
@@ -0,0 +1,417 @@
+import { describe, expect, it } from 'vitest';
+
+import type { ResourceCorrelation } from '@/types/aiIntelligence';
+import type { ResourceRelationship } from '@/types/resource';
+import {
+ formatResourceCorrelationEndpoint,
+ formatResourceCorrelationPattern,
+ formatResourceCorrelationSummary,
+ formatResourceRelationshipEndpoint,
+ formatResourceRelationshipSummary,
+ sortResourceCorrelations,
+ sortResourceRelationships,
+} from '@/utils/resourceCorrelationPresentation';
+
+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: 5_000_000_000,
+ confidence: 0.875,
+ 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,
+});
+
+// humanizeCorrelationToken is a private (non-exported) function in the module.
+// It is reachable through formatResourceCorrelationPattern, which delegates
+// directly: humanizeCorrelationToken(correlation.event_pattern).
+describe('humanizeCorrelationToken (via formatResourceCorrelationPattern)', () => {
+ it('returns the fallback label when event_pattern is undefined', () => {
+ expect(
+ formatResourceCorrelationPattern(
+ makeCorrelation({ event_pattern: undefined as unknown as string }),
+ ),
+ ).toBe('Correlation');
+ });
+
+ it('returns the fallback label when event_pattern is empty', () => {
+ expect(formatResourceCorrelationPattern(makeCorrelation({ event_pattern: '' }))).toBe(
+ 'Correlation',
+ );
+ });
+
+ it('returns the fallback label when event_pattern is whitespace-only', () => {
+ expect(formatResourceCorrelationPattern(makeCorrelation({ event_pattern: ' ' }))).toBe(
+ 'Correlation',
+ );
+ });
+
+ it('lowercases an all-caps token (with A-Z letters) before humanizing', () => {
+ expect(formatResourceCorrelationPattern(makeCorrelation({ event_pattern: 'API_ERROR' }))).toBe(
+ 'Api Error',
+ );
+ });
+
+ it('keeps a digits-only token untouched (no A-Z, so the lowercase arm is skipped)', () => {
+ expect(formatResourceCorrelationPattern(makeCorrelation({ event_pattern: '404' }))).toBe('404');
+ });
+});
+
+describe('formatResourceCorrelationEndpoint (branch coverage)', () => {
+ it('falls back to source_id when source_name is empty', () => {
+ expect(
+ formatResourceCorrelationEndpoint(
+ makeCorrelation({ source_name: '', source_id: 'sid-9' }),
+ 'source',
+ ),
+ ).toBe('sid-9');
+ });
+
+ it('falls back to target_id when target_name is empty', () => {
+ expect(
+ formatResourceCorrelationEndpoint(
+ makeCorrelation({ target_name: '', target_id: 'tid-7' }),
+ 'target',
+ ),
+ ).toBe('tid-7');
+ });
+
+ it('returns Unknown resource when source name and id are both whitespace-only', () => {
+ expect(
+ formatResourceCorrelationEndpoint(
+ makeCorrelation({ source_name: ' ', source_id: ' \t' }),
+ 'source',
+ ),
+ ).toBe('Unknown resource');
+ });
+
+ it('returns Unknown resource when target name and id are both empty', () => {
+ expect(
+ formatResourceCorrelationEndpoint(
+ makeCorrelation({ target_name: '', target_id: '' }),
+ 'target',
+ ),
+ ).toBe('Unknown resource');
+ });
+
+ it('trims whitespace around a resolved source name', () => {
+ expect(
+ formatResourceCorrelationEndpoint(makeCorrelation({ source_name: ' Web Node ' }), 'source'),
+ ).toBe('Web Node');
+ });
+});
+
+describe('formatResourceCorrelationSummary (branch coverage)', () => {
+ it('uses the singular occurrence when occurrences is exactly 1', () => {
+ expect(
+ formatResourceCorrelationSummary(
+ makeCorrelation({
+ occurrences: 1,
+ avg_delay: 0,
+ confidence: undefined as unknown as number,
+ }),
+ ),
+ ).toBe('1 occurrence');
+ });
+
+ it('omits the occurrence part when occurrences is 0', () => {
+ expect(
+ formatResourceCorrelationSummary(
+ makeCorrelation({ occurrences: 0, avg_delay: 0, confidence: 0.5 }),
+ ),
+ ).toBe('50% confidence');
+ });
+
+ it('parses avg_delay from a Go duration string', () => {
+ expect(
+ formatResourceCorrelationSummary(
+ makeCorrelation({ occurrences: 3, avg_delay: '5s', confidence: 0.9 }),
+ ),
+ ).toBe('3 occurrences · avg delay 5s · 90% confidence');
+ });
+
+ it('omits the delay when the Go duration string is unparseable', () => {
+ expect(
+ formatResourceCorrelationSummary(
+ makeCorrelation({ occurrences: 1, avg_delay: 'not-a-duration', confidence: NaN }),
+ ),
+ ).toBe('1 occurrence');
+ });
+
+ it('omits the delay when a numeric avg_delay rounds to zero', () => {
+ expect(
+ formatResourceCorrelationSummary(
+ makeCorrelation({ occurrences: 2, avg_delay: 1, confidence: NaN }),
+ ),
+ ).toBe('2 occurrences');
+ });
+
+ it('omits confidence when it is not finite and parses a minute duration string', () => {
+ expect(
+ formatResourceCorrelationSummary(
+ makeCorrelation({ occurrences: 1, avg_delay: '1m', confidence: Infinity }),
+ ),
+ ).toBe('1 occurrence · avg delay 1m');
+ });
+
+ it('returns an empty string when no parts apply', () => {
+ expect(
+ formatResourceCorrelationSummary(
+ makeCorrelation({
+ occurrences: 0,
+ avg_delay: '',
+ confidence: undefined as unknown as number,
+ }),
+ ),
+ ).toBe('');
+ });
+});
+
+describe('sortResourceCorrelations (branch coverage)', () => {
+ it('returns a new empty array for empty input', () => {
+ expect(sortResourceCorrelations([])).toEqual([]);
+ });
+
+ it('does not mutate the original array', () => {
+ const input = [
+ makeCorrelation({ source_id: 'low', confidence: 0.1 }),
+ makeCorrelation({ source_id: 'high', confidence: 0.9 }),
+ ];
+ sortResourceCorrelations(input);
+ expect(input.map((c) => c.source_id)).toEqual(['low', 'high']);
+ });
+
+ it('treats zero confidence as 0 in the confidence comparison', () => {
+ const sorted = sortResourceCorrelations([
+ makeCorrelation({ source_id: 'zero', confidence: 0 }),
+ makeCorrelation({ source_id: 'high', confidence: 0.5 }),
+ ]);
+ expect(sorted.map((c) => c.source_id)).toEqual(['high', 'zero']);
+ });
+
+ it('breaks a confidence tie using last_seen recency', () => {
+ const sorted = sortResourceCorrelations([
+ makeCorrelation({
+ source_id: 'older',
+ confidence: 0.5,
+ last_seen: '2026-01-01T00:00:00Z',
+ }),
+ makeCorrelation({
+ source_id: 'newer',
+ confidence: 0.5,
+ last_seen: '2026-06-01T00:00:00Z',
+ }),
+ ]);
+ expect(sorted.map((c) => c.source_id)).toEqual(['newer', 'older']);
+ });
+
+ it('treats a missing last_seen as time zero when confidence ties', () => {
+ const sorted = sortResourceCorrelations([
+ makeCorrelation({ source_id: 'no-date', confidence: 0.5, last_seen: '' }),
+ makeCorrelation({
+ source_id: 'has-date',
+ confidence: 0.5,
+ last_seen: '2026-06-01T00:00:00Z',
+ }),
+ ]);
+ expect(sorted.map((c) => c.source_id)).toEqual(['has-date', 'no-date']);
+ });
+
+ it('keeps relative order when confidence and dates are equivalent (both invalid)', () => {
+ const sorted = sortResourceCorrelations([
+ makeCorrelation({ source_id: 'a', confidence: 0.5, last_seen: 'not-a-date' }),
+ makeCorrelation({ source_id: 'b', confidence: 0.5, last_seen: 'also-bad' }),
+ ]);
+ expect(sorted.map((c) => c.source_id)).toEqual(['a', 'b']);
+ });
+});
+
+describe('formatResourceRelationshipEndpoint (branch coverage)', () => {
+ it('returns Unknown resource when sourceId is empty', () => {
+ expect(
+ formatResourceRelationshipEndpoint(makeRelationship({ sourceId: '' }), 'source'),
+ ).toBe('Unknown resource');
+ });
+
+ it('returns Unknown resource when targetId is whitespace-only', () => {
+ expect(
+ formatResourceRelationshipEndpoint(makeRelationship({ targetId: ' ' }), 'target'),
+ ).toBe('Unknown resource');
+ });
+
+ it('trims a resolved targetId', () => {
+ expect(
+ formatResourceRelationshipEndpoint(makeRelationship({ targetId: ' vm-99 ' }), 'target'),
+ ).toBe('vm-99');
+ });
+});
+
+describe('formatResourceRelationshipSummary (branch coverage)', () => {
+ it('omits confidence when it is NaN and shows discoverer and Historical', () => {
+ expect(
+ formatResourceRelationshipSummary(
+ makeRelationship({ confidence: NaN, active: false, discoverer: 'k8s_adapter' }),
+ ),
+ ).toBe('K8s Adapter · Historical');
+ });
+
+ it('filters out the fallback discoverer label when discoverer is empty', () => {
+ expect(
+ formatResourceRelationshipSummary(
+ makeRelationship({ confidence: 0.5, discoverer: '' }),
+ ),
+ ).toBe('50% confidence');
+ });
+
+ it('filters out the fallback discoverer label when discoverer is undefined', () => {
+ expect(
+ formatResourceRelationshipSummary(
+ makeRelationship({
+ confidence: 0.5,
+ discoverer: undefined as unknown as string,
+ active: true,
+ }),
+ ),
+ ).toBe('50% confidence');
+ });
+
+ it('humanizes an all-caps discoverer via the lowercase arm', () => {
+ expect(
+ formatResourceRelationshipSummary(
+ makeRelationship({ confidence: 0.4, discoverer: 'SNMP' }),
+ ),
+ ).toBe('40% confidence · Snmp');
+ });
+
+ it('does not add Historical when active is true', () => {
+ expect(
+ formatResourceRelationshipSummary(
+ makeRelationship({ confidence: 0.5, active: true, discoverer: 'snmp' }),
+ ),
+ ).toBe('50% confidence · Snmp');
+ });
+
+ it('does not add Historical when active is not strictly false', () => {
+ expect(
+ formatResourceRelationshipSummary(
+ makeRelationship({
+ confidence: undefined as unknown as number,
+ active: undefined as unknown as boolean,
+ discoverer: '',
+ }),
+ ),
+ ).toBe('');
+ });
+});
+
+describe('sortResourceRelationships (branch coverage)', () => {
+ it('returns a new empty array for empty input', () => {
+ expect(sortResourceRelationships([])).toEqual([]);
+ });
+
+ it('does not mutate the original array', () => {
+ const input = [
+ makeRelationship({ sourceId: 'inactive', active: false }),
+ makeRelationship({ sourceId: 'active', active: true }),
+ ];
+ sortResourceRelationships(input);
+ expect(input.map((r) => r.sourceId)).toEqual(['inactive', 'active']);
+ });
+
+ it('places an inactive relationship after an active one via the left.active falsy arm', () => {
+ const sorted = sortResourceRelationships([
+ makeRelationship({ sourceId: 'sleeping', active: false, confidence: 1 }),
+ makeRelationship({ sourceId: 'live', active: true, confidence: 0.1 }),
+ ]);
+ expect(sorted.map((r) => r.sourceId)).toEqual(['live', 'sleeping']);
+ });
+
+ it('breaks an active-group tie using confidence with the zero-coalesce arm', () => {
+ const sorted = sortResourceRelationships([
+ makeRelationship({ sourceId: 'zero-conf', active: true, confidence: 0 }),
+ makeRelationship({ sourceId: 'half-conf', active: true, confidence: 0.5 }),
+ ]);
+ expect(sorted.map((r) => r.sourceId)).toEqual(['half-conf', 'zero-conf']);
+ });
+
+ it('falls back to observedAt when lastSeenAt is missing', () => {
+ const sorted = sortResourceRelationships([
+ makeRelationship({
+ sourceId: 'observed-only',
+ active: true,
+ confidence: 0.5,
+ lastSeenAt: '',
+ observedAt: '2026-01-01T00:00:00Z',
+ }),
+ makeRelationship({
+ sourceId: 'recent',
+ active: true,
+ confidence: 0.5,
+ lastSeenAt: '2026-06-01T00:00:00Z',
+ observedAt: '2020-01-01T00:00:00Z',
+ }),
+ ]);
+ expect(sorted.map((r) => r.sourceId)).toEqual(['recent', 'observed-only']);
+ });
+
+ it('treats missing lastSeenAt and observedAt as time zero', () => {
+ const sorted = sortResourceRelationships([
+ makeRelationship({
+ sourceId: 'no-times',
+ active: true,
+ confidence: 0.5,
+ lastSeenAt: '',
+ observedAt: '',
+ }),
+ makeRelationship({
+ sourceId: 'timed',
+ active: true,
+ confidence: 0.5,
+ lastSeenAt: '2026-06-01T00:00:00Z',
+ }),
+ ]);
+ expect(sorted.map((r) => r.sourceId)).toEqual(['timed', 'no-times']);
+ });
+
+ it('keeps relative order when active, confidence, and times are equivalent', () => {
+ const sorted = sortResourceRelationships([
+ makeRelationship({
+ sourceId: 'first',
+ active: true,
+ confidence: 0.5,
+ lastSeenAt: 'bad',
+ observedAt: 'bad',
+ }),
+ makeRelationship({
+ sourceId: 'second',
+ active: true,
+ confidence: 0.5,
+ lastSeenAt: 'bad',
+ observedAt: 'bad',
+ }),
+ ]);
+ expect(sorted.map((r) => r.sourceId)).toEqual(['first', 'second']);
+ });
+});
diff --git a/frontend-modern/src/utils/__tests__/searchQuery.branchcov.test.ts b/frontend-modern/src/utils/__tests__/searchQuery.branchcov.test.ts
new file mode 100644
index 0000000000..5a0f9fe898
--- /dev/null
+++ b/frontend-modern/src/utils/__tests__/searchQuery.branchcov.test.ts
@@ -0,0 +1,553 @@
+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';
+
+/**
+ * Branch-coverage companion to searchQuery.test.ts.
+ *
+ * `evaluateMetricCondition` and `evaluateTextCondition` are module-private
+ * (not exported) but reachable through the exported `evaluateFilterStack`.
+ * We drive them by constructing `ParsedFilter` / `FilterStack` objects directly
+ * so each guard / switch arm / ternary is exercised independently of the parser.
+ */
+
+// 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: [] });
+
+/** Metric filter helper (value defaults to a number so the metric arm runs). */
+const metric = (
+ field: MetricCondition['field'],
+ operator: ComparisonOperator,
+ value: number,
+): ParsedFilter => ({ type: 'metric', field, operator, value });
+
+describe('evaluateMetricCondition — field switch branches (via evaluateFilterStack)', () => {
+ it('cpu: converts the decimal to a percentage and compares with >=', () => {
+ // cpu 0.5 -> 50%; 50 >= 50 is true
+ expect(evaluateFilterStack(makeGuest({ cpu: 0.5 }), single(metric('cpu', '>=', 50)))).toBe(
+ true,
+ );
+ });
+
+ it('cpu: >= is false below the threshold', () => {
+ expect(evaluateFilterStack(makeGuest({ cpu: 0.49 }), single(metric('cpu', '>=', 50)))).toBe(
+ false,
+ );
+ });
+
+ it('cpu: <= is true at the threshold and false above', () => {
+ expect(evaluateFilterStack(makeGuest({ cpu: 0.5 }), single(metric('cpu', '<=', 50)))).toBe(
+ true,
+ );
+ expect(evaluateFilterStack(makeGuest({ cpu: 0.8 }), single(metric('cpu', '<=', 50)))).toBe(
+ false,
+ );
+ });
+
+ it('cpu: = operator matches within the 0.01 epsilon', () => {
+ expect(evaluateFilterStack(makeGuest({ cpu: 0.5 }), single(metric('cpu', '=', 50)))).toBe(true);
+ expect(evaluateFilterStack(makeGuest({ cpu: 0.6 }), single(metric('cpu', '=', 50)))).toBe(
+ false,
+ );
+ });
+
+ it('cpu: == operator matches within the 0.01 epsilon', () => {
+ expect(evaluateFilterStack(makeGuest({ cpu: 0.5 }), single(metric('cpu', '==', 50)))).toBe(
+ true,
+ );
+ });
+
+ it('cpu: falsy cpu (0) falls back to 0 via the || 0 arm', () => {
+ // 0 -> 0%; 0 >= 0 true, exercising guest.cpu || 0
+ expect(evaluateFilterStack(makeGuest({ cpu: 0 }), single(metric('cpu', '>=', 0)))).toBe(true);
+ });
+
+ it('cpu: missing cpu key uses the : 0 ternary arm', () => {
+ // 'cpu' not in guest -> value 0; 0 < 1 true
+ expect(
+ evaluateFilterStack(guestWithout(['cpu']), single(metric('cpu', '<', 1))),
+ ).toBe(true);
+ });
+
+ it('memory: falsy/missing memory yields 0', () => {
+ // memory null -> guest.memory falsy -> 0; 0 > -1 true
+ expect(
+ evaluateFilterStack(
+ makeGuest({ memory: null as unknown as VM['memory'] }),
+ single(metric('memory', '>', -1)),
+ ),
+ ).toBe(true);
+ // memory key absent -> 0; 0 <= 0 true
+ expect(
+ evaluateFilterStack(guestWithout(['memory']), single(metric('memory', '<=', 0))),
+ ).toBe(true);
+ });
+
+ it('memory: compares the raw usage value when present', () => {
+ expect(
+ evaluateFilterStack(
+ makeGuest({ memory: { usage: 900, total: 1000, used: 900, free: 100 } }),
+ single(metric('memory', '>', 500)),
+ ),
+ ).toBe(true);
+ });
+
+ it('disk: falsy/missing disk yields 0', () => {
+ expect(
+ evaluateFilterStack(
+ makeGuest({ disk: null as unknown as VM['disk'] }),
+ single(metric('disk', '<', 1)),
+ ),
+ ).toBe(true);
+ expect(evaluateFilterStack(guestWithout(['disk']), single(metric('disk', '<', 1)))).toBe(true);
+ });
+
+ it('uptime: running guest uses the uptime value', () => {
+ expect(
+ evaluateFilterStack(makeGuest({ status: 'running', uptime: 7200 }), single(metric('uptime', '>', 3600))),
+ ).toBe(true);
+ });
+
+ it('uptime: non-running status yields 0', () => {
+ expect(
+ evaluateFilterStack(
+ makeGuest({ status: 'stopped', uptime: 9999 }),
+ single(metric('uptime', '>', 3600)),
+ ),
+ ).toBe(false);
+ });
+
+ it('uptime: running status but missing uptime key yields 0', () => {
+ expect(
+ evaluateFilterStack(guestWithout(['uptime']), single(metric('uptime', '>', 1))),
+ ).toBe(false);
+ });
+
+ it('default field: a switch-unlisted metric field present on the guest is read numerically', () => {
+ // 'networkIn' is a valid MetricCondition field but not in the switch; falls to default.
+ // networkIn 100 > 50 -> true
+ expect(
+ evaluateFilterStack(makeGuest({ networkIn: 100 }), single(metric('networkIn', '>', 50))),
+ ).toBe(true);
+ expect(
+ evaluateFilterStack(makeGuest({ networkIn: 100 }), single(metric('networkIn', '>', 999))),
+ ).toBe(false);
+ });
+
+ it('default field: non-numeric field value coerces to 0 via Number() || 0', () => {
+ // diskRead stored as a non-numeric string -> Number('abc') = NaN -> || 0 = 0
+ expect(
+ evaluateFilterStack(
+ makeGuest({ diskRead: 'abc' as unknown as number }),
+ single(metric('diskRead', '<', 1)),
+ ),
+ ).toBe(true);
+ });
+
+ it('default field: field present but value undefined returns false', () => {
+ expect(
+ evaluateFilterStack(
+ makeGuest({ networkOut: undefined }),
+ single(metric('networkOut', '>', 0)),
+ ),
+ ).toBe(false);
+ });
+
+ it('default field: field absent from the guest returns false', () => {
+ expect(
+ evaluateFilterStack(guestWithout(['networkIn']), single(metric('networkIn', '>', 0))),
+ ).toBe(false);
+ });
+
+ it('operator default: an unknown operator returns false', () => {
+ 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 branches (via evaluateFilterStack)', () => {
+ const text = (field: string, value: string): ParsedFilter => ({ type: 'text', field, value });
+
+ it('name: missing/empty name returns false', () => {
+ expect(
+ evaluateFilterStack(guestWithout(['name']), single(text('name', 'test'))),
+ ).toBe(false);
+ expect(
+ evaluateFilterStack(makeGuest({ name: '' }), single(text('name', 'test'))),
+ ).toBe(false);
+ });
+
+ it('name: case-insensitive substring match', () => {
+ expect(evaluateFilterStack(makeGuest({ name: 'Prod-Web' }), single(text('name', 'prod')))).toBe(
+ true,
+ );
+ });
+
+ it('node: missing node returns false', () => {
+ expect(evaluateFilterStack(guestWithout(['node']), single(text('node', 'x')))).toBe(false);
+ });
+
+ it('node: substring match', () => {
+ expect(evaluateFilterStack(makeGuest({ node: 'cluster-a' }), single(text('node', 'cluster')))).toBe(
+ true,
+ );
+ });
+
+ it('vmid: falsy vmid (0) returns false', () => {
+ expect(evaluateFilterStack(makeGuest({ vmid: 0 }), single(text('vmid', '0')))).toBe(false);
+ });
+
+ it('vmid: numeric substring match', () => {
+ expect(evaluateFilterStack(makeGuest({ vmid: 100 }), single(text('vmid', '10')))).toBe(true);
+ });
+
+ describe('tags field', () => {
+ it('returns false when tags key is absent', () => {
+ expect(evaluateFilterStack(guestWithout(['tags']), single(text('tags', 'x')))).toBe(false);
+ });
+
+ it('returns false when tags is null', () => {
+ expect(
+ evaluateFilterStack(makeGuest({ tags: null }), single(text('tags', 'x'))),
+ ).toBe(false);
+ });
+
+ it('returns false for an empty tags array', () => {
+ expect(evaluateFilterStack(makeGuest({ tags: [] }), single(text('tags', 'x')))).toBe(false);
+ });
+
+ it('returns false when an array contains only non-string entries', () => {
+ expect(
+ evaluateFilterStack(
+ makeGuest({ tags: [1, 2] as unknown as string[] }),
+ single(text('tags', 'x')),
+ ),
+ ).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('matches any tag in a comma-separated search (OR) — positive', () => {
+ expect(
+ evaluateFilterStack(
+ makeGuest({ tags: ['production', 'web'] }),
+ single(text('tags', 'staging,web')),
+ ),
+ ).toBe(true);
+ });
+
+ it('splits a comma-separated tags string and matches', () => {
+ expect(
+ evaluateFilterStack(
+ makeGuest({ tags: 'production,web,api' }),
+ single(text('tags', 'api')),
+ ),
+ ).toBe(true);
+ });
+
+ it('ignores empty segments in a comma-separated tag search', () => {
+ // ',,' splits to [] after filtering -> no search tags -> some([]) is false
+ expect(
+ evaluateFilterStack(
+ makeGuest({ tags: ['production'] }),
+ single(text('tags', ',,')),
+ ),
+ ).toBe(false);
+ });
+ });
+
+ describe('default field (non-name/node/vmid/tags)', () => {
+ it('matches a string field value (substring, case-insensitive)', () => {
+ // 'type' is not in the TextCondition switch; falls to default with a string value.
+ expect(evaluateFilterStack(makeGuest({ type: 'qemu' }), single(text('type', 'qe')))).toBe(
+ true,
+ );
+ expect(evaluateFilterStack(makeGuest({ type: 'qemu' }), single(text('type', 'ZZZ')))).toBe(
+ false,
+ );
+ });
+
+ it('matches a numeric field value via toString', () => {
+ // 'cpus' is numeric on the guest; search '2'
+ expect(evaluateFilterStack(makeGuest({ cpus: 2 }), single(text('cpus', '2')))).toBe(true);
+ });
+
+ it('matches a boolean field value against its string form', () => {
+ expect(
+ evaluateFilterStack(makeGuest({ template: true }), single(text('template', 'true'))),
+ ).toBe(true);
+ expect(
+ evaluateFilterStack(makeGuest({ template: true }), single(text('template', 'false'))),
+ ).toBe(false);
+ });
+
+ it('returns false when the default field value is falsy', () => {
+ // 'lock' is '' on the base guest -> falsy -> false
+ expect(evaluateFilterStack(makeGuest(), single(text('lock', '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 for a non-string/number/boolean field value', () => {
+ expect(
+ evaluateFilterStack(
+ makeGuest({ cpus: { n: 1 } as unknown as number }),
+ single(text('cpus', 'x')),
+ ),
+ ).toBe(false);
+ });
+ });
+});
+
+describe('evaluateFilterStack — top-level branches', () => {
+ it('returns true for a single metric filter whose result is true (results.length === 1 fast path)', () => {
+ expect(evaluateFilterStack(makeGuest({ cpu: 0.9 }), single(metric('cpu', '>', 50)))).toBe(true);
+ });
+
+ it('malformed metric filter (missing value) falls through to the true catch-all', () => {
+ const filter = { type: 'metric', field: 'cpu', operator: '>' } as ParsedFilter;
+ expect(evaluateFilterStack(makeGuest(), single(filter))).toBe(true);
+ });
+
+ it('text filter with a falsy value falls through to the true catch-all', () => {
+ const filter = { type: 'text', field: 'name', value: '' } as ParsedFilter;
+ expect(evaluateFilterStack(makeGuest(), single(filter))).toBe(true);
+ });
+
+ it('raw filter with empty rawText falls through to the true catch-all', () => {
+ const filter = { type: 'raw', rawText: '' } as ParsedFilter;
+ expect(evaluateFilterStack(makeGuest(), single(filter))).toBe(true);
+ });
+
+ it('an unknown filter type falls through to the true catch-all', () => {
+ const filter = { type: 'bogus' } as unknown as ParsedFilter;
+ expect(evaluateFilterStack(makeGuest(), single(filter))).toBe(true);
+ });
+
+ describe('raw text matching across fields', () => {
+ it('matches raw text against node', () => {
+ expect(evaluateFilterStack(makeGuest({ node: 'cluster-a' }), single(parseFilter('cluster')))).toBe(
+ true,
+ );
+ });
+
+ it('matches raw text against vmid', () => {
+ expect(evaluateFilterStack(makeGuest({ vmid: 100 }), single(parseFilter('100')))).toBe(true);
+ });
+
+ it('returns false when raw text matches no field', () => {
+ const guest = makeGuest({ name: 'alpha', node: 'beta', status: 'running', tags: [] });
+ expect(evaluateFilterStack(guest, single(parseFilter('zzz')))).toBe(false);
+ });
+
+ it('raw tag match is false when tags is not an array', () => {
+ const guest = makeGuest({ tags: 'production,web' });
+ // Raw matcher only inspects tags when Array.isArray(...) is true; the needle below
+ // matches none of name/node/vmid/status, so the non-array tags branch yields false.
+ const stack = single(parseFilter('production'));
+ expect(evaluateFilterStack(guest, stack)).toBe(false);
+ });
+ });
+
+ describe('operator combination between multiple filters', () => {
+ it('AND short-circuits to false when the first operand is false', () => {
+ const stack: FilterStack = {
+ filters: [metric('cpu', '>', 50), { type: 'text', field: 'name', value: 'test' }],
+ operators: ['AND'],
+ };
+ expect(evaluateFilterStack(makeGuest({ cpu: 0.1, name: 'test-vm' }), stack)).toBe(false);
+ });
+
+ it('OR yields true when the second operand is true', () => {
+ const stack: FilterStack = {
+ filters: [metric('cpu', '>', 50), { type: 'text', field: 'name', value: 'test' }],
+ operators: ['OR'],
+ };
+ expect(evaluateFilterStack(makeGuest({ cpu: 0.1, name: 'test-vm' }), stack)).toBe(true);
+ });
+
+ it('OR yields false when both operands are false', () => {
+ const stack: FilterStack = {
+ filters: [metric('cpu', '>', 50), { type: 'text', field: 'name', value: 'zzz' }],
+ operators: ['OR'],
+ };
+ expect(evaluateFilterStack(makeGuest({ cpu: 0.1, name: 'test-vm' }), stack)).toBe(false);
+ });
+
+ it('left-to-right reduction with three filters and two operators', () => {
+ // (false OR true) AND false -> false
+ const stack: FilterStack = {
+ filters: [
+ metric('cpu', '>', 99),
+ { type: 'text', field: 'name', value: 'test' },
+ metric('disk', '>', 99),
+ ],
+ operators: ['OR', 'AND'],
+ };
+ expect(evaluateFilterStack(makeGuest({ cpu: 0.5, name: 'test-vm' }), stack)).toBe(false);
+ });
+
+ it('stops reducing when operators run out before filters (operator array shorter)', () => {
+ // 3 filters, only 1 operator -> third filter result is never combined.
+ // (true AND false) ... ignored -> false
+ const stack: FilterStack = {
+ filters: [
+ { type: 'text', field: 'name', value: 'test' },
+ metric('cpu', '>', 99),
+ metric('disk', '>', 99),
+ ],
+ operators: ['AND'],
+ };
+ expect(evaluateFilterStack(makeGuest({ name: 'test-vm', cpu: 0.5, disk: { usage: 50, total: 100, used: 50, free: 50 } }), stack)).toBe(false);
+ });
+ });
+});
+
+describe('parseFilter — uncovered parser branches', () => {
+ it('parses a metric term with whitespace around the operator', () => {
+ expect(parseFilter('cpu >= 50')).toEqual({
+ type: 'metric',
+ field: 'cpu',
+ operator: '>=',
+ value: 50,
+ });
+ });
+
+ it('parses a metric term with a decimal value and == operator with spaces', () => {
+ expect(parseFilter('cpu == 50.5')).toEqual({
+ type: 'metric',
+ field: 'cpu',
+ operator: '==',
+ value: 50.5,
+ });
+ });
+
+ it('parses a text term with whitespace around the colon', () => {
+ expect(parseFilter('name : prod')).toEqual({
+ type: 'text',
+ field: 'name',
+ value: 'prod',
+ });
+ });
+
+ it('preserves internal spaces in a text value', () => {
+ expect(parseFilter('name:prod server')).toEqual({
+ type: 'text',
+ field: 'name',
+ value: 'prod server',
+ });
+ });
+
+ it('treats a lone dash as raw text', () => {
+ expect(parseFilter('-')).toEqual({ type: 'raw', rawText: '-' });
+ });
+
+ it('treats an operator-led term (no field) as raw text', () => {
+ expect(parseFilter('>50')).toEqual({ type: 'raw', rawText: '>50' });
+ });
+
+ it('treats an empty string after trim as raw text', () => {
+ expect(parseFilter(' ')).toEqual({ type: 'raw', rawText: '' });
+ });
+
+ it('lowercases a mixed-case field name for text conditions', () => {
+ expect(parseFilter('NODE:cluster')).toEqual({
+ type: 'text',
+ field: 'node',
+ value: 'cluster',
+ });
+ });
+});
+
+describe('parseFilterStack — uncovered stack branches', () => {
+ it('parses a lowercase "or" operator', () => {
+ const result = parseFilterStack('name:a or name:b');
+ expect(result.operators).toEqual(['OR']);
+ expect(result.filters).toHaveLength(2);
+ });
+
+ it('parses with multiple spaces between filters and operator', () => {
+ const result = parseFilterStack('cpu>80 AND memory<50');
+ expect(result.operators).toEqual(['AND']);
+ expect(result.filters).toHaveLength(2);
+ });
+
+ it('uppercases a mixed-case "Or" operator', () => {
+ const result = parseFilterStack('name:a Or name:b');
+ expect(result.operators).toEqual(['OR']);
+ });
+
+ it('preserves operator order across a three-filter stack with mixed operators', () => {
+ const result = parseFilterStack('cpu>80 AND name:prod OR tags:web');
+ expect(result.filters).toHaveLength(3);
+ expect(result.operators).toEqual(['AND', 'OR']);
+ });
+
+ it('parses a leading operator token as a single raw filter', () => {
+ // No leading whitespace before the operator token, so it does not split.
+ // The raw fallback preserves the original term casing.
+ const result = parseFilterStack('AND cpu>80');
+ expect(result.filters).toHaveLength(1);
+ expect(result.filters[0]).toEqual({ type: 'raw', rawText: 'AND cpu>80' });
+ expect(result.operators).toEqual([]);
+ });
+});